bootstrap.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. import { DynamicModule, INestApplication, INestApplicationContext } from '@nestjs/common';
  2. import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-application-context-options.interface';
  3. import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface';
  4. import { NestFactory } from '@nestjs/core';
  5. import { NestExpressApplication } from '@nestjs/platform-express';
  6. import { getConnectionToken } from '@nestjs/typeorm';
  7. import { DEFAULT_COOKIE_NAME } from '@vendure/common/lib/shared-constants';
  8. import { Type } from '@vendure/common/lib/shared-types';
  9. import { satisfies } from 'semver';
  10. import { Connection, DataSourceOptions, EntitySubscriberInterface } from 'typeorm';
  11. import cookieSession = require('cookie-session');
  12. import { InternalServerError } from './common/error/errors';
  13. import { getConfig, setConfig } from './config/config-helpers';
  14. import { DefaultLogger } from './config/logger/default-logger';
  15. import { Logger } from './config/logger/vendure-logger';
  16. import { RuntimeVendureConfig, VendureConfig } from './config/vendure-config';
  17. import { Administrator } from './entity/administrator/administrator.entity';
  18. import { coreEntitiesMap } from './entity/entities';
  19. import { registerCustomEntityFields } from './entity/register-custom-entity-fields';
  20. import { runEntityMetadataModifiers } from './entity/run-entity-metadata-modifiers';
  21. import { setEntityIdStrategy } from './entity/set-entity-id-strategy';
  22. import { setMoneyStrategy } from './entity/set-money-strategy';
  23. import { validateCustomFieldsConfig } from './entity/validate-custom-fields-config';
  24. import { getCompatibility, getConfigurationFunction, getEntitiesFromPlugins } from './plugin/plugin-metadata';
  25. import { getPluginStartupMessages } from './plugin/plugin-utils';
  26. import { setProcessContext } from './process-context/process-context';
  27. import { VENDURE_VERSION } from './version';
  28. import { VendureWorker } from './worker/vendure-worker';
  29. export type VendureBootstrapFunction = (config: VendureConfig) => Promise<INestApplication>;
  30. /**
  31. * @description
  32. * Additional options that can be used to configure the bootstrap process of the
  33. * Vendure server.
  34. *
  35. * @since 2.2.0
  36. * @docsCategory common
  37. * @docsPage bootstrap
  38. */
  39. export interface BootstrapOptions {
  40. /**
  41. * @description
  42. * These options get passed directly to the `NestFactory.create()` method.
  43. */
  44. nestApplicationOptions?: NestApplicationOptions;
  45. /**
  46. * @description
  47. * By default, if a plugin specifies a compatibility range which does not include the current
  48. * Vendure version, the bootstrap process will fail. This option allows you to ignore compatibility
  49. * errors for specific plugins.
  50. *
  51. * This setting should be used with caution, only if you are sure that the plugin will still
  52. * work as expected with the current version of Vendure.
  53. *
  54. * @example
  55. * ```ts
  56. * import { bootstrap } from '\@vendure/core';
  57. * import { config } from './vendure-config';
  58. * import { MyPlugin } from './plugins/my-plugin';
  59. *
  60. * bootstrap(config, {
  61. * ignoreCompatibilityErrorsForPlugins: [MyPlugin],
  62. * });
  63. * ```
  64. *
  65. * @default []
  66. * @since 3.1.0
  67. */
  68. ignoreCompatibilityErrorsForPlugins?: Array<DynamicModule | Type<any>>;
  69. }
  70. /**
  71. * @description
  72. * Additional options that can be used to configure the bootstrap process of the
  73. * Vendure worker.
  74. *
  75. * @since 2.2.0
  76. * @docsCategory worker
  77. * @docsPage bootstrapWorker
  78. */
  79. export interface BootstrapWorkerOptions {
  80. /**
  81. * @description
  82. * These options get passed directly to the `NestFactory.createApplicationContext` method.
  83. */
  84. nestApplicationContextOptions?: NestApplicationContextOptions;
  85. /**
  86. * @description
  87. * See the `ignoreCompatibilityErrorsForPlugins` option in {@link BootstrapOptions}.
  88. *
  89. * @default []
  90. * @since 3.1.0
  91. */
  92. ignoreCompatibilityErrorsForPlugins?: Array<DynamicModule | Type<any>>;
  93. }
  94. /**
  95. * @description
  96. * Bootstraps the Vendure server. This is the entry point to the application.
  97. *
  98. * @example
  99. * ```ts
  100. * import { bootstrap } from '\@vendure/core';
  101. * import { config } from './vendure-config';
  102. *
  103. * bootstrap(config).catch(err => {
  104. * console.log(err);
  105. * process.exit(1);
  106. * });
  107. * ```
  108. *
  109. * ### Passing additional options
  110. *
  111. * Since v2.2.0, you can pass additional options to the NestJs application via the `options` parameter.
  112. * For example, to integrate with the [Nest Devtools](https://docs.nestjs.com/devtools/overview), you need to
  113. * pass the `snapshot` option:
  114. *
  115. * ```ts
  116. * import { bootstrap } from '\@vendure/core';
  117. * import { config } from './vendure-config';
  118. *
  119. * bootstrap(config, {
  120. * // highlight-start
  121. * nestApplicationOptions: {
  122. * snapshot: true,
  123. * }
  124. * // highlight-end
  125. * }).catch(err => {
  126. * console.log(err);
  127. * process.exit(1);
  128. * });
  129. * ```
  130. *
  131. * ### Ignoring compatibility errors for plugins
  132. *
  133. * Since v3.1.0, you can ignore compatibility errors for specific plugins by passing the `ignoreCompatibilityErrorsForPlugins` option.
  134. *
  135. * This should be used with caution, only if you are sure that the plugin will still work as expected with the current version of Vendure.
  136. *
  137. * @example
  138. * ```ts
  139. * import { bootstrap } from '\@vendure/core';
  140. * import { config } from './vendure-config';
  141. * import { MyPlugin } from './plugins/my-plugin';
  142. *
  143. * bootstrap(config, {
  144. * // Let's say that `MyPlugin` is not yet compatible with the current version of Vendure
  145. * // but we know that it will still work as expected, and we are not able to publish
  146. * // a new version of the plugin right now.
  147. * ignoreCompatibilityErrorsForPlugins: [MyPlugin],
  148. * });
  149. * ```
  150. *
  151. * @docsCategory common
  152. * @docsPage bootstrap
  153. * @docsWeight 0
  154. * */
  155. export async function bootstrap(
  156. userConfig: Partial<VendureConfig>,
  157. options?: BootstrapOptions,
  158. ): Promise<INestApplication> {
  159. const config = await preBootstrapConfig(userConfig);
  160. Logger.useLogger(config.logger);
  161. Logger.info(`Bootstrapping Vendure Server (pid: ${process.pid})...`);
  162. checkPluginCompatibility(config, options?.ignoreCompatibilityErrorsForPlugins);
  163. // The AppModule *must* be loaded only after the entities have been set in the
  164. // config, so that they are available when the AppModule decorator is evaluated.
  165. // eslint-disable-next-line
  166. const appModule = await import('./app.module.js');
  167. setProcessContext('server');
  168. const { hostname, port, cors, middleware, trustProxy } = config.apiOptions;
  169. DefaultLogger.hideNestBoostrapLogs();
  170. const app = await NestFactory.create<NestExpressApplication>(appModule.AppModule, {
  171. cors,
  172. logger: new Logger(),
  173. ...options?.nestApplicationOptions,
  174. });
  175. DefaultLogger.restoreOriginalLogLevel();
  176. app.useLogger(new Logger());
  177. app.set('trust proxy', trustProxy);
  178. const { tokenMethod } = config.authOptions;
  179. const usingCookie =
  180. tokenMethod === 'cookie' || (Array.isArray(tokenMethod) && tokenMethod.includes('cookie'));
  181. if (usingCookie) {
  182. configureSessionCookies(app, config);
  183. }
  184. const earlyMiddlewares = middleware.filter(mid => mid.beforeListen);
  185. earlyMiddlewares.forEach(mid => {
  186. app.use(mid.route, mid.handler);
  187. });
  188. await app.listen(port, hostname || '');
  189. app.enableShutdownHooks();
  190. logWelcomeMessage(config);
  191. return app;
  192. }
  193. /**
  194. * @description
  195. * Bootstraps a Vendure worker. Resolves to a {@link VendureWorker} object containing a reference to the underlying
  196. * NestJs [standalone application](https://docs.nestjs.com/standalone-applications) as well as convenience
  197. * methods for starting the job queue and health check server.
  198. *
  199. * Read more about the [Vendure Worker](/guides/developer-guide/worker-job-queue/).
  200. *
  201. * @example
  202. * ```ts
  203. * import { bootstrapWorker } from '\@vendure/core';
  204. * import { config } from './vendure-config';
  205. *
  206. * bootstrapWorker(config)
  207. * .then(worker => worker.startJobQueue())
  208. * .then(worker => worker.startHealthCheckServer({ port: 3020 }))
  209. * .catch(err => {
  210. * console.log(err);
  211. * process.exit(1);
  212. * });
  213. * ```
  214. * @docsCategory worker
  215. * @docsPage bootstrapWorker
  216. * @docsWeight 0
  217. * */
  218. export async function bootstrapWorker(
  219. userConfig: Partial<VendureConfig>,
  220. options?: BootstrapWorkerOptions,
  221. ): Promise<VendureWorker> {
  222. const vendureConfig = await preBootstrapConfig(userConfig);
  223. const config = disableSynchronize(vendureConfig);
  224. config.logger.setDefaultContext?.('Vendure Worker');
  225. Logger.useLogger(config.logger);
  226. Logger.info(`Bootstrapping Vendure Worker (pid: ${process.pid})...`);
  227. checkPluginCompatibility(config, options?.ignoreCompatibilityErrorsForPlugins);
  228. setProcessContext('worker');
  229. DefaultLogger.hideNestBoostrapLogs();
  230. const WorkerModule = await import('./worker/worker.module.js').then(m => m.WorkerModule);
  231. const workerApp = await NestFactory.createApplicationContext(WorkerModule, {
  232. logger: new Logger(),
  233. ...options?.nestApplicationContextOptions,
  234. });
  235. DefaultLogger.restoreOriginalLogLevel();
  236. workerApp.useLogger(new Logger());
  237. workerApp.enableShutdownHooks();
  238. await validateDbTablesForWorker(workerApp);
  239. Logger.info('Vendure Worker is ready');
  240. return new VendureWorker(workerApp);
  241. }
  242. /**
  243. * Setting the global config must be done prior to loading the AppModule.
  244. */
  245. export async function preBootstrapConfig(
  246. userConfig: Partial<VendureConfig>,
  247. ): Promise<Readonly<RuntimeVendureConfig>> {
  248. if (userConfig) {
  249. await setConfig(userConfig);
  250. }
  251. const entities = getAllEntities(userConfig);
  252. const { coreSubscribersMap } = await import('./entity/subscribers.js');
  253. await setConfig({
  254. dbConnectionOptions: {
  255. entities,
  256. subscribers: [
  257. ...((userConfig.dbConnectionOptions?.subscribers ?? []) as Array<
  258. Type<EntitySubscriberInterface>
  259. >),
  260. ...(Object.values(coreSubscribersMap) as Array<Type<EntitySubscriberInterface>>),
  261. ],
  262. },
  263. });
  264. let config = getConfig();
  265. // The logger is set here so that we are able to log any messages prior to the final
  266. // logger (which may depend on config coming from a plugin) being set.
  267. Logger.useLogger(config.logger);
  268. config = await runPluginConfigurations(config);
  269. const entityIdStrategy = config.entityOptions.entityIdStrategy ?? config.entityIdStrategy;
  270. setEntityIdStrategy(entityIdStrategy, entities);
  271. const moneyStrategy = config.entityOptions.moneyStrategy;
  272. setMoneyStrategy(moneyStrategy, entities);
  273. const customFieldValidationResult = validateCustomFieldsConfig(config.customFields, entities);
  274. if (!customFieldValidationResult.valid) {
  275. process.exitCode = 1;
  276. throw new Error('CustomFields config error:\n- ' + customFieldValidationResult.errors.join('\n- '));
  277. }
  278. registerCustomEntityFields(config);
  279. await runEntityMetadataModifiers(config);
  280. setExposedHeaders(config);
  281. return config;
  282. }
  283. function checkPluginCompatibility(
  284. config: RuntimeVendureConfig,
  285. ignoredPlugins: Array<DynamicModule | Type<any>> = [],
  286. ): void {
  287. for (const plugin of config.plugins) {
  288. const compatibility = getCompatibility(plugin);
  289. const pluginName = (plugin as any).name as string;
  290. if (!compatibility) {
  291. Logger.info(
  292. `The plugin "${pluginName}" does not specify a compatibility range, so it is not guaranteed to be compatible with this version of Vendure.`,
  293. );
  294. } else {
  295. if (!satisfies(VENDURE_VERSION, compatibility, { loose: true, includePrerelease: true })) {
  296. const compatibilityErrorMessage =
  297. `Plugin "${pluginName}" is not compatible with this version of Vendure. ` +
  298. `It specifies a semver range of "${compatibility}" but the current version is "${VENDURE_VERSION}".`;
  299. if (ignoredPlugins.includes(plugin)) {
  300. Logger.warn(
  301. compatibilityErrorMessage +
  302. `However, this plugin has been explicitly marked as ignored using the 'ignoreCompatibilityErrorsForPlugins' bootstrap option,` +
  303. ` so it will be loaded anyway.`,
  304. );
  305. continue;
  306. } else {
  307. Logger.error(compatibilityErrorMessage);
  308. throw new InternalServerError(
  309. `Plugin "${pluginName}" is not compatible with this version of Vendure.`,
  310. );
  311. }
  312. }
  313. }
  314. }
  315. }
  316. /**
  317. * Run the configuration functions of all plugins and return the final config object.
  318. */
  319. export async function runPluginConfigurations(config: RuntimeVendureConfig): Promise<RuntimeVendureConfig> {
  320. for (const plugin of config.plugins) {
  321. const configFn = getConfigurationFunction(plugin);
  322. if (typeof configFn === 'function') {
  323. const result = await configFn(config);
  324. Object.assign(config, result);
  325. }
  326. }
  327. return config;
  328. }
  329. /**
  330. * Returns an array of core entities and any additional entities defined in plugins.
  331. */
  332. export function getAllEntities(userConfig: Partial<VendureConfig>): Array<Type<any>> {
  333. const coreEntities = Object.values(coreEntitiesMap) as Array<Type<any>>;
  334. const pluginEntities = getEntitiesFromPlugins(userConfig.plugins);
  335. const allEntities: Array<Type<any>> = coreEntities;
  336. // Check to ensure that no plugins are defining entities with names
  337. // which conflict with existing entities.
  338. for (const pluginEntity of pluginEntities) {
  339. if (allEntities.find(e => e.name === pluginEntity.name)) {
  340. throw new InternalServerError('error.entity-name-conflict', { entityName: pluginEntity.name });
  341. } else {
  342. allEntities.push(pluginEntity);
  343. }
  344. }
  345. return allEntities;
  346. }
  347. /**
  348. * If the 'bearer' tokenMethod is being used, then we automatically expose the authTokenHeaderKey header
  349. * in the CORS options, making sure to preserve any user-configured exposedHeaders.
  350. */
  351. function setExposedHeaders(config: Readonly<RuntimeVendureConfig>) {
  352. const { tokenMethod } = config.authOptions;
  353. const isUsingBearerToken =
  354. tokenMethod === 'bearer' || (Array.isArray(tokenMethod) && tokenMethod.includes('bearer'));
  355. if (isUsingBearerToken) {
  356. const authTokenHeaderKey = config.authOptions.authTokenHeaderKey;
  357. const corsOptions = config.apiOptions.cors;
  358. if (typeof corsOptions !== 'boolean') {
  359. const { exposedHeaders } = corsOptions;
  360. let exposedHeadersWithAuthKey: string[];
  361. if (!exposedHeaders) {
  362. exposedHeadersWithAuthKey = [authTokenHeaderKey];
  363. } else if (typeof exposedHeaders === 'string') {
  364. exposedHeadersWithAuthKey = exposedHeaders
  365. .split(',')
  366. .map(x => x.trim())
  367. .concat(authTokenHeaderKey);
  368. } else {
  369. exposedHeadersWithAuthKey = exposedHeaders.concat(authTokenHeaderKey);
  370. }
  371. corsOptions.exposedHeaders = exposedHeadersWithAuthKey;
  372. }
  373. }
  374. }
  375. function logWelcomeMessage(config: RuntimeVendureConfig) {
  376. const { port, shopApiPath, adminApiPath, hostname } = config.apiOptions;
  377. const apiCliGreetings: Array<readonly [string, string]> = [];
  378. const pathToUrl = (path: string) => `http://${hostname || 'localhost'}:${port}/${path}`;
  379. apiCliGreetings.push(['Shop API', pathToUrl(shopApiPath)]);
  380. apiCliGreetings.push(['Admin API', pathToUrl(adminApiPath)]);
  381. apiCliGreetings.push(
  382. ...getPluginStartupMessages().map(({ label, path }) => [label, pathToUrl(path)] as const),
  383. );
  384. const columnarGreetings = arrangeCliGreetingsInColumns(apiCliGreetings);
  385. const title = `Vendure server (v${VENDURE_VERSION}) now running on port ${port}`;
  386. const maxLineLength = Math.max(title.length, ...columnarGreetings.map(l => l.length));
  387. const titlePadLength = title.length < maxLineLength ? Math.floor((maxLineLength - title.length) / 2) : 0;
  388. Logger.info('='.repeat(maxLineLength));
  389. Logger.info(title.padStart(title.length + titlePadLength));
  390. Logger.info('-'.repeat(maxLineLength).padStart(titlePadLength));
  391. columnarGreetings.forEach(line => Logger.info(line));
  392. Logger.info('='.repeat(maxLineLength));
  393. }
  394. function arrangeCliGreetingsInColumns(lines: Array<readonly [string, string]>): string[] {
  395. const columnWidth = Math.max(...lines.map(l => l[0].length)) + 2;
  396. return lines.map(l => `${(l[0] + ':').padEnd(columnWidth)}${l[1]}`);
  397. }
  398. /**
  399. * Fix race condition when modifying DB
  400. * See: https://github.com/vendure-ecommerce/vendure/issues/152
  401. */
  402. function disableSynchronize(userConfig: Readonly<RuntimeVendureConfig>): Readonly<RuntimeVendureConfig> {
  403. const config = {
  404. ...userConfig,
  405. dbConnectionOptions: {
  406. ...userConfig.dbConnectionOptions,
  407. synchronize: false,
  408. } as DataSourceOptions,
  409. };
  410. return config;
  411. }
  412. /**
  413. * Check that the Database tables exist. When running Vendure server & worker
  414. * concurrently for the first time, the worker will attempt to access the
  415. * DB tables before the server has populated them (assuming synchronize = true
  416. * in config). This method will use polling to check the existence of a known table
  417. * before allowing the rest of the worker bootstrap to continue.
  418. * @param worker
  419. */
  420. async function validateDbTablesForWorker(worker: INestApplicationContext) {
  421. const connection: Connection = worker.get(getConnectionToken());
  422. await new Promise<void>(async (resolve, reject) => {
  423. const checkForTables = async (): Promise<boolean> => {
  424. try {
  425. const adminCount = await connection.getRepository(Administrator).count();
  426. return 0 < adminCount;
  427. } catch (e: any) {
  428. return false;
  429. }
  430. };
  431. const pollIntervalMs = 5000;
  432. let attempts = 0;
  433. const maxAttempts = 10;
  434. let validTableStructure = false;
  435. Logger.verbose('Checking for expected DB table structure...');
  436. while (!validTableStructure && attempts < maxAttempts) {
  437. attempts++;
  438. validTableStructure = await checkForTables();
  439. if (validTableStructure) {
  440. Logger.verbose('Table structure verified');
  441. resolve();
  442. return;
  443. }
  444. Logger.verbose(
  445. `Table structure could not be verified, trying again after ${pollIntervalMs}ms (attempt ${attempts} of ${maxAttempts})`,
  446. );
  447. await new Promise(resolve1 => setTimeout(resolve1, pollIntervalMs));
  448. }
  449. reject('Could not validate DB table structure. Aborting bootstrap.');
  450. });
  451. }
  452. export function configureSessionCookies(
  453. app: INestApplication,
  454. userConfig: Readonly<RuntimeVendureConfig>,
  455. ): void {
  456. const { cookieOptions } = userConfig.authOptions;
  457. // Globally set the cookie session middleware
  458. const cookieName =
  459. typeof cookieOptions?.name !== 'string' ? cookieOptions.name?.shop : cookieOptions.name;
  460. app.use(
  461. cookieSession({
  462. ...cookieOptions,
  463. name: cookieName ?? DEFAULT_COOKIE_NAME,
  464. }),
  465. );
  466. }