@docusaurus/core 2.0.0-beta.1ec2c95e3 → 2.0.0-beta.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/bin/beforeCli.mjs +140 -0
  2. package/bin/docusaurus.mjs +236 -0
  3. package/lib/babel/preset.d.ts +8 -3
  4. package/lib/babel/preset.js +10 -8
  5. package/lib/client/.eslintrc.js +2 -4
  6. package/lib/client/App.d.ts +2 -3
  7. package/lib/client/App.js +31 -28
  8. package/lib/client/BaseUrlIssueBanner/index.d.ts +27 -0
  9. package/lib/client/{baseUrlIssueBanner/BaseUrlIssueBanner.js → BaseUrlIssueBanner/index.js} +24 -14
  10. package/lib/client/{baseUrlIssueBanner → BaseUrlIssueBanner}/styles.module.css +0 -0
  11. package/lib/client/ClientLifecyclesDispatcher.d.ts +16 -0
  12. package/lib/client/ClientLifecyclesDispatcher.js +39 -0
  13. package/lib/client/LinksCollector.d.ts +3 -3
  14. package/lib/client/LinksCollector.js +8 -13
  15. package/lib/client/PendingNavigation.d.ts +17 -3
  16. package/lib/client/PendingNavigation.js +41 -72
  17. package/lib/client/{baseUrlIssueBanner/BaseUrlIssueBanner.d.ts → SiteMetadataDefaults.d.ts} +1 -2
  18. package/lib/client/SiteMetadataDefaults.js +21 -0
  19. package/lib/{choosePort.d.ts → client/browserContext.d.ts} +5 -5
  20. package/lib/client/browserContext.js +22 -0
  21. package/lib/client/clientEntry.js +14 -9
  22. package/lib/client/docusaurus.d.ts +12 -6
  23. package/lib/client/docusaurus.js +30 -43
  24. package/lib/client/docusaurusContext.d.ts +12 -0
  25. package/lib/client/docusaurusContext.js +25 -0
  26. package/lib/client/exports/BrowserOnly.d.ts +3 -5
  27. package/lib/client/exports/BrowserOnly.js +14 -8
  28. package/lib/client/exports/ComponentCreator.d.ts +6 -2
  29. package/lib/client/exports/ComponentCreator.js +75 -42
  30. package/lib/client/exports/ErrorBoundary.d.ts +18 -0
  31. package/lib/client/exports/ErrorBoundary.js +36 -0
  32. package/lib/client/exports/Head.d.ts +2 -3
  33. package/lib/client/exports/Head.js +3 -4
  34. package/lib/client/exports/Interpolate.d.ts +2 -2
  35. package/lib/client/exports/Interpolate.js +20 -49
  36. package/lib/client/exports/Link.d.ts +4 -10
  37. package/lib/client/exports/Link.js +38 -38
  38. package/lib/client/exports/Translate.d.ts +1 -1
  39. package/lib/client/exports/Translate.js +14 -9
  40. package/lib/client/exports/constants.js +1 -11
  41. package/lib/client/exports/isInternalUrl.js +1 -1
  42. package/lib/client/exports/renderRoutes.d.ts +1 -2
  43. package/lib/client/exports/renderRoutes.js +1 -2
  44. package/lib/client/exports/router.d.ts +1 -1
  45. package/lib/client/exports/router.js +1 -1
  46. package/lib/client/exports/useBaseUrl.js +11 -14
  47. package/lib/client/exports/useDocusaurusContext.d.ts +2 -3
  48. package/lib/client/exports/useDocusaurusContext.js +3 -9
  49. package/lib/client/exports/useGlobalData.d.ts +4 -3
  50. package/lib/client/exports/useGlobalData.js +6 -13
  51. package/lib/{server/versions/__tests/index.test.d.ts → client/exports/useIsBrowser.d.ts} +1 -1
  52. package/lib/client/exports/useIsBrowser.js +11 -0
  53. package/lib/client/exports/useRouteContext.d.ts +8 -0
  54. package/lib/client/exports/useRouteContext.js +15 -0
  55. package/lib/client/flat.d.ts +12 -2
  56. package/lib/client/flat.js +19 -15
  57. package/lib/client/normalizeLocation.d.ts +2 -5
  58. package/lib/client/normalizeLocation.js +14 -10
  59. package/lib/client/prefetch.d.ts +1 -2
  60. package/lib/client/prefetch.js +12 -32
  61. package/lib/client/preload.d.ts +3 -4
  62. package/lib/client/preload.js +5 -12
  63. package/lib/client/routeContext.d.ts +13 -0
  64. package/lib/client/routeContext.js +31 -0
  65. package/lib/client/serverEntry.d.ts +10 -0
  66. package/lib/client/serverEntry.js +105 -146
  67. package/lib/client/theme-fallback/Error/index.d.ts +10 -0
  68. package/lib/client/theme-fallback/Error/index.js +45 -0
  69. package/lib/client/theme-fallback/Layout/index.d.ts +10 -0
  70. package/lib/client/theme-fallback/Layout/index.js +2 -26
  71. package/lib/client/theme-fallback/Loading/index.d.ts +9 -0
  72. package/lib/client/theme-fallback/Loading/index.js +50 -116
  73. package/lib/client/{exports/context.js → theme-fallback/NotFound/index.d.ts} +2 -2
  74. package/lib/client/theme-fallback/NotFound/index.js +19 -18
  75. package/lib/client/theme-fallback/Root/index.d.ts +10 -0
  76. package/lib/client/theme-fallback/Root/index.js +2 -6
  77. package/lib/{server/html-tags/htmlTags.d.ts → client/theme-fallback/SiteMetadata/index.d.ts} +2 -1
  78. package/lib/client/theme-fallback/SiteMetadata/index.js +10 -0
  79. package/lib/commands/build.d.ts +6 -2
  80. package/lib/commands/build.js +80 -64
  81. package/lib/commands/clear.d.ts +7 -1
  82. package/lib/commands/clear.js +32 -20
  83. package/lib/commands/deploy.d.ts +5 -2
  84. package/lib/commands/deploy.js +93 -81
  85. package/lib/commands/external.d.ts +2 -2
  86. package/lib/commands/external.js +6 -11
  87. package/lib/commands/serve.d.ts +8 -2
  88. package/lib/commands/serve.js +26 -27
  89. package/lib/commands/start.d.ts +9 -2
  90. package/lib/commands/start.js +106 -92
  91. package/lib/commands/swizzle/actions.d.ts +23 -0
  92. package/lib/commands/swizzle/actions.js +100 -0
  93. package/lib/commands/swizzle/common.d.ts +33 -0
  94. package/lib/commands/swizzle/common.js +56 -0
  95. package/lib/commands/swizzle/components.d.ts +29 -0
  96. package/lib/commands/swizzle/components.js +200 -0
  97. package/lib/commands/swizzle/config.d.ts +10 -0
  98. package/lib/commands/swizzle/config.js +84 -0
  99. package/lib/{server/client-modules/index.d.ts → commands/swizzle/context.d.ts} +2 -2
  100. package/lib/commands/swizzle/context.js +24 -0
  101. package/lib/commands/swizzle/index.d.ts +8 -0
  102. package/lib/commands/swizzle/index.js +116 -0
  103. package/lib/commands/swizzle/prompts.d.ts +12 -0
  104. package/lib/commands/swizzle/prompts.js +110 -0
  105. package/lib/{client/exports/context.d.ts → commands/swizzle/tables.d.ts} +3 -4
  106. package/lib/commands/swizzle/tables.js +113 -0
  107. package/lib/commands/swizzle/themes.d.ts +20 -0
  108. package/lib/commands/swizzle/themes.js +106 -0
  109. package/lib/commands/writeHeadingIds.d.ts +2 -6
  110. package/lib/commands/writeHeadingIds.js +21 -81
  111. package/lib/commands/writeTranslations.d.ts +4 -5
  112. package/lib/commands/writeTranslations.js +39 -20
  113. package/lib/index.d.ts +9 -9
  114. package/lib/index.js +14 -14
  115. package/lib/server/brokenLinks.d.ts +4 -17
  116. package/lib/server/brokenLinks.js +67 -56
  117. package/lib/server/clientModules.d.ts +12 -0
  118. package/lib/server/clientModules.js +20 -0
  119. package/lib/server/config.d.ts +5 -2
  120. package/lib/server/config.js +29 -6
  121. package/lib/server/configValidation.d.ts +4 -4
  122. package/lib/server/configValidation.js +80 -38
  123. package/lib/server/getHostPort.d.ts +14 -0
  124. package/lib/server/getHostPort.js +79 -0
  125. package/lib/server/htmlTags.d.ts +12 -0
  126. package/lib/server/htmlTags.js +62 -0
  127. package/lib/server/i18n.d.ts +3 -13
  128. package/lib/server/i18n.js +19 -55
  129. package/lib/server/index.d.ts +28 -13
  130. package/lib/server/index.js +79 -163
  131. package/lib/server/plugins/configs.d.ts +51 -0
  132. package/lib/server/plugins/configs.js +101 -0
  133. package/lib/server/plugins/index.d.ts +9 -8
  134. package/lib/server/plugins/index.js +72 -135
  135. package/lib/server/plugins/init.d.ts +6 -5
  136. package/lib/server/plugins/init.js +44 -109
  137. package/lib/server/plugins/moduleShorthand.d.ts +9 -0
  138. package/lib/server/plugins/moduleShorthand.js +46 -0
  139. package/lib/server/plugins/pluginIds.d.ts +5 -1
  140. package/lib/server/plugins/pluginIds.js +12 -7
  141. package/lib/server/plugins/presets.d.ts +12 -0
  142. package/lib/server/plugins/presets.js +49 -0
  143. package/lib/server/plugins/routeConfig.d.ts +11 -0
  144. package/lib/server/plugins/routeConfig.js +54 -0
  145. package/lib/server/plugins/synthetic.d.ts +20 -0
  146. package/lib/server/plugins/synthetic.js +112 -0
  147. package/lib/server/routes.d.ts +39 -7
  148. package/lib/server/routes.js +185 -95
  149. package/lib/server/siteMetadata.d.ts +12 -0
  150. package/lib/server/siteMetadata.js +81 -0
  151. package/lib/server/translations/translations.d.ts +11 -14
  152. package/lib/server/translations/translations.js +36 -60
  153. package/lib/server/translations/translationsExtractor.d.ts +10 -4
  154. package/lib/server/translations/translationsExtractor.js +158 -122
  155. package/lib/server/utils.d.ts +9 -3
  156. package/lib/server/utils.js +7 -9
  157. package/lib/webpack/aliases/index.d.ts +34 -0
  158. package/lib/webpack/aliases/index.js +106 -0
  159. package/lib/webpack/base.d.ts +3 -4
  160. package/lib/webpack/base.js +45 -57
  161. package/lib/webpack/client.d.ts +3 -3
  162. package/lib/webpack/client.js +12 -19
  163. package/lib/webpack/plugins/ChunkAssetPlugin.d.ts +13 -3
  164. package/lib/webpack/plugins/ChunkAssetPlugin.js +24 -17
  165. package/lib/webpack/plugins/CleanWebpackPlugin.d.ts +6 -25
  166. package/lib/webpack/plugins/CleanWebpackPlugin.js +33 -17
  167. package/lib/webpack/plugins/LogPlugin.d.ts +1 -1
  168. package/lib/webpack/plugins/LogPlugin.js +4 -5
  169. package/lib/webpack/plugins/WaitPlugin.d.ts +3 -3
  170. package/lib/webpack/plugins/WaitPlugin.js +1 -1
  171. package/lib/webpack/server.d.ts +5 -5
  172. package/lib/webpack/server.js +16 -12
  173. package/lib/{client → webpack}/templates/index.html.template.ejs +0 -0
  174. package/lib/webpack/templates/ssr.html.template.d.ts +8 -0
  175. package/lib/{client → webpack}/templates/ssr.html.template.js +3 -2
  176. package/lib/webpack/utils.d.ts +15 -31
  177. package/lib/webpack/utils.js +61 -182
  178. package/package.json +82 -77
  179. package/bin/docusaurus.js +0 -325
  180. package/lib/.tsbuildinfo +0 -1
  181. package/lib/choosePort.js +0 -105
  182. package/lib/client/.tsbuildinfo +0 -1
  183. package/lib/client/client-lifecycles-dispatcher.d.ts +0 -12
  184. package/lib/client/client-lifecycles-dispatcher.js +0 -27
  185. package/lib/client/nprogress.css +0 -36
  186. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  187. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  188. package/lib/commands/commandUtils.d.ts +0 -3
  189. package/lib/commands/commandUtils.js +0 -21
  190. package/lib/commands/swizzle.d.ts +0 -9
  191. package/lib/commands/swizzle.js +0 -245
  192. package/lib/constants.d.ts +0 -18
  193. package/lib/constants.js +0 -23
  194. package/lib/server/client-modules/index.js +0 -14
  195. package/lib/server/duplicateRoutes.d.ts +0 -10
  196. package/lib/server/duplicateRoutes.js +0 -38
  197. package/lib/server/html-tags/htmlTags.js +0 -40
  198. package/lib/server/html-tags/index.d.ts +0 -9
  199. package/lib/server/html-tags/index.js +0 -43
  200. package/lib/server/loadSetup.d.ts +0 -9
  201. package/lib/server/loadSetup.js +0 -25
  202. package/lib/server/plugins/applyRouteTrailingSlash.d.ts +0 -9
  203. package/lib/server/plugins/applyRouteTrailingSlash.js +0 -19
  204. package/lib/server/presets/index.d.ts +0 -11
  205. package/lib/server/presets/index.js +0 -48
  206. package/lib/server/themes/alias.d.ts +0 -8
  207. package/lib/server/themes/alias.js +0 -40
  208. package/lib/server/themes/index.d.ts +0 -12
  209. package/lib/server/themes/index.js +0 -47
  210. package/lib/server/versions/__fixtures__/dummy-plugin.js +0 -0
  211. package/lib/server/versions/__fixtures__/package.json +0 -3
  212. package/lib/server/versions/__tests/index.test.js +0 -25
  213. package/lib/server/versions/index.d.ts +0 -10
  214. package/lib/server/versions/index.js +0 -50
  215. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  216. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  217. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  218. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  219. package/lib/webpack/sharedModuleAliases.d.ts +0 -10
  220. package/lib/webpack/sharedModuleAliases.js +0 -18
  221. package/tsconfig.client.json +0 -13
  222. package/tsconfig.json +0 -13
@@ -4,5 +4,5 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import { Command } from 'commander';
8
- export default function externalCommand(cli: Command, siteDir: string): Promise<void>;
7
+ import type { CommanderStatic } from 'commander';
8
+ export declare function externalCommand(cli: CommanderStatic, siteDir: string): Promise<void>;
@@ -6,20 +6,15 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- const tslib_1 = require("tslib");
9
+ exports.externalCommand = void 0;
10
10
  const server_1 = require("../server");
11
- const init_1 = tslib_1.__importDefault(require("../server/plugins/init"));
11
+ const init_1 = require("../server/plugins/init");
12
12
  async function externalCommand(cli, siteDir) {
13
- const context = await server_1.loadContext(siteDir);
14
- const pluginConfigs = server_1.loadPluginConfigs(context);
15
- const plugins = init_1.default({ pluginConfigs, context });
13
+ const context = await (0, server_1.loadContext)({ siteDir });
14
+ const plugins = await (0, init_1.initPlugins)(context);
16
15
  // Plugin Lifecycle - extendCli.
17
16
  plugins.forEach((plugin) => {
18
- const { extendCli } = plugin;
19
- if (!extendCli) {
20
- return;
21
- }
22
- extendCli(cli);
17
+ plugin.extendCli?.(cli);
23
18
  });
24
19
  }
25
- exports.default = externalCommand;
20
+ exports.externalCommand = externalCommand;
@@ -4,5 +4,11 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import { ServeCLIOptions } from '@docusaurus/types';
8
- export default function serve(siteDir: string, cliOptions: ServeCLIOptions): Promise<void>;
7
+ import { type HostPortOptions } from '../server/getHostPort';
8
+ import type { LoadContextOptions } from '../server';
9
+ export declare type ServeCLIOptions = HostPortOptions & Pick<LoadContextOptions, 'config'> & {
10
+ dir?: string;
11
+ build?: boolean;
12
+ open?: boolean;
13
+ };
14
+ export declare function serve(siteDir: string, cliOptions: Partial<ServeCLIOptions>): Promise<void>;
@@ -6,60 +6,59 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.serve = void 0;
9
10
  const tslib_1 = require("tslib");
10
11
  const http_1 = tslib_1.__importDefault(require("http"));
11
- const serve_handler_1 = tslib_1.__importDefault(require("serve-handler"));
12
- const boxen_1 = tslib_1.__importDefault(require("boxen"));
13
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
14
12
  const path_1 = tslib_1.__importDefault(require("path"));
15
- const server_1 = require("../server");
16
- const build_1 = tslib_1.__importDefault(require("./build"));
17
- const commandUtils_1 = require("./commandUtils");
13
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
14
+ const utils_1 = require("@docusaurus/utils");
15
+ const serve_handler_1 = tslib_1.__importDefault(require("serve-handler"));
16
+ const openBrowser_1 = tslib_1.__importDefault(require("react-dev-utils/openBrowser"));
17
+ const config_1 = require("../server/config");
18
+ const build_1 = require("./build");
19
+ const getHostPort_1 = require("../server/getHostPort");
18
20
  async function serve(siteDir, cliOptions) {
19
- let dir = path_1.default.isAbsolute(cliOptions.dir)
20
- ? cliOptions.dir
21
- : path_1.default.join(siteDir, cliOptions.dir);
21
+ const buildDir = cliOptions.dir ?? utils_1.DEFAULT_BUILD_DIR_NAME;
22
+ let dir = path_1.default.resolve(siteDir, buildDir);
22
23
  if (cliOptions.build) {
23
- dir = await build_1.default(siteDir, {
24
+ dir = await (0, build_1.build)(siteDir, {
24
25
  config: cliOptions.config,
25
26
  outDir: dir,
26
27
  }, false);
27
28
  }
28
- const host = commandUtils_1.getCLIOptionHost(cliOptions.host);
29
- const port = await commandUtils_1.getCLIOptionPort(cliOptions.port, host);
29
+ const { host, port } = await (0, getHostPort_1.getHostPort)(cliOptions);
30
30
  if (port === null) {
31
31
  process.exit();
32
32
  }
33
- const { siteConfig: { baseUrl, trailingSlash }, } = await server_1.loadSiteConfig({
33
+ const { siteConfig: { baseUrl, trailingSlash }, } = await (0, config_1.loadSiteConfig)({
34
34
  siteDir,
35
35
  customConfigFilePath: cliOptions.config,
36
36
  });
37
- const servingUrl = `http://${cliOptions.host}:${cliOptions.port}`;
37
+ const servingUrl = `http://${host}:${port}`;
38
38
  const server = http_1.default.createServer((req, res) => {
39
- var _a, _b;
40
39
  // Automatically redirect requests to /baseUrl/
41
- if (!((_a = req.url) === null || _a === void 0 ? void 0 : _a.startsWith(baseUrl))) {
40
+ if (!req.url?.startsWith(baseUrl)) {
42
41
  res.writeHead(302, {
43
42
  Location: baseUrl,
44
43
  });
45
44
  res.end();
46
45
  return;
47
46
  }
48
- // Remove baseUrl before calling serveHandler
49
- // Reason: /baseUrl/ should serve /build/index.html, not /build/baseUrl/index.html (does not exist)
50
- req.url = (_b = req.url) === null || _b === void 0 ? void 0 : _b.replace(baseUrl, '/');
51
- serve_handler_1.default(req, res, {
47
+ // Remove baseUrl before calling serveHandler, because /baseUrl/ should
48
+ // serve /build/index.html, not /build/baseUrl/index.html (does not exist)
49
+ req.url = req.url.replace(baseUrl, '/');
50
+ (0, serve_handler_1.default)(req, res, {
52
51
  cleanUrls: true,
53
52
  public: dir,
54
53
  trailingSlash,
54
+ directoryListing: false,
55
55
  });
56
56
  });
57
- console.log(boxen_1.default(chalk_1.default.green(`Serving "${cliOptions.dir}" directory at "${servingUrl + baseUrl}".`), {
58
- borderColor: 'green',
59
- padding: 1,
60
- margin: 1,
61
- align: 'center',
62
- }));
57
+ const url = servingUrl + baseUrl;
58
+ logger_1.default.success `Serving path=${buildDir} directory at: url=${url}`;
63
59
  server.listen(port);
60
+ if (cliOptions.open && !process.env.CI) {
61
+ (0, openBrowser_1.default)(url);
62
+ }
64
63
  }
65
- exports.default = serve;
64
+ exports.serve = serve;
@@ -4,5 +4,12 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import { StartCLIOptions } from '@docusaurus/types';
8
- export default function start(siteDir: string, cliOptions: Partial<StartCLIOptions>): Promise<void>;
7
+ import { type LoadContextOptions } from '../server';
8
+ import { type HostPortOptions } from '../server/getHostPort';
9
+ export declare type StartCLIOptions = HostPortOptions & Pick<LoadContextOptions, 'locale' | 'config'> & {
10
+ hotOnly?: boolean;
11
+ open?: boolean;
12
+ poll?: boolean | number;
13
+ minify?: boolean;
14
+ };
15
+ export declare function start(siteDir: string, cliOptions: Partial<StartCLIOptions>): Promise<void>;
@@ -6,99 +6,106 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.start = void 0;
9
10
  const tslib_1 = require("tslib");
11
+ const path_1 = tslib_1.__importDefault(require("path"));
12
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
13
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
10
14
  const utils_1 = require("@docusaurus/utils");
11
- const chalk = require("chalk");
12
15
  const chokidar_1 = tslib_1.__importDefault(require("chokidar"));
13
- const express_1 = tslib_1.__importDefault(require("express"));
14
16
  const html_webpack_plugin_1 = tslib_1.__importDefault(require("html-webpack-plugin"));
15
- const path_1 = tslib_1.__importDefault(require("path"));
16
- const lodash_1 = require("lodash");
17
17
  const openBrowser_1 = tslib_1.__importDefault(require("react-dev-utils/openBrowser"));
18
18
  const WebpackDevServerUtils_1 = require("react-dev-utils/WebpackDevServerUtils");
19
- const errorOverlayMiddleware_1 = tslib_1.__importDefault(require("react-dev-utils/errorOverlayMiddleware"));
20
- // import evalSourceMapMiddleware from 'react-dev-utils/evalSourceMapMiddleware';
21
- const evalSourceMapMiddleware_1 = tslib_1.__importDefault(require("../webpack/react-dev-utils-webpack5/evalSourceMapMiddleware"));
19
+ const evalSourceMapMiddleware_1 = tslib_1.__importDefault(require("react-dev-utils/evalSourceMapMiddleware"));
22
20
  const webpack_1 = tslib_1.__importDefault(require("webpack"));
23
21
  const webpack_dev_server_1 = tslib_1.__importDefault(require("webpack-dev-server"));
24
22
  const webpack_merge_1 = tslib_1.__importDefault(require("webpack-merge"));
25
- const HotModuleReplacementPlugin_1 = tslib_1.__importDefault(require("webpack/lib/HotModuleReplacementPlugin"));
26
23
  const server_1 = require("../server");
27
- const constants_1 = require("../constants");
28
24
  const client_1 = tslib_1.__importDefault(require("../webpack/client"));
29
25
  const utils_2 = require("../webpack/utils");
30
- const commandUtils_1 = require("./commandUtils");
26
+ const getHostPort_1 = require("../server/getHostPort");
31
27
  const translations_1 = require("../server/translations/translations");
32
28
  async function start(siteDir, cliOptions) {
33
29
  process.env.NODE_ENV = 'development';
34
30
  process.env.BABEL_ENV = 'development';
35
- console.log(chalk.blue('Starting the development server...'));
31
+ logger_1.default.info('Starting the development server...');
36
32
  function loadSite() {
37
- return server_1.load(siteDir, {
38
- customConfigFilePath: cliOptions.config,
33
+ return (0, server_1.load)({
34
+ siteDir,
35
+ config: cliOptions.config,
39
36
  locale: cliOptions.locale,
40
- localizePath: undefined, // should this be configurable?
37
+ localizePath: undefined, // Should this be configurable?
41
38
  });
42
39
  }
43
40
  // Process all related files as a prop.
44
41
  const props = await loadSite();
45
42
  const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
46
- const host = commandUtils_1.getCLIOptionHost(cliOptions.host);
47
- const port = await commandUtils_1.getCLIOptionPort(cliOptions.port, host);
43
+ const { host, port } = await (0, getHostPort_1.getHostPort)(cliOptions);
48
44
  if (port === null) {
49
45
  process.exit();
50
46
  }
51
47
  const { baseUrl, headTags, preBodyTags, postBodyTags } = props;
52
- const urls = WebpackDevServerUtils_1.prepareUrls(protocol, host, port);
53
- const openUrl = utils_1.normalizeUrl([urls.localUrlForBrowser, baseUrl]);
54
- console.log(chalk.cyanBright(`Docusaurus website is running at "${openUrl}".`));
48
+ const urls = (0, WebpackDevServerUtils_1.prepareUrls)(protocol, host, port);
49
+ const openUrl = (0, utils_1.normalizeUrl)([urls.localUrlForBrowser, baseUrl]);
50
+ logger_1.default.success `Docusaurus website is running at: url=${openUrl}`;
55
51
  // Reload files processing.
56
- const reload = lodash_1.debounce(() => {
52
+ const reload = lodash_1.default.debounce(() => {
57
53
  loadSite()
58
54
  .then(({ baseUrl: newBaseUrl }) => {
59
- const newOpenUrl = utils_1.normalizeUrl([urls.localUrlForBrowser, newBaseUrl]);
55
+ const newOpenUrl = (0, utils_1.normalizeUrl)([urls.localUrlForBrowser, newBaseUrl]);
60
56
  if (newOpenUrl !== openUrl) {
61
- console.log(chalk.cyanBright(`Docusaurus website is running at "${newOpenUrl}".`));
57
+ logger_1.default.success `Docusaurus website is running at: url=${newOpenUrl}`;
62
58
  }
63
59
  })
64
60
  .catch((err) => {
65
- console.error(chalk.red(err.stack));
61
+ logger_1.default.error(err.stack);
66
62
  });
67
63
  }, 500);
68
- const { siteConfig, plugins = [] } = props;
64
+ const { siteConfig, plugins } = props;
69
65
  const normalizeToSiteDir = (filepath) => {
70
66
  if (filepath && path_1.default.isAbsolute(filepath)) {
71
- return utils_1.posixPath(path_1.default.relative(siteDir, filepath));
67
+ return (0, utils_1.posixPath)(path_1.default.relative(siteDir, filepath));
72
68
  }
73
- return utils_1.posixPath(filepath);
69
+ return (0, utils_1.posixPath)(filepath);
74
70
  };
75
- const pluginPaths = []
76
- .concat(...plugins
77
- .map((plugin) => { var _a, _b; return (_b = (_a = plugin.getPathsToWatch) === null || _a === void 0 ? void 0 : _a.call(plugin)) !== null && _b !== void 0 ? _b : []; })
78
- .filter(Boolean))
71
+ const pluginPaths = plugins
72
+ .flatMap((plugin) => plugin.getPathsToWatch?.() ?? [])
73
+ .filter(Boolean)
79
74
  .map(normalizeToSiteDir);
80
75
  const pathsToWatch = [
81
76
  ...pluginPaths,
82
77
  props.siteConfigPath,
83
- translations_1.getTranslationsLocaleDirPath({
78
+ (0, translations_1.getTranslationsLocaleDirPath)({
84
79
  siteDir,
85
80
  locale: props.i18n.currentLocale,
86
81
  }),
87
82
  ];
88
- const fsWatcher = chokidar_1.default.watch(pathsToWatch, {
89
- cwd: siteDir,
90
- ignoreInitial: true,
83
+ const pollingOptions = {
91
84
  usePolling: !!cliOptions.poll,
92
85
  interval: Number.isInteger(cliOptions.poll)
93
86
  ? cliOptions.poll
94
87
  : undefined,
88
+ };
89
+ const httpsConfig = await (0, utils_2.getHttpsConfig)();
90
+ const fsWatcher = chokidar_1.default.watch(pathsToWatch, {
91
+ cwd: siteDir,
92
+ ignoreInitial: true,
93
+ ...{ pollingOptions },
95
94
  });
96
95
  ['add', 'change', 'unlink', 'addDir', 'unlinkDir'].forEach((event) => fsWatcher.on(event, reload));
97
- let config = webpack_merge_1.default(client_1.default(props), {
96
+ let config = (0, webpack_merge_1.default)(await (0, client_1.default)(props, cliOptions.minify), {
97
+ watchOptions: {
98
+ ignored: /node_modules\/(?!@docusaurus)/,
99
+ poll: cliOptions.poll,
100
+ },
101
+ infrastructureLogging: {
102
+ // Reduce log verbosity, see https://github.com/facebook/docusaurus/pull/5420#issuecomment-906613105
103
+ level: 'warn',
104
+ },
98
105
  plugins: [
99
106
  // Generates an `index.html` file with the <script> injected.
100
107
  new html_webpack_plugin_1.default({
101
- template: path_1.default.resolve(__dirname, '../client/templates/index.html.template.ejs'),
108
+ template: path_1.default.join(__dirname, '../webpack/templates/index.html.template.ejs'),
102
109
  // So we can define the position where the scripts are injected.
103
110
  inject: false,
104
111
  filename: 'index.html',
@@ -107,86 +114,93 @@ async function start(siteDir, cliOptions) {
107
114
  preBodyTags,
108
115
  postBodyTags,
109
116
  }),
110
- // This is necessary to emit hot updates for webpack-dev-server.
111
- new HotModuleReplacementPlugin_1.default(),
112
117
  ],
113
118
  });
114
119
  // Plugin Lifecycle - configureWebpack and configurePostCss.
115
120
  plugins.forEach((plugin) => {
116
- var _a;
117
121
  const { configureWebpack, configurePostCss } = plugin;
118
122
  if (configurePostCss) {
119
- config = utils_2.applyConfigurePostCss(configurePostCss, config);
123
+ config = (0, utils_2.applyConfigurePostCss)(configurePostCss.bind(plugin), config);
120
124
  }
121
125
  if (configureWebpack) {
122
- config = utils_2.applyConfigureWebpack(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`. // TODO remove this implicit api: inject in callback instead
123
- config, false, (_a = props.siteConfig.webpack) === null || _a === void 0 ? void 0 : _a.jsLoader, plugin.content);
126
+ config = (0, utils_2.applyConfigureWebpack)(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`.
127
+ config, false, props.siteConfig.webpack?.jsLoader, plugin.content);
124
128
  }
125
129
  });
126
- // https://webpack.js.org/configuration/dev-server
127
- const devServerConfig = {
128
- ...{
129
- compress: true,
130
- clientLogLevel: 'error',
131
- hot: true,
132
- hotOnly: cliOptions.hotOnly,
133
- // Use 'ws' instead of 'sockjs-node' on server since we're using native
134
- // websockets in `webpackHotDevClient`.
135
- transportMode: 'ws',
136
- // Prevent a WS client from getting injected as we're already including
137
- // `webpackHotDevClient`.
138
- injectClient: false,
139
- quiet: true,
140
- https: utils_2.getHttpsConfig(),
141
- headers: {
142
- 'access-control-allow-origin': '*',
143
- },
144
- publicPath: baseUrl,
145
- watchOptions: {
146
- ignored: /node_modules/,
147
- poll: cliOptions.poll,
148
- },
149
- historyApiFallback: {
150
- rewrites: [{ from: /\/*/, to: baseUrl }],
151
- },
152
- disableHostCheck: true,
153
- // Disable overlay on browser since we use CRA's overlay error reporting.
154
- overlay: false,
155
- host,
156
- before: (app, server) => {
157
- app.use(baseUrl, express_1.default.static(path_1.default.resolve(siteDir, constants_1.STATIC_DIR_NAME)));
158
- // This lets us fetch source contents from webpack for the error overlay.
159
- app.use(evalSourceMapMiddleware_1.default(server));
160
- // This lets us open files from the runtime error overlay.
161
- app.use(errorOverlayMiddleware_1.default());
162
- },
163
- },
164
- };
165
- const compiler = webpack_1.default(config);
130
+ const compiler = (0, webpack_1.default)(config);
166
131
  if (process.env.E2E_TEST) {
167
132
  compiler.hooks.done.tap('done', (stats) => {
168
133
  if (stats.hasErrors()) {
169
- console.log('E2E_TEST: Project has compiler errors.');
134
+ logger_1.default.error('E2E_TEST: Project has compiler errors.');
170
135
  process.exit(1);
171
136
  }
172
- console.log('E2E_TEST: Project can compile.');
137
+ logger_1.default.success('E2E_TEST: Project can compile.');
173
138
  process.exit(0);
174
139
  });
175
140
  }
176
- const devServer = new webpack_dev_server_1.default(compiler, devServerConfig);
177
- devServer.listen(port, host, (err) => {
178
- if (err) {
179
- console.log(err);
180
- }
141
+ // https://webpack.js.org/configuration/dev-server
142
+ const defaultDevServerConfig = {
143
+ hot: cliOptions.hotOnly ? 'only' : true,
144
+ liveReload: false,
145
+ client: {
146
+ progress: true,
147
+ overlay: {
148
+ warnings: false,
149
+ errors: true,
150
+ },
151
+ },
152
+ headers: {
153
+ 'access-control-allow-origin': '*',
154
+ },
155
+ devMiddleware: {
156
+ publicPath: baseUrl,
157
+ // Reduce log verbosity, see https://github.com/facebook/docusaurus/pull/5420#issuecomment-906613105
158
+ stats: 'summary',
159
+ },
160
+ static: siteConfig.staticDirectories.map((dir) => ({
161
+ publicPath: baseUrl,
162
+ directory: path_1.default.resolve(siteDir, dir),
163
+ watch: {
164
+ // Useful options for our own monorepo using symlinks!
165
+ // See https://github.com/webpack/webpack/issues/11612#issuecomment-879259806
166
+ followSymlinks: true,
167
+ ignored: /node_modules\/(?!@docusaurus)/,
168
+ ...{ pollingOptions },
169
+ },
170
+ })),
171
+ ...(httpsConfig && {
172
+ server: typeof httpsConfig === 'object'
173
+ ? {
174
+ type: 'https',
175
+ options: httpsConfig,
176
+ }
177
+ : 'https',
178
+ }),
179
+ historyApiFallback: {
180
+ rewrites: [{ from: /\/*/, to: baseUrl }],
181
+ },
182
+ allowedHosts: 'all',
183
+ host,
184
+ port,
185
+ setupMiddlewares: (middlewares, devServer) => {
186
+ // This lets us fetch source contents from webpack for the error overlay.
187
+ middlewares.unshift((0, evalSourceMapMiddleware_1.default)(devServer));
188
+ return middlewares;
189
+ },
190
+ };
191
+ // Allow plugin authors to customize/override devServer config
192
+ const devServerConfig = (0, webpack_merge_1.default)([defaultDevServerConfig, config.devServer].filter(Boolean));
193
+ const devServer = new webpack_dev_server_1.default(devServerConfig, compiler);
194
+ devServer.startCallback(() => {
181
195
  if (cliOptions.open) {
182
- openBrowser_1.default(openUrl);
196
+ (0, openBrowser_1.default)(openUrl);
183
197
  }
184
198
  });
185
199
  ['SIGINT', 'SIGTERM'].forEach((sig) => {
186
200
  process.on(sig, () => {
187
- devServer.close();
201
+ devServer.stop();
188
202
  process.exit();
189
203
  });
190
204
  });
191
205
  }
192
- exports.default = start;
206
+ exports.start = start;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import type { SwizzleAction, SwizzleComponentConfig } from '@docusaurus/types';
8
+ import type { SwizzleCLIOptions } from './common';
9
+ export declare const SwizzleActions: SwizzleAction[];
10
+ export declare function getAction(componentConfig: SwizzleComponentConfig, options: Pick<SwizzleCLIOptions, 'wrap' | 'eject'>): Promise<SwizzleAction>;
11
+ export declare type ActionParams = {
12
+ siteDir: string;
13
+ themePath: string;
14
+ componentName: string;
15
+ };
16
+ export declare type ActionResult = {
17
+ createdFiles: string[];
18
+ };
19
+ export declare function eject({ siteDir, themePath, componentName, }: ActionParams): Promise<ActionResult>;
20
+ export declare function wrap({ siteDir, themePath, componentName: themeComponentName, typescript, importType, }: ActionParams & {
21
+ typescript: boolean;
22
+ importType?: 'original' | 'init';
23
+ }): Promise<ActionResult>;
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.wrap = exports.eject = exports.getAction = exports.SwizzleActions = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
12
+ const path_1 = tslib_1.__importDefault(require("path"));
13
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
14
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
15
+ const utils_1 = require("@docusaurus/utils");
16
+ const prompts_1 = require("./prompts");
17
+ exports.SwizzleActions = ['wrap', 'eject'];
18
+ async function getAction(componentConfig, options) {
19
+ if (options.wrap) {
20
+ return 'wrap';
21
+ }
22
+ if (options.eject) {
23
+ return 'eject';
24
+ }
25
+ return (0, prompts_1.askSwizzleAction)(componentConfig);
26
+ }
27
+ exports.getAction = getAction;
28
+ async function isDir(dirPath) {
29
+ return ((await fs_extra_1.default.pathExists(dirPath)) && (await fs_extra_1.default.stat(dirPath)).isDirectory());
30
+ }
31
+ async function eject({ siteDir, themePath, componentName, }) {
32
+ const fromPath = path_1.default.join(themePath, componentName);
33
+ const isDirectory = await isDir(fromPath);
34
+ const globPattern = isDirectory
35
+ ? // Do we really want to copy all components?
36
+ path_1.default.join(fromPath, '*')
37
+ : `${fromPath}.*`;
38
+ const globPatternPosix = (0, utils_1.posixPath)(globPattern);
39
+ const filesToCopy = await (0, utils_1.Globby)(globPatternPosix, {
40
+ ignore: ['**/*.{story,stories,test,tests}.{js,jsx,ts,tsx}'],
41
+ });
42
+ if (filesToCopy.length === 0) {
43
+ // This should never happen
44
+ throw new Error(logger_1.default.interpolate `No files to copy from path=${fromPath} with glob code=${globPatternPosix}`);
45
+ }
46
+ const toPath = path_1.default.join(siteDir, utils_1.THEME_PATH);
47
+ await fs_extra_1.default.ensureDir(toPath);
48
+ const createdFiles = await Promise.all(filesToCopy.map(async (sourceFile) => {
49
+ const targetFile = path_1.default.join(toPath, path_1.default.relative(themePath, sourceFile));
50
+ try {
51
+ const fileContents = await fs_extra_1.default.readFile(sourceFile, 'utf-8');
52
+ await fs_extra_1.default.outputFile(targetFile, fileContents.trimStart().replace(/^\/\*.+?\*\/\s*/ms, ''));
53
+ }
54
+ catch (err) {
55
+ logger_1.default.error `Could not copy file from path=${sourceFile} to path=${targetFile}`;
56
+ throw err;
57
+ }
58
+ return targetFile;
59
+ }));
60
+ return { createdFiles };
61
+ }
62
+ exports.eject = eject;
63
+ async function wrap({ siteDir, themePath, componentName: themeComponentName, typescript, importType = 'original', }) {
64
+ const isDirectory = await isDir(path_1.default.join(themePath, themeComponentName));
65
+ // Top/Parent/ComponentName => ComponentName
66
+ const componentName = lodash_1.default.last(themeComponentName.split('/'));
67
+ const wrapperComponentName = `${componentName}Wrapper`;
68
+ const wrapperFileName = `${themeComponentName}${isDirectory ? '/index' : ''}${typescript ? '.tsx' : '.js'}`;
69
+ await fs_extra_1.default.ensureDir(path_1.default.resolve(siteDir, utils_1.THEME_PATH));
70
+ const toPath = path_1.default.resolve(siteDir, utils_1.THEME_PATH, wrapperFileName);
71
+ const content = typescript
72
+ ? `import React, {ComponentProps} from 'react';
73
+ import ${componentName} from '@theme-${importType}/${themeComponentName}';
74
+ import type ${componentName}Type from '@theme/${themeComponentName}';
75
+
76
+ type Props = ComponentProps<typeof ${componentName}Type>;
77
+
78
+ export default function ${wrapperComponentName}(props: Props): JSX.Element {
79
+ return (
80
+ <>
81
+ <${componentName} {...props} />
82
+ </>
83
+ );
84
+ }
85
+ `
86
+ : `import React from 'react';
87
+ import ${componentName} from '@theme-${importType}/${themeComponentName}';
88
+
89
+ export default function ${wrapperComponentName}(props) {
90
+ return (
91
+ <>
92
+ <${componentName} {...props} />
93
+ </>
94
+ );
95
+ }
96
+ `;
97
+ await fs_extra_1.default.outputFile(toPath, content);
98
+ return { createdFiles: [toPath] };
99
+ }
100
+ exports.wrap = wrap;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import type { NormalizedPluginConfig } from '../../server/plugins/configs';
8
+ import type { InitializedPlugin, SwizzleAction, SwizzleActionStatus } from '@docusaurus/types';
9
+ export declare const SwizzleActions: SwizzleAction[];
10
+ export declare const SwizzleActionsStatuses: SwizzleActionStatus[];
11
+ export declare const PartiallySafeHint: string;
12
+ export declare function actionStatusLabel(status: SwizzleActionStatus): string;
13
+ export declare function actionStatusColor(status: SwizzleActionStatus, str: string): string;
14
+ export declare function actionStatusSuffix(status: SwizzleActionStatus, options?: {
15
+ partiallySafe?: boolean;
16
+ }): string;
17
+ export declare type SwizzlePlugin = {
18
+ instance: InitializedPlugin;
19
+ plugin: NormalizedPluginConfig;
20
+ };
21
+ export declare type SwizzleContext = {
22
+ plugins: SwizzlePlugin[];
23
+ };
24
+ export declare type SwizzleCLIOptions = {
25
+ typescript: boolean;
26
+ danger: boolean;
27
+ list: boolean;
28
+ wrap: boolean;
29
+ eject: boolean;
30
+ };
31
+ export declare function normalizeOptions(options: Partial<SwizzleCLIOptions>): SwizzleCLIOptions;
32
+ export declare function findStringIgnoringCase(str: string, values: string[]): string | undefined;
33
+ export declare function findClosestValue(str: string, values: string[], maxLevenshtein?: number): string | undefined;