@docusaurus/core 2.0.0-beta.1 → 2.0.0-beta.10

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 (115) hide show
  1. package/bin/beforeCli.js +125 -0
  2. package/bin/docusaurus.js +36 -105
  3. package/lib/.tsbuildinfo +1 -1
  4. package/lib/babel/preset.d.ts +6 -0
  5. package/lib/babel/preset.js +3 -3
  6. package/lib/choosePort.js +12 -13
  7. package/lib/client/.eslintrc.js +0 -1
  8. package/lib/client/.tsbuildinfo +1 -1
  9. package/lib/client/App.js +12 -22
  10. package/lib/client/LinksCollector.d.ts +2 -2
  11. package/lib/client/LinksCollector.js +4 -8
  12. package/lib/client/PendingNavigation.d.ts +24 -1
  13. package/lib/client/PendingNavigation.js +1 -1
  14. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.d.ts +5 -0
  15. package/lib/client/client-lifecycles-dispatcher.d.ts +2 -2
  16. package/lib/client/client-lifecycles-dispatcher.js +0 -2
  17. package/lib/client/docusaurus.d.ts +6 -0
  18. package/lib/client/docusaurus.js +11 -19
  19. package/lib/client/exports/BrowserOnly.js +5 -3
  20. package/lib/client/exports/ErrorBoundary.d.ts +18 -0
  21. package/lib/client/exports/ErrorBoundary.js +35 -0
  22. package/lib/client/exports/Interpolate.js +12 -15
  23. package/lib/client/exports/Link.js +11 -11
  24. package/lib/client/exports/Translate.d.ts +2 -2
  25. package/lib/client/exports/Translate.js +13 -9
  26. package/lib/client/exports/browserContext.d.ts +11 -0
  27. package/lib/client/exports/browserContext.js +21 -0
  28. package/lib/client/exports/constants.js +1 -11
  29. package/lib/client/exports/{context.d.ts → docusaurusContext.d.ts} +5 -3
  30. package/lib/client/exports/docusaurusContext.js +25 -0
  31. package/lib/client/exports/useBaseUrl.js +2 -4
  32. package/lib/client/exports/useDocusaurusContext.js +2 -7
  33. package/lib/client/exports/useGlobalData.js +1 -5
  34. package/lib/client/exports/{context.js → useIsBrowser.d.ts} +1 -2
  35. package/lib/{webpack/sharedModuleAliases.d.ts → client/exports/useIsBrowser.js} +5 -4
  36. package/lib/client/flat.d.ts +2 -1
  37. package/lib/client/flat.js +7 -9
  38. package/lib/client/normalizeLocation.d.ts +1 -3
  39. package/lib/client/prefetch.js +0 -1
  40. package/lib/client/serverEntry.js +15 -31
  41. package/lib/client/theme-fallback/Error/index.js +47 -0
  42. package/lib/client/theme-fallback/Layout/index.js +1 -1
  43. package/lib/client/theme-fallback/Loading/index.js +2 -2
  44. package/lib/client/theme-fallback/Root/index.js +1 -3
  45. package/lib/commands/build.js +37 -40
  46. package/lib/commands/clear.d.ts +6 -0
  47. package/lib/commands/clear.js +9 -9
  48. package/lib/commands/commandUtils.d.ts +6 -0
  49. package/lib/commands/commandUtils.js +7 -7
  50. package/lib/commands/deploy.d.ts +3 -0
  51. package/lib/commands/deploy.js +98 -53
  52. package/lib/commands/external.js +4 -4
  53. package/lib/commands/serve.js +13 -13
  54. package/lib/commands/start.js +83 -73
  55. package/lib/commands/swizzle.js +49 -49
  56. package/lib/commands/writeHeadingIds.d.ts +9 -6
  57. package/lib/commands/writeHeadingIds.js +32 -32
  58. package/lib/commands/writeTranslations.js +31 -11
  59. package/lib/server/brokenLinks.js +13 -17
  60. package/lib/server/client-modules/index.js +1 -3
  61. package/lib/server/config.js +4 -4
  62. package/lib/server/configValidation.d.ts +1 -1
  63. package/lib/server/configValidation.js +12 -7
  64. package/lib/server/duplicateRoutes.js +8 -2
  65. package/lib/server/html-tags/htmlTags.js +5 -6
  66. package/lib/server/html-tags/index.d.ts +2 -2
  67. package/lib/server/html-tags/index.js +3 -3
  68. package/lib/server/i18n.js +16 -13
  69. package/lib/server/index.js +129 -71
  70. package/lib/server/loadSetup.js +3 -3
  71. package/lib/server/moduleShorthand.d.ts +9 -0
  72. package/lib/server/moduleShorthand.js +42 -0
  73. package/lib/server/plugins/applyRouteTrailingSlash.d.ts +2 -1
  74. package/lib/server/plugins/applyRouteTrailingSlash.js +3 -3
  75. package/lib/server/plugins/index.d.ts +3 -4
  76. package/lib/server/plugins/index.js +44 -33
  77. package/lib/server/plugins/init.d.ts +2 -6
  78. package/lib/server/plugins/init.js +9 -12
  79. package/lib/server/plugins/pluginIds.d.ts +2 -2
  80. package/lib/server/plugins/pluginIds.js +6 -4
  81. package/lib/server/presets/index.js +12 -12
  82. package/lib/server/routes.js +41 -23
  83. package/lib/server/themes/alias.d.ts +3 -2
  84. package/lib/server/themes/alias.js +22 -12
  85. package/lib/server/themes/index.d.ts +6 -2
  86. package/lib/server/themes/index.js +32 -21
  87. package/lib/server/translations/translations.d.ts +10 -5
  88. package/lib/server/translations/translations.js +15 -17
  89. package/lib/server/translations/translationsExtractor.d.ts +8 -3
  90. package/lib/server/translations/translationsExtractor.js +65 -56
  91. package/lib/server/utils.d.ts +8 -2
  92. package/lib/server/utils.js +8 -10
  93. package/lib/server/versions/__fixtures__/dummy-plugin.d.ts +0 -0
  94. package/lib/server/versions/__tests/index.test.js +5 -5
  95. package/lib/server/versions/index.js +6 -6
  96. package/lib/webpack/base.js +29 -21
  97. package/lib/webpack/client.js +8 -17
  98. package/lib/webpack/plugins/CleanWebpackPlugin.js +4 -11
  99. package/lib/webpack/plugins/LogPlugin.js +5 -6
  100. package/lib/webpack/plugins/WaitPlugin.js +4 -4
  101. package/lib/webpack/server.js +13 -9
  102. package/lib/webpack/utils.d.ts +2 -23
  103. package/lib/webpack/utils.js +29 -127
  104. package/package.json +56 -51
  105. package/tsconfig.client.json +1 -2
  106. package/tsconfig.json +5 -4
  107. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  108. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  109. package/lib/constants.d.ts +0 -18
  110. package/lib/constants.js +0 -23
  111. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  112. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  113. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  114. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  115. package/lib/webpack/sharedModuleAliases.js +0 -18
@@ -9,23 +9,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  const tslib_1 = require("tslib");
10
10
  const utils_1 = require("@docusaurus/utils");
11
11
  const chalk = require("chalk");
12
- const chokidar_1 = tslib_1.__importDefault(require("chokidar"));
13
- const express_1 = tslib_1.__importDefault(require("express"));
14
- const html_webpack_plugin_1 = tslib_1.__importDefault(require("html-webpack-plugin"));
15
- const path_1 = tslib_1.__importDefault(require("path"));
12
+ const chokidar_1 = (0, tslib_1.__importDefault)(require("chokidar"));
13
+ const html_webpack_plugin_1 = (0, tslib_1.__importDefault)(require("html-webpack-plugin"));
14
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
16
15
  const lodash_1 = require("lodash");
17
- const openBrowser_1 = tslib_1.__importDefault(require("react-dev-utils/openBrowser"));
16
+ const openBrowser_1 = (0, tslib_1.__importDefault)(require("react-dev-utils/openBrowser"));
18
17
  const WebpackDevServerUtils_1 = require("react-dev-utils/WebpackDevServerUtils");
19
- const errorOverlayMiddleware_1 = tslib_1.__importDefault(require("react-dev-utils/errorOverlayMiddleware"));
20
- // import evalSourceMapMiddleware from 'react-dev-utils/evalSourceMapMiddleware';
21
- const evalSourceMapMiddleware_1 = tslib_1.__importDefault(require("../webpack/react-dev-utils-webpack5/evalSourceMapMiddleware"));
22
- const webpack_1 = tslib_1.__importDefault(require("webpack"));
23
- const webpack_dev_server_1 = tslib_1.__importDefault(require("webpack-dev-server"));
24
- const webpack_merge_1 = tslib_1.__importDefault(require("webpack-merge"));
25
- const HotModuleReplacementPlugin_1 = tslib_1.__importDefault(require("webpack/lib/HotModuleReplacementPlugin"));
18
+ const evalSourceMapMiddleware_1 = (0, tslib_1.__importDefault)(require("react-dev-utils/evalSourceMapMiddleware"));
19
+ const webpack_1 = (0, tslib_1.__importDefault)(require("webpack"));
20
+ const webpack_dev_server_1 = (0, tslib_1.__importDefault)(require("webpack-dev-server"));
21
+ const webpack_merge_1 = (0, tslib_1.__importDefault)(require("webpack-merge"));
26
22
  const server_1 = require("../server");
27
- const constants_1 = require("../constants");
28
- const client_1 = tslib_1.__importDefault(require("../webpack/client"));
23
+ const client_1 = (0, tslib_1.__importDefault)(require("../webpack/client"));
29
24
  const utils_2 = require("../webpack/utils");
30
25
  const commandUtils_1 = require("./commandUtils");
31
26
  const translations_1 = require("../server/translations/translations");
@@ -34,7 +29,7 @@ async function start(siteDir, cliOptions) {
34
29
  process.env.BABEL_ENV = 'development';
35
30
  console.log(chalk.blue('Starting the development server...'));
36
31
  function loadSite() {
37
- return server_1.load(siteDir, {
32
+ return (0, server_1.load)(siteDir, {
38
33
  customConfigFilePath: cliOptions.config,
39
34
  locale: cliOptions.locale,
40
35
  localizePath: undefined, // should this be configurable?
@@ -43,20 +38,20 @@ async function start(siteDir, cliOptions) {
43
38
  // Process all related files as a prop.
44
39
  const props = await loadSite();
45
40
  const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
46
- const host = commandUtils_1.getCLIOptionHost(cliOptions.host);
47
- const port = await commandUtils_1.getCLIOptionPort(cliOptions.port, host);
41
+ const host = (0, commandUtils_1.getCLIOptionHost)(cliOptions.host);
42
+ const port = await (0, commandUtils_1.getCLIOptionPort)(cliOptions.port, host);
48
43
  if (port === null) {
49
44
  process.exit();
50
45
  }
51
46
  const { baseUrl, headTags, preBodyTags, postBodyTags } = props;
52
- const urls = WebpackDevServerUtils_1.prepareUrls(protocol, host, port);
53
- const openUrl = utils_1.normalizeUrl([urls.localUrlForBrowser, baseUrl]);
47
+ const urls = (0, WebpackDevServerUtils_1.prepareUrls)(protocol, host, port);
48
+ const openUrl = (0, utils_1.normalizeUrl)([urls.localUrlForBrowser, baseUrl]);
54
49
  console.log(chalk.cyanBright(`Docusaurus website is running at "${openUrl}".`));
55
50
  // Reload files processing.
56
- const reload = lodash_1.debounce(() => {
51
+ const reload = (0, lodash_1.debounce)(() => {
57
52
  loadSite()
58
53
  .then(({ baseUrl: newBaseUrl }) => {
59
- const newOpenUrl = utils_1.normalizeUrl([urls.localUrlForBrowser, newBaseUrl]);
54
+ const newOpenUrl = (0, utils_1.normalizeUrl)([urls.localUrlForBrowser, newBaseUrl]);
60
55
  if (newOpenUrl !== openUrl) {
61
56
  console.log(chalk.cyanBright(`Docusaurus website is running at "${newOpenUrl}".`));
62
57
  }
@@ -68,9 +63,9 @@ async function start(siteDir, cliOptions) {
68
63
  const { siteConfig, plugins = [] } = props;
69
64
  const normalizeToSiteDir = (filepath) => {
70
65
  if (filepath && path_1.default.isAbsolute(filepath)) {
71
- return utils_1.posixPath(path_1.default.relative(siteDir, filepath));
66
+ return (0, utils_1.posixPath)(path_1.default.relative(siteDir, filepath));
72
67
  }
73
- return utils_1.posixPath(filepath);
68
+ return (0, utils_1.posixPath)(filepath);
74
69
  };
75
70
  const pluginPaths = []
76
71
  .concat(...plugins
@@ -80,21 +75,29 @@ async function start(siteDir, cliOptions) {
80
75
  const pathsToWatch = [
81
76
  ...pluginPaths,
82
77
  props.siteConfigPath,
83
- translations_1.getTranslationsLocaleDirPath({
78
+ (0, translations_1.getTranslationsLocaleDirPath)({
84
79
  siteDir,
85
80
  locale: props.i18n.currentLocale,
86
81
  }),
87
82
  ];
88
- const fsWatcher = chokidar_1.default.watch(pathsToWatch, {
89
- cwd: siteDir,
90
- ignoreInitial: true,
83
+ const pollingOptions = {
91
84
  usePolling: !!cliOptions.poll,
92
85
  interval: Number.isInteger(cliOptions.poll)
93
86
  ? cliOptions.poll
94
87
  : undefined,
88
+ };
89
+ const httpsConfig = (0, utils_2.getHttpsConfig)();
90
+ const fsWatcher = chokidar_1.default.watch(pathsToWatch, {
91
+ cwd: siteDir,
92
+ ignoreInitial: true,
93
+ ...{ pollingOptions },
95
94
  });
96
95
  ['add', 'change', 'unlink', 'addDir', 'unlinkDir'].forEach((event) => fsWatcher.on(event, reload));
97
- let config = webpack_merge_1.default(client_1.default(props), {
96
+ let config = (0, webpack_merge_1.default)((0, client_1.default)(props), {
97
+ infrastructureLogging: {
98
+ // Reduce log verbosity, see https://github.com/facebook/docusaurus/pull/5420#issuecomment-906613105
99
+ level: 'warn',
100
+ },
98
101
  plugins: [
99
102
  // Generates an `index.html` file with the <script> injected.
100
103
  new html_webpack_plugin_1.default({
@@ -107,8 +110,6 @@ async function start(siteDir, cliOptions) {
107
110
  preBodyTags,
108
111
  postBodyTags,
109
112
  }),
110
- // This is necessary to emit hot updates for webpack-dev-server.
111
- new HotModuleReplacementPlugin_1.default(),
112
113
  ],
113
114
  });
114
115
  // Plugin Lifecycle - configureWebpack and configurePostCss.
@@ -116,53 +117,65 @@ async function start(siteDir, cliOptions) {
116
117
  var _a;
117
118
  const { configureWebpack, configurePostCss } = plugin;
118
119
  if (configurePostCss) {
119
- config = utils_2.applyConfigurePostCss(configurePostCss, config);
120
+ config = (0, utils_2.applyConfigurePostCss)(configurePostCss, config);
120
121
  }
121
122
  if (configureWebpack) {
122
- config = utils_2.applyConfigureWebpack(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`.
123
- config, false, (_a = props.siteConfig.webpack) === null || _a === void 0 ? void 0 : _a.jsLoader);
123
+ config = (0, utils_2.applyConfigureWebpack)(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`. // TODO remove this implicit api: inject in callback instead
124
+ config, false, (_a = props.siteConfig.webpack) === null || _a === void 0 ? void 0 : _a.jsLoader, plugin.content);
124
125
  }
125
126
  });
126
127
  // https://webpack.js.org/configuration/dev-server
127
128
  const devServerConfig = {
128
- ...{
129
- compress: true,
130
- clientLogLevel: 'error',
131
- hot: true,
132
- hotOnly: cliOptions.hotOnly,
133
- // Use 'ws' instead of 'sockjs-node' on server since we're using native
134
- // websockets in `webpackHotDevClient`.
135
- transportMode: 'ws',
136
- // Prevent a WS client from getting injected as we're already including
137
- // `webpackHotDevClient`.
138
- injectClient: false,
139
- quiet: true,
140
- https: utils_2.getHttpsConfig(),
141
- headers: {
142
- 'access-control-allow-origin': '*',
129
+ hot: cliOptions.hotOnly ? 'only' : true,
130
+ liveReload: false,
131
+ client: {
132
+ progress: true,
133
+ overlay: {
134
+ warnings: false,
135
+ errors: true,
143
136
  },
137
+ },
138
+ headers: {
139
+ 'access-control-allow-origin': '*',
140
+ },
141
+ devMiddleware: {
144
142
  publicPath: baseUrl,
145
- watchOptions: {
146
- ignored: /node_modules/,
147
- poll: cliOptions.poll,
148
- },
149
- historyApiFallback: {
150
- rewrites: [{ from: /\/*/, to: baseUrl }],
151
- },
152
- disableHostCheck: true,
153
- // Disable overlay on browser since we use CRA's overlay error reporting.
154
- overlay: false,
155
- host,
156
- before: (app, server) => {
157
- app.use(baseUrl, express_1.default.static(path_1.default.resolve(siteDir, constants_1.STATIC_DIR_NAME)));
158
- // This lets us fetch source contents from webpack for the error overlay.
159
- app.use(evalSourceMapMiddleware_1.default(server));
160
- // This lets us open files from the runtime error overlay.
161
- app.use(errorOverlayMiddleware_1.default());
143
+ // Reduce log verbosity, see https://github.com/facebook/docusaurus/pull/5420#issuecomment-906613105
144
+ stats: 'summary',
145
+ },
146
+ static: siteConfig.staticDirectories.map((dir) => ({
147
+ publicPath: baseUrl,
148
+ directory: path_1.default.resolve(siteDir, dir),
149
+ watch: {
150
+ // Useful options for our own monorepo using symlinks!
151
+ // See https://github.com/webpack/webpack/issues/11612#issuecomment-879259806
152
+ followSymlinks: true,
153
+ ignored: /node_modules\/(?!@docusaurus)/,
154
+ ...{ pollingOptions },
162
155
  },
156
+ })),
157
+ ...(httpsConfig && {
158
+ server: typeof httpsConfig === 'object'
159
+ ? {
160
+ type: 'https',
161
+ options: httpsConfig,
162
+ }
163
+ : 'https',
164
+ }),
165
+ historyApiFallback: {
166
+ rewrites: [{ from: /\/*/, to: baseUrl }],
167
+ },
168
+ allowedHosts: 'all',
169
+ host,
170
+ port,
171
+ onBeforeSetupMiddleware: (devServer) => {
172
+ // This lets us fetch source contents from webpack for the error overlay.
173
+ devServer.app.use((0, evalSourceMapMiddleware_1.default)(
174
+ // @ts-expect-error: bad types
175
+ devServer));
163
176
  },
164
177
  };
165
- const compiler = webpack_1.default(config);
178
+ const compiler = (0, webpack_1.default)(config);
166
179
  if (process.env.E2E_TEST) {
167
180
  compiler.hooks.done.tap('done', (stats) => {
168
181
  if (stats.hasErrors()) {
@@ -173,18 +186,15 @@ async function start(siteDir, cliOptions) {
173
186
  process.exit(0);
174
187
  });
175
188
  }
176
- const devServer = new webpack_dev_server_1.default(compiler, devServerConfig);
177
- devServer.listen(port, host, (err) => {
178
- if (err) {
179
- console.log(err);
180
- }
189
+ const devServer = new webpack_dev_server_1.default(devServerConfig, compiler);
190
+ devServer.startCallback(() => {
181
191
  if (cliOptions.open) {
182
- openBrowser_1.default(openUrl);
192
+ (0, openBrowser_1.default)(openUrl);
183
193
  }
184
194
  });
185
195
  ['SIGINT', 'SIGTERM'].forEach((sig) => {
186
196
  process.on(sig, () => {
187
- devServer.close();
197
+ devServer.stop();
188
198
  process.exit();
189
199
  });
190
200
  });
@@ -8,15 +8,15 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.getPluginNames = void 0;
10
10
  const tslib_1 = require("tslib");
11
- const chalk = require("chalk");
12
- const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
13
- const import_fresh_1 = tslib_1.__importDefault(require("import-fresh"));
14
- const path_1 = tslib_1.__importDefault(require("path"));
15
- const leven_1 = tslib_1.__importDefault(require("leven"));
11
+ const chalk_1 = (0, tslib_1.__importDefault)(require("chalk"));
12
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
13
+ const import_fresh_1 = (0, tslib_1.__importDefault)(require("import-fresh"));
14
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
15
+ const leven_1 = (0, tslib_1.__importDefault)(require("leven"));
16
16
  const lodash_1 = require("lodash");
17
- const constants_1 = require("../constants");
17
+ const utils_1 = require("@docusaurus/utils");
18
18
  const server_1 = require("../server");
19
- const init_1 = tslib_1.__importDefault(require("../server/plugins/init"));
19
+ const init_1 = (0, tslib_1.__importDefault)(require("../server/plugins/init"));
20
20
  const utils_validation_1 = require("@docusaurus/utils-validation");
21
21
  function getPluginNames(plugins) {
22
22
  return plugins
@@ -37,32 +37,32 @@ function getPluginNames(plugins) {
37
37
  if (packagePath === '.') {
38
38
  return pluginPath;
39
39
  }
40
- return import_fresh_1.default(path_1.default.join(packagePath, 'package.json')).name;
40
+ return (0, import_fresh_1.default)(path_1.default.join(packagePath, 'package.json')).name;
41
41
  }
42
42
  return '';
43
43
  })
44
44
  .filter((plugin) => plugin !== '');
45
45
  }
46
46
  exports.getPluginNames = getPluginNames;
47
- function walk(dir) {
48
- let results = [];
49
- const list = fs_extra_1.default.readdirSync(dir);
50
- list.forEach((file) => {
51
- const fullPath = path_1.default.join(dir, file);
52
- const stat = fs_extra_1.default.statSync(fullPath);
53
- if (stat && stat.isDirectory()) {
54
- results = results.concat(walk(fullPath));
55
- }
56
- else if (!/node_modules|.css|.d.ts|.d.map/.test(fullPath)) {
57
- results.push(fullPath);
58
- }
59
- });
60
- return results;
61
- }
62
47
  const formatComponentName = (componentName) => componentName
63
- .replace(/(\/|\\)index.(js|tsx|ts|jsx)/, '')
64
- .replace(/.(js|tsx|ts|jsx)/, '');
48
+ .replace(/(\/|\\)index\.(js|tsx|ts|jsx)/, '')
49
+ .replace(/\.(js|tsx|ts|jsx)/, '');
65
50
  function readComponent(themePath) {
51
+ function walk(dir) {
52
+ let results = [];
53
+ const list = fs_extra_1.default.readdirSync(dir);
54
+ list.forEach((file) => {
55
+ const fullPath = path_1.default.join(dir, file);
56
+ const stat = fs_extra_1.default.statSync(fullPath);
57
+ if (stat && stat.isDirectory()) {
58
+ results = results.concat(walk(fullPath));
59
+ }
60
+ else if (!/\.css|\.d\.ts|\.d\.map/.test(fullPath)) {
61
+ results.push(fullPath);
62
+ }
63
+ });
64
+ return results;
65
+ }
66
66
  return walk(themePath).map((filePath) => formatComponentName(path_1.default.relative(themePath, filePath)));
67
67
  }
68
68
  // load components from theme based on configurations
@@ -82,13 +82,13 @@ function getComponentName(themePath, plugin, danger) {
82
82
  function themeComponents(themePath, plugin) {
83
83
  const components = colorCode(themePath, plugin);
84
84
  if (components.length === 0) {
85
- return `${chalk.red('No component to swizzle.')}`;
85
+ return `${chalk_1.default.red('No component to swizzle.')}`;
86
86
  }
87
87
  return `
88
- ${chalk.cyan('Theme components available for swizzle.')}
88
+ ${chalk_1.default.cyan('Theme components available for swizzle.')}
89
89
 
90
- ${chalk.green('green =>')} safe: lower breaking change risk
91
- ${chalk.red('red =>')} unsafe: higher breaking change risk
90
+ ${chalk_1.default.green('green =>')} safe: lower breaking change risk
91
+ ${chalk_1.default.red('red =>')} unsafe: higher breaking change risk
92
92
 
93
93
  ${components.join('\n')}
94
94
  `;
@@ -104,18 +104,18 @@ function colorCode(themePath, plugin) {
104
104
  const allowedComponent = getSwizzleComponentList
105
105
  ? getSwizzleComponentList()
106
106
  : [];
107
- const [greenComponents, redComponents] = lodash_1.partition(components, (comp) => allowedComponent.includes(comp));
107
+ const [greenComponents, redComponents] = (0, lodash_1.partition)(components, (comp) => allowedComponent.includes(comp));
108
108
  return [
109
- ...greenComponents.map((component) => chalk.green(`safe: ${component}`)),
110
- ...redComponents.map((component) => chalk.red(`unsafe: ${component}`)),
109
+ ...greenComponents.map((component) => chalk_1.default.green(`safe: ${component}`)),
110
+ ...redComponents.map((component) => chalk_1.default.red(`unsafe: ${component}`)),
111
111
  ];
112
112
  }
113
113
  async function swizzle(siteDir, themeName, componentName, typescript, danger) {
114
114
  var _a, _b, _c, _d, _e;
115
- const context = await server_1.loadContext(siteDir);
116
- const pluginConfigs = server_1.loadPluginConfigs(context);
115
+ const context = await (0, server_1.loadContext)(siteDir);
116
+ const pluginConfigs = (0, server_1.loadPluginConfigs)(context);
117
117
  const pluginNames = getPluginNames(pluginConfigs);
118
- const plugins = init_1.default({
118
+ const plugins = (0, init_1.default)({
119
119
  pluginConfigs,
120
120
  context,
121
121
  });
@@ -128,16 +128,16 @@ async function swizzle(siteDir, themeName, componentName, typescript, danger) {
128
128
  }
129
129
  let pluginModule;
130
130
  try {
131
- pluginModule = import_fresh_1.default(themeName);
131
+ pluginModule = (0, import_fresh_1.default)(themeName);
132
132
  }
133
133
  catch {
134
134
  let suggestion;
135
135
  themeNames.forEach((name) => {
136
- if (leven_1.default(name, themeName) < 4) {
136
+ if ((0, leven_1.default)(name, themeName) < 4) {
137
137
  suggestion = name;
138
138
  }
139
139
  });
140
- chalk.red(`Theme ${themeName} not found. ${suggestion
140
+ chalk_1.default.red(`Theme ${themeName} not found. ${suggestion
141
141
  ? `Did you mean "${suggestion}" ?`
142
142
  : formattedThemeNames(themeNames)}`);
143
143
  process.exit(1);
@@ -171,7 +171,7 @@ async function swizzle(siteDir, themeName, componentName, typescript, danger) {
171
171
  ? (_d = pluginInstance.getTypeScriptThemePath) === null || _d === void 0 ? void 0 : _d.call(pluginInstance)
172
172
  : (_e = pluginInstance.getThemePath) === null || _e === void 0 ? void 0 : _e.call(pluginInstance);
173
173
  if (!themePath) {
174
- console.warn(chalk.yellow(typescript
174
+ console.warn(chalk_1.default.yellow(typescript
175
175
  ? `${themeName} does not provide TypeScript theme code via "getTypeScriptThemePath()".`
176
176
  : `${themeName} does not provide any theme code.`));
177
177
  process.exit(1);
@@ -190,7 +190,7 @@ async function swizzle(siteDir, themeName, componentName, typescript, danger) {
190
190
  components.forEach((component) => {
191
191
  if (component.toLowerCase() === formattedComponentName.toLowerCase()) {
192
192
  // may be components with same lowercase key, try to match closest component
193
- const currentScore = leven_1.default(formattedComponentName, component);
193
+ const currentScore = (0, leven_1.default)(formattedComponentName, component);
194
194
  if (currentScore < score) {
195
195
  score = currentScore;
196
196
  mostSuitableMatch = component;
@@ -199,11 +199,11 @@ async function swizzle(siteDir, themeName, componentName, typescript, danger) {
199
199
  });
200
200
  if (mostSuitableMatch !== componentName) {
201
201
  mostSuitableComponent = mostSuitableMatch;
202
- console.log(chalk.red(`Component "${componentName}" doesn't exists.`), chalk.yellow(`"${mostSuitableComponent}" is swizzled instead of "${componentName}".`));
202
+ console.log(chalk_1.default.red(`Component "${componentName}" doesn't exist.`), chalk_1.default.yellow(`"${mostSuitableComponent}" is swizzled instead of "${componentName}".`));
203
203
  }
204
204
  }
205
205
  let fromPath = path_1.default.join(themePath, mostSuitableComponent);
206
- let toPath = path_1.default.resolve(siteDir, constants_1.THEME_PATH, mostSuitableComponent);
206
+ let toPath = path_1.default.resolve(siteDir, utils_1.THEME_PATH, mostSuitableComponent);
207
207
  // Handle single TypeScript/JavaScript file only.
208
208
  // E.g: if <fromPath> does not exist, we try to swizzle <fromPath>.(ts|tsx|js) instead
209
209
  if (!fs_extra_1.default.existsSync(fromPath)) {
@@ -219,11 +219,11 @@ async function swizzle(siteDir, themeName, componentName, typescript, danger) {
219
219
  else {
220
220
  let suggestion;
221
221
  components.forEach((name) => {
222
- if (leven_1.default(name, mostSuitableComponent) < 3) {
222
+ if ((0, leven_1.default)(name, mostSuitableComponent) < 3) {
223
223
  suggestion = name;
224
224
  }
225
225
  });
226
- console.warn(chalk.red(`Component ${mostSuitableComponent} not found.`));
226
+ console.warn(chalk_1.default.red(`Component ${mostSuitableComponent} not found.`));
227
227
  console.warn(suggestion
228
228
  ? `Did you mean "${suggestion}"?`
229
229
  : `${themeComponents(themePath, pluginModule)}`);
@@ -231,15 +231,15 @@ async function swizzle(siteDir, themeName, componentName, typescript, danger) {
231
231
  }
232
232
  }
233
233
  if (!components.includes(mostSuitableComponent) && !danger) {
234
- console.warn(chalk.red(`${mostSuitableComponent} is an internal component, and have a higher breaking change probability. If you want to swizzle it, use the "--danger" flag.`));
234
+ console.warn(chalk_1.default.red(`${mostSuitableComponent} is an internal component and has a higher breaking change probability. If you want to swizzle it, use the "--danger" flag.`));
235
235
  process.exit(1);
236
236
  }
237
237
  await fs_extra_1.default.copy(fromPath, toPath);
238
238
  const relativeDir = path_1.default.relative(process.cwd(), toPath);
239
- const fromMsg = chalk.blue(mostSuitableComponent
240
- ? `${themeName} ${chalk.yellow(mostSuitableComponent)}`
239
+ const fromMsg = chalk_1.default.blue(mostSuitableComponent
240
+ ? `${themeName} ${chalk_1.default.yellow(mostSuitableComponent)}`
241
241
  : themeName);
242
- const toMsg = chalk.cyan(relativeDir);
243
- console.log(`\n${chalk.green('Success!')} Copied ${fromMsg} to ${toMsg}.\n`);
242
+ const toMsg = chalk_1.default.cyan(relativeDir);
243
+ console.log(`\n${chalk_1.default.green('Success!')} Copied ${fromMsg} to ${toMsg}.\n`);
244
244
  }
245
245
  exports.default = swizzle;
@@ -4,9 +4,12 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import GithubSlugger from 'github-slugger';
8
- export declare function unwrapMarkdownLinks(line: string): string;
9
- export declare function transformMarkdownHeadingLine(line: string, slugger: GithubSlugger): string;
10
- export declare function transformMarkdownLine(line: string, slugger: GithubSlugger): string;
11
- export declare function transformMarkdownContent(content: string): string;
12
- export default function writeHeadingIds(siteDir: string): Promise<void>;
7
+ import { Slugger } from '@docusaurus/utils';
8
+ declare type Options = {
9
+ maintainCase?: boolean;
10
+ overwrite?: boolean;
11
+ };
12
+ export declare function transformMarkdownHeadingLine(line: string, slugger: Slugger, options?: Options): string;
13
+ export declare function transformMarkdownContent(content: string, options?: Options): string;
14
+ export default function writeHeadingIds(siteDir: string, files?: string, options?: Options): Promise<void>;
15
+ export {};
@@ -6,55 +6,55 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.transformMarkdownContent = exports.transformMarkdownLine = exports.transformMarkdownHeadingLine = exports.unwrapMarkdownLinks = void 0;
9
+ exports.transformMarkdownContent = exports.transformMarkdownHeadingLine = void 0;
10
10
  const tslib_1 = require("tslib");
11
- const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
12
- const github_slugger_1 = tslib_1.__importDefault(require("github-slugger"));
13
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
11
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
12
+ const chalk_1 = (0, tslib_1.__importDefault)(require("chalk"));
14
13
  const server_1 = require("../server");
15
- const init_1 = tslib_1.__importDefault(require("../server/plugins/init"));
16
- const lodash_1 = require("lodash");
14
+ const init_1 = (0, tslib_1.__importDefault)(require("../server/plugins/init"));
17
15
  const utils_1 = require("@docusaurus/utils");
18
16
  const utils_2 = require("../server/utils");
19
17
  function unwrapMarkdownLinks(line) {
20
18
  return line.replace(/\[([^\]]+)\]\([^)]+\)/g, (match, p1) => p1);
21
19
  }
22
- exports.unwrapMarkdownLinks = unwrapMarkdownLinks;
23
- function addHeadingId(line, slugger) {
20
+ function addHeadingId(line, slugger, maintainCase) {
24
21
  let headingLevel = 0;
25
22
  while (line.charAt(headingLevel) === '#') {
26
23
  headingLevel += 1;
27
24
  }
28
25
  const headingText = line.slice(headingLevel).trimEnd();
29
26
  const headingHashes = line.slice(0, headingLevel);
30
- const slug = slugger.slug(unwrapMarkdownLinks(headingText));
27
+ const slug = slugger
28
+ .slug(unwrapMarkdownLinks(headingText).trim(), { maintainCase })
29
+ .replace(/^-+/, '')
30
+ .replace(/-+$/, '');
31
31
  return `${headingHashes}${headingText} {#${slug}}`;
32
32
  }
33
- function transformMarkdownHeadingLine(line, slugger) {
33
+ function transformMarkdownHeadingLine(line, slugger, options = { maintainCase: false, overwrite: false }) {
34
+ const { maintainCase = false, overwrite = false } = options;
34
35
  if (!line.startsWith('#')) {
35
36
  throw new Error(`Line is not a Markdown heading: ${line}.`);
36
37
  }
37
- const parsedHeading = utils_1.parseMarkdownHeadingId(line);
38
- // Do not process if id is already therer
39
- if (parsedHeading.id) {
38
+ const parsedHeading = (0, utils_1.parseMarkdownHeadingId)(line);
39
+ // Do not process if id is already there
40
+ if (parsedHeading.id && !overwrite) {
40
41
  return line;
41
42
  }
42
- return addHeadingId(line, slugger);
43
+ return addHeadingId(parsedHeading.text, slugger, maintainCase);
43
44
  }
44
45
  exports.transformMarkdownHeadingLine = transformMarkdownHeadingLine;
45
- function transformMarkdownLine(line, slugger) {
46
+ function transformMarkdownLine(line, slugger, options) {
46
47
  // Ignore h1 headings on purpose, as we don't create anchor links for those
47
48
  if (line.startsWith('##')) {
48
- return transformMarkdownHeadingLine(line, slugger);
49
+ return transformMarkdownHeadingLine(line, slugger, options);
49
50
  }
50
51
  else {
51
52
  return line;
52
53
  }
53
54
  }
54
- exports.transformMarkdownLine = transformMarkdownLine;
55
- function transformMarkdownLines(lines) {
55
+ function transformMarkdownLines(lines, options) {
56
56
  let inCode = false;
57
- const slugger = new github_slugger_1.default();
57
+ const slugger = (0, utils_1.createSlugger)();
58
58
  return lines.map((line) => {
59
59
  if (line.startsWith('```')) {
60
60
  inCode = !inCode;
@@ -64,17 +64,17 @@ function transformMarkdownLines(lines) {
64
64
  if (inCode) {
65
65
  return line;
66
66
  }
67
- return transformMarkdownLine(line, slugger);
67
+ return transformMarkdownLine(line, slugger, options);
68
68
  }
69
69
  });
70
70
  }
71
- function transformMarkdownContent(content) {
72
- return transformMarkdownLines(content.split('\n')).join('\n');
71
+ function transformMarkdownContent(content, options) {
72
+ return transformMarkdownLines(content.split('\n'), options).join('\n');
73
73
  }
74
74
  exports.transformMarkdownContent = transformMarkdownContent;
75
- async function transformMarkdownFile(filepath) {
75
+ async function transformMarkdownFile(filepath, options) {
76
76
  const content = await fs_extra_1.default.readFile(filepath, 'utf8');
77
- const updatedContent = transformMarkdownLines(content.split('\n')).join('\n');
77
+ const updatedContent = transformMarkdownLines(content.split('\n'), options).join('\n');
78
78
  if (content !== updatedContent) {
79
79
  await fs_extra_1.default.writeFile(filepath, updatedContent);
80
80
  return filepath;
@@ -85,26 +85,26 @@ async function transformMarkdownFile(filepath) {
85
85
  // Also we don't want to transform the site md docs that do not belong to a content plugin
86
86
  // For example ./README.md should not be transformed
87
87
  async function getPathsToWatch(siteDir) {
88
- const context = await server_1.loadContext(siteDir);
89
- const pluginConfigs = server_1.loadPluginConfigs(context);
90
- const plugins = await init_1.default({
88
+ const context = await (0, server_1.loadContext)(siteDir);
89
+ const pluginConfigs = (0, server_1.loadPluginConfigs)(context);
90
+ const plugins = (0, init_1.default)({
91
91
  pluginConfigs,
92
92
  context,
93
93
  });
94
- return lodash_1.flatten(plugins.map((plugin) => { var _a, _b; return (_b = (_a = plugin === null || plugin === void 0 ? void 0 : plugin.getPathsToWatch) === null || _a === void 0 ? void 0 : _a.call(plugin)) !== null && _b !== void 0 ? _b : []; }));
94
+ return plugins.flatMap((plugin) => { var _a, _b; return (_b = (_a = plugin === null || plugin === void 0 ? void 0 : plugin.getPathsToWatch) === null || _a === void 0 ? void 0 : _a.call(plugin)) !== null && _b !== void 0 ? _b : []; });
95
95
  }
96
- async function writeHeadingIds(siteDir) {
97
- const markdownFiles = await utils_2.safeGlobby(await getPathsToWatch(siteDir), {
96
+ async function writeHeadingIds(siteDir, files, options) {
97
+ const markdownFiles = await (0, utils_2.safeGlobby)(files ? [files] : await getPathsToWatch(siteDir), {
98
98
  expandDirectories: ['**/*.{md,mdx}'],
99
99
  });
100
- const result = await Promise.all(markdownFiles.map(transformMarkdownFile));
100
+ const result = await Promise.all(markdownFiles.map((p) => transformMarkdownFile(p, options)));
101
101
  const pathsModified = result.filter(Boolean);
102
102
  if (pathsModified.length) {
103
103
  console.log(chalk_1.default.green(`Heading ids added to Markdown files (${pathsModified.length}/${markdownFiles.length} files):
104
104
  - ${pathsModified.join('\n- ')}`));
105
105
  }
106
106
  else {
107
- console.log(chalk_1.default.yellow(`${markdownFiles.length} Markdown files already have explicit heading ids.`));
107
+ console.log(chalk_1.default.yellow(`${markdownFiles.length} Markdown files already have explicit heading IDs. If you intend to overwrite the existing heading IDs, use the ${chalk_1.default.cyan('--overwrite')} option.`));
108
108
  }
109
109
  }
110
110
  exports.default = writeHeadingIds;