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

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 (191) hide show
  1. package/bin/beforeCli.mjs +136 -0
  2. package/bin/docusaurus.mjs +280 -0
  3. package/lib/babel/preset.d.ts +8 -3
  4. package/lib/babel/preset.js +8 -7
  5. package/lib/choosePort.js +32 -41
  6. package/lib/client/.eslintrc.js +0 -1
  7. package/lib/client/App.d.ts +1 -2
  8. package/lib/client/App.js +19 -24
  9. package/lib/client/LinksCollector.d.ts +3 -3
  10. package/lib/client/LinksCollector.js +5 -9
  11. package/lib/client/PendingNavigation.d.ts +24 -1
  12. package/lib/client/PendingNavigation.js +5 -7
  13. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.d.ts +13 -0
  14. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.js +15 -10
  15. package/lib/client/client-lifecycles-dispatcher.d.ts +2 -5
  16. package/lib/client/client-lifecycles-dispatcher.js +5 -9
  17. package/lib/client/clientEntry.js +11 -5
  18. package/lib/client/docusaurus.d.ts +6 -0
  19. package/lib/client/docusaurus.js +17 -23
  20. package/lib/client/exports/BrowserOnly.d.ts +2 -3
  21. package/lib/client/exports/BrowserOnly.js +14 -7
  22. package/lib/client/exports/ComponentCreator.d.ts +1 -2
  23. package/lib/client/exports/ComponentCreator.js +7 -6
  24. package/lib/client/exports/ErrorBoundary.d.ts +18 -0
  25. package/lib/client/exports/ErrorBoundary.js +36 -0
  26. package/lib/client/exports/Head.d.ts +2 -3
  27. package/lib/client/exports/Head.js +3 -4
  28. package/lib/client/exports/Interpolate.d.ts +1 -1
  29. package/lib/client/exports/Interpolate.js +15 -21
  30. package/lib/client/exports/Link.d.ts +11 -5
  31. package/lib/client/exports/Link.js +29 -17
  32. package/lib/client/exports/Translate.d.ts +3 -3
  33. package/lib/client/exports/Translate.js +15 -10
  34. package/lib/client/exports/browserContext.d.ts +11 -0
  35. package/lib/client/exports/browserContext.js +22 -0
  36. package/lib/client/exports/constants.js +1 -11
  37. package/lib/client/exports/docusaurusContext.d.ts +12 -0
  38. package/lib/client/exports/docusaurusContext.js +25 -0
  39. package/lib/client/exports/isInternalUrl.js +1 -1
  40. package/lib/client/exports/renderRoutes.d.ts +1 -2
  41. package/lib/client/exports/renderRoutes.js +1 -2
  42. package/lib/client/exports/router.d.ts +1 -1
  43. package/lib/client/exports/router.js +1 -1
  44. package/lib/client/exports/useBaseUrl.js +3 -5
  45. package/lib/client/exports/useDocusaurusContext.d.ts +2 -3
  46. package/lib/client/exports/useDocusaurusContext.js +3 -9
  47. package/lib/client/exports/useGlobalData.js +4 -8
  48. package/lib/{server/versions/__tests/index.test.d.ts → client/exports/useIsBrowser.d.ts} +1 -1
  49. package/lib/client/exports/useIsBrowser.js +11 -0
  50. package/lib/client/flat.d.ts +2 -2
  51. package/lib/client/flat.js +8 -11
  52. package/lib/client/normalizeLocation.d.ts +2 -5
  53. package/lib/client/normalizeLocation.js +1 -2
  54. package/lib/client/nprogress.css +2 -2
  55. package/lib/client/prefetch.d.ts +1 -2
  56. package/lib/client/prefetch.js +1 -3
  57. package/lib/client/preload.d.ts +3 -2
  58. package/lib/client/preload.js +2 -1
  59. package/lib/client/serverEntry.d.ts +10 -0
  60. package/lib/client/serverEntry.js +90 -142
  61. package/lib/client/theme-fallback/Error/index.d.ts +10 -0
  62. package/lib/client/theme-fallback/Error/index.js +39 -0
  63. package/lib/client/theme-fallback/Layout/index.d.ts +10 -0
  64. package/lib/client/theme-fallback/Layout/index.js +10 -19
  65. package/lib/client/theme-fallback/Loading/index.d.ts +9 -0
  66. package/lib/client/theme-fallback/Loading/index.js +47 -115
  67. package/lib/client/{exports/context.js → theme-fallback/NotFound/index.d.ts} +2 -2
  68. package/lib/client/theme-fallback/NotFound/index.js +9 -16
  69. package/lib/{webpack/sharedModuleAliases.d.ts → client/theme-fallback/Root/index.d.ts} +4 -4
  70. package/lib/client/theme-fallback/Root/index.js +2 -7
  71. package/lib/commands/build.d.ts +1 -1
  72. package/lib/commands/build.js +59 -61
  73. package/lib/commands/clear.d.ts +6 -0
  74. package/lib/commands/clear.js +32 -21
  75. package/lib/commands/commandUtils.d.ts +7 -1
  76. package/lib/commands/commandUtils.js +7 -7
  77. package/lib/commands/deploy.d.ts +4 -1
  78. package/lib/commands/deploy.js +115 -71
  79. package/lib/commands/external.d.ts +2 -2
  80. package/lib/commands/external.js +4 -4
  81. package/lib/commands/serve.d.ts +1 -1
  82. package/lib/commands/serve.js +30 -16
  83. package/lib/commands/start.d.ts +1 -1
  84. package/lib/commands/start.js +100 -89
  85. package/lib/commands/swizzle/actions.d.ts +23 -0
  86. package/lib/commands/swizzle/actions.js +102 -0
  87. package/lib/commands/swizzle/common.d.ts +33 -0
  88. package/lib/commands/swizzle/common.js +57 -0
  89. package/lib/commands/swizzle/components.d.ts +29 -0
  90. package/lib/commands/swizzle/components.js +165 -0
  91. package/lib/commands/swizzle/config.d.ts +10 -0
  92. package/lib/commands/swizzle/config.js +77 -0
  93. package/lib/{client/exports → commands/swizzle}/context.d.ts +2 -4
  94. package/lib/commands/swizzle/context.js +30 -0
  95. package/lib/commands/swizzle/index.d.ts +8 -0
  96. package/lib/commands/swizzle/index.js +115 -0
  97. package/lib/commands/swizzle/prompts.d.ts +12 -0
  98. package/lib/commands/swizzle/prompts.js +110 -0
  99. package/lib/commands/swizzle/tables.d.ts +9 -0
  100. package/lib/commands/swizzle/tables.js +116 -0
  101. package/lib/commands/swizzle/themes.d.ts +20 -0
  102. package/lib/commands/swizzle/themes.js +105 -0
  103. package/lib/commands/writeHeadingIds.d.ts +9 -6
  104. package/lib/commands/writeHeadingIds.js +44 -46
  105. package/lib/commands/writeTranslations.d.ts +2 -2
  106. package/lib/commands/writeTranslations.js +36 -14
  107. package/lib/index.d.ts +10 -9
  108. package/lib/index.js +20 -19
  109. package/lib/server/brokenLinks.d.ts +1 -1
  110. package/lib/server/brokenLinks.js +38 -33
  111. package/lib/server/client-modules/index.d.ts +1 -1
  112. package/lib/server/client-modules/index.js +1 -3
  113. package/lib/server/config.d.ts +2 -2
  114. package/lib/server/config.js +10 -7
  115. package/lib/server/configValidation.d.ts +4 -2
  116. package/lib/server/configValidation.js +63 -32
  117. package/lib/server/duplicateRoutes.d.ts +1 -1
  118. package/lib/server/duplicateRoutes.js +10 -6
  119. package/lib/server/html-tags/htmlTags.js +8 -9
  120. package/lib/server/html-tags/index.d.ts +2 -2
  121. package/lib/server/html-tags/index.js +3 -3
  122. package/lib/server/i18n.d.ts +1 -2
  123. package/lib/server/i18n.js +31 -46
  124. package/lib/server/index.d.ts +9 -2
  125. package/lib/server/index.js +165 -87
  126. package/lib/server/loadSetup.d.ts +2 -3
  127. package/lib/server/loadSetup.js +5 -5
  128. package/lib/server/moduleShorthand.d.ts +9 -0
  129. package/lib/server/moduleShorthand.js +46 -0
  130. package/lib/server/plugins/applyRouteTrailingSlash.d.ts +9 -0
  131. package/lib/server/plugins/applyRouteTrailingSlash.js +19 -0
  132. package/lib/server/plugins/index.d.ts +3 -4
  133. package/lib/server/plugins/index.js +53 -37
  134. package/lib/server/plugins/init.d.ts +11 -5
  135. package/lib/server/plugins/init.js +40 -47
  136. package/lib/server/plugins/pluginIds.d.ts +2 -2
  137. package/lib/server/plugins/pluginIds.js +8 -5
  138. package/lib/server/presets/index.d.ts +3 -3
  139. package/lib/server/presets/index.js +14 -14
  140. package/lib/server/routes.d.ts +1 -1
  141. package/lib/server/routes.js +51 -28
  142. package/lib/server/themes/alias.d.ts +3 -2
  143. package/lib/server/themes/alias.js +24 -15
  144. package/lib/server/themes/index.d.ts +6 -2
  145. package/lib/server/themes/index.js +36 -24
  146. package/lib/server/translations/translations.d.ts +10 -5
  147. package/lib/server/translations/translations.js +27 -35
  148. package/lib/server/translations/translationsExtractor.d.ts +9 -4
  149. package/lib/server/translations/translationsExtractor.js +160 -119
  150. package/lib/server/utils.d.ts +9 -3
  151. package/lib/server/utils.js +8 -10
  152. package/lib/server/versions/__fixtures__/dummy-plugin.d.ts +0 -0
  153. package/lib/server/versions/index.d.ts +3 -4
  154. package/lib/server/versions/index.js +22 -21
  155. package/lib/webpack/base.d.ts +4 -4
  156. package/lib/webpack/base.js +54 -38
  157. package/lib/webpack/client.d.ts +3 -3
  158. package/lib/webpack/client.js +15 -21
  159. package/lib/webpack/plugins/ChunkAssetPlugin.d.ts +13 -3
  160. package/lib/webpack/plugins/ChunkAssetPlugin.js +17 -10
  161. package/lib/webpack/plugins/CleanWebpackPlugin.d.ts +6 -6
  162. package/lib/webpack/plugins/CleanWebpackPlugin.js +10 -16
  163. package/lib/webpack/plugins/LogPlugin.d.ts +1 -1
  164. package/lib/webpack/plugins/LogPlugin.js +5 -6
  165. package/lib/webpack/plugins/WaitPlugin.d.ts +1 -1
  166. package/lib/webpack/plugins/WaitPlugin.js +4 -4
  167. package/lib/webpack/server.d.ts +3 -3
  168. package/lib/webpack/server.js +18 -11
  169. package/lib/{client → webpack}/templates/index.html.template.ejs +0 -0
  170. package/lib/webpack/templates/ssr.html.template.d.ts +8 -0
  171. package/lib/{client → webpack}/templates/ssr.html.template.js +5 -4
  172. package/lib/webpack/utils.d.ts +9 -30
  173. package/lib/webpack/utils.js +58 -171
  174. package/package.json +76 -69
  175. package/bin/docusaurus.js +0 -326
  176. package/lib/.tsbuildinfo +0 -5732
  177. package/lib/client/.tsbuildinfo +0 -4171
  178. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  179. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  180. package/lib/commands/swizzle.d.ts +0 -9
  181. package/lib/commands/swizzle.js +0 -245
  182. package/lib/constants.d.ts +0 -18
  183. package/lib/constants.js +0 -23
  184. package/lib/server/versions/__tests/index.test.js +0 -25
  185. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  186. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  187. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  188. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  189. package/lib/webpack/sharedModuleAliases.js +0 -18
  190. package/tsconfig.client.json +0 -13
  191. package/tsconfig.json +0 -13
@@ -1,22 +1,21 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractSourceCodeFileTranslations = exports.extractAllSourceCodeFileTranslations = exports.extractSiteSourceCodeTranslations = exports.globSourceCodeFilePaths = void 0;
4
- const tslib_1 = require("tslib");
5
2
  /**
6
3
  * Copyright (c) Facebook, Inc. and its affiliates.
7
4
  *
8
5
  * This source code is licensed under the MIT license found in the
9
6
  * LICENSE file in the root directory of this source tree.
10
7
  */
11
- const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
12
- const traverse_1 = tslib_1.__importDefault(require("@babel/traverse"));
13
- const generator_1 = tslib_1.__importDefault(require("@babel/generator"));
14
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.extractSourceCodeFileTranslations = exports.extractAllSourceCodeFileTranslations = exports.extractSiteSourceCodeTranslations = exports.globSourceCodeFilePaths = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
12
+ const traverse_1 = (0, tslib_1.__importDefault)(require("@babel/traverse"));
13
+ const generator_1 = (0, tslib_1.__importDefault)(require("@babel/generator"));
14
+ const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
15
15
  const core_1 = require("@babel/core");
16
- const lodash_1 = require("lodash");
17
- const path_1 = tslib_1.__importDefault(require("path"));
18
- const constants_1 = require("../../constants");
19
- const utils_1 = require("../utils");
16
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
17
+ const utils_1 = require("@docusaurus/utils");
18
+ const utils_2 = require("../utils");
20
19
  // We only support extracting source code translations from these kind of files
21
20
  const TranslatableSourceCodeExtension = new Set([
22
21
  '.js',
@@ -24,7 +23,7 @@ const TranslatableSourceCodeExtension = new Set([
24
23
  '.ts',
25
24
  '.tsx',
26
25
  // TODO support md/mdx too? (may be overkill)
27
- // need to compile the MDX to JSX first and remove frontmatter
26
+ // need to compile the MDX to JSX first and remove front matter
28
27
  // '.md',
29
28
  // '.mdx',
30
29
  ]);
@@ -32,13 +31,14 @@ function isTranslatableSourceCodePath(filePath) {
32
31
  return TranslatableSourceCodeExtension.has(path_1.default.extname(filePath));
33
32
  }
34
33
  function getSiteSourceCodeFilePaths(siteDir) {
35
- return [path_1.default.join(siteDir, constants_1.SRC_DIR_NAME)];
34
+ return [path_1.default.join(siteDir, utils_1.SRC_DIR_NAME)];
36
35
  }
37
36
  function getPluginSourceCodeFilePaths(plugin) {
38
37
  var _a, _b, _c;
39
38
  // The getPathsToWatch() generally returns the js/jsx/ts/tsx/md/mdx file paths
40
- // We can use this method as well to know which folders we should try to extract translations from
41
- // Hacky/implicit, but do we want to introduce a new lifecycle method just for that???
39
+ // We can use this method as well to know which folders we should try to
40
+ // extract translations from. Hacky/implicit, but do we want to introduce a
41
+ // new lifecycle method just for that???
42
42
  const codePaths = (_b = (_a = plugin.getPathsToWatch) === null || _a === void 0 ? void 0 : _a.call(plugin)) !== null && _b !== void 0 ? _b : [];
43
43
  // We also include theme code
44
44
  const themePath = (_c = plugin.getThemePath) === null || _c === void 0 ? void 0 : _c.call(plugin);
@@ -48,28 +48,32 @@ function getPluginSourceCodeFilePaths(plugin) {
48
48
  return codePaths;
49
49
  }
50
50
  async function globSourceCodeFilePaths(dirPaths) {
51
- const filePaths = await utils_1.safeGlobby(dirPaths);
51
+ const filePaths = await (0, utils_2.safeGlobby)(dirPaths);
52
52
  return filePaths.filter(isTranslatableSourceCodePath);
53
53
  }
54
54
  exports.globSourceCodeFilePaths = globSourceCodeFilePaths;
55
55
  async function getSourceCodeFilePaths(siteDir, plugins) {
56
56
  const sitePaths = getSiteSourceCodeFilePaths(siteDir);
57
57
  // The getPathsToWatch() generally returns the js/jsx/ts/tsx/md/mdx file paths
58
- // We can use this method as well to know which folders we should try to extract translations from
59
- // Hacky/implicit, but do we want to introduce a new lifecycle method for that???
60
- const pluginsPaths = lodash_1.flatten(plugins.map(getPluginSourceCodeFilePaths));
58
+ // We can use this method as well to know which folders we should try to
59
+ // extract translations from. Hacky/implicit, but do we want to introduce a
60
+ // new lifecycle method for that???
61
+ const pluginsPaths = plugins.flatMap(getPluginSourceCodeFilePaths);
61
62
  const allPaths = [...sitePaths, ...pluginsPaths];
62
63
  return globSourceCodeFilePaths(allPaths);
63
64
  }
64
- async function extractSiteSourceCodeTranslations(siteDir, plugins, babelOptions) {
65
- // Should we warn here if the same translation "key" is found in multiple source code files?
65
+ async function extractSiteSourceCodeTranslations(siteDir, plugins, babelOptions, extraSourceCodeFilePaths = []) {
66
+ // Should we warn here if the same translation "key" is found in multiple
67
+ // source code files?
66
68
  function toTranslationFileContent(sourceCodeFileTranslations) {
67
- return sourceCodeFileTranslations.reduce((acc, item) => {
68
- return { ...acc, ...item.translations };
69
- }, {});
69
+ return sourceCodeFileTranslations.reduce((acc, item) => ({ ...acc, ...item.translations }), {});
70
70
  }
71
71
  const sourceCodeFilePaths = await getSourceCodeFilePaths(siteDir, plugins);
72
- const sourceCodeFilesTranslations = await extractAllSourceCodeFileTranslations(sourceCodeFilePaths, babelOptions);
72
+ const allSourceCodeFilePaths = [
73
+ ...sourceCodeFilePaths,
74
+ ...extraSourceCodeFilePaths,
75
+ ];
76
+ const sourceCodeFilesTranslations = await extractAllSourceCodeFileTranslations(allSourceCodeFilePaths, babelOptions);
73
77
  logSourceCodeFileTranslationsWarnings(sourceCodeFilesTranslations);
74
78
  return toTranslationFileContent(sourceCodeFilesTranslations);
75
79
  }
@@ -77,29 +81,31 @@ exports.extractSiteSourceCodeTranslations = extractSiteSourceCodeTranslations;
77
81
  function logSourceCodeFileTranslationsWarnings(sourceCodeFilesTranslations) {
78
82
  sourceCodeFilesTranslations.forEach(({ sourceCodeFilePath, warnings }) => {
79
83
  if (warnings.length > 0) {
80
- console.warn(`Translation extraction warnings for file path=${sourceCodeFilePath}:\n- ${chalk_1.default.yellow(warnings.join('\n\n- '))}`);
84
+ logger_1.default.warn `Translation extraction warnings for file path=${sourceCodeFilePath}: ${warnings}`;
81
85
  }
82
86
  });
83
87
  }
84
88
  async function extractAllSourceCodeFileTranslations(sourceCodeFilePaths, babelOptions) {
85
- return lodash_1.flatten(await Promise.all(sourceCodeFilePaths.map((sourceFilePath) => extractSourceCodeFileTranslations(sourceFilePath, babelOptions))));
89
+ return Promise.all(sourceCodeFilePaths.flatMap((sourceFilePath) => extractSourceCodeFileTranslations(sourceFilePath, babelOptions)));
86
90
  }
87
91
  exports.extractAllSourceCodeFileTranslations = extractAllSourceCodeFileTranslations;
88
92
  async function extractSourceCodeFileTranslations(sourceCodeFilePath, babelOptions) {
89
93
  try {
90
94
  const code = await fs_extra_1.default.readFile(sourceCodeFilePath, 'utf8');
91
- const ast = core_1.parse(code, {
95
+ const ast = (0, core_1.parse)(code, {
92
96
  ...babelOptions,
93
97
  ast: true,
94
- // filename is important, because babel does not process the same files according to their js/ts extensions
95
- // see see https://twitter.com/NicoloRibaudo/status/1321130735605002243
98
+ // filename is important, because babel does not process the same files
99
+ // according to their js/ts extensions.
100
+ // See https://twitter.com/NicoloRibaudo/status/1321130735605002243
96
101
  filename: sourceCodeFilePath,
97
102
  });
98
- return await extractSourceCodeAstTranslations(ast, sourceCodeFilePath);
103
+ const translations = await extractSourceCodeAstTranslations(ast, sourceCodeFilePath);
104
+ return translations;
99
105
  }
100
- catch (e) {
101
- e.message = `Error while attempting to extract Docusaurus translations from source code file at path=${sourceCodeFilePath}\n${e.message}`;
102
- throw e;
106
+ catch (err) {
107
+ logger_1.default.error `Error while attempting to extract Docusaurus translations from source code file at path=${sourceCodeFilePath}.`;
108
+ throw err;
103
109
  }
104
110
  }
105
111
  exports.extractSourceCodeFileTranslations = extractSourceCodeFileTranslations;
@@ -112,108 +118,143 @@ https://github.com/formatjs/formatjs/blob/main/packages/babel-plugin-formatjs/in
112
118
  https://github.com/pugjs/babel-walk
113
119
  */
114
120
  function extractSourceCodeAstTranslations(ast, sourceCodeFilePath) {
115
- function staticTranslateJSXWarningPart() {
116
- return 'Translate content could not be extracted.\nIt has to be a static string and use optional but static props, like <Translate id="my-id" description="my-description">text</Translate>.';
117
- }
118
- function sourceFileWarningPart(node) {
121
+ function sourceWarningPart(node) {
119
122
  var _a;
120
- return `File=${sourceCodeFilePath} at line=${(_a = node.loc) === null || _a === void 0 ? void 0 : _a.start.line}`;
121
- }
122
- function generateCode(node) {
123
- return generator_1.default(node).code;
123
+ return `File: ${sourceCodeFilePath} at line ${(_a = node.loc) === null || _a === void 0 ? void 0 : _a.start.line}
124
+ Full code: ${(0, generator_1.default)(node).code}`;
124
125
  }
125
126
  const translations = {};
126
127
  const warnings = [];
127
- // TODO we should check the presence of the correct @docusaurus imports here!
128
- traverse_1.default(ast, {
129
- JSXElement(path) {
130
- if (!path
131
- .get('openingElement')
132
- .get('name')
133
- .isJSXIdentifier({ name: 'Translate' })) {
128
+ let translateComponentName;
129
+ let translateFunctionName;
130
+ // First pass: find import declarations of Translate / translate.
131
+ // If not found, don't process the rest to avoid false positives
132
+ (0, traverse_1.default)(ast, {
133
+ ImportDeclaration(path) {
134
+ if (path.node.importKind === 'type' ||
135
+ path.get('source').node.value !== '@docusaurus/Translate') {
134
136
  return;
135
137
  }
136
- function evaluateJSXProp(propName) {
137
- const attributePath = path
138
- .get('openingElement.attributes')
139
- .find((attr) => attr.isJSXAttribute() &&
140
- attr
141
- .get('name')
142
- .isJSXIdentifier({ name: propName }));
143
- if (attributePath) {
144
- const attributeValue = attributePath.get('value');
145
- const attributeValueEvaluated = attributeValue.isJSXExpressionContainer()
146
- ? attributeValue.get('expression').evaluate()
147
- : attributeValue.evaluate();
148
- if (attributeValueEvaluated.confident &&
149
- typeof attributeValueEvaluated.value === 'string') {
150
- return attributeValueEvaluated.value;
151
- }
152
- else {
153
- warnings.push(`<Translate> prop=${propName} should be a statically evaluable object.\nExample: <Translate id="optional.id" description="optional description">Message</Translate>\nDynamically constructed values are not allowed, because they prevent translations to be extracted.\n${sourceFileWarningPart(path.node)}\n${generateCode(path.node)}`);
138
+ const importSpecifiers = path.get('specifiers');
139
+ const defaultImport = importSpecifiers.find((specifier) => specifier.node.type === 'ImportDefaultSpecifier');
140
+ const callbackImport = importSpecifiers.find((specifier) => specifier.node.type === 'ImportSpecifier' &&
141
+ (specifier.get('imported')
142
+ .node.name === 'translate' ||
143
+ specifier.get('imported')
144
+ .node.value === 'translate'));
145
+ translateComponentName = defaultImport === null || defaultImport === void 0 ? void 0 : defaultImport.get('local').node.name;
146
+ translateFunctionName = callbackImport === null || callbackImport === void 0 ? void 0 : callbackImport.get('local').node.name;
147
+ },
148
+ });
149
+ (0, traverse_1.default)(ast, {
150
+ ...(translateComponentName && {
151
+ JSXElement(path) {
152
+ if (!path
153
+ .get('openingElement')
154
+ .get('name')
155
+ .isJSXIdentifier({ name: translateComponentName })) {
156
+ return;
157
+ }
158
+ function evaluateJSXProp(propName) {
159
+ const attributePath = path
160
+ .get('openingElement.attributes')
161
+ .find((attr) => attr.isJSXAttribute() &&
162
+ attr
163
+ .get('name')
164
+ .isJSXIdentifier({ name: propName }));
165
+ if (attributePath) {
166
+ const attributeValue = attributePath.get('value');
167
+ const attributeValueEvaluated = attributeValue.isJSXExpressionContainer()
168
+ ? attributeValue.get('expression').evaluate()
169
+ : attributeValue.evaluate();
170
+ if (attributeValueEvaluated.confident &&
171
+ typeof attributeValueEvaluated.value === 'string') {
172
+ return attributeValueEvaluated.value;
173
+ }
174
+ warnings.push(`<Translate> prop=${propName} should be a statically evaluable object.
175
+ Example: <Translate id="optional id" description="optional description">Message</Translate>
176
+ Dynamically constructed values are not allowed, because they prevent translations to be extracted.
177
+ ${sourceWarningPart(path.node)}`);
154
178
  }
179
+ return undefined;
155
180
  }
156
- return undefined;
157
- }
158
- // We only handle the optimistic case where we have a single non-empty content
159
- const singleChildren = path
160
- .get('children')
161
- // Remove empty/useless text nodes that might be around our translation!
162
- // Makes the translation system more reliable to JSX formatting issues
163
- .filter((childrenPath) => !(childrenPath.isJSXText() &&
164
- childrenPath.node.value.replace('\n', '').trim() === ''))
165
- .pop();
166
- if (singleChildren && singleChildren.isJSXText()) {
167
- const message = singleChildren.node.value.trim().replace(/\s+/g, ' ');
168
181
  const id = evaluateJSXProp('id');
169
182
  const description = evaluateJSXProp('description');
170
- translations[id !== null && id !== void 0 ? id : message] = {
171
- message,
172
- ...(description && { description }),
173
- };
174
- }
175
- else if (singleChildren &&
176
- singleChildren.isJSXExpressionContainer() &&
177
- singleChildren.get('expression').evaluate().confident) {
178
- const message = singleChildren.get('expression').evaluate().value;
179
- const id = evaluateJSXProp('id');
180
- const description = evaluateJSXProp('description');
181
- translations[id !== null && id !== void 0 ? id : message] = {
182
- message,
183
- ...(description && { description }),
184
- };
185
- }
186
- else {
187
- warnings.push(`${staticTranslateJSXWarningPart()}\n${sourceFileWarningPart(path.node)}\n${generateCode(path.node)}`);
188
- }
189
- },
190
- CallExpression(path) {
191
- if (!path.get('callee').isIdentifier({ name: 'translate' })) {
192
- return;
193
- }
194
- // console.log('CallExpression', path.node);
195
- const args = path.get('arguments');
196
- if (args.length === 1 || args.length === 2) {
197
- const firstArgPath = args[0];
198
- // evaluation allows translate("x" + "y"); to be considered as translate("xy");
199
- const firstArgEvaluated = firstArgPath.evaluate();
200
- // console.log('firstArgEvaluated', firstArgEvaluated);
201
- if (firstArgEvaluated.confident &&
202
- typeof firstArgEvaluated.value === 'object') {
203
- const { message, id, description } = firstArgEvaluated.value;
183
+ let message;
184
+ const childrenPath = path.get('children');
185
+ // Handle empty content
186
+ if (!childrenPath.length) {
187
+ if (!id) {
188
+ warnings.push(`<Translate> without children must have id prop.
189
+ Example: <Translate id="my-id" />
190
+ ${sourceWarningPart(path.node)}`);
191
+ }
192
+ else {
193
+ translations[id] = {
194
+ message: id,
195
+ ...(description && { description }),
196
+ };
197
+ }
198
+ return;
199
+ }
200
+ // Handle single non-empty content
201
+ const singleChildren = childrenPath
202
+ // Remove empty/useless text nodes that might be around our
203
+ // translation! Makes the translation system more reliable to JSX
204
+ // formatting issues
205
+ .filter((children) => !(children.isJSXText() &&
206
+ children.node.value.replace('\n', '').trim() === ''))
207
+ .pop();
208
+ const isJSXText = singleChildren && singleChildren.isJSXText();
209
+ const isJSXExpressionContainer = singleChildren &&
210
+ singleChildren.isJSXExpressionContainer() &&
211
+ singleChildren.get('expression').evaluate().confident;
212
+ if (isJSXText || isJSXExpressionContainer) {
213
+ message = isJSXText
214
+ ? singleChildren.node.value.trim().replace(/\s+/g, ' ')
215
+ : singleChildren.get('expression').evaluate().value;
204
216
  translations[id !== null && id !== void 0 ? id : message] = {
205
217
  message,
206
218
  ...(description && { description }),
207
219
  };
208
220
  }
209
221
  else {
210
- warnings.push(`translate() first arg should be a statically evaluable object.\nExample: translate({message: "text",id: "optional.id",description: "optional description"}\nDynamically constructed values are not allowed, because they prevent translations to be extracted.\n${sourceFileWarningPart(path.node)}\n${generateCode(path.node)}`);
222
+ warnings.push(`Translate content could not be extracted. It has to be a static string and use optional but static props, like <Translate id="my-id" description="my-description">text</Translate>.
223
+ ${sourceWarningPart(path.node)}`);
211
224
  }
212
- }
213
- else {
214
- warnings.push(`translate() function only takes 1 or 2 args\n${sourceFileWarningPart(path.node)}\n${generateCode(path.node)}`);
215
- }
216
- },
225
+ },
226
+ }),
227
+ ...(translateFunctionName && {
228
+ CallExpression(path) {
229
+ if (!path.get('callee').isIdentifier({ name: translateFunctionName })) {
230
+ return;
231
+ }
232
+ const args = path.get('arguments');
233
+ if (args.length === 1 || args.length === 2) {
234
+ const firstArgPath = args[0];
235
+ // translate("x" + "y"); => translate("xy");
236
+ const firstArgEvaluated = firstArgPath.evaluate();
237
+ if (firstArgEvaluated.confident &&
238
+ typeof firstArgEvaluated.value === 'object') {
239
+ const { message, id, description } = firstArgEvaluated.value;
240
+ translations[id !== null && id !== void 0 ? id : message] = {
241
+ message: message !== null && message !== void 0 ? message : id,
242
+ ...(description && { description }),
243
+ };
244
+ }
245
+ else {
246
+ warnings.push(`translate() first arg should be a statically evaluable object.
247
+ Example: translate({message: "text",id: "optional.id",description: "optional description"}
248
+ Dynamically constructed values are not allowed, because they prevent translations to be extracted.
249
+ ${sourceWarningPart(path.node)}`);
250
+ }
251
+ }
252
+ else {
253
+ warnings.push(`translate() function only takes 1 or 2 args
254
+ ${sourceWarningPart(path.node)}`);
255
+ }
256
+ },
257
+ }),
217
258
  });
218
259
  return { sourceCodeFilePath, translations, warnings };
219
260
  }
@@ -1,4 +1,10 @@
1
- import { RouteConfig } from '@docusaurus/types';
2
- import globby from 'globby';
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 { RouteConfig } from '@docusaurus/types';
8
+ import { Globby } from '@docusaurus/utils';
3
9
  export declare function getAllFinalRoutes(routeConfig: RouteConfig[]): RouteConfig[];
4
- export declare function safeGlobby(patterns: string[], options?: globby.GlobbyOptions): Promise<string[]>;
10
+ export declare function safeGlobby(patterns: string[], options?: Globby.GlobbyOptions): Promise<string[]>;
@@ -1,23 +1,21 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.safeGlobby = exports.getAllFinalRoutes = void 0;
4
- const tslib_1 = require("tslib");
5
2
  /**
6
3
  * Copyright (c) Facebook, Inc. and its affiliates.
7
4
  *
8
5
  * This source code is licensed under the MIT license found in the
9
6
  * LICENSE file in the root directory of this source tree.
10
7
  */
11
- const lodash_1 = require("lodash");
12
- const globby_1 = tslib_1.__importDefault(require("globby"));
13
- const path_1 = tslib_1.__importDefault(require("path"));
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.safeGlobby = exports.getAllFinalRoutes = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
14
12
  const utils_1 = require("@docusaurus/utils");
15
13
  // Recursively get the final routes (routes with no subroutes)
16
14
  function getAllFinalRoutes(routeConfig) {
17
15
  function getFinalRoutes(route) {
18
- return route.routes ? lodash_1.flatMap(route.routes, getFinalRoutes) : [route];
16
+ return route.routes ? route.routes.flatMap(getFinalRoutes) : [route];
19
17
  }
20
- return lodash_1.flatMap(routeConfig, getFinalRoutes);
18
+ return routeConfig.flatMap(getFinalRoutes);
21
19
  }
22
20
  exports.getAllFinalRoutes = getAllFinalRoutes;
23
21
  // Globby that fix Windows path patterns
@@ -25,7 +23,7 @@ exports.getAllFinalRoutes = getAllFinalRoutes;
25
23
  async function safeGlobby(patterns, options) {
26
24
  // Required for Windows support, as paths using \ should not be used by globby
27
25
  // (also using the windows hard drive prefix like c: is not a good idea)
28
- const globPaths = patterns.map((dirPath) => utils_1.posixPath(path_1.default.relative(process.cwd(), dirPath)));
29
- return globby_1.default(globPaths, options);
26
+ const globPaths = patterns.map((dirPath) => (0, utils_1.posixPath)(path_1.default.relative(process.cwd(), dirPath)));
27
+ return (0, utils_1.Globby)(globPaths, options);
30
28
  }
31
29
  exports.safeGlobby = safeGlobby;
@@ -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 { DocusaurusPluginVersionInformation } from '@docusaurus/types';
8
- export declare function getPackageJsonVersion(packageJsonPath: string): string | undefined;
9
- export declare function getPackageJsonName(packageJsonPath: string): string | undefined;
10
- export declare function getPluginVersion(pluginPath: string, siteDir: string): DocusaurusPluginVersionInformation;
7
+ import type { DocusaurusPluginVersionInformation } from '@docusaurus/types';
8
+ export declare function getPackageJsonVersion(packageJsonPath: string): Promise<string | undefined>;
9
+ export declare function getPluginVersion(pluginPath: string, siteDir: string): Promise<DocusaurusPluginVersionInformation>;
@@ -6,45 +6,46 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.getPluginVersion = exports.getPackageJsonName = exports.getPackageJsonVersion = void 0;
10
- const fs_extra_1 = require("fs-extra");
11
- const path_1 = require("path");
12
- function getPackageJsonVersion(packageJsonPath) {
13
- if (fs_extra_1.existsSync(packageJsonPath)) {
9
+ exports.getPluginVersion = exports.getPackageJsonVersion = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
12
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
13
+ async function getPackageJsonVersion(packageJsonPath) {
14
+ if (await fs_extra_1.default.pathExists(packageJsonPath)) {
14
15
  // eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-dynamic-require, global-require
15
- const { version } = require(packageJsonPath);
16
- return typeof version === 'string' ? version : undefined;
16
+ return require(packageJsonPath).version;
17
17
  }
18
18
  return undefined;
19
19
  }
20
20
  exports.getPackageJsonVersion = getPackageJsonVersion;
21
- function getPackageJsonName(packageJsonPath) {
22
- if (fs_extra_1.existsSync(packageJsonPath)) {
21
+ async function getPackageJsonName(packageJsonPath) {
22
+ if (await fs_extra_1.default.pathExists(packageJsonPath)) {
23
23
  // eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-dynamic-require, global-require
24
- const { name } = require(packageJsonPath);
25
- return typeof name === 'string' ? name : undefined;
24
+ return require(packageJsonPath).name;
26
25
  }
27
26
  return undefined;
28
27
  }
29
- exports.getPackageJsonName = getPackageJsonName;
30
- function getPluginVersion(pluginPath, siteDir) {
31
- let potentialPluginPackageJsonDirectory = path_1.dirname(pluginPath);
28
+ async function getPluginVersion(pluginPath, siteDir) {
29
+ let potentialPluginPackageJsonDirectory = path_1.default.dirname(pluginPath);
32
30
  while (potentialPluginPackageJsonDirectory !== '/') {
33
- const packageJsonPath = path_1.join(potentialPluginPackageJsonDirectory, 'package.json');
34
- if (fs_extra_1.existsSync(packageJsonPath) && fs_extra_1.lstatSync(packageJsonPath).isFile()) {
31
+ const packageJsonPath = path_1.default.join(potentialPluginPackageJsonDirectory, 'package.json');
32
+ if ((await fs_extra_1.default.pathExists(packageJsonPath)) &&
33
+ (await fs_extra_1.default.lstat(packageJsonPath)).isFile()) {
35
34
  if (potentialPluginPackageJsonDirectory === siteDir) {
36
- // If the plugin belongs to the same docusaurus project, we classify it as local plugin.
35
+ // If the plugin belongs to the same docusaurus project, we classify it
36
+ // as local plugin.
37
37
  return { type: 'project' };
38
38
  }
39
39
  return {
40
40
  type: 'package',
41
- name: getPackageJsonName(packageJsonPath),
42
- version: getPackageJsonVersion(packageJsonPath),
41
+ name: await getPackageJsonName(packageJsonPath),
42
+ version: await getPackageJsonVersion(packageJsonPath),
43
43
  };
44
44
  }
45
- potentialPluginPackageJsonDirectory = path_1.dirname(potentialPluginPackageJsonDirectory);
45
+ potentialPluginPackageJsonDirectory = path_1.default.dirname(potentialPluginPackageJsonDirectory);
46
46
  }
47
- // In rare cases where a plugin is a path where no parent directory contains package.json, we can only classify it as local.
47
+ // In the case where a plugin is a path where no parent directory contains
48
+ // package.json (e.g. inline plugin), we can only classify it as local.
48
49
  return { type: 'local' };
49
50
  }
50
51
  exports.getPluginVersion = getPluginVersion;
@@ -4,9 +4,9 @@
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 { Configuration } from 'webpack';
8
- import { Props } from '@docusaurus/types';
7
+ import type { Configuration } from 'webpack';
8
+ import type { Props } from '@docusaurus/types';
9
9
  export declare const clientDir: string;
10
10
  export declare function excludeJS(modulePath: string): boolean;
11
- export declare function getDocusaurusAliases(): Record<string, string>;
12
- export declare function createBaseConfig(props: Props, isServer: boolean, minify?: boolean): Configuration;
11
+ export declare function getDocusaurusAliases(): Promise<Record<string, string>>;
12
+ export declare function createBaseConfig(props: Props, isServer: boolean, minify?: boolean): Promise<Configuration>;