@rspress/core 2.0.0-beta.21 → 2.0.0-beta.23

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.
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ /*! For license information please see index.js.LICENSE.txt */
1
2
  import __rslib_shim_module__ from 'module';
2
3
  const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(import.meta.url);
3
4
  import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__ from "@rspress/shared";
@@ -14,24 +15,24 @@ import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
14
15
  import * as __WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__ from "node:util";
15
16
  import * as __WEBPACK_EXTERNAL_MODULE_path__ from "path";
16
17
  import * as __WEBPACK_EXTERNAL_MODULE_stream__ from "stream";
18
+ import { matchPath } from "@rspress/runtime/server";
19
+ import { logger } from "@rspress/shared/logger";
20
+ import { extractTextAndId, getIconUrlPath, getNodeAttribute, loadFrontMatter, mergeDocConfig } from "@rspress/shared/node-utils";
17
21
  import node_fs_promises, { mkdir, readFile, readdir, rm, stat as promises_stat, writeFile } from "node:fs/promises";
18
22
  import { PLUGIN_REACT_NAME, pluginReact } from "@rsbuild/plugin-react";
19
23
  import { DEFAULT_PAGE_EXTENSIONS } from "@rspress/shared/constants";
20
- import { logger } from "@rspress/shared/logger";
21
24
  import picocolors from "picocolors";
22
25
  import { glob } from "tinyglobby";
23
- import { extractTextAndId, getIconUrlPath, getNodeAttribute, loadFrontMatter, mergeDocConfig } from "@rspress/shared/node-utils";
24
26
  import { RspackVirtualModulePlugin } from "rspack-plugin-virtual-module";
25
- import { groupBy } from "lodash-es";
27
+ import { chunk, groupBy } from "lodash-es";
26
28
  import { compile } from "@rspress/mdx-rs";
27
29
  import { htmlToText } from "html-to-text";
28
30
  import { createProcessor } from "@mdx-js/mdx";
29
31
  import enhanced_resolve from "enhanced-resolve";
30
32
  import { createHash } from "node:crypto";
31
33
  import { createHead, transformHtmlTemplate } from "@unhead/react/server";
32
- import { mergeRsbuildConfig as core_mergeRsbuildConfig } from "@rsbuild/core";
33
34
  import { visit } from "unist-util-visit";
34
- import { matchPath } from "@rspress/runtime/server";
35
+ import { mergeRsbuildConfig as core_mergeRsbuildConfig } from "@rsbuild/core";
35
36
  var __webpack_modules__ = {
36
37
  "@rspress/shared": function(module) {
37
38
  module.exports = __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__;
@@ -145,128 +146,39 @@ __webpack_require__.m = __webpack_modules__;
145
146
  }
146
147
  };
147
148
  })();
148
- class PluginDriver {
149
- #config;
150
- #configFilePath;
151
- #plugins;
152
- #isProd;
153
- constructor(config, configFilePath, isProd){
154
- this.#config = config;
155
- this.#configFilePath = configFilePath;
156
- this.#isProd = isProd;
157
- this.#plugins = [];
158
- }
159
- getConfigFilePath() {
160
- return this.#configFilePath;
161
- }
162
- async init() {
163
- this.clearPlugins();
164
- const config = this.#config;
165
- const themeConfig = config?.themeConfig || {};
166
- const enableLastUpdated = themeConfig?.lastUpdated || themeConfig?.locales?.some((locale)=>locale.lastUpdated);
167
- const mediumZoomConfig = config?.mediumZoom ?? true;
168
- if (enableLastUpdated) {
169
- const { pluginLastUpdated } = await Promise.all([
170
- __webpack_require__.e("94"),
171
- __webpack_require__.e("208")
172
- ]).then(__webpack_require__.bind(__webpack_require__, "./src/node/last-updated/index.ts"));
173
- this.addPlugin(pluginLastUpdated());
174
- }
175
- if (mediumZoomConfig) {
176
- const { pluginMediumZoom } = await __webpack_require__.e("309").then(__webpack_require__.bind(__webpack_require__, "./src/node/medium-zoom/index.ts"));
177
- this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
178
- }
179
- (config.plugins || []).forEach((plugin)=>{
180
- this.addPlugin(plugin);
181
- });
182
- }
183
- addPlugin(plugin) {
184
- const existedIndex = this.#plugins.findIndex((item)=>item.name === plugin.name);
185
- if (-1 !== existedIndex) throw new Error(`The plugin "${plugin.name}" has been registered`);
186
- this.#plugins.push(plugin);
187
- }
188
- getPlugins() {
189
- return this.#plugins;
190
- }
191
- clearPlugins() {
192
- this.#plugins = [];
193
- }
194
- removePlugin(pluginName) {
195
- const index = this.#plugins.findIndex((item)=>item.name === pluginName);
196
- if (-1 !== index) this.#plugins.splice(index, 1);
197
- }
198
- async modifyConfig() {
199
- let config = this.#config;
200
- for(let i = 0; i < this.#plugins.length; i++){
201
- const plugin = this.#plugins[i];
202
- if ('function' == typeof plugin.config) config = await plugin.config(config || {}, {
203
- addPlugin: this.addPlugin.bind(this),
204
- removePlugin: (pluginName)=>{
205
- const index = this.#plugins.findIndex((item)=>item.name === pluginName);
206
- this.removePlugin(pluginName);
207
- if (index <= i && index > 0) i--;
208
- }
209
- }, this.#isProd);
210
- }
211
- this.#config = config;
212
- return this.#config;
213
- }
214
- async beforeBuild() {
215
- return this._runParallelAsyncHook('beforeBuild', this.#config || {}, this.#isProd);
216
- }
217
- async afterBuild() {
218
- return this._runParallelAsyncHook('afterBuild', this.#config || {}, this.#isProd);
219
- }
220
- async modifySearchIndexData(pages) {
221
- return this._runParallelAsyncHook('modifySearchIndexData', pages, this.#isProd);
222
- }
223
- async extendPageData(pageData) {
224
- return this._runParallelAsyncHook('extendPageData', pageData, this.#isProd);
225
- }
226
- async addPages() {
227
- const result = await this._runParallelAsyncHook('addPages', this.#config || {}, this.#isProd);
228
- return result.flat();
229
- }
230
- async routeGenerated(routes) {
231
- return this._runParallelAsyncHook('routeGenerated', routes, this.#isProd);
232
- }
233
- async routeServiceGenerated(routeService) {
234
- return this._runParallelAsyncHook('routeServiceGenerated', routeService, this.#isProd);
235
- }
236
- async addRuntimeModules() {
237
- const result = await this._runParallelAsyncHook('addRuntimeModules', this.#config || {}, this.#isProd);
238
- return result.reduce((prev, current)=>({
239
- ...prev,
240
- ...current
241
- }), {});
242
- }
243
- async addSSGRoutes() {
244
- const result = await this._runParallelAsyncHook('addSSGRoutes', this.#config || {}, this.#isProd);
245
- return result.flat();
246
- }
247
- globalUIComponents() {
248
- const result = this.#plugins.map((plugin)=>plugin.globalUIComponents || []);
249
- return result.flat();
250
- }
251
- globalStyles() {
252
- return this.#plugins.filter((plugin)=>'string' == typeof plugin.globalStyles).map((plugin)=>plugin.globalStyles);
253
- }
254
- _runParallelAsyncHook(hookName, ...args) {
255
- return Promise.all(this.#plugins.filter((plugin)=>'function' == typeof plugin[hookName]).map((plugin)=>plugin[hookName](...args)));
256
- }
257
- _runSerialAsyncHook(hookName, ...args) {
258
- return this.#plugins.reduce(async (prev, plugin)=>{
259
- if ('function' == typeof plugin[hookName]) {
260
- await prev;
261
- return plugin[hookName](...args);
262
- }
263
- return prev;
264
- }, Promise.resolve());
265
- }
149
+ var shared_ = __webpack_require__("@rspress/shared");
150
+ function defineConfig(config) {
151
+ return config;
266
152
  }
267
153
  var external_node_path_ = __webpack_require__("node:path");
268
154
  var external_node_url_ = __webpack_require__("node:url");
269
- var shared_ = __webpack_require__("@rspress/shared");
155
+ var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.23"}');
156
+ const RSPRESS_VERSION = package_namespaceObject.i8;
157
+ const isProduction = ()=>'production' === process.env.NODE_ENV;
158
+ const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
159
+ const inlineThemeScript = `{
160
+ const saved = localStorage.getItem('${shared_.APPEARANCE_KEY}')
161
+ const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
162
+ const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
163
+ document.documentElement.classList.toggle('dark', isDark)
164
+ document.documentElement.classList.toggle('rp-dark', isDark)
165
+ document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
166
+ }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
167
+ const dirname = external_node_path_["default"].dirname((0, external_node_url_.fileURLToPath)(new URL(import.meta.url)));
168
+ const PACKAGE_ROOT = external_node_path_["default"].join(dirname, '..');
169
+ const TEMPLATE_PATH = external_node_path_["default"].join(PACKAGE_ROOT, 'index.html');
170
+ const CSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
171
+ const SSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
172
+ const SSR_SERVER_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
173
+ const OUTPUT_DIR = 'doc_build';
174
+ const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
175
+ const HEAD_MARKER = '<!--<?- HEAD ?>-->';
176
+ const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
177
+ const DEFAULT_TITLE = 'Rspress';
178
+ const PUBLIC_DIR = 'public';
179
+ const constants_TEMP_DIR = external_node_path_["default"].join(process.cwd(), 'node_modules', shared_.RSPRESS_TEMP_DIR);
180
+ const NODE_SSG_BUNDLE_FOLDER = '__ssg__';
181
+ const NODE_SSG_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
270
182
  const PLUGIN_VIRTUAL_MODULE_NAME = 'rsbuild:virtual-module';
271
183
  const pluginVirtualModule = (pluginOptions = {})=>({
272
184
  name: PLUGIN_VIRTUAL_MODULE_NAME,
@@ -340,16 +252,16 @@ async function hintThemeBreakingChange(customThemeDir) {
340
252
  }
341
253
  }
342
254
  if (useDefaultExportFilePath) logger.warn(`[Rspress v2] Breaking Change: The "theme/index.tsx" is now using named export instead of default export, please update ${picocolors.greenBright(useDefaultExportFilePath)} (https://github.com/web-infra-dev/rspress/discussions/1891#discussioncomment-12422737).\n`, picocolors.redBright(`
343
- - import Theme from '@rspress/theme-default';
255
+ - import Theme from '@rspress/core/theme';
344
256
  - export default {
345
257
  - ...Theme,
346
258
  - Layout,
347
259
  - };
348
- - export * from 'rspress/theme';`) + picocolors.greenBright(`
349
- + import { Layout } from '@rspress/theme-default';
260
+ - export * from '@rspress/core/theme';`) + picocolors.greenBright(`
261
+ + import { Layout } from '@rspress/core/theme';
350
262
 
351
263
  + export { Layout };
352
- + export * from 'rspress/theme';
264
+ + export * from '@rspress/core/theme';
353
265
  `));
354
266
  }
355
267
  function hintBuilderPluginsBreakingChange(config) {
@@ -371,7 +283,7 @@ ${picocolors.greenBright(` builderConfig: {
371
283
  function hintSSGFailed() {
372
284
  logger.info(`[Rspress v2] \`ssg: true\` requires the source code to support SSR. If the code is not compatible to SSR, the build process will fail. You can try:
373
285
  1. Fix code to make it SSR-compatible.
374
- 2. Set \`ssg: false\`, but the SSG feature will be lost.`);
286
+ 2. Set \`ssg: false\` if the code in node_modules may be difficult to fix, but the SSG feature will be lost.`);
375
287
  }
376
288
  function hintSSGFalse() {
377
289
  logger.info('`ssg: false` detected, SSG will be disabled.');
@@ -406,34 +318,15 @@ function slash(p) {
406
318
  function normalizePath(id) {
407
319
  return external_node_path_["default"].posix.normalize(isWindows ? slash(id) : id);
408
320
  }
409
- var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.21"}');
410
- const RSPRESS_VERSION = package_namespaceObject.i8;
411
- const isProduction = ()=>'production' === process.env.NODE_ENV;
412
- const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
413
- const inlineThemeScript = `{
414
- const saved = localStorage.getItem('${shared_.APPEARANCE_KEY}')
415
- const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
416
- const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
417
- document.documentElement.classList.toggle('dark', isDark)
418
- document.documentElement.classList.toggle('rp-dark', isDark)
419
- document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
420
- }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
421
- const dirname = external_node_path_["default"].dirname((0, external_node_url_.fileURLToPath)(new URL(import.meta.url)));
422
- const PACKAGE_ROOT = external_node_path_["default"].join(dirname, '..');
423
- const TEMPLATE_PATH = external_node_path_["default"].join(PACKAGE_ROOT, 'index.html');
424
- const CSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
425
- const SSR_CLIENT_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
426
- const SSR_SERVER_ENTRY = external_node_path_["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
427
- const OUTPUT_DIR = 'doc_build';
428
- const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
429
- const HEAD_MARKER = '<!--<?- HEAD ?>-->';
430
- const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
431
- const DEFAULT_TITLE = 'Rspress';
432
- const PUBLIC_DIR = 'public';
433
- const constants_TEMP_DIR = external_node_path_["default"].join(process.cwd(), 'node_modules', shared_.RSPRESS_TEMP_DIR);
434
- const NODE_SSG_BUNDLE_FOLDER = '__ssg__';
435
- const NODE_SSG_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
436
321
  const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
322
+ const [versionPart, langPart, purePath] = splitRoutePathParts(relativePath, lang, version, langs, versions);
323
+ return [
324
+ versionPart === version ? '' : versionPart,
325
+ langPart === lang ? '' : langPart,
326
+ purePath
327
+ ];
328
+ };
329
+ const splitRoutePathParts = (relativePath, lang, version, langs, versions)=>{
437
330
  const hasTrailSlash = relativePath.endsWith('/');
438
331
  let versionPart = '';
439
332
  let langPart = '';
@@ -441,17 +334,11 @@ const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
441
334
  const parts = relativePath.split('/').filter(Boolean);
442
335
  if (version) {
443
336
  const versionToMatch = parts[0];
444
- if (versions.includes(versionToMatch)) {
445
- if (versionToMatch !== version) versionPart = versionToMatch;
446
- parts.shift();
447
- }
337
+ if (versions.includes(versionToMatch)) versionPart = parts.shift() ?? '';
448
338
  }
449
339
  if (lang) {
450
340
  const langToMatch = parts[0];
451
- if (langs.includes(langToMatch)) {
452
- if (langToMatch !== lang) langPart = langToMatch;
453
- parts.shift();
454
- }
341
+ if (langs.includes(langToMatch)) langPart = parts.shift() ?? '';
455
342
  }
456
343
  purePathPart = parts.join('/');
457
344
  return [
@@ -464,6 +351,7 @@ const normalizeRoutePath = (relativePath, lang, version, langs, versions, extens
464
351
  const extensionsWithoutDot = extensions.map((i)=>i.slice(1));
465
352
  const cleanExtensionPattern = new RegExp(`\\.(${extensionsWithoutDot.join('|')})$`, 'i');
466
353
  let routePath = relativePath.replace(cleanExtensionPattern, '').replace(/\.html$/, '');
354
+ if (routePath.endsWith('/')) routePath = `${routePath}index`;
467
355
  const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
468
356
  routePath = purePathPart.replace(/\/index$/, '/');
469
357
  if ('index' === routePath) routePath = '';
@@ -485,13 +373,14 @@ class RouteService {
485
373
  routeData = new Map();
486
374
  #scanDir;
487
375
  #defaultLang;
488
- #defaultVersion = '';
489
- #extensions = [];
490
- #langs = [];
491
- #versions = [];
492
- #include = [];
493
- #exclude = [];
494
- #tempDir = '';
376
+ #defaultVersion;
377
+ #extensions;
378
+ #langs;
379
+ #versions;
380
+ #include;
381
+ #exclude;
382
+ #excludeConvention;
383
+ #tempDir;
495
384
  #pluginDriver;
496
385
  static __instance__ = null;
497
386
  static getInstance() {
@@ -511,6 +400,9 @@ class RouteService {
511
400
  this.#extensions = routeOptions.extensions || DEFAULT_PAGE_EXTENSIONS;
512
401
  this.#include = routeOptions.include || [];
513
402
  this.#exclude = routeOptions.exclude || [];
403
+ this.#excludeConvention = routeOptions.excludeConvention || [
404
+ '**/_[^_]*'
405
+ ];
514
406
  this.#defaultLang = userConfig?.lang || '';
515
407
  this.#langs = (userConfig?.locales ?? userConfig?.themeConfig?.locales ?? []).map((item)=>item.lang);
516
408
  this.#tempDir = tempDir;
@@ -518,6 +410,9 @@ class RouteService {
518
410
  if (userConfig.multiVersion) {
519
411
  this.#defaultVersion = userConfig.multiVersion.default || '';
520
412
  this.#versions = userConfig.multiVersion.versions || [];
413
+ } else {
414
+ this.#defaultVersion = '';
415
+ this.#versions = [];
521
416
  }
522
417
  }
523
418
  get extensions() {
@@ -534,10 +429,12 @@ class RouteService {
534
429
  onlyFiles: true,
535
430
  ignore: [
536
431
  ...this.#exclude,
432
+ ...this.#excludeConvention,
537
433
  '**/node_modules/**',
538
434
  '**/.eslintrc.js',
539
435
  '**/.nx/**',
540
- `./${PUBLIC_DIR}/**`
436
+ `./${PUBLIC_DIR}/**`,
437
+ '**/*.d.ts'
541
438
  ]
542
439
  })).sort();
543
440
  files.forEach((filePath)=>{
@@ -597,12 +494,19 @@ ${routeMeta.map((route, index)=>{
597
494
  getRoutePathParts(relativePath) {
598
495
  return getRoutePathParts(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
599
496
  }
497
+ splitRoutePathParts(relativePath) {
498
+ return splitRoutePathParts(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
499
+ }
600
500
  normalizeRoutePath(relativePath) {
601
501
  return normalizeRoutePath(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions, this.#extensions);
602
502
  }
603
503
  absolutePathToRoutePath(absolutePath) {
604
504
  return absolutePathToRoutePath(absolutePath, this.#scanDir, this);
605
505
  }
506
+ isInDocsDir(absolutePath) {
507
+ const relativePath = external_node_path_["default"].relative(this.#scanDir, absolutePath);
508
+ return !relativePath.startsWith('..') && !external_node_path_["default"].isAbsolute(relativePath);
509
+ }
606
510
  absolutePathToRelativePath(absolutePath) {
607
511
  return absolutePathToRelativePath(absolutePath, this.#scanDir);
608
512
  }
@@ -839,13 +743,18 @@ async function metaFileItemToSidebarItem(metaItemRaw, workDir, docsDir, extensio
839
743
  }
840
744
  function metaCustomLinkItemToSidebarItem(metaItem, workDir, docsDir) {
841
745
  if ('items' in metaItem && Array.isArray(metaItem.items) && metaItem.items.length > 0) {
842
- const { label, link, context, items, tag } = metaItem;
746
+ const { label, link, context, items, tag, collapsed, collapsible, overviewHeaders } = metaItem;
843
747
  return {
844
748
  text: label ?? link,
845
749
  context,
846
750
  tag,
847
751
  link,
848
- items: items.map((subItem)=>metaCustomLinkItemToSidebarItem(subItem, workDir, docsDir))
752
+ items: items.map((subItem)=>metaCustomLinkItemToSidebarItem(Object.assign(subItem, {
753
+ type: 'custom-link'
754
+ }), workDir, docsDir)),
755
+ collapsed,
756
+ collapsible,
757
+ overviewHeaders
849
758
  };
850
759
  }
851
760
  if ('link' in metaItem && 'string' == typeof metaItem.link) {
@@ -892,7 +801,7 @@ async function scanNav(workDir, docsDir) {
892
801
  const rootNavJson = external_node_path_["default"].resolve(workDir, '_nav.json');
893
802
  try {
894
803
  navConfig = await utils_readJson(rootNavJson);
895
- } catch (e) {
804
+ } catch (_e) {
896
805
  logger.error('[auto-nav-sidebar]', `Generate nav meta error: ${rootNavJson} failed`);
897
806
  navConfig = [];
898
807
  }
@@ -1368,7 +1277,6 @@ async function siteDataVMPlugin(context) {
1368
1277
  locales: userConfig?.locales || userConfig.themeConfig?.locales || [],
1369
1278
  logo: userConfig?.logo || '',
1370
1279
  logoText: userConfig?.logoText || '',
1371
- ssg: Boolean(userConfig?.ssg ?? true),
1372
1280
  multiVersion: {
1373
1281
  default: userConfig?.multiVersion?.default || '',
1374
1282
  versions: userConfig?.multiVersion?.versions || []
@@ -1377,7 +1285,7 @@ async function siteDataVMPlugin(context) {
1377
1285
  mode: 'local'
1378
1286
  },
1379
1287
  pages: pages.map((page)=>{
1380
- const { content, _filepath, _html, _flattenContent, ...rest } = page;
1288
+ const { content: _content, _filepath, _html, _flattenContent, ...rest } = page;
1381
1289
  return isProduction() ? rest : {
1382
1290
  ...rest,
1383
1291
  _filepath
@@ -1607,10 +1515,10 @@ async function pMap(iterable, mapper, { concurrency = 1 / 0, stopOnError = true,
1607
1515
  });
1608
1516
  }
1609
1517
  const pMapSkip = Symbol('skip');
1610
- async function renderConfigHead(config, route) {
1518
+ async function renderConfigHead(head, route) {
1611
1519
  if (!isRouteMeta(route)) return '';
1612
- if (!config.head || 0 === config.head.length) return '';
1613
- return config.head.map((head)=>{
1520
+ if (!head || 0 === head.length) return '';
1521
+ return head.map((head)=>{
1614
1522
  if ('string' == typeof head) return head;
1615
1523
  if ('function' == typeof head) {
1616
1524
  const resultHead = head(route);
@@ -1621,6 +1529,12 @@ async function renderConfigHead(config, route) {
1621
1529
  return `<${head[0]} ${renderAttrs(head[1])}>`;
1622
1530
  }).join('');
1623
1531
  }
1532
+ async function renderHtmlTemplate(htmlTemplate, head, route, appHtml = '') {
1533
+ const replacedHtmlTemplate = htmlTemplate.replace(APP_HTML_MARKER, ()=>appHtml).replace(META_GENERATOR, ()=>`<meta name="generator" content="Rspress v${RSPRESS_VERSION}">`).replace(HEAD_MARKER, [
1534
+ await renderConfigHead(head, route)
1535
+ ].join(''));
1536
+ return replacedHtmlTemplate;
1537
+ }
1624
1538
  function renderAttrs(attrs) {
1625
1539
  return Object.entries(attrs).map(([key, value])=>{
1626
1540
  if ('boolean' == typeof value) return key;
@@ -1631,9 +1545,7 @@ function renderAttrs(attrs) {
1631
1545
  function isRouteMeta(route) {
1632
1546
  return !!route && 'object' == typeof route && 'routePath' in route && 'absolutePath' in route;
1633
1547
  }
1634
- async function renderPages(routeService, config, pluginDriver, ssrBundlePath, htmlTemplate, emitAsset) {
1635
- logger.info('Rendering pages...');
1636
- const startTime = Date.now();
1548
+ async function renderPage(route, htmlTemplate, configHead, ssrBundlePath) {
1637
1549
  let render;
1638
1550
  try {
1639
1551
  const { default: ssrExports } = await import((0, external_node_url_.pathToFileURL)(ssrBundlePath).toString());
@@ -1646,45 +1558,123 @@ async function renderPages(routeService, config, pluginDriver, ssrBundlePath, ht
1646
1558
  }
1647
1559
  throw e;
1648
1560
  }
1561
+ const head = createHead();
1562
+ const { routePath } = route;
1563
+ let appHtml = '';
1564
+ if (render) try {
1565
+ ({ appHtml } = await render(routePath, head));
1566
+ } catch (e) {
1567
+ if (e instanceof Error) {
1568
+ logger.error(`Page "${picocolors.yellow(routePath)}" SSG rendering failed.\n ${picocolors.gray(e.toString())}`);
1569
+ throw e;
1570
+ }
1571
+ }
1572
+ const replacedHtmlTemplate = await renderHtmlTemplate(htmlTemplate, configHead, route, appHtml);
1573
+ const html = await transformHtmlTemplate(head, replacedHtmlTemplate);
1574
+ return html;
1575
+ }
1576
+ /**
1577
+ * these codes are copied from
1578
+ * @link https://github.com/facebook/docusaurus/blob/45065e8d2b5831117b8d69fec1be28f5520cf105/packages/docusaurus/src/ssg/ssgEnv.ts#L11
1579
+ * @license MIT
1580
+ */ function SSGWorkerThreadTaskSize() {
1581
+ return process.env.RSPRESS_SSG_WORKER_THREAD_TASK_SIZE ? Number.parseInt(process.env.RSPRESS_SSG_WORKER_THREAD_TASK_SIZE, 10) : 10;
1582
+ }
1583
+ function SSGWorkerThreadRecyclerMaxMemory() {
1584
+ return process.env.RSPRESS_SSG_WORKER_THREAD_RECYCLER_MAX_MEMORY ? Number.parseInt(process.env.RSPRESS_SSG_WORKER_THREAD_RECYCLER_MAX_MEMORY, 10) : 1000000000;
1585
+ }
1586
+ function inferNumberOfThreads({ pageCount, cpuCount, minPagesPerCpu }) {
1587
+ const threadsByWorkload = Math.ceil(pageCount / minPagesPerCpu);
1588
+ return Math.max(1, Math.min(threadsByWorkload, cpuCount));
1589
+ }
1590
+ function SSGWorkerThreadCount() {
1591
+ return process.env.RSPRESS_SSG_WORKER_THREAD_COUNT ? Number.parseInt(process.env.RSPRESS_SSG_WORKER_THREAD_COUNT, 10) : void 0;
1592
+ }
1593
+ function getNumberOfThreads(pathnamesLength) {
1594
+ const workerCount = SSGWorkerThreadCount();
1595
+ if (void 0 !== workerCount) return workerCount;
1596
+ const cpuCount = 'function' == typeof external_node_os_["default"].availableParallelism ? external_node_os_["default"].availableParallelism() : external_node_os_["default"].cpus().length;
1597
+ return inferNumberOfThreads({
1598
+ pageCount: pathnamesLength,
1599
+ cpuCount,
1600
+ minPagesPerCpu: 100
1601
+ });
1602
+ }
1603
+ function SSGConcurrency() {
1604
+ return process.env.RSPRESS_SSG_CONCURRENCY ? Number.parseInt(process.env.RSPRESS_SSG_CONCURRENCY, 10) : 32;
1605
+ }
1606
+ const routePath2HtmlFileName = (routePath)=>{
1607
+ let fileName = routePath;
1608
+ fileName = fileName.endsWith('/') ? `${routePath}index.html` : `${routePath}.html`;
1609
+ return fileName.replace(/^\/+/, '');
1610
+ };
1611
+ async function renderPages(routeService, config, ssrBundlePath, htmlTemplate, emitAsset) {
1612
+ logger.info('Rendering pages...');
1613
+ const startTime = Date.now();
1614
+ const ssg = config.ssg || true;
1649
1615
  try {
1650
1616
  const routes = routeService.getRoutes();
1651
- const additionalRoutes = (await pluginDriver.addSSGRoutes()).map((route)=>({
1652
- routePath: route.path
1653
- }));
1654
- const allRoutes = [
1655
- ...routes,
1656
- ...additionalRoutes
1657
- ];
1658
- const is404RouteInRoutes = allRoutes.some((route)=>'/404' === route.routePath);
1659
- if (!is404RouteInRoutes) allRoutes.push({
1617
+ if (!routeService.isExistRoute('/404')) routes.push({
1660
1618
  routePath: '/404'
1661
1619
  });
1662
- const filteredRoutes = allRoutes.filter((route)=>!route.routePath.includes(':'));
1663
- await pMap(filteredRoutes, async (route)=>{
1664
- const head = createHead();
1665
- const { routePath } = route;
1666
- let appHtml = '';
1667
- if (render) try {
1668
- ({ appHtml } = await render(routePath, head));
1669
- } catch (e) {
1670
- if (e instanceof Error) {
1671
- logger.error(`Page "${picocolors.yellow(routePath)}" SSG rendering failed.\n ${picocolors.gray(e.toString())}`);
1672
- throw e;
1673
- }
1620
+ if ('object' == typeof ssg && Array.isArray(ssg?.experimentalExcludeRoutePaths) && ssg.experimentalExcludeRoutePaths.length > 0) {
1621
+ const shouldIgnoreRoutePaths = new Set();
1622
+ const shouldIgnoreRoutePathsRegExp = [];
1623
+ for (const routePath of ssg.experimentalExcludeRoutePaths)if ('string' == typeof routePath) shouldIgnoreRoutePaths.add(routePath);
1624
+ else if (routePath instanceof RegExp) shouldIgnoreRoutePathsRegExp.push(routePath);
1625
+ const promiseList = [];
1626
+ const csrRoutes = [];
1627
+ const ssgRoutes = [];
1628
+ for (const route of routes)if (shouldIgnoreRoutePaths.has(route.routePath) || shouldIgnoreRoutePathsRegExp.some((reg)=>reg.test(route.routePath))) {
1629
+ csrRoutes.push(route);
1630
+ promiseList.push(renderCSRPage(config.head, route, htmlTemplate, emitAsset));
1631
+ } else ssgRoutes.push(route);
1632
+ if (csrRoutes.length > 0) {
1633
+ logger.warn(`Some routes are ignored in SSG and fallback to CSR via \`ssg.experimentalExcludeRoutePaths\`: ${picocolors.yellow(csrRoutes.map((r)=>r.routePath).join(', '))}`);
1634
+ await Promise.all(promiseList);
1635
+ routes.length = 0;
1636
+ routes.push(...ssgRoutes);
1674
1637
  }
1675
- const replacedHtmlTemplate = htmlTemplate.replace(/<title>(.*?)<\/title>/gi, '').replace(APP_HTML_MARKER, ()=>appHtml).replace(META_GENERATOR, ()=>`<meta name="generator" content="Rspress v${RSPRESS_VERSION}">`).replace(HEAD_MARKER, [
1676
- await renderConfigHead(config, route)
1677
- ].join(''));
1678
- const html = await transformHtmlTemplate(head, replacedHtmlTemplate);
1679
- const normalizeHtmlFilePath = (path)=>{
1680
- const normalizedBase = `${(0, shared_.normalizeSlash)(config?.base || '/')}/`;
1681
- if (path.endsWith('/')) return `${path}index.html`.replace(normalizedBase, '');
1682
- return `${path}.html`.replace(normalizedBase, '');
1683
- };
1684
- const fileName = normalizeHtmlFilePath(routePath);
1638
+ }
1639
+ if ('object' == typeof ssg && ssg?.experimentalWorker) {
1640
+ const numberOfThreads = getNumberOfThreads(routes.length);
1641
+ const Tinypool = await import("tinypool").then((m)=>m.default);
1642
+ const pool = new Tinypool({
1643
+ filename: new URL('./renderPageWorker.js', import.meta.url).href,
1644
+ concurrentTasksPerWorker: 1,
1645
+ minThreads: numberOfThreads,
1646
+ maxThreads: numberOfThreads,
1647
+ /**
1648
+ * https://github.com/facebook/docusaurus/blob/0306d182407bb98f140cd5ec7481fa9608fe0297/packages/docusaurus/src/ssg/ssgExecutor.ts#L123
1649
+ * @license MIT
1650
+ */ maxMemoryLimitBeforeRecycle: SSGWorkerThreadRecyclerMaxMemory(),
1651
+ isolateWorkers: false,
1652
+ workerData: {
1653
+ params: {
1654
+ htmlTemplate,
1655
+ head: config.head,
1656
+ ssrBundlePath
1657
+ }
1658
+ }
1659
+ });
1660
+ await Promise.all(chunk(routes, SSGWorkerThreadTaskSize()).map(async (routes)=>{
1661
+ const htmlList = await pool.run({
1662
+ routes
1663
+ });
1664
+ for(let i = 0; i < routes.length; i++){
1665
+ const route = routes[i];
1666
+ const html = htmlList[i];
1667
+ const fileName = routePath2HtmlFileName(route.routePath);
1668
+ emitAsset(fileName, html);
1669
+ }
1670
+ }));
1671
+ await pool.destroy();
1672
+ } else await pMap(routes, async (route)=>{
1673
+ const html = await renderPage(route, htmlTemplate, config.head, ssrBundlePath);
1674
+ const fileName = routePath2HtmlFileName(route.routePath);
1685
1675
  emitAsset(fileName, html);
1686
1676
  }, {
1687
- concurrency: process.env.RSPRESS_SSG_CONCURRENCY ? Number.parseInt(process.env.RSPRESS_SSG_CONCURRENCY, 10) : 32
1677
+ concurrency: SSGConcurrency()
1688
1678
  });
1689
1679
  const totalTime = Date.now() - startTime;
1690
1680
  logger.success(`Pages rendered in ${picocolors.yellow(totalTime)} ms.`);
@@ -1697,7 +1687,44 @@ async function renderPages(routeService, config, pluginDriver, ssrBundlePath, ht
1697
1687
  throw e;
1698
1688
  }
1699
1689
  }
1700
- const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1690
+ async function renderCSRPage(head, route, htmlTemplate, emitAsset) {
1691
+ const html = await renderHtmlTemplate(htmlTemplate, head, route, '');
1692
+ const fileName = routePath2HtmlFileName(route.routePath);
1693
+ emitAsset(fileName, html);
1694
+ }
1695
+ async function renderCSRPages(routeService, config, htmlTemplate, emitAsset) {
1696
+ const routes = routeService.getRoutes();
1697
+ if (!routeService.isExistRoute('/404')) routes.push({
1698
+ routePath: '/404'
1699
+ });
1700
+ await Promise.all(routes.map((route)=>renderCSRPage(config.head, route, htmlTemplate, emitAsset)));
1701
+ }
1702
+ const rsbuildPluginCSR = ({ routeService, config })=>({
1703
+ name: 'rspress-inner-rsbuild-plugin-csr',
1704
+ async setup (api) {
1705
+ api.onBeforeBuild(()=>{
1706
+ api.processAssets({
1707
+ stage: 'report',
1708
+ environments: [
1709
+ 'web'
1710
+ ]
1711
+ }, async ({ assets, compilation, compiler })=>{
1712
+ if (compilation.errors.length > 0) return;
1713
+ const emitAsset = (assetName, content)=>{
1714
+ compilation.emitAsset(assetName, new compiler.webpack.sources.RawSource(content));
1715
+ };
1716
+ let htmlTemplate = '';
1717
+ for (const [assetName, assetSource] of Object.entries(assets))if ('index.html' === assetName) {
1718
+ htmlTemplate = assetSource.source().toString();
1719
+ compilation.deleteAsset(assetName);
1720
+ break;
1721
+ }
1722
+ await renderCSRPages(routeService, config, htmlTemplate, emitAsset);
1723
+ });
1724
+ });
1725
+ }
1726
+ });
1727
+ const rsbuildPluginSSG = ({ routeService, config })=>({
1701
1728
  name: 'rspress-inner-rsbuild-plugin-ssg',
1702
1729
  async setup (api) {
1703
1730
  api.onBeforeBuild(()=>{
@@ -1706,11 +1733,10 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1706
1733
  const indexHtmlEmittedInWeb = new Promise((resolve, reject)=>{
1707
1734
  api.processAssets({
1708
1735
  stage: 'report',
1709
- targets: [
1736
+ environments: [
1710
1737
  'web'
1711
1738
  ]
1712
- }, ({ assets, compilation, environment })=>{
1713
- if ('web' !== environment.name) return;
1739
+ }, ({ assets, compilation })=>{
1714
1740
  if (compilation.errors.length > 0) {
1715
1741
  hasError = true;
1716
1742
  return;
@@ -1731,16 +1757,18 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1731
1757
  });
1732
1758
  api.processAssets({
1733
1759
  stage: 'optimize-transfer',
1734
- targets: [
1760
+ environments: [
1735
1761
  'node'
1736
1762
  ]
1737
1763
  }, async ({ assets, compilation, environment, compiler })=>{
1738
- if ('node' !== environment.name) return;
1739
1764
  if (compilation.errors.length > 0) {
1740
1765
  hasError = true;
1741
1766
  return;
1742
1767
  }
1743
1768
  if (hasError) return;
1769
+ const emitAsset = (assetName, content)=>{
1770
+ compilation.emitAsset(assetName, new compiler.webpack.sources.RawSource(content));
1771
+ };
1744
1772
  const distPath = environment.distPath;
1745
1773
  const ssgFolderPath = (0, external_node_path_.join)(distPath, NODE_SSG_BUNDLE_FOLDER);
1746
1774
  const mainCjsAbsolutePath = (0, external_node_path_.join)(ssgFolderPath, NODE_SSG_BUNDLE_NAME);
@@ -1754,11 +1782,8 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1754
1782
  compilation.deleteAsset(assetName);
1755
1783
  }
1756
1784
  }));
1757
- const emitAsset = (assetName, content)=>{
1758
- compilation.emitAsset(assetName, new compiler.webpack.sources.RawSource(content));
1759
- };
1760
1785
  await indexHtmlEmittedInWeb;
1761
- await renderPages(routeService, config, pluginDriver, mainCjsAbsolutePath, htmlTemplate, emitAsset);
1786
+ await renderPages(routeService, config, mainCjsAbsolutePath, htmlTemplate, emitAsset);
1762
1787
  if (!(0, shared_.isDebugMode)()) await rm(ssgFolderPath, {
1763
1788
  recursive: true
1764
1789
  });
@@ -1945,13 +1970,13 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1945
1970
  ...runtimeConfigVMPlugin(context)
1946
1971
  }
1947
1972
  }),
1948
- ...enableSSG ? [
1949
- rsbuildPluginSSG({
1950
- routeService,
1951
- config,
1952
- pluginDriver
1953
- })
1954
- ] : []
1973
+ enableSSG ? rsbuildPluginSSG({
1974
+ routeService,
1975
+ config
1976
+ }) : rsbuildPluginCSR({
1977
+ routeService,
1978
+ config
1979
+ })
1955
1980
  ],
1956
1981
  server: {
1957
1982
  port: !isProduction() && process.env.PORT ? Number(process.env.PORT) : void 0,
@@ -1998,7 +2023,6 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1998
2023
  DEFAULT_THEME
1999
2024
  ],
2000
2025
  '@theme-assets': external_node_path_["default"].join(DEFAULT_THEME, '../assets'),
2001
- '@rspress/core': PACKAGE_ROOT,
2002
2026
  'react-lazy-with-preload': require.resolve('react-lazy-with-preload')
2003
2027
  }
2004
2028
  },
@@ -2026,6 +2050,11 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
2026
2050
  })) ?? {
2027
2051
  nav: config.themeConfig?.nav,
2028
2052
  sidebar: config.themeConfig?.sidebar
2053
+ }),
2054
+ JSON.stringify({
2055
+ base: config.base,
2056
+ ssg: config.ssg,
2057
+ pluginLength: config.plugins?.length ?? 0
2029
2058
  })
2030
2059
  ]
2031
2060
  }
@@ -2049,14 +2078,12 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
2049
2078
  const isServer = 'node' === target;
2050
2079
  const jsModuleRule = chain.module.rule(CHAIN_ID.RULE.JS);
2051
2080
  const swcLoaderOptions = jsModuleRule.use(CHAIN_ID.USE.SWC).get('options');
2052
- const checkDeadLinks = (config?.markdown?.checkDeadLinks && !isServer) ?? false;
2053
2081
  chain.module.rule('MDX').type("javascript/auto").test(shared_.MDX_OR_MD_REGEXP).resolve.merge({
2054
2082
  conditionNames: jsModuleRule.resolve.conditionNames.values(),
2055
2083
  mainFields: jsModuleRule.resolve.mainFields.values()
2056
2084
  }).end().oneOf('MDXCompile').use('builtin:swc-loader').loader('builtin:swc-loader').options(swcLoaderOptions).end().use('mdx-loader').loader(require.resolve('./loader.js')).options({
2057
2085
  config,
2058
2086
  docDirectory: userDocRoot,
2059
- checkDeadLinks,
2060
2087
  routeService,
2061
2088
  pluginDriver
2062
2089
  }).end();
@@ -2161,24 +2188,139 @@ async function initRsbuild(rootDir, config, pluginDriver, enableSSG, extraRsbuil
2161
2188
  });
2162
2189
  return rsbuild;
2163
2190
  }
2164
- function checkLanguageParity_normalizePath(filePath) {
2165
- return filePath.split(external_node_path_["default"].sep).join('/');
2166
- }
2167
- async function getAllMarkdownFilesFrom(dirPath) {
2168
- const files = await node_fs_promises.readdir(dirPath, {
2169
- withFileTypes: true
2170
- });
2171
- const allFiles = [];
2172
- for (const file of files){
2173
- const fullPath = external_node_path_["default"].join(dirPath, file.name);
2174
- if (file.isDirectory()) {
2175
- const nestedFiles = await getAllMarkdownFilesFrom(fullPath);
2176
- allFiles.push(...nestedFiles);
2177
- } else if ([
2178
- '.md',
2179
- '.mdx'
2180
- ].includes(external_node_path_["default"].extname(file.name))) allFiles.push(fullPath);
2181
- }
2191
+ class PluginDriver {
2192
+ #config;
2193
+ #configFilePath;
2194
+ #plugins;
2195
+ #isProd;
2196
+ constructor(config, configFilePath, isProd){
2197
+ this.#config = config;
2198
+ this.#configFilePath = configFilePath;
2199
+ this.#isProd = isProd;
2200
+ this.#plugins = [];
2201
+ }
2202
+ getConfigFilePath() {
2203
+ return this.#configFilePath;
2204
+ }
2205
+ async init() {
2206
+ this.clearPlugins();
2207
+ const config = this.#config;
2208
+ const themeConfig = config?.themeConfig || {};
2209
+ const enableLastUpdated = themeConfig?.lastUpdated || themeConfig?.locales?.some((locale)=>locale.lastUpdated);
2210
+ const mediumZoomConfig = config?.mediumZoom ?? true;
2211
+ if (enableLastUpdated) {
2212
+ const { pluginLastUpdated } = await Promise.all([
2213
+ __webpack_require__.e("94"),
2214
+ __webpack_require__.e("208")
2215
+ ]).then(__webpack_require__.bind(__webpack_require__, "./src/node/last-updated/index.ts"));
2216
+ this.addPlugin(pluginLastUpdated());
2217
+ }
2218
+ if (mediumZoomConfig) {
2219
+ const { pluginMediumZoom } = await __webpack_require__.e("309").then(__webpack_require__.bind(__webpack_require__, "./src/node/medium-zoom/index.ts"));
2220
+ this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
2221
+ }
2222
+ (config.plugins || []).forEach((plugin)=>{
2223
+ this.addPlugin(plugin);
2224
+ });
2225
+ }
2226
+ addPlugin(plugin) {
2227
+ const existedIndex = this.#plugins.findIndex((item)=>item.name === plugin.name);
2228
+ if (-1 !== existedIndex) throw new Error(`The plugin "${plugin.name}" has been registered`);
2229
+ this.#plugins.push(plugin);
2230
+ }
2231
+ getPlugins() {
2232
+ return this.#plugins;
2233
+ }
2234
+ clearPlugins() {
2235
+ this.#plugins = [];
2236
+ }
2237
+ removePlugin(pluginName) {
2238
+ const index = this.#plugins.findIndex((item)=>item.name === pluginName);
2239
+ if (-1 !== index) this.#plugins.splice(index, 1);
2240
+ }
2241
+ async modifyConfig() {
2242
+ let config = this.#config;
2243
+ for(let i = 0; i < this.#plugins.length; i++){
2244
+ const plugin = this.#plugins[i];
2245
+ if ('function' == typeof plugin.config) config = await plugin.config(config || {}, {
2246
+ addPlugin: this.addPlugin.bind(this),
2247
+ removePlugin: (pluginName)=>{
2248
+ const index = this.#plugins.findIndex((item)=>item.name === pluginName);
2249
+ this.removePlugin(pluginName);
2250
+ if (index <= i && index > 0) i--;
2251
+ }
2252
+ }, this.#isProd);
2253
+ }
2254
+ this.#config = config;
2255
+ return this.#config;
2256
+ }
2257
+ async beforeBuild() {
2258
+ return this._runParallelAsyncHook('beforeBuild', this.#config || {}, this.#isProd);
2259
+ }
2260
+ async afterBuild() {
2261
+ return this._runParallelAsyncHook('afterBuild', this.#config || {}, this.#isProd);
2262
+ }
2263
+ async modifySearchIndexData(pages) {
2264
+ return this._runParallelAsyncHook('modifySearchIndexData', pages, this.#isProd);
2265
+ }
2266
+ async extendPageData(pageData) {
2267
+ return this._runParallelAsyncHook('extendPageData', pageData, this.#isProd);
2268
+ }
2269
+ async addPages() {
2270
+ const result = await this._runParallelAsyncHook('addPages', this.#config || {}, this.#isProd);
2271
+ return result.flat();
2272
+ }
2273
+ async routeGenerated(routes) {
2274
+ return this._runParallelAsyncHook('routeGenerated', routes, this.#isProd);
2275
+ }
2276
+ async routeServiceGenerated(routeService) {
2277
+ return this._runParallelAsyncHook('routeServiceGenerated', routeService, this.#isProd);
2278
+ }
2279
+ async addRuntimeModules() {
2280
+ const result = await this._runParallelAsyncHook('addRuntimeModules', this.#config || {}, this.#isProd);
2281
+ return result.reduce((prev, current)=>({
2282
+ ...prev,
2283
+ ...current
2284
+ }), {});
2285
+ }
2286
+ globalUIComponents() {
2287
+ const result = this.#plugins.map((plugin)=>plugin.globalUIComponents || []);
2288
+ return result.flat();
2289
+ }
2290
+ globalStyles() {
2291
+ return this.#plugins.filter((plugin)=>'string' == typeof plugin.globalStyles).map((plugin)=>plugin.globalStyles);
2292
+ }
2293
+ _runParallelAsyncHook(hookName, ...args) {
2294
+ return Promise.all(this.#plugins.filter((plugin)=>'function' == typeof plugin[hookName]).map((plugin)=>plugin[hookName](...args)));
2295
+ }
2296
+ _runSerialAsyncHook(hookName, ...args) {
2297
+ return this.#plugins.reduce(async (prev, plugin)=>{
2298
+ if ('function' == typeof plugin[hookName]) {
2299
+ await prev;
2300
+ return plugin[hookName](...args);
2301
+ }
2302
+ return prev;
2303
+ }, Promise.resolve());
2304
+ }
2305
+ }
2306
+ function checkLanguageParity_normalizePath(filePath) {
2307
+ return filePath.split(external_node_path_["default"].sep).join('/');
2308
+ }
2309
+ async function getAllMarkdownFilesFrom(dirPath) {
2310
+ const files = await node_fs_promises.readdir(dirPath, {
2311
+ withFileTypes: true
2312
+ });
2313
+ const allFiles = [];
2314
+ for (const file of files){
2315
+ const fullPath = external_node_path_["default"].join(dirPath, file.name);
2316
+ if (file.isDirectory()) {
2317
+ const nestedFiles = await getAllMarkdownFilesFrom(fullPath);
2318
+ allFiles.push(...nestedFiles);
2319
+ } else if ([
2320
+ '.md',
2321
+ '.mdx'
2322
+ ].includes(external_node_path_["default"].extname(file.name))) allFiles.push(fullPath);
2323
+ }
2182
2324
  return allFiles;
2183
2325
  }
2184
2326
  async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs, fileLangMap) {
@@ -2235,27 +2377,6 @@ async function checkLanguageParity(config) {
2235
2377
  throw err;
2236
2378
  }
2237
2379
  }
2238
- async function dev(options) {
2239
- const { docDirectory, config, extraBuilderConfig, configFilePath } = options;
2240
- const isProd = false;
2241
- const pluginDriver = new PluginDriver(config, configFilePath, isProd);
2242
- await pluginDriver.init();
2243
- const modifiedConfig = await pluginDriver.modifyConfig();
2244
- try {
2245
- const rsbuild = await initRsbuild(docDirectory, modifiedConfig, pluginDriver, false, extraBuilderConfig);
2246
- await pluginDriver.beforeBuild();
2247
- rsbuild.onDevCompileDone(async ()=>{
2248
- await pluginDriver.afterBuild();
2249
- });
2250
- const { server } = await rsbuild.startDevServer({
2251
- getPortSilently: true
2252
- });
2253
- return server;
2254
- } finally{
2255
- await writeSearchIndex(modifiedConfig);
2256
- await checkLanguageParity(modifiedConfig);
2257
- }
2258
- }
2259
2380
  async function bundle(docDirectory, config, pluginDriver, enableSSG) {
2260
2381
  try {
2261
2382
  const rsbuild = await initRsbuild(docDirectory, config, pluginDriver, enableSSG);
@@ -2278,65 +2399,98 @@ async function build(options) {
2278
2399
  const pluginDriver = new PluginDriver(config, configFilePath, true);
2279
2400
  await pluginDriver.init();
2280
2401
  const modifiedConfig = await pluginDriver.modifyConfig();
2281
- const ssgConfig = modifiedConfig.ssg ?? true;
2402
+ const ssgConfig = Boolean(modifiedConfig.ssg ?? true);
2282
2403
  await emptyDir(constants_TEMP_DIR);
2283
2404
  await bundle(docDirectory, modifiedConfig, pluginDriver, ssgConfig);
2284
2405
  if (!ssgConfig) hintSSGFalse();
2285
2406
  }
2286
- async function serve(options) {
2287
- const { config, port: userPort, host: userHost, configFilePath } = options;
2288
- const envPort = process.env.PORT;
2289
- const envHost = process.env.HOST;
2290
- const { builderConfig } = config;
2291
- const port = Number(envPort || userPort || builderConfig?.server?.port || 4173);
2292
- const host = envHost || userHost || builderConfig?.server?.host || 'localhost';
2293
- config.builderConfig = core_mergeRsbuildConfig(builderConfig, {
2294
- server: {
2295
- port,
2296
- host
2297
- }
2298
- });
2299
- const pluginDriver = new PluginDriver(config, configFilePath, true);
2407
+ async function dev(options) {
2408
+ const { docDirectory, config, extraBuilderConfig, configFilePath } = options;
2409
+ const isProd = false;
2410
+ const pluginDriver = new PluginDriver(config, configFilePath, isProd);
2300
2411
  await pluginDriver.init();
2301
2412
  const modifiedConfig = await pluginDriver.modifyConfig();
2302
- const rsbuild = await initRsbuild(config.root, modifiedConfig, pluginDriver, false);
2303
- return rsbuild.preview();
2413
+ try {
2414
+ const rsbuild = await initRsbuild(docDirectory, modifiedConfig, pluginDriver, false, extraBuilderConfig);
2415
+ await pluginDriver.beforeBuild();
2416
+ rsbuild.onDevCompileDone(async ()=>{
2417
+ await pluginDriver.afterBuild();
2418
+ });
2419
+ const { server } = await rsbuild.startDevServer({
2420
+ getPortSilently: true
2421
+ });
2422
+ return server;
2423
+ } finally{
2424
+ await writeSearchIndex(modifiedConfig);
2425
+ await checkLanguageParity(modifiedConfig);
2426
+ }
2304
2427
  }
2305
- const getASTNodeImport = (name, from)=>({
2306
- type: 'mdxjsEsm',
2307
- value: `import ${name} from ${JSON.stringify(from)}`,
2308
- data: {
2309
- estree: {
2310
- type: 'Program',
2311
- sourceType: 'module',
2312
- body: [
2313
- {
2314
- type: 'ImportDeclaration',
2315
- specifiers: [
2316
- {
2317
- type: 'ImportDefaultSpecifier',
2318
- local: {
2319
- type: 'Identifier',
2320
- name
2321
- }
2322
- }
2323
- ],
2324
- source: {
2325
- type: 'Literal',
2326
- value: from,
2327
- raw: `${JSON.stringify(from)}`
2328
- }
2329
- }
2330
- ]
2428
+ const ERROR_PREFIX = '[remarkFileCodeBlock]';
2429
+ function parseFileFromMeta(meta) {
2430
+ if (!meta) return '';
2431
+ const kvList = meta.split(' ').filter(Boolean);
2432
+ for (const item of kvList){
2433
+ const [k, v = ''] = item.split('=');
2434
+ if ('file' === k && v.length > 0) return v.replace(/["'`]/g, '');
2435
+ }
2436
+ return '';
2437
+ }
2438
+ const remarkFileCodeBlock = ({ filepath, addDependency })=>async (tree)=>{
2439
+ const promiseList = [];
2440
+ visit(tree, 'code', (node)=>{
2441
+ const { meta, value, lang } = node;
2442
+ const file = parseFileFromMeta(meta ?? '');
2443
+ if (!file) return;
2444
+ const originalMetaForErrorInfo = picocolors.cyan(`\`\`\`${lang} ${meta}`);
2445
+ if (file.startsWith('./') || file.startsWith('../')) {
2446
+ const resolvedFilePath = external_node_path_["default"].join(external_node_path_["default"].dirname(filepath), file);
2447
+ if ('' !== value.trim()) {
2448
+ logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.
2449
+
2450
+ \`\`\`tsx file="./filename"
2451
+ content
2452
+ \`\`\`
2453
+
2454
+ this usage is not allowed, please use below:
2455
+
2456
+ \`\`\`tsx file="./filename"
2457
+ \`\`\`
2458
+ `);
2459
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.`);
2460
+ }
2461
+ const promise = readFile(resolvedFilePath, 'utf-8').then((fileContent)=>{
2462
+ addDependency?.(resolvedFilePath);
2463
+ node.value = fileContent;
2464
+ }).catch((e)=>{
2465
+ const message = `${ERROR_PREFIX} ${originalMetaForErrorInfo} introduces another file in "${resolvedFilePath}", but the file does not exist.`;
2466
+ logger.error(message);
2467
+ e.message = `${message}\n${e.message}`;
2468
+ throw e;
2469
+ });
2470
+ promiseList.push(promise);
2471
+ return;
2331
2472
  }
2332
- }
2333
- });
2334
- function normalizeLink_checkDeadLinks(internalLinks, filePath, routeService) {
2473
+ logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block:
2474
+ Please use below:
2475
+
2476
+ \`\`\`tsx file="./filename"
2477
+ \`\`\`
2478
+ `);
2479
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block`);
2480
+ });
2481
+ await Promise.all(promiseList);
2482
+ };
2483
+ function link_checkDeadLinks(checkDeadLinks, internalLinks, filePath, routeService) {
2335
2484
  const errorInfos = [];
2485
+ const excludes = 'object' == typeof checkDeadLinks ? checkDeadLinks.excludes : void 0;
2486
+ const excludesUrl = Array.isArray(excludes) ? new Set(excludes) : void 0;
2487
+ const excludesFn = 'function' == typeof excludes ? excludes : void 0;
2336
2488
  let possibleBreakingChange = false;
2337
2489
  [
2338
2490
  ...internalLinks.entries()
2339
2491
  ].forEach(([nodeUrl, link])=>{
2492
+ if (excludesUrl?.has(nodeUrl)) return;
2493
+ if (excludesFn?.(nodeUrl)) return;
2340
2494
  const cleanLinkPath = linkToRoutePath(link);
2341
2495
  if (!cleanLinkPath) return;
2342
2496
  if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
@@ -2352,13 +2506,31 @@ ${errorInfos.map(([nodeUrl, link])=>` ${picocolors.green(`"[..](${nodeUrl})"`)}
2352
2506
  if ((0, shared_.isProduction)()) throw new Error('Dead link found');
2353
2507
  }
2354
2508
  }
2355
- function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, internalLinks, __base) {
2509
+ function looseMarkdownLink(url, routeService, filePath) {
2510
+ if (!routeService.isInDocsDir(filePath)) return url;
2511
+ const [versionPart, langPart, pureRoute] = routeService.splitRoutePathParts(url);
2512
+ const relativePath = routeService.absolutePathToRelativePath(filePath);
2513
+ const [versionPartCurrFile, langPartCurrFile] = routeService.getRoutePathParts(relativePath);
2514
+ if ('' === versionPart) {
2515
+ if ('' === langPart) return (0, shared_.addLeadingSlash)(`${[
2516
+ versionPartCurrFile,
2517
+ langPartCurrFile
2518
+ ].filter(Boolean).join('/')}${(0, shared_.addLeadingSlash)(pureRoute.replace(/^\/*/, ''))}`);
2519
+ return (0, shared_.addLeadingSlash)(`${[
2520
+ versionPartCurrFile,
2521
+ langPart
2522
+ ].filter(Boolean).join('/')}${(0, shared_.addLeadingSlash)(pureRoute.replace(/^\/*/, ''))}`);
2523
+ }
2524
+ return url;
2525
+ }
2526
+ function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, autoPrefix, internalLinks, __base) {
2356
2527
  if (!nodeUrl) return '';
2357
2528
  if (nodeUrl.startsWith('#')) return nodeUrl;
2358
2529
  let { url, hash } = (0, shared_.parseUrl)(nodeUrl);
2359
2530
  if ((0, shared_.isExternalUrl)(url)) return url + (hash ? `#${hash}` : '');
2360
2531
  if (!routeService) return nodeUrl;
2361
2532
  if (url.startsWith('/')) {
2533
+ if (autoPrefix) url = looseMarkdownLink(url, routeService, filePath);
2362
2534
  const { routePath } = routeService.normalizeRoutePath(url);
2363
2535
  url = routePath;
2364
2536
  } else {
@@ -2378,130 +2550,44 @@ function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, internalLinks
2378
2550
  function linkToRoutePath(routePath) {
2379
2551
  return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
2380
2552
  }
2381
- const normalizeImageUrl = (imageUrl)=>{
2382
- if ((0, shared_.isExternalUrl)(imageUrl) || imageUrl.startsWith('/')) return '';
2383
- return imageUrl;
2384
- };
2385
- const remarkPluginNormalizeLink = ({ cleanUrls, routeService, checkDeadLinks: shouldCheckDeadLinks = false, __base })=>(tree, file)=>{
2553
+ const remarkLink = ({ cleanUrls, routeService, remarkLinkOptions, __base })=>(tree, file)=>{
2554
+ const { checkDeadLinks: shouldCheckDeadLinks = true, autoPrefix = true } = remarkLinkOptions ?? {};
2386
2555
  const internalLinks = new Map();
2387
2556
  visit(tree, 'link', (node)=>{
2388
2557
  const { url: nodeUrl } = node;
2389
- const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
2558
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, autoPrefix, internalLinks, __base);
2390
2559
  node.url = link;
2391
2560
  });
2392
2561
  visit(tree, 'definition', (node)=>{
2393
2562
  const { url: nodeUrl } = node;
2394
- const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
2563
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, autoPrefix, internalLinks, __base);
2395
2564
  node.url = link;
2396
2565
  });
2397
- if (shouldCheckDeadLinks && routeService) normalizeLink_checkDeadLinks(internalLinks, file.path, routeService);
2398
- const images = [];
2399
- const getMdxSrcAttribute = (tempVar)=>({
2400
- type: 'mdxJsxAttribute',
2401
- name: 'src',
2402
- value: {
2403
- type: 'mdxJsxAttributeValueExpression',
2404
- value: tempVar,
2405
- data: {
2406
- estree: {
2407
- type: 'Program',
2408
- sourceType: 'module',
2409
- body: [
2410
- {
2411
- type: 'ExpressionStatement',
2412
- expression: {
2413
- type: 'Identifier',
2414
- name: tempVar
2415
- }
2416
- }
2417
- ]
2418
- }
2419
- }
2420
- }
2421
- });
2422
- visit(tree, 'image', (node)=>{
2423
- const { alt, url } = node;
2424
- if (!url) return;
2425
- const imagePath = normalizeImageUrl(url);
2426
- if (!imagePath) return;
2427
- const tempVariableName = `image${images.length}`;
2428
- Object.assign(node, {
2429
- type: 'mdxJsxFlowElement',
2430
- name: 'img',
2431
- children: [],
2432
- attributes: [
2433
- alt && {
2434
- type: 'mdxJsxAttribute',
2435
- name: 'alt',
2436
- value: alt
2437
- },
2438
- getMdxSrcAttribute(tempVariableName)
2439
- ].filter(Boolean)
2440
- });
2441
- images.push(getASTNodeImport(tempVariableName, imagePath));
2442
- });
2443
- visit(tree, (node)=>{
2444
- if ('mdxJsxFlowElement' !== node.type && 'mdxJsxTextElement' !== node.type || 'img' !== node.name) return;
2445
- const srcAttr = getNodeAttribute(node, 'src', true);
2446
- if ('string' != typeof srcAttr?.value) return;
2447
- const imagePath = normalizeImageUrl(srcAttr.value);
2448
- if (!imagePath) return;
2449
- const tempVariableName = `image${images.length}`;
2450
- Object.assign(srcAttr, getMdxSrcAttribute(tempVariableName));
2451
- images.push(getASTNodeImport(tempVariableName, imagePath));
2452
- });
2453
- tree.children.unshift(...images);
2566
+ if (shouldCheckDeadLinks && routeService) link_checkDeadLinks(shouldCheckDeadLinks, internalLinks, file.path, routeService);
2454
2567
  };
2455
- const ERROR_PREFIX = '[remarkFileCodeBlock]';
2456
- function parseFileFromMeta(meta) {
2457
- if (!meta) return '';
2458
- const kvList = meta.split(' ').filter(Boolean);
2459
- for (const item of kvList){
2460
- const [k, v] = item.split('=');
2461
- if ('file' === k && v.length > 0) return v.replace(/["'`]/g, '');
2462
- }
2463
- return '';
2568
+ async function serve(options) {
2569
+ const { config, port: userPort, host: userHost, configFilePath } = options;
2570
+ const envPort = process.env.PORT;
2571
+ const envHost = process.env.HOST;
2572
+ const { builderConfig } = config;
2573
+ const port = Number(envPort || userPort || builderConfig?.server?.port || 4173);
2574
+ const host = envHost || userHost || builderConfig?.server?.host || 'localhost';
2575
+ config.builderConfig = core_mergeRsbuildConfig(builderConfig, {
2576
+ server: {
2577
+ port,
2578
+ host
2579
+ }
2580
+ });
2581
+ const pluginDriver = new PluginDriver(config, configFilePath, true);
2582
+ await pluginDriver.init();
2583
+ const modifiedConfig = await pluginDriver.modifyConfig();
2584
+ const rsbuild = await initRsbuild(config.root, modifiedConfig, pluginDriver, false);
2585
+ return rsbuild.preview();
2464
2586
  }
2465
- const remarkFileCodeBlock = ({ filepath })=>async (tree)=>{
2466
- const promiseList = [];
2467
- visit(tree, 'code', (node)=>{
2468
- const { meta, value } = node;
2469
- const file = parseFileFromMeta(meta ?? '');
2470
- if (!file) return;
2471
- if (file.startsWith('./') || file.startsWith('../')) {
2472
- const resolvedFilePath = external_node_path_["default"].join(external_node_path_["default"].dirname(filepath), file);
2473
- if ('' !== value.trim()) {
2474
- logger.error(`${ERROR_PREFIX} The content of file code block should be empty.
2475
-
2476
- \`\`\`tsx file="./filename"
2477
- content
2478
- \`\`\`
2479
-
2480
- this usage is not allowed, please use below:
2481
-
2482
- \`\`\`tsx file="./filename"
2483
- \`\`\`
2484
- `);
2485
- throw new Error(`${ERROR_PREFIX} The content of file code block should be empty.`);
2486
- }
2487
- const promise = readFile(resolvedFilePath, 'utf-8').then((fileContent)=>{
2488
- node.value = fileContent;
2489
- }).catch((e)=>{
2490
- logger.error(`${ERROR_PREFIX} The file does not exist.
2491
- \`file="${file}"\` is resolved to ${resolvedFilePath}"`);
2492
- throw e;
2493
- });
2494
- promiseList.push(promise);
2495
- return;
2496
- }
2497
- throw new Error(`${ERROR_PREFIX} The file path should use relative path "./" or "../"`);
2498
- });
2499
- await Promise.all(promiseList);
2500
- };
2501
2587
  var __webpack_exports__RSPRESS_TEMP_DIR = shared_.RSPRESS_TEMP_DIR;
2502
2588
  var __webpack_exports__getSidebarDataGroup = shared_.getSidebarDataGroup;
2503
2589
  var __webpack_exports__normalizeHref = shared_.normalizeHref;
2504
2590
  var __webpack_exports__normalizePosixPath = shared_.normalizePosixPath;
2505
2591
  var __webpack_exports__removeTrailingSlash = shared_.removeTrailingSlash;
2506
2592
  var __webpack_exports__withBase = shared_.withBase;
2507
- export { build, dev, getIconUrlPath, getNodeAttribute, logger, matchPath, mergeDocConfig, remarkFileCodeBlock, remarkPluginNormalizeLink, serve, __webpack_exports__RSPRESS_TEMP_DIR as RSPRESS_TEMP_DIR, __webpack_exports__getSidebarDataGroup as getSidebarDataGroup, __webpack_exports__normalizeHref as normalizeHref, __webpack_exports__normalizePosixPath as normalizePosixPath, __webpack_exports__removeTrailingSlash as removeTrailingSlash, __webpack_exports__withBase as withBase };
2593
+ export { build, defineConfig, dev, getIconUrlPath, getNodeAttribute, logger, matchPath, mergeDocConfig, remarkFileCodeBlock, remarkLink, serve, __webpack_exports__RSPRESS_TEMP_DIR as RSPRESS_TEMP_DIR, __webpack_exports__getSidebarDataGroup as getSidebarDataGroup, __webpack_exports__normalizeHref as normalizeHref, __webpack_exports__normalizePosixPath as normalizePosixPath, __webpack_exports__removeTrailingSlash as removeTrailingSlash, __webpack_exports__withBase as withBase };