@docusaurus/core 3.1.1 → 3.2.0

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 (85) hide show
  1. package/bin/docusaurus.mjs +10 -5
  2. package/lib/client/{serverRenderer.d.ts → renderToHtml.d.ts} +1 -1
  3. package/lib/client/{serverRenderer.js → renderToHtml.js} +1 -1
  4. package/lib/client/serverEntry.d.ts +3 -4
  5. package/lib/client/serverEntry.js +12 -113
  6. package/lib/client/theme-fallback/Error/index.js +22 -8
  7. package/lib/commands/build.d.ts +3 -3
  8. package/lib/commands/build.js +133 -112
  9. package/lib/commands/deploy.d.ts +2 -2
  10. package/lib/commands/deploy.js +3 -3
  11. package/lib/commands/external.js +2 -2
  12. package/lib/commands/serve.d.ts +2 -2
  13. package/lib/commands/serve.js +4 -4
  14. package/lib/commands/{start.d.ts → start/start.d.ts} +3 -3
  15. package/lib/commands/start/start.js +47 -0
  16. package/lib/commands/start/utils.d.ts +31 -0
  17. package/lib/commands/start/utils.js +87 -0
  18. package/lib/commands/start/watcher.d.ts +42 -0
  19. package/lib/commands/start/watcher.js +78 -0
  20. package/lib/commands/start/webpack.d.ts +15 -0
  21. package/lib/commands/start/webpack.js +133 -0
  22. package/lib/commands/swizzle/common.d.ts +1 -0
  23. package/lib/commands/swizzle/common.js +1 -0
  24. package/lib/commands/swizzle/context.js +2 -2
  25. package/lib/commands/swizzle/index.js +32 -3
  26. package/lib/commands/writeHeadingIds.js +2 -2
  27. package/lib/commands/writeTranslations.d.ts +2 -2
  28. package/lib/commands/writeTranslations.js +3 -3
  29. package/lib/index.d.ts +1 -1
  30. package/lib/index.js +1 -1
  31. package/lib/server/brokenLinks.js +4 -4
  32. package/lib/server/clientModules.d.ts +1 -1
  33. package/lib/server/clientModules.js +3 -3
  34. package/lib/server/codegen/codegen.d.ts +20 -0
  35. package/lib/server/codegen/codegen.js +65 -0
  36. package/lib/server/codegen/codegenRoutes.d.ts +49 -0
  37. package/lib/server/codegen/codegenRoutes.js +190 -0
  38. package/lib/server/configValidation.js +6 -4
  39. package/lib/server/i18n.d.ts +2 -2
  40. package/lib/server/i18n.js +20 -2
  41. package/lib/server/plugins/actions.d.ts +19 -0
  42. package/lib/server/plugins/actions.js +62 -0
  43. package/lib/server/plugins/init.js +3 -3
  44. package/lib/server/plugins/plugins.d.ts +21 -0
  45. package/lib/server/plugins/plugins.js +188 -0
  46. package/lib/server/plugins/pluginsUtils.d.ts +16 -0
  47. package/lib/server/plugins/pluginsUtils.js +75 -0
  48. package/lib/server/plugins/routeConfig.d.ts +1 -1
  49. package/lib/server/plugins/routeConfig.js +4 -4
  50. package/lib/server/plugins/synthetic.d.ts +3 -3
  51. package/lib/server/plugins/synthetic.js +0 -2
  52. package/lib/server/routes.d.ts +3 -45
  53. package/lib/server/routes.js +16 -168
  54. package/lib/server/{index.d.ts → site.d.ts} +12 -5
  55. package/lib/server/site.js +164 -0
  56. package/lib/server/siteMetadata.d.ts +5 -4
  57. package/lib/server/siteMetadata.js +14 -10
  58. package/lib/server/translations/translations.d.ts +9 -2
  59. package/lib/server/translations/translations.js +21 -4
  60. package/lib/server/utils.d.ts +0 -2
  61. package/lib/server/utils.js +1 -9
  62. package/lib/ssg.d.ts +31 -0
  63. package/lib/ssg.js +167 -0
  64. package/lib/templates/templates.d.ts +28 -0
  65. package/lib/templates/templates.js +63 -0
  66. package/lib/utils.d.ts +9 -0
  67. package/lib/utils.js +78 -0
  68. package/lib/webpack/base.d.ts +5 -1
  69. package/lib/webpack/base.js +4 -6
  70. package/lib/webpack/client.d.ts +15 -1
  71. package/lib/webpack/client.js +78 -23
  72. package/lib/webpack/minification.d.ts +8 -0
  73. package/lib/webpack/minification.js +97 -0
  74. package/lib/webpack/server.d.ts +5 -3
  75. package/lib/webpack/server.js +41 -50
  76. package/lib/webpack/utils.d.ts +13 -4
  77. package/lib/webpack/utils.js +27 -83
  78. package/package.json +13 -11
  79. package/lib/commands/start.js +0 -212
  80. package/lib/server/index.js +0 -154
  81. package/lib/server/plugins/index.d.ts +0 -18
  82. package/lib/server/plugins/index.js +0 -106
  83. /package/lib/{webpack/templates/index.html.template.ejs → templates/dev.html.template.ejs} +0 -0
  84. /package/lib/{webpack/templates → templates}/ssr.html.template.d.ts +0 -0
  85. /package/lib/{webpack/templates → templates}/ssr.html.template.js +0 -0
@@ -0,0 +1,188 @@
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.reloadPlugin = exports.loadPlugins = void 0;
10
+ const init_1 = require("./init");
11
+ const synthetic_1 = require("./synthetic");
12
+ const translations_1 = require("../translations/translations");
13
+ const routeConfig_1 = require("./routeConfig");
14
+ const utils_1 = require("../../utils");
15
+ const actions_1 = require("./actions");
16
+ const pluginsUtils_1 = require("./pluginsUtils");
17
+ async function translatePluginContent({ plugin, content, context, }) {
18
+ const rawTranslationFiles = (await plugin.getTranslationFiles?.({ content })) ?? [];
19
+ const translationFiles = await Promise.all(rawTranslationFiles.map((translationFile) => (0, translations_1.localizePluginTranslationFile)({
20
+ localizationDir: context.localizationDir,
21
+ translationFile,
22
+ plugin,
23
+ })));
24
+ const translatedContent = plugin.translateContent?.({ content, translationFiles }) ?? content;
25
+ const translatedThemeConfigSlice = plugin.translateThemeConfig?.({
26
+ themeConfig: context.siteConfig.themeConfig,
27
+ translationFiles,
28
+ });
29
+ // TODO dangerous legacy, need to be refactored!
30
+ // Side-effect to merge theme config translations. A plugin should only
31
+ // translate its own slice of theme config and should make no assumptions
32
+ // about other plugins' keys, so this is safe to run in parallel.
33
+ Object.assign(context.siteConfig.themeConfig, translatedThemeConfigSlice);
34
+ return translatedContent;
35
+ }
36
+ async function executePluginContentLoading({ plugin, context, }) {
37
+ return utils_1.PerfLogger.async(`Load ${(0, pluginsUtils_1.formatPluginName)(plugin)}`, async () => {
38
+ let content = await utils_1.PerfLogger.async('loadContent()', () => plugin.loadContent?.());
39
+ content = await utils_1.PerfLogger.async('translatePluginContent()', () => translatePluginContent({
40
+ plugin,
41
+ content,
42
+ context,
43
+ }));
44
+ const defaultCodeTranslations = (await utils_1.PerfLogger.async('getDefaultCodeTranslationMessages()', () => plugin.getDefaultCodeTranslationMessages?.())) ?? {};
45
+ if (!plugin.contentLoaded) {
46
+ return {
47
+ ...plugin,
48
+ content,
49
+ defaultCodeTranslations,
50
+ routes: [],
51
+ globalData: undefined,
52
+ };
53
+ }
54
+ const pluginActionsUtils = await (0, actions_1.createPluginActionsUtils)({
55
+ plugin,
56
+ generatedFilesDir: context.generatedFilesDir,
57
+ baseUrl: context.siteConfig.baseUrl,
58
+ trailingSlash: context.siteConfig.trailingSlash,
59
+ });
60
+ await utils_1.PerfLogger.async('contentLoaded()', () =>
61
+ // @ts-expect-error: should autofix with TS 5.4
62
+ plugin.contentLoaded({
63
+ content,
64
+ actions: pluginActionsUtils.getActions(),
65
+ }));
66
+ return {
67
+ ...plugin,
68
+ content,
69
+ defaultCodeTranslations,
70
+ routes: pluginActionsUtils.getRoutes(),
71
+ globalData: pluginActionsUtils.getGlobalData(),
72
+ };
73
+ });
74
+ }
75
+ async function executeAllPluginsContentLoading({ plugins, context, }) {
76
+ return utils_1.PerfLogger.async(`Load plugins content`, () => {
77
+ return Promise.all(plugins.map((plugin) => executePluginContentLoading({ plugin, context })));
78
+ });
79
+ }
80
+ async function executePluginAllContentLoaded({ plugin, context, allContent, }) {
81
+ return utils_1.PerfLogger.async(`allContentLoaded() - ${(0, pluginsUtils_1.formatPluginName)(plugin)}`, async () => {
82
+ if (!plugin.allContentLoaded) {
83
+ return { routes: [], globalData: undefined };
84
+ }
85
+ const pluginActionsUtils = await (0, actions_1.createPluginActionsUtils)({
86
+ plugin,
87
+ generatedFilesDir: context.generatedFilesDir,
88
+ baseUrl: context.siteConfig.baseUrl,
89
+ trailingSlash: context.siteConfig.trailingSlash,
90
+ });
91
+ await plugin.allContentLoaded({
92
+ allContent,
93
+ actions: pluginActionsUtils.getActions(),
94
+ });
95
+ return {
96
+ routes: pluginActionsUtils.getRoutes(),
97
+ globalData: pluginActionsUtils.getGlobalData(),
98
+ };
99
+ });
100
+ }
101
+ async function executeAllPluginsAllContentLoaded({ plugins, context, }) {
102
+ return utils_1.PerfLogger.async(`allContentLoaded()`, async () => {
103
+ const allContent = (0, pluginsUtils_1.aggregateAllContent)(plugins);
104
+ const routes = [];
105
+ const globalData = {};
106
+ await Promise.all(plugins.map(async (plugin) => {
107
+ var _a;
108
+ const { routes: pluginRoutes, globalData: pluginGlobalData } = await executePluginAllContentLoaded({
109
+ plugin,
110
+ context,
111
+ allContent,
112
+ });
113
+ routes.push(...pluginRoutes);
114
+ if (pluginGlobalData !== undefined) {
115
+ globalData[_a = plugin.name] ?? (globalData[_a] = {});
116
+ globalData[plugin.name][plugin.options.id] = pluginGlobalData;
117
+ }
118
+ }));
119
+ return { routes, globalData };
120
+ });
121
+ }
122
+ // This merges plugins routes and global data created from both lifecycles:
123
+ // - contentLoaded()
124
+ // - allContentLoaded()
125
+ function mergeResults({ plugins, allContentLoadedResult, }) {
126
+ const routes = [
127
+ ...(0, pluginsUtils_1.aggregateRoutes)(plugins),
128
+ ...allContentLoadedResult.routes,
129
+ ];
130
+ (0, routeConfig_1.sortRoutes)(routes);
131
+ const globalData = (0, pluginsUtils_1.mergeGlobalData)((0, pluginsUtils_1.aggregateGlobalData)(plugins), allContentLoadedResult.globalData);
132
+ return { routes, globalData };
133
+ }
134
+ /**
135
+ * Initializes the plugins and run their lifecycle functions.
136
+ */
137
+ async function loadPlugins(context) {
138
+ return utils_1.PerfLogger.async('Load plugins', async () => {
139
+ const initializedPlugins = await utils_1.PerfLogger.async('Init plugins', () => (0, init_1.initPlugins)(context));
140
+ // TODO probably not the ideal place to hardcode those plugins
141
+ initializedPlugins.push((0, synthetic_1.createBootstrapPlugin)(context), (0, synthetic_1.createMDXFallbackPlugin)(context));
142
+ const plugins = await executeAllPluginsContentLoading({
143
+ plugins: initializedPlugins,
144
+ context,
145
+ });
146
+ const allContentLoadedResult = await executeAllPluginsAllContentLoaded({
147
+ plugins,
148
+ context,
149
+ });
150
+ const { routes, globalData } = mergeResults({
151
+ plugins,
152
+ allContentLoadedResult,
153
+ });
154
+ return { plugins, routes, globalData };
155
+ });
156
+ }
157
+ exports.loadPlugins = loadPlugins;
158
+ async function reloadPlugin({ pluginIdentifier, plugins: previousPlugins, context, }) {
159
+ return utils_1.PerfLogger.async(`Reload plugin ${(0, pluginsUtils_1.formatPluginName)(pluginIdentifier)}`, async () => {
160
+ const previousPlugin = (0, pluginsUtils_1.getPluginByIdentifier)({
161
+ plugins: previousPlugins,
162
+ pluginIdentifier,
163
+ });
164
+ const plugin = await executePluginContentLoading({
165
+ plugin: previousPlugin,
166
+ context,
167
+ });
168
+ /*
169
+ // TODO Docusaurus v4 - upgrade to Node 20, use array.with()
170
+ const plugins = previousPlugins.with(
171
+ previousPlugins.indexOf(previousPlugin),
172
+ plugin,
173
+ );
174
+ */
175
+ const plugins = [...previousPlugins];
176
+ plugins[previousPlugins.indexOf(previousPlugin)] = plugin;
177
+ const allContentLoadedResult = await executeAllPluginsAllContentLoaded({
178
+ plugins,
179
+ context,
180
+ });
181
+ const { routes, globalData } = mergeResults({
182
+ plugins,
183
+ allContentLoadedResult,
184
+ });
185
+ return { plugins, routes, globalData };
186
+ });
187
+ }
188
+ exports.reloadPlugin = reloadPlugin;
@@ -0,0 +1,16 @@
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 { AllContent, GlobalData, InitializedPlugin, LoadedPlugin, PluginIdentifier, RouteConfig } from '@docusaurus/types';
8
+ export declare function getPluginByIdentifier<P extends InitializedPlugin>({ plugins, pluginIdentifier, }: {
9
+ pluginIdentifier: PluginIdentifier;
10
+ plugins: P[];
11
+ }): P;
12
+ export declare function aggregateAllContent(loadedPlugins: LoadedPlugin[]): AllContent;
13
+ export declare function aggregateRoutes(loadedPlugins: LoadedPlugin[]): RouteConfig[];
14
+ export declare function aggregateGlobalData(loadedPlugins: LoadedPlugin[]): GlobalData;
15
+ export declare function mergeGlobalData(...globalDataList: GlobalData[]): GlobalData;
16
+ export declare function formatPluginName(plugin: InitializedPlugin | PluginIdentifier): string;
@@ -0,0 +1,75 @@
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.formatPluginName = exports.mergeGlobalData = exports.aggregateGlobalData = exports.aggregateRoutes = exports.aggregateAllContent = exports.getPluginByIdentifier = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
12
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
13
+ function getPluginByIdentifier({ plugins, pluginIdentifier, }) {
14
+ const plugin = plugins.find((p) => p.name === pluginIdentifier.name && p.options.id === pluginIdentifier.id);
15
+ if (!plugin) {
16
+ throw new Error(logger_1.default.interpolate `Plugin not found for identifier ${formatPluginName(pluginIdentifier)}`);
17
+ }
18
+ return plugin;
19
+ }
20
+ exports.getPluginByIdentifier = getPluginByIdentifier;
21
+ function aggregateAllContent(loadedPlugins) {
22
+ return lodash_1.default.chain(loadedPlugins)
23
+ .groupBy((item) => item.name)
24
+ .mapValues((nameItems) => lodash_1.default.chain(nameItems)
25
+ .groupBy((item) => item.options.id)
26
+ .mapValues((idItems) => idItems[0].content)
27
+ .value())
28
+ .value();
29
+ }
30
+ exports.aggregateAllContent = aggregateAllContent;
31
+ function aggregateRoutes(loadedPlugins) {
32
+ return loadedPlugins.flatMap((p) => p.routes);
33
+ }
34
+ exports.aggregateRoutes = aggregateRoutes;
35
+ function aggregateGlobalData(loadedPlugins) {
36
+ const globalData = {};
37
+ loadedPlugins.forEach((plugin) => {
38
+ var _a;
39
+ if (plugin.globalData !== undefined) {
40
+ globalData[_a = plugin.name] ?? (globalData[_a] = {});
41
+ globalData[plugin.name][plugin.options.id] = plugin.globalData;
42
+ }
43
+ });
44
+ return globalData;
45
+ }
46
+ exports.aggregateGlobalData = aggregateGlobalData;
47
+ function mergeGlobalData(...globalDataList) {
48
+ const result = {};
49
+ const allPluginIdentifiers = globalDataList.flatMap((gd) => Object.keys(gd).flatMap((name) => Object.keys(gd[name]).map((id) => ({ name, id }))));
50
+ allPluginIdentifiers.forEach(({ name, id }) => {
51
+ const allData = globalDataList
52
+ .map((gd) => gd?.[name]?.[id])
53
+ .filter((d) => typeof d !== 'undefined');
54
+ const mergedData = allData.length === 1 ? allData[0] : Object.assign({}, ...allData);
55
+ result[name] ?? (result[name] = {});
56
+ result[name][id] = mergedData;
57
+ });
58
+ return result;
59
+ }
60
+ exports.mergeGlobalData = mergeGlobalData;
61
+ // This is primarily useful for colored logging purpose
62
+ // Do not rely on this for logic
63
+ function formatPluginName(plugin) {
64
+ let formattedName = plugin.name;
65
+ // Hacky way to reduce string size for logging purpose
66
+ formattedName = formattedName.replace('docusaurus-plugin-content-', '');
67
+ formattedName = formattedName.replace('docusaurus-plugin-', '');
68
+ formattedName = formattedName.replace('docusaurus-theme-', '');
69
+ formattedName = formattedName.replace('-plugin', '');
70
+ formattedName = logger_1.default.name(formattedName);
71
+ const id = 'id' in plugin ? plugin.id : plugin.options.id;
72
+ const formattedId = logger_1.default.subdue(id);
73
+ return `${formattedName}@${formattedId}`;
74
+ }
75
+ exports.formatPluginName = formatPluginName;
@@ -8,4 +8,4 @@ import { type ApplyTrailingSlashParams } from '@docusaurus/utils-common';
8
8
  import type { RouteConfig } from '@docusaurus/types';
9
9
  /** Recursively applies trailing slash config to all nested routes. */
10
10
  export declare function applyRouteTrailingSlash(route: RouteConfig, params: ApplyTrailingSlashParams): RouteConfig;
11
- export declare function sortConfig(routeConfigs: RouteConfig[], baseUrl?: string): void;
11
+ export declare function sortRoutes(routeConfigs: RouteConfig[], baseUrl?: string): void;
@@ -6,7 +6,7 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.sortConfig = exports.applyRouteTrailingSlash = void 0;
9
+ exports.sortRoutes = exports.applyRouteTrailingSlash = void 0;
10
10
  const utils_common_1 = require("@docusaurus/utils-common");
11
11
  /** Recursively applies trailing slash config to all nested routes. */
12
12
  function applyRouteTrailingSlash(route, params) {
@@ -19,7 +19,7 @@ function applyRouteTrailingSlash(route, params) {
19
19
  };
20
20
  }
21
21
  exports.applyRouteTrailingSlash = applyRouteTrailingSlash;
22
- function sortConfig(routeConfigs, baseUrl = '/') {
22
+ function sortRoutes(routeConfigs, baseUrl = '/') {
23
23
  // Sort the route config. This ensures that route with nested
24
24
  // routes is always placed last.
25
25
  routeConfigs.sort((a, b) => {
@@ -49,8 +49,8 @@ function sortConfig(routeConfigs, baseUrl = '/') {
49
49
  });
50
50
  routeConfigs.forEach((routeConfig) => {
51
51
  if (routeConfig.routes) {
52
- sortConfig(routeConfig.routes, baseUrl);
52
+ sortRoutes(routeConfig.routes, baseUrl);
53
53
  }
54
54
  });
55
55
  }
56
- exports.sortConfig = sortConfig;
56
+ exports.sortRoutes = sortRoutes;
@@ -4,17 +4,17 @@
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 type { LoadedPlugin, LoadContext } from '@docusaurus/types';
7
+ import type { LoadContext, InitializedPlugin } from '@docusaurus/types';
8
8
  /**
9
9
  * Make a synthetic plugin to:
10
10
  * - Inject site client modules
11
11
  * - Inject scripts/stylesheets
12
12
  */
13
- export declare function createBootstrapPlugin({ siteDir, siteConfig, }: LoadContext): LoadedPlugin;
13
+ export declare function createBootstrapPlugin({ siteDir, siteConfig, }: LoadContext): InitializedPlugin;
14
14
  /**
15
15
  * Configure Webpack fallback mdx loader for md/mdx files out of content-plugin
16
16
  * folders. Adds a "fallback" mdx loader for mdx files that are not processed by
17
17
  * content plugins. This allows to do things such as importing repo/README.md as
18
18
  * a partial from another doc. Not ideal solution, but good enough for now
19
19
  */
20
- export declare function createMDXFallbackPlugin({ siteDir, siteConfig, }: LoadContext): LoadedPlugin;
20
+ export declare function createMDXFallbackPlugin({ siteDir, siteConfig, }: LoadContext): InitializedPlugin;
@@ -18,7 +18,6 @@ function createBootstrapPlugin({ siteDir, siteConfig, }) {
18
18
  const { stylesheets, scripts, headTags, clientModules: siteConfigClientModules, } = siteConfig;
19
19
  return {
20
20
  name: 'docusaurus-bootstrap-plugin',
21
- content: null,
22
21
  options: {
23
22
  id: 'default',
24
23
  },
@@ -61,7 +60,6 @@ exports.createBootstrapPlugin = createBootstrapPlugin;
61
60
  function createMDXFallbackPlugin({ siteDir, siteConfig, }) {
62
61
  return {
63
62
  name: 'docusaurus-mdx-fallback-plugin',
64
- content: null,
65
63
  options: {
66
64
  id: 'default',
67
65
  },
@@ -4,48 +4,6 @@
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 type { RouteConfig, RouteChunkNames, ReportingSeverity } from '@docusaurus/types';
8
- type LoadedRoutes = {
9
- /** Serialized routes config that can be directly emitted into temp file. */
10
- routesConfig: string;
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;
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
- */
26
- routesPaths: string[];
27
- };
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;
51
- export {};
7
+ import type { RouteConfig, ReportingSeverity } from '@docusaurus/types';
8
+ export declare function handleDuplicateRoutes(routes: RouteConfig[], onDuplicateRoutes: ReportingSeverity): void;
9
+ export declare function getRoutesPaths(routeConfigs: RouteConfig[], baseUrl: string): string[];
@@ -6,115 +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
- exports.loadRoutes = exports.handleDuplicateRoutes = exports.genChunkName = void 0;
9
+ exports.getRoutesPaths = exports.handleDuplicateRoutes = void 0;
10
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
11
  const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
14
12
  const utils_1 = require("@docusaurus/utils");
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
- const chunkNameCount = new Map();
22
- /**
23
- * Generates a unique chunk name that can be used in the chunk registry.
24
- *
25
- * @param modulePath A path to generate chunk name from. The actual value has no
26
- * semantic significance.
27
- * @param prefix A prefix to append to the chunk name, to avoid name clash.
28
- * @param preferredName Chunk names default to `modulePath`, and this can supply
29
- * a more human-readable name.
30
- * @param shortId When `true`, the chunk name would only be a hash without any
31
- * other characters. Useful for bundle size. Defaults to `true` in production.
32
- */
33
- function genChunkName(modulePath, prefix, preferredName, shortId = process.env.NODE_ENV === 'production') {
34
- let chunkName = chunkNameCache.get(modulePath);
35
- if (!chunkName) {
36
- if (shortId) {
37
- chunkName = (0, utils_1.simpleHash)(modulePath, 8);
38
- }
39
- else {
40
- let str = modulePath;
41
- if (preferredName) {
42
- const shortHash = (0, utils_1.simpleHash)(modulePath, 3);
43
- str = `${preferredName}${shortHash}`;
44
- }
45
- const name = (0, utils_1.docuHash)(str);
46
- chunkName = prefix ? `${prefix}---${name}` : name;
47
- }
48
- const seenCount = (chunkNameCount.get(chunkName) ?? 0) + 1;
49
- if (seenCount > 1) {
50
- chunkName += seenCount.toString(36);
51
- }
52
- chunkNameCache.set(modulePath, chunkName);
53
- chunkNameCount.set(chunkName, seenCount);
54
- }
55
- return chunkName;
56
- }
57
- exports.genChunkName = genChunkName;
58
- /**
59
- * Takes a piece of route config, and serializes it into raw JS code. The shape
60
- * is the same as react-router's `RouteConfig`. Formatting is similar to
61
- * `JSON.stringify` but without all the quotes.
62
- */
63
- function serializeRouteConfig({ routePath, routeHash, exact, subroutesCodeStrings, props, }) {
64
- const parts = [
65
- `path: '${routePath}'`,
66
- `component: ComponentCreator('${routePath}', '${routeHash}')`,
67
- ];
68
- if (exact) {
69
- parts.push(`exact: true`);
70
- }
71
- if (subroutesCodeStrings) {
72
- parts.push(`routes: [
73
- ${indent(subroutesCodeStrings.join(',\n'))}
74
- ]`);
75
- }
76
- Object.entries(props).forEach(([propName, propValue]) => {
77
- const isIdentifier = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u.test(propName);
78
- const key = isIdentifier ? propName : JSON.stringify(propName);
79
- parts.push(`${key}: ${JSON.stringify(propValue)}`);
80
- });
81
- return `{
82
- ${indent(parts.join(',\n'))}
83
- }`;
84
- }
85
- const isModule = (value) => typeof value === 'string' ||
86
- (typeof value === 'object' &&
87
- // eslint-disable-next-line no-underscore-dangle
88
- !!value?.__import);
89
- /**
90
- * Takes a {@link Module} (which is nothing more than a path plus some metadata
91
- * like query) and returns the string path it represents.
92
- */
93
- function getModulePath(target) {
94
- if (typeof target === 'string') {
95
- return target;
96
- }
97
- const queryStr = target.query ? `?${querystring_1.default.stringify(target.query)}` : '';
98
- return `${target.path}${queryStr}`;
99
- }
100
- function genChunkNames(routeModule, prefix, name, res) {
101
- if (isModule(routeModule)) {
102
- // This is a leaf node, no need to recurse
103
- const modulePath = getModulePath(routeModule);
104
- const chunkName = genChunkName(modulePath, prefix, name);
105
- res.registry[chunkName] = (0, utils_1.escapePath)(modulePath);
106
- return chunkName;
107
- }
108
- if (Array.isArray(routeModule)) {
109
- return routeModule.map((val, index) => genChunkNames(val, `${index}`, name, res));
110
- }
111
- return lodash_1.default.mapValues(routeModule, (v, key) => genChunkNames(v, key, name, res));
112
- }
113
- function handleDuplicateRoutes(pluginsRouteConfigs, onDuplicateRoutes) {
13
+ function handleDuplicateRoutes(routes, onDuplicateRoutes) {
114
14
  if (onDuplicateRoutes === 'ignore') {
115
15
  return;
116
16
  }
117
- const allRoutes = (0, utils_2.getAllFinalRoutes)(pluginsRouteConfigs).map((routeConfig) => routeConfig.path);
17
+ const allRoutes = (0, utils_1.flattenRoutes)(routes).map((routeConfig) => routeConfig.path);
118
18
  const seenRoutes = new Set();
119
19
  const duplicatePaths = allRoutes.filter((route) => {
120
20
  if (seenRoutes.has(route)) {
@@ -129,77 +29,25 @@ This could lead to non-deterministic routing behavior.`;
129
29
  }
130
30
  }
131
31
  exports.handleDuplicateRoutes = handleDuplicateRoutes;
132
- /**
133
- * This is the higher level overview of route code generation. For each route
134
- * config node, it returns the node's serialized form, and mutates `registry`,
135
- * `routesPaths`, and `routesChunkNames` accordingly.
136
- */
137
- function genRouteCode(routeConfig, res) {
138
- const { path: routePath, component, modules = {}, context, routes: subroutes, priority, exact, ...props } = routeConfig;
139
- if (typeof routePath !== 'string' || !component) {
140
- throw new Error(`Invalid route config: path must be a string and component is required.
141
- ${JSON.stringify(routeConfig)}`);
142
- }
143
- if (!subroutes) {
144
- res.routesPaths.push(routePath);
145
- }
146
- const routeHash = (0, utils_1.simpleHash)(JSON.stringify(routeConfig), 3);
147
- res.routesChunkNames[`${routePath}-${routeHash}`] = {
148
- // Avoid clash with a prop called "component"
149
- ...genChunkNames({ __comp: component }, 'component', component, res),
150
- ...(context &&
151
- genChunkNames({ __context: context }, 'context', routePath, res)),
152
- ...genChunkNames(modules, 'module', routePath, res),
153
- };
154
- return serializeRouteConfig({
155
- routePath: routePath.replace(/'/g, "\\'"),
156
- routeHash,
157
- subroutesCodeStrings: subroutes?.map((r) => genRouteCode(r, res)),
158
- exact,
159
- props,
160
- });
161
- }
162
32
  /**
163
33
  * Old stuff
164
34
  * As far as I understand, this is what permits to SSG the 404.html file
165
35
  * This is rendered through the catch-all ComponentCreator("*") route
166
36
  * Note CDNs only understand the 404.html file by convention
167
37
  * The extension probably permits to avoid emitting "/404/index.html"
168
- */
169
- const NotFoundRoutePath = '/404.html';
170
- /**
171
- * Routes are prepared into three temp files:
172
38
  *
173
- * - `routesConfig`, the route config passed to react-router. This file is kept
174
- * minimal, because it can't be code-splitted.
175
- * - `routesChunkNames`, a mapping from route paths (hashed) to code-splitted
176
- * chunk names.
177
- * - `registry`, a mapping from chunk names to options for react-loadable.
39
+ * TODO we should probably deprecate/remove "postBuild({routesPaths})
40
+ * The 404 generation handling can be moved to the SSG code
41
+ * We only need getAllFinalRoutes() utils IMHO
42
+ * This would be a plugin lifecycle breaking change :/
43
+ * Although not many plugins probably use this
44
+ *
178
45
  */
179
- function loadRoutes(routeConfigs, baseUrl, onDuplicateRoutes) {
180
- handleDuplicateRoutes(routeConfigs, onDuplicateRoutes);
181
- const res = {
182
- // To be written by `genRouteCode`
183
- routesConfig: '',
184
- routesChunkNames: {},
185
- registry: {},
186
- routesPaths: [(0, utils_1.normalizeUrl)([baseUrl, NotFoundRoutePath])],
187
- };
188
- // `genRouteCode` would mutate `res`
189
- const routeConfigSerialized = routeConfigs
190
- .map((r) => genRouteCode(r, res))
191
- .join(',\n');
192
- res.routesConfig = `import React from 'react';
193
- import ComponentCreator from '@docusaurus/ComponentCreator';
194
-
195
- export default [
196
- ${indent(routeConfigSerialized)},
197
- {
198
- path: '*',
199
- component: ComponentCreator('*'),
200
- },
201
- ];
202
- `;
203
- return res;
46
+ const NotFoundRoutePath = '/404.html';
47
+ function getRoutesPaths(routeConfigs, baseUrl) {
48
+ return [
49
+ (0, utils_1.normalizeUrl)([baseUrl, NotFoundRoutePath]),
50
+ ...(0, utils_1.flattenRoutes)(routeConfigs).map((r) => r.path),
51
+ ];
204
52
  }
205
- exports.loadRoutes = loadRoutes;
53
+ exports.getRoutesPaths = getRoutesPaths;
@@ -4,8 +4,8 @@
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 type { LoadContext, Props } from '@docusaurus/types';
8
- export type LoadContextOptions = {
7
+ import type { LoadContext, Props, PluginIdentifier } from '@docusaurus/types';
8
+ export type LoadContextParams = {
9
9
  /** Usually the CWD; can be overridden with command argument. */
10
10
  siteDir: string;
11
11
  /** Custom output directory. Can be customized with `--out-dir` option */
@@ -22,17 +22,24 @@ export type LoadContextOptions = {
22
22
  */
23
23
  localizePath?: boolean;
24
24
  };
25
+ export type LoadSiteParams = LoadContextParams;
26
+ export type Site = {
27
+ props: Props;
28
+ params: LoadSiteParams;
29
+ };
25
30
  /**
26
- * Loading context is the very first step in site building. Its options are
31
+ * Loading context is the very first step in site building. Its params are
27
32
  * directly acquired from CLI options. It mainly loads `siteConfig` and the i18n
28
33
  * context (which includes code translations). The `LoadContext` will be passed
29
34
  * to plugin constructors.
30
35
  */
31
- export declare function loadContext(options: LoadContextOptions): Promise<LoadContext>;
36
+ export declare function loadContext(params: LoadContextParams): Promise<LoadContext>;
32
37
  /**
33
38
  * This is the crux of the Docusaurus server-side. It reads everything it needs—
34
39
  * code translations, config file, plugin modules... Plugins then use their
35
40
  * lifecycles to generate content and other data. It is side-effect-ful because
36
41
  * it generates temp files in the `.docusaurus` folder for the bundler.
37
42
  */
38
- export declare function load(options: LoadContextOptions): Promise<Props>;
43
+ export declare function loadSite(params: LoadContextParams): Promise<Site>;
44
+ export declare function reloadSite(site: Site): Promise<Site>;
45
+ export declare function reloadSitePlugin(site: Site, pluginIdentifier: PluginIdentifier): Promise<Site>;