@docusaurus/core 2.0.0-beta.138b4c997 → 2.0.0-beta.14

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 (112) hide show
  1. package/bin/beforeCli.js +124 -0
  2. package/bin/docusaurus.js +42 -109
  3. package/lib/babel/preset.d.ts +6 -0
  4. package/lib/babel/preset.js +3 -3
  5. package/lib/choosePort.js +19 -20
  6. package/lib/client/.eslintrc.js +0 -1
  7. package/lib/client/App.js +12 -22
  8. package/lib/client/LinksCollector.d.ts +2 -2
  9. package/lib/client/LinksCollector.js +4 -8
  10. package/lib/client/PendingNavigation.d.ts +24 -1
  11. package/lib/client/PendingNavigation.js +1 -1
  12. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.d.ts +5 -0
  13. package/lib/client/client-lifecycles-dispatcher.d.ts +2 -2
  14. package/lib/client/client-lifecycles-dispatcher.js +0 -2
  15. package/lib/client/docusaurus.d.ts +6 -0
  16. package/lib/client/docusaurus.js +11 -19
  17. package/lib/client/exports/BrowserOnly.js +5 -3
  18. package/lib/client/exports/ErrorBoundary.d.ts +18 -0
  19. package/lib/client/exports/ErrorBoundary.js +35 -0
  20. package/lib/client/exports/Interpolate.js +12 -15
  21. package/lib/client/exports/Link.js +11 -11
  22. package/lib/client/exports/Translate.d.ts +2 -2
  23. package/lib/client/exports/Translate.js +13 -9
  24. package/lib/client/exports/browserContext.d.ts +11 -0
  25. package/lib/client/exports/browserContext.js +21 -0
  26. package/lib/client/exports/constants.js +1 -11
  27. package/lib/client/exports/{context.d.ts → docusaurusContext.d.ts} +5 -3
  28. package/lib/client/exports/docusaurusContext.js +25 -0
  29. package/lib/client/exports/useBaseUrl.js +2 -4
  30. package/lib/client/exports/useDocusaurusContext.js +2 -7
  31. package/lib/client/exports/useGlobalData.js +1 -5
  32. package/lib/client/exports/{context.js → useIsBrowser.d.ts} +1 -2
  33. package/lib/{webpack/sharedModuleAliases.d.ts → client/exports/useIsBrowser.js} +5 -4
  34. package/lib/client/flat.d.ts +2 -1
  35. package/lib/client/flat.js +7 -9
  36. package/lib/client/normalizeLocation.d.ts +1 -3
  37. package/lib/client/prefetch.js +0 -1
  38. package/lib/client/serverEntry.js +20 -42
  39. package/lib/client/theme-fallback/Error/index.js +47 -0
  40. package/lib/client/theme-fallback/Layout/index.js +1 -1
  41. package/lib/client/theme-fallback/Loading/index.js +2 -2
  42. package/lib/client/theme-fallback/Root/index.js +1 -3
  43. package/lib/commands/build.js +39 -44
  44. package/lib/commands/clear.d.ts +6 -0
  45. package/lib/commands/clear.js +17 -18
  46. package/lib/commands/commandUtils.d.ts +6 -0
  47. package/lib/commands/commandUtils.js +7 -7
  48. package/lib/commands/deploy.d.ts +3 -0
  49. package/lib/commands/deploy.js +99 -64
  50. package/lib/commands/external.js +4 -4
  51. package/lib/commands/serve.js +12 -18
  52. package/lib/commands/start.js +98 -86
  53. package/lib/commands/swizzle.js +57 -66
  54. package/lib/commands/writeHeadingIds.d.ts +9 -6
  55. package/lib/commands/writeHeadingIds.js +33 -34
  56. package/lib/commands/writeTranslations.js +31 -11
  57. package/lib/server/brokenLinks.js +13 -17
  58. package/lib/server/client-modules/index.js +1 -3
  59. package/lib/server/config.js +4 -4
  60. package/lib/server/configValidation.d.ts +1 -1
  61. package/lib/server/configValidation.js +14 -7
  62. package/lib/server/duplicateRoutes.js +8 -2
  63. package/lib/server/html-tags/htmlTags.js +5 -6
  64. package/lib/server/html-tags/index.js +2 -2
  65. package/lib/server/i18n.js +16 -16
  66. package/lib/server/index.js +132 -59
  67. package/lib/server/loadSetup.js +3 -3
  68. package/lib/server/moduleShorthand.d.ts +9 -0
  69. package/lib/server/moduleShorthand.js +42 -0
  70. package/lib/server/plugins/applyRouteTrailingSlash.d.ts +2 -1
  71. package/lib/server/plugins/applyRouteTrailingSlash.js +3 -3
  72. package/lib/server/plugins/index.d.ts +1 -1
  73. package/lib/server/plugins/index.js +28 -21
  74. package/lib/server/plugins/init.js +9 -12
  75. package/lib/server/plugins/pluginIds.js +6 -4
  76. package/lib/server/presets/index.js +12 -12
  77. package/lib/server/routes.js +41 -23
  78. package/lib/server/themes/alias.d.ts +1 -0
  79. package/lib/server/themes/alias.js +21 -12
  80. package/lib/server/themes/index.d.ts +1 -1
  81. package/lib/server/themes/index.js +22 -23
  82. package/lib/server/translations/translations.d.ts +6 -0
  83. package/lib/server/translations/translations.js +19 -26
  84. package/lib/server/translations/translationsExtractor.d.ts +7 -1
  85. package/lib/server/translations/translationsExtractor.js +66 -59
  86. package/lib/server/utils.d.ts +8 -2
  87. package/lib/server/utils.js +8 -10
  88. package/lib/server/versions/__fixtures__/dummy-plugin.d.ts +0 -0
  89. package/lib/server/versions/__tests/index.test.js +5 -5
  90. package/lib/server/versions/index.js +6 -6
  91. package/lib/webpack/base.js +13 -15
  92. package/lib/webpack/client.js +9 -18
  93. package/lib/webpack/plugins/CleanWebpackPlugin.js +4 -11
  94. package/lib/webpack/plugins/LogPlugin.js +5 -6
  95. package/lib/webpack/plugins/WaitPlugin.js +4 -4
  96. package/lib/webpack/server.js +13 -9
  97. package/lib/webpack/utils.d.ts +0 -22
  98. package/lib/webpack/utils.js +37 -134
  99. package/package.json +55 -50
  100. package/lib/.tsbuildinfo +0 -1
  101. package/lib/client/.tsbuildinfo +0 -1
  102. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  103. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  104. package/lib/constants.d.ts +0 -18
  105. package/lib/constants.js +0 -23
  106. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  107. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  108. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  109. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  110. package/lib/webpack/sharedModuleAliases.js +0 -18
  111. package/tsconfig.client.json +0 -13
  112. package/tsconfig.json +0 -13
@@ -0,0 +1,124 @@
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
+ const logger = require('@docusaurus/logger').default;
11
+ const fs = require('fs-extra');
12
+ const semver = require('semver');
13
+ const path = require('path');
14
+ const updateNotifier = require('update-notifier');
15
+ const boxen = require('boxen');
16
+
17
+ const {
18
+ name,
19
+ version,
20
+ engines: {node: requiredVersion},
21
+ } = require('../package.json');
22
+
23
+ // Notify user if @docusaurus packages is outdated
24
+ //
25
+ // Note: this is a 2-step process to avoid delaying cli usage by awaiting a response:
26
+ // - 1st run: trigger background job to check releases + store result
27
+ // - 2nd run: display potential update to users
28
+ //
29
+ // Note: even if the
30
+ //
31
+ // cache data is stored in ~/.config/configstore/update-notifier-@docusaurus
32
+ //
33
+ const notifier = updateNotifier({
34
+ pkg: {
35
+ name,
36
+ version,
37
+ },
38
+ // Check is in background so it's fine to use a small value like 1h
39
+ // Use 0 for debugging
40
+ updateCheckInterval: 1000 * 60 * 60,
41
+ // updateCheckInterval: 0
42
+ });
43
+
44
+ // Hacky way to ensure we check for updates on first run
45
+ // Note: the notification will only happen in the 2nd run
46
+ // See https://github.com/yeoman/update-notifier/issues/209
47
+ try {
48
+ if (
49
+ notifier.config &&
50
+ !notifier.disabled &&
51
+ Date.now() - notifier.config.get('lastUpdateCheck') < 50
52
+ ) {
53
+ notifier.config.set('lastUpdateCheck', 0);
54
+ notifier.check();
55
+ }
56
+ } catch (e) {
57
+ // Do not stop cli if this fails, see https://github.com/facebook/docusaurus/issues/5400
58
+ logger.error(e);
59
+ }
60
+
61
+ // We don't want to display update message for canary releases
62
+ // See https://github.com/facebook/docusaurus/issues/5378
63
+ function ignoreUpdate(update) {
64
+ const isCanaryRelease =
65
+ update && update.current && update.current.startsWith('0.0.0');
66
+ return isCanaryRelease;
67
+ }
68
+
69
+ if (
70
+ notifier.config &&
71
+ notifier.update &&
72
+ semver.lt(notifier.update.current, notifier.update.latest)
73
+ ) {
74
+ // Because notifier clears cached data after reading it, leading to notifier not consistently displaying the update
75
+ // See https://github.com/yeoman/update-notifier/issues/209
76
+ notifier.config.set('update', notifier.update);
77
+
78
+ if (ignoreUpdate(notifier.update)) {
79
+ // @ts-expect-error: it works
80
+ return;
81
+ }
82
+
83
+ // eslint-disable-next-line import/no-dynamic-require, global-require
84
+ const sitePkg = require(path.resolve(process.cwd(), 'package.json'));
85
+ const siteDocusaurusPackagesForUpdate = Object.keys({
86
+ ...sitePkg.dependencies,
87
+ ...sitePkg.devDependencies,
88
+ })
89
+ .filter((p) => p.startsWith('@docusaurus'))
90
+ .map((p) => p.concat('@latest'))
91
+ .join(' ');
92
+ const isYarnUsed = fs.existsSync(path.resolve(process.cwd(), 'yarn.lock'));
93
+ const upgradeCommand = isYarnUsed
94
+ ? `yarn upgrade ${siteDocusaurusPackagesForUpdate}`
95
+ : `npm i ${siteDocusaurusPackagesForUpdate}`;
96
+
97
+ /** @type {import('boxen').Options} */
98
+ const boxenOptions = {
99
+ padding: 1,
100
+ margin: 1,
101
+ align: 'center',
102
+ borderColor: 'yellow',
103
+ borderStyle: 'round',
104
+ };
105
+
106
+ const docusaurusUpdateMessage = boxen(
107
+ `Update available ${logger.dim(
108
+ `${notifier.update.current}`,
109
+ )} → ${logger.green(`${notifier.update.latest}`)}
110
+
111
+ To upgrade Docusaurus packages with the latest version, run the following command:
112
+ ${logger.code(upgradeCommand)}`,
113
+ boxenOptions,
114
+ );
115
+
116
+ console.log(docusaurusUpdateMessage);
117
+ }
118
+
119
+ // notify user if node version needs to be updated
120
+ if (!semver.satisfies(process.version, requiredVersion)) {
121
+ logger.error('Minimum Node.js version not met :(');
122
+ logger.info`You are using Node.js number=${process.version}, Requirement: Node.js number=${requiredVersion}.`;
123
+ process.exit(1);
124
+ }
package/bin/docusaurus.js CHANGED
@@ -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,13 +6,11 @@
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');
9
+ // @ts-check
10
+
11
+ const logger = require('@docusaurus/logger').default;
12
+ const fs = require('fs');
16
13
  const cli = require('commander');
17
- const updateNotifier = require('update-notifier');
18
- const boxen = require('boxen');
19
14
  const {
20
15
  build,
21
16
  swizzle,
@@ -27,69 +22,10 @@ const {
27
22
  writeTranslations,
28
23
  writeHeadingIds,
29
24
  } = 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}`;
60
25
 
61
- const boxenOptions = {
62
- padding: 1,
63
- margin: 1,
64
- align: 'center',
65
- borderColor: 'yellow',
66
- borderStyle: 'round',
67
- };
26
+ require('./beforeCli');
68
27
 
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
- }
28
+ const resolveDir = (dir = '.') => fs.realpathSync(dir);
93
29
 
94
30
  cli.version(require('../package.json').version).usage('<command> [options]');
95
31
 
@@ -116,8 +52,8 @@ cli
116
52
  '--no-minify',
117
53
  'build website without minimizing JS bundles (default: false)',
118
54
  )
119
- .action((siteDir = '.', {bundleAnalyzer, config, outDir, locale, minify}) => {
120
- build(path.resolve(siteDir), {
55
+ .action((siteDir, {bundleAnalyzer, config, outDir, locale, minify}) => {
56
+ build(resolveDir(siteDir), {
121
57
  bundleAnalyzer,
122
58
  outDir,
123
59
  config,
@@ -134,14 +70,8 @@ cli
134
70
  'copy TypeScript theme files when possible (default: false)',
135
71
  )
136
72
  .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
- );
73
+ .action((themeName, componentName, siteDir, {typescript, danger}) => {
74
+ swizzle(resolveDir(siteDir), themeName, componentName, typescript, danger);
145
75
  });
146
76
 
147
77
  cli
@@ -163,8 +93,8 @@ cli
163
93
  '--skip-build',
164
94
  'skip building website before deploy it (default: false)',
165
95
  )
166
- .action((siteDir = '.', {outDir, skipBuild, config}) => {
167
- deploy(path.resolve(siteDir), {
96
+ .action((siteDir, {outDir, skipBuild, config}) => {
97
+ deploy(resolveDir(siteDir), {
168
98
  outDir,
169
99
  config,
170
100
  skipBuild,
@@ -190,19 +120,17 @@ cli
190
120
  '--poll [interval]',
191
121
  'use polling rather than watching for reload (default: false). Can specify a poll interval in milliseconds',
192
122
  )
193
- .action(
194
- (siteDir = '.', {port, host, locale, config, hotOnly, open, poll}) => {
195
- start(path.resolve(siteDir), {
196
- port,
197
- host,
198
- locale,
199
- config,
200
- hotOnly,
201
- open,
202
- poll,
203
- });
204
- },
205
- );
123
+ .action((siteDir, {port, host, locale, config, hotOnly, open, poll}) => {
124
+ start(resolveDir(siteDir), {
125
+ port,
126
+ host,
127
+ locale,
128
+ config,
129
+ hotOnly,
130
+ open,
131
+ poll,
132
+ });
133
+ });
206
134
 
207
135
  cli
208
136
  .command('serve [siteDir]')
@@ -220,7 +148,7 @@ cli
220
148
  .option('-h, --host <host>', 'use specified host (default: localhost)')
221
149
  .action(
222
150
  (
223
- siteDir = '.',
151
+ siteDir,
224
152
  {
225
153
  dir = 'build',
226
154
  port = 3000,
@@ -229,7 +157,7 @@ cli
229
157
  config,
230
158
  },
231
159
  ) => {
232
- serve(path.resolve(siteDir), {
160
+ serve(resolveDir(siteDir), {
233
161
  dir,
234
162
  port,
235
163
  build: buildSite,
@@ -242,8 +170,8 @@ cli
242
170
  cli
243
171
  .command('clear [siteDir]')
244
172
  .description('Remove build artifacts.')
245
- .action((siteDir = '.') => {
246
- clear(path.resolve(siteDir));
173
+ .action((siteDir) => {
174
+ clear(resolveDir(siteDir));
247
175
  });
248
176
 
249
177
  cli
@@ -267,10 +195,10 @@ cli
267
195
  )
268
196
  .action(
269
197
  (
270
- siteDir = '.',
198
+ siteDir,
271
199
  {locale = undefined, override = false, messagePrefix = '', config},
272
200
  ) => {
273
- writeTranslations(path.resolve(siteDir), {
201
+ writeTranslations(resolveDir(siteDir), {
274
202
  locale,
275
203
  override,
276
204
  config,
@@ -280,16 +208,20 @@ cli
280
208
  );
281
209
 
282
210
  cli
283
- .command('write-heading-ids [contentDir]')
211
+ .command('write-heading-ids [contentDir] [files]')
284
212
  .description('Generate heading ids in Markdown content.')
285
- .action((siteDir = '.') => {
286
- writeHeadingIds(siteDir);
287
- });
213
+ .option(
214
+ '--maintain-case',
215
+ "keep the headings' casing, otherwise make all lowercase (default: false)",
216
+ )
217
+ .option('--overwrite', 'overwrite existing heading IDs (default: false)')
218
+ .action((siteDir, files, options) =>
219
+ writeHeadingIds(resolveDir(siteDir), files, options),
220
+ );
288
221
 
289
222
  cli.arguments('<command>').action((cmd) => {
290
223
  cli.outputHelp();
291
- console.log(` ${chalk.red(`\n Unknown command ${chalk.yellow(cmd)}.`)}.`);
292
- console.log();
224
+ logger.error` Unknown command name=${cmd}.`;
293
225
  });
294
226
 
295
227
  function isInternalCommand(command) {
@@ -307,7 +239,8 @@ function isInternalCommand(command) {
307
239
 
308
240
  async function run() {
309
241
  if (!isInternalCommand(process.argv.slice(2)[0])) {
310
- await externalCommand(cli, path.resolve('.'));
242
+ // @ts-expect-error: Hmmm
243
+ await externalCommand(cli, resolveDir('.'));
311
244
  }
312
245
 
313
246
  cli.parse(process.argv);
@@ -320,6 +253,6 @@ async function run() {
320
253
  run();
321
254
 
322
255
  process.on('unhandledRejection', (err) => {
323
- console.error(chalk.red(err.stack));
256
+ logger.error(err.stack);
324
257
  process.exit(1);
325
258
  });
@@ -1,3 +1,9 @@
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
+ */
1
7
  import { ConfigAPI, TransformOptions } from '@babel/core';
2
8
  declare function babelPresets(api: ConfigAPI): TransformOptions;
3
9
  export default babelPresets;
@@ -1,13 +1,13 @@
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
  */
10
- const path_1 = tslib_1.__importDefault(require("path"));
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ const tslib_1 = require("tslib");
10
+ const path_1 = (0, 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 {
package/lib/choosePort.js CHANGED
@@ -12,10 +12,10 @@ const tslib_1 = require("tslib");
12
12
  * uses many of the same utility functions to implement it.
13
13
  */
14
14
  const child_process_1 = require("child_process");
15
- const detect_port_1 = tslib_1.__importDefault(require("detect-port"));
16
- const is_root_1 = tslib_1.__importDefault(require("is-root"));
17
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
18
- const prompts_1 = tslib_1.__importDefault(require("prompts"));
15
+ const detect_port_1 = (0, tslib_1.__importDefault)(require("detect-port"));
16
+ const is_root_1 = (0, tslib_1.__importDefault)(require("is-root"));
17
+ const logger_1 = (0, tslib_1.__importDefault)(require("@docusaurus/logger"));
18
+ const prompts_1 = (0, tslib_1.__importDefault)(require("prompts"));
19
19
  const isInteractive = process.stdout.isTTY;
20
20
  const execOptions = {
21
21
  encoding: 'utf8',
@@ -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,10 +53,7 @@ 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
58
  catch (e) {
62
59
  return null;
@@ -67,12 +64,12 @@ 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
+ return (0, detect_port_1.default)({ port: defaultPort, hostname: host }).then((port) => new Promise((resolve) => {
72
68
  if (port === defaultPort) {
73
- return resolve(port);
69
+ resolve(port);
70
+ return;
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
75
  if (isInteractive) {
@@ -81,10 +78,12 @@ async function choosePort(host, defaultPort) {
81
78
  const question = {
82
79
  type: 'confirm',
83
80
  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?`,
81
+ message: logger_1.default.yellow(`${logger_1.default.bold('[WARNING]')} ${message}${existingProcess ? ` Probably:\n ${existingProcess}` : ''}
82
+
83
+ Would you like to run the app on another port instead?`),
85
84
  initial: true,
86
85
  };
87
- prompts_1.default(question).then((answer) => {
86
+ (0, prompts_1.default)(question).then((answer) => {
88
87
  if (answer.shouldChangePort === true) {
89
88
  resolve(port);
90
89
  }
@@ -94,12 +93,12 @@ async function choosePort(host, defaultPort) {
94
93
  });
95
94
  }
96
95
  else {
97
- console.log(chalk_1.default.red(message));
96
+ logger_1.default.error(message);
98
97
  resolve(null);
99
98
  }
100
- return null;
101
99
  }), (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`);
100
+ throw new Error(`Could not find an open port at ${host}.
101
+ ${`Network error message: "${err.message || err}".`}`);
103
102
  });
104
103
  }
105
104
  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
  ],
package/lib/client/App.js CHANGED
@@ -4,34 +4,24 @@
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';
16
+ // TODO, quick fix for CSS insertion order
17
+ import ErrorBoundary from '@docusaurus/ErrorBoundary';
18
+ import Error from '@theme/Error';
20
19
  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)))));
20
+ return (React.createElement(ErrorBoundary, { fallback: Error },
21
+ React.createElement(DocusaurusContextProvider, null,
22
+ React.createElement(BrowserContextProvider, null,
23
+ React.createElement(Root, null,
24
+ React.createElement(BaseUrlIssueBanner, null),
25
+ React.createElement(PendingNavigation, { routes: routes, delay: 1000 }, renderRoutes(routes)))))));
36
26
  }
37
27
  export default App;
@@ -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 {};
@@ -12,9 +12,7 @@ export const createStatefulLinksCollector = () => {
12
12
  collectLink: (link) => {
13
13
  allLinks.add(link);
14
14
  },
15
- getCollectedLinks: () => {
16
- return [...allLinks];
17
- },
15
+ getCollectedLinks: () => [...allLinks],
18
16
  };
19
17
  };
20
18
  const Context = createContext({
@@ -23,9 +21,7 @@ const Context = createContext({
23
21
  // we only use the broken links checker server-side
24
22
  },
25
23
  });
26
- export const useLinksCollector = () => {
27
- return useContext(Context);
28
- };
29
- export const ProvideLinksCollector = ({ children, linksCollector, }) => {
24
+ export const useLinksCollector = () => useContext(Context);
25
+ export function ProvideLinksCollector({ children, linksCollector, }) {
30
26
  return React.createElement(Context.Provider, { value: linksCollector }, children);
31
- };
27
+ }
@@ -4,6 +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
+ /// <reference types="node" />
8
+ import React from 'react';
9
+ import { RouteComponentProps } from 'react-router-dom';
10
+ import { RouteConfig } from 'react-router-config';
11
+ import type { Location } from '@docusaurus/history';
7
12
  import './nprogress.css';
8
- declare const _default: any;
13
+ interface Props extends RouteComponentProps {
14
+ readonly routes: RouteConfig[];
15
+ readonly delay: number;
16
+ readonly location: Location;
17
+ }
18
+ interface State {
19
+ nextRouteHasLoaded: boolean;
20
+ }
21
+ declare class PendingNavigation extends React.Component<Props, State> {
22
+ previousLocation: Location | null;
23
+ progressBarTimeout: NodeJS.Timeout | null;
24
+ constructor(props: Props);
25
+ shouldComponentUpdate(nextProps: Props, nextState: State): boolean;
26
+ clearProgressBarTimeout(): void;
27
+ startProgressBar(delay: number): void;
28
+ stopProgressBar(): void;
29
+ render(): JSX.Element;
30
+ }
31
+ declare const _default: React.ComponentClass<Pick<Props, "routes" | "delay">, any> & import("react-router").WithRouterStatics<typeof PendingNavigation>;
9
32
  export default _default;
@@ -26,7 +26,7 @@ class PendingNavigation extends React.Component {
26
26
  // is done loading.
27
27
  shouldComponentUpdate(nextProps, nextState) {
28
28
  const routeDidChange = nextProps.location !== this.props.location;
29
- const { routes, delay = 1000 } = this.props;
29
+ const { routes, delay } = this.props;
30
30
  // If `routeDidChange` is true, means the router is trying to navigate to a new
31
31
  // route. We will preload the new route.
32
32
  if (routeDidChange) {
@@ -6,4 +6,9 @@
6
6
  */
7
7
  /// <reference types="react" />
8
8
  import './styles.module.css';
9
+ declare global {
10
+ interface Window {
11
+ __DOCUSAURUS_INSERT_BASEURL_BANNER: boolean;
12
+ }
13
+ }
9
14
  export default function BaseUrlIssueBanner(): JSX.Element | null;
@@ -5,8 +5,8 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
  interface Dispatchers {
8
- onRouteUpdate: (...args: any) => void;
9
- onRouteUpdateDelayed: (...args: any) => void;
8
+ onRouteUpdate: (...args: unknown[]) => void;
9
+ onRouteUpdateDelayed: (...args: unknown[]) => void;
10
10
  }
11
11
  declare const clientLifecyclesDispatchers: Dispatchers;
12
12
  export default clientLifecyclesDispatchers;
@@ -4,8 +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
- // too dynamic
8
- /* eslint-disable @typescript-eslint/no-explicit-any */
9
7
  import clientModules from '@generated/client-modules';
10
8
  function dispatchLifecycleAction(lifecycleAction, ...args) {
11
9
  clientModules.forEach((clientModule) => {