@docusaurus/core 2.0.0-beta.15a2b59f9 → 2.0.0-beta.17

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 (189) hide show
  1. package/bin/beforeCli.mjs +136 -0
  2. package/bin/{docusaurus.js → docusaurus.mjs} +63 -108
  3. package/lib/babel/preset.d.ts +8 -3
  4. package/lib/babel/preset.js +8 -7
  5. package/lib/choosePort.js +29 -38
  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 +6 -10
  17. package/lib/client/clientEntry.js +11 -5
  18. package/lib/client/docusaurus.d.ts +6 -0
  19. package/lib/client/docusaurus.js +16 -25
  20. package/lib/client/exports/BrowserOnly.d.ts +2 -3
  21. package/lib/client/exports/BrowserOnly.js +13 -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 +35 -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 +16 -22
  30. package/lib/client/exports/Link.d.ts +11 -5
  31. package/lib/client/exports/Link.js +24 -19
  32. package/lib/client/exports/Translate.d.ts +3 -3
  33. package/lib/client/exports/Translate.js +14 -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 +1 -5
  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 +50 -54
  73. package/lib/commands/clear.d.ts +6 -0
  74. package/lib/commands/clear.js +30 -19
  75. package/lib/commands/commandUtils.d.ts +7 -1
  76. package/lib/commands/commandUtils.js +6 -6
  77. package/lib/commands/deploy.d.ts +4 -1
  78. package/lib/commands/deploy.js +102 -66
  79. package/lib/commands/external.d.ts +2 -2
  80. package/lib/commands/external.js +3 -3
  81. package/lib/commands/serve.d.ts +1 -1
  82. package/lib/commands/serve.js +13 -19
  83. package/lib/commands/start.d.ts +1 -1
  84. package/lib/commands/start.js +93 -83
  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 +56 -0
  89. package/lib/commands/swizzle/components.d.ts +29 -0
  90. package/lib/commands/swizzle/components.js +162 -0
  91. package/lib/commands/swizzle/config.d.ts +10 -0
  92. package/lib/commands/swizzle/config.js +80 -0
  93. package/lib/{server/loadSetup.d.ts → commands/swizzle/context.d.ts} +2 -3
  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/{client/exports/context.d.ts → commands/swizzle/tables.d.ts} +3 -4
  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 +103 -0
  103. package/lib/commands/writeHeadingIds.d.ts +9 -6
  104. package/lib/commands/writeHeadingIds.js +41 -43
  105. package/lib/commands/writeTranslations.d.ts +2 -2
  106. package/lib/commands/writeTranslations.js +35 -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 +57 -38
  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 +7 -4
  115. package/lib/server/configValidation.d.ts +2 -2
  116. package/lib/server/configValidation.js +43 -28
  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 +2 -4
  120. package/lib/server/html-tags/index.d.ts +1 -1
  121. package/lib/server/html-tags/index.js +1 -1
  122. package/lib/server/i18n.d.ts +1 -2
  123. package/lib/server/i18n.js +32 -46
  124. package/lib/server/index.d.ts +2 -2
  125. package/lib/server/index.js +147 -68
  126. package/lib/server/moduleShorthand.d.ts +9 -0
  127. package/lib/server/moduleShorthand.js +46 -0
  128. package/lib/server/plugins/applyRouteTrailingSlash.d.ts +2 -2
  129. package/lib/server/plugins/applyRouteTrailingSlash.js +1 -1
  130. package/lib/server/plugins/index.d.ts +2 -2
  131. package/lib/server/plugins/index.js +34 -35
  132. package/lib/server/plugins/init.d.ts +12 -2
  133. package/lib/server/plugins/init.js +48 -58
  134. package/lib/server/plugins/pluginIds.d.ts +1 -1
  135. package/lib/server/plugins/pluginIds.js +8 -5
  136. package/lib/server/presets/index.d.ts +3 -3
  137. package/lib/server/presets/index.js +12 -13
  138. package/lib/server/routes.d.ts +1 -1
  139. package/lib/server/routes.js +50 -29
  140. package/lib/server/themes/alias.d.ts +3 -2
  141. package/lib/server/themes/alias.js +22 -14
  142. package/lib/server/themes/index.d.ts +3 -3
  143. package/lib/server/themes/index.js +26 -26
  144. package/lib/server/translations/translations.d.ts +7 -1
  145. package/lib/server/translations/translations.js +30 -45
  146. package/lib/server/translations/translationsExtractor.d.ts +9 -3
  147. package/lib/server/translations/translationsExtractor.js +159 -120
  148. package/lib/server/utils.d.ts +9 -3
  149. package/lib/server/utils.js +7 -9
  150. package/lib/server/versions/__fixtures__/dummy-plugin.d.ts +0 -0
  151. package/lib/server/versions/index.d.ts +3 -4
  152. package/lib/server/versions/index.js +22 -21
  153. package/lib/webpack/base.d.ts +4 -4
  154. package/lib/webpack/base.js +38 -33
  155. package/lib/webpack/client.d.ts +3 -3
  156. package/lib/webpack/client.js +12 -19
  157. package/lib/webpack/plugins/ChunkAssetPlugin.d.ts +13 -3
  158. package/lib/webpack/plugins/ChunkAssetPlugin.js +17 -10
  159. package/lib/webpack/plugins/CleanWebpackPlugin.d.ts +6 -6
  160. package/lib/webpack/plugins/CleanWebpackPlugin.js +8 -14
  161. package/lib/webpack/plugins/LogPlugin.d.ts +1 -1
  162. package/lib/webpack/plugins/LogPlugin.js +4 -5
  163. package/lib/webpack/plugins/WaitPlugin.d.ts +1 -1
  164. package/lib/webpack/plugins/WaitPlugin.js +1 -1
  165. package/lib/webpack/server.d.ts +3 -3
  166. package/lib/webpack/server.js +9 -8
  167. package/lib/{client → webpack}/templates/index.html.template.ejs +0 -0
  168. package/lib/webpack/templates/ssr.html.template.d.ts +8 -0
  169. package/lib/{client → webpack}/templates/ssr.html.template.js +3 -2
  170. package/lib/webpack/utils.d.ts +7 -29
  171. package/lib/webpack/utils.js +54 -171
  172. package/package.json +74 -69
  173. package/lib/.tsbuildinfo +0 -1
  174. package/lib/client/.tsbuildinfo +0 -1
  175. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  176. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  177. package/lib/commands/swizzle.d.ts +0 -9
  178. package/lib/commands/swizzle.js +0 -245
  179. package/lib/constants.d.ts +0 -18
  180. package/lib/constants.js +0 -23
  181. package/lib/server/loadSetup.js +0 -25
  182. package/lib/server/versions/__tests/index.test.js +0 -25
  183. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  184. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  185. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  186. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  187. package/lib/webpack/sharedModuleAliases.js +0 -18
  188. package/tsconfig.client.json +0 -13
  189. package/tsconfig.json +0 -13
@@ -0,0 +1,136 @@
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
+
8
+ // @ts-check
9
+
10
+ import logger from '@docusaurus/logger';
11
+ import fs from 'fs-extra';
12
+ import semver from 'semver';
13
+ import path from 'path';
14
+ import updateNotifier from 'update-notifier';
15
+ import boxen from 'boxen';
16
+ import {createRequire} from 'module';
17
+
18
+ const packageJson = createRequire(import.meta.url)('../package.json');
19
+ const sitePkg = createRequire(path.join(process.cwd(), 'package.json'))(
20
+ './package.json',
21
+ );
22
+
23
+ const {
24
+ name,
25
+ version,
26
+ engines: {node: requiredVersion},
27
+ } = packageJson;
28
+
29
+ /**
30
+ * Notify user if `@docusaurus` packages are outdated
31
+ *
32
+ * Note: this is a 2-step process to avoid delaying cli usage by awaiting a
33
+ * response:
34
+ * - 1st run: trigger background job to check releases + store result
35
+ * - 2nd run: display potential update to users
36
+ *
37
+ * cache data is stored in `~/.config/configstore/update-notifier-@docusaurus`
38
+ */
39
+ export default async function beforeCli() {
40
+ const notifier = updateNotifier({
41
+ pkg: {
42
+ name,
43
+ version,
44
+ },
45
+ // Check is in background so it's fine to use a small value like 1h
46
+ // Use 0 for debugging
47
+ updateCheckInterval: 1000 * 60 * 60,
48
+ // updateCheckInterval: 0
49
+ });
50
+
51
+ // Hacky way to ensure we check for updates on first run
52
+ // Note: the notification will only happen in the 2nd run
53
+ // See https://github.com/yeoman/update-notifier/issues/209
54
+ try {
55
+ if (
56
+ notifier.config &&
57
+ // @ts-expect-error: this is an internal API
58
+ !notifier.disabled &&
59
+ Date.now() - notifier.config.get('lastUpdateCheck') < 50
60
+ ) {
61
+ notifier.config.set('lastUpdateCheck', 0);
62
+ notifier.check();
63
+ }
64
+ } catch (err) {
65
+ // Do not stop cli if this fails, see https://github.com/facebook/docusaurus/issues/5400
66
+ logger.error(err);
67
+ }
68
+
69
+ /**
70
+ * We don't want to display update message for canary releases.
71
+ * See https://github.com/facebook/docusaurus/issues/5378
72
+ * @param {import('update-notifier').UpdateInfo} update
73
+ */
74
+ function ignoreUpdate(update) {
75
+ const isCanaryRelease =
76
+ update && update.current && update.current.startsWith('0.0.0');
77
+ return isCanaryRelease;
78
+ }
79
+
80
+ if (
81
+ notifier.config &&
82
+ notifier.update &&
83
+ semver.lt(notifier.update.current, notifier.update.latest)
84
+ ) {
85
+ // Because notifier clears cached data after reading it, leading to notifier
86
+ // not consistently displaying the update.
87
+ // See https://github.com/yeoman/update-notifier/issues/209
88
+ notifier.config.set('update', notifier.update);
89
+
90
+ if (ignoreUpdate(notifier.update)) {
91
+ return;
92
+ }
93
+
94
+ const siteDocusaurusPackagesForUpdate = Object.keys({
95
+ ...sitePkg.dependencies,
96
+ ...sitePkg.devDependencies,
97
+ })
98
+ .filter((p) => p.startsWith('@docusaurus'))
99
+ .map((p) => p.concat('@latest'))
100
+ .join(' ');
101
+ const isYarnUsed = await fs.pathExists(
102
+ path.resolve(process.cwd(), 'yarn.lock'),
103
+ );
104
+ const upgradeCommand = isYarnUsed
105
+ ? `yarn upgrade ${siteDocusaurusPackagesForUpdate}`
106
+ : `npm i ${siteDocusaurusPackagesForUpdate}`;
107
+
108
+ /** @type {import('boxen').Options} */
109
+ const boxenOptions = {
110
+ padding: 1,
111
+ margin: 1,
112
+ align: 'center',
113
+ borderColor: 'yellow',
114
+ borderStyle: 'round',
115
+ };
116
+
117
+ const docusaurusUpdateMessage = boxen(
118
+ `Update available ${logger.dim(
119
+ `${notifier.update.current}`,
120
+ )} → ${logger.green(`${notifier.update.latest}`)}
121
+
122
+ To upgrade Docusaurus packages with the latest version, run the following command:
123
+ ${logger.code(upgradeCommand)}`,
124
+ boxenOptions,
125
+ );
126
+
127
+ console.log(docusaurusUpdateMessage);
128
+ }
129
+
130
+ // notify user if node version needs to be updated
131
+ if (!semver.satisfies(process.version, requiredVersion)) {
132
+ logger.error('Minimum Node.js version not met :(');
133
+ logger.info`You are using Node.js number=${process.version}, Requirement: Node.js number=${requiredVersion}.`;
134
+ process.exit(1);
135
+ }
136
+ }
@@ -1,7 +1,4 @@
1
1
  #!/usr/bin/env node
2
-
3
- // TODO remove when fixed: https://github.com/Stuk/eslint-plugin-header/issues/39
4
- /* eslint-disable header/header */
5
2
  /**
6
3
  * Copyright (c) Facebook, Inc. and its affiliates.
7
4
  *
@@ -9,14 +6,13 @@
9
6
  * LICENSE file in the root directory of this source tree.
10
7
  */
11
8
 
12
- const chalk = require('chalk');
13
- const fs = require('fs-extra');
14
- const semver = require('semver');
15
- const path = require('path');
16
- const cli = require('commander');
17
- const updateNotifier = require('update-notifier');
18
- const boxen = require('boxen');
19
- const {
9
+ // @ts-check
10
+
11
+ import logger from '@docusaurus/logger';
12
+ import fs from 'fs-extra';
13
+ import cli from 'commander';
14
+ import {createRequire} from 'module';
15
+ import {
20
16
  build,
21
17
  swizzle,
22
18
  deploy,
@@ -26,79 +22,23 @@ const {
26
22
  clear,
27
23
  writeTranslations,
28
24
  writeHeadingIds,
29
- } = require('../lib');
30
- const {
31
- name,
32
- version,
33
- engines: {node: requiredVersion},
34
- } = require('../package.json');
35
-
36
- // notify user if @docusaurus packages is outdated
37
- const notifier = updateNotifier({
38
- pkg: {
39
- name,
40
- version,
41
- },
42
- });
43
-
44
- // allow the user to be notified for updates on the first run
45
- if (notifier.lastUpdateCheck === Date.now()) {
46
- notifier.lastUpdateCheck = 0;
47
- }
48
-
49
- if (notifier.update && semver.gt(this.update.latest, this.update.current)) {
50
- // eslint-disable-next-line import/no-dynamic-require, global-require
51
- const sitePkg = require(path.resolve(process.cwd(), 'package.json'));
52
- const siteDocusaurusPackagesForUpdate = Object.keys(sitePkg.dependencies)
53
- .filter((p) => p.startsWith('@docusaurus'))
54
- .map((p) => p.concat('@latest'))
55
- .join(' ');
56
- const isYarnUsed = fs.existsSync(path.resolve(process.cwd(), 'yarn.lock'));
57
- const upgradeCommand = isYarnUsed
58
- ? `yarn upgrade ${siteDocusaurusPackagesForUpdate}`
59
- : `npm i ${siteDocusaurusPackagesForUpdate}`;
25
+ } from '../lib/index.js';
26
+ import beforeCli from './beforeCli.mjs';
60
27
 
61
- const boxenOptions = {
62
- padding: 1,
63
- margin: 1,
64
- align: 'center',
65
- borderColor: 'yellow',
66
- borderStyle: 'round',
67
- };
28
+ await beforeCli();
68
29
 
69
- const docusaurusUpdateMessage = boxen(
70
- `Update available ${chalk.dim(`${notifier.update.current}`)}${chalk.reset(
71
- ' → ',
72
- )}${chalk.green(
73
- `${notifier.update.latest}`,
74
- )}\n\nTo upgrade Docusaurus packages with the latest version, run the following command:\n${chalk.cyan(
75
- `${upgradeCommand}`,
76
- )}`,
77
- boxenOptions,
78
- );
79
-
80
- console.log(docusaurusUpdateMessage);
81
- }
82
-
83
- // notify user if node version needs to be updated
84
- if (!semver.satisfies(process.version, requiredVersion)) {
85
- console.log(
86
- chalk.red(`\nMinimum Node.js version not met :(`) +
87
- chalk.yellow(
88
- `\n\nYou are using Node.js ${process.version}. We require Node.js ${requiredVersion} or up!\n`,
89
- ),
90
- );
91
- process.exit(1);
92
- }
30
+ const resolveDir = (dir = '.') => fs.realpath(dir);
93
31
 
94
- cli.version(require('../package.json').version).usage('<command> [options]');
32
+ cli
33
+ .version(createRequire(import.meta.url)('../package.json').version)
34
+ .usage('<command> [options]');
95
35
 
96
36
  cli
97
37
  .command('build [siteDir]')
98
38
  .description('Build website.')
99
39
  .option(
100
40
  '--bundle-analyzer',
101
- 'visualize size of webpack output files with an interactive zoomable treemap (default: false)',
41
+ 'visualize size of webpack output files with an interactive zoomable tree map (default: false)',
102
42
  )
103
43
  .option(
104
44
  '--out-dir <dir>',
@@ -116,8 +56,8 @@ cli
116
56
  '--no-minify',
117
57
  'build website without minimizing JS bundles (default: false)',
118
58
  )
119
- .action((siteDir = '.', {bundleAnalyzer, config, outDir, locale, minify}) => {
120
- build(path.resolve(siteDir), {
59
+ .action(async (siteDir, {bundleAnalyzer, config, outDir, locale, minify}) => {
60
+ build(await resolveDir(siteDir), {
121
61
  bundleAnalyzer,
122
62
  outDir,
123
63
  config,
@@ -128,20 +68,28 @@ cli
128
68
 
129
69
  cli
130
70
  .command('swizzle [themeName] [componentName] [siteDir]')
131
- .description('Copy the theme files into website folder for customization.')
71
+ .description(
72
+ 'Wraps or ejects the original theme files into website folder for customization.',
73
+ )
74
+ .option(
75
+ '-w, --wrap',
76
+ 'Creates a wrapper around the original theme component.\nAllows rendering other components before/after the original theme component.',
77
+ )
78
+ .option(
79
+ '-e, --eject',
80
+ 'Ejects the full source code of the original theme component.\nAllows overriding the original component entirely with your own UI and logic.',
81
+ )
82
+ .option(
83
+ '-l, --list',
84
+ 'only list the available themes/components without further prompting (default: false)',
85
+ )
132
86
  .option(
133
- '--typescript',
87
+ '-t, --typescript',
134
88
  'copy TypeScript theme files when possible (default: false)',
135
89
  )
136
- .option('--danger', 'enable swizzle for internal component of themes')
137
- .action((themeName, componentName, siteDir = '.', {typescript, danger}) => {
138
- swizzle(
139
- path.resolve(siteDir),
140
- themeName,
141
- componentName,
142
- typescript,
143
- danger,
144
- );
90
+ .option('--danger', 'enable swizzle for unsafe component of themes')
91
+ .action(async (themeName, componentName, siteDir, options) => {
92
+ swizzle(await resolveDir(siteDir), themeName, componentName, options);
145
93
  });
146
94
 
147
95
  cli
@@ -163,8 +111,8 @@ cli
163
111
  '--skip-build',
164
112
  'skip building website before deploy it (default: false)',
165
113
  )
166
- .action((siteDir = '.', {outDir, skipBuild, config}) => {
167
- deploy(path.resolve(siteDir), {
114
+ .action(async (siteDir, {outDir, skipBuild, config}) => {
115
+ deploy(await resolveDir(siteDir), {
168
116
  outDir,
169
117
  config,
170
118
  skipBuild,
@@ -191,8 +139,8 @@ cli
191
139
  'use polling rather than watching for reload (default: false). Can specify a poll interval in milliseconds',
192
140
  )
193
141
  .action(
194
- (siteDir = '.', {port, host, locale, config, hotOnly, open, poll}) => {
195
- start(path.resolve(siteDir), {
142
+ async (siteDir, {port, host, locale, config, hotOnly, open, poll}) => {
143
+ start(await resolveDir(siteDir), {
196
144
  port,
197
145
  host,
198
146
  locale,
@@ -219,8 +167,8 @@ cli
219
167
  .option('--build', 'build website before serving (default: false)')
220
168
  .option('-h, --host <host>', 'use specified host (default: localhost)')
221
169
  .action(
222
- (
223
- siteDir = '.',
170
+ async (
171
+ siteDir,
224
172
  {
225
173
  dir = 'build',
226
174
  port = 3000,
@@ -229,7 +177,7 @@ cli
229
177
  config,
230
178
  },
231
179
  ) => {
232
- serve(path.resolve(siteDir), {
180
+ serve(await resolveDir(siteDir), {
233
181
  dir,
234
182
  port,
235
183
  build: buildSite,
@@ -242,8 +190,8 @@ cli
242
190
  cli
243
191
  .command('clear [siteDir]')
244
192
  .description('Remove build artifacts.')
245
- .action((siteDir = '.') => {
246
- clear(path.resolve(siteDir));
193
+ .action(async (siteDir) => {
194
+ clear(await resolveDir(siteDir));
247
195
  });
248
196
 
249
197
  cli
@@ -266,11 +214,11 @@ cli
266
214
  'allows to init new written messages with a given prefix. This might help you to highlight untranslated message to make them stand out in the UI',
267
215
  )
268
216
  .action(
269
- (
270
- siteDir = '.',
217
+ async (
218
+ siteDir,
271
219
  {locale = undefined, override = false, messagePrefix = '', config},
272
220
  ) => {
273
- writeTranslations(path.resolve(siteDir), {
221
+ writeTranslations(await resolveDir(siteDir), {
274
222
  locale,
275
223
  override,
276
224
  config,
@@ -280,18 +228,25 @@ cli
280
228
  );
281
229
 
282
230
  cli
283
- .command('write-heading-ids [contentDir]')
231
+ .command('write-heading-ids [siteDir] [files...]')
284
232
  .description('Generate heading ids in Markdown content.')
285
- .action((siteDir = '.') => {
286
- writeHeadingIds(siteDir);
287
- });
233
+ .option(
234
+ '--maintain-case',
235
+ "keep the headings' casing, otherwise make all lowercase (default: false)",
236
+ )
237
+ .option('--overwrite', 'overwrite existing heading IDs (default: false)')
238
+ .action(async (siteDir, files, options) =>
239
+ writeHeadingIds(await resolveDir(siteDir), files, options),
240
+ );
288
241
 
289
242
  cli.arguments('<command>').action((cmd) => {
290
243
  cli.outputHelp();
291
- console.log(` ${chalk.red(`\n Unknown command ${chalk.yellow(cmd)}.`)}.`);
292
- console.log();
244
+ logger.error` Unknown command name=${cmd}.`;
293
245
  });
294
246
 
247
+ /**
248
+ * @param {string} command
249
+ */
295
250
  function isInternalCommand(command) {
296
251
  return [
297
252
  'start',
@@ -307,7 +262,7 @@ function isInternalCommand(command) {
307
262
 
308
263
  async function run() {
309
264
  if (!isInternalCommand(process.argv.slice(2)[0])) {
310
- await externalCommand(cli, path.resolve('.'));
265
+ await externalCommand(cli, await resolveDir('.'));
311
266
  }
312
267
 
313
268
  cli.parse(process.argv);
@@ -320,6 +275,6 @@ async function run() {
320
275
  run();
321
276
 
322
277
  process.on('unhandledRejection', (err) => {
323
- console.error(chalk.red(err.stack));
278
+ logger.error(err);
324
279
  process.exit(1);
325
280
  });
@@ -1,3 +1,8 @@
1
- import { ConfigAPI, TransformOptions } from '@babel/core';
2
- declare function babelPresets(api: ConfigAPI): TransformOptions;
3
- export default babelPresets;
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 { ConfigAPI, TransformOptions } from '@babel/core';
8
+ export default function babelPresets(api: ConfigAPI): TransformOptions;
@@ -1,17 +1,18 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
2
  /**
5
3
  * Copyright (c) Facebook, Inc. and its affiliates.
6
4
  *
7
5
  * This source code is licensed under the MIT license found in the
8
6
  * LICENSE file in the root directory of this source tree.
9
7
  */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ const tslib_1 = require("tslib");
10
10
  const path_1 = tslib_1.__importDefault(require("path"));
11
11
  function getTransformOptions(isServer) {
12
12
  const absoluteRuntimePath = path_1.default.dirname(require.resolve(`@babel/runtime/package.json`));
13
13
  return {
14
- // All optional newlines and whitespace will be omitted when generating code in compact mode
14
+ // All optional newlines and whitespace will be omitted when generating code
15
+ // in compact mode
15
16
  compact: true,
16
17
  presets: [
17
18
  isServer
@@ -46,9 +47,9 @@ function getTransformOptions(isServer) {
46
47
  {
47
48
  corejs: false,
48
49
  helpers: true,
49
- // By default, it assumes @babel/runtime@7.0.0. Since we use >7.0.0, better to
50
- // explicitly specify the version so that it can reuse the helper better
51
- // See https://github.com/babel/babel/issues/10261
50
+ // By default, it assumes @babel/runtime@7.0.0. Since we use >7.0.0,
51
+ // better to explicitly specify the version so that it can reuse the
52
+ // helper better. See https://github.com/babel/babel/issues/10261
52
53
  // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require
53
54
  version: require('@babel/runtime/package.json').version,
54
55
  regenerator: true,
@@ -67,7 +68,7 @@ function getTransformOptions(isServer) {
67
68
  };
68
69
  }
69
70
  function babelPresets(api) {
70
- const callerName = api.caller((caller) => caller === null || caller === void 0 ? void 0 : caller.name);
71
+ const callerName = api.caller((caller) => caller?.name);
71
72
  return getTransformOptions(callerName === 'server');
72
73
  }
73
74
  exports.default = babelPresets;
package/lib/choosePort.js CHANGED
@@ -14,7 +14,7 @@ const tslib_1 = require("tslib");
14
14
  const child_process_1 = require("child_process");
15
15
  const detect_port_1 = tslib_1.__importDefault(require("detect-port"));
16
16
  const is_root_1 = tslib_1.__importDefault(require("is-root"));
17
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
17
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
18
18
  const prompts_1 = tslib_1.__importDefault(require("prompts"));
19
19
  const isInteractive = process.stdout.isTTY;
20
20
  const execOptions = {
@@ -31,19 +31,19 @@ function clearConsole() {
31
31
  }
32
32
  // Gets process id of what is on port
33
33
  function getProcessIdOnPort(port) {
34
- return child_process_1.execSync(`lsof -i:${port} -P -t -sTCP:LISTEN`, execOptions)
34
+ return (0, child_process_1.execSync)(`lsof -i:${port} -P -t -sTCP:LISTEN`, execOptions)
35
35
  .toString()
36
36
  .split('\n')[0]
37
37
  .trim();
38
38
  }
39
39
  // Gets process command
40
40
  function getProcessCommand(processId) {
41
- const command = child_process_1.execSync(`ps -o command -p ${processId} | sed -n 2p`, execOptions);
41
+ const command = (0, child_process_1.execSync)(`ps -o command -p ${processId} | sed -n 2p`, execOptions);
42
42
  return command.toString().replace(/\n$/, '');
43
43
  }
44
44
  // Gets directory of a process from its process id
45
45
  function getDirectoryOfProcessById(processId) {
46
- return child_process_1.execSync(`lsof -p ${processId} | awk '$4=="cwd" {for (i=9; i<=NF; i++) printf "%s ", $i}'`, execOptions)
46
+ return (0, child_process_1.execSync)(`lsof -p ${processId} | awk '$4=="cwd" {for (i=9; i<=NF; i++) printf "%s ", $i}'`, execOptions)
47
47
  .toString()
48
48
  .trim();
49
49
  }
@@ -53,12 +53,9 @@ function getProcessForPort(port) {
53
53
  const processId = getProcessIdOnPort(port);
54
54
  const directory = getDirectoryOfProcessById(processId);
55
55
  const command = getProcessCommand(processId);
56
- return (chalk_1.default.cyan(command) +
57
- chalk_1.default.grey(` (pid ${processId})\n`) +
58
- chalk_1.default.blue(' in ') +
59
- chalk_1.default.cyan(directory));
56
+ return logger_1.default.interpolate `code=${command} subdue=${`(pid ${processId})`} in path=${directory}`;
60
57
  }
61
- catch (e) {
58
+ catch {
62
59
  return null;
63
60
  }
64
61
  }
@@ -67,39 +64,33 @@ function getProcessForPort(port) {
67
64
  * to choose another if port is already being used
68
65
  */
69
66
  async function choosePort(host, defaultPort) {
70
- // @ts-expect-error: bad lib typedef?
71
- return detect_port_1.default(defaultPort, host).then((port) => new Promise((resolve) => {
67
+ try {
68
+ const port = await (0, detect_port_1.default)({ port: defaultPort, hostname: host });
72
69
  if (port === defaultPort) {
73
- return resolve(port);
70
+ return port;
74
71
  }
75
- const message = process.platform !== 'win32' && defaultPort < 1024 && !is_root_1.default()
72
+ const message = process.platform !== 'win32' && defaultPort < 1024 && !(0, is_root_1.default)()
76
73
  ? `Admin permissions are required to run a server on a port below 1024.`
77
74
  : `Something is already running on port ${defaultPort}.`;
78
- if (isInteractive) {
79
- clearConsole();
80
- const existingProcess = getProcessForPort(defaultPort);
81
- const question = {
82
- type: 'confirm',
83
- name: 'shouldChangePort',
84
- message: `${chalk_1.default.yellow(`${message}${existingProcess ? ` Probably:\n ${existingProcess}` : ''}`)}\n\nWould you like to run the app on another port instead?`,
85
- initial: true,
86
- };
87
- prompts_1.default(question).then((answer) => {
88
- if (answer.shouldChangePort === true) {
89
- resolve(port);
90
- }
91
- else {
92
- resolve(null);
93
- }
94
- });
95
- }
96
- else {
97
- console.log(chalk_1.default.red(message));
98
- resolve(null);
75
+ if (!isInteractive) {
76
+ logger_1.default.error(message);
77
+ return null;
99
78
  }
100
- return null;
101
- }), (err) => {
102
- throw new Error(`${chalk_1.default.red(`Could not find an open port at ${chalk_1.default.bold(host)}.`)}\n${`Network error message: "${err.message}".` || err}\n`);
103
- });
79
+ clearConsole();
80
+ const existingProcess = getProcessForPort(defaultPort);
81
+ const { shouldChangePort } = await (0, prompts_1.default)({
82
+ type: 'confirm',
83
+ name: 'shouldChangePort',
84
+ message: logger_1.default.yellow(`${logger_1.default.bold('[WARNING]')} ${message}${existingProcess ? ` Probably:\n ${existingProcess}` : ''}
85
+
86
+ Would you like to run the app on another port instead?`),
87
+ initial: true,
88
+ });
89
+ return shouldChangePort ? port : null;
90
+ }
91
+ catch (err) {
92
+ logger_1.default.error `Could not find an open port at ${host}.`;
93
+ throw err;
94
+ }
104
95
  }
105
96
  exports.default = choosePort;
@@ -21,7 +21,6 @@ module.exports = {
21
21
  '**/../server/**',
22
22
  '**/../commands/**',
23
23
  '**/../webpack/**',
24
- '**/../constants',
25
24
  ],
26
25
  },
27
26
  ],
@@ -6,5 +6,4 @@
6
6
  */
7
7
  /// <reference types="react" />
8
8
  import './client-lifecycles-dispatcher';
9
- declare function App(): JSX.Element;
10
- export default App;
9
+ export default function App(): JSX.Element;
package/lib/client/App.js CHANGED
@@ -4,34 +4,29 @@
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, { useEffect, useState } from 'react';
7
+ import React from 'react';
8
8
  import routes from '@generated/routes';
9
- import siteConfig from '@generated/docusaurus.config';
10
- import globalData from '@generated/globalData';
11
- import i18n from '@generated/i18n';
12
- import codeTranslations from '@generated/codeTranslations';
13
- import siteMetadata from '@generated/site-metadata';
14
9
  import renderRoutes from './exports/renderRoutes';
15
- import DocusaurusContext from './exports/context';
10
+ import { BrowserContextProvider } from './exports/browserContext';
11
+ import { DocusaurusContextProvider } from './exports/docusaurusContext';
16
12
  import PendingNavigation from './PendingNavigation';
17
13
  import BaseUrlIssueBanner from './baseUrlIssueBanner/BaseUrlIssueBanner';
18
14
  import Root from '@theme/Root';
19
15
  import './client-lifecycles-dispatcher';
20
- function App() {
21
- const [isClient, setIsClient] = useState(false);
22
- useEffect(() => {
23
- setIsClient(true);
24
- }, []);
25
- return (React.createElement(DocusaurusContext.Provider, { value: {
26
- siteConfig,
27
- siteMetadata,
28
- globalData,
29
- i18n,
30
- codeTranslations,
31
- isClient,
32
- } },
33
- React.createElement(Root, null,
34
- React.createElement(BaseUrlIssueBanner, null),
35
- React.createElement(PendingNavigation, { routes: routes }, renderRoutes(routes)))));
16
+ // TODO, quick fix for CSS insertion order
17
+ import ErrorBoundary from '@docusaurus/ErrorBoundary';
18
+ import Error from '@theme/Error';
19
+ export default function App() {
20
+ return (<ErrorBoundary fallback={Error}>
21
+ <DocusaurusContextProvider>
22
+ <BrowserContextProvider>
23
+ <Root>
24
+ <BaseUrlIssueBanner />
25
+ <PendingNavigation routes={routes} delay={1000}>
26
+ {renderRoutes(routes)}
27
+ </PendingNavigation>
28
+ </Root>
29
+ </BrowserContextProvider>
30
+ </DocusaurusContextProvider>
31
+ </ErrorBoundary>);
36
32
  }
37
- export default App;
@@ -4,7 +4,7 @@
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 { ReactNode } from 'react';
7
+ import { type ReactNode } from 'react';
8
8
  declare type LinksCollector = {
9
9
  collectLink: (link: string) => void;
10
10
  };
@@ -13,8 +13,8 @@ declare type StatefulLinksCollector = LinksCollector & {
13
13
  };
14
14
  export declare const createStatefulLinksCollector: () => StatefulLinksCollector;
15
15
  export declare const useLinksCollector: () => LinksCollector;
16
- export declare const ProvideLinksCollector: ({ children, linksCollector, }: {
16
+ export declare function ProvideLinksCollector({ children, linksCollector, }: {
17
17
  children: ReactNode;
18
18
  linksCollector: LinksCollector;
19
- }) => JSX.Element;
19
+ }): JSX.Element;
20
20
  export {};