plugin.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 { getApiExtensions } from './api/api-extensions';
  26. import { MetricsResolver } from './api/metrics.resolver';
  27. import {
  28. DEFAULT_APP_PATH,
  29. defaultAvailableLanguages,
  30. defaultAvailableLocales,
  31. defaultLanguage,
  32. defaultLocale,
  33. loggerCtx,
  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. * @description
  80. * @deprecated This option no longer has any effect.
  81. *
  82. * Previously used when running the AdminUiPlugin at the same time as the new `DashboardPlugin`
  83. * to avoid conflicts, but this is no longer necessary as the schemas use different type names.
  84. *
  85. * @since 3.4.0
  86. */
  87. compatibilityMode?: boolean;
  88. }
  89. /**
  90. * @description
  91. *
  92. * :::warning Deprecated
  93. * From Vendure v3.5.0, the Angular-based Admin UI has been replaced by the new [React Admin Dashboard](/guides/extending-the-dashboard/getting-started/).
  94. * The Angular Admin UI will not be maintained after **July 2026**. Until then, we will continue patching critical bugs and security issues.
  95. * Community contributions will always be merged and released.
  96. * :::
  97. *
  98. * This plugin starts a static server for the Admin UI app, and proxies it via the `/admin/` path of the main Vendure server.
  99. *
  100. * The Admin UI allows you to administer all aspects of your store, from inventory management to order tracking. It is the tool used by
  101. * store administrators on a day-to-day basis for the management of the store.
  102. *
  103. * ## Installation
  104. *
  105. * `yarn add \@vendure/admin-ui-plugin`
  106. *
  107. * or
  108. *
  109. * `npm install \@vendure/admin-ui-plugin`
  110. *
  111. * @example
  112. * ```ts
  113. * import { AdminUiPlugin } from '\@vendure/admin-ui-plugin';
  114. *
  115. * const config: VendureConfig = {
  116. * // Add an instance of the plugin to the plugins array
  117. * plugins: [
  118. * AdminUiPlugin.init({ port: 3002 }),
  119. * ],
  120. * };
  121. * ```
  122. *
  123. * ## Metrics
  124. *
  125. * This plugin also defines a `metricSummary` query which is used by the Admin UI to display the order metrics on the dashboard.
  126. *
  127. * 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,
  128. * you can still use the `metricSummary` query by adding the `AdminUiPlugin` to the `plugins` array, but without calling the `init()` method:
  129. *
  130. * @example
  131. * ```ts
  132. * import { AdminUiPlugin } from '\@vendure/admin-ui-plugin';
  133. *
  134. * const config: VendureConfig = {
  135. * plugins: [
  136. * AdminUiPlugin, // <-- no call to .init()
  137. * ],
  138. * // ...
  139. * };
  140. * ```
  141. *
  142. * @docsCategory core plugins/AdminUiPlugin
  143. */
  144. @VendurePlugin({
  145. imports: [PluginCommonModule],
  146. adminApiExtensions: {
  147. schema: () => getApiExtensions(),
  148. resolvers: () => [MetricsResolver],
  149. },
  150. providers: [MetricsService],
  151. compatibility: '^3.0.0',
  152. })
  153. export class AdminUiPlugin implements NestModule {
  154. private static options: AdminUiPluginOptions | undefined;
  155. constructor(
  156. private configService: ConfigService,
  157. private processContext: ProcessContext,
  158. ) {}
  159. /**
  160. * @description
  161. * Set the plugin options
  162. */
  163. static init(options: AdminUiPluginOptions): Type<AdminUiPlugin> {
  164. this.options = options;
  165. return AdminUiPlugin;
  166. }
  167. async configure(consumer: MiddlewareConsumer) {
  168. if (this.processContext.isWorker) {
  169. return;
  170. }
  171. if (!AdminUiPlugin.options) {
  172. Logger.info(
  173. `AdminUiPlugin's init() method was not called. The Admin UI will not be served.`,
  174. loggerCtx,
  175. );
  176. return;
  177. }
  178. const { app, hostname, route, adminUiConfig } = AdminUiPlugin.options;
  179. const adminUiAppPath = AdminUiPlugin.isDevModeApp(app)
  180. ? path.join(app.sourcePath, 'src')
  181. : (app && app.path) || DEFAULT_APP_PATH;
  182. const adminUiConfigPath = path.join(adminUiAppPath, 'vendure-ui-config.json');
  183. const indexHtmlPath = path.join(adminUiAppPath, 'index.html');
  184. const overwriteConfig = async () => {
  185. const uiConfig = this.getAdminUiConfig(adminUiConfig);
  186. await this.overwriteAdminUiConfig(adminUiConfigPath, uiConfig);
  187. await this.overwriteBaseHref(indexHtmlPath, route);
  188. };
  189. let port: number;
  190. if (AdminUiPlugin.isDevModeApp(app)) {
  191. port = app.port;
  192. } else {
  193. port = AdminUiPlugin.options.port;
  194. }
  195. if (AdminUiPlugin.isDevModeApp(app)) {
  196. Logger.info('Creating admin ui middleware (dev mode)', loggerCtx);
  197. consumer
  198. .apply(
  199. createProxyHandler({
  200. hostname,
  201. port,
  202. route,
  203. label: 'Admin UI',
  204. basePath: route,
  205. }),
  206. )
  207. .forRoutes(route);
  208. consumer
  209. .apply(
  210. createProxyHandler({
  211. hostname,
  212. port,
  213. route: 'sockjs-node',
  214. label: 'Admin UI live reload',
  215. basePath: 'sockjs-node',
  216. }),
  217. )
  218. .forRoutes('sockjs-node');
  219. Logger.info('Compiling Admin UI app in development mode', loggerCtx);
  220. app.compile().then(
  221. () => {
  222. Logger.info('Admin UI compiling and watching for changes...', loggerCtx);
  223. },
  224. (err: any) => {
  225. Logger.error(`Failed to compile: ${JSON.stringify(err)}`, loggerCtx, err.stack);
  226. },
  227. );
  228. await overwriteConfig();
  229. } else {
  230. Logger.info('Creating admin ui middleware (prod mode)', loggerCtx);
  231. consumer.apply(this.createStaticServer(app)).forRoutes(route);
  232. if (app && typeof app.compile === 'function') {
  233. Logger.info('Compiling Admin UI app in production mode...', loggerCtx);
  234. app.compile()
  235. .then(overwriteConfig)
  236. .then(
  237. () => {
  238. Logger.info('Admin UI successfully compiled', loggerCtx);
  239. },
  240. (err: any) => {
  241. Logger.error(`Failed to compile: ${JSON.stringify(err)}`, loggerCtx, err.stack);
  242. },
  243. );
  244. } else {
  245. await overwriteConfig();
  246. }
  247. }
  248. registerPluginStartupMessage('Admin UI', route);
  249. }
  250. private createStaticServer(app?: AdminUiAppConfig) {
  251. const adminUiAppPath = (app && app.path) || DEFAULT_APP_PATH;
  252. const limiter = rateLimit({
  253. windowMs: 60 * 1000,
  254. limit: process.env.NODE_ENV === 'production' ? 500 : 2000,
  255. standardHeaders: true,
  256. legacyHeaders: false,
  257. });
  258. const adminUiServer = express.Router();
  259. // This is a workaround for a type mismatch between express v5 (Vendure core)
  260. // and express v4 (several transitive dependencies). Can be removed once the
  261. // ecosystem has more significantly shifted to v5.
  262. adminUiServer.use(limiter as any);
  263. adminUiServer.use(express.static(adminUiAppPath));
  264. adminUiServer.use((req, res) => {
  265. res.sendFile('index.html', { root: adminUiAppPath });
  266. });
  267. return adminUiServer;
  268. }
  269. /**
  270. * Takes an optional AdminUiConfig provided in the plugin options, and returns a complete
  271. * config object for writing to disk.
  272. */
  273. private getAdminUiConfig(partialConfig?: Partial<AdminUiConfig>): AdminUiConfig {
  274. const { authOptions, apiOptions } = this.configService;
  275. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  276. const options = AdminUiPlugin.options!;
  277. const propOrDefault = <Prop extends keyof AdminUiConfig>(
  278. prop: Prop,
  279. defaultVal: AdminUiConfig[Prop],
  280. isArray: boolean = false,
  281. ): AdminUiConfig[Prop] => {
  282. if (isArray) {
  283. const isValidArray = !!partialConfig
  284. ? !!((partialConfig as AdminUiConfig)[prop] as any[])?.length
  285. : false;
  286. return !!partialConfig && isValidArray ? (partialConfig as AdminUiConfig)[prop] : defaultVal;
  287. } else {
  288. return partialConfig ? (partialConfig as AdminUiConfig)[prop] || defaultVal : defaultVal;
  289. }
  290. };
  291. return {
  292. adminApiPath: propOrDefault('adminApiPath', apiOptions.adminApiPath),
  293. apiHost: propOrDefault('apiHost', 'auto'),
  294. apiPort: propOrDefault('apiPort', 'auto'),
  295. tokenMethod: propOrDefault(
  296. 'tokenMethod',
  297. authOptions.tokenMethod === 'bearer' ? 'bearer' : 'cookie',
  298. ),
  299. authTokenHeaderKey: propOrDefault(
  300. 'authTokenHeaderKey',
  301. authOptions.authTokenHeaderKey || DEFAULT_AUTH_TOKEN_HEADER_KEY,
  302. ),
  303. channelTokenKey: propOrDefault(
  304. 'channelTokenKey',
  305. apiOptions.channelTokenKey || DEFAULT_CHANNEL_TOKEN_KEY,
  306. ),
  307. defaultLanguage: propOrDefault('defaultLanguage', defaultLanguage),
  308. defaultLocale: propOrDefault('defaultLocale', defaultLocale),
  309. availableLanguages: propOrDefault('availableLanguages', defaultAvailableLanguages, true),
  310. availableLocales: propOrDefault('availableLocales', defaultAvailableLocales, true),
  311. loginUrl: options.adminUiConfig?.loginUrl,
  312. brand: options.adminUiConfig?.brand,
  313. hideVendureBranding: propOrDefault(
  314. 'hideVendureBranding',
  315. options.adminUiConfig?.hideVendureBranding || false,
  316. ),
  317. hideVersion: propOrDefault('hideVersion', options.adminUiConfig?.hideVersion || false),
  318. loginImageUrl: options.adminUiConfig?.loginImageUrl,
  319. cancellationReasons: propOrDefault('cancellationReasons', undefined),
  320. };
  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 overwriteAdminUiConfig(adminUiConfigPath: string, config: AdminUiConfig) {
  327. try {
  328. const content = await this.pollForFile(adminUiConfigPath);
  329. } catch (e: any) {
  330. Logger.error(e.message, loggerCtx);
  331. throw e;
  332. }
  333. try {
  334. await fs.writeFile(adminUiConfigPath, JSON.stringify(config, null, 2));
  335. } catch (e: any) {
  336. throw new Error(
  337. '[AdminUiPlugin] Could not write vendure-ui-config.json file:\n' + JSON.stringify(e.message),
  338. );
  339. }
  340. Logger.verbose('Applied configuration to vendure-ui-config.json file', loggerCtx);
  341. }
  342. /**
  343. * Overwrites the parts of the admin-ui app's `vendure-ui-config.json` file relating to connecting to
  344. * the server admin API.
  345. */
  346. private async overwriteBaseHref(indexHtmlPath: string, baseHref: string) {
  347. let indexHtmlContent: string;
  348. try {
  349. indexHtmlContent = await this.pollForFile(indexHtmlPath);
  350. } catch (e: any) {
  351. Logger.error(e.message, loggerCtx);
  352. throw e;
  353. }
  354. try {
  355. const withCustomBaseHref = indexHtmlContent.replace(
  356. /<base href=".+"\s*\/>/,
  357. `<base href="/${baseHref}/" />`,
  358. );
  359. await fs.writeFile(indexHtmlPath, withCustomBaseHref);
  360. } catch (e: any) {
  361. throw new Error('[AdminUiPlugin] Could not write index.html file:\n' + JSON.stringify(e.message));
  362. }
  363. Logger.verbose(`Applied baseHref "/${baseHref}/" to index.html file`, loggerCtx);
  364. }
  365. /**
  366. * It might be that the ui-devkit compiler has not yet copied the config
  367. * file to the expected location (particularly when running in watch mode),
  368. * so polling is used to check multiple times with a delay.
  369. */
  370. private async pollForFile(filePath: string) {
  371. const maxRetries = 10;
  372. const retryDelay = 200;
  373. let attempts = 0;
  374. const pause = () => new Promise(resolve => setTimeout(resolve, retryDelay));
  375. while (attempts < maxRetries) {
  376. try {
  377. Logger.verbose(`Checking for admin ui file: ${filePath}`, loggerCtx);
  378. const configFileContent = await fs.readFile(filePath, 'utf-8');
  379. return configFileContent;
  380. } catch (e: any) {
  381. attempts++;
  382. Logger.verbose(
  383. `Unable to locate admin ui file: ${filePath} (attempt ${attempts})`,
  384. loggerCtx,
  385. );
  386. }
  387. await pause();
  388. }
  389. throw new Error(`Unable to locate admin ui file: ${filePath}`);
  390. }
  391. private static isDevModeApp(
  392. app?: AdminUiAppConfig | AdminUiAppDevModeConfig,
  393. ): app is AdminUiAppDevModeConfig {
  394. if (!app) {
  395. return false;
  396. }
  397. return !!(app as AdminUiAppDevModeConfig).sourcePath;
  398. }
  399. }