bootstrap.ts 19 KB

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