plugin.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. import { MiddlewareConsumer, NestModule } from '@nestjs/common';
  2. import {
  3. DEFAULT_AUTH_TOKEN_HEADER_KEY,
  4. DEFAULT_CHANNEL_TOKEN_KEY,
  5. } from '@vendure/common/lib/shared-constants';
  6. import {
  7. AdminUiAppConfig,
  8. AdminUiAppDevModeConfig,
  9. AdminUiConfig,
  10. Type,
  11. } from '@vendure/common/lib/shared-types';
  12. import {
  13. ConfigService,
  14. createProxyHandler,
  15. Logger,
  16. PluginCommonModule,
  17. ProcessContext,
  18. registerPluginStartupMessage,
  19. VendurePlugin,
  20. } from '@vendure/core';
  21. import express from 'express';
  22. import { rateLimit } from 'express-rate-limit';
  23. import fs from 'fs-extra';
  24. import path from 'path';
  25. import { adminApiExtensions } from './api/api-extensions';
  26. import { MetricsResolver } from './api/metrics.resolver';
  27. import {
  28. defaultAvailableLanguages,
  29. defaultLanguage,
  30. defaultLocale,
  31. DEFAULT_APP_PATH,
  32. loggerCtx,
  33. defaultAvailableLocales,
  34. } from './constants';
  35. import { MetricsService } from './service/metrics.service';
  36. /**
  37. * @description
  38. * Configuration options for the {@link AdminUiPlugin}.
  39. *
  40. * @docsCategory core plugins/AdminUiPlugin
  41. */
  42. export interface AdminUiPluginOptions {
  43. /**
  44. * @description
  45. * The route to the Admin UI.
  46. *
  47. * Note: If you are using the `compileUiExtensions` function to compile a custom version of the Admin UI, then
  48. * the route should match the `baseHref` option passed to that function. The default value of `baseHref` is `/admin/`,
  49. * so it only needs to be changed if you set this `route` option to something other than `"admin"`.
  50. */
  51. route: string;
  52. /**
  53. * @description
  54. * The port on which the server will listen. This port will be proxied by the AdminUiPlugin to the same port that
  55. * the Vendure server is running on.
  56. */
  57. port: number;
  58. /**
  59. * @description
  60. * The hostname of the server serving the static admin ui files.
  61. *
  62. * @default 'localhost'
  63. */
  64. hostname?: string;
  65. /**
  66. * @description
  67. * By default, the AdminUiPlugin comes bundles with a pre-built version of the
  68. * Admin UI. This option can be used to override this default build with a different
  69. * version, e.g. one pre-compiled with one or more ui extensions.
  70. */
  71. app?: AdminUiAppConfig | AdminUiAppDevModeConfig;
  72. /**
  73. * @description
  74. * Allows the contents of the `vendure-ui-config.json` file to be set, e.g.
  75. * for specifying the Vendure GraphQL API host, available UI languages, etc.
  76. */
  77. adminUiConfig?: Partial<AdminUiConfig>;
  78. }
  79. /**
  80. * @description
  81. * This plugin starts a static server for the Admin UI app, and proxies it via the `/admin/` path of the main Vendure server.
  82. *
  83. * The Admin UI allows you to administer all aspects of your store, from inventory management to order tracking. It is the tool used by
  84. * store administrators on a day-to-day basis for the management of the store.
  85. *
  86. * ## Installation
  87. *
  88. * `yarn add \@vendure/admin-ui-plugin`
  89. *
  90. * or
  91. *
  92. * `npm install \@vendure/admin-ui-plugin`
  93. *
  94. * @example
  95. * ```ts
  96. * import { AdminUiPlugin } from '\@vendure/admin-ui-plugin';
  97. *
  98. * const config: VendureConfig = {
  99. * // Add an instance of the plugin to the plugins array
  100. * plugins: [
  101. * AdminUiPlugin.init({ port: 3002 }),
  102. * ],
  103. * };
  104. * ```
  105. *
  106. * ## Metrics
  107. *
  108. * This plugin also defines a `metricSummary` query which is used by the Admin UI to display the order metrics on the dashboard.
  109. *
  110. * If you are building a stand-alone version of the Admin UI app, and therefore don't need this plugin to server the Admin UI,
  111. * you can still use the `metricSummary` query by adding the `AdminUiPlugin` to the `plugins` array, but without calling the `init()` method:
  112. *
  113. * @example
  114. * ```ts
  115. * import { AdminUiPlugin } from '\@vendure/admin-ui-plugin';
  116. *
  117. * const config: VendureConfig = {
  118. * plugins: [
  119. * AdminUiPlugin, // <-- no call to .init()
  120. * ],
  121. * // ...
  122. * };
  123. * ```
  124. *
  125. * @docsCategory core plugins/AdminUiPlugin
  126. */
  127. @VendurePlugin({
  128. imports: [PluginCommonModule],
  129. adminApiExtensions: {
  130. schema: adminApiExtensions,
  131. resolvers: [MetricsResolver],
  132. },
  133. providers: [MetricsService],
  134. compatibility: '^3.0.0',
  135. })
  136. export class AdminUiPlugin implements NestModule {
  137. private static options: AdminUiPluginOptions | undefined;
  138. constructor(
  139. private configService: ConfigService,
  140. private processContext: ProcessContext,
  141. ) {}
  142. /**
  143. * @description
  144. * Set the plugin options
  145. */
  146. static init(options: AdminUiPluginOptions): Type<AdminUiPlugin> {
  147. this.options = options;
  148. return AdminUiPlugin;
  149. }
  150. async configure(consumer: MiddlewareConsumer) {
  151. if (this.processContext.isWorker) {
  152. return;
  153. }
  154. if (!AdminUiPlugin.options) {
  155. Logger.info(
  156. `AdminUiPlugin's init() method was not called. The Admin UI will not be served.`,
  157. loggerCtx,
  158. );
  159. return;
  160. }
  161. const { app, hostname, route, adminUiConfig } = AdminUiPlugin.options;
  162. const adminUiAppPath = AdminUiPlugin.isDevModeApp(app)
  163. ? path.join(app.sourcePath, 'src')
  164. : (app && app.path) || DEFAULT_APP_PATH;
  165. const adminUiConfigPath = path.join(adminUiAppPath, 'vendure-ui-config.json');
  166. const indexHtmlPath = path.join(adminUiAppPath, 'index.html');
  167. const overwriteConfig = async () => {
  168. const uiConfig = this.getAdminUiConfig(adminUiConfig);
  169. await this.overwriteAdminUiConfig(adminUiConfigPath, uiConfig);
  170. await this.overwriteBaseHref(indexHtmlPath, route);
  171. };
  172. let port: number;
  173. if (AdminUiPlugin.isDevModeApp(app)) {
  174. port = app.port;
  175. } else {
  176. port = AdminUiPlugin.options.port;
  177. }
  178. if (AdminUiPlugin.isDevModeApp(app)) {
  179. Logger.info('Creating admin ui middleware (dev mode)', loggerCtx);
  180. consumer
  181. .apply(
  182. createProxyHandler({
  183. hostname,
  184. port,
  185. route,
  186. label: 'Admin UI',
  187. basePath: route,
  188. }),
  189. )
  190. .forRoutes(route);
  191. consumer
  192. .apply(
  193. createProxyHandler({
  194. hostname,
  195. port,
  196. route: 'sockjs-node',
  197. label: 'Admin UI live reload',
  198. basePath: 'sockjs-node',
  199. }),
  200. )
  201. .forRoutes('sockjs-node');
  202. Logger.info('Compiling Admin UI app in development mode', loggerCtx);
  203. app.compile().then(
  204. () => {
  205. Logger.info('Admin UI compiling and watching for changes...', loggerCtx);
  206. },
  207. (err: any) => {
  208. Logger.error(`Failed to compile: ${JSON.stringify(err)}`, loggerCtx, err.stack);
  209. },
  210. );
  211. await overwriteConfig();
  212. } else {
  213. Logger.info('Creating admin ui middleware (prod mode)', loggerCtx);
  214. consumer.apply(this.createStaticServer(app)).forRoutes(route);
  215. if (app && typeof app.compile === 'function') {
  216. Logger.info('Compiling Admin UI app in production mode...', loggerCtx);
  217. app.compile()
  218. .then(overwriteConfig)
  219. .then(
  220. () => {
  221. Logger.info('Admin UI successfully compiled', loggerCtx);
  222. },
  223. (err: any) => {
  224. Logger.error(`Failed to compile: ${JSON.stringify(err)}`, loggerCtx, err.stack);
  225. },
  226. );
  227. } else {
  228. await overwriteConfig();
  229. }
  230. }
  231. registerPluginStartupMessage('Admin UI', route);
  232. }
  233. private createStaticServer(app?: AdminUiAppConfig) {
  234. const adminUiAppPath = (app && app.path) || DEFAULT_APP_PATH;
  235. const limiter = rateLimit({
  236. windowMs: 60 * 1000,
  237. limit: process.env.NODE_ENV === 'production' ? 500 : 2000,
  238. standardHeaders: true,
  239. legacyHeaders: false,
  240. });
  241. const adminUiServer = express.Router();
  242. adminUiServer.use(limiter);
  243. adminUiServer.use(express.static(adminUiAppPath));
  244. adminUiServer.use((req, res) => {
  245. res.sendFile(path.join(adminUiAppPath, 'index.html'));
  246. });
  247. return adminUiServer;
  248. }
  249. /**
  250. * Takes an optional AdminUiConfig provided in the plugin options, and returns a complete
  251. * config object for writing to disk.
  252. */
  253. private getAdminUiConfig(partialConfig?: Partial<AdminUiConfig>): AdminUiConfig {
  254. const { authOptions, apiOptions } = this.configService;
  255. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  256. const options = AdminUiPlugin.options!;
  257. const propOrDefault = <Prop extends keyof AdminUiConfig>(
  258. prop: Prop,
  259. defaultVal: AdminUiConfig[Prop],
  260. isArray: boolean = false,
  261. ): AdminUiConfig[Prop] => {
  262. if (isArray) {
  263. const isValidArray = !!partialConfig
  264. ? !!((partialConfig as AdminUiConfig)[prop] as any[])?.length
  265. : false;
  266. return !!partialConfig && isValidArray ? (partialConfig as AdminUiConfig)[prop] : defaultVal;
  267. } else {
  268. return partialConfig ? (partialConfig as AdminUiConfig)[prop] || defaultVal : defaultVal;
  269. }
  270. };
  271. return {
  272. adminApiPath: propOrDefault('adminApiPath', apiOptions.adminApiPath),
  273. apiHost: propOrDefault('apiHost', 'auto'),
  274. apiPort: propOrDefault('apiPort', 'auto'),
  275. tokenMethod: propOrDefault(
  276. 'tokenMethod',
  277. authOptions.tokenMethod === 'bearer' ? 'bearer' : 'cookie',
  278. ),
  279. authTokenHeaderKey: propOrDefault(
  280. 'authTokenHeaderKey',
  281. authOptions.authTokenHeaderKey || DEFAULT_AUTH_TOKEN_HEADER_KEY,
  282. ),
  283. channelTokenKey: propOrDefault(
  284. 'channelTokenKey',
  285. apiOptions.channelTokenKey || DEFAULT_CHANNEL_TOKEN_KEY,
  286. ),
  287. defaultLanguage: propOrDefault('defaultLanguage', defaultLanguage),
  288. defaultLocale: propOrDefault('defaultLocale', defaultLocale),
  289. availableLanguages: propOrDefault('availableLanguages', defaultAvailableLanguages, true),
  290. availableLocales: propOrDefault('availableLocales', defaultAvailableLocales, true),
  291. loginUrl: options.adminUiConfig?.loginUrl,
  292. brand: options.adminUiConfig?.brand,
  293. hideVendureBranding: propOrDefault(
  294. 'hideVendureBranding',
  295. options.adminUiConfig?.hideVendureBranding || false,
  296. ),
  297. hideVersion: propOrDefault('hideVersion', options.adminUiConfig?.hideVersion || false),
  298. loginImageUrl: options.adminUiConfig?.loginImageUrl,
  299. cancellationReasons: propOrDefault('cancellationReasons', undefined),
  300. };
  301. }
  302. /**
  303. * Overwrites the parts of the admin-ui app's `vendure-ui-config.json` file relating to connecting to
  304. * the server admin API.
  305. */
  306. private async overwriteAdminUiConfig(adminUiConfigPath: string, config: AdminUiConfig) {
  307. try {
  308. const content = await this.pollForFile(adminUiConfigPath);
  309. } catch (e: any) {
  310. Logger.error(e.message, loggerCtx);
  311. throw e;
  312. }
  313. try {
  314. await fs.writeFile(adminUiConfigPath, JSON.stringify(config, null, 2));
  315. } catch (e: any) {
  316. throw new Error(
  317. '[AdminUiPlugin] Could not write vendure-ui-config.json file:\n' + JSON.stringify(e.message),
  318. );
  319. }
  320. Logger.verbose('Applied configuration to vendure-ui-config.json file', loggerCtx);
  321. }
  322. /**
  323. * Overwrites the parts of the admin-ui app's `vendure-ui-config.json` file relating to connecting to
  324. * the server admin API.
  325. */
  326. private async overwriteBaseHref(indexHtmlPath: string, baseHref: string) {
  327. let indexHtmlContent: string;
  328. try {
  329. indexHtmlContent = await this.pollForFile(indexHtmlPath);
  330. } catch (e: any) {
  331. Logger.error(e.message, loggerCtx);
  332. throw e;
  333. }
  334. try {
  335. const withCustomBaseHref = indexHtmlContent.replace(
  336. /<base href=".+"\s*\/>/,
  337. `<base href="/${baseHref}/" />`,
  338. );
  339. await fs.writeFile(indexHtmlPath, withCustomBaseHref);
  340. } catch (e: any) {
  341. throw new Error('[AdminUiPlugin] Could not write index.html file:\n' + JSON.stringify(e.message));
  342. }
  343. Logger.verbose(`Applied baseHref "/${baseHref}/" to index.html file`, loggerCtx);
  344. }
  345. /**
  346. * It might be that the ui-devkit compiler has not yet copied the config
  347. * file to the expected location (particularly when running in watch mode),
  348. * so polling is used to check multiple times with a delay.
  349. */
  350. private async pollForFile(filePath: string) {
  351. const maxRetries = 10;
  352. const retryDelay = 200;
  353. let attempts = 0;
  354. const pause = () => new Promise(resolve => setTimeout(resolve, retryDelay));
  355. while (attempts < maxRetries) {
  356. try {
  357. Logger.verbose(`Checking for admin ui file: ${filePath}`, loggerCtx);
  358. const configFileContent = await fs.readFile(filePath, 'utf-8');
  359. return configFileContent;
  360. } catch (e: any) {
  361. attempts++;
  362. Logger.verbose(
  363. `Unable to locate admin ui file: ${filePath} (attempt ${attempts})`,
  364. loggerCtx,
  365. );
  366. }
  367. await pause();
  368. }
  369. throw new Error(`Unable to locate admin ui file: ${filePath}`);
  370. }
  371. private static isDevModeApp(
  372. app?: AdminUiAppConfig | AdminUiAppDevModeConfig,
  373. ): app is AdminUiAppDevModeConfig {
  374. if (!app) {
  375. return false;
  376. }
  377. return !!(app as AdminUiAppDevModeConfig).sourcePath;
  378. }
  379. }