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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/bin/beforeCli.mjs +136 -0
  2. package/bin/{docusaurus.js → docusaurus.mjs} +63 -108
  3. package/lib/babel/preset.d.ts +8 -3
  4. package/lib/babel/preset.js +8 -7
  5. package/lib/choosePort.js +29 -38
  6. package/lib/client/.eslintrc.js +0 -1
  7. package/lib/client/App.d.ts +1 -2
  8. package/lib/client/App.js +19 -24
  9. package/lib/client/LinksCollector.d.ts +3 -3
  10. package/lib/client/LinksCollector.js +5 -9
  11. package/lib/client/PendingNavigation.d.ts +24 -1
  12. package/lib/client/PendingNavigation.js +5 -7
  13. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.d.ts +13 -0
  14. package/lib/client/baseUrlIssueBanner/BaseUrlIssueBanner.js +15 -10
  15. package/lib/client/client-lifecycles-dispatcher.d.ts +2 -5
  16. package/lib/client/client-lifecycles-dispatcher.js +6 -10
  17. package/lib/client/clientEntry.js +11 -5
  18. package/lib/client/docusaurus.d.ts +6 -0
  19. package/lib/client/docusaurus.js +16 -25
  20. package/lib/client/exports/BrowserOnly.d.ts +2 -3
  21. package/lib/client/exports/BrowserOnly.js +13 -7
  22. package/lib/client/exports/ComponentCreator.d.ts +1 -2
  23. package/lib/client/exports/ComponentCreator.js +7 -6
  24. package/lib/client/exports/ErrorBoundary.d.ts +18 -0
  25. package/lib/client/exports/ErrorBoundary.js +35 -0
  26. package/lib/client/exports/Head.d.ts +2 -3
  27. package/lib/client/exports/Head.js +3 -4
  28. package/lib/client/exports/Interpolate.d.ts +1 -1
  29. package/lib/client/exports/Interpolate.js +16 -22
  30. package/lib/client/exports/Link.d.ts +11 -5
  31. package/lib/client/exports/Link.js +24 -19
  32. package/lib/client/exports/Translate.d.ts +3 -3
  33. package/lib/client/exports/Translate.js +14 -10
  34. package/lib/client/exports/browserContext.d.ts +11 -0
  35. package/lib/client/exports/browserContext.js +22 -0
  36. package/lib/client/exports/constants.js +1 -11
  37. package/lib/client/exports/docusaurusContext.d.ts +12 -0
  38. package/lib/client/exports/docusaurusContext.js +25 -0
  39. package/lib/client/exports/isInternalUrl.js +1 -1
  40. package/lib/client/exports/renderRoutes.d.ts +1 -2
  41. package/lib/client/exports/renderRoutes.js +1 -2
  42. package/lib/client/exports/router.d.ts +1 -1
  43. package/lib/client/exports/router.js +1 -1
  44. package/lib/client/exports/useBaseUrl.js +3 -5
  45. package/lib/client/exports/useDocusaurusContext.d.ts +2 -3
  46. package/lib/client/exports/useDocusaurusContext.js +3 -9
  47. package/lib/client/exports/useGlobalData.js +1 -5
  48. package/lib/{server/versions/__tests/index.test.d.ts → client/exports/useIsBrowser.d.ts} +1 -1
  49. package/lib/client/exports/useIsBrowser.js +11 -0
  50. package/lib/client/flat.d.ts +2 -2
  51. package/lib/client/flat.js +8 -11
  52. package/lib/client/normalizeLocation.d.ts +2 -5
  53. package/lib/client/normalizeLocation.js +1 -2
  54. package/lib/client/nprogress.css +2 -2
  55. package/lib/client/prefetch.d.ts +1 -2
  56. package/lib/client/prefetch.js +1 -3
  57. package/lib/client/preload.d.ts +3 -2
  58. package/lib/client/preload.js +2 -1
  59. package/lib/client/serverEntry.d.ts +10 -0
  60. package/lib/client/serverEntry.js +90 -142
  61. package/lib/client/theme-fallback/Error/index.d.ts +10 -0
  62. package/lib/client/theme-fallback/Error/index.js +39 -0
  63. package/lib/client/theme-fallback/Layout/index.d.ts +10 -0
  64. package/lib/client/theme-fallback/Layout/index.js +10 -19
  65. package/lib/client/theme-fallback/Loading/index.d.ts +9 -0
  66. package/lib/client/theme-fallback/Loading/index.js +47 -115
  67. package/lib/client/{exports/context.js → theme-fallback/NotFound/index.d.ts} +2 -2
  68. package/lib/client/theme-fallback/NotFound/index.js +9 -16
  69. package/lib/{webpack/sharedModuleAliases.d.ts → client/theme-fallback/Root/index.d.ts} +4 -4
  70. package/lib/client/theme-fallback/Root/index.js +2 -7
  71. package/lib/commands/build.d.ts +1 -1
  72. package/lib/commands/build.js +50 -54
  73. package/lib/commands/clear.d.ts +6 -0
  74. package/lib/commands/clear.js +30 -19
  75. package/lib/commands/commandUtils.d.ts +7 -1
  76. package/lib/commands/commandUtils.js +6 -6
  77. package/lib/commands/deploy.d.ts +4 -1
  78. package/lib/commands/deploy.js +102 -66
  79. package/lib/commands/external.d.ts +2 -2
  80. package/lib/commands/external.js +3 -3
  81. package/lib/commands/serve.d.ts +1 -1
  82. package/lib/commands/serve.js +13 -19
  83. package/lib/commands/start.d.ts +1 -1
  84. package/lib/commands/start.js +93 -83
  85. package/lib/commands/swizzle/actions.d.ts +23 -0
  86. package/lib/commands/swizzle/actions.js +102 -0
  87. package/lib/commands/swizzle/common.d.ts +33 -0
  88. package/lib/commands/swizzle/common.js +56 -0
  89. package/lib/commands/swizzle/components.d.ts +29 -0
  90. package/lib/commands/swizzle/components.js +162 -0
  91. package/lib/commands/swizzle/config.d.ts +10 -0
  92. package/lib/commands/swizzle/config.js +80 -0
  93. package/lib/{server/loadSetup.d.ts → commands/swizzle/context.d.ts} +2 -3
  94. package/lib/commands/swizzle/context.js +30 -0
  95. package/lib/commands/swizzle/index.d.ts +8 -0
  96. package/lib/commands/swizzle/index.js +115 -0
  97. package/lib/commands/swizzle/prompts.d.ts +12 -0
  98. package/lib/commands/swizzle/prompts.js +110 -0
  99. package/lib/{client/exports/context.d.ts → commands/swizzle/tables.d.ts} +3 -4
  100. package/lib/commands/swizzle/tables.js +116 -0
  101. package/lib/commands/swizzle/themes.d.ts +20 -0
  102. package/lib/commands/swizzle/themes.js +103 -0
  103. package/lib/commands/writeHeadingIds.d.ts +9 -6
  104. package/lib/commands/writeHeadingIds.js +41 -43
  105. package/lib/commands/writeTranslations.d.ts +2 -2
  106. package/lib/commands/writeTranslations.js +35 -14
  107. package/lib/index.d.ts +10 -9
  108. package/lib/index.js +20 -19
  109. package/lib/server/brokenLinks.d.ts +1 -1
  110. package/lib/server/brokenLinks.js +57 -38
  111. package/lib/server/client-modules/index.d.ts +1 -1
  112. package/lib/server/client-modules/index.js +1 -3
  113. package/lib/server/config.d.ts +2 -2
  114. package/lib/server/config.js +7 -4
  115. package/lib/server/configValidation.d.ts +2 -2
  116. package/lib/server/configValidation.js +43 -28
  117. package/lib/server/duplicateRoutes.d.ts +1 -1
  118. package/lib/server/duplicateRoutes.js +10 -6
  119. package/lib/server/html-tags/htmlTags.js +2 -4
  120. package/lib/server/html-tags/index.d.ts +1 -1
  121. package/lib/server/html-tags/index.js +1 -1
  122. package/lib/server/i18n.d.ts +1 -2
  123. package/lib/server/i18n.js +32 -46
  124. package/lib/server/index.d.ts +2 -2
  125. package/lib/server/index.js +147 -68
  126. package/lib/server/moduleShorthand.d.ts +9 -0
  127. package/lib/server/moduleShorthand.js +46 -0
  128. package/lib/server/plugins/applyRouteTrailingSlash.d.ts +2 -2
  129. package/lib/server/plugins/applyRouteTrailingSlash.js +1 -1
  130. package/lib/server/plugins/index.d.ts +2 -2
  131. package/lib/server/plugins/index.js +34 -35
  132. package/lib/server/plugins/init.d.ts +12 -2
  133. package/lib/server/plugins/init.js +48 -58
  134. package/lib/server/plugins/pluginIds.d.ts +1 -1
  135. package/lib/server/plugins/pluginIds.js +8 -5
  136. package/lib/server/presets/index.d.ts +3 -3
  137. package/lib/server/presets/index.js +12 -13
  138. package/lib/server/routes.d.ts +1 -1
  139. package/lib/server/routes.js +50 -29
  140. package/lib/server/themes/alias.d.ts +3 -2
  141. package/lib/server/themes/alias.js +22 -14
  142. package/lib/server/themes/index.d.ts +3 -3
  143. package/lib/server/themes/index.js +26 -26
  144. package/lib/server/translations/translations.d.ts +7 -1
  145. package/lib/server/translations/translations.js +30 -45
  146. package/lib/server/translations/translationsExtractor.d.ts +9 -3
  147. package/lib/server/translations/translationsExtractor.js +159 -120
  148. package/lib/server/utils.d.ts +9 -3
  149. package/lib/server/utils.js +7 -9
  150. package/lib/server/versions/__fixtures__/dummy-plugin.d.ts +0 -0
  151. package/lib/server/versions/index.d.ts +3 -4
  152. package/lib/server/versions/index.js +22 -21
  153. package/lib/webpack/base.d.ts +4 -4
  154. package/lib/webpack/base.js +38 -33
  155. package/lib/webpack/client.d.ts +3 -3
  156. package/lib/webpack/client.js +12 -19
  157. package/lib/webpack/plugins/ChunkAssetPlugin.d.ts +13 -3
  158. package/lib/webpack/plugins/ChunkAssetPlugin.js +17 -10
  159. package/lib/webpack/plugins/CleanWebpackPlugin.d.ts +6 -6
  160. package/lib/webpack/plugins/CleanWebpackPlugin.js +8 -14
  161. package/lib/webpack/plugins/LogPlugin.d.ts +1 -1
  162. package/lib/webpack/plugins/LogPlugin.js +4 -5
  163. package/lib/webpack/plugins/WaitPlugin.d.ts +1 -1
  164. package/lib/webpack/plugins/WaitPlugin.js +1 -1
  165. package/lib/webpack/server.d.ts +3 -3
  166. package/lib/webpack/server.js +9 -8
  167. package/lib/{client → webpack}/templates/index.html.template.ejs +0 -0
  168. package/lib/webpack/templates/ssr.html.template.d.ts +8 -0
  169. package/lib/{client → webpack}/templates/ssr.html.template.js +3 -2
  170. package/lib/webpack/utils.d.ts +7 -29
  171. package/lib/webpack/utils.js +54 -171
  172. package/package.json +74 -69
  173. package/lib/.tsbuildinfo +0 -1
  174. package/lib/client/.tsbuildinfo +0 -1
  175. package/lib/commands/buildRemoteBranchUrl.d.ts +0 -7
  176. package/lib/commands/buildRemoteBranchUrl.js +0 -27
  177. package/lib/commands/swizzle.d.ts +0 -9
  178. package/lib/commands/swizzle.js +0 -245
  179. package/lib/constants.d.ts +0 -18
  180. package/lib/constants.js +0 -23
  181. package/lib/server/loadSetup.js +0 -25
  182. package/lib/server/versions/__tests/index.test.js +0 -25
  183. package/lib/webpack/react-dev-utils-webpack5/README.md +0 -11
  184. package/lib/webpack/react-dev-utils-webpack5/evalSourceMapMiddleware.js +0 -57
  185. package/lib/webpack/react-dev-utils-webpack5/formatWebpackMessages.js +0 -138
  186. package/lib/webpack/react-dev-utils-webpack5/webpackHotDevClient.js +0 -285
  187. package/lib/webpack/sharedModuleAliases.js +0 -18
  188. package/tsconfig.client.json +0 -13
  189. package/tsconfig.json +0 -13
@@ -7,14 +7,13 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  const tslib_1 = require("tslib");
10
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
10
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
11
11
  const copy_webpack_plugin_1 = tslib_1.__importDefault(require("copy-webpack-plugin"));
12
12
  const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
13
13
  const path_1 = tslib_1.__importDefault(require("path"));
14
14
  const react_loadable_ssr_addon_v5_slorber_1 = tslib_1.__importDefault(require("react-loadable-ssr-addon-v5-slorber"));
15
15
  const webpack_bundle_analyzer_1 = require("webpack-bundle-analyzer");
16
16
  const webpack_merge_1 = tslib_1.__importDefault(require("webpack-merge"));
17
- const constants_1 = require("../constants");
18
17
  const server_1 = require("../server");
19
18
  const brokenLinks_1 = require("../server/brokenLinks");
20
19
  const client_1 = tslib_1.__importDefault(require("../webpack/client"));
@@ -24,11 +23,16 @@ const CleanWebpackPlugin_1 = tslib_1.__importDefault(require("../webpack/plugins
24
23
  const i18n_1 = require("../server/i18n");
25
24
  const utils_2 = require("@docusaurus/utils");
26
25
  async function build(siteDir, cliOptions = {},
27
- // TODO what's the purpose of this arg ?
26
+ // When running build, we force terminate the process to prevent async
27
+ // operations from never returning. However, if run as part of docusaurus
28
+ // deploy, we have to let deploy finish.
29
+ // See https://github.com/facebook/docusaurus/pull/2496
28
30
  forceTerminate = true) {
31
+ ['SIGINT', 'SIGTERM'].forEach((sig) => {
32
+ process.on(sig, () => process.exit());
33
+ });
29
34
  async function tryToBuildLocale({ locale, isLastLocale, }) {
30
35
  try {
31
- // console.log(chalk.green(`Site successfully built in locale=${locale}`));
32
36
  return await buildLocale({
33
37
  siteDir,
34
38
  locale,
@@ -37,60 +41,58 @@ forceTerminate = true) {
37
41
  isLastLocale,
38
42
  });
39
43
  }
40
- catch (e) {
41
- console.error(`Unable to build website for locale "${locale}".`);
42
- throw e;
44
+ catch (err) {
45
+ logger_1.default.error `Unable to build website for locale name=${locale}.`;
46
+ throw err;
43
47
  }
44
48
  }
45
- const context = await server_1.loadContext(siteDir, {
49
+ const context = await (0, server_1.loadContext)(siteDir, {
46
50
  customOutDir: cliOptions.outDir,
47
51
  customConfigFilePath: cliOptions.config,
48
52
  locale: cliOptions.locale,
49
53
  localizePath: cliOptions.locale ? false : undefined,
50
54
  });
51
- const i18n = await i18n_1.loadI18n(context.siteConfig, {
55
+ const i18n = await (0, i18n_1.loadI18n)(context.siteConfig, {
52
56
  locale: cliOptions.locale,
53
57
  });
54
58
  if (cliOptions.locale) {
55
59
  return tryToBuildLocale({ locale: cliOptions.locale, isLastLocale: true });
56
60
  }
57
- else {
58
- if (i18n.locales.length > 1) {
59
- console.log(chalk_1.default.yellow(`\nWebsite will be built for all these locales:
60
- - ${i18n.locales.join('\n- ')}`));
61
- }
62
- // We need the default locale to always be the 1st in the list
63
- // If we build it last, it would "erase" the localized sites built in subfolders
64
- const orderedLocales = [
65
- i18n.defaultLocale,
66
- ...i18n.locales.filter((locale) => locale !== i18n.defaultLocale),
67
- ];
68
- const results = await utils_2.mapAsyncSequencial(orderedLocales, (locale) => {
69
- const isLastLocale = orderedLocales.indexOf(locale) === orderedLocales.length - 1;
70
- return tryToBuildLocale({ locale, isLastLocale });
71
- });
72
- return results[0];
61
+ if (i18n.locales.length > 1) {
62
+ logger_1.default.info `Website will be built for all these locales: ${i18n.locales}`;
73
63
  }
64
+ // We need the default locale to always be the 1st in the list. If we build it
65
+ // last, it would "erase" the localized sites built in sub-folders
66
+ const orderedLocales = [
67
+ i18n.defaultLocale,
68
+ ...i18n.locales.filter((locale) => locale !== i18n.defaultLocale),
69
+ ];
70
+ const results = await (0, utils_2.mapAsyncSequential)(orderedLocales, (locale) => {
71
+ const isLastLocale = orderedLocales.indexOf(locale) === orderedLocales.length - 1;
72
+ return tryToBuildLocale({ locale, isLastLocale });
73
+ });
74
+ return results[0];
74
75
  }
75
76
  exports.default = build;
76
77
  async function buildLocale({ siteDir, locale, cliOptions, forceTerminate, isLastLocale, }) {
77
78
  process.env.BABEL_ENV = 'production';
78
79
  process.env.NODE_ENV = 'production';
79
- console.log(chalk_1.default.blue(`\n[${locale}] Creating an optimized production build...`));
80
- const props = await server_1.load(siteDir, {
80
+ logger_1.default.info `name=${`[${locale}]`} Creating an optimized production build...`;
81
+ const props = await (0, server_1.load)(siteDir, {
81
82
  customOutDir: cliOptions.outDir,
82
83
  customConfigFilePath: cliOptions.config,
83
84
  locale,
84
85
  localizePath: cliOptions.locale ? false : undefined,
85
86
  });
86
87
  // Apply user webpack config.
87
- const { outDir, generatedFilesDir, plugins, siteConfig: { baseUrl, onBrokenLinks }, routes, } = props;
88
+ const { outDir, generatedFilesDir, plugins, siteConfig: { baseUrl, onBrokenLinks, staticDirectories }, routes, } = props;
88
89
  const clientManifestPath = path_1.default.join(generatedFilesDir, 'client-manifest.json');
89
- let clientConfig = webpack_merge_1.default(client_1.default(props, cliOptions.minify), {
90
+ let clientConfig = (0, webpack_merge_1.default)(await (0, client_1.default)(props, cliOptions.minify), {
90
91
  plugins: [
91
92
  // Remove/clean build folders before building bundles.
92
93
  new CleanWebpackPlugin_1.default({ verbose: false }),
93
- // Visualize size of webpack output files with an interactive zoomable treemap.
94
+ // Visualize size of webpack output files with an interactive zoomable
95
+ // tree map.
94
96
  cliOptions.bundleAnalyzer && new webpack_bundle_analyzer_1.BundleAnalyzerPlugin(),
95
97
  // Generate client manifests file that will be used for server bundle.
96
98
  new react_loadable_ssr_addon_v5_slorber_1.default({
@@ -99,39 +101,35 @@ async function buildLocale({ siteDir, locale, cliOptions, forceTerminate, isLast
99
101
  ].filter(Boolean),
100
102
  });
101
103
  const allCollectedLinks = {};
102
- let serverConfig = server_2.default({
104
+ let serverConfig = await (0, server_2.default)({
103
105
  props,
104
106
  onLinksCollected: (staticPagePath, links) => {
105
107
  allCollectedLinks[staticPagePath] = links;
106
108
  },
107
109
  });
108
- const staticDir = path_1.default.resolve(siteDir, constants_1.STATIC_DIR_NAME);
109
- if (await fs_extra_1.default.pathExists(staticDir)) {
110
- serverConfig = webpack_merge_1.default(serverConfig, {
110
+ if (staticDirectories.length > 0) {
111
+ await Promise.all(staticDirectories.map((dir) => fs_extra_1.default.ensureDir(dir)));
112
+ serverConfig = (0, webpack_merge_1.default)(serverConfig, {
111
113
  plugins: [
112
114
  new copy_webpack_plugin_1.default({
113
- patterns: [
114
- {
115
- from: staticDir,
116
- to: outDir,
117
- },
118
- ],
115
+ patterns: staticDirectories
116
+ .map((dir) => path_1.default.resolve(siteDir, dir))
117
+ .map((dir) => ({ from: dir, to: outDir })),
119
118
  }),
120
119
  ],
121
120
  });
122
121
  }
123
122
  // Plugin Lifecycle - configureWebpack and configurePostCss.
124
123
  plugins.forEach((plugin) => {
125
- var _a, _b;
126
124
  const { configureWebpack, configurePostCss } = plugin;
127
125
  if (configurePostCss) {
128
- clientConfig = utils_1.applyConfigurePostCss(configurePostCss, clientConfig);
126
+ clientConfig = (0, utils_1.applyConfigurePostCss)(configurePostCss, clientConfig);
129
127
  }
130
128
  if (configureWebpack) {
131
- clientConfig = utils_1.applyConfigureWebpack(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`. // TODO remove this implicit api: inject in callback instead
132
- clientConfig, false, (_a = props.siteConfig.webpack) === null || _a === void 0 ? void 0 : _a.jsLoader, plugin.content);
133
- serverConfig = utils_1.applyConfigureWebpack(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`. // TODO remove this implicit api: inject in callback instead
134
- serverConfig, true, (_b = props.siteConfig.webpack) === null || _b === void 0 ? void 0 : _b.jsLoader, plugin.content);
129
+ clientConfig = (0, utils_1.applyConfigureWebpack)(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`.
130
+ clientConfig, false, props.siteConfig.webpack?.jsLoader, plugin.content);
131
+ serverConfig = (0, utils_1.applyConfigureWebpack)(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`.
132
+ serverConfig, true, props.siteConfig.webpack?.jsLoader, plugin.content);
135
133
  }
136
134
  });
137
135
  // Make sure generated client-manifest is cleaned first so we don't reuse
@@ -140,11 +138,9 @@ async function buildLocale({ siteDir, locale, cliOptions, forceTerminate, isLast
140
138
  await fs_extra_1.default.unlink(clientManifestPath);
141
139
  }
142
140
  // Run webpack to build JS bundle (client) and static html files (server).
143
- await utils_1.compile([clientConfig, serverConfig]);
141
+ await (0, utils_1.compile)([clientConfig, serverConfig]);
144
142
  // Remove server.bundle.js because it is not needed.
145
- if (serverConfig.output &&
146
- serverConfig.output.filename &&
147
- typeof serverConfig.output.filename === 'string') {
143
+ if (typeof serverConfig.output?.filename === 'string') {
148
144
  const serverBundle = path_1.default.join(outDir, serverConfig.output.filename);
149
145
  if (await fs_extra_1.default.pathExists(serverBundle)) {
150
146
  await fs_extra_1.default.unlink(serverBundle);
@@ -155,18 +151,18 @@ async function buildLocale({ siteDir, locale, cliOptions, forceTerminate, isLast
155
151
  if (!plugin.postBuild) {
156
152
  return;
157
153
  }
158
- await plugin.postBuild(props);
154
+ await plugin.postBuild({ ...props, content: plugin.content });
159
155
  }));
160
- await brokenLinks_1.handleBrokenLinks({
156
+ await (0, brokenLinks_1.handleBrokenLinks)({
161
157
  allCollectedLinks,
162
158
  routes,
163
159
  onBrokenLinks,
164
160
  outDir,
165
161
  baseUrl,
166
162
  });
167
- console.log(`${chalk_1.default.green(`Success!`)} Generated static files in "${chalk_1.default.cyan(path_1.default.relative(process.cwd(), outDir))}".`);
163
+ logger_1.default.success `Generated static files in path=${path_1.default.relative(process.cwd(), outDir)}.`;
168
164
  if (isLastLocale) {
169
- console.log(`\nUse ${chalk_1.default.greenBright('`npm run serve`')} command to test your build locally.\n`);
165
+ logger_1.default.info `Use code=${'npm run serve'} command to test your build locally.`;
170
166
  }
171
167
  if (forceTerminate && isLastLocale && !cliOptions.bundleAnalyzer) {
172
168
  process.exit(0);
@@ -1 +1,7 @@
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
  export default function clear(siteDir: string): Promise<unknown>;
@@ -1,32 +1,43 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
2
  /**
5
3
  * Copyright (c) Facebook, Inc. and its affiliates.
6
4
  *
7
5
  * This source code is licensed under the MIT license found in the
8
6
  * LICENSE file in the root directory of this source tree.
9
7
  */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ const tslib_1 = require("tslib");
10
10
  const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
11
11
  const path_1 = tslib_1.__importDefault(require("path"));
12
- const chalk = require("chalk");
13
- const constants_1 = require("../constants");
14
- function removePath(fsPath) {
15
- return fs_extra_1.default
16
- .remove(path_1.default.join(fsPath))
17
- .then(() => {
18
- console.log(chalk.green(`Successfully removed "${fsPath}" directory.`));
19
- })
20
- .catch((err) => {
21
- console.error(`Could not remove ${fsPath} directory.`);
22
- console.error(err);
23
- });
12
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
13
+ const utils_1 = require("@docusaurus/utils");
14
+ async function removePath(entry) {
15
+ if (!(await fs_extra_1.default.pathExists(entry.path))) {
16
+ return;
17
+ }
18
+ try {
19
+ await fs_extra_1.default.remove(entry.path);
20
+ logger_1.default.success `Removed the ${entry.description} at path=${entry.path}.`;
21
+ }
22
+ catch (err) {
23
+ logger_1.default.error `Could not remove the ${entry.description} at path=${entry.path}.`;
24
+ logger_1.default.error(err);
25
+ }
24
26
  }
25
27
  async function clear(siteDir) {
26
- return Promise.all([
27
- removePath(path_1.default.join(siteDir, constants_1.GENERATED_FILES_DIR_NAME)),
28
- removePath(path_1.default.join(siteDir, constants_1.DEFAULT_BUILD_DIR_NAME)),
29
- removePath(path_1.default.join(siteDir, 'node_modules', '.cache')),
30
- ]);
28
+ const generatedFolder = {
29
+ path: path_1.default.join(siteDir, utils_1.GENERATED_FILES_DIR_NAME),
30
+ description: 'generated folder',
31
+ };
32
+ const buildFolder = {
33
+ path: path_1.default.join(siteDir, utils_1.DEFAULT_BUILD_DIR_NAME),
34
+ description: 'build output folder',
35
+ };
36
+ // In Yarn PnP, cache is stored in `.yarn/.cache` because n_m doesn't exist
37
+ const cacheFolders = ['node_modules', '.yarn'].map((p) => ({
38
+ path: path_1.default.join(siteDir, p, '.cache'),
39
+ description: 'Webpack persistent cache folder',
40
+ }));
41
+ return Promise.all([generatedFolder, buildFolder, ...cacheFolders].map(removePath));
31
42
  }
32
43
  exports.default = clear;
@@ -1,3 +1,9 @@
1
- import { HostPortCLIOptions } from '@docusaurus/types';
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import type { HostPortCLIOptions } from '@docusaurus/types';
2
8
  export declare function getCLIOptionHost(hostOption: HostPortCLIOptions['host']): string;
3
9
  export declare function getCLIOptionPort(portOption: HostPortCLIOptions['port'], host: string): Promise<number | null>;
@@ -1,21 +1,21 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getCLIOptionPort = exports.getCLIOptionHost = void 0;
4
- const tslib_1 = require("tslib");
5
2
  /**
6
3
  * Copyright (c) Facebook, Inc. and its affiliates.
7
4
  *
8
5
  * This source code is licensed under the MIT license found in the
9
6
  * LICENSE file in the root directory of this source tree.
10
7
  */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.getCLIOptionPort = exports.getCLIOptionHost = void 0;
10
+ const tslib_1 = require("tslib");
11
11
  const choosePort_1 = tslib_1.__importDefault(require("../choosePort"));
12
- const constants_1 = require("../constants");
12
+ const utils_1 = require("@docusaurus/utils");
13
13
  function getCLIOptionHost(hostOption) {
14
14
  return hostOption || 'localhost';
15
15
  }
16
16
  exports.getCLIOptionHost = getCLIOptionHost;
17
17
  async function getCLIOptionPort(portOption, host) {
18
- const basePort = portOption ? parseInt(portOption, 10) : constants_1.DEFAULT_PORT;
19
- return choosePort_1.default(host, basePort);
18
+ const basePort = portOption ? parseInt(portOption, 10) : utils_1.DEFAULT_PORT;
19
+ return (0, choosePort_1.default)(host, basePort);
20
20
  }
21
21
  exports.getCLIOptionPort = getCLIOptionPort;
@@ -4,5 +4,8 @@
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 { BuildCLIOptions } from '@docusaurus/types';
7
+ import type { BuildCLIOptions } from '@docusaurus/types';
8
+ export declare function buildSshUrl(githubHost: string, organizationName: string, projectName: string, githubPort?: string): string;
9
+ export declare function buildHttpsUrl(gitCredentials: string, githubHost: string, organizationName: string, projectName: string, githubPort?: string): string;
10
+ export declare function hasSSHProtocol(sourceRepoUrl: string): boolean;
8
11
  export default function deploy(siteDir: string, cliOptions?: Partial<BuildCLIOptions>): Promise<void>;
@@ -6,15 +6,15 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.hasSSHProtocol = exports.buildHttpsUrl = exports.buildSshUrl = void 0;
9
10
  const tslib_1 = require("tslib");
10
11
  const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
11
12
  const shelljs_1 = tslib_1.__importDefault(require("shelljs"));
12
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
13
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
13
14
  const server_1 = require("../server");
14
15
  const build_1 = tslib_1.__importDefault(require("./build"));
15
16
  const path_1 = tslib_1.__importDefault(require("path"));
16
17
  const os_1 = tslib_1.__importDefault(require("os"));
17
- const buildRemoteBranchUrl_1 = require("./buildRemoteBranchUrl");
18
18
  // GIT_PASS env variable should not appear in logs
19
19
  function obfuscateGitPass(str) {
20
20
  const gitPass = process.env.GIT_PASS;
@@ -25,80 +25,126 @@ function obfuscateGitPass(str) {
25
25
  function shellExecLog(cmd) {
26
26
  try {
27
27
  const result = shelljs_1.default.exec(cmd);
28
- console.log(`${chalk_1.default.cyan('CMD:')} ${obfuscateGitPass(cmd)} ${chalk_1.default.cyan(`(code: ${result.code})`)}`);
28
+ logger_1.default.info `code=${obfuscateGitPass(cmd)} subdue=${`code: ${result.code}`}`;
29
29
  return result;
30
30
  }
31
- catch (e) {
32
- console.log(`${chalk_1.default.red('CMD:')} ${obfuscateGitPass(cmd)}`);
33
- throw e;
31
+ catch (err) {
32
+ logger_1.default.error `code=${obfuscateGitPass(cmd)}`;
33
+ throw err;
34
34
  }
35
35
  }
36
+ function buildSshUrl(githubHost, organizationName, projectName, githubPort) {
37
+ if (githubPort) {
38
+ return `ssh://git@${githubHost}:${githubPort}/${organizationName}/${projectName}.git`;
39
+ }
40
+ return `git@${githubHost}:${organizationName}/${projectName}.git`;
41
+ }
42
+ exports.buildSshUrl = buildSshUrl;
43
+ function buildHttpsUrl(gitCredentials, githubHost, organizationName, projectName, githubPort) {
44
+ if (githubPort) {
45
+ return `https://${gitCredentials}@${githubHost}:${githubPort}/${organizationName}/${projectName}.git`;
46
+ }
47
+ return `https://${gitCredentials}@${githubHost}/${organizationName}/${projectName}.git`;
48
+ }
49
+ exports.buildHttpsUrl = buildHttpsUrl;
50
+ function hasSSHProtocol(sourceRepoUrl) {
51
+ try {
52
+ if (new URL(sourceRepoUrl).protocol === 'ssh:') {
53
+ return true;
54
+ }
55
+ return false;
56
+ }
57
+ catch {
58
+ // Fails when there isn't a protocol
59
+ return /^(?:[\w-]+@)?[\w.-]+:[\w./_-]+/.test(sourceRepoUrl); // git@github.com:facebook/docusaurus.git
60
+ }
61
+ }
62
+ exports.hasSSHProtocol = hasSSHProtocol;
36
63
  async function deploy(siteDir, cliOptions = {}) {
37
- const { outDir, siteConfig, siteConfigPath } = await server_1.loadContext(siteDir, {
64
+ const { outDir, siteConfig, siteConfigPath } = await (0, server_1.loadContext)(siteDir, {
38
65
  customConfigFilePath: cliOptions.config,
39
66
  customOutDir: cliOptions.outDir,
40
67
  });
41
68
  if (typeof siteConfig.trailingSlash === 'undefined') {
42
- console.warn(chalk_1.default.yellow(`
43
- Docusaurus recommendation:
44
- When deploying to GitHub Pages, it is better to use an explicit "trailingSlash" site config.
69
+ logger_1.default.warn(`When deploying to GitHub Pages, it is better to use an explicit "trailingSlash" site config.
45
70
  Otherwise, GitHub Pages will add an extra trailing slash to your site urls only on direct-access (not when navigation) with a server redirect.
46
71
  This behavior can have SEO impacts and create relative link issues.
47
- `));
72
+ `);
48
73
  }
49
- console.log('Deploy command invoked...');
74
+ logger_1.default.info('Deploy command invoked...');
50
75
  if (!shelljs_1.default.which('git')) {
51
76
  throw new Error('Git not installed or on the PATH!');
52
77
  }
78
+ // Source repo is the repo from where the command is invoked
79
+ const sourceRepoUrl = shelljs_1.default
80
+ .exec('git config --get remote.origin.url', { silent: true })
81
+ .stdout.trim();
82
+ // The source branch; defaults to the currently checked out branch
83
+ const sourceBranch = process.env.CURRENT_BRANCH ||
84
+ shelljs_1.default.exec('git rev-parse --abbrev-ref HEAD', { silent: true }).stdout.trim();
53
85
  const gitUser = process.env.GIT_USER;
54
- if (!gitUser) {
55
- throw new Error('Please set the GIT_USER environment variable!');
86
+ let useSSH = process.env.USE_SSH !== undefined &&
87
+ process.env.USE_SSH.toLowerCase() === 'true';
88
+ if (!gitUser && !useSSH) {
89
+ // If USE_SSH is unspecified: try inferring from repo URL
90
+ if (process.env.USE_SSH === undefined && hasSSHProtocol(sourceRepoUrl)) {
91
+ useSSH = true;
92
+ }
93
+ else {
94
+ throw new Error('Please set the GIT_USER environment variable, or explicitly specify USE_SSH instead!');
95
+ }
56
96
  }
57
- // The branch that contains the latest docs changes that will be deployed.
58
- const currentBranch = process.env.CURRENT_BRANCH ||
59
- shelljs_1.default.exec('git rev-parse --abbrev-ref HEAD').stdout.trim();
60
97
  const organizationName = process.env.ORGANIZATION_NAME ||
61
98
  process.env.CIRCLE_PROJECT_USERNAME ||
62
99
  siteConfig.organizationName;
63
100
  if (!organizationName) {
64
101
  throw new Error(`Missing project organization name. Did you forget to define "organizationName" in ${siteConfigPath}? You may also export it via the ORGANIZATION_NAME environment variable.`);
65
102
  }
66
- console.log(`${chalk_1.default.cyan('organizationName:')} ${organizationName}`);
103
+ logger_1.default.info `organizationName: name=${organizationName}`;
67
104
  const projectName = process.env.PROJECT_NAME ||
68
105
  process.env.CIRCLE_PROJECT_REPONAME ||
69
106
  siteConfig.projectName;
70
107
  if (!projectName) {
71
108
  throw new Error(`Missing project name. Did you forget to define "projectName" in ${siteConfigPath}? You may also export it via the PROJECT_NAME environment variable.`);
72
109
  }
73
- console.log(`${chalk_1.default.cyan('projectName:')} ${projectName}`);
110
+ logger_1.default.info `projectName: name=${projectName}`;
74
111
  // We never deploy on pull request.
75
112
  const isPullRequest = process.env.CI_PULL_REQUEST || process.env.CIRCLE_PULL_REQUEST;
76
113
  if (isPullRequest) {
77
114
  shelljs_1.default.echo('Skipping deploy on a pull request.');
78
115
  shelljs_1.default.exit(0);
79
116
  }
80
- // github.io indicates organization repos that deploy via master. All others use gh-pages.
81
- const deploymentBranch = process.env.DEPLOYMENT_BRANCH ||
82
- (projectName.indexOf('.github.io') !== -1 ? 'master' : 'gh-pages');
83
- console.log(`${chalk_1.default.cyan('deploymentBranch:')} ${deploymentBranch}`);
117
+ // github.io indicates organization repos that deploy via default branch.
118
+ // All others use gh-pages. Organization deploys looks like:
119
+ // - Git repo: https://github.com/<organization>/<organization>.github.io
120
+ // - Site url: https://<organization>.github.io
121
+ const isGitHubPagesOrganizationDeploy = projectName.includes('.github.io');
122
+ if (isGitHubPagesOrganizationDeploy &&
123
+ !process.env.DEPLOYMENT_BRANCH &&
124
+ !siteConfig.deploymentBranch) {
125
+ throw new Error(`For GitHub pages organization deployments, 'docusaurus deploy' does not assume anymore that 'master' is your default Git branch.
126
+ Please provide the branch name to deploy to as an environment variable, for example DEPLOYMENT_BRANCH=main or DEPLOYMENT_BRANCH=master .
127
+ You can also set the deploymentBranch property in docusaurus.config.js .`);
128
+ }
129
+ const deploymentBranch = process.env.DEPLOYMENT_BRANCH || siteConfig.deploymentBranch || 'gh-pages';
130
+ logger_1.default.info `deploymentBranch: name=${deploymentBranch}`;
84
131
  const githubHost = process.env.GITHUB_HOST || siteConfig.githubHost || 'github.com';
85
132
  const githubPort = process.env.GITHUB_PORT || siteConfig.githubPort;
86
- const gitPass = process.env.GIT_PASS;
87
- let gitCredentials = `${gitUser}`;
88
- if (gitPass) {
89
- gitCredentials = `${gitCredentials}:${gitPass}`;
133
+ let deploymentRepoURL;
134
+ if (useSSH) {
135
+ deploymentRepoURL = buildSshUrl(githubHost, organizationName, projectName, githubPort);
90
136
  }
91
- const useSSH = process.env.USE_SSH;
92
- const remoteBranch = buildRemoteBranchUrl_1.buildUrl(githubHost, githubPort, gitCredentials, organizationName, projectName, useSSH !== undefined && useSSH.toLowerCase() === 'true');
93
- console.log(`${chalk_1.default.cyan('Remote branch:')} ${obfuscateGitPass(remoteBranch)}`);
137
+ else {
138
+ const gitPass = process.env.GIT_PASS;
139
+ const gitCredentials = gitPass ? `${gitUser}:${gitPass}` : gitUser;
140
+ deploymentRepoURL = buildHttpsUrl(gitCredentials, githubHost, organizationName, projectName, githubPort);
141
+ }
142
+ logger_1.default.info `Remote repo URL: name=${obfuscateGitPass(deploymentRepoURL)}`;
94
143
  // Check if this is a cross-repo publish.
95
- const currentRepoUrl = shelljs_1.default
96
- .exec('git config --get remote.origin.url')
97
- .stdout.trim();
98
- const crossRepoPublish = !currentRepoUrl.endsWith(`${organizationName}/${projectName}.git`);
144
+ const crossRepoPublish = !sourceRepoUrl.endsWith(`${organizationName}/${projectName}.git`);
99
145
  // We don't allow deploying to the same branch unless it's a cross publish.
100
- if (currentBranch === deploymentBranch && !crossRepoPublish) {
101
- throw new Error(`You cannot deploy from this branch (${currentBranch}).` +
146
+ if (sourceBranch === deploymentBranch && !crossRepoPublish) {
147
+ throw new Error(`You cannot deploy from this branch (${sourceBranch}).` +
102
148
  '\nYou will need to checkout to a different branch!');
103
149
  }
104
150
  // Save the commit hash that triggers publish-gh-pages before checking
@@ -107,42 +153,32 @@ This behavior can have SEO impacts and create relative link issues.
107
153
  const runDeploy = async (outputDirectory) => {
108
154
  const fromPath = outputDirectory;
109
155
  const toPath = await fs_extra_1.default.mkdtemp(path_1.default.join(os_1.default.tmpdir(), `${projectName}-${deploymentBranch}`));
110
- if (shellExecLog(`git clone ${remoteBranch} ${toPath}`).code !== 0) {
111
- throw new Error(`Running "git clone" command in "${toPath}" failed.`);
112
- }
113
156
  shelljs_1.default.cd(toPath);
114
- // If the default branch is the one we're deploying to, then we'll fail
115
- // to create it. This is the case of a cross-repo publish, where we clone
116
- // a github.io repo with a default master branch.
117
- const defaultBranch = shelljs_1.default
118
- .exec('git rev-parse --abbrev-ref HEAD')
119
- .stdout.trim();
120
- if (defaultBranch !== deploymentBranch) {
121
- if (shellExecLog(`git checkout origin/${deploymentBranch}`).code !== 0) {
122
- if (shellExecLog(`git checkout --orphan ${deploymentBranch}`).code !== 0) {
123
- throw new Error(`Running "git checkout ${deploymentBranch}" command failed.`);
124
- }
125
- }
126
- else if (shellExecLog(`git checkout -b ${deploymentBranch}`).code +
127
- shellExecLog(`git branch --set-upstream-to=origin/${deploymentBranch}`).code !==
128
- 0) {
129
- throw new Error(`Running "git checkout ${deploymentBranch}" command failed.`);
130
- }
157
+ // Check out deployment branch when cloning repository, and then remove all
158
+ // the files in the directory. If the 'clone' command fails, assume that
159
+ // the deployment branch doesn't exist, and initialize git in an empty
160
+ // directory, check out a clean deployment branch and add remote.
161
+ if (shellExecLog(`git clone --depth 1 --branch ${deploymentBranch} ${deploymentRepoURL} "${toPath}"`).code === 0) {
162
+ shellExecLog('git rm -rf .');
163
+ }
164
+ else {
165
+ shellExecLog('git init');
166
+ shellExecLog(`git checkout -b ${deploymentBranch}`);
167
+ shellExecLog(`git remote add origin ${deploymentRepoURL}`);
131
168
  }
132
- shellExecLog('git rm -rf .');
133
169
  try {
134
170
  await fs_extra_1.default.copy(fromPath, toPath);
135
171
  }
136
- catch (error) {
137
- throw new Error(`Copying build assets from "${fromPath}" to "${toPath}" failed with error "${error}".`);
172
+ catch (err) {
173
+ logger_1.default.error `Copying build assets from path=${fromPath} to path=${toPath} failed.`;
174
+ throw err;
138
175
  }
139
- shelljs_1.default.cd(toPath);
140
176
  shellExecLog('git add --all');
141
177
  const commitMessage = process.env.CUSTOM_COMMIT_MESSAGE ||
142
178
  `Deploy website - based on ${currentCommit}`;
143
179
  const commitResults = shellExecLog(`git commit -m "${commitMessage}"`);
144
180
  if (shellExecLog(`git push --force origin ${deploymentBranch}`).code !== 0) {
145
- throw new Error('Running "git push" command failed.');
181
+ throw new Error('Running "git push" command failed. Does the GitHub user account you are using have push access to the repository?');
146
182
  }
147
183
  else if (commitResults.code === 0) {
148
184
  // The commit might return a non-zero value when site is up to date.
@@ -161,13 +197,13 @@ This behavior can have SEO impacts and create relative link issues.
161
197
  }
162
198
  };
163
199
  if (!cliOptions.skipBuild) {
164
- // Build static html files, then push to deploymentBranch branch of specified repo.
200
+ // Build site, then push to deploymentBranch branch of specified repo.
165
201
  try {
166
- await runDeploy(await build_1.default(siteDir, cliOptions, false));
202
+ await runDeploy(await (0, build_1.default)(siteDir, cliOptions, false));
167
203
  }
168
- catch (buildError) {
169
- console.error(buildError);
170
- process.exit(1);
204
+ catch (err) {
205
+ logger_1.default.error('Deployment of the build output failed.');
206
+ throw err;
171
207
  }
172
208
  }
173
209
  else {
@@ -4,5 +4,5 @@
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 { Command } from 'commander';
8
- export default function externalCommand(cli: Command, siteDir: string): Promise<void>;
7
+ import type { CommanderStatic } from 'commander';
8
+ export default function externalCommand(cli: CommanderStatic, siteDir: string): Promise<void>;
@@ -10,9 +10,9 @@ const tslib_1 = require("tslib");
10
10
  const server_1 = require("../server");
11
11
  const init_1 = tslib_1.__importDefault(require("../server/plugins/init"));
12
12
  async function externalCommand(cli, siteDir) {
13
- const context = await server_1.loadContext(siteDir);
14
- const pluginConfigs = server_1.loadPluginConfigs(context);
15
- const plugins = init_1.default({ pluginConfigs, context });
13
+ const context = await (0, server_1.loadContext)(siteDir);
14
+ const pluginConfigs = await (0, server_1.loadPluginConfigs)(context);
15
+ const plugins = await (0, init_1.default)({ pluginConfigs, context });
16
16
  // Plugin Lifecycle - extendCli.
17
17
  plugins.forEach((plugin) => {
18
18
  const { extendCli } = plugin;
@@ -4,5 +4,5 @@
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 { ServeCLIOptions } from '@docusaurus/types';
7
+ import type { ServeCLIOptions } from '@docusaurus/types';
8
8
  export default function serve(siteDir: string, cliOptions: ServeCLIOptions): Promise<void>;