@docusaurus/core 3.3.2 → 3.5.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 (96) hide show
  1. package/bin/docusaurus.mjs +13 -12
  2. package/lib/babel/preset.js +1 -1
  3. package/lib/client/App.d.ts +0 -2
  4. package/lib/client/BaseUrlIssueBanner/index.d.ts +0 -1
  5. package/lib/client/BrokenLinksContext.d.ts +0 -1
  6. package/lib/client/SiteMetadataDefaults.d.ts +0 -1
  7. package/lib/client/clientEntry.js +7 -3
  8. package/lib/client/exports/BrowserOnly.d.ts +0 -2
  9. package/lib/client/exports/ErrorBoundary.d.ts +0 -1
  10. package/lib/client/exports/Head.d.ts +0 -2
  11. package/lib/client/exports/Interpolate.d.ts +0 -1
  12. package/lib/client/exports/Link.d.ts +0 -1
  13. package/lib/client/exports/Link.js +26 -5
  14. package/lib/client/exports/Translate.d.ts +0 -2
  15. package/lib/client/exports/useBaseUrl.d.ts +8 -1
  16. package/lib/client/exports/useBaseUrl.js +11 -3
  17. package/lib/client/exports/useBrokenLinks.d.ts +0 -1
  18. package/lib/client/hasHydratedDataAttribute.d.ts +0 -1
  19. package/lib/client/theme-fallback/Error/index.d.ts +0 -2
  20. package/lib/client/theme-fallback/Layout/index.d.ts +0 -2
  21. package/lib/client/theme-fallback/Loading/index.d.ts +0 -1
  22. package/lib/client/theme-fallback/NotFound/index.d.ts +0 -1
  23. package/lib/client/theme-fallback/Root/index.d.ts +0 -2
  24. package/lib/client/theme-fallback/SiteMetadata/index.d.ts +0 -1
  25. package/lib/commands/build.js +36 -23
  26. package/lib/commands/clear.js +1 -2
  27. package/lib/commands/deploy.js +1 -2
  28. package/lib/commands/external.js +1 -2
  29. package/lib/commands/serve.js +16 -6
  30. package/lib/commands/start/start.js +1 -2
  31. package/lib/commands/start/utils.d.ts +3 -2
  32. package/lib/commands/start/utils.js +9 -5
  33. package/lib/commands/start/watcher.js +5 -6
  34. package/lib/commands/start/webpack.js +4 -5
  35. package/lib/commands/swizzle/actions.js +4 -4
  36. package/lib/commands/swizzle/common.js +7 -7
  37. package/lib/commands/swizzle/components.js +5 -6
  38. package/lib/commands/swizzle/config.js +2 -3
  39. package/lib/commands/swizzle/context.js +19 -8
  40. package/lib/commands/swizzle/index.js +1 -2
  41. package/lib/commands/swizzle/prompts.js +4 -5
  42. package/lib/commands/swizzle/tables.js +2 -3
  43. package/lib/commands/swizzle/themes.js +5 -6
  44. package/lib/commands/writeHeadingIds.js +1 -2
  45. package/lib/commands/writeTranslations.js +1 -2
  46. package/lib/server/brokenLinks.js +10 -3
  47. package/lib/server/clientModules.js +1 -2
  48. package/lib/server/codegen/codegen.d.ts +2 -1
  49. package/lib/server/codegen/codegen.js +5 -2
  50. package/lib/server/codegen/codegenRoutes.d.ts +1 -0
  51. package/lib/server/codegen/codegenRoutes.js +22 -9
  52. package/lib/server/config.js +1 -2
  53. package/lib/server/configValidation.d.ts +4 -1
  54. package/lib/server/configValidation.js +30 -2
  55. package/lib/server/getHostPort.js +1 -2
  56. package/lib/server/htmlTags.d.ts +5 -2
  57. package/lib/server/htmlTags.js +16 -8
  58. package/lib/server/i18n.js +39 -11
  59. package/lib/server/plugins/actions.js +1 -2
  60. package/lib/server/plugins/configs.js +1 -2
  61. package/lib/server/plugins/init.d.ts +11 -0
  62. package/lib/server/plugins/init.js +42 -7
  63. package/lib/server/plugins/moduleShorthand.d.ts +0 -1
  64. package/lib/server/plugins/moduleShorthand.js +2 -3
  65. package/lib/server/plugins/pluginIds.js +1 -2
  66. package/lib/server/plugins/plugins.js +2 -3
  67. package/lib/server/plugins/pluginsUtils.js +7 -8
  68. package/lib/server/plugins/presets.js +1 -2
  69. package/lib/server/plugins/routeConfig.js +2 -3
  70. package/lib/server/plugins/synthetic.js +2 -3
  71. package/lib/server/routes.js +2 -3
  72. package/lib/server/site.js +17 -10
  73. package/lib/server/siteMetadata.js +3 -4
  74. package/lib/server/storage.d.ts +13 -0
  75. package/lib/server/storage.js +35 -0
  76. package/lib/server/translations/translations.js +9 -10
  77. package/lib/server/translations/translationsExtractor.js +4 -5
  78. package/lib/server/utils.js +1 -2
  79. package/lib/ssg.d.ts +4 -1
  80. package/lib/ssg.js +10 -3
  81. package/lib/templates/templates.d.ts +3 -0
  82. package/lib/templates/templates.js +27 -3
  83. package/lib/webpack/aliases/index.js +4 -5
  84. package/lib/webpack/base.js +4 -4
  85. package/lib/webpack/client.js +13 -22
  86. package/lib/webpack/configure.d.ts +25 -0
  87. package/lib/webpack/configure.js +99 -0
  88. package/lib/webpack/minification.js +1 -2
  89. package/lib/webpack/plugins/ForceTerminatePlugin.d.ts +10 -0
  90. package/lib/webpack/plugins/ForceTerminatePlugin.js +25 -0
  91. package/lib/webpack/plugins/StaticDirectoriesCopyPlugin.d.ts +11 -0
  92. package/lib/webpack/plugins/StaticDirectoriesCopyPlugin.js +38 -0
  93. package/lib/webpack/server.js +1 -29
  94. package/lib/webpack/utils.d.ts +1 -24
  95. package/lib/webpack/utils.js +8 -87
  96. package/package.json +10 -10
@@ -6,7 +6,10 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.generateRouteFiles = exports.generateRoutesCode = exports.genChunkName = void 0;
9
+ exports.genChunkName = genChunkName;
10
+ exports.generateRoutesCode = generateRoutesCode;
11
+ exports.generateRoutePropFilename = generateRoutePropFilename;
12
+ exports.generateRouteFiles = generateRouteFiles;
10
13
  const tslib_1 = require("tslib");
11
14
  const querystring_1 = tslib_1.__importDefault(require("querystring"));
12
15
  const path_1 = tslib_1.__importDefault(require("path"));
@@ -53,7 +56,6 @@ function genChunkName(modulePath, prefix, preferredName, shortId = process.env.N
53
56
  }
54
57
  return chunkName;
55
58
  }
56
- exports.genChunkName = genChunkName;
57
59
  /**
58
60
  * Takes a piece of route config, and serializes it into raw JS code. The shape
59
61
  * is the same as react-router's `RouteConfig`. Formatting is similar to
@@ -169,7 +171,6 @@ ${indent(routeConfigSerialized)},
169
171
  `;
170
172
  return res;
171
173
  }
172
- exports.generateRoutesCode = generateRoutesCode;
173
174
  const genRegistry = ({ generatedFilesDir, registry, }) => (0, utils_1.generate)(generatedFilesDir, 'registry.js', `export default {
174
175
  ${Object.entries(registry)
175
176
  .sort((a, b) => a[0].localeCompare(b[0]))
@@ -180,12 +181,25 @@ ${Object.entries(registry)
180
181
  `);
181
182
  const genRoutesChunkNames = ({ generatedFilesDir, routesChunkNames, }) => (0, utils_1.generate)(generatedFilesDir, 'routesChunkNames.json', JSON.stringify(routesChunkNames, null, 2));
182
183
  const genRoutes = ({ generatedFilesDir, routesConfig, }) => (0, utils_1.generate)(generatedFilesDir, 'routes.js', routesConfig);
184
+ // The generated filename per route must be unique to avoid conflicts
185
+ // See also https://github.com/facebook/docusaurus/issues/10125
186
+ function generateRoutePropFilename(route) {
187
+ // TODO if possible, we could try to shorten the filename by removing
188
+ // the plugin routeBasePath prefix from the name
189
+ return `${(0, utils_1.docuHash)(route.path,
190
+ // Note: using hash(route.path + route.component) is not technically
191
+ // as robust as hashing the entire prop content object.
192
+ // But it's faster and should be good enough considering it's very unlikely
193
+ // anyone would have 2 routes on the same path also rendering the exact
194
+ // same component.
195
+ { hashExtra: route.component })}.json`;
196
+ }
183
197
  async function generateRoutePropModule({ generatedFilesDir, route, plugin, }) {
184
198
  ensureNoPropsConflict(route);
185
199
  const moduleContent = JSON.stringify(route.props);
186
200
  // TODO we should aim to reduce this path length
187
201
  // This adds bytes to the global module registry
188
- const relativePath = path_1.default.posix.join(plugin.name, plugin.id, 'p', `${(0, utils_1.docuHash)(route.path)}.json`);
202
+ const relativePath = path_1.default.posix.join(plugin.name, plugin.id, 'p', generateRoutePropFilename(route));
189
203
  const modulePath = path_1.default.posix.join(generatedFilesDir, relativePath);
190
204
  const aliasedPath = path_1.default.posix.join('@generated', relativePath);
191
205
  await (0, utils_1.generate)(generatedFilesDir, modulePath, moduleContent);
@@ -201,14 +215,14 @@ function ensureNoPropsConflict(route) {
201
215
  }
202
216
  }
203
217
  async function preprocessRouteProps({ generatedFilesDir, route, plugin, }) {
204
- const propsModulePathPromise = route.props
218
+ const getPropsModulePathPromise = () => route.props
205
219
  ? generateRoutePropModule({
206
220
  generatedFilesDir,
207
221
  route,
208
222
  plugin,
209
223
  })
210
224
  : undefined;
211
- const subRoutesPromise = route.routes
225
+ const getSubRoutesPromise = () => route.routes
212
226
  ? Promise.all(route.routes.map((subRoute) => {
213
227
  return preprocessRouteProps({
214
228
  generatedFilesDir,
@@ -218,8 +232,8 @@ async function preprocessRouteProps({ generatedFilesDir, route, plugin, }) {
218
232
  }))
219
233
  : undefined;
220
234
  const [propsModulePath, subRoutes] = await Promise.all([
221
- propsModulePathPromise,
222
- subRoutesPromise,
235
+ getPropsModulePathPromise(),
236
+ getSubRoutesPromise(),
223
237
  ]);
224
238
  const newRoute = {
225
239
  ...route,
@@ -256,4 +270,3 @@ async function generateRouteFiles({ generatedFilesDir, routes: initialRoutes, })
256
270
  genRoutes({ generatedFilesDir, routesConfig }),
257
271
  ]);
258
272
  }
259
- exports.generateRouteFiles = generateRouteFiles;
@@ -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.loadSiteConfig = void 0;
9
+ exports.loadSiteConfig = loadSiteConfig;
10
10
  const tslib_1 = require("tslib");
11
11
  const path_1 = tslib_1.__importDefault(require("path"));
12
12
  const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
@@ -39,4 +39,3 @@ async function loadSiteConfig({ siteDir, customConfigFilePath, }) {
39
39
  const siteConfig = (0, configValidation_1.validateConfig)(loadedConfig, path_1.default.relative(siteDir, siteConfigPath));
40
40
  return { siteConfig, siteConfigPath };
41
41
  }
42
- exports.loadSiteConfig = loadSiteConfig;
@@ -5,9 +5,12 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
  import { Joi } from '@docusaurus/utils-validation';
8
+ import type { FutureConfig, StorageConfig } from '@docusaurus/types/src/config';
8
9
  import type { DocusaurusConfig, I18nConfig, MarkdownConfig } from '@docusaurus/types';
9
10
  export declare const DEFAULT_I18N_CONFIG: I18nConfig;
11
+ export declare const DEFAULT_STORAGE_CONFIG: StorageConfig;
12
+ export declare const DEFAULT_FUTURE_CONFIG: FutureConfig;
10
13
  export declare const DEFAULT_MARKDOWN_CONFIG: MarkdownConfig;
11
- export declare const DEFAULT_CONFIG: Pick<DocusaurusConfig, 'i18n' | 'onBrokenLinks' | 'onBrokenAnchors' | 'onBrokenMarkdownLinks' | 'onDuplicateRoutes' | 'plugins' | 'themes' | 'presets' | 'headTags' | 'stylesheets' | 'scripts' | 'clientModules' | 'customFields' | 'themeConfig' | 'titleDelimiter' | 'noIndex' | 'tagline' | 'baseUrlIssueBanner' | 'staticDirectories' | 'markdown'>;
14
+ export declare const DEFAULT_CONFIG: Pick<DocusaurusConfig, 'i18n' | 'future' | 'onBrokenLinks' | 'onBrokenAnchors' | 'onBrokenMarkdownLinks' | 'onDuplicateRoutes' | 'plugins' | 'themes' | 'presets' | 'headTags' | 'stylesheets' | 'scripts' | 'clientModules' | 'customFields' | 'themeConfig' | 'titleDelimiter' | 'noIndex' | 'tagline' | 'baseUrlIssueBanner' | 'staticDirectories' | 'markdown'>;
12
15
  export declare const ConfigSchema: Joi.ObjectSchema<DocusaurusConfig>;
13
16
  export declare function validateConfig(config: unknown, siteConfigPath: string): DocusaurusConfig;
@@ -6,7 +6,8 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.validateConfig = exports.ConfigSchema = exports.DEFAULT_CONFIG = exports.DEFAULT_MARKDOWN_CONFIG = exports.DEFAULT_I18N_CONFIG = void 0;
9
+ exports.ConfigSchema = exports.DEFAULT_CONFIG = exports.DEFAULT_MARKDOWN_CONFIG = exports.DEFAULT_FUTURE_CONFIG = exports.DEFAULT_STORAGE_CONFIG = exports.DEFAULT_I18N_CONFIG = void 0;
10
+ exports.validateConfig = validateConfig;
10
11
  const utils_1 = require("@docusaurus/utils");
11
12
  const utils_validation_1 = require("@docusaurus/utils-validation");
12
13
  const utils_common_1 = require("@docusaurus/utils-common");
@@ -17,6 +18,14 @@ exports.DEFAULT_I18N_CONFIG = {
17
18
  locales: [DEFAULT_I18N_LOCALE],
18
19
  localeConfigs: {},
19
20
  };
21
+ exports.DEFAULT_STORAGE_CONFIG = {
22
+ type: 'localStorage',
23
+ namespace: false,
24
+ };
25
+ exports.DEFAULT_FUTURE_CONFIG = {
26
+ experimental_storage: exports.DEFAULT_STORAGE_CONFIG,
27
+ experimental_router: 'browser',
28
+ };
20
29
  exports.DEFAULT_MARKDOWN_CONFIG = {
21
30
  format: 'mdx', // TODO change this to "detect" in Docusaurus v4?
22
31
  mermaid: false,
@@ -34,6 +43,7 @@ exports.DEFAULT_MARKDOWN_CONFIG = {
34
43
  };
35
44
  exports.DEFAULT_CONFIG = {
36
45
  i18n: exports.DEFAULT_I18N_CONFIG,
46
+ future: exports.DEFAULT_FUTURE_CONFIG,
37
47
  onBrokenLinks: 'throw',
38
48
  onBrokenAnchors: 'warn', // TODO Docusaurus v4: change to throw
39
49
  onBrokenMarkdownLinks: 'warn',
@@ -120,6 +130,24 @@ const I18N_CONFIG_SCHEMA = utils_validation_1.Joi.object({
120
130
  })
121
131
  .optional()
122
132
  .default(exports.DEFAULT_I18N_CONFIG);
133
+ const STORAGE_CONFIG_SCHEMA = utils_validation_1.Joi.object({
134
+ type: utils_validation_1.Joi.string()
135
+ .equal('localStorage', 'sessionStorage')
136
+ .default(exports.DEFAULT_STORAGE_CONFIG.type),
137
+ namespace: utils_validation_1.Joi.alternatives()
138
+ .try(utils_validation_1.Joi.string(), utils_validation_1.Joi.boolean())
139
+ .default(exports.DEFAULT_STORAGE_CONFIG.namespace),
140
+ })
141
+ .optional()
142
+ .default(exports.DEFAULT_STORAGE_CONFIG);
143
+ const FUTURE_CONFIG_SCHEMA = utils_validation_1.Joi.object({
144
+ experimental_storage: STORAGE_CONFIG_SCHEMA,
145
+ experimental_router: utils_validation_1.Joi.string()
146
+ .equal('browser', 'hash')
147
+ .default(exports.DEFAULT_FUTURE_CONFIG.experimental_router),
148
+ })
149
+ .optional()
150
+ .default(exports.DEFAULT_FUTURE_CONFIG);
123
151
  const SiteUrlSchema = utils_validation_1.Joi.string()
124
152
  .required()
125
153
  .custom((value, helpers) => {
@@ -152,6 +180,7 @@ exports.ConfigSchema = utils_validation_1.Joi.object({
152
180
  url: SiteUrlSchema,
153
181
  trailingSlash: utils_validation_1.Joi.boolean(), // No default value! undefined = retrocompatible legacy behavior!
154
182
  i18n: I18N_CONFIG_SCHEMA,
183
+ future: FUTURE_CONFIG_SCHEMA,
155
184
  onBrokenLinks: utils_validation_1.Joi.string()
156
185
  .equal('ignore', 'log', 'warn', 'throw')
157
186
  .default(exports.DEFAULT_CONFIG.onBrokenLinks),
@@ -273,4 +302,3 @@ function validateConfig(config, siteConfigPath) {
273
302
  return value;
274
303
  }
275
304
  }
276
- exports.validateConfig = validateConfig;
@@ -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.getHostPort = void 0;
9
+ exports.getHostPort = getHostPort;
10
10
  const tslib_1 = require("tslib");
11
11
  const child_process_1 = require("child_process");
12
12
  const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
@@ -79,4 +79,3 @@ async function getHostPort(options) {
79
79
  const port = await choosePort(host, basePort);
80
80
  return { host, port };
81
81
  }
82
- exports.getHostPort = getHostPort;
@@ -4,9 +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 type { Props, LoadedPlugin } from '@docusaurus/types';
7
+ import type { Props, LoadedPlugin, RouterType } from '@docusaurus/types';
8
8
  /**
9
9
  * Runs the `injectHtmlTags` lifecycle, and aggregates all plugins' tags into
10
10
  * directly render-able HTML markup.
11
11
  */
12
- export declare function loadHtmlTags(plugins: LoadedPlugin[]): Pick<Props, 'headTags' | 'preBodyTags' | 'postBodyTags'>;
12
+ export declare function loadHtmlTags({ plugins, router, }: {
13
+ plugins: LoadedPlugin[];
14
+ router: RouterType;
15
+ }): Pick<Props, 'headTags' | 'preBodyTags' | 'postBodyTags'>;
@@ -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.loadHtmlTags = void 0;
9
+ exports.loadHtmlTags = loadHtmlTags;
10
10
  const tslib_1 = require("tslib");
11
11
  const lodash_1 = tslib_1.__importDefault(require("lodash"));
12
12
  const html_tags_1 = tslib_1.__importDefault(require("html-tags"));
@@ -23,16 +23,25 @@ function assertIsHtmlTagObject(val) {
23
23
  throw new Error(`Error loading ${JSON.stringify(val)}, "${val.tagName}" is not a valid HTML tag.`);
24
24
  }
25
25
  }
26
- function htmlTagObjectToString(tag) {
26
+ function hashRouterAbsoluteToRelativeTagAttribute(name, value) {
27
+ if ((name === 'src' || name === 'href') && value.startsWith('/')) {
28
+ return `.${value}`;
29
+ }
30
+ return value;
31
+ }
32
+ function htmlTagObjectToString({ tag, router, }) {
27
33
  assertIsHtmlTagObject(tag);
28
34
  const isVoidTag = void_1.default.includes(tag.tagName);
29
35
  const tagAttributes = tag.attributes ?? {};
30
36
  const attributes = Object.keys(tagAttributes)
31
37
  .map((attr) => {
32
- const value = tagAttributes[attr];
38
+ let value = tagAttributes[attr];
33
39
  if (typeof value === 'boolean') {
34
40
  return value ? attr : undefined;
35
41
  }
42
+ if (router === 'hash') {
43
+ value = hashRouterAbsoluteToRelativeTagAttribute(attr, value);
44
+ }
36
45
  return `${attr}="${(0, escape_html_1.default)(value)}"`;
37
46
  })
38
47
  .filter((str) => Boolean(str));
@@ -41,22 +50,21 @@ function htmlTagObjectToString(tag) {
41
50
  const closingTag = isVoidTag ? '' : `</${tag.tagName}>`;
42
51
  return openingTag + innerHTML + closingTag;
43
52
  }
44
- function createHtmlTagsString(tags) {
53
+ function createHtmlTagsString({ tags, router, }) {
45
54
  return (Array.isArray(tags) ? tags : [tags])
46
55
  .filter(Boolean)
47
- .map((val) => (typeof val === 'string' ? val : htmlTagObjectToString(val)))
56
+ .map((val) => typeof val === 'string' ? val : htmlTagObjectToString({ tag: val, router }))
48
57
  .join('\n');
49
58
  }
50
59
  /**
51
60
  * Runs the `injectHtmlTags` lifecycle, and aggregates all plugins' tags into
52
61
  * directly render-able HTML markup.
53
62
  */
54
- function loadHtmlTags(plugins) {
63
+ function loadHtmlTags({ plugins, router, }) {
55
64
  const pluginHtmlTags = plugins.map((plugin) => plugin.injectHtmlTags?.({ content: plugin.content }) ?? {});
56
65
  const tagTypes = ['headTags', 'preBodyTags', 'postBodyTags'];
57
66
  return Object.fromEntries(lodash_1.default.zip(tagTypes, tagTypes.map((type) => pluginHtmlTags
58
- .map((tags) => createHtmlTagsString(tags[type]))
67
+ .map((tags) => createHtmlTagsString({ tags: tags[type], router }))
59
68
  .join('\n')
60
69
  .trim())));
61
70
  }
62
- exports.loadHtmlTags = loadHtmlTags;
@@ -6,12 +6,37 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.loadI18n = exports.getDefaultLocaleConfig = void 0;
9
+ exports.getDefaultLocaleConfig = getDefaultLocaleConfig;
10
+ exports.loadI18n = loadI18n;
10
11
  const tslib_1 = require("tslib");
11
12
  const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
12
13
  const rtl_detect_1 = require("rtl-detect");
14
+ function inferLanguageDisplayName(locale) {
15
+ const tryLocale = (l) => {
16
+ try {
17
+ return new Intl.DisplayNames(l, {
18
+ type: 'language',
19
+ fallback: 'code',
20
+ }).of(l);
21
+ }
22
+ catch (e) {
23
+ // This is to compensate "of()" that is a bit strict
24
+ // Looks like starting Node 22, this locale throws: "en-US-u-ca-buddhist"
25
+ // RangeError: invalid_argument
26
+ return null;
27
+ }
28
+ };
29
+ const parts = locale.split('-');
30
+ // This is a best effort, we try various locale forms that could give a result
31
+ return (tryLocale(locale) ??
32
+ tryLocale(`${parts[0]}-${parts[1]}`) ??
33
+ tryLocale(parts[0]));
34
+ }
13
35
  function getDefaultLocaleLabel(locale) {
14
- const languageName = new Intl.DisplayNames(locale, { type: 'language' }).of(locale);
36
+ const languageName = inferLanguageDisplayName(locale);
37
+ if (!languageName) {
38
+ return locale;
39
+ }
15
40
  return (languageName.charAt(0).toLocaleUpperCase(locale) + languageName.substring(1));
16
41
  }
17
42
  function getDefaultCalendar(localeStr) {
@@ -34,15 +59,19 @@ function getDefaultCalendar(localeStr) {
34
59
  return 'gregory';
35
60
  }
36
61
  function getDefaultLocaleConfig(locale) {
37
- return {
38
- label: getDefaultLocaleLabel(locale),
39
- direction: (0, rtl_detect_1.getLangDir)(locale),
40
- htmlLang: locale,
41
- calendar: getDefaultCalendar(locale),
42
- path: locale,
43
- };
62
+ try {
63
+ return {
64
+ label: getDefaultLocaleLabel(locale),
65
+ direction: (0, rtl_detect_1.getLangDir)(locale),
66
+ htmlLang: locale,
67
+ calendar: getDefaultCalendar(locale),
68
+ path: locale,
69
+ };
70
+ }
71
+ catch (e) {
72
+ throw new Error(`Docusaurus couldn't get default locale config for ${locale}`, { cause: e });
73
+ }
44
74
  }
45
- exports.getDefaultLocaleConfig = getDefaultLocaleConfig;
46
75
  async function loadI18n(config, options) {
47
76
  const { i18n: i18nConfig } = config;
48
77
  const currentLocale = options.locale ?? i18nConfig.defaultLocale;
@@ -68,4 +97,3 @@ Note: Docusaurus only support running one locale at a time.`;
68
97
  localeConfigs,
69
98
  };
70
99
  }
71
- exports.loadI18n = loadI18n;
@@ -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.createPluginActionsUtils = void 0;
9
+ exports.createPluginActionsUtils = createPluginActionsUtils;
10
10
  const tslib_1 = require("tslib");
11
11
  const path_1 = tslib_1.__importDefault(require("path"));
12
12
  const utils_1 = require("@docusaurus/utils");
@@ -67,4 +67,3 @@ async function createPluginActionsUtils({ plugin, generatedFilesDir, baseUrl, tr
67
67
  getActions: () => actions,
68
68
  };
69
69
  }
70
- exports.createPluginActionsUtils = createPluginActionsUtils;
@@ -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.loadPluginConfigs = void 0;
9
+ exports.loadPluginConfigs = loadPluginConfigs;
10
10
  const module_1 = require("module");
11
11
  const utils_1 = require("@docusaurus/utils");
12
12
  const presets_1 = require("./presets");
@@ -97,4 +97,3 @@ async function loadPluginConfigs(context) {
97
97
  ].filter((x) => Boolean(x));
98
98
  return Promise.all(pluginConfigs.map((pluginConfig) => normalizePluginConfig(pluginConfig, context.siteConfigPath, pluginRequire)));
99
99
  }
100
- exports.loadPluginConfigs = loadPluginConfigs;
@@ -4,9 +4,20 @@
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 NormalizedPluginConfig } from './configs';
7
8
  import type { LoadContext, InitializedPlugin } from '@docusaurus/types';
9
+ type PluginConfigInitResult = {
10
+ config: NormalizedPluginConfig;
11
+ plugin: InitializedPlugin | null;
12
+ };
8
13
  /**
9
14
  * Runs the plugin constructors and returns their return values. It would load
10
15
  * plugin configs from `plugins`, `themes`, and `presets`.
11
16
  */
17
+ export declare function initPluginsConfigs(context: LoadContext, pluginConfigs: NormalizedPluginConfig[]): Promise<PluginConfigInitResult[]>;
18
+ /**
19
+ * Runs the plugin constructors and returns their return values
20
+ * for all the site context plugins that do not return null to self-disable.
21
+ */
12
22
  export declare function initPlugins(context: LoadContext): Promise<InitializedPlugin[]>;
23
+ export {};
@@ -6,7 +6,8 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.initPlugins = void 0;
9
+ exports.initPluginsConfigs = initPluginsConfigs;
10
+ exports.initPlugins = initPlugins;
10
11
  const tslib_1 = require("tslib");
11
12
  const module_1 = require("module");
12
13
  const path_1 = tslib_1.__importDefault(require("path"));
@@ -31,15 +32,20 @@ function getThemeValidationFunction(normalizedPluginConfig) {
31
32
  }
32
33
  return normalizedPluginConfig.plugin.validateThemeConfig;
33
34
  }
35
+ // This filters self-disabling plugins and returns only the initialized ones
36
+ function onlyInitializedPlugins(initPluginsConfigsResults) {
37
+ return initPluginsConfigsResults
38
+ .map((results) => results.plugin)
39
+ .filter((p) => p !== null);
40
+ }
34
41
  /**
35
42
  * Runs the plugin constructors and returns their return values. It would load
36
43
  * plugin configs from `plugins`, `themes`, and `presets`.
37
44
  */
38
- async function initPlugins(context) {
45
+ async function initPluginsConfigs(context, pluginConfigs) {
39
46
  // We need to resolve plugins from the perspective of the site config, as if
40
47
  // we are using `require.resolve` on those module names.
41
48
  const pluginRequire = (0, module_1.createRequire)(context.siteConfigPath);
42
- const pluginConfigs = await (0, configs_1.loadPluginConfigs)(context);
43
49
  async function doLoadPluginVersion(normalizedPluginConfig) {
44
50
  if (normalizedPluginConfig.pluginModule?.path) {
45
51
  const pluginPath = pluginRequire.resolve(normalizedPluginConfig.pluginModule.path);
@@ -76,20 +82,49 @@ async function initPlugins(context) {
76
82
  const pluginVersion = await doLoadPluginVersion(normalizedPluginConfig);
77
83
  const pluginOptions = doValidatePluginOptions(normalizedPluginConfig);
78
84
  // Side-effect: merge the normalized theme config in the original one
85
+ // Note: it's important to do this before calling the plugin constructor
86
+ // Example: the theme classic plugin will read siteConfig.themeConfig
79
87
  context.siteConfig.themeConfig = {
80
88
  ...context.siteConfig.themeConfig,
81
89
  ...doValidateThemeConfig(normalizedPluginConfig),
82
90
  };
83
91
  const pluginInstance = await normalizedPluginConfig.plugin(context, pluginOptions);
84
- return {
92
+ // Returning null has been explicitly allowed
93
+ // It's a way for plugins to self-disable depending on context
94
+ // See https://github.com/facebook/docusaurus/pull/10286
95
+ if (pluginInstance === null) {
96
+ return { config: normalizedPluginConfig, plugin: null };
97
+ }
98
+ if (pluginInstance === undefined) {
99
+ throw new Error(`A Docusaurus plugin returned 'undefined', which is forbidden.
100
+ A plugin is expected to return an object having at least a 'name' property.
101
+ If you want a plugin to self-disable depending on context/options, you can explicitly return 'null' instead of 'undefined'`);
102
+ }
103
+ if (!pluginInstance?.name) {
104
+ throw new Error(`A Docusaurus plugin is missing a 'name' property.
105
+ Note that even inline/anonymous plugin functions require a 'name' property.`);
106
+ }
107
+ const plugin = {
85
108
  ...pluginInstance,
86
109
  options: pluginOptions,
87
110
  version: pluginVersion,
88
111
  path: path_1.default.dirname(normalizedPluginConfig.entryPath),
89
112
  };
113
+ return {
114
+ config: normalizedPluginConfig,
115
+ plugin,
116
+ };
90
117
  }
91
- const plugins = await Promise.all(pluginConfigs.map(initializePlugin));
92
- (0, pluginIds_1.ensureUniquePluginInstanceIds)(plugins);
118
+ const plugins = (await Promise.all(pluginConfigs.map(initializePlugin))).filter((p) => p !== null);
119
+ (0, pluginIds_1.ensureUniquePluginInstanceIds)(onlyInitializedPlugins(plugins));
93
120
  return plugins;
94
121
  }
95
- exports.initPlugins = initPlugins;
122
+ /**
123
+ * Runs the plugin constructors and returns their return values
124
+ * for all the site context plugins that do not return null to self-disable.
125
+ */
126
+ async function initPlugins(context) {
127
+ const pluginConfigs = await (0, configs_1.loadPluginConfigs)(context);
128
+ const initPluginsConfigsResults = await initPluginsConfigs(context, pluginConfigs);
129
+ return onlyInitializedPlugins(initPluginsConfigsResults);
130
+ }
@@ -4,6 +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
- /// <reference types="node" />
8
7
  export declare function getNamePatterns(moduleName: string, moduleType: 'preset' | 'theme' | 'plugin'): string[];
9
8
  export declare function resolveModuleName(moduleName: string, moduleRequire: NodeRequire, moduleType: 'preset' | 'theme' | 'plugin'): string;
@@ -6,7 +6,8 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.resolveModuleName = exports.getNamePatterns = void 0;
9
+ exports.getNamePatterns = getNamePatterns;
10
+ exports.resolveModuleName = resolveModuleName;
10
11
  function getNamePatterns(moduleName, moduleType) {
11
12
  if (moduleName.startsWith('@')) {
12
13
  // Pure scope: `@scope` => `@scope/docusaurus-plugin`
@@ -25,7 +26,6 @@ function getNamePatterns(moduleName, moduleType) {
25
26
  `docusaurus-${moduleType}-${moduleName}`,
26
27
  ];
27
28
  }
28
- exports.getNamePatterns = getNamePatterns;
29
29
  function resolveModuleName(moduleName, moduleRequire, moduleType) {
30
30
  const modulePatterns = getNamePatterns(moduleName, moduleType);
31
31
  const module = modulePatterns.find((m) => {
@@ -43,4 +43,3 @@ ${modulePatterns.map((m) => `- ${m}`).join('\n')}`);
43
43
  }
44
44
  return module;
45
45
  }
46
- exports.resolveModuleName = resolveModuleName;
@@ -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.ensureUniquePluginInstanceIds = void 0;
9
+ exports.ensureUniquePluginInstanceIds = ensureUniquePluginInstanceIds;
10
10
  const tslib_1 = require("tslib");
11
11
  const lodash_1 = tslib_1.__importDefault(require("lodash"));
12
12
  const utils_1 = require("@docusaurus/utils");
@@ -27,4 +27,3 @@ function ensureUniquePluginInstanceIds(plugins) {
27
27
  });
28
28
  });
29
29
  }
30
- exports.ensureUniquePluginInstanceIds = ensureUniquePluginInstanceIds;
@@ -6,7 +6,8 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.reloadPlugin = exports.loadPlugins = void 0;
9
+ exports.loadPlugins = loadPlugins;
10
+ exports.reloadPlugin = reloadPlugin;
10
11
  const init_1 = require("./init");
11
12
  const synthetic_1 = require("./synthetic");
12
13
  const translations_1 = require("../translations/translations");
@@ -152,7 +153,6 @@ async function loadPlugins(context) {
152
153
  return { plugins, routes, globalData };
153
154
  });
154
155
  }
155
- exports.loadPlugins = loadPlugins;
156
156
  async function reloadPlugin({ pluginIdentifier, plugins: previousPlugins, context, }) {
157
157
  return utils_1.PerfLogger.async(`Reload plugin ${(0, pluginsUtils_1.formatPluginName)(pluginIdentifier)}`, async () => {
158
158
  const previousPlugin = (0, pluginsUtils_1.getPluginByIdentifier)({
@@ -184,4 +184,3 @@ async function reloadPlugin({ pluginIdentifier, plugins: previousPlugins, contex
184
184
  return { plugins, routes, globalData };
185
185
  });
186
186
  }
187
- exports.reloadPlugin = reloadPlugin;
@@ -6,7 +6,13 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.formatPluginName = exports.mergeGlobalData = exports.aggregateGlobalData = exports.aggregateRoutes = exports.toPluginRoute = exports.aggregateAllContent = exports.getPluginByIdentifier = void 0;
9
+ exports.getPluginByIdentifier = getPluginByIdentifier;
10
+ exports.aggregateAllContent = aggregateAllContent;
11
+ exports.toPluginRoute = toPluginRoute;
12
+ exports.aggregateRoutes = aggregateRoutes;
13
+ exports.aggregateGlobalData = aggregateGlobalData;
14
+ exports.mergeGlobalData = mergeGlobalData;
15
+ exports.formatPluginName = formatPluginName;
10
16
  const tslib_1 = require("tslib");
11
17
  const lodash_1 = tslib_1.__importDefault(require("lodash"));
12
18
  const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
@@ -17,7 +23,6 @@ function getPluginByIdentifier({ plugins, pluginIdentifier, }) {
17
23
  }
18
24
  return plugin;
19
25
  }
20
- exports.getPluginByIdentifier = getPluginByIdentifier;
21
26
  function aggregateAllContent(loadedPlugins) {
22
27
  return lodash_1.default.chain(loadedPlugins)
23
28
  .groupBy((item) => item.name)
@@ -27,15 +32,12 @@ function aggregateAllContent(loadedPlugins) {
27
32
  .value())
28
33
  .value();
29
34
  }
30
- exports.aggregateAllContent = aggregateAllContent;
31
35
  function toPluginRoute({ plugin, route, }) {
32
36
  return { plugin: { name: plugin.name, id: plugin.options.id }, ...route };
33
37
  }
34
- exports.toPluginRoute = toPluginRoute;
35
38
  function aggregateRoutes(loadedPlugins) {
36
39
  return loadedPlugins.flatMap((plugin) => plugin.routes.map((route) => toPluginRoute({ plugin, route })));
37
40
  }
38
- exports.aggregateRoutes = aggregateRoutes;
39
41
  function aggregateGlobalData(loadedPlugins) {
40
42
  const globalData = {};
41
43
  loadedPlugins.forEach((plugin) => {
@@ -47,7 +49,6 @@ function aggregateGlobalData(loadedPlugins) {
47
49
  });
48
50
  return globalData;
49
51
  }
50
- exports.aggregateGlobalData = aggregateGlobalData;
51
52
  function mergeGlobalData(...globalDataList) {
52
53
  const result = {};
53
54
  const allPluginIdentifiers = globalDataList.flatMap((gd) => Object.keys(gd).flatMap((name) => Object.keys(gd[name]).map((id) => ({ name, id }))));
@@ -61,7 +62,6 @@ function mergeGlobalData(...globalDataList) {
61
62
  });
62
63
  return result;
63
64
  }
64
- exports.mergeGlobalData = mergeGlobalData;
65
65
  // This is primarily useful for colored logging purpose
66
66
  // Do not rely on this for logic
67
67
  function formatPluginName(plugin) {
@@ -76,4 +76,3 @@ function formatPluginName(plugin) {
76
76
  const formattedId = logger_1.default.subdue(id);
77
77
  return `${formattedName}@${formattedId}`;
78
78
  }
79
- exports.formatPluginName = formatPluginName;
@@ -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.loadPresets = void 0;
9
+ exports.loadPresets = loadPresets;
10
10
  const module_1 = require("module");
11
11
  const utils_1 = require("@docusaurus/utils");
12
12
  const moduleShorthand_1 = require("./moduleShorthand");
@@ -39,4 +39,3 @@ async function loadPresets(context) {
39
39
  const themes = loadedPresets.flatMap((preset) => preset.themes ?? []);
40
40
  return { plugins, themes };
41
41
  }
42
- exports.loadPresets = loadPresets;
@@ -6,7 +6,8 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.sortRoutes = exports.applyRouteTrailingSlash = void 0;
9
+ exports.applyRouteTrailingSlash = applyRouteTrailingSlash;
10
+ exports.sortRoutes = sortRoutes;
10
11
  const utils_common_1 = require("@docusaurus/utils-common");
11
12
  /** Recursively applies trailing slash config to all nested routes. */
12
13
  function applyRouteTrailingSlash(route, params) {
@@ -18,7 +19,6 @@ function applyRouteTrailingSlash(route, params) {
18
19
  }),
19
20
  };
20
21
  }
21
- exports.applyRouteTrailingSlash = applyRouteTrailingSlash;
22
22
  function sortRoutes(routesToSort, baseUrl) {
23
23
  const routeConfigs = [...routesToSort];
24
24
  // Sort the route config. This ensures that route with nested
@@ -71,4 +71,3 @@ function sortRoutes(routesToSort, baseUrl) {
71
71
  });
72
72
  return routeConfigs;
73
73
  }
74
- exports.sortRoutes = sortRoutes;