@docusaurus/core 2.0.0-beta.15d451942 → 2.0.0-beta.18

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 (200) hide show
  1. package/bin/beforeCli.mjs +133 -0
  2. package/bin/docusaurus.mjs +279 -0
  3. package/lib/babel/preset.d.ts +8 -3
  4. package/lib/babel/preset.js +8 -7
  5. package/lib/choosePort.js +31 -43
  6. package/lib/client/.eslintrc.js +0 -1
  7. package/lib/client/App.d.ts +1 -2
  8. package/lib/client/App.js +23 -24
  9. package/lib/client/LinksCollector.d.ts +3 -3
  10. package/lib/client/LinksCollector.js +7 -11
  11. package/lib/client/PendingNavigation.d.ts +24 -1
  12. package/lib/client/PendingNavigation.js +5 -7
  13. package/lib/{webpack/sharedModuleAliases.d.ts → client/SiteMetadataDefaults.d.ts} +2 -4
  14. package/lib/client/SiteMetadataDefaults.js +19 -0
  15. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.d.ts +13 -0
  16. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.js +15 -10
  17. package/lib/client/browserContext.d.ts +11 -0
  18. package/lib/client/browserContext.js +22 -0
  19. package/lib/client/client-lifecycles-dispatcher.d.ts +2 -5
  20. package/lib/client/client-lifecycles-dispatcher.js +6 -10
  21. package/lib/client/clientEntry.js +13 -7
  22. package/lib/client/docusaurus.d.ts +6 -0
  23. package/lib/client/docusaurus.js +16 -25
  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 +2 -3
  27. package/lib/client/exports/BrowserOnly.js +14 -7
  28. package/lib/client/exports/ComponentCreator.d.ts +1 -2
  29. package/lib/client/exports/ComponentCreator.js +40 -19
  30. package/lib/client/exports/ErrorBoundary.d.ts +18 -0
  31. package/lib/client/exports/ErrorBoundary.js +35 -0
  32. package/lib/client/exports/Head.d.ts +2 -3
  33. package/lib/client/exports/Head.js +3 -4
  34. package/lib/client/exports/Interpolate.d.ts +2 -2
  35. package/lib/client/exports/Interpolate.js +20 -26
  36. package/lib/client/exports/Link.d.ts +11 -5
  37. package/lib/client/exports/Link.js +31 -20
  38. package/lib/client/exports/Translate.d.ts +1 -1
  39. package/lib/client/exports/Translate.js +14 -9
  40. package/lib/client/exports/constants.js +1 -11
  41. package/lib/client/exports/isInternalUrl.js +1 -1
  42. package/lib/client/exports/renderRoutes.d.ts +1 -2
  43. package/lib/client/exports/renderRoutes.js +1 -2
  44. package/lib/client/exports/router.d.ts +1 -1
  45. package/lib/client/exports/router.js +1 -1
  46. package/lib/client/exports/useBaseUrl.js +8 -5
  47. package/lib/client/exports/useDocusaurusContext.d.ts +2 -3
  48. package/lib/client/exports/useDocusaurusContext.js +3 -9
  49. package/lib/client/exports/useGlobalData.d.ts +4 -3
  50. package/lib/client/exports/useGlobalData.js +4 -8
  51. package/lib/{server/versions/__tests/index.test.d.ts → client/exports/useIsBrowser.d.ts} +1 -1
  52. package/lib/client/exports/useIsBrowser.js +11 -0
  53. package/lib/{server/loadSetup.d.ts → client/exports/useRouteContext.d.ts} +2 -3
  54. package/lib/client/exports/useRouteContext.js +15 -0
  55. package/lib/client/flat.d.ts +4 -2
  56. package/lib/client/flat.js +9 -13
  57. package/lib/client/normalizeLocation.d.ts +2 -5
  58. package/lib/client/normalizeLocation.js +2 -7
  59. package/lib/client/nprogress.css +2 -2
  60. package/lib/client/prefetch.d.ts +1 -2
  61. package/lib/client/prefetch.js +4 -6
  62. package/lib/client/preload.d.ts +3 -2
  63. package/lib/client/preload.js +5 -10
  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 +90 -142
  68. package/lib/client/theme-fallback/Error/index.d.ts +10 -0
  69. package/lib/client/theme-fallback/Error/index.js +43 -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 +47 -115
  74. package/lib/client/{exports/context.js → theme-fallback/NotFound/index.d.ts} +2 -2
  75. package/lib/client/theme-fallback/NotFound/index.js +17 -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/theme-fallback/SiteMetadata/index.d.ts +8 -0
  79. package/lib/client/theme-fallback/SiteMetadata/index.js +10 -0
  80. package/lib/commands/build.d.ts +1 -1
  81. package/lib/commands/build.js +50 -54
  82. package/lib/commands/clear.d.ts +6 -0
  83. package/lib/commands/clear.js +30 -19
  84. package/lib/commands/commandUtils.d.ts +7 -1
  85. package/lib/commands/commandUtils.js +7 -7
  86. package/lib/commands/deploy.d.ts +1 -1
  87. package/lib/commands/deploy.js +83 -66
  88. package/lib/commands/external.d.ts +2 -2
  89. package/lib/commands/external.js +4 -8
  90. package/lib/commands/serve.d.ts +1 -1
  91. package/lib/commands/serve.js +25 -12
  92. package/lib/commands/start.d.ts +1 -1
  93. package/lib/commands/start.js +96 -87
  94. package/lib/commands/swizzle/actions.d.ts +23 -0
  95. package/lib/commands/swizzle/actions.js +101 -0
  96. package/lib/commands/swizzle/common.d.ts +33 -0
  97. package/lib/commands/swizzle/common.js +56 -0
  98. package/lib/commands/swizzle/components.d.ts +29 -0
  99. package/lib/commands/swizzle/components.js +162 -0
  100. package/lib/commands/swizzle/config.d.ts +10 -0
  101. package/lib/commands/swizzle/config.js +80 -0
  102. package/lib/commands/swizzle/context.d.ts +8 -0
  103. package/lib/commands/swizzle/context.js +28 -0
  104. package/lib/commands/swizzle/index.d.ts +8 -0
  105. package/lib/commands/swizzle/index.js +115 -0
  106. package/lib/commands/swizzle/prompts.d.ts +12 -0
  107. package/lib/commands/swizzle/prompts.js +110 -0
  108. package/lib/{client/exports/context.d.ts → commands/swizzle/tables.d.ts} +3 -4
  109. package/lib/commands/swizzle/tables.js +113 -0
  110. package/lib/commands/swizzle/themes.d.ts +20 -0
  111. package/lib/commands/swizzle/themes.js +106 -0
  112. package/lib/commands/writeHeadingIds.d.ts +2 -6
  113. package/lib/commands/writeHeadingIds.js +19 -76
  114. package/lib/commands/writeTranslations.d.ts +2 -2
  115. package/lib/commands/writeTranslations.js +37 -17
  116. package/lib/index.d.ts +10 -9
  117. package/lib/index.js +20 -19
  118. package/lib/server/brokenLinks.d.ts +4 -17
  119. package/lib/server/brokenLinks.js +64 -52
  120. package/lib/server/client-modules/index.d.ts +2 -2
  121. package/lib/server/client-modules/index.js +4 -3
  122. package/lib/server/config.d.ts +2 -2
  123. package/lib/server/config.js +8 -5
  124. package/lib/server/configValidation.d.ts +4 -2
  125. package/lib/server/configValidation.js +93 -37
  126. package/lib/server/duplicateRoutes.d.ts +1 -3
  127. package/lib/server/duplicateRoutes.js +17 -13
  128. package/lib/server/html-tags/htmlTags.js +7 -8
  129. package/lib/server/html-tags/index.d.ts +2 -3
  130. package/lib/server/html-tags/index.js +3 -4
  131. package/lib/server/i18n.d.ts +2 -3
  132. package/lib/server/i18n.js +27 -48
  133. package/lib/server/index.d.ts +9 -2
  134. package/lib/server/index.js +175 -96
  135. package/lib/server/moduleShorthand.d.ts +9 -0
  136. package/lib/server/moduleShorthand.js +46 -0
  137. package/lib/server/plugins/applyRouteTrailingSlash.d.ts +9 -0
  138. package/lib/server/plugins/applyRouteTrailingSlash.js +19 -0
  139. package/lib/server/plugins/index.d.ts +4 -5
  140. package/lib/server/plugins/index.js +69 -45
  141. package/lib/server/plugins/init.d.ts +15 -5
  142. package/lib/server/plugins/init.js +68 -81
  143. package/lib/server/plugins/pluginIds.d.ts +2 -2
  144. package/lib/server/plugins/pluginIds.js +8 -5
  145. package/lib/server/presets/index.d.ts +3 -3
  146. package/lib/server/presets/index.js +16 -23
  147. package/lib/server/routes.d.ts +3 -5
  148. package/lib/server/routes.js +68 -36
  149. package/lib/server/themes/alias.d.ts +3 -2
  150. package/lib/server/themes/alias.js +24 -13
  151. package/lib/server/themes/index.d.ts +6 -2
  152. package/lib/server/themes/index.js +36 -24
  153. package/lib/server/translations/translations.d.ts +21 -17
  154. package/lib/server/translations/translations.js +33 -54
  155. package/lib/server/translations/translationsExtractor.d.ts +12 -5
  156. package/lib/server/translations/translationsExtractor.js +159 -121
  157. package/lib/server/utils.d.ts +9 -3
  158. package/lib/server/utils.js +7 -9
  159. package/lib/server/versions/index.d.ts +3 -4
  160. package/lib/server/versions/index.js +22 -24
  161. package/lib/webpack/base.d.ts +6 -4
  162. package/lib/webpack/base.js +51 -36
  163. package/lib/webpack/client.d.ts +3 -3
  164. package/lib/webpack/client.js +12 -19
  165. package/lib/webpack/plugins/ChunkAssetPlugin.d.ts +13 -3
  166. package/lib/webpack/plugins/ChunkAssetPlugin.js +24 -17
  167. package/lib/webpack/plugins/CleanWebpackPlugin.d.ts +6 -6
  168. package/lib/webpack/plugins/CleanWebpackPlugin.js +10 -16
  169. package/lib/webpack/plugins/LogPlugin.d.ts +1 -1
  170. package/lib/webpack/plugins/LogPlugin.js +4 -5
  171. package/lib/webpack/plugins/WaitPlugin.d.ts +1 -1
  172. package/lib/webpack/plugins/WaitPlugin.js +1 -1
  173. package/lib/webpack/server.d.ts +3 -3
  174. package/lib/webpack/server.js +14 -7
  175. package/lib/{client → webpack}/templates/index.html.template.ejs +0 -0
  176. package/lib/webpack/templates/ssr.html.template.d.ts +8 -0
  177. package/lib/{client → webpack}/templates/ssr.html.template.js +5 -4
  178. package/lib/webpack/utils.d.ts +15 -30
  179. package/lib/webpack/utils.js +57 -175
  180. package/package.json +77 -70
  181. package/bin/docusaurus.js +0 -326
  182. package/lib/.tsbuildinfo +0 -5732
  183. package/lib/client/.tsbuildinfo +0 -4171
  184. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  185. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  186. package/lib/commands/swizzle.d.ts +0 -9
  187. package/lib/commands/swizzle.js +0 -245
  188. package/lib/constants.d.ts +0 -18
  189. package/lib/constants.js +0 -23
  190. package/lib/server/loadSetup.js +0 -25
  191. package/lib/server/versions/__fixtures__/dummy-plugin.js +0 -0
  192. package/lib/server/versions/__fixtures__/package.json +0 -3
  193. package/lib/server/versions/__tests/index.test.js +0 -25
  194. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  195. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  196. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  197. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  198. package/lib/webpack/sharedModuleAliases.js +0 -18
  199. package/tsconfig.client.json +0 -13
  200. package/tsconfig.json +0 -13
@@ -0,0 +1,110 @@
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.askSwizzleAction = exports.askSwizzleDangerousComponent = exports.askComponentName = exports.askThemeName = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
12
+ const prompts_1 = tslib_1.__importDefault(require("prompts"));
13
+ const common_1 = require("./common");
14
+ const ExitTitle = logger_1.default.yellow('[Exit]');
15
+ async function askThemeName(themeNames) {
16
+ const { themeName } = await (0, prompts_1.default)({
17
+ type: 'select',
18
+ name: 'themeName',
19
+ message: 'Select a theme to swizzle:',
20
+ choices: themeNames
21
+ .map((theme) => ({ title: theme, value: theme }))
22
+ .concat({ title: ExitTitle, value: '[Exit]' }),
23
+ });
24
+ if (!themeName || themeName === '[Exit]') {
25
+ process.exit(0);
26
+ }
27
+ return themeName;
28
+ }
29
+ exports.askThemeName = askThemeName;
30
+ async function askComponentName(themeComponents) {
31
+ function formatComponentName(componentName) {
32
+ const anySafe = themeComponents.hasAnySafeAction(componentName);
33
+ const allSafe = themeComponents.hasAllSafeAction(componentName);
34
+ const safestStatus = anySafe ? 'safe' : 'unsafe'; // Not 100% accurate but good enough for now.
35
+ const partiallySafe = anySafe && !allSafe;
36
+ return `${componentName}${(0, common_1.actionStatusSuffix)(safestStatus, {
37
+ partiallySafe,
38
+ })}`;
39
+ }
40
+ const { componentName } = await (0, prompts_1.default)({
41
+ type: 'autocomplete',
42
+ name: 'componentName',
43
+ message: `
44
+ Select or type the component to swizzle.
45
+ ${common_1.PartiallySafeHint} = not safe for all swizzle actions
46
+ `,
47
+ // This doesn't work well in small-height terminals (like IDE)
48
+ // limit: 30,
49
+ // This does not work well and messes up with terminal scroll position
50
+ // limit: Number.POSITIVE_INFINITY,
51
+ choices: themeComponents.all
52
+ .map((compName) => ({
53
+ title: formatComponentName(compName),
54
+ value: compName,
55
+ }))
56
+ .concat({ title: ExitTitle, value: '[Exit]' }),
57
+ async suggest(input, choices) {
58
+ return choices.filter((choice) => choice.title.toLowerCase().includes(input.toLowerCase()));
59
+ },
60
+ });
61
+ logger_1.default.newLine();
62
+ if (!componentName || componentName === '[Exit]') {
63
+ return process.exit(0);
64
+ }
65
+ return componentName;
66
+ }
67
+ exports.askComponentName = askComponentName;
68
+ async function askSwizzleDangerousComponent() {
69
+ const { switchToDanger } = await (0, prompts_1.default)({
70
+ type: 'select',
71
+ name: 'switchToDanger',
72
+ message: `Do you really want to swizzle this unsafe internal component?`,
73
+ choices: [
74
+ { title: logger_1.default.green('NO: cancel and stay safe'), value: false },
75
+ {
76
+ title: logger_1.default.red('YES: I know what I am doing!'),
77
+ value: true,
78
+ },
79
+ { title: ExitTitle, value: '[Exit]' },
80
+ ],
81
+ });
82
+ if (typeof switchToDanger === 'undefined' || switchToDanger === '[Exit]') {
83
+ return process.exit(0);
84
+ }
85
+ return !!switchToDanger;
86
+ }
87
+ exports.askSwizzleDangerousComponent = askSwizzleDangerousComponent;
88
+ async function askSwizzleAction(componentConfig) {
89
+ const { action } = await (0, prompts_1.default)({
90
+ type: 'select',
91
+ name: 'action',
92
+ message: `Which swizzle action do you want to do?`,
93
+ choices: [
94
+ {
95
+ title: `${logger_1.default.bold('Wrap')}${(0, common_1.actionStatusSuffix)(componentConfig.actions.wrap)}`,
96
+ value: 'wrap',
97
+ },
98
+ {
99
+ title: `${logger_1.default.bold('Eject')}${(0, common_1.actionStatusSuffix)(componentConfig.actions.eject)}`,
100
+ value: 'eject',
101
+ },
102
+ { title: ExitTitle, value: '[Exit]' },
103
+ ],
104
+ });
105
+ if (typeof action === 'undefined' || action === '[Exit]') {
106
+ return process.exit(0);
107
+ }
108
+ return action;
109
+ }
110
+ exports.askSwizzleAction = askSwizzleAction;
@@ -4,7 +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 React from 'react';
8
- import { DocusaurusContext } from '@docusaurus/types';
9
- declare const _default: React.Context<DocusaurusContext | null>;
10
- export default _default;
7
+ import type { ThemeComponents } from './components';
8
+ export declare function helpTables(): string;
9
+ export declare function themeComponentsTable(themeComponents: ThemeComponents): string;
@@ -0,0 +1,113 @@
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.themeComponentsTable = exports.helpTables = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
12
+ const cli_table3_1 = tslib_1.__importDefault(require("cli-table3"));
13
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
14
+ const actions_1 = require("./actions");
15
+ const common_1 = require("./common");
16
+ function tableStatusLabel(status) {
17
+ return (0, common_1.actionStatusColor)(status, (0, common_1.actionStatusLabel)(status));
18
+ }
19
+ function getStatusLabel(status) {
20
+ return (0, common_1.actionStatusColor)(status, (0, common_1.actionStatusLabel)(status));
21
+ }
22
+ function statusTable() {
23
+ const table = new cli_table3_1.default({
24
+ head: ['Status', 'CLI option', 'Description'],
25
+ });
26
+ table.push({
27
+ [tableStatusLabel('safe')]: [
28
+ '',
29
+ `
30
+ This component is safe to swizzle and was designed for this purpose.
31
+ The swizzled component is retro-compatible with minor version upgrades.
32
+ `,
33
+ ],
34
+ }, {
35
+ [tableStatusLabel('unsafe')]: [
36
+ logger_1.default.code('--danger'),
37
+ `
38
+ This component is unsafe to swizzle, but you can still do it!
39
+ Warning: we may release breaking changes within minor version upgrades.
40
+ You will have to upgrade your component manually and maintain it over time.
41
+
42
+ ${logger_1.default.green('Tip')}: your customization can't be done in a ${tableStatusLabel('safe')} way?
43
+ Report it here: https://github.com/facebook/docusaurus/discussions/5468
44
+ `,
45
+ ],
46
+ }, {
47
+ [tableStatusLabel('forbidden')]: [
48
+ '',
49
+ `
50
+ This component is not meant to be swizzled.
51
+ `,
52
+ ],
53
+ });
54
+ return table.toString();
55
+ }
56
+ function actionsTable() {
57
+ const table = new cli_table3_1.default({
58
+ head: ['Actions', 'CLI option', 'Description'],
59
+ });
60
+ table.push({
61
+ [logger_1.default.bold('Wrap')]: [
62
+ logger_1.default.code('--wrap'),
63
+ `
64
+ Creates a wrapper around the original theme component.
65
+ Allows rendering other components before/after the original theme component.
66
+
67
+ ${logger_1.default.green('Tip')}: prefer ${logger_1.default.code('--wrap')} whenever possible to reduce the amount of code to maintain.
68
+ `,
69
+ ],
70
+ }, {
71
+ [logger_1.default.bold('Eject')]: [
72
+ logger_1.default.code('--eject'),
73
+ `
74
+ Ejects the full source code of the original theme component.
75
+ Allows overriding of the original component entirely with your own UI and logic.
76
+
77
+ ${logger_1.default.green('Tip')}: ${logger_1.default.code('--eject')} can be useful for completely redesigning a component.
78
+ `,
79
+ ],
80
+ });
81
+ return table.toString();
82
+ }
83
+ function helpTables() {
84
+ return `${logger_1.default.bold('Swizzle actions')}:
85
+ ${actionsTable()}
86
+
87
+ ${logger_1.default.bold('Swizzle safety statuses')}:
88
+ ${statusTable()}
89
+
90
+ ${logger_1.default.bold('Swizzle guide')}: https://docusaurus.io/docs/swizzling`;
91
+ }
92
+ exports.helpTables = helpTables;
93
+ function themeComponentsTable(themeComponents) {
94
+ const table = new cli_table3_1.default({
95
+ head: [
96
+ 'Component name',
97
+ ...actions_1.SwizzleActions.map((action) => lodash_1.default.capitalize(action)),
98
+ 'Description',
99
+ ],
100
+ });
101
+ themeComponents.all.forEach((component) => {
102
+ table.push({
103
+ [component]: [
104
+ ...actions_1.SwizzleActions.map((action) => getStatusLabel(themeComponents.getActionStatus(component, action))),
105
+ themeComponents.getDescription(component),
106
+ ],
107
+ });
108
+ });
109
+ return `${logger_1.default.bold(`Components available for swizzle in ${logger_1.default.name(themeComponents.themeName)}`)}:
110
+ ${table.toString()}
111
+ `;
112
+ }
113
+ exports.themeComponentsTable = themeComponentsTable;
@@ -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 SwizzlePlugin } from './common';
8
+ export declare function pluginToThemeName(plugin: SwizzlePlugin): string | undefined;
9
+ export declare function getPluginByThemeName(plugins: SwizzlePlugin[], themeName: string): SwizzlePlugin;
10
+ export declare function getThemeNames(plugins: SwizzlePlugin[]): string[];
11
+ export declare function getThemeName({ themeNameParam, themeNames, list, }: {
12
+ themeNameParam: string | undefined;
13
+ themeNames: string[];
14
+ list: boolean | undefined;
15
+ }): Promise<string>;
16
+ export declare function getThemePath({ plugins, themeName, typescript, }: {
17
+ plugins: SwizzlePlugin[];
18
+ themeName: string;
19
+ typescript: boolean | undefined;
20
+ }): string;
@@ -0,0 +1,106 @@
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.getThemePath = exports.getThemeName = exports.getThemeNames = exports.getPluginByThemeName = exports.pluginToThemeName = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
12
+ const path_1 = tslib_1.__importDefault(require("path"));
13
+ const leven_1 = tslib_1.__importDefault(require("leven"));
14
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
15
+ const prompts_1 = require("./prompts");
16
+ const common_1 = require("./common");
17
+ function pluginToThemeName(plugin) {
18
+ if (plugin.instance.getThemePath) {
19
+ return (plugin.instance.version.name ?? plugin.instance.name);
20
+ }
21
+ return undefined;
22
+ }
23
+ exports.pluginToThemeName = pluginToThemeName;
24
+ function getPluginByThemeName(plugins, themeName) {
25
+ const plugin = plugins.find((p) => pluginToThemeName(p) === themeName);
26
+ if (!plugin) {
27
+ throw new Error(`Theme ${themeName} not found`);
28
+ }
29
+ return plugin;
30
+ }
31
+ exports.getPluginByThemeName = getPluginByThemeName;
32
+ function getThemeNames(plugins) {
33
+ const themeNames = lodash_1.default.uniq(
34
+ // The fact that getThemePath is attached to the plugin instance makes
35
+ // this code impossible to optimize. If this is a static method, we don't
36
+ // need to initialize all plugins just to filter which are themes
37
+ // Benchmark: loadContext-58ms; initPlugins-323ms
38
+ plugins.map((plugin) => pluginToThemeName(plugin)).filter(Boolean));
39
+ // Opinionated ordering: user is most likely to swizzle:
40
+ // - the classic theme
41
+ // - official themes
42
+ // - official plugins
43
+ return lodash_1.default.orderBy(themeNames, [
44
+ (t) => t === '@docusaurus/theme-classic',
45
+ (t) => t.includes('@docusaurus/theme'),
46
+ (t) => t.includes('@docusaurus'),
47
+ ], ['desc', 'desc', 'desc']);
48
+ }
49
+ exports.getThemeNames = getThemeNames;
50
+ // Returns a valid value if recovering is possible
51
+ function handleInvalidThemeName({ themeNameParam, themeNames, }) {
52
+ // Trying to recover invalid value
53
+ // We look for potential matches that only differ in casing.
54
+ const differentCaseMatch = (0, common_1.findStringIgnoringCase)(themeNameParam, themeNames);
55
+ if (differentCaseMatch) {
56
+ logger_1.default.warn `Theme name=${themeNameParam} doesn't exist.`;
57
+ logger_1.default.info `name=${differentCaseMatch} will be used instead of name=${themeNameParam}.`;
58
+ return differentCaseMatch;
59
+ }
60
+ // TODO recover from short theme-names here: "classic" => "@docusaurus/theme-classic"
61
+ // No recovery value is possible: print error
62
+ const suggestion = themeNames.find((name) => (0, leven_1.default)(name, themeNameParam) < 4);
63
+ logger_1.default.error `Theme name=${themeNameParam} not found. ${suggestion
64
+ ? logger_1.default.interpolate `Did you mean name=${suggestion}?`
65
+ : logger_1.default.interpolate `Themes available for swizzle: ${themeNames}`}`;
66
+ return process.exit(1);
67
+ }
68
+ async function validateThemeName({ themeNameParam, themeNames, }) {
69
+ const isValidName = themeNames.includes(themeNameParam);
70
+ if (!isValidName) {
71
+ return handleInvalidThemeName({
72
+ themeNameParam,
73
+ themeNames,
74
+ });
75
+ }
76
+ return themeNameParam;
77
+ }
78
+ async function getThemeName({ themeNameParam, themeNames, list, }) {
79
+ if (list && !themeNameParam) {
80
+ logger_1.default.info `Themes available for swizzle: name=${themeNames}`;
81
+ return process.exit(0);
82
+ }
83
+ return themeNameParam
84
+ ? validateThemeName({ themeNameParam, themeNames })
85
+ : (0, prompts_1.askThemeName)(themeNames);
86
+ }
87
+ exports.getThemeName = getThemeName;
88
+ function getThemePath({ plugins, themeName, typescript, }) {
89
+ const pluginInstance = getPluginByThemeName(plugins, themeName);
90
+ const themePath = typescript
91
+ ? pluginInstance.instance.getTypeScriptThemePath &&
92
+ path_1.default.resolve(pluginInstance.instance.path, pluginInstance.instance.getTypeScriptThemePath())
93
+ : pluginInstance.instance.getThemePath &&
94
+ path_1.default.resolve(pluginInstance.instance.path, pluginInstance.instance.getThemePath());
95
+ if (!themePath) {
96
+ logger_1.default.warn(typescript
97
+ ? logger_1.default.interpolate `name=${themeName} does not provide TypeScript theme code via ${'getTypeScriptThemePath()'}.`
98
+ : // This is... technically possible to happen, e.g. returning undefined
99
+ // from getThemePath. Plugins may intentionally or unintentionally
100
+ // disguise as themes?
101
+ logger_1.default.interpolate `name=${themeName} does not provide any theme code.`);
102
+ return process.exit(1);
103
+ }
104
+ return themePath;
105
+ }
106
+ exports.getThemePath = getThemePath;
@@ -4,9 +4,5 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import GithubSlugger from 'github-slugger';
8
- export declare function unwrapMarkdownLinks(line: string): string;
9
- export declare function transformMarkdownHeadingLine(line: string, slugger: GithubSlugger): string;
10
- export declare function transformMarkdownLine(line: string, slugger: GithubSlugger): string;
11
- export declare function transformMarkdownContent(content: string): string;
12
- export default function writeHeadingIds(siteDir: string): Promise<void>;
7
+ import { type WriteHeadingIDOptions } from '@docusaurus/utils';
8
+ export default function writeHeadingIds(siteDir: string, files?: string[], options?: WriteHeadingIDOptions): Promise<void>;
@@ -6,105 +6,48 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.transformMarkdownContent = exports.transformMarkdownLine = exports.transformMarkdownHeadingLine = exports.unwrapMarkdownLinks = void 0;
10
9
  const tslib_1 = require("tslib");
11
10
  const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
12
- const github_slugger_1 = tslib_1.__importDefault(require("github-slugger"));
13
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
11
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
12
+ const utils_1 = require("@docusaurus/utils");
14
13
  const server_1 = require("../server");
15
14
  const init_1 = tslib_1.__importDefault(require("../server/plugins/init"));
16
- const lodash_1 = require("lodash");
17
- const utils_1 = require("@docusaurus/utils");
18
15
  const utils_2 = require("../server/utils");
19
- function unwrapMarkdownLinks(line) {
20
- return line.replace(/\[([^\]]+)\]\([^)]+\)/g, (match, p1) => p1);
21
- }
22
- exports.unwrapMarkdownLinks = unwrapMarkdownLinks;
23
- function addHeadingId(line, slugger) {
24
- let headingLevel = 0;
25
- while (line.charAt(headingLevel) === '#') {
26
- headingLevel += 1;
27
- }
28
- const headingText = line.slice(headingLevel).trimEnd();
29
- const headingHashes = line.slice(0, headingLevel);
30
- const slug = slugger.slug(unwrapMarkdownLinks(headingText));
31
- return `${headingHashes}${headingText} {#${slug}}`;
32
- }
33
- function transformMarkdownHeadingLine(line, slugger) {
34
- if (!line.startsWith('#')) {
35
- throw new Error(`Line is not a markdown heading: ${line}`);
36
- }
37
- const parsedHeading = utils_1.parseMarkdownHeadingId(line);
38
- // Do not process if id is already therer
39
- if (parsedHeading.id) {
40
- return line;
41
- }
42
- return addHeadingId(line, slugger);
43
- }
44
- exports.transformMarkdownHeadingLine = transformMarkdownHeadingLine;
45
- function transformMarkdownLine(line, slugger) {
46
- // Ignore h1 headings on purpose, as we don't create anchor links for those
47
- if (line.startsWith('##')) {
48
- return transformMarkdownHeadingLine(line, slugger);
49
- }
50
- else {
51
- return line;
52
- }
53
- }
54
- exports.transformMarkdownLine = transformMarkdownLine;
55
- function transformMarkdownLines(lines) {
56
- let inCode = false;
57
- const slugger = new github_slugger_1.default();
58
- return lines.map((line) => {
59
- if (line.startsWith('```')) {
60
- inCode = !inCode;
61
- return line;
62
- }
63
- else {
64
- if (inCode) {
65
- return line;
66
- }
67
- return transformMarkdownLine(line, slugger);
68
- }
69
- });
70
- }
71
- function transformMarkdownContent(content) {
72
- return transformMarkdownLines(content.split('\n')).join('\n');
73
- }
74
- exports.transformMarkdownContent = transformMarkdownContent;
75
- async function transformMarkdownFile(filepath) {
16
+ async function transformMarkdownFile(filepath, options) {
76
17
  const content = await fs_extra_1.default.readFile(filepath, 'utf8');
77
- const updatedContent = transformMarkdownLines(content.split('\n')).join('\n');
18
+ const updatedContent = (0, utils_1.writeMarkdownHeadingId)(content, options);
78
19
  if (content !== updatedContent) {
79
20
  await fs_extra_1.default.writeFile(filepath, updatedContent);
80
21
  return filepath;
81
22
  }
82
23
  return undefined;
83
24
  }
84
- // We only handle the "paths to watch" because these are the paths where the markdown files are
85
- // Also we don't want to transform the site md docs that do not belong to a content plugin
86
- // For example ./README.md should not be transformed
25
+ /**
26
+ * We only handle the "paths to watch" because these are the paths where the
27
+ * markdown files are. Also we don't want to transform the site md docs that do
28
+ * not belong to a content plugin. For example ./README.md should not be
29
+ * transformed
30
+ */
87
31
  async function getPathsToWatch(siteDir) {
88
- const context = await server_1.loadContext(siteDir);
89
- const pluginConfigs = server_1.loadPluginConfigs(context);
90
- const plugins = await init_1.default({
32
+ const context = await (0, server_1.loadContext)(siteDir);
33
+ const pluginConfigs = await (0, server_1.loadPluginConfigs)(context);
34
+ const plugins = await (0, init_1.default)({
91
35
  pluginConfigs,
92
36
  context,
93
37
  });
94
- return lodash_1.flatten(plugins.map((plugin) => { var _a, _b; return (_b = (_a = plugin === null || plugin === void 0 ? void 0 : plugin.getPathsToWatch) === null || _a === void 0 ? void 0 : _a.call(plugin)) !== null && _b !== void 0 ? _b : []; }));
38
+ return plugins.flatMap((plugin) => plugin?.getPathsToWatch?.() ?? []);
95
39
  }
96
- async function writeHeadingIds(siteDir) {
97
- const markdownFiles = await utils_2.safeGlobby(await getPathsToWatch(siteDir), {
40
+ async function writeHeadingIds(siteDir, files, options) {
41
+ const markdownFiles = await (0, utils_2.safeGlobby)(files ?? (await getPathsToWatch(siteDir)), {
98
42
  expandDirectories: ['**/*.{md,mdx}'],
99
43
  });
100
- const result = await Promise.all(markdownFiles.map(transformMarkdownFile));
44
+ const result = await Promise.all(markdownFiles.map((p) => transformMarkdownFile(p, options)));
101
45
  const pathsModified = result.filter(Boolean);
102
46
  if (pathsModified.length) {
103
- console.log(chalk_1.default.green(`Heading ids added to markdown files (${pathsModified.length}/${markdownFiles.length} files):
104
- - ${pathsModified.join('\n- ')}`));
47
+ logger_1.default.success `Heading ids added to Markdown files (number=${`${pathsModified.length}/${markdownFiles.length}`} files): ${pathsModified}`;
105
48
  }
106
49
  else {
107
- console.log(chalk_1.default.yellow(`${markdownFiles.length} markdown files already have explicit heading ids`));
50
+ logger_1.default.warn `number=${markdownFiles.length} Markdown files already have explicit heading IDs. If you intend to overwrite the existing heading IDs, use the code=${'--overwrite'} option.`;
108
51
  }
109
52
  }
110
53
  exports.default = writeHeadingIds;
@@ -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 { ConfigOptions } from '@docusaurus/types';
8
- import { WriteTranslationsOptions } from '../server/translations/translations';
7
+ import type { ConfigOptions } from '@docusaurus/types';
8
+ import { type WriteTranslationsOptions } from '../server/translations/translations';
9
9
  export default function writeTranslations(siteDir: string, options: WriteTranslationsOptions & ConfigOptions & {
10
10
  locale?: string;
11
11
  }): Promise<void>;
@@ -1,20 +1,42 @@
1
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
+ */
2
8
  Object.defineProperty(exports, "__esModule", { value: true });
3
9
  const tslib_1 = require("tslib");
10
+ const path_1 = tslib_1.__importDefault(require("path"));
4
11
  const server_1 = require("../server");
5
12
  const init_1 = tslib_1.__importDefault(require("../server/plugins/init"));
6
13
  const translations_1 = require("../server/translations/translations");
7
14
  const translationsExtractor_1 = require("../server/translations/translationsExtractor");
8
15
  const utils_1 = require("../webpack/utils");
16
+ /**
17
+ * This is a hack, so that @docusaurus/theme-common translations are extracted!
18
+ * A theme doesn't have a way to express that one of its dependency (like
19
+ * @docusaurus/theme-common) also has translations to extract.
20
+ * Instead of introducing a new lifecycle (like `getThemeTranslationPaths()`?)
21
+ * We just make an exception and assume that user is using an official theme
22
+ */
23
+ async function getExtraSourceCodeFilePaths() {
24
+ try {
25
+ const themeCommonSourceDir = path_1.default.dirname(require.resolve('@docusaurus/theme-common/lib'));
26
+ return (0, translationsExtractor_1.globSourceCodeFilePaths)([themeCommonSourceDir]);
27
+ }
28
+ catch {
29
+ return []; // User may not use a Docusaurus official theme? Quite unlikely...
30
+ }
31
+ }
9
32
  async function writePluginTranslationFiles({ siteDir, plugin, locale, options, }) {
10
- var _a;
11
33
  if (plugin.getTranslationFiles) {
12
- const content = await ((_a = plugin.loadContent) === null || _a === void 0 ? void 0 : _a.call(plugin));
34
+ const content = await plugin.loadContent?.();
13
35
  const translationFiles = await plugin.getTranslationFiles({
14
36
  content,
15
37
  });
16
38
  await Promise.all(translationFiles.map(async (translationFile) => {
17
- await translations_1.writePluginTranslations({
39
+ await (0, translations_1.writePluginTranslations)({
18
40
  siteDir,
19
41
  plugin,
20
42
  translationFile,
@@ -25,33 +47,31 @@ async function writePluginTranslationFiles({ siteDir, plugin, locale, options, }
25
47
  }
26
48
  }
27
49
  async function writeTranslations(siteDir, options) {
28
- var _a;
29
- const context = await server_1.loadContext(siteDir, {
50
+ const context = await (0, server_1.loadContext)(siteDir, {
30
51
  customConfigFilePath: options.config,
31
52
  locale: options.locale,
32
53
  });
33
- const pluginConfigs = server_1.loadPluginConfigs(context);
34
- const plugins = init_1.default({
54
+ const pluginConfigs = await (0, server_1.loadPluginConfigs)(context);
55
+ const plugins = await (0, init_1.default)({
35
56
  pluginConfigs,
36
57
  context,
37
58
  });
38
- const locale = (_a = options.locale) !== null && _a !== void 0 ? _a : context.i18n.defaultLocale;
59
+ const locale = options.locale ?? context.i18n.defaultLocale;
39
60
  if (!context.i18n.locales.includes(locale)) {
40
- throw new Error(`Can't write-translation for locale that is not in the locale configuration file.
41
- Unknown locale=[${locale}].
42
- Available locales=[${context.i18n.locales.join(',')}]`);
61
+ throw new Error(`Can't write-translation for locale "${locale}" that is not in the locale configuration file.
62
+ Available locales are: ${context.i18n.locales.join(',')}.`);
43
63
  }
44
- const babelOptions = utils_1.getBabelOptions({
64
+ const babelOptions = (0, utils_1.getBabelOptions)({
45
65
  isServer: true,
46
- babelOptions: utils_1.getCustomBabelConfigFilePath(siteDir),
66
+ babelOptions: await (0, utils_1.getCustomBabelConfigFilePath)(siteDir),
47
67
  });
48
- const extractedCodeTranslations = await translationsExtractor_1.extractSiteSourceCodeTranslations(siteDir, plugins, babelOptions);
49
- const defaultCodeMessages = await translations_1.getPluginsDefaultCodeTranslationMessages(plugins);
50
- const codeTranslations = translations_1.applyDefaultCodeTranslations({
68
+ const extractedCodeTranslations = await (0, translationsExtractor_1.extractSiteSourceCodeTranslations)(siteDir, plugins, babelOptions, await getExtraSourceCodeFilePaths());
69
+ const defaultCodeMessages = await (0, translations_1.getPluginsDefaultCodeTranslationMessages)(plugins);
70
+ const codeTranslations = (0, translations_1.applyDefaultCodeTranslations)({
51
71
  extractedCodeTranslations,
52
72
  defaultCodeMessages,
53
73
  });
54
- await translations_1.writeCodeTranslations({ siteDir, locale }, codeTranslations, options);
74
+ await (0, translations_1.writeCodeTranslations)({ siteDir, locale }, codeTranslations, options);
55
75
  await Promise.all(plugins.map(async (plugin) => {
56
76
  await writePluginTranslationFiles({ siteDir, plugin, locale, options });
57
77
  }));
package/lib/index.d.ts CHANGED
@@ -4,12 +4,13 @@
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
- export { default as build } from './commands/build';
8
- export { default as start } from './commands/start';
9
- export { default as swizzle } from './commands/swizzle';
10
- export { default as deploy } from './commands/deploy';
11
- export { default as externalCommand } from './commands/external';
12
- export { default as serve } from './commands/serve';
13
- export { default as clear } from './commands/clear';
14
- export { default as writeTranslations } from './commands/writeTranslations';
15
- export { default as writeHeadingIds } from './commands/writeHeadingIds';
7
+ import build from './commands/build';
8
+ import clear from './commands/clear';
9
+ import deploy from './commands/deploy';
10
+ import externalCommand from './commands/external';
11
+ import serve from './commands/serve';
12
+ import start from './commands/start';
13
+ import swizzle from './commands/swizzle';
14
+ import writeHeadingIds from './commands/writeHeadingIds';
15
+ import writeTranslations from './commands/writeTranslations';
16
+ export { build, clear, deploy, externalCommand, serve, start, swizzle, writeHeadingIds, writeTranslations, };