@docusaurus/core 2.0.0-beta.12faed89d → 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 (111) hide show
  1. package/bin/beforeCli.js +46 -22
  2. package/bin/docusaurus.js +42 -44
  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 +9 -9
  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 +42 -51
  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.js +1 -1
  71. package/lib/server/plugins/index.d.ts +1 -1
  72. package/lib/server/plugins/index.js +25 -21
  73. package/lib/server/plugins/init.js +9 -12
  74. package/lib/server/plugins/pluginIds.js +6 -4
  75. package/lib/server/presets/index.js +12 -12
  76. package/lib/server/routes.js +9 -11
  77. package/lib/server/themes/alias.d.ts +1 -0
  78. package/lib/server/themes/alias.js +21 -12
  79. package/lib/server/themes/index.d.ts +1 -1
  80. package/lib/server/themes/index.js +22 -23
  81. package/lib/server/translations/translations.d.ts +6 -0
  82. package/lib/server/translations/translations.js +19 -26
  83. package/lib/server/translations/translationsExtractor.d.ts +7 -1
  84. package/lib/server/translations/translationsExtractor.js +66 -59
  85. package/lib/server/utils.d.ts +8 -2
  86. package/lib/server/utils.js +8 -10
  87. package/lib/server/versions/__fixtures__/dummy-plugin.d.ts +0 -0
  88. package/lib/server/versions/__tests/index.test.js +5 -5
  89. package/lib/server/versions/index.js +6 -6
  90. package/lib/webpack/base.js +14 -16
  91. package/lib/webpack/client.js +9 -18
  92. package/lib/webpack/plugins/CleanWebpackPlugin.js +4 -11
  93. package/lib/webpack/plugins/LogPlugin.js +5 -6
  94. package/lib/webpack/plugins/WaitPlugin.js +4 -4
  95. package/lib/webpack/server.js +9 -9
  96. package/lib/webpack/utils.d.ts +0 -22
  97. package/lib/webpack/utils.js +37 -134
  98. package/package.json +55 -50
  99. package/lib/.tsbuildinfo +0 -1
  100. package/lib/client/.tsbuildinfo +0 -1
  101. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  102. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  103. package/lib/constants.d.ts +0 -18
  104. package/lib/constants.js +0 -23
  105. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  106. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  107. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  108. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  109. package/lib/webpack/sharedModuleAliases.js +0 -18
  110. package/tsconfig.client.json +0 -13
  111. package/tsconfig.json +0 -13
package/bin/beforeCli.js CHANGED
@@ -5,7 +5,9 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- const chalk = require('chalk');
8
+ // @ts-check
9
+
10
+ const logger = require('@docusaurus/logger').default;
9
11
  const fs = require('fs-extra');
10
12
  const semver = require('semver');
11
13
  const path = require('path');
@@ -42,22 +44,48 @@ const notifier = updateNotifier({
42
44
  // Hacky way to ensure we check for updates on first run
43
45
  // Note: the notification will only happen in the 2nd run
44
46
  // See https://github.com/yeoman/update-notifier/issues/209
45
- if (
46
- !notifier.disabled &&
47
- Date.now() - notifier.config.get('lastUpdateCheck') < 50
48
- ) {
49
- notifier.config.set('lastUpdateCheck', 0);
50
- notifier.check();
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;
51
67
  }
52
68
 
53
- if (notifier.update && notifier.update.current !== notifier.update.latest) {
69
+ if (
70
+ notifier.config &&
71
+ notifier.update &&
72
+ semver.lt(notifier.update.current, notifier.update.latest)
73
+ ) {
54
74
  // Because notifier clears cached data after reading it, leading to notifier not consistently displaying the update
55
75
  // See https://github.com/yeoman/update-notifier/issues/209
56
76
  notifier.config.set('update', notifier.update);
57
77
 
78
+ if (ignoreUpdate(notifier.update)) {
79
+ // @ts-expect-error: it works
80
+ return;
81
+ }
82
+
58
83
  // eslint-disable-next-line import/no-dynamic-require, global-require
59
84
  const sitePkg = require(path.resolve(process.cwd(), 'package.json'));
60
- const siteDocusaurusPackagesForUpdate = Object.keys(sitePkg.dependencies)
85
+ const siteDocusaurusPackagesForUpdate = Object.keys({
86
+ ...sitePkg.dependencies,
87
+ ...sitePkg.devDependencies,
88
+ })
61
89
  .filter((p) => p.startsWith('@docusaurus'))
62
90
  .map((p) => p.concat('@latest'))
63
91
  .join(' ');
@@ -66,6 +94,7 @@ if (notifier.update && notifier.update.current !== notifier.update.latest) {
66
94
  ? `yarn upgrade ${siteDocusaurusPackagesForUpdate}`
67
95
  : `npm i ${siteDocusaurusPackagesForUpdate}`;
68
96
 
97
+ /** @type {import('boxen').Options} */
69
98
  const boxenOptions = {
70
99
  padding: 1,
71
100
  margin: 1,
@@ -75,13 +104,12 @@ if (notifier.update && notifier.update.current !== notifier.update.latest) {
75
104
  };
76
105
 
77
106
  const docusaurusUpdateMessage = boxen(
78
- `Update available ${chalk.dim(`${notifier.update.current}`)}${chalk.reset(
79
- ' → ',
80
- )}${chalk.green(
81
- `${notifier.update.latest}`,
82
- )}\n\nTo upgrade Docusaurus packages with the latest version, run the following command:\n${chalk.cyan(
83
- `${upgradeCommand}`,
84
- )}`,
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)}`,
85
113
  boxenOptions,
86
114
  );
87
115
 
@@ -90,11 +118,7 @@ if (notifier.update && notifier.update.current !== notifier.update.latest) {
90
118
 
91
119
  // notify user if node version needs to be updated
92
120
  if (!semver.satisfies(process.version, requiredVersion)) {
93
- console.log(
94
- chalk.red(`\nMinimum Node version not met :(`) +
95
- chalk.yellow(
96
- `\n\nYou are using Node ${process.version}. We require Node ${requiredVersion} or up!\n`,
97
- ),
98
- );
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}.`;
99
123
  process.exit(1);
100
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,8 +6,10 @@
9
6
  * LICENSE file in the root directory of this source tree.
10
7
  */
11
8
 
12
- const chalk = require('chalk');
13
- const path = require('path');
9
+ // @ts-check
10
+
11
+ const logger = require('@docusaurus/logger').default;
12
+ const fs = require('fs');
14
13
  const cli = require('commander');
15
14
  const {
16
15
  build,
@@ -26,6 +25,8 @@ const {
26
25
 
27
26
  require('./beforeCli');
28
27
 
28
+ const resolveDir = (dir = '.') => fs.realpathSync(dir);
29
+
29
30
  cli.version(require('../package.json').version).usage('<command> [options]');
30
31
 
31
32
  cli
@@ -51,8 +52,8 @@ cli
51
52
  '--no-minify',
52
53
  'build website without minimizing JS bundles (default: false)',
53
54
  )
54
- .action((siteDir = '.', {bundleAnalyzer, config, outDir, locale, minify}) => {
55
- build(path.resolve(siteDir), {
55
+ .action((siteDir, {bundleAnalyzer, config, outDir, locale, minify}) => {
56
+ build(resolveDir(siteDir), {
56
57
  bundleAnalyzer,
57
58
  outDir,
58
59
  config,
@@ -69,14 +70,8 @@ cli
69
70
  'copy TypeScript theme files when possible (default: false)',
70
71
  )
71
72
  .option('--danger', 'enable swizzle for internal component of themes')
72
- .action((themeName, componentName, siteDir = '.', {typescript, danger}) => {
73
- swizzle(
74
- path.resolve(siteDir),
75
- themeName,
76
- componentName,
77
- typescript,
78
- danger,
79
- );
73
+ .action((themeName, componentName, siteDir, {typescript, danger}) => {
74
+ swizzle(resolveDir(siteDir), themeName, componentName, typescript, danger);
80
75
  });
81
76
 
82
77
  cli
@@ -98,8 +93,8 @@ cli
98
93
  '--skip-build',
99
94
  'skip building website before deploy it (default: false)',
100
95
  )
101
- .action((siteDir = '.', {outDir, skipBuild, config}) => {
102
- deploy(path.resolve(siteDir), {
96
+ .action((siteDir, {outDir, skipBuild, config}) => {
97
+ deploy(resolveDir(siteDir), {
103
98
  outDir,
104
99
  config,
105
100
  skipBuild,
@@ -125,19 +120,17 @@ cli
125
120
  '--poll [interval]',
126
121
  'use polling rather than watching for reload (default: false). Can specify a poll interval in milliseconds',
127
122
  )
128
- .action(
129
- (siteDir = '.', {port, host, locale, config, hotOnly, open, poll}) => {
130
- start(path.resolve(siteDir), {
131
- port,
132
- host,
133
- locale,
134
- config,
135
- hotOnly,
136
- open,
137
- poll,
138
- });
139
- },
140
- );
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
+ });
141
134
 
142
135
  cli
143
136
  .command('serve [siteDir]')
@@ -155,7 +148,7 @@ cli
155
148
  .option('-h, --host <host>', 'use specified host (default: localhost)')
156
149
  .action(
157
150
  (
158
- siteDir = '.',
151
+ siteDir,
159
152
  {
160
153
  dir = 'build',
161
154
  port = 3000,
@@ -164,7 +157,7 @@ cli
164
157
  config,
165
158
  },
166
159
  ) => {
167
- serve(path.resolve(siteDir), {
160
+ serve(resolveDir(siteDir), {
168
161
  dir,
169
162
  port,
170
163
  build: buildSite,
@@ -177,8 +170,8 @@ cli
177
170
  cli
178
171
  .command('clear [siteDir]')
179
172
  .description('Remove build artifacts.')
180
- .action((siteDir = '.') => {
181
- clear(path.resolve(siteDir));
173
+ .action((siteDir) => {
174
+ clear(resolveDir(siteDir));
182
175
  });
183
176
 
184
177
  cli
@@ -202,10 +195,10 @@ cli
202
195
  )
203
196
  .action(
204
197
  (
205
- siteDir = '.',
198
+ siteDir,
206
199
  {locale = undefined, override = false, messagePrefix = '', config},
207
200
  ) => {
208
- writeTranslations(path.resolve(siteDir), {
201
+ writeTranslations(resolveDir(siteDir), {
209
202
  locale,
210
203
  override,
211
204
  config,
@@ -215,16 +208,20 @@ cli
215
208
  );
216
209
 
217
210
  cli
218
- .command('write-heading-ids [contentDir]')
211
+ .command('write-heading-ids [contentDir] [files]')
219
212
  .description('Generate heading ids in Markdown content.')
220
- .action((siteDir = '.') => {
221
- writeHeadingIds(siteDir);
222
- });
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
+ );
223
221
 
224
222
  cli.arguments('<command>').action((cmd) => {
225
223
  cli.outputHelp();
226
- console.log(` ${chalk.red(`\n Unknown command ${chalk.yellow(cmd)}.`)}.`);
227
- console.log();
224
+ logger.error` Unknown command name=${cmd}.`;
228
225
  });
229
226
 
230
227
  function isInternalCommand(command) {
@@ -242,7 +239,8 @@ function isInternalCommand(command) {
242
239
 
243
240
  async function run() {
244
241
  if (!isInternalCommand(process.argv.slice(2)[0])) {
245
- await externalCommand(cli, path.resolve('.'));
242
+ // @ts-expect-error: Hmmm
243
+ await externalCommand(cli, resolveDir('.'));
246
244
  }
247
245
 
248
246
  cli.parse(process.argv);
@@ -255,6 +253,6 @@ async function run() {
255
253
  run();
256
254
 
257
255
  process.on('unhandledRejection', (err) => {
258
- console.error(chalk.red(err.stack));
256
+ logger.error(err.stack);
259
257
  process.exit(1);
260
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) => {
@@ -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
  declare global {
2
8
  const __webpack_require__: {
3
9
  gca: (name: string) => string;
@@ -12,31 +12,23 @@ import preloadHelper from './preload';
12
12
  import flat from './flat';
13
13
  const fetched = {};
14
14
  const loaded = {};
15
+ // If user is on slow or constrained connection.
15
16
  const isSlowConnection = () => {
16
- // If user is on slow or constrained connection.
17
- if (`connection` in navigator) {
18
- if ((navigator.connection.effectiveType || ``).indexOf(`2g`) !== -1 &&
19
- navigator.connection.saveData) {
20
- return true;
21
- }
22
- }
23
- return false;
17
+ var _a, _b;
18
+ return ((_a = navigator.connection) === null || _a === void 0 ? void 0 : _a.effectiveType.includes('2g')) &&
19
+ ((_b = navigator.connection) === null || _b === void 0 ? void 0 : _b.saveData);
24
20
  };
25
21
  const canPrefetch = (routePath) => !isSlowConnection() && !loaded[routePath] && !fetched[routePath];
26
22
  const canPreload = (routePath) => !isSlowConnection() && !loaded[routePath];
27
- const flatten = (arrays) => Array.prototype.concat.apply([], arrays);
28
23
  // Remove the last part containing the route hash
29
24
  // input: /blog/2018/12/14/Happy-First-Birthday-Slash-fe9
30
25
  // output: /blog/2018/12/14/Happy-First-Birthday-Slash
31
26
  const removeRouteNameHash = (str) => str.replace(/(-[^-]+)$/, '');
32
- const getChunkNamesToLoad = (path) => {
33
- return flatten(Object.entries(routesChunkNames)
34
- .filter(([routeNameWithHash]) => removeRouteNameHash(routeNameWithHash) === path)
35
- .map(([, routeChunks]) => {
36
- // flat() is useful for nested chunk names, it's not like array.flat()
37
- return Object.values(flat(routeChunks));
38
- }));
39
- };
27
+ const getChunkNamesToLoad = (path) => Object.entries(routesChunkNames)
28
+ .filter(([routeNameWithHash]) => removeRouteNameHash(routeNameWithHash) === path)
29
+ .flatMap(([, routeChunks]) =>
30
+ // flat() is useful for nested chunk names, it's not like array.flat()
31
+ Object.values(flat(routeChunks)));
40
32
  const docusaurus = {
41
33
  prefetch: (routePath) => {
42
34
  if (!canPrefetch(routePath)) {
@@ -46,12 +38,12 @@ const docusaurus = {
46
38
  fetched[routePath] = true;
47
39
  // Find all webpack chunk names needed.
48
40
  const matches = matchRoutes(routes, routePath);
49
- const chunkNamesNeeded = flatten(matches.map((match) => getChunkNamesToLoad(match.route.path)));
41
+ const chunkNamesNeeded = matches.flatMap((match) => getChunkNamesToLoad(match.route.path));
50
42
  // Prefetch all webpack chunk assets file needed.
51
43
  chunkNamesNeeded.forEach((chunkName) => {
52
44
  // "__webpack_require__.gca" is a custom function provided by ChunkAssetPlugin.
53
45
  // Pass it the chunkName or chunkId you want to load and it will return the URL for that chunk.
54
- // eslint-disable-next-line no-undef
46
+ // eslint-disable-next-line camelcase
55
47
  const chunkAsset = __webpack_require__.gca(chunkName);
56
48
  // In some cases, webpack might decide to optimize further & hence the chunk assets are merged to another chunk/previous chunk.
57
49
  // Hence, we can safely filter it out/don't need to load it.