Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Abstract REPL setup complexity in new @seedcompany/nest library #2915

Merged
merged 1 commit into from
Oct 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"@patarapolw/prettyprint": "^1.0.3",
"@seedcompany/common": ">=0.11 <1",
"@seedcompany/data-loader": "^0.5.4",
"@seedcompany/nest": ">=0.1 <1",
"@seedcompany/nestjs-email": "^3.3.2",
"@seedcompany/scripture": "^0.3.0",
"argon2": "^0.31.1",
Expand Down
120 changes: 41 additions & 79 deletions src/repl.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
import { clc } from '@nestjs/common/utils/cli-colors.util.js';
import { NestFactory } from '@nestjs/core';
import { assignToObject } from '@nestjs/core/repl/assign-to-object.util.js';
import { ReplContext } from '@nestjs/core/repl/repl-context.js';
import { bufferFromStream } from '@seedcompany/common';
import { runRepl } from '@seedcompany/nest';
import * as fs from 'fs';
import { mkdir } from 'fs/promises';
// eslint-disable-next-line no-restricted-imports
import * as lodash from 'lodash';
import { DateTime, Duration, Interval } from 'luxon';
import { promisify } from 'util';
import { createContext, runInContext } from 'vm';
import {
CalendarDate,
DateInterval,
Expand All @@ -22,75 +15,44 @@ import {
import * as common from '~/common';
import './polyfills';

/**
* This does the same thing as {@link import('@nestjs/core').repl}
* Just that we use our own logger & add more to the global context
*/
async function bootstrap() {
// Ensure src files are initialized here were init errors can be caught
const { AppModule } = await import('./app.module');
const { bootstrapLogger, ConfigService, ResourcesHost } = await import(
'~/core'
);
const { AuthenticationService } = await import('./components/authentication');
const { Pnp } = await import('./components/pnp');

const app = await NestFactory.createApplicationContext(AppModule, {
abortOnError: false,
logger: bootstrapLogger,
});
await app.init();

const session = await app
.get(AuthenticationService)
.sessionForUser(app.get(ConfigService).rootAdmin.id);
const Resources = await app.get(ResourcesHost).getEnhancedMap();

const context = assignToObject(new ReplContext(app).globalScope, {
DateTime,
Duration,
Interval,
CalendarDate,
DateInterval,
mapFromList,
many,
maybeMany,
common,
// eslint-disable-next-line @typescript-eslint/naming-convention
__: lodash, // single underscore is "last execution result"
lodash,
session,
sessionFor: (role: Role): Session => ({
...session,
roles: [`global:${role}`],
}),
Resources,
loadPnp: (filepath: string) => Pnp.fromBuffer(fs.readFileSync(filepath)),
});

if (!process.stdin.isTTY) {
const input = await bufferFromStream(process.stdin);
runInContext(input.toString(), createContext(context));
await app.close();
return;
}

const _repl = await Promise.resolve().then(() => import('repl'));
const replServer = _repl.start({
prompt: clc.green('> '),
ignoreUndefined: true,
});
replServer.on('exit', () => void app.close());

assignToObject(replServer.context, context);

await mkdir('.cache', { recursive: true });
await promisify(replServer.setupHistory.bind(replServer))(
'.cache/repl_history',
);
}
bootstrap().catch((err) => {
// eslint-disable-next-line no-console
console.error(err);
process.exit(1);
runRepl({
module: () => import('./app.module').then((m) => m.AppModule),
options: async () => {
const { bootstrapLogger: logger } = await import('~/core');
return { logger };
},
extraContext: async (app) => {
const { ConfigService, ResourcesHost } = await import('~/core');
const { AuthenticationService } = await import(
'./components/authentication'
);
const { Pnp } = await import('./components/pnp');

const session = await app
.get(AuthenticationService)
.sessionForUser(app.get(ConfigService).rootAdmin.id);
const Resources = await app.get(ResourcesHost).getEnhancedMap();

return {
DateTime,
Duration,
Interval,
CalendarDate,
DateInterval,
mapFromList,
many,
maybeMany,
common,
// eslint-disable-next-line @typescript-eslint/naming-convention
__: lodash, // single underscore is "last execution result"
lodash,
session,
sessionFor: (role: Role): Session => ({
...session,
roles: [`global:${role}`],
}),
Resources,
loadPnp: (filepath: string) => Pnp.fromBuffer(fs.readFileSync(filepath)),
};
},
});
58 changes: 37 additions & 21 deletions yarn.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.