plugin.ts 10 KB

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