plugin.ts 12 KB

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