@docusaurus/core 2.0.0-beta.fbdeefcac → 2.0.0-rc.1

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 (224) hide show
  1. package/README.md +1 -0
  2. package/bin/beforeCli.mjs +140 -0
  3. package/bin/{docusaurus.js → docusaurus.mjs} +79 -118
  4. package/lib/babel/preset.d.ts +8 -3
  5. package/lib/babel/preset.js +10 -8
  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} +25 -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 +47 -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 +37 -0
  32. package/lib/client/exports/ExecutionEnvironment.js +7 -8
  33. package/lib/client/exports/Head.d.ts +2 -3
  34. package/lib/client/exports/Head.js +3 -4
  35. package/lib/client/exports/Interpolate.d.ts +2 -2
  36. package/lib/client/exports/Interpolate.js +20 -49
  37. package/lib/client/exports/Link.d.ts +4 -10
  38. package/lib/client/exports/Link.js +38 -38
  39. package/lib/client/exports/Translate.d.ts +1 -1
  40. package/lib/client/exports/Translate.js +14 -9
  41. package/lib/client/exports/constants.js +1 -11
  42. package/lib/client/exports/isInternalUrl.js +1 -1
  43. package/lib/client/exports/renderRoutes.d.ts +1 -2
  44. package/lib/client/exports/renderRoutes.js +1 -2
  45. package/lib/client/exports/router.d.ts +1 -1
  46. package/lib/client/exports/router.js +1 -1
  47. package/lib/client/exports/useBaseUrl.js +11 -14
  48. package/lib/client/exports/useDocusaurusContext.d.ts +2 -3
  49. package/lib/client/exports/useDocusaurusContext.js +3 -9
  50. package/lib/client/exports/useGlobalData.d.ts +4 -3
  51. package/lib/client/exports/useGlobalData.js +6 -13
  52. package/lib/{server/versions/__tests/index.test.d.ts → client/exports/useIsBrowser.d.ts} +1 -1
  53. package/lib/client/exports/useIsBrowser.js +11 -0
  54. package/lib/client/exports/useRouteContext.d.ts +8 -0
  55. package/lib/client/exports/useRouteContext.js +15 -0
  56. package/lib/client/flat.d.ts +12 -2
  57. package/lib/client/flat.js +19 -15
  58. package/lib/client/normalizeLocation.d.ts +2 -5
  59. package/lib/client/normalizeLocation.js +14 -10
  60. package/lib/client/prefetch.d.ts +1 -2
  61. package/lib/client/prefetch.js +12 -32
  62. package/lib/client/preload.d.ts +3 -4
  63. package/lib/client/preload.js +5 -12
  64. package/lib/client/routeContext.d.ts +13 -0
  65. package/lib/client/routeContext.js +31 -0
  66. package/lib/client/serverEntry.d.ts +10 -0
  67. package/lib/client/serverEntry.js +108 -146
  68. package/lib/client/theme-fallback/Error/index.d.ts +10 -0
  69. package/lib/client/theme-fallback/Error/index.js +45 -0
  70. package/lib/client/theme-fallback/Layout/index.d.ts +10 -0
  71. package/lib/client/theme-fallback/Layout/index.js +2 -26
  72. package/lib/client/theme-fallback/Loading/index.d.ts +9 -0
  73. package/lib/client/theme-fallback/Loading/index.js +50 -116
  74. package/lib/{server/html-tags/htmlTags.d.ts → client/theme-fallback/NotFound/index.d.ts} +2 -1
  75. package/lib/client/theme-fallback/NotFound/index.js +19 -18
  76. package/lib/client/theme-fallback/Root/index.d.ts +10 -0
  77. package/lib/client/theme-fallback/Root/index.js +2 -6
  78. package/lib/client/{exports/context.js → theme-fallback/SiteMetadata/index.d.ts} +2 -2
  79. package/lib/client/theme-fallback/SiteMetadata/index.js +10 -0
  80. package/lib/commands/build.d.ts +6 -2
  81. package/lib/commands/build.js +81 -64
  82. package/lib/commands/clear.d.ts +7 -1
  83. package/lib/commands/clear.js +34 -21
  84. package/lib/commands/deploy.d.ts +5 -2
  85. package/lib/commands/deploy.js +94 -81
  86. package/lib/commands/external.d.ts +2 -2
  87. package/lib/commands/external.js +9 -11
  88. package/lib/commands/serve.d.ts +8 -2
  89. package/lib/commands/serve.js +29 -28
  90. package/lib/commands/start.d.ts +9 -2
  91. package/lib/commands/start.js +109 -101
  92. package/lib/commands/swizzle/actions.d.ts +23 -0
  93. package/lib/commands/swizzle/actions.js +106 -0
  94. package/lib/commands/swizzle/common.d.ts +33 -0
  95. package/lib/commands/swizzle/common.js +56 -0
  96. package/lib/commands/swizzle/components.d.ts +29 -0
  97. package/lib/commands/swizzle/components.js +200 -0
  98. package/lib/commands/swizzle/config.d.ts +10 -0
  99. package/lib/commands/swizzle/config.js +84 -0
  100. package/lib/{server/client-modules/index.d.ts → commands/swizzle/context.d.ts} +2 -2
  101. package/lib/commands/swizzle/context.js +24 -0
  102. package/lib/commands/swizzle/index.d.ts +8 -0
  103. package/lib/commands/swizzle/index.js +119 -0
  104. package/lib/commands/swizzle/prompts.d.ts +12 -0
  105. package/lib/commands/swizzle/prompts.js +110 -0
  106. package/lib/{client/exports/context.d.ts → commands/swizzle/tables.d.ts} +3 -4
  107. package/lib/commands/swizzle/tables.js +113 -0
  108. package/lib/commands/swizzle/themes.d.ts +20 -0
  109. package/lib/commands/swizzle/themes.js +106 -0
  110. package/lib/commands/writeHeadingIds.d.ts +2 -6
  111. package/lib/commands/writeHeadingIds.js +22 -81
  112. package/lib/commands/writeTranslations.d.ts +4 -5
  113. package/lib/commands/writeTranslations.js +46 -25
  114. package/lib/index.d.ts +9 -9
  115. package/lib/index.js +14 -14
  116. package/lib/server/brokenLinks.d.ts +4 -17
  117. package/lib/server/brokenLinks.js +67 -56
  118. package/lib/server/clientModules.d.ts +12 -0
  119. package/lib/server/clientModules.js +20 -0
  120. package/lib/server/config.d.ts +5 -2
  121. package/lib/server/config.js +29 -6
  122. package/lib/server/configValidation.d.ts +4 -4
  123. package/lib/server/configValidation.js +86 -41
  124. package/lib/server/getHostPort.d.ts +14 -0
  125. package/lib/server/getHostPort.js +79 -0
  126. package/lib/server/htmlTags.d.ts +12 -0
  127. package/lib/server/htmlTags.js +62 -0
  128. package/lib/server/i18n.d.ts +3 -13
  129. package/lib/server/i18n.js +21 -55
  130. package/lib/server/index.d.ts +28 -13
  131. package/lib/server/index.js +83 -165
  132. package/lib/server/plugins/configs.d.ts +51 -0
  133. package/lib/server/plugins/configs.js +101 -0
  134. package/lib/server/plugins/index.d.ts +9 -8
  135. package/lib/server/plugins/index.js +73 -137
  136. package/lib/server/plugins/init.d.ts +6 -5
  137. package/lib/server/plugins/init.js +44 -109
  138. package/lib/server/plugins/moduleShorthand.d.ts +9 -0
  139. package/lib/server/plugins/moduleShorthand.js +46 -0
  140. package/lib/server/plugins/pluginIds.d.ts +5 -1
  141. package/lib/server/plugins/pluginIds.js +12 -7
  142. package/lib/server/plugins/presets.d.ts +12 -0
  143. package/lib/server/plugins/presets.js +49 -0
  144. package/lib/server/plugins/routeConfig.d.ts +11 -0
  145. package/lib/server/plugins/routeConfig.js +54 -0
  146. package/lib/server/plugins/synthetic.d.ts +20 -0
  147. package/lib/server/plugins/synthetic.js +111 -0
  148. package/lib/server/routes.d.ts +39 -7
  149. package/lib/server/routes.js +182 -95
  150. package/lib/server/siteMetadata.d.ts +12 -0
  151. package/lib/server/siteMetadata.js +81 -0
  152. package/lib/server/translations/translations.d.ts +14 -19
  153. package/lib/server/translations/translations.js +40 -72
  154. package/lib/server/translations/translationsExtractor.d.ts +10 -4
  155. package/lib/server/translations/translationsExtractor.js +158 -122
  156. package/lib/server/utils.d.ts +9 -3
  157. package/lib/server/utils.js +7 -9
  158. package/lib/webpack/aliases/index.d.ts +34 -0
  159. package/lib/webpack/aliases/index.js +106 -0
  160. package/lib/webpack/base.d.ts +3 -4
  161. package/lib/webpack/base.js +45 -57
  162. package/lib/webpack/client.d.ts +3 -3
  163. package/lib/webpack/client.js +12 -19
  164. package/lib/webpack/plugins/ChunkAssetPlugin.d.ts +13 -3
  165. package/lib/webpack/plugins/ChunkAssetPlugin.js +24 -17
  166. package/lib/webpack/plugins/CleanWebpackPlugin.d.ts +6 -25
  167. package/lib/webpack/plugins/CleanWebpackPlugin.js +33 -17
  168. package/lib/webpack/plugins/LogPlugin.d.ts +1 -1
  169. package/lib/webpack/plugins/LogPlugin.js +4 -5
  170. package/lib/webpack/plugins/WaitPlugin.d.ts +3 -3
  171. package/lib/webpack/plugins/WaitPlugin.js +1 -1
  172. package/lib/webpack/server.d.ts +5 -5
  173. package/lib/webpack/server.js +21 -12
  174. package/lib/{client → webpack}/templates/index.html.template.ejs +0 -0
  175. package/lib/webpack/templates/ssr.html.template.d.ts +8 -0
  176. package/lib/{client → webpack}/templates/ssr.html.template.js +3 -2
  177. package/lib/webpack/utils.d.ts +15 -31
  178. package/lib/webpack/utils.js +61 -182
  179. package/package.json +81 -77
  180. package/bin/beforeCli.js +0 -100
  181. package/lib/.tsbuildinfo +0 -1
  182. package/lib/choosePort.js +0 -105
  183. package/lib/client/.eslintrc.js +0 -29
  184. package/lib/client/.tsbuildinfo +0 -1
  185. package/lib/client/client-lifecycles-dispatcher.d.ts +0 -12
  186. package/lib/client/client-lifecycles-dispatcher.js +0 -27
  187. package/lib/client/nprogress.css +0 -36
  188. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  189. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  190. package/lib/commands/commandUtils.d.ts +0 -3
  191. package/lib/commands/commandUtils.js +0 -21
  192. package/lib/commands/swizzle.d.ts +0 -9
  193. package/lib/commands/swizzle.js +0 -245
  194. package/lib/constants.d.ts +0 -18
  195. package/lib/constants.js +0 -23
  196. package/lib/server/client-modules/index.js +0 -14
  197. package/lib/server/duplicateRoutes.d.ts +0 -10
  198. package/lib/server/duplicateRoutes.js +0 -38
  199. package/lib/server/html-tags/htmlTags.js +0 -40
  200. package/lib/server/html-tags/index.d.ts +0 -9
  201. package/lib/server/html-tags/index.js +0 -43
  202. package/lib/server/loadSetup.d.ts +0 -9
  203. package/lib/server/loadSetup.js +0 -25
  204. package/lib/server/plugins/applyRouteTrailingSlash.d.ts +0 -9
  205. package/lib/server/plugins/applyRouteTrailingSlash.js +0 -19
  206. package/lib/server/presets/index.d.ts +0 -11
  207. package/lib/server/presets/index.js +0 -48
  208. package/lib/server/themes/alias.d.ts +0 -8
  209. package/lib/server/themes/alias.js +0 -40
  210. package/lib/server/themes/index.d.ts +0 -12
  211. package/lib/server/themes/index.js +0 -47
  212. package/lib/server/versions/__fixtures__/dummy-plugin.js +0 -0
  213. package/lib/server/versions/__fixtures__/package.json +0 -3
  214. package/lib/server/versions/__tests/index.test.js +0 -25
  215. package/lib/server/versions/index.d.ts +0 -10
  216. package/lib/server/versions/index.js +0 -50
  217. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  218. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  219. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  220. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  221. package/lib/webpack/sharedModuleAliases.d.ts +0 -10
  222. package/lib/webpack/sharedModuleAliases.js +0 -18
  223. package/tsconfig.client.json +0 -13
  224. package/tsconfig.json +0 -13
@@ -7,17 +7,22 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.ensureUniquePluginInstanceIds = void 0;
10
- const lodash_1 = require("lodash");
11
- const constants_1 = require("../../constants");
12
- // It is forbidden to have 2 plugins of the same name sharing the same id
13
- // this is required to support multi-instance plugins without conflict
10
+ const tslib_1 = require("tslib");
11
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
12
+ const utils_1 = require("@docusaurus/utils");
13
+ /**
14
+ * It is forbidden to have 2 plugins of the same name sharing the same ID.
15
+ * This is required to support multi-instance plugins without conflict.
16
+ */
14
17
  function ensureUniquePluginInstanceIds(plugins) {
15
- const pluginsByName = lodash_1.groupBy(plugins, (p) => p.name);
18
+ const pluginsByName = lodash_1.default.groupBy(plugins, (p) => p.name);
16
19
  Object.entries(pluginsByName).forEach(([pluginName, pluginInstances]) => {
17
- const pluginInstancesById = lodash_1.groupBy(pluginInstances, (p) => { var _a; return (_a = p.options.id) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_PLUGIN_ID; });
20
+ const pluginInstancesById = lodash_1.default.groupBy(pluginInstances, (p) => p.options.id ?? utils_1.DEFAULT_PLUGIN_ID);
18
21
  Object.entries(pluginInstancesById).forEach(([pluginId, pluginInstancesWithId]) => {
19
22
  if (pluginInstancesWithId.length !== 1) {
20
- throw new Error(`Plugin "${pluginName}" is used ${pluginInstancesWithId.length} times with id ${pluginId}.\nTo use the same plugin multiple times on a Docusaurus site, you need to assign a unique id to each plugin instance.`);
23
+ throw new Error(`Plugin "${pluginName}" is used ${pluginInstancesWithId.length} times with ID "${pluginId}".\nTo use the same plugin multiple times on a Docusaurus site, you need to assign a unique ID to each plugin instance.${pluginId === utils_1.DEFAULT_PLUGIN_ID
24
+ ? `\n\nThe plugin ID is "${utils_1.DEFAULT_PLUGIN_ID}" by default. It's possible that the preset you are using already includes a plugin instance, in which case you either want to disable the plugin in the preset (to use a single instance), or assign another ID to your extra plugin instance (to use multiple instances).`
25
+ : ''}`);
21
26
  }
22
27
  });
23
28
  });
@@ -0,0 +1,12 @@
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 { LoadContext, DocusaurusConfig } from '@docusaurus/types';
8
+ /**
9
+ * Calls preset functions, aggregates each of their return values, and returns
10
+ * the plugin and theme configs.
11
+ */
12
+ export declare function loadPresets(context: LoadContext): Promise<Pick<DocusaurusConfig, 'plugins' | 'themes'>>;
@@ -0,0 +1,49 @@
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.loadPresets = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const module_1 = require("module");
12
+ const import_fresh_1 = tslib_1.__importDefault(require("import-fresh"));
13
+ const moduleShorthand_1 = require("./moduleShorthand");
14
+ /**
15
+ * Calls preset functions, aggregates each of their return values, and returns
16
+ * the plugin and theme configs.
17
+ */
18
+ async function loadPresets(context) {
19
+ // We need to resolve plugins from the perspective of the site config, as if
20
+ // we are using `require.resolve` on those module names.
21
+ const presetRequire = (0, module_1.createRequire)(context.siteConfigPath);
22
+ const { presets } = context.siteConfig;
23
+ const plugins = [];
24
+ const themes = [];
25
+ presets.forEach((presetItem) => {
26
+ let presetModuleImport;
27
+ let presetOptions = {};
28
+ if (!presetItem) {
29
+ return;
30
+ }
31
+ if (typeof presetItem === 'string') {
32
+ presetModuleImport = presetItem;
33
+ }
34
+ else {
35
+ [presetModuleImport, presetOptions] = presetItem;
36
+ }
37
+ const presetName = (0, moduleShorthand_1.resolveModuleName)(presetModuleImport, presetRequire, 'preset');
38
+ const presetModule = (0, import_fresh_1.default)(presetRequire.resolve(presetName));
39
+ const preset = (presetModule.default ?? presetModule)(context, presetOptions);
40
+ if (preset.plugins) {
41
+ plugins.push(...preset.plugins);
42
+ }
43
+ if (preset.themes) {
44
+ themes.push(...preset.themes);
45
+ }
46
+ });
47
+ return { plugins, themes };
48
+ }
49
+ exports.loadPresets = loadPresets;
@@ -0,0 +1,11 @@
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 ApplyTrailingSlashParams } from '@docusaurus/utils-common';
8
+ import type { RouteConfig } from '@docusaurus/types';
9
+ /** Recursively applies trailing slash config to all nested routes. */
10
+ export declare function applyRouteTrailingSlash(route: RouteConfig, params: ApplyTrailingSlashParams): RouteConfig;
11
+ export declare function sortConfig(routeConfigs: RouteConfig[], baseUrl?: string): void;
@@ -0,0 +1,54 @@
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.sortConfig = exports.applyRouteTrailingSlash = void 0;
10
+ const utils_common_1 = require("@docusaurus/utils-common");
11
+ /** Recursively applies trailing slash config to all nested routes. */
12
+ function applyRouteTrailingSlash(route, params) {
13
+ return {
14
+ ...route,
15
+ path: (0, utils_common_1.applyTrailingSlash)(route.path, params),
16
+ ...(route.routes && {
17
+ routes: route.routes.map((subroute) => applyRouteTrailingSlash(subroute, params)),
18
+ }),
19
+ };
20
+ }
21
+ exports.applyRouteTrailingSlash = applyRouteTrailingSlash;
22
+ function sortConfig(routeConfigs, baseUrl = '/') {
23
+ // Sort the route config. This ensures that route with nested
24
+ // routes is always placed last.
25
+ routeConfigs.sort((a, b) => {
26
+ // Root route should get placed last.
27
+ if (a.path === baseUrl && b.path !== baseUrl) {
28
+ return 1;
29
+ }
30
+ if (a.path !== baseUrl && b.path === baseUrl) {
31
+ return -1;
32
+ }
33
+ if (a.routes && !b.routes) {
34
+ return 1;
35
+ }
36
+ if (!a.routes && b.routes) {
37
+ return -1;
38
+ }
39
+ // Higher priority get placed first.
40
+ if (a.priority || b.priority) {
41
+ const priorityA = a.priority ?? 0;
42
+ const priorityB = b.priority ?? 0;
43
+ const score = priorityB - priorityA;
44
+ if (score !== 0) {
45
+ return score;
46
+ }
47
+ }
48
+ return a.path.localeCompare(b.path);
49
+ });
50
+ routeConfigs.forEach((routeConfig) => {
51
+ routeConfig.routes?.sort((a, b) => a.path.localeCompare(b.path));
52
+ });
53
+ }
54
+ exports.sortConfig = sortConfig;
@@ -0,0 +1,20 @@
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 { LoadedPlugin, LoadContext } from '@docusaurus/types';
8
+ /**
9
+ * Make a synthetic plugin to:
10
+ * - Inject site client modules
11
+ * - Inject scripts/stylesheets
12
+ */
13
+ export declare function createBootstrapPlugin({ siteDir, siteConfig, }: LoadContext): LoadedPlugin;
14
+ /**
15
+ * Configure Webpack fallback mdx loader for md/mdx files out of content-plugin
16
+ * folders. Adds a "fallback" mdx loader for mdx files that are not processed by
17
+ * content plugins. This allows to do things such as importing repo/README.md as
18
+ * a partial from another doc. Not ideal solution, but good enough for now
19
+ */
20
+ export declare function createMDXFallbackPlugin({ siteDir, siteConfig, }: LoadContext): LoadedPlugin;
@@ -0,0 +1,111 @@
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.createMDXFallbackPlugin = exports.createBootstrapPlugin = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const path_1 = tslib_1.__importDefault(require("path"));
12
+ /**
13
+ * Make a synthetic plugin to:
14
+ * - Inject site client modules
15
+ * - Inject scripts/stylesheets
16
+ */
17
+ function createBootstrapPlugin({ siteDir, siteConfig, }) {
18
+ const { stylesheets, scripts, clientModules: siteConfigClientModules, } = siteConfig;
19
+ return {
20
+ name: 'docusaurus-bootstrap-plugin',
21
+ content: null,
22
+ options: {
23
+ id: 'default',
24
+ },
25
+ version: { type: 'synthetic' },
26
+ path: siteDir,
27
+ getClientModules() {
28
+ return siteConfigClientModules;
29
+ },
30
+ injectHtmlTags: () => {
31
+ const stylesheetsTags = stylesheets.map((source) => typeof source === 'string'
32
+ ? `<link rel="stylesheet" href="${source}">`
33
+ : {
34
+ tagName: 'link',
35
+ attributes: {
36
+ rel: 'stylesheet',
37
+ ...source,
38
+ },
39
+ });
40
+ const scriptsTags = scripts.map((source) => typeof source === 'string'
41
+ ? `<script src="${source}"></script>`
42
+ : {
43
+ tagName: 'script',
44
+ attributes: {
45
+ ...source,
46
+ },
47
+ });
48
+ return {
49
+ headTags: [...stylesheetsTags, ...scriptsTags],
50
+ };
51
+ },
52
+ };
53
+ }
54
+ exports.createBootstrapPlugin = createBootstrapPlugin;
55
+ /**
56
+ * Configure Webpack fallback mdx loader for md/mdx files out of content-plugin
57
+ * folders. Adds a "fallback" mdx loader for mdx files that are not processed by
58
+ * content plugins. This allows to do things such as importing repo/README.md as
59
+ * a partial from another doc. Not ideal solution, but good enough for now
60
+ */
61
+ function createMDXFallbackPlugin({ siteDir, siteConfig, }) {
62
+ return {
63
+ name: 'docusaurus-mdx-fallback-plugin',
64
+ content: null,
65
+ options: {
66
+ id: 'default',
67
+ },
68
+ version: { type: 'synthetic' },
69
+ // Synthetic, the path doesn't matter much
70
+ path: '.',
71
+ configureWebpack(config, isServer, { getJSLoader }) {
72
+ // We need the mdx fallback loader to exclude files that were already
73
+ // processed by content plugins mdx loaders. This works, but a bit
74
+ // hacky... Not sure there's a way to handle that differently in webpack
75
+ function getMDXFallbackExcludedPaths() {
76
+ const rules = config.module?.rules;
77
+ return rules.flatMap((rule) => {
78
+ const isMDXRule = rule.test instanceof RegExp && rule.test.test('x.mdx');
79
+ return isMDXRule ? rule.include : [];
80
+ });
81
+ }
82
+ const mdxLoaderOptions = {
83
+ admonitions: true,
84
+ staticDirs: siteConfig.staticDirectories.map((dir) => path_1.default.resolve(siteDir, dir)),
85
+ siteDir,
86
+ // External MDX files are always meant to be imported as partials
87
+ isMDXPartial: () => true,
88
+ // External MDX files might have front matter, just disable the warning
89
+ isMDXPartialFrontMatterWarningDisabled: true,
90
+ };
91
+ return {
92
+ module: {
93
+ rules: [
94
+ {
95
+ test: /\.mdx?$/i,
96
+ exclude: getMDXFallbackExcludedPaths(),
97
+ use: [
98
+ getJSLoader({ isServer }),
99
+ {
100
+ loader: require.resolve('@docusaurus/mdx-loader'),
101
+ options: mdxLoaderOptions,
102
+ },
103
+ ],
104
+ },
105
+ ],
106
+ },
107
+ };
108
+ },
109
+ };
110
+ }
111
+ exports.createMDXFallbackPlugin = createMDXFallbackPlugin;
@@ -4,16 +4,48 @@
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 { ChunkRegistry, RouteConfig, ChunkNames } from '@docusaurus/types';
7
+ import type { RouteConfig, RouteChunkNames, ReportingSeverity } from '@docusaurus/types';
8
8
  declare type LoadedRoutes = {
9
- registry: {
10
- [chunkName: string]: ChunkRegistry;
11
- };
9
+ /** Serialized routes config that can be directly emitted into temp file. */
12
10
  routesConfig: string;
13
- routesChunkNames: {
14
- [routePath: string]: ChunkNames;
11
+ /** @see {ChunkNames} */
12
+ routesChunkNames: RouteChunkNames;
13
+ /**
14
+ * A map from chunk name to module paths. Module paths would have backslash
15
+ * escaped already, so they can be directly printed.
16
+ */
17
+ registry: {
18
+ [chunkName: string]: string;
15
19
  };
20
+ /**
21
+ * Collect all page paths for injecting it later in the plugin lifecycle.
22
+ * This is useful for plugins like sitemaps, redirects etc... Only collects
23
+ * "actual" pages, i.e. those without subroutes, because if a route has
24
+ * subroutes, it is probably a wrapper.
25
+ */
16
26
  routesPaths: string[];
17
27
  };
18
- export default function loadRoutes(pluginsRouteConfigs: RouteConfig[], baseUrl: string): Promise<LoadedRoutes>;
28
+ /**
29
+ * Generates a unique chunk name that can be used in the chunk registry.
30
+ *
31
+ * @param modulePath A path to generate chunk name from. The actual value has no
32
+ * semantic significance.
33
+ * @param prefix A prefix to append to the chunk name, to avoid name clash.
34
+ * @param preferredName Chunk names default to `modulePath`, and this can supply
35
+ * a more human-readable name.
36
+ * @param shortId When `true`, the chunk name would only be a hash without any
37
+ * other characters. Useful for bundle size. Defaults to `true` in production.
38
+ */
39
+ export declare function genChunkName(modulePath: string, prefix?: string, preferredName?: string, shortId?: boolean): string;
40
+ export declare function handleDuplicateRoutes(pluginsRouteConfigs: RouteConfig[], onDuplicateRoutes: ReportingSeverity): void;
41
+ /**
42
+ * Routes are prepared into three temp files:
43
+ *
44
+ * - `routesConfig`, the route config passed to react-router. This file is kept
45
+ * minimal, because it can't be code-splitted.
46
+ * - `routesChunkNames`, a mapping from route paths (hashed) to code-splitted
47
+ * chunk names.
48
+ * - `registry`, a mapping from chunk names to options for react-loadable.
49
+ */
50
+ export declare function loadRoutes(routeConfigs: RouteConfig[], baseUrl: string, onDuplicateRoutes: ReportingSeverity): LoadedRoutes;
19
51
  export {};
@@ -6,115 +6,202 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.loadRoutes = exports.handleDuplicateRoutes = exports.genChunkName = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const querystring_1 = tslib_1.__importDefault(require("querystring"));
12
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
13
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
9
14
  const utils_1 = require("@docusaurus/utils");
10
- const lodash_1 = require("lodash");
11
- const querystring_1 = require("querystring");
12
- const createRouteCodeString = ({ routePath, routeHash, exact, subroutesCodeStrings, }) => {
13
- const str = `{
14
- path: '${routePath}',
15
- component: ComponentCreator('${routePath}','${routeHash}'),
16
- ${exact ? `exact: true,` : ''}
17
- ${subroutesCodeStrings
18
- ? ` routes: [
19
- ${utils_1.removeSuffix(subroutesCodeStrings.join(',\n'), ',\n')},
20
- ]
21
- `
22
- : ''}}`;
23
- return str;
24
- };
25
- const NotFoundRouteCode = `{
26
- path: '*',
27
- component: ComponentCreator('*')
28
- }`;
29
- const RoutesImportsCode = [
30
- `import React from 'react';`,
31
- `import ComponentCreator from '@docusaurus/ComponentCreator';`,
32
- ].join('\n');
33
- function isModule(value) {
34
- if (lodash_1.isString(value)) {
35
- return true;
15
+ const utils_2 = require("./utils");
16
+ /** Indents every line of `str` by one level. */
17
+ function indent(str) {
18
+ return ` ${str.replace(/\n/g, `\n `)}`;
19
+ }
20
+ const chunkNameCache = new Map();
21
+ /**
22
+ * Generates a unique chunk name that can be used in the chunk registry.
23
+ *
24
+ * @param modulePath A path to generate chunk name from. The actual value has no
25
+ * semantic significance.
26
+ * @param prefix A prefix to append to the chunk name, to avoid name clash.
27
+ * @param preferredName Chunk names default to `modulePath`, and this can supply
28
+ * a more human-readable name.
29
+ * @param shortId When `true`, the chunk name would only be a hash without any
30
+ * other characters. Useful for bundle size. Defaults to `true` in production.
31
+ */
32
+ function genChunkName(modulePath, prefix, preferredName, shortId = process.env.NODE_ENV === 'production') {
33
+ let chunkName = chunkNameCache.get(modulePath);
34
+ if (!chunkName) {
35
+ if (shortId) {
36
+ chunkName = (0, utils_1.simpleHash)(modulePath, 8);
37
+ }
38
+ else {
39
+ let str = modulePath;
40
+ if (preferredName) {
41
+ const shortHash = (0, utils_1.simpleHash)(modulePath, 3);
42
+ str = `${preferredName}${shortHash}`;
43
+ }
44
+ const name = str === '/' ? 'index' : (0, utils_1.docuHash)(str);
45
+ chunkName = prefix ? `${prefix}---${name}` : name;
46
+ }
47
+ chunkNameCache.set(modulePath, chunkName);
48
+ }
49
+ return chunkName;
50
+ }
51
+ exports.genChunkName = genChunkName;
52
+ /**
53
+ * Takes a piece of route config, and serializes it into raw JS code. The shape
54
+ * is the same as react-router's `RouteConfig`. Formatting is similar to
55
+ * `JSON.stringify` but without all the quotes.
56
+ */
57
+ function serializeRouteConfig({ routePath, routeHash, exact, subroutesCodeStrings, props, }) {
58
+ const parts = [
59
+ `path: '${routePath}'`,
60
+ `component: ComponentCreator('${routePath}', '${routeHash}')`,
61
+ ];
62
+ if (exact) {
63
+ parts.push(`exact: true`);
36
64
  }
37
- if (lodash_1.isPlainObject(value) && lodash_1.has(value, '__import') && lodash_1.has(value, 'path')) {
38
- return true;
65
+ if (subroutesCodeStrings) {
66
+ parts.push(`routes: [
67
+ ${indent(subroutesCodeStrings.join(',\n'))}
68
+ ]`);
39
69
  }
40
- return false;
70
+ Object.entries(props).forEach(([propName, propValue]) => {
71
+ // Inspired by https://github.com/armanozak/should-quote/blob/main/packages/should-quote/src/lib/should-quote.ts
72
+ const shouldQuote = ((key) => {
73
+ // Pre-sanitation to prevent injection
74
+ if (/[.,;:}/\s]/.test(key)) {
75
+ return true;
76
+ }
77
+ try {
78
+ // If this key can be used in an expression like ({a:0}).a
79
+ // eslint-disable-next-line no-eval
80
+ eval(`({${key}:0}).${key}`);
81
+ return false;
82
+ }
83
+ catch {
84
+ return true;
85
+ }
86
+ })(propName);
87
+ // Escape quotes as well
88
+ const key = shouldQuote ? JSON.stringify(propName) : propName;
89
+ parts.push(`${key}: ${JSON.stringify(propValue)}`);
90
+ });
91
+ return `{
92
+ ${indent(parts.join(',\n'))}
93
+ }`;
41
94
  }
95
+ const isModule = (value) => typeof value === 'string' ||
96
+ (typeof value === 'object' &&
97
+ // eslint-disable-next-line no-underscore-dangle
98
+ !!value?.__import);
99
+ /**
100
+ * Takes a {@link Module} (which is nothing more than a path plus some metadata
101
+ * like query) and returns the string path it represents.
102
+ */
42
103
  function getModulePath(target) {
43
104
  if (typeof target === 'string') {
44
105
  return target;
45
106
  }
46
- const queryStr = target.query ? `?${querystring_1.stringify(target.query)}` : '';
107
+ const queryStr = target.query ? `?${querystring_1.default.stringify(target.query)}` : '';
47
108
  return `${target.path}${queryStr}`;
48
109
  }
49
- async function loadRoutes(pluginsRouteConfigs, baseUrl) {
50
- const registry = {};
51
- const routesPaths = [utils_1.normalizeUrl([baseUrl, '404.html'])];
52
- const routesChunkNames = {};
53
- // This is the higher level overview of route code generation.
54
- function generateRouteCode(routeConfig) {
55
- const { path: routePath, component, modules = {}, routes: subroutes, exact, } = routeConfig;
56
- if (!lodash_1.isString(routePath) || !component) {
57
- throw new Error(`Invalid route config: path must be a string and component is required.\n${JSON.stringify(routeConfig)}`);
58
- }
59
- // Collect all page paths for injecting it later in the plugin lifecycle
60
- // This is useful for plugins like sitemaps, redirects etc...
61
- // If a route has subroutes, it is not necessarily a valid page path (more likely to be a wrapper)
62
- if (!subroutes) {
63
- routesPaths.push(routePath);
64
- }
65
- // We hash the route to generate the key, because 2 routes can conflict with
66
- // each others if they have the same path, ex: parent=/docs, child=/docs
67
- // see https://github.com/facebook/docusaurus/issues/2917
68
- const routeHash = utils_1.simpleHash(JSON.stringify(routeConfig), 3);
69
- const chunkNamesKey = `${routePath}-${routeHash}`;
70
- routesChunkNames[chunkNamesKey] = {
71
- ...genRouteChunkNames(registry, { component }, 'component', component),
72
- ...genRouteChunkNames(registry, modules, 'module', routePath),
73
- };
74
- return createRouteCodeString({
75
- routePath: routeConfig.path.replace(/'/g, "\\'"),
76
- routeHash,
77
- exact,
78
- subroutesCodeStrings: subroutes === null || subroutes === void 0 ? void 0 : subroutes.map(generateRouteCode),
79
- });
110
+ function genChunkNames(routeModule, prefix, name, res) {
111
+ if (isModule(routeModule)) {
112
+ // This is a leaf node, no need to recurse
113
+ const modulePath = getModulePath(routeModule);
114
+ const chunkName = genChunkName(modulePath, prefix, name);
115
+ res.registry[chunkName] = (0, utils_1.escapePath)(modulePath);
116
+ return chunkName;
80
117
  }
81
- const routesConfig = `
82
- ${RoutesImportsCode}
83
- export default [
84
- ${pluginsRouteConfigs.map(generateRouteCode).join(',\n')},
85
- ${NotFoundRouteCode}
86
- ];\n`;
87
- return {
88
- registry,
89
- routesConfig,
90
- routesChunkNames,
91
- routesPaths,
92
- };
118
+ if (Array.isArray(routeModule)) {
119
+ return routeModule.map((val, index) => genChunkNames(val, `${index}`, name, res));
120
+ }
121
+ return lodash_1.default.mapValues(routeModule, (v, key) => genChunkNames(v, key, name, res));
93
122
  }
94
- exports.default = loadRoutes;
95
- function genRouteChunkNames(
96
- // TODO instead of passing a mutating the registry, return a registry slice?
97
- registry, value, prefix, name) {
98
- if (!value) {
99
- return null;
123
+ function handleDuplicateRoutes(pluginsRouteConfigs, onDuplicateRoutes) {
124
+ if (onDuplicateRoutes === 'ignore') {
125
+ return;
100
126
  }
101
- if (Array.isArray(value)) {
102
- return value.map((val, index) => genRouteChunkNames(registry, val, `${index}`, name));
127
+ const allRoutes = (0, utils_2.getAllFinalRoutes)(pluginsRouteConfigs).map((routeConfig) => routeConfig.path);
128
+ const seenRoutes = new Set();
129
+ const duplicatePaths = allRoutes.filter((route) => {
130
+ if (seenRoutes.has(route)) {
131
+ return true;
132
+ }
133
+ seenRoutes.add(route);
134
+ return false;
135
+ });
136
+ if (duplicatePaths.length > 0) {
137
+ logger_1.default.report(onDuplicateRoutes) `Duplicate routes found!${duplicatePaths.map((duplicateRoute) => logger_1.default.interpolate `Attempting to create page at url=${duplicateRoute}, but a page already exists at this route.`)}
138
+ This could lead to non-deterministic routing behavior.`;
103
139
  }
104
- if (isModule(value)) {
105
- const modulePath = getModulePath(value);
106
- const chunkName = utils_1.genChunkName(modulePath, prefix, name);
107
- // We need to JSON.stringify so that if its on windows, backslashes are escaped.
108
- const loader = `() => import(/* webpackChunkName: '${chunkName}' */ ${JSON.stringify(modulePath)})`;
109
- registry[chunkName] = {
110
- loader,
111
- modulePath,
112
- };
113
- return chunkName;
140
+ }
141
+ exports.handleDuplicateRoutes = handleDuplicateRoutes;
142
+ /**
143
+ * This is the higher level overview of route code generation. For each route
144
+ * config node, it returns the node's serialized form, and mutates `registry`,
145
+ * `routesPaths`, and `routesChunkNames` accordingly.
146
+ */
147
+ function genRouteCode(routeConfig, res) {
148
+ const { path: routePath, component, modules = {}, context, routes: subroutes, priority, exact, ...props } = routeConfig;
149
+ if (typeof routePath !== 'string' || !component) {
150
+ throw new Error(`Invalid route config: path must be a string and component is required.
151
+ ${JSON.stringify(routeConfig)}`);
114
152
  }
115
- const newValue = {};
116
- Object.keys(value).forEach((key) => {
117
- newValue[key] = genRouteChunkNames(registry, value[key], key, name);
153
+ if (!subroutes) {
154
+ res.routesPaths.push(routePath);
155
+ }
156
+ const routeHash = (0, utils_1.simpleHash)(JSON.stringify(routeConfig), 3);
157
+ res.routesChunkNames[`${routePath}-${routeHash}`] = {
158
+ // Avoid clash with a prop called "component"
159
+ ...genChunkNames({ __comp: component }, 'component', component, res),
160
+ ...(context &&
161
+ genChunkNames({ __context: context }, 'context', routePath, res)),
162
+ ...genChunkNames(modules, 'module', routePath, res),
163
+ };
164
+ return serializeRouteConfig({
165
+ routePath: routePath.replace(/'/g, "\\'"),
166
+ routeHash,
167
+ subroutesCodeStrings: subroutes?.map((r) => genRouteCode(r, res)),
168
+ exact,
169
+ props,
118
170
  });
119
- return newValue;
120
171
  }
172
+ /**
173
+ * Routes are prepared into three temp files:
174
+ *
175
+ * - `routesConfig`, the route config passed to react-router. This file is kept
176
+ * minimal, because it can't be code-splitted.
177
+ * - `routesChunkNames`, a mapping from route paths (hashed) to code-splitted
178
+ * chunk names.
179
+ * - `registry`, a mapping from chunk names to options for react-loadable.
180
+ */
181
+ function loadRoutes(routeConfigs, baseUrl, onDuplicateRoutes) {
182
+ handleDuplicateRoutes(routeConfigs, onDuplicateRoutes);
183
+ const res = {
184
+ // To be written by `genRouteCode`
185
+ routesConfig: '',
186
+ routesChunkNames: {},
187
+ registry: {},
188
+ routesPaths: [(0, utils_1.normalizeUrl)([baseUrl, '404.html'])],
189
+ };
190
+ // `genRouteCode` would mutate `res`
191
+ const routeConfigSerialized = routeConfigs
192
+ .map((r) => genRouteCode(r, res))
193
+ .join(',\n');
194
+ res.routesConfig = `import React from 'react';
195
+ import ComponentCreator from '@docusaurus/ComponentCreator';
196
+
197
+ export default [
198
+ ${indent(routeConfigSerialized)},
199
+ {
200
+ path: '*',
201
+ component: ComponentCreator('*'),
202
+ },
203
+ ];
204
+ `;
205
+ return res;
206
+ }
207
+ exports.loadRoutes = loadRoutes;
@@ -0,0 +1,12 @@
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 { LoadedPlugin, PluginVersionInformation, SiteMetadata } from '@docusaurus/types';
8
+ export declare function getPluginVersion(pluginPath: string, siteDir: string): Promise<PluginVersionInformation>;
9
+ export declare function loadSiteMetadata({ plugins, siteDir, }: {
10
+ plugins: LoadedPlugin[];
11
+ siteDir: string;
12
+ }): Promise<SiteMetadata>;