@rspress/core 1.39.2 → 1.39.4

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
@@ -66,7 +66,7 @@ var require_package = __commonJS({
66
66
  "package.json"(exports, module) {
67
67
  module.exports = {
68
68
  name: "@rspress/core",
69
- version: "1.39.2",
69
+ version: "1.39.4",
70
70
  description: "The Rspress Documentation Framework",
71
71
  bugs: "https://github.com/web-infra-dev/rspress/issues",
72
72
  repository: {
@@ -75,11 +75,16 @@ var require_package = __commonJS({
75
75
  directory: "packages/cli/core"
76
76
  },
77
77
  license: "MIT",
78
+ sideEffects: [
79
+ "*.css",
80
+ "*.less",
81
+ "*.sass",
82
+ "*.scss",
83
+ "**/virtual-global-styles.js",
84
+ "virtual-global-styles",
85
+ "./src/theme-default/styles/index.ts"
86
+ ],
78
87
  type: "module",
79
- "jsnext:source": "./src/index.ts",
80
- types: "./dist/index.d.ts",
81
- main: "./dist/index.js",
82
- module: "./dist/node/index.js",
83
88
  exports: {
84
89
  ".": {
85
90
  types: "./dist/index.d.ts",
@@ -95,20 +100,31 @@ var require_package = __commonJS({
95
100
  default: "./runtime.ts"
96
101
  }
97
102
  },
103
+ main: "./dist/index.js",
104
+ module: "./dist/node/index.js",
105
+ types: "./dist/index.d.ts",
106
+ files: [
107
+ "dist",
108
+ "src/runtime",
109
+ "src/theme-default",
110
+ "src/shared",
111
+ "index.html",
112
+ "runtime.ts",
113
+ "theme.ts",
114
+ "loader.cjs",
115
+ "compiled"
116
+ ],
98
117
  scripts: {
99
- dev: "modern build -w",
100
118
  build: "modern build",
119
+ dev: "modern build -w",
101
120
  reset: "rimraf ./**/node_modules",
102
121
  test: "vitest run --passWithNoTests"
103
122
  },
104
- engines: {
105
- node: ">=14.17.6"
106
- },
107
123
  dependencies: {
108
124
  "@mdx-js/loader": "2.3.0",
109
125
  "@mdx-js/mdx": "2.3.0",
110
126
  "@mdx-js/react": "2.3.0",
111
- "@rsbuild/core": "~1.1.12",
127
+ "@rsbuild/core": "~1.1.13",
112
128
  "@rsbuild/plugin-less": "~1.1.0",
113
129
  "@rsbuild/plugin-react": "~1.1.0",
114
130
  "@rsbuild/plugin-sass": "~1.1.2",
@@ -142,8 +158,8 @@ var require_package = __commonJS({
142
158
  "unist-util-visit-children": "^3.0.0"
143
159
  },
144
160
  devDependencies: {
145
- "@modern-js/plugin-tailwindcss": "2.63.3",
146
- "@modern-js/tsconfig": "2.63.3",
161
+ "@modern-js/plugin-tailwindcss": "2.63.5",
162
+ "@modern-js/tsconfig": "2.63.5",
147
163
  "@types/hast": "3.0.4",
148
164
  "@types/html-to-text": "^9.0.4",
149
165
  "@types/jest": "~29.5.14",
@@ -161,43 +177,219 @@ var require_package = __commonJS({
161
177
  typescript: "^5.5.3",
162
178
  vitest: "2.1.8"
163
179
  },
164
- sideEffects: [
165
- "*.css",
166
- "*.less",
167
- "*.sass",
168
- "*.scss",
169
- "**/virtual-global-styles.js",
170
- "virtual-global-styles",
171
- "./src/theme-default/styles/index.ts"
172
- ],
173
- files: [
174
- "dist",
175
- "src/runtime",
176
- "src/theme-default",
177
- "src/shared",
178
- "index.html",
179
- "runtime.ts",
180
- "theme.ts",
181
- "loader.cjs",
182
- "compiled"
183
- ],
180
+ engines: {
181
+ node: ">=14.17.6"
182
+ },
184
183
  publishConfig: {
185
184
  access: "public",
186
185
  provenance: true,
187
186
  registry: "https://registry.npmjs.org/"
188
- }
187
+ },
188
+ "jsnext:source": "./src/index.ts"
189
189
  };
190
190
  }
191
191
  });
192
192
 
193
+ // src/node/PluginDriver.ts
194
+ import { pluginContainerSyntax } from "@rspress/plugin-container-syntax";
195
+ import { isDevDebugMode } from "@rspress/shared";
196
+ var _config, _plugins, _isProd;
197
+ var PluginDriver = class {
198
+ constructor(config, isProd) {
199
+ __privateAdd(this, _config, void 0);
200
+ __privateAdd(this, _plugins, void 0);
201
+ __privateAdd(this, _isProd, void 0);
202
+ __privateSet(this, _config, config);
203
+ __privateSet(this, _isProd, isProd);
204
+ __privateSet(this, _plugins, []);
205
+ }
206
+ // The init function is used to initialize the doc plugins and will execute before the build process.
207
+ async init() {
208
+ this.clearPlugins();
209
+ const config = __privateGet(this, _config);
210
+ const themeConfig = config?.themeConfig || {};
211
+ const enableLastUpdated = themeConfig?.lastUpdated || themeConfig?.locales?.some((locale) => locale.lastUpdated);
212
+ const mediumZoomConfig = config?.mediumZoom ?? true;
213
+ const haveNavSidebarConfig = themeConfig.nav || themeConfig.sidebar || themeConfig.locales?.[0]?.nav || themeConfig.locales?.[0]?.sidebar;
214
+ if (enableLastUpdated) {
215
+ const { pluginLastUpdated } = await import("@rspress/plugin-last-updated");
216
+ this.addPlugin(pluginLastUpdated());
217
+ }
218
+ if (mediumZoomConfig) {
219
+ const { pluginMediumZoom } = await import("@rspress/plugin-medium-zoom");
220
+ this.addPlugin(
221
+ pluginMediumZoom(
222
+ typeof mediumZoomConfig === "object" ? mediumZoomConfig : void 0
223
+ )
224
+ );
225
+ }
226
+ this.addPlugin(pluginContainerSyntax());
227
+ if (isDevDebugMode()) {
228
+ const SourceBuildPlugin = await import(
229
+ // @ts-expect-error need moduleResolution: Node16, NodeNext or Bundler to get type declarations work
230
+ "@rspress/theme-default/node/source-build-plugin.js"
231
+ ).then(
232
+ (r) => r.SourceBuildPlugin,
233
+ () => null
234
+ );
235
+ if (SourceBuildPlugin) {
236
+ this.addPlugin(SourceBuildPlugin());
237
+ }
238
+ }
239
+ (config.plugins || []).forEach((plugin) => {
240
+ this.addPlugin(plugin);
241
+ });
242
+ if (!haveNavSidebarConfig) {
243
+ const { pluginAutoNavSidebar } = await import("@rspress/plugin-auto-nav-sidebar");
244
+ this.addPlugin(pluginAutoNavSidebar());
245
+ }
246
+ }
247
+ addPlugin(plugin) {
248
+ const existedIndex = __privateGet(this, _plugins).findIndex(
249
+ (item) => item.name === plugin.name
250
+ );
251
+ if (existedIndex !== -1) {
252
+ throw new Error(`The plugin "${plugin.name}" has been registered`);
253
+ }
254
+ __privateGet(this, _plugins).push(plugin);
255
+ }
256
+ getPlugins() {
257
+ return __privateGet(this, _plugins);
258
+ }
259
+ clearPlugins() {
260
+ __privateSet(this, _plugins, []);
261
+ }
262
+ removePlugin(pluginName) {
263
+ const index = __privateGet(this, _plugins).findIndex((item) => item.name === pluginName);
264
+ if (index !== -1) {
265
+ __privateGet(this, _plugins).splice(index, 1);
266
+ }
267
+ }
268
+ async modifyConfig() {
269
+ let config = __privateGet(this, _config);
270
+ for (let i = 0; i < __privateGet(this, _plugins).length; i++) {
271
+ const plugin = __privateGet(this, _plugins)[i];
272
+ if (typeof plugin.config === "function") {
273
+ config = await plugin.config(
274
+ config || {},
275
+ {
276
+ addPlugin: this.addPlugin.bind(this),
277
+ removePlugin: (pluginName) => {
278
+ const index = __privateGet(this, _plugins).findIndex(
279
+ (item) => item.name === pluginName
280
+ );
281
+ this.removePlugin(pluginName);
282
+ if (index <= i && index > 0) {
283
+ i--;
284
+ }
285
+ }
286
+ },
287
+ __privateGet(this, _isProd)
288
+ );
289
+ }
290
+ }
291
+ __privateSet(this, _config, config);
292
+ return __privateGet(this, _config);
293
+ }
294
+ async beforeBuild() {
295
+ return this._runParallelAsyncHook(
296
+ "beforeBuild",
297
+ __privateGet(this, _config) || {},
298
+ __privateGet(this, _isProd)
299
+ );
300
+ }
301
+ async afterBuild() {
302
+ return this._runParallelAsyncHook(
303
+ "afterBuild",
304
+ __privateGet(this, _config) || {},
305
+ __privateGet(this, _isProd)
306
+ );
307
+ }
308
+ async modifySearchIndexData(pages) {
309
+ return this._runParallelAsyncHook(
310
+ "modifySearchIndexData",
311
+ pages,
312
+ __privateGet(this, _isProd)
313
+ );
314
+ }
315
+ async extendPageData(pageData) {
316
+ return this._runParallelAsyncHook("extendPageData", pageData, __privateGet(this, _isProd));
317
+ }
318
+ async addPages() {
319
+ const result = await this._runParallelAsyncHook(
320
+ "addPages",
321
+ __privateGet(this, _config) || {},
322
+ __privateGet(this, _isProd)
323
+ );
324
+ return result.flat();
325
+ }
326
+ async routeGenerated(routes) {
327
+ return this._runParallelAsyncHook("routeGenerated", routes);
328
+ }
329
+ async addRuntimeModules() {
330
+ const result = await this._runParallelAsyncHook(
331
+ "addRuntimeModules",
332
+ __privateGet(this, _config) || {},
333
+ __privateGet(this, _isProd)
334
+ );
335
+ return result.reduce((prev, current) => {
336
+ return {
337
+ ...prev,
338
+ ...current
339
+ };
340
+ }, {});
341
+ }
342
+ async addSSGRoutes() {
343
+ const result = await this._runParallelAsyncHook(
344
+ "addSSGRoutes",
345
+ __privateGet(this, _config) || {},
346
+ __privateGet(this, _isProd)
347
+ );
348
+ return result.flat();
349
+ }
350
+ globalUIComponents() {
351
+ const result = __privateGet(this, _plugins).map((plugin) => {
352
+ return plugin.globalUIComponents || [];
353
+ });
354
+ return result.flat();
355
+ }
356
+ globalStyles() {
357
+ return __privateGet(this, _plugins).filter((plugin) => typeof plugin.globalStyles === "string").map((plugin) => {
358
+ return plugin.globalStyles;
359
+ });
360
+ }
361
+ _runParallelAsyncHook(hookName, ...args) {
362
+ return Promise.all(
363
+ __privateGet(this, _plugins).filter((plugin) => typeof plugin[hookName] === "function").map((plugin) => {
364
+ return plugin[hookName](...args);
365
+ })
366
+ );
367
+ }
368
+ _runSerialAsyncHook(hookName, ...args) {
369
+ return __privateGet(this, _plugins).reduce(async (prev, plugin) => {
370
+ if (typeof plugin[hookName] === "function") {
371
+ await prev;
372
+ return plugin[hookName](...args);
373
+ }
374
+ return prev;
375
+ }, Promise.resolve());
376
+ }
377
+ };
378
+ _config = new WeakMap();
379
+ _plugins = new WeakMap();
380
+ _isProd = new WeakMap();
381
+
193
382
  // src/node/initRsbuild.ts
194
383
  import path11 from "path";
384
+ import { PLUGIN_LESS_NAME, pluginLess } from "@rsbuild/plugin-less";
385
+ import { PLUGIN_REACT_NAME, pluginReact } from "@rsbuild/plugin-react";
386
+ import { PLUGIN_SASS_NAME, pluginSass } from "@rsbuild/plugin-sass";
195
387
  import {
196
- removeLeadingSlash as removeLeadingSlash2,
197
388
  MDX_REGEXP as MDX_REGEXP3,
198
389
  RSPRESS_TEMP_DIR as RSPRESS_TEMP_DIR2,
199
- removeTrailingSlash,
200
- isDebugMode
390
+ isDebugMode,
391
+ removeLeadingSlash as removeLeadingSlash2,
392
+ removeTrailingSlash
201
393
  } from "@rspress/shared";
202
394
  import fs8 from "@rspress/shared/fs-extra";
203
395
 
@@ -242,28 +434,14 @@ var TEMP_DIR = path.join(
242
434
  RSPRESS_TEMP_DIR
243
435
  );
244
436
 
245
- // src/node/runtimeModule/index.ts
246
- import { RspackVirtualModulePlugin } from "rspack-plugin-virtual-module";
247
-
248
- // src/node/runtimeModule/routeData.ts
249
- async function routeVMPlugin(context) {
250
- const { routeService: routeService2, isSSR } = context;
251
- if (!isSSR) {
252
- return {
253
- ["virtual-routes" /* RouteForClient */]: routeService2.generateRoutesCode(false)
254
- };
255
- }
256
- return {
257
- ["virtual-routes" /* RouteForClient */]: routeService2.generateRoutesCode(false),
258
- ["virtual-routes-ssr" /* RouteForSSR */]: routeService2.generateRoutesCode(true)
259
- };
260
- }
261
-
262
- // src/node/runtimeModule/siteData/index.ts
263
- import path6 from "path";
264
- import fs4 from "@rspress/shared/fs-extra";
265
- import { groupBy } from "lodash-es";
266
- import { SEARCH_INDEX_NAME } from "@rspress/shared";
437
+ // src/node/route/RouteService.ts
438
+ import path5 from "path";
439
+ import {
440
+ addLeadingSlash,
441
+ addTrailingSlash,
442
+ withBase
443
+ } from "@rspress/shared";
444
+ import fs3 from "@rspress/shared/fs-extra";
267
445
 
268
446
  // src/node/utils/normalizePath.ts
269
447
  import os from "os";
@@ -292,8 +470,8 @@ function createHash(str) {
292
470
  // src/node/utils/detectReactVersion.ts
293
471
  import path3 from "path";
294
472
  import fs from "@rspress/shared/fs-extra";
295
- import enhancedResolve from "enhanced-resolve";
296
473
  import { logger } from "@rspress/shared/logger";
474
+ import enhancedResolve from "enhanced-resolve";
297
475
  var { CachedInputFileSystem, ResolverFactory } = enhancedResolve;
298
476
  var DEFAULT_REACT_VERSION = 18;
299
477
  async function detectReactVersion() {
@@ -353,10 +531,10 @@ async function resolveReactAlias(reactVersion, isSSR) {
353
531
 
354
532
  // src/node/utils/flattenMdxContent.ts
355
533
  import path4 from "path";
534
+ import { createProcessor } from "@mdx-js/mdx";
535
+ import { MDX_REGEXP } from "@rspress/shared";
356
536
  import fs2 from "@rspress/shared/fs-extra";
357
537
  import enhancedResolve2 from "enhanced-resolve";
358
- import { MDX_REGEXP } from "@rspress/shared";
359
- import { createProcessor } from "@mdx-js/mdx";
360
538
  var resolver;
361
539
  var startFlatten = false;
362
540
  var processor = createProcessor();
@@ -451,217 +629,587 @@ function applyReplaceRules(code = "", replaceRules = []) {
451
629
  return result;
452
630
  }
453
631
 
454
- // src/node/runtimeModule/siteData/extractPageData.ts
455
- import path5 from "path";
456
- import fs3 from "@rspress/shared/fs-extra";
457
- import { htmlToText } from "html-to-text";
458
- import { compile } from "@rspress/mdx-rs";
459
- import { loadFrontMatter } from "@rspress/shared/node-utils";
460
- import {
461
- MDX_REGEXP as MDX_REGEXP2
462
- } from "@rspress/shared";
463
- function applyReplaceRulesToNestedObject(obj, replaceRules) {
464
- for (const key in obj) {
465
- if (typeof obj[key] === "string") {
466
- obj[key] = applyReplaceRules(obj[key], replaceRules);
467
- } else if (typeof obj[key] === "object") {
468
- obj[key] = applyReplaceRulesToNestedObject(obj[key], replaceRules);
632
+ // src/node/route/RouteService.ts
633
+ var DEFAULT_PAGE_EXTENSIONS = ["js", "jsx", "ts", "tsx", "md", "mdx"];
634
+ var normalizeRoutePath = (routePath, base, lang, version, langs, versions, extensions = DEFAULT_PAGE_EXTENSIONS) => {
635
+ const hasTrailSlash = routePath.endsWith("/");
636
+ let versionPart = "";
637
+ let langPart = "";
638
+ let purePathPart = "";
639
+ const parts = routePath.split("/").filter(Boolean);
640
+ if (version) {
641
+ const versionToMatch = parts[0];
642
+ if (versions.includes(versionToMatch)) {
643
+ if (versionToMatch !== version) {
644
+ versionPart = versionToMatch;
645
+ }
646
+ parts.shift();
469
647
  }
470
648
  }
471
- return obj;
472
- }
473
- async function extractPageData(replaceRules, alias, domain, root, routeService2, highlighterLangs) {
474
- const pageData = await Promise.all(
475
- routeService2.getRoutes().map(async (route, index) => {
476
- const defaultIndexInfo = {
477
- id: index,
478
- title: "",
479
- content: "",
480
- _html: "",
481
- routePath: route.routePath,
482
- lang: route.lang,
483
- toc: [],
484
- domain,
485
- frontmatter: {},
486
- version: route.version,
487
- _filepath: route.absolutePath,
488
- _relativePath: path5.relative(root, route.absolutePath)
489
- };
490
- if (!MDX_REGEXP2.test(route.absolutePath)) {
491
- return defaultIndexInfo;
492
- }
493
- let content = await fs3.readFile(route.absolutePath, "utf8");
494
- const { frontmatter, content: strippedFrontMatter } = loadFrontMatter(
495
- content,
496
- route.absolutePath,
497
- root
498
- );
499
- applyReplaceRulesToNestedObject(frontmatter, replaceRules);
500
- const { flattenContent } = await flattenMdxContent(
501
- applyReplaceRules(strippedFrontMatter, replaceRules),
502
- route.absolutePath,
503
- alias
504
- );
505
- content = flattenContent.replace(importStatementRegex, "");
506
- const {
507
- html,
508
- title,
509
- toc: rawToc,
510
- languages
511
- } = await compile({
512
- value: content,
513
- filepath: route.absolutePath,
514
- development: process.env.NODE_ENV !== "production",
515
- root
516
- });
517
- if (!title?.length && !frontmatter && !frontmatter.title?.length) {
518
- return null;
519
- }
520
- content = htmlToText(String(html), {
521
- wordwrap: 80,
522
- selectors: [
523
- {
524
- selector: "a",
525
- options: {
526
- ignoreHref: true
527
- }
528
- },
529
- {
530
- selector: "img",
531
- format: "skip"
532
- },
533
- {
534
- // Skip code blocks
535
- selector: "pre > code",
536
- format: "skip"
537
- },
538
- ...["h1", "h2", "h3", "h4", "h5", "h6"].map((tag) => ({
539
- selector: tag,
540
- options: {
541
- uppercase: false
542
- }
543
- }))
544
- ],
545
- tables: true,
546
- longWordSplit: {
547
- forceWrapOnLimit: true
548
- }
549
- });
550
- if (content.startsWith(title)) {
551
- content = content.slice(title.length);
649
+ if (lang) {
650
+ const langToMatch = parts[0];
651
+ if (langs.includes(langToMatch)) {
652
+ if (langToMatch !== lang) {
653
+ langPart = langToMatch;
552
654
  }
553
- languages.forEach((lang) => highlighterLangs.add(lang));
554
- const toc = rawToc.map((item) => {
555
- const match = item.id.match(/-(\d+)$/);
556
- let position = -1;
557
- if (match) {
558
- for (let i = 0; i < Number(match[1]); i++) {
559
- position = content.indexOf(`
560
- ${item.text}#
561
-
562
- `, position + 1);
563
- if (position === -1) {
564
- break;
565
- }
566
- }
567
- }
568
- return {
569
- ...item,
570
- charIndex: content.indexOf(`
571
- ${item.text}#
572
-
573
- `, position + 1)
574
- };
575
- });
576
- return {
577
- ...defaultIndexInfo,
578
- title: frontmatter.title || title,
579
- toc,
580
- // Stripped frontmatter content
581
- content,
582
- _html: html,
583
- frontmatter: {
584
- ...frontmatter,
585
- __content: void 0
586
- }
587
- };
588
- })
589
- );
590
- return pageData.filter(Boolean);
591
- }
592
-
593
- // src/node/runtimeModule/siteData/normalizeThemeConfig.ts
594
- import {
595
- withBase,
596
- addLeadingSlash,
597
- isExternalUrl,
598
- withoutBase,
599
- slash as slash2
600
- } from "@rspress/shared";
601
-
602
- // src/node/runtimeModule/i18n.ts
603
- import { join } from "path";
604
- var DEFAULT_I18N_SOURCE = join(process.cwd(), "i18n.json");
605
- function getI18nData(docConfig) {
606
- const { i18nSourcePath = DEFAULT_I18N_SOURCE } = docConfig;
607
- try {
608
- delete __require.cache[i18nSourcePath];
609
- const i18nSource = __require(i18nSourcePath);
610
- return i18nSource;
611
- } catch (e) {
612
- return {};
655
+ parts.shift();
656
+ }
657
+ }
658
+ purePathPart = parts.join("/");
659
+ let normalizedRoutePath = addLeadingSlash(
660
+ [versionPart, langPart, purePathPart].filter(Boolean).join("/")
661
+ ).replace(new RegExp(`\\.(${extensions.join("|")})$`), "").replace(/\.html$/, "").replace(/\/index$/, "/");
662
+ if (hasTrailSlash) {
663
+ normalizedRoutePath = addTrailingSlash(normalizedRoutePath);
613
664
  }
614
- }
615
- function i18nVMPlugin(context) {
616
- const { config } = context;
617
- const i18nData = getI18nData(config);
618
665
  return {
619
- ["virtual-i18n-text" /* I18nText */]: `export default ${JSON.stringify(i18nData, null, 2)}`
620
- };
621
- }
622
-
623
- // src/node/runtimeModule/siteData/normalizeThemeConfig.ts
624
- function normalizeThemeConfig(docConfig, pages = []) {
625
- const {
626
- locales: siteLocales,
627
- base = "",
628
- lang,
629
- replaceRules = [],
630
- multiVersion
631
- } = docConfig;
632
- const { versions = [] } = multiVersion || {};
633
- const hasMultiVersion = versions.length > 0;
634
- docConfig.themeConfig = docConfig.themeConfig || {};
635
- const { themeConfig } = docConfig;
636
- const locales = siteLocales ?? (themeConfig?.locales || []);
637
- const i18nTextData = getI18nData(docConfig);
638
- const normalizeLinkPrefix = (link = "", currentLang = "") => {
639
- const normalizedLink = slash2(link);
640
- if (!currentLang || !link || withoutBase(normalizedLink, base).startsWith(`/${currentLang}`) || isExternalUrl(normalizedLink) || // In multi version case, we have got the complete link prefix in `plugin-auto-nav-sidebar` and does not need to add the lang prefix
641
- hasMultiVersion) {
642
- return normalizedLink;
643
- }
644
- return lang === currentLang ? normalizedLink : `/${currentLang}${addLeadingSlash(normalizedLink)}`;
645
- };
646
- const getI18nText = (key = "", currentLang = "") => {
647
- const text = i18nTextData[key]?.[currentLang];
648
- return text || key;
666
+ routePath: withBase(normalizedRoutePath, base),
667
+ lang: langPart || lang,
668
+ version: versionPart || version
649
669
  };
650
- const normalizeSidebar = (sidebar, currentLang = "") => {
651
- const normalizedSidebar = {};
652
- if (!sidebar) {
653
- return {};
654
- }
655
- const normalizeSidebarItem = (item) => {
656
- if (typeof item === "object" && "dividerType" in item) {
657
- return item;
658
- }
659
- if (typeof item === "object" && "sectionHeaderText" in item) {
660
- item.sectionHeaderText = applyReplaceRules(
661
- getI18nText(item.sectionHeaderText, currentLang),
662
- replaceRules
663
- );
664
- return item;
670
+ };
671
+ var _scanDir, _defaultLang, _defaultVersion, _extensions, _langs, _versions, _include, _exclude, _base, _tempDir, _pluginDriver, _writeTempFile, writeTempFile_fn, _generateRouteInfo, generateRouteInfo_fn;
672
+ var RouteService = class {
673
+ constructor(scanDir, userConfig, tempDir, pluginDriver) {
674
+ __privateAdd(this, _writeTempFile);
675
+ __privateAdd(this, _generateRouteInfo);
676
+ __publicField(this, "routeData", /* @__PURE__ */ new Map());
677
+ __privateAdd(this, _scanDir, void 0);
678
+ __privateAdd(this, _defaultLang, void 0);
679
+ __privateAdd(this, _defaultVersion, "");
680
+ __privateAdd(this, _extensions, []);
681
+ __privateAdd(this, _langs, []);
682
+ __privateAdd(this, _versions, []);
683
+ __privateAdd(this, _include, []);
684
+ __privateAdd(this, _exclude, []);
685
+ __privateAdd(this, _base, "");
686
+ __privateAdd(this, _tempDir, "");
687
+ __privateAdd(this, _pluginDriver, void 0);
688
+ const routeOptions = userConfig?.route || {};
689
+ __privateSet(this, _scanDir, scanDir);
690
+ __privateSet(this, _extensions, routeOptions.extensions || DEFAULT_PAGE_EXTENSIONS);
691
+ __privateSet(this, _include, routeOptions.include || []);
692
+ __privateSet(this, _exclude, routeOptions.exclude || []);
693
+ __privateSet(this, _defaultLang, userConfig?.lang || "");
694
+ __privateSet(this, _langs, (userConfig?.locales ?? userConfig?.themeConfig?.locales ?? []).map((item) => item.lang));
695
+ __privateSet(this, _base, userConfig?.base || "");
696
+ __privateSet(this, _tempDir, tempDir);
697
+ __privateSet(this, _pluginDriver, pluginDriver);
698
+ if (userConfig.multiVersion) {
699
+ __privateSet(this, _defaultVersion, userConfig.multiVersion.default || "");
700
+ __privateSet(this, _versions, userConfig.multiVersion.versions || []);
701
+ }
702
+ }
703
+ async init() {
704
+ const globby = (await import(
705
+ // @ts-expect-error
706
+ // eslint-disable-next-line node/file-extension-in-import
707
+ "../compiled/globby/index.js"
708
+ )).default;
709
+ const files = (await globby([`**/*.{${__privateGet(this, _extensions).join(",")}}`, ...__privateGet(this, _include)], {
710
+ cwd: __privateGet(this, _scanDir),
711
+ absolute: true,
712
+ ignore: [
713
+ ...__privateGet(this, _exclude),
714
+ "**/node_modules/**",
715
+ "**/.eslintrc.js",
716
+ "**/.nx-cache/**",
717
+ `./${PUBLIC_DIR}/**`
718
+ ]
719
+ })).sort();
720
+ files.forEach((filePath) => {
721
+ const fileRelativePath = normalizePath(
722
+ path5.relative(__privateGet(this, _scanDir), filePath)
723
+ );
724
+ const { routePath, lang, version } = this.normalizeRoutePath(fileRelativePath);
725
+ const absolutePath = path5.join(__privateGet(this, _scanDir), fileRelativePath);
726
+ const routeInfo = {
727
+ routePath,
728
+ absolutePath: normalizePath(absolutePath),
729
+ relativePath: fileRelativePath,
730
+ pageName: getPageKey(fileRelativePath),
731
+ lang,
732
+ version
733
+ };
734
+ this.addRoute(routeInfo);
735
+ });
736
+ const externalPages = await __privateGet(this, _pluginDriver).addPages();
737
+ await Promise.all(
738
+ externalPages.map(async (route, index) => {
739
+ const { routePath, content, filepath } = route;
740
+ if (filepath) {
741
+ const routeInfo = __privateMethod(this, _generateRouteInfo, generateRouteInfo_fn).call(this, routePath, filepath);
742
+ this.addRoute(routeInfo);
743
+ return;
744
+ }
745
+ if (content) {
746
+ const filepath2 = await __privateMethod(this, _writeTempFile, writeTempFile_fn).call(this, index, content);
747
+ const routeInfo = __privateMethod(this, _generateRouteInfo, generateRouteInfo_fn).call(this, routePath, filepath2);
748
+ this.addRoute(routeInfo);
749
+ }
750
+ })
751
+ );
752
+ await __privateGet(this, _pluginDriver).routeGenerated(this.getRoutes());
753
+ }
754
+ addRoute(routeInfo) {
755
+ const { routePath, absolutePath } = routeInfo;
756
+ if (this.routeData.has(routePath)) {
757
+ const preRouteExtIndex = __privateGet(this, _extensions).indexOf(
758
+ path5.extname(this.routeData.get(routePath).absolutePath).slice(1)
759
+ );
760
+ const currRouteExtIndex = __privateGet(this, _extensions).indexOf(
761
+ path5.extname(absolutePath).slice(1)
762
+ );
763
+ if (currRouteExtIndex !== -1 && (currRouteExtIndex < preRouteExtIndex || preRouteExtIndex === -1)) {
764
+ this.routeData.set(routePath, routeInfo);
765
+ }
766
+ } else {
767
+ this.routeData.set(routePath, routeInfo);
768
+ }
769
+ }
770
+ removeRoute(filePath) {
771
+ const fileRelativePath = path5.relative(__privateGet(this, _scanDir), filePath);
772
+ const { routePath } = this.normalizeRoutePath(fileRelativePath);
773
+ this.routeData.delete(routePath);
774
+ }
775
+ getRoutes() {
776
+ return Array.from(this.routeData.values());
777
+ }
778
+ isExistRoute(routePath) {
779
+ const { routePath: normalizedRoute } = this.normalizeRoutePath(routePath);
780
+ return this.routeData.get(normalizedRoute);
781
+ }
782
+ isEmpty() {
783
+ return this.routeData.size === 0;
784
+ }
785
+ generateRoutesCode(isStaticImport = false) {
786
+ return this.generateRoutesCodeByRouteMeta(this.getRoutes(), isStaticImport);
787
+ }
788
+ generateRoutesCodeByRouteMeta(routeMeta, isStaticImport) {
789
+ return `
790
+ import React from 'react';
791
+ import { lazyWithPreload } from "react-lazy-with-preload";
792
+ ${routeMeta.map((route, index) => {
793
+ return isStaticImport ? `import * as Route${index} from '${route.absolutePath}';` : `const Route${index} = lazyWithPreload(() => import('${route.absolutePath}'))`;
794
+ }).join("\n")}
795
+ export const routes = [
796
+ ${routeMeta.map((route, index) => {
797
+ const preload = isStaticImport ? `() => Route${index}` : `async () => {
798
+ await Route${index}.preload();
799
+ return import("${route.absolutePath}");
800
+ }`;
801
+ const component = isStaticImport ? `Route${index}.default` : `Route${index}`;
802
+ return `{ path: '${route.routePath}', element: React.createElement(${component}), filePath: '${route.relativePath}', preload: ${preload}, lang: '${route.lang}', version: '${route.version}' }`;
803
+ }).join(",\n")}
804
+ ];
805
+ `;
806
+ }
807
+ normalizeRoutePath(routePath) {
808
+ return normalizeRoutePath(
809
+ routePath,
810
+ __privateGet(this, _base),
811
+ __privateGet(this, _defaultLang),
812
+ __privateGet(this, _defaultVersion),
813
+ __privateGet(this, _langs),
814
+ __privateGet(this, _versions),
815
+ __privateGet(this, _extensions)
816
+ );
817
+ }
818
+ };
819
+ _scanDir = new WeakMap();
820
+ _defaultLang = new WeakMap();
821
+ _defaultVersion = new WeakMap();
822
+ _extensions = new WeakMap();
823
+ _langs = new WeakMap();
824
+ _versions = new WeakMap();
825
+ _include = new WeakMap();
826
+ _exclude = new WeakMap();
827
+ _base = new WeakMap();
828
+ _tempDir = new WeakMap();
829
+ _pluginDriver = new WeakMap();
830
+ _writeTempFile = new WeakSet();
831
+ writeTempFile_fn = async function(index, content) {
832
+ const tempFilePath = path5.join(__privateGet(this, _tempDir), `temp-${index}.mdx`);
833
+ await fs3.writeFile(tempFilePath, content);
834
+ return tempFilePath;
835
+ };
836
+ _generateRouteInfo = new WeakSet();
837
+ generateRouteInfo_fn = function(routePath, filepath) {
838
+ const {
839
+ routePath: normalizedPath,
840
+ lang,
841
+ version
842
+ } = this.normalizeRoutePath(routePath);
843
+ return {
844
+ routePath: normalizedPath,
845
+ absolutePath: normalizePath(filepath),
846
+ relativePath: normalizePath(path5.relative(__privateGet(this, _scanDir), filepath)),
847
+ pageName: getPageKey(routePath),
848
+ lang,
849
+ version
850
+ };
851
+ };
852
+
853
+ // src/node/route/init.ts
854
+ var routeService = null;
855
+ async function initRouteService(options) {
856
+ const { scanDir, config, runtimeTempDir, pluginDriver } = options;
857
+ routeService = new RouteService(
858
+ scanDir,
859
+ config,
860
+ runtimeTempDir,
861
+ pluginDriver
862
+ );
863
+ await routeService.init();
864
+ return routeService;
865
+ }
866
+
867
+ // src/node/runtimeModule/index.ts
868
+ import { RspackVirtualModulePlugin } from "rspack-plugin-virtual-module";
869
+
870
+ // src/node/runtimeModule/globalStyles.ts
871
+ import fs4 from "@rspress/shared/fs-extra";
872
+ async function globalStylesVMPlugin(context) {
873
+ const { config, pluginDriver } = context;
874
+ const globalStylesByPlugins = pluginDriver.globalStyles();
875
+ if (config.globalStyles) {
876
+ const source = config.globalStyles;
877
+ const styleContent = await fs4.readFile(source, "utf-8");
878
+ const patchedStyleContent = styleContent.replace(/--modern-/g, "--rp-").replace(/\.modern-doc/g, ".rspress").replace(/\.modern-/g, ".rspress-");
879
+ await fs4.writeFile(source, patchedStyleContent, "utf-8");
880
+ }
881
+ const moduleContent = (await Promise.all(
882
+ [config?.globalStyles || "", ...globalStylesByPlugins].filter((source) => source.length > 0).map(async (source) => {
883
+ return `import ${JSON.stringify(source)};`;
884
+ })
885
+ )).join("");
886
+ return {
887
+ ["virtual-global-styles" /* GlobalStyles */]: moduleContent
888
+ };
889
+ }
890
+
891
+ // src/node/runtimeModule/globalUIComponents.ts
892
+ async function globalUIComponentsVMPlugin(context) {
893
+ const { config, pluginDriver } = context;
894
+ let index = 0;
895
+ const globalUIComponentsByPlugins = pluginDriver.globalUIComponents();
896
+ const globalComponents = [
897
+ ...config?.globalUIComponents || [],
898
+ ...globalUIComponentsByPlugins
899
+ ];
900
+ const moduleContent = globalComponents.map((source) => {
901
+ const name = `Comp_${index}`;
902
+ if (Array.isArray(source)) {
903
+ return `import ${name} from ${JSON.stringify(source[0])};
904
+ const Props_${index++} = ${JSON.stringify(source[1])};
905
+ `;
906
+ }
907
+ index++;
908
+ return `import ${name} from ${JSON.stringify(source)};
909
+ `;
910
+ }).concat(
911
+ `export default [${Array.from({ length: index }, (_, i) => {
912
+ if (Array.isArray(globalComponents[i])) {
913
+ return `[${`Comp_${i}`}, Props_${i}]`;
914
+ }
915
+ return `Comp_${i}`;
916
+ }).join(", ")}];`
917
+ ).join("");
918
+ return {
919
+ ["virtual-global-components" /* GlobalComponents */]: moduleContent
920
+ };
921
+ }
922
+
923
+ // src/node/runtimeModule/i18n.ts
924
+ import { join } from "path";
925
+ var DEFAULT_I18N_SOURCE = join(process.cwd(), "i18n.json");
926
+ function getI18nData(docConfig) {
927
+ const { i18nSourcePath = DEFAULT_I18N_SOURCE } = docConfig;
928
+ try {
929
+ delete __require.cache[i18nSourcePath];
930
+ const i18nSource = __require(i18nSourcePath);
931
+ return i18nSource;
932
+ } catch (e) {
933
+ return {};
934
+ }
935
+ }
936
+ function i18nVMPlugin(context) {
937
+ const { config } = context;
938
+ const i18nData = getI18nData(config);
939
+ return {
940
+ ["virtual-i18n-text" /* I18nText */]: `export default ${JSON.stringify(i18nData, null, 2)}`
941
+ };
942
+ }
943
+
944
+ // src/node/runtimeModule/routeData.ts
945
+ async function routeVMPlugin(context) {
946
+ const { routeService: routeService2, isSSR } = context;
947
+ if (!isSSR) {
948
+ return {
949
+ ["virtual-routes" /* RouteForClient */]: routeService2.generateRoutesCode(false)
950
+ };
951
+ }
952
+ return {
953
+ ["virtual-routes" /* RouteForClient */]: routeService2.generateRoutesCode(false),
954
+ ["virtual-routes-ssr" /* RouteForSSR */]: routeService2.generateRoutesCode(true)
955
+ };
956
+ }
957
+
958
+ // src/node/runtimeModule/searchHooks.ts
959
+ import path6 from "path";
960
+ async function searchHookVMPlugin(context) {
961
+ const { config } = context;
962
+ let content = "export const onSearch = () => {};";
963
+ let extname = "";
964
+ if (typeof config.search === "object" && typeof config.search.searchHooks === "string") {
965
+ content = `export * from '${config.search.searchHooks}'`;
966
+ extname = path6.extname(config.search.searchHooks);
967
+ }
968
+ return {
969
+ [`${"virtual-search-hooks" /* SearchHooks */}${extname}`]: content
970
+ };
971
+ }
972
+
973
+ // src/node/runtimeModule/siteData/index.ts
974
+ import path8 from "path";
975
+ import { SEARCH_INDEX_NAME } from "@rspress/shared";
976
+ import fs6 from "@rspress/shared/fs-extra";
977
+ import { groupBy } from "lodash-es";
978
+
979
+ // src/node/runtimeModule/siteData/extractPageData.ts
980
+ import path7 from "path";
981
+ import { compile } from "@rspress/mdx-rs";
982
+ import {
983
+ MDX_REGEXP as MDX_REGEXP2
984
+ } from "@rspress/shared";
985
+ import fs5 from "@rspress/shared/fs-extra";
986
+ import { loadFrontMatter } from "@rspress/shared/node-utils";
987
+ import { htmlToText } from "html-to-text";
988
+ function applyReplaceRulesToNestedObject(obj, replaceRules) {
989
+ for (const key in obj) {
990
+ if (typeof obj[key] === "string") {
991
+ obj[key] = applyReplaceRules(obj[key], replaceRules);
992
+ } else if (typeof obj[key] === "object") {
993
+ obj[key] = applyReplaceRulesToNestedObject(obj[key], replaceRules);
994
+ }
995
+ }
996
+ return obj;
997
+ }
998
+ async function extractPageData(replaceRules, alias, domain, root, routeService2, highlighterLangs) {
999
+ const pageData = await Promise.all(
1000
+ routeService2.getRoutes().map(async (route, index) => {
1001
+ const defaultIndexInfo = {
1002
+ id: index,
1003
+ title: "",
1004
+ content: "",
1005
+ _html: "",
1006
+ routePath: route.routePath,
1007
+ lang: route.lang,
1008
+ toc: [],
1009
+ domain,
1010
+ frontmatter: {},
1011
+ version: route.version,
1012
+ _filepath: route.absolutePath,
1013
+ _relativePath: path7.relative(root, route.absolutePath)
1014
+ };
1015
+ if (!MDX_REGEXP2.test(route.absolutePath)) {
1016
+ return defaultIndexInfo;
1017
+ }
1018
+ let content = await fs5.readFile(route.absolutePath, "utf8");
1019
+ const { frontmatter, content: strippedFrontMatter } = loadFrontMatter(
1020
+ content,
1021
+ route.absolutePath,
1022
+ root
1023
+ );
1024
+ applyReplaceRulesToNestedObject(frontmatter, replaceRules);
1025
+ const { flattenContent } = await flattenMdxContent(
1026
+ applyReplaceRules(strippedFrontMatter, replaceRules),
1027
+ route.absolutePath,
1028
+ alias
1029
+ );
1030
+ content = flattenContent.replace(importStatementRegex, "");
1031
+ const {
1032
+ html,
1033
+ title,
1034
+ toc: rawToc,
1035
+ languages
1036
+ } = await compile({
1037
+ value: content,
1038
+ filepath: route.absolutePath,
1039
+ development: process.env.NODE_ENV !== "production",
1040
+ root
1041
+ });
1042
+ if (!title?.length && !frontmatter && !frontmatter.title?.length) {
1043
+ return null;
1044
+ }
1045
+ content = htmlToText(String(html), {
1046
+ wordwrap: 80,
1047
+ selectors: [
1048
+ {
1049
+ selector: "a",
1050
+ options: {
1051
+ ignoreHref: true
1052
+ }
1053
+ },
1054
+ {
1055
+ selector: "img",
1056
+ format: "skip"
1057
+ },
1058
+ {
1059
+ // Skip code blocks
1060
+ selector: "pre > code",
1061
+ format: "skip"
1062
+ },
1063
+ ...["h1", "h2", "h3", "h4", "h5", "h6"].map((tag) => ({
1064
+ selector: tag,
1065
+ options: {
1066
+ uppercase: false
1067
+ }
1068
+ }))
1069
+ ],
1070
+ tables: true,
1071
+ longWordSplit: {
1072
+ forceWrapOnLimit: true
1073
+ }
1074
+ });
1075
+ if (content.startsWith(title)) {
1076
+ content = content.slice(title.length);
1077
+ }
1078
+ languages.forEach((lang) => highlighterLangs.add(lang));
1079
+ const toc = rawToc.map((item) => {
1080
+ const match = item.id.match(/-(\d+)$/);
1081
+ let position = -1;
1082
+ if (match) {
1083
+ for (let i = 0; i < Number(match[1]); i++) {
1084
+ position = content.indexOf(`
1085
+ ${item.text}#
1086
+
1087
+ `, position + 1);
1088
+ if (position === -1) {
1089
+ break;
1090
+ }
1091
+ }
1092
+ }
1093
+ return {
1094
+ ...item,
1095
+ charIndex: content.indexOf(`
1096
+ ${item.text}#
1097
+
1098
+ `, position + 1)
1099
+ };
1100
+ });
1101
+ return {
1102
+ ...defaultIndexInfo,
1103
+ title: frontmatter.title || title,
1104
+ toc,
1105
+ // Stripped frontmatter content
1106
+ content,
1107
+ _html: html,
1108
+ frontmatter: {
1109
+ ...frontmatter,
1110
+ __content: void 0
1111
+ }
1112
+ };
1113
+ })
1114
+ );
1115
+ return pageData.filter(Boolean);
1116
+ }
1117
+
1118
+ // src/node/runtimeModule/siteData/highlightLanguages.ts
1119
+ import { DEFAULT_HIGHLIGHT_LANGUAGES } from "@rspress/shared";
1120
+ import chalk from "@rspress/shared/chalk";
1121
+ var supportedLanguages;
1122
+ function handleHighlightLanguages(highlightLanguages, defaultLanguages) {
1123
+ const aliases = {};
1124
+ if (highlightLanguages.size) {
1125
+ if (!supportedLanguages) {
1126
+ const langs = __require("react-syntax-highlighter/dist/cjs/languages/prism/supported-languages").default;
1127
+ supportedLanguages = new Set(langs);
1128
+ }
1129
+ let useDeprecatedTypeWarning = true;
1130
+ const names = {};
1131
+ [...DEFAULT_HIGHLIGHT_LANGUAGES, ...defaultLanguages].forEach((lang) => {
1132
+ if (Array.isArray(lang)) {
1133
+ const [alias, name] = lang;
1134
+ names[alias] = name;
1135
+ } else if (useDeprecatedTypeWarning) {
1136
+ console.log(
1137
+ `${chalk.yellowBright(
1138
+ "warning"
1139
+ )} Automatic import is supported. \`highlightLanguages\` is now used only as alias, and string types will be ignored.
1140
+ `
1141
+ );
1142
+ useDeprecatedTypeWarning = false;
1143
+ }
1144
+ });
1145
+ [...highlightLanguages.values()].forEach((lang) => {
1146
+ const name = names[lang];
1147
+ if (name && supportedLanguages.has(name)) {
1148
+ const temp = aliases[name] || (aliases[name] = []);
1149
+ if (!temp.includes(lang)) {
1150
+ temp.push(lang);
1151
+ }
1152
+ highlightLanguages.delete(lang);
1153
+ highlightLanguages.add(name);
1154
+ return;
1155
+ }
1156
+ if (!supportedLanguages.has(lang)) {
1157
+ highlightLanguages.delete(lang);
1158
+ }
1159
+ });
1160
+ }
1161
+ return aliases;
1162
+ }
1163
+
1164
+ // src/node/runtimeModule/siteData/normalizeThemeConfig.ts
1165
+ import {
1166
+ addLeadingSlash as addLeadingSlash2,
1167
+ isExternalUrl,
1168
+ slash as slash2,
1169
+ withBase as withBase2,
1170
+ withoutBase
1171
+ } from "@rspress/shared";
1172
+ function normalizeThemeConfig(docConfig, pages = []) {
1173
+ const {
1174
+ locales: siteLocales,
1175
+ base = "",
1176
+ lang,
1177
+ replaceRules = [],
1178
+ multiVersion
1179
+ } = docConfig;
1180
+ const { versions = [] } = multiVersion || {};
1181
+ const hasMultiVersion = versions.length > 0;
1182
+ docConfig.themeConfig = docConfig.themeConfig || {};
1183
+ const { themeConfig } = docConfig;
1184
+ const locales = siteLocales ?? (themeConfig?.locales || []);
1185
+ const i18nTextData = getI18nData(docConfig);
1186
+ const normalizeLinkPrefix = (link = "", currentLang = "") => {
1187
+ const normalizedLink = slash2(link);
1188
+ if (!currentLang || !link || withoutBase(normalizedLink, base).startsWith(`/${currentLang}`) || isExternalUrl(normalizedLink) || // In multi version case, we have got the complete link prefix in `plugin-auto-nav-sidebar` and does not need to add the lang prefix
1189
+ hasMultiVersion) {
1190
+ return normalizedLink;
1191
+ }
1192
+ return lang === currentLang ? normalizedLink : `/${currentLang}${addLeadingSlash2(normalizedLink)}`;
1193
+ };
1194
+ const getI18nText = (key = "", currentLang = "") => {
1195
+ const text = i18nTextData[key]?.[currentLang];
1196
+ return text || key;
1197
+ };
1198
+ const normalizeSidebar = (sidebar, currentLang = "") => {
1199
+ const normalizedSidebar = {};
1200
+ if (!sidebar) {
1201
+ return {};
1202
+ }
1203
+ const normalizeSidebarItem = (item) => {
1204
+ if (typeof item === "object" && "dividerType" in item) {
1205
+ return item;
1206
+ }
1207
+ if (typeof item === "object" && "sectionHeaderText" in item) {
1208
+ item.sectionHeaderText = applyReplaceRules(
1209
+ getI18nText(item.sectionHeaderText, currentLang),
1210
+ replaceRules
1211
+ );
1212
+ return item;
665
1213
  }
666
1214
  if (typeof item === "object" && "items" in item) {
667
1215
  return {
@@ -682,7 +1230,7 @@ function normalizeThemeConfig(docConfig, pages = []) {
682
1230
  if (typeof item === "string") {
683
1231
  const normalizedItem = normalizeLinkPrefix(item, currentLang);
684
1232
  const page = pages.find(
685
- (page2) => page2.routePath === withBase(normalizedItem, base)
1233
+ (page2) => page2.routePath === withBase2(normalizedItem, base)
686
1234
  );
687
1235
  return {
688
1236
  text: applyReplaceRules(page?.title || "", replaceRules),
@@ -777,52 +1325,6 @@ function normalizeThemeConfig(docConfig, pages = []) {
777
1325
  return themeConfig;
778
1326
  }
779
1327
 
780
- // src/node/runtimeModule/siteData/highlightLanguages.ts
781
- import chalk from "@rspress/shared/chalk";
782
- import { DEFAULT_HIGHLIGHT_LANGUAGES } from "@rspress/shared";
783
- var supportedLanguages;
784
- function handleHighlightLanguages(highlightLanguages, defaultLanguages) {
785
- const aliases = {};
786
- if (highlightLanguages.size) {
787
- if (!supportedLanguages) {
788
- const langs = __require("react-syntax-highlighter/dist/cjs/languages/prism/supported-languages").default;
789
- supportedLanguages = new Set(langs);
790
- }
791
- let useDeprecatedTypeWarning = true;
792
- const names = {};
793
- [...DEFAULT_HIGHLIGHT_LANGUAGES, ...defaultLanguages].forEach((lang) => {
794
- if (Array.isArray(lang)) {
795
- const [alias, name] = lang;
796
- names[alias] = name;
797
- } else if (useDeprecatedTypeWarning) {
798
- console.log(
799
- `${chalk.yellowBright(
800
- "warning"
801
- )} Automatic import is supported. \`highlightLanguages\` is now used only as alias, and string types will be ignored.
802
- `
803
- );
804
- useDeprecatedTypeWarning = false;
805
- }
806
- });
807
- [...highlightLanguages.values()].forEach((lang) => {
808
- const name = names[lang];
809
- if (name && supportedLanguages.has(name)) {
810
- const temp = aliases[name] || (aliases[name] = []);
811
- if (!temp.includes(lang)) {
812
- temp.push(lang);
813
- }
814
- highlightLanguages.delete(lang);
815
- highlightLanguages.add(name);
816
- return;
817
- }
818
- if (!supportedLanguages.has(lang)) {
819
- highlightLanguages.delete(lang);
820
- }
821
- });
822
- }
823
- return aliases;
824
- }
825
-
826
1328
  // src/node/runtimeModule/siteData/index.ts
827
1329
  function deletePrivateField(obj) {
828
1330
  if (typeof obj !== "object" || obj === null) {
@@ -876,9 +1378,9 @@ async function siteDataVMPlugin(context) {
876
1378
  const [version, lang] = group.split("###");
877
1379
  const indexVersion = version ? `.${version.replace(".", "_")}` : "";
878
1380
  const indexLang = lang ? `.${lang}` : "";
879
- await fs4.ensureDir(TEMP_DIR);
880
- await fs4.writeFile(
881
- path6.join(
1381
+ await fs6.ensureDir(TEMP_DIR);
1382
+ await fs6.writeFile(
1383
+ path8.join(
882
1384
  TEMP_DIR,
883
1385
  `${SEARCH_INDEX_NAME}${indexVersion}${indexLang}.${indexHash}.json`
884
1386
  ),
@@ -912,113 +1414,45 @@ async function siteDataVMPlugin(context) {
912
1414
  }),
913
1415
  markdown: {
914
1416
  showLineNumbers: userConfig?.markdown?.showLineNumbers ?? false,
915
- defaultWrapCode: userConfig?.markdown?.defaultWrapCode ?? false,
916
- codeHighlighter: userConfig?.markdown?.codeHighlighter || "prism"
917
- }
918
- };
919
- const { highlightLanguages: defaultLanguages = [] } = config.markdown || {};
920
- if (siteData.pages[0]?.extraHighlightLanguages?.length) {
921
- siteData.pages[0].extraHighlightLanguages.forEach(
922
- (lang) => highlightLanguages.add(lang)
923
- );
924
- }
925
- const aliases = handleHighlightLanguages(
926
- highlightLanguages,
927
- defaultLanguages
928
- );
929
- const sortedAliases = Object.fromEntries(Object.entries(aliases).sort());
930
- const sortedHighlightLanguages = Array.from(highlightLanguages).sort();
931
- return {
932
- [`${"virtual-site-data" /* SiteData */}.mjs`]: `export default ${JSON.stringify(
933
- siteData,
934
- null,
935
- 2
936
- )}`,
937
- ["virtual-search-index-hash" /* SearchIndexHash */]: `export default ${JSON.stringify(
938
- indexHashByGroup,
939
- null,
940
- 2
941
- )}`,
942
- ["virtual-prism-languages" /* PrismLanguages */]: `export const aliases = ${JSON.stringify(
943
- sortedAliases,
944
- null,
945
- 2
946
- )};
947
- export const languages = {
948
- ${sortedHighlightLanguages.map((lang) => {
949
- return `"${lang}": require(
950
- "react-syntax-highlighter/dist/cjs/languages/prism/${lang}"
951
- ).default`;
952
- })}
953
- }`
954
- };
955
- }
956
-
957
- // src/node/runtimeModule/globalUIComponents.ts
958
- async function globalUIComponentsVMPlugin(context) {
959
- const { config, pluginDriver } = context;
960
- let index = 0;
961
- const globalUIComponentsByPlugins = pluginDriver.globalUIComponents();
962
- const globalComponents = [
963
- ...config?.globalUIComponents || [],
964
- ...globalUIComponentsByPlugins
965
- ];
966
- const moduleContent = globalComponents.map((source) => {
967
- const name = `Comp_${index}`;
968
- if (Array.isArray(source)) {
969
- return `import ${name} from ${JSON.stringify(source[0])};
970
- const Props_${index++} = ${JSON.stringify(source[1])};
971
- `;
972
- }
973
- index++;
974
- return `import ${name} from ${JSON.stringify(source)};
975
- `;
976
- }).concat(
977
- `export default [${Array.from({ length: index }, (_, i) => {
978
- if (Array.isArray(globalComponents[i])) {
979
- return `[${`Comp_${i}`}, Props_${i}]`;
980
- }
981
- return `Comp_${i}`;
982
- }).join(", ")}];`
983
- ).join("");
984
- return {
985
- ["virtual-global-components" /* GlobalComponents */]: moduleContent
986
- };
987
- }
988
-
989
- // src/node/runtimeModule/globalStyles.ts
990
- import fs5 from "@rspress/shared/fs-extra";
991
- async function globalStylesVMPlugin(context) {
992
- const { config, pluginDriver } = context;
993
- const globalStylesByPlugins = pluginDriver.globalStyles();
994
- if (config.globalStyles) {
995
- const source = config.globalStyles;
996
- const styleContent = await fs5.readFile(source, "utf-8");
997
- const patchedStyleContent = styleContent.replace(/--modern-/g, "--rp-").replace(/\.modern-doc/g, ".rspress").replace(/\.modern-/g, ".rspress-");
998
- await fs5.writeFile(source, patchedStyleContent, "utf-8");
999
- }
1000
- const moduleContent = (await Promise.all(
1001
- [config?.globalStyles || "", ...globalStylesByPlugins].filter((source) => source.length > 0).map(async (source) => {
1002
- return `import ${JSON.stringify(source)};`;
1003
- })
1004
- )).join("");
1005
- return {
1006
- ["virtual-global-styles" /* GlobalStyles */]: moduleContent
1417
+ defaultWrapCode: userConfig?.markdown?.defaultWrapCode ?? false,
1418
+ codeHighlighter: userConfig?.markdown?.codeHighlighter || "prism"
1419
+ }
1007
1420
  };
1008
- }
1009
-
1010
- // src/node/runtimeModule/searchHooks.ts
1011
- import path7 from "path";
1012
- async function searchHookVMPlugin(context) {
1013
- const { config } = context;
1014
- let content = "export const onSearch = () => {};";
1015
- let extname = "";
1016
- if (typeof config.search === "object" && typeof config.search.searchHooks === "string") {
1017
- content = `export * from '${config.search.searchHooks}'`;
1018
- extname = path7.extname(config.search.searchHooks);
1421
+ const { highlightLanguages: defaultLanguages = [] } = config.markdown || {};
1422
+ if (siteData.pages[0]?.extraHighlightLanguages?.length) {
1423
+ siteData.pages[0].extraHighlightLanguages.forEach(
1424
+ (lang) => highlightLanguages.add(lang)
1425
+ );
1019
1426
  }
1427
+ const aliases = handleHighlightLanguages(
1428
+ highlightLanguages,
1429
+ defaultLanguages
1430
+ );
1431
+ const sortedAliases = Object.fromEntries(Object.entries(aliases).sort());
1432
+ const sortedHighlightLanguages = Array.from(highlightLanguages).sort();
1020
1433
  return {
1021
- [`${"virtual-search-hooks" /* SearchHooks */}${extname}`]: content
1434
+ [`${"virtual-site-data" /* SiteData */}.mjs`]: `export default ${JSON.stringify(
1435
+ siteData,
1436
+ null,
1437
+ 2
1438
+ )}`,
1439
+ ["virtual-search-index-hash" /* SearchIndexHash */]: `export default ${JSON.stringify(
1440
+ indexHashByGroup,
1441
+ null,
1442
+ 2
1443
+ )}`,
1444
+ ["virtual-prism-languages" /* PrismLanguages */]: `export const aliases = ${JSON.stringify(
1445
+ sortedAliases,
1446
+ null,
1447
+ 2
1448
+ )};
1449
+ export const languages = {
1450
+ ${sortedHighlightLanguages.map((lang) => {
1451
+ return `"${lang}": require(
1452
+ "react-syntax-highlighter/dist/cjs/languages/prism/${lang}"
1453
+ ).default`;
1454
+ })}
1455
+ }`
1022
1456
  };
1023
1457
  }
1024
1458
 
@@ -1088,33 +1522,33 @@ function rsbuildPluginDocVM(factoryContext) {
1088
1522
  }
1089
1523
 
1090
1524
  // src/node/searchIndex.ts
1091
- import path8, { join as join2 } from "path";
1092
- import fs6 from "@rspress/shared/fs-extra";
1525
+ import path9, { join as join2 } from "path";
1526
+ import { SEARCH_INDEX_NAME as SEARCH_INDEX_NAME2, isSCM } from "@rspress/shared";
1093
1527
  import chalk2 from "@rspress/shared/chalk";
1094
- import { isSCM, SEARCH_INDEX_NAME as SEARCH_INDEX_NAME2 } from "@rspress/shared";
1528
+ import fs7 from "@rspress/shared/fs-extra";
1095
1529
  import { logger as logger2 } from "@rspress/shared/logger";
1096
1530
  async function writeSearchIndex(config) {
1097
1531
  if (config?.search === false) {
1098
1532
  return;
1099
1533
  }
1100
1534
  const cwd = process.cwd();
1101
- const searchIndexFiles = await fs6.readdir(TEMP_DIR);
1535
+ const searchIndexFiles = await fs7.readdir(TEMP_DIR);
1102
1536
  const outDir = config?.outDir ?? join2(cwd, OUTPUT_DIR);
1103
1537
  let searchIndexData = "[]";
1104
- let scaning = false;
1538
+ let scanning = false;
1105
1539
  for (const searchIndexFile of searchIndexFiles) {
1106
1540
  if (!searchIndexFile.includes(SEARCH_INDEX_NAME2) || !searchIndexFile.endsWith(".json")) {
1107
1541
  continue;
1108
1542
  }
1109
1543
  const source = join2(TEMP_DIR, searchIndexFile);
1110
1544
  const target = join2(outDir, "static", searchIndexFile);
1111
- const searchIndex = await fs6.readFile(
1545
+ const searchIndex = await fs7.readFile(
1112
1546
  join2(TEMP_DIR, searchIndexFile),
1113
1547
  "utf-8"
1114
1548
  );
1115
- searchIndexData = `${searchIndexData.slice(0, -1)}${scaning ? "," : ""}${searchIndex.slice(1)}`;
1116
- await fs6.move(source, target, { overwrite: true });
1117
- scaning = true;
1549
+ searchIndexData = `${searchIndexData.slice(0, -1)}${scanning ? "," : ""}${searchIndex.slice(1)}`;
1550
+ await fs7.move(source, target, { overwrite: true });
1551
+ scanning = true;
1118
1552
  }
1119
1553
  if (isProduction() && isSCM() && config?.search?.mode === "remote") {
1120
1554
  const { apiUrl, indexName } = config.search;
@@ -1135,271 +1569,29 @@ async function writeSearchIndex(config) {
1135
1569
  `[doc-tools] Upload search index \`${indexName}\` failed:
1136
1570
  ${e}`
1137
1571
  )
1138
- );
1139
- }
1140
- }
1141
- }
1142
- function serveSearchIndexMiddleware(config) {
1143
- return (req, res, next) => {
1144
- const searchIndexRequestMatch = `/${SEARCH_INDEX_NAME2}.`;
1145
- if (req.url?.includes(searchIndexRequestMatch)) {
1146
- res.setHeader("Content-Type", "application/json");
1147
- const searchIndexFile = req.url?.split("/").pop();
1148
- fs6.createReadStream(
1149
- path8.join(
1150
- process.cwd(),
1151
- config?.outDir || OUTPUT_DIR,
1152
- "static",
1153
- searchIndexFile
1154
- ),
1155
- "utf-8"
1156
- ).pipe(res, { end: true });
1157
- } else {
1158
- next?.();
1159
- }
1160
- };
1161
- }
1162
-
1163
- // src/node/route/RouteService.ts
1164
- import path9 from "path";
1165
- import fs7 from "@rspress/shared/fs-extra";
1166
- import {
1167
- addLeadingSlash as addLeadingSlash2,
1168
- addTrailingSlash,
1169
- withBase as withBase2
1170
- } from "@rspress/shared";
1171
- var DEFAULT_PAGE_EXTENSIONS = ["js", "jsx", "ts", "tsx", "md", "mdx"];
1172
- var normalizeRoutePath = (routePath, base, lang, version, langs, versions, extensions = DEFAULT_PAGE_EXTENSIONS) => {
1173
- const hasTrailSlash = routePath.endsWith("/");
1174
- let versionPart = "";
1175
- let langPart = "";
1176
- let purePathPart = "";
1177
- const parts = routePath.split("/").filter(Boolean);
1178
- if (version) {
1179
- const versionToMatch = parts[0];
1180
- if (versions.includes(versionToMatch)) {
1181
- if (versionToMatch !== version) {
1182
- versionPart = versionToMatch;
1183
- }
1184
- parts.shift();
1185
- }
1186
- }
1187
- if (lang) {
1188
- const langToMatch = parts[0];
1189
- if (langs.includes(langToMatch)) {
1190
- if (langToMatch !== lang) {
1191
- langPart = langToMatch;
1192
- }
1193
- parts.shift();
1194
- }
1195
- }
1196
- purePathPart = parts.join("/");
1197
- let normalizedRoutePath = addLeadingSlash2(
1198
- [versionPart, langPart, purePathPart].filter(Boolean).join("/")
1199
- ).replace(new RegExp(`\\.(${extensions.join("|")})$`), "").replace(/\.html$/, "").replace(/\/index$/, "/");
1200
- if (hasTrailSlash) {
1201
- normalizedRoutePath = addTrailingSlash(normalizedRoutePath);
1202
- }
1203
- return {
1204
- routePath: withBase2(normalizedRoutePath, base),
1205
- lang: langPart || lang,
1206
- version: versionPart || version
1207
- };
1208
- };
1209
- var _scanDir, _defaultLang, _defaultVersion, _extensions, _langs, _versions, _include, _exclude, _base, _tempDir, _pluginDriver, _writeTempFile, writeTempFile_fn, _generateRouteInfo, generateRouteInfo_fn;
1210
- var RouteService = class {
1211
- constructor(scanDir, userConfig, tempDir, pluginDriver) {
1212
- __privateAdd(this, _writeTempFile);
1213
- __privateAdd(this, _generateRouteInfo);
1214
- __publicField(this, "routeData", /* @__PURE__ */ new Map());
1215
- __privateAdd(this, _scanDir, void 0);
1216
- __privateAdd(this, _defaultLang, void 0);
1217
- __privateAdd(this, _defaultVersion, "");
1218
- __privateAdd(this, _extensions, []);
1219
- __privateAdd(this, _langs, []);
1220
- __privateAdd(this, _versions, []);
1221
- __privateAdd(this, _include, []);
1222
- __privateAdd(this, _exclude, []);
1223
- __privateAdd(this, _base, "");
1224
- __privateAdd(this, _tempDir, "");
1225
- __privateAdd(this, _pluginDriver, void 0);
1226
- const routeOptions = userConfig?.route || {};
1227
- __privateSet(this, _scanDir, scanDir);
1228
- __privateSet(this, _extensions, routeOptions.extensions || DEFAULT_PAGE_EXTENSIONS);
1229
- __privateSet(this, _include, routeOptions.include || []);
1230
- __privateSet(this, _exclude, routeOptions.exclude || []);
1231
- __privateSet(this, _defaultLang, userConfig?.lang || "");
1232
- __privateSet(this, _langs, (userConfig?.locales ?? userConfig?.themeConfig?.locales ?? []).map((item) => item.lang));
1233
- __privateSet(this, _base, userConfig?.base || "");
1234
- __privateSet(this, _tempDir, tempDir);
1235
- __privateSet(this, _pluginDriver, pluginDriver);
1236
- if (userConfig.multiVersion) {
1237
- __privateSet(this, _defaultVersion, userConfig.multiVersion.default || "");
1238
- __privateSet(this, _versions, userConfig.multiVersion.versions || []);
1239
- }
1240
- }
1241
- async init() {
1242
- const globby = (await import(
1243
- // @ts-expect-error
1244
- // eslint-disable-next-line node/file-extension-in-import
1245
- "../compiled/globby/index.js"
1246
- )).default;
1247
- const files = (await globby([`**/*.{${__privateGet(this, _extensions).join(",")}}`, ...__privateGet(this, _include)], {
1248
- cwd: __privateGet(this, _scanDir),
1249
- absolute: true,
1250
- ignore: [
1251
- ...__privateGet(this, _exclude),
1252
- "**/node_modules/**",
1253
- "**/.eslintrc.js",
1254
- "**/.nx-cache/**",
1255
- `./${PUBLIC_DIR}/**`
1256
- ]
1257
- })).sort();
1258
- files.forEach((filePath) => {
1259
- const fileRelativePath = normalizePath(
1260
- path9.relative(__privateGet(this, _scanDir), filePath)
1261
- );
1262
- const { routePath, lang, version } = this.normalizeRoutePath(fileRelativePath);
1263
- const absolutePath = path9.join(__privateGet(this, _scanDir), fileRelativePath);
1264
- const routeInfo = {
1265
- routePath,
1266
- absolutePath: normalizePath(absolutePath),
1267
- relativePath: fileRelativePath,
1268
- pageName: getPageKey(fileRelativePath),
1269
- lang,
1270
- version
1271
- };
1272
- this.addRoute(routeInfo);
1273
- });
1274
- const externalPages = await __privateGet(this, _pluginDriver).addPages();
1275
- await Promise.all(
1276
- externalPages.map(async (route, index) => {
1277
- const { routePath, content, filepath } = route;
1278
- if (filepath) {
1279
- const routeInfo = __privateMethod(this, _generateRouteInfo, generateRouteInfo_fn).call(this, routePath, filepath);
1280
- this.addRoute(routeInfo);
1281
- return;
1282
- }
1283
- if (content) {
1284
- const filepath2 = await __privateMethod(this, _writeTempFile, writeTempFile_fn).call(this, index, content);
1285
- const routeInfo = __privateMethod(this, _generateRouteInfo, generateRouteInfo_fn).call(this, routePath, filepath2);
1286
- this.addRoute(routeInfo);
1287
- }
1288
- })
1289
- );
1290
- await __privateGet(this, _pluginDriver).routeGenerated(this.getRoutes());
1291
- }
1292
- addRoute(routeInfo) {
1293
- const { routePath, absolutePath } = routeInfo;
1294
- if (this.routeData.has(routePath)) {
1295
- const preRouteExtIndex = __privateGet(this, _extensions).indexOf(
1296
- path9.extname(this.routeData.get(routePath).absolutePath).slice(1)
1297
- );
1298
- const currRouteExtIndex = __privateGet(this, _extensions).indexOf(
1299
- path9.extname(absolutePath).slice(1)
1300
- );
1301
- if (currRouteExtIndex !== -1 && (currRouteExtIndex < preRouteExtIndex || preRouteExtIndex === -1)) {
1302
- this.routeData.set(routePath, routeInfo);
1303
- }
1304
- } else {
1305
- this.routeData.set(routePath, routeInfo);
1306
- }
1307
- }
1308
- removeRoute(filePath) {
1309
- const fileRelativePath = path9.relative(__privateGet(this, _scanDir), filePath);
1310
- const { routePath } = this.normalizeRoutePath(fileRelativePath);
1311
- this.routeData.delete(routePath);
1312
- }
1313
- getRoutes() {
1314
- return Array.from(this.routeData.values());
1315
- }
1316
- isExistRoute(routePath) {
1317
- const { routePath: normalizedRoute } = this.normalizeRoutePath(routePath);
1318
- return this.routeData.get(normalizedRoute);
1319
- }
1320
- isEmpty() {
1321
- return this.routeData.size === 0;
1322
- }
1323
- generateRoutesCode(isStaticImport = false) {
1324
- return this.generateRoutesCodeByRouteMeta(this.getRoutes(), isStaticImport);
1325
- }
1326
- generateRoutesCodeByRouteMeta(routeMeta, isStaticImport) {
1327
- return `
1328
- import React from 'react';
1329
- import { lazyWithPreload } from "react-lazy-with-preload";
1330
- ${routeMeta.map((route, index) => {
1331
- return isStaticImport ? `import * as Route${index} from '${route.absolutePath}';` : `const Route${index} = lazyWithPreload(() => import('${route.absolutePath}'))`;
1332
- }).join("\n")}
1333
- export const routes = [
1334
- ${routeMeta.map((route, index) => {
1335
- const preload = isStaticImport ? `() => Route${index}` : `async () => {
1336
- await Route${index}.preload();
1337
- return import("${route.absolutePath}");
1338
- }`;
1339
- const component = isStaticImport ? `Route${index}.default` : `Route${index}`;
1340
- return `{ path: '${route.routePath}', element: React.createElement(${component}), filePath: '${route.relativePath}', preload: ${preload}, lang: '${route.lang}', version: '${route.version}' }`;
1341
- }).join(",\n")}
1342
- ];
1343
- `;
1344
- }
1345
- normalizeRoutePath(routePath) {
1346
- return normalizeRoutePath(
1347
- routePath,
1348
- __privateGet(this, _base),
1349
- __privateGet(this, _defaultLang),
1350
- __privateGet(this, _defaultVersion),
1351
- __privateGet(this, _langs),
1352
- __privateGet(this, _versions),
1353
- __privateGet(this, _extensions)
1354
- );
1572
+ );
1573
+ }
1355
1574
  }
1356
- };
1357
- _scanDir = new WeakMap();
1358
- _defaultLang = new WeakMap();
1359
- _defaultVersion = new WeakMap();
1360
- _extensions = new WeakMap();
1361
- _langs = new WeakMap();
1362
- _versions = new WeakMap();
1363
- _include = new WeakMap();
1364
- _exclude = new WeakMap();
1365
- _base = new WeakMap();
1366
- _tempDir = new WeakMap();
1367
- _pluginDriver = new WeakMap();
1368
- _writeTempFile = new WeakSet();
1369
- writeTempFile_fn = async function(index, content) {
1370
- const tempFilePath = path9.join(__privateGet(this, _tempDir), `temp-${index}.mdx`);
1371
- await fs7.writeFile(tempFilePath, content);
1372
- return tempFilePath;
1373
- };
1374
- _generateRouteInfo = new WeakSet();
1375
- generateRouteInfo_fn = function(routePath, filepath) {
1376
- const {
1377
- routePath: normalizedPath,
1378
- lang,
1379
- version
1380
- } = this.normalizeRoutePath(routePath);
1381
- return {
1382
- routePath: normalizedPath,
1383
- absolutePath: normalizePath(filepath),
1384
- relativePath: normalizePath(path9.relative(__privateGet(this, _scanDir), filepath)),
1385
- pageName: getPageKey(routePath),
1386
- lang,
1387
- version
1575
+ }
1576
+ function serveSearchIndexMiddleware(config) {
1577
+ return (req, res, next) => {
1578
+ const searchIndexRequestMatch = `/${SEARCH_INDEX_NAME2}.`;
1579
+ if (req.url?.includes(searchIndexRequestMatch)) {
1580
+ res.setHeader("Content-Type", "application/json");
1581
+ const searchIndexFile = req.url?.split("/").pop();
1582
+ fs7.createReadStream(
1583
+ path9.join(
1584
+ process.cwd(),
1585
+ config?.outDir || OUTPUT_DIR,
1586
+ "static",
1587
+ searchIndexFile
1588
+ ),
1589
+ "utf-8"
1590
+ ).pipe(res, { end: true });
1591
+ } else {
1592
+ next?.();
1593
+ }
1388
1594
  };
1389
- };
1390
-
1391
- // src/node/route/init.ts
1392
- var routeService = null;
1393
- async function initRouteService(options) {
1394
- const { scanDir, config, runtimeTempDir, pluginDriver } = options;
1395
- routeService = new RouteService(
1396
- scanDir,
1397
- config,
1398
- runtimeTempDir,
1399
- pluginDriver
1400
- );
1401
- await routeService.init();
1402
- return routeService;
1403
1595
  }
1404
1596
 
1405
1597
  // src/node/utils/detectCustomIcon.ts
@@ -1427,9 +1619,6 @@ var detectCustomIcon = async (customThemeDir) => {
1427
1619
  };
1428
1620
 
1429
1621
  // src/node/initRsbuild.ts
1430
- import { PLUGIN_REACT_NAME, pluginReact } from "@rsbuild/plugin-react";
1431
- import { PLUGIN_SASS_NAME, pluginSass } from "@rsbuild/plugin-sass";
1432
- import { PLUGIN_LESS_NAME, pluginLess } from "@rsbuild/plugin-less";
1433
1622
  function isPluginIncluded(config, pluginName) {
1434
1623
  return config.builderPlugins?.some((plugin) => plugin.name === pluginName) || config.builderConfig?.plugins?.some(
1435
1624
  (plugin) => plugin && plugin.name === pluginName
@@ -1668,195 +1857,6 @@ async function initRsbuild(rootDir, config, pluginDriver, enableSSG, extraRsbuil
1668
1857
  return rsbuild;
1669
1858
  }
1670
1859
 
1671
- // src/node/PluginDriver.ts
1672
- import { isDevDebugMode } from "@rspress/shared";
1673
- import { pluginContainerSyntax } from "@rspress/plugin-container-syntax";
1674
- var _config, _plugins, _isProd;
1675
- var PluginDriver = class {
1676
- constructor(config, isProd) {
1677
- __privateAdd(this, _config, void 0);
1678
- __privateAdd(this, _plugins, void 0);
1679
- __privateAdd(this, _isProd, void 0);
1680
- __privateSet(this, _config, config);
1681
- __privateSet(this, _isProd, isProd);
1682
- __privateSet(this, _plugins, []);
1683
- }
1684
- // The init function is used to initialize the doc plugins and will execute before the build process.
1685
- async init() {
1686
- this.clearPlugins();
1687
- const config = __privateGet(this, _config);
1688
- const themeConfig = config?.themeConfig || {};
1689
- const enableLastUpdated = themeConfig?.lastUpdated || themeConfig?.locales?.some((locale) => locale.lastUpdated);
1690
- const mediumZoomConfig = config?.mediumZoom ?? true;
1691
- const haveNavSidebarConfig = themeConfig.nav || themeConfig.sidebar || themeConfig.locales?.[0]?.nav || themeConfig.locales?.[0]?.sidebar;
1692
- if (enableLastUpdated) {
1693
- const { pluginLastUpdated } = await import("@rspress/plugin-last-updated");
1694
- this.addPlugin(pluginLastUpdated());
1695
- }
1696
- if (mediumZoomConfig) {
1697
- const { pluginMediumZoom } = await import("@rspress/plugin-medium-zoom");
1698
- this.addPlugin(
1699
- pluginMediumZoom(
1700
- typeof mediumZoomConfig === "object" ? mediumZoomConfig : void 0
1701
- )
1702
- );
1703
- }
1704
- this.addPlugin(pluginContainerSyntax());
1705
- if (isDevDebugMode()) {
1706
- const SourceBuildPlugin = await import(
1707
- // @ts-expect-error need moduleResolution: Node16, NodeNext or Bundler to get type declerations work
1708
- "@rspress/theme-default/node/source-build-plugin.js"
1709
- ).then(
1710
- (r) => r.SourceBuildPlugin,
1711
- () => null
1712
- );
1713
- if (SourceBuildPlugin) {
1714
- this.addPlugin(SourceBuildPlugin());
1715
- }
1716
- }
1717
- (config.plugins || []).forEach((plugin) => {
1718
- this.addPlugin(plugin);
1719
- });
1720
- if (!haveNavSidebarConfig) {
1721
- const { pluginAutoNavSidebar } = await import("@rspress/plugin-auto-nav-sidebar");
1722
- this.addPlugin(pluginAutoNavSidebar());
1723
- }
1724
- }
1725
- addPlugin(plugin) {
1726
- const existedIndex = __privateGet(this, _plugins).findIndex(
1727
- (item) => item.name === plugin.name
1728
- );
1729
- if (existedIndex !== -1) {
1730
- throw new Error(`The plugin "${plugin.name}" has been registered`);
1731
- }
1732
- __privateGet(this, _plugins).push(plugin);
1733
- }
1734
- getPlugins() {
1735
- return __privateGet(this, _plugins);
1736
- }
1737
- clearPlugins() {
1738
- __privateSet(this, _plugins, []);
1739
- }
1740
- removePlugin(pluginName) {
1741
- const index = __privateGet(this, _plugins).findIndex((item) => item.name === pluginName);
1742
- if (index !== -1) {
1743
- __privateGet(this, _plugins).splice(index, 1);
1744
- }
1745
- }
1746
- async modifyConfig() {
1747
- let config = __privateGet(this, _config);
1748
- for (let i = 0; i < __privateGet(this, _plugins).length; i++) {
1749
- const plugin = __privateGet(this, _plugins)[i];
1750
- if (typeof plugin.config === "function") {
1751
- config = await plugin.config(
1752
- config || {},
1753
- {
1754
- addPlugin: this.addPlugin.bind(this),
1755
- removePlugin: (pluginName) => {
1756
- const index = __privateGet(this, _plugins).findIndex(
1757
- (item) => item.name === pluginName
1758
- );
1759
- this.removePlugin(pluginName);
1760
- if (index <= i && index > 0) {
1761
- i--;
1762
- }
1763
- }
1764
- },
1765
- __privateGet(this, _isProd)
1766
- );
1767
- }
1768
- }
1769
- __privateSet(this, _config, config);
1770
- return __privateGet(this, _config);
1771
- }
1772
- async beforeBuild() {
1773
- return this._runParallelAsyncHook(
1774
- "beforeBuild",
1775
- __privateGet(this, _config) || {},
1776
- __privateGet(this, _isProd)
1777
- );
1778
- }
1779
- async afterBuild() {
1780
- return this._runParallelAsyncHook(
1781
- "afterBuild",
1782
- __privateGet(this, _config) || {},
1783
- __privateGet(this, _isProd)
1784
- );
1785
- }
1786
- async modifySearchIndexData(pages) {
1787
- return this._runParallelAsyncHook(
1788
- "modifySearchIndexData",
1789
- pages,
1790
- __privateGet(this, _isProd)
1791
- );
1792
- }
1793
- async extendPageData(pageData) {
1794
- return this._runParallelAsyncHook("extendPageData", pageData, __privateGet(this, _isProd));
1795
- }
1796
- async addPages() {
1797
- const result = await this._runParallelAsyncHook(
1798
- "addPages",
1799
- __privateGet(this, _config) || {},
1800
- __privateGet(this, _isProd)
1801
- );
1802
- return result.flat();
1803
- }
1804
- async routeGenerated(routes) {
1805
- return this._runParallelAsyncHook("routeGenerated", routes);
1806
- }
1807
- async addRuntimeModules() {
1808
- const result = await this._runParallelAsyncHook(
1809
- "addRuntimeModules",
1810
- __privateGet(this, _config) || {},
1811
- __privateGet(this, _isProd)
1812
- );
1813
- return result.reduce((prev, current) => {
1814
- return {
1815
- ...prev,
1816
- ...current
1817
- };
1818
- }, {});
1819
- }
1820
- async addSSGRoutes() {
1821
- const result = await this._runParallelAsyncHook(
1822
- "addSSGRoutes",
1823
- __privateGet(this, _config) || {},
1824
- __privateGet(this, _isProd)
1825
- );
1826
- return result.flat();
1827
- }
1828
- globalUIComponents() {
1829
- const result = __privateGet(this, _plugins).map((plugin) => {
1830
- return plugin.globalUIComponents || [];
1831
- });
1832
- return result.flat();
1833
- }
1834
- globalStyles() {
1835
- return __privateGet(this, _plugins).filter((plugin) => typeof plugin.globalStyles === "string").map((plugin) => {
1836
- return plugin.globalStyles;
1837
- });
1838
- }
1839
- _runParallelAsyncHook(hookName, ...args) {
1840
- return Promise.all(
1841
- __privateGet(this, _plugins).filter((plugin) => typeof plugin[hookName] === "function").map((plugin) => {
1842
- return plugin[hookName](...args);
1843
- })
1844
- );
1845
- }
1846
- _runSerialAysncHook(hookName, ...args) {
1847
- return __privateGet(this, _plugins).reduce(async (prev, plugin) => {
1848
- if (typeof plugin[hookName] === "function") {
1849
- await prev;
1850
- return plugin[hookName](...args);
1851
- }
1852
- return prev;
1853
- }, Promise.resolve());
1854
- }
1855
- };
1856
- _config = new WeakMap();
1857
- _plugins = new WeakMap();
1858
- _isProd = new WeakMap();
1859
-
1860
1860
  // src/node/dev.ts
1861
1861
  async function dev(options) {
1862
1862
  const { docDirectory, config, extraBuilderConfig } = options;
@@ -1889,13 +1889,13 @@ async function dev(options) {
1889
1889
  // src/node/build.ts
1890
1890
  import { dirname as dirname2, join as join3 } from "path";
1891
1891
  import { pathToFileURL } from "url";
1892
- import chalk3 from "@rspress/shared/chalk";
1893
- import fs9 from "@rspress/shared/fs-extra";
1894
1892
  import {
1893
+ isDebugMode as isDebugMode2,
1895
1894
  normalizeSlash,
1896
- withBase as withBase3,
1897
- isDebugMode as isDebugMode2
1895
+ withBase as withBase3
1898
1896
  } from "@rspress/shared";
1897
+ import chalk3 from "@rspress/shared/chalk";
1898
+ import fs9 from "@rspress/shared/fs-extra";
1899
1899
  import { logger as logger3 } from "@rspress/shared/logger";
1900
1900
 
1901
1901
  // src/node/utils/renderHead.ts