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

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,28 +1,150 @@
1
1
  import __rslib_shim_module__ from 'module';
2
2
  const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(import.meta.url);
3
+ import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__ from "@rspress/shared";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_child_process__ from "child_process";
5
+ import * as __WEBPACK_EXTERNAL_MODULE_fs__ from "fs";
6
+ import * as __WEBPACK_EXTERNAL_MODULE_node_buffer_fb286294__ from "node:buffer";
7
+ import * as __WEBPACK_EXTERNAL_MODULE_node_child_process_27f17141__ from "node:child_process";
8
+ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
9
+ import * as __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__ from "node:os";
10
+ import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
11
+ import * as __WEBPACK_EXTERNAL_MODULE_node_process_786449bf__ from "node:process";
12
+ import * as __WEBPACK_EXTERNAL_MODULE_node_timers_promises_aedbf14c__ from "node:timers/promises";
13
+ import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
14
+ import * as __WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__ from "node:util";
15
+ import * as __WEBPACK_EXTERNAL_MODULE_path__ from "path";
16
+ import * as __WEBPACK_EXTERNAL_MODULE_stream__ from "stream";
3
17
  import node_fs_promises, { mkdir, readFile, readdir, rm, stat as promises_stat, writeFile } from "node:fs/promises";
4
- import node_path, { dirname, extname, join, relative } from "node:path";
5
- import { fileURLToPath, pathToFileURL } from "node:url";
6
18
  import { PLUGIN_REACT_NAME, pluginReact } from "@rsbuild/plugin-react";
7
- import { APPEARANCE_KEY, MDX_OR_MD_REGEXP, RSPRESS_TEMP_DIR, SEARCH_INDEX_NAME, addLeadingSlash, addTrailingSlash, isDebugMode, isExternalUrl, isProduction, isSCM, normalizeHref, normalizeSlash, parseUrl, removeLeadingSlash, removeTrailingSlash, slash, withBase } from "@rspress/shared";
8
19
  import { DEFAULT_PAGE_EXTENSIONS } from "@rspress/shared/constants";
9
20
  import { logger } from "@rspress/shared/logger";
10
21
  import picocolors from "picocolors";
11
- import node_os from "node:os";
12
22
  import { glob } from "tinyglobby";
13
23
  import { extractTextAndId, getIconUrlPath, getNodeAttribute, loadFrontMatter, mergeDocConfig } from "@rspress/shared/node-utils";
14
24
  import { RspackVirtualModulePlugin } from "rspack-plugin-virtual-module";
15
25
  import { groupBy } from "lodash-es";
16
26
  import { compile } from "@rspress/mdx-rs";
17
27
  import { htmlToText } from "html-to-text";
18
- import node_fs, { createReadStream, existsSync } from "node:fs";
19
28
  import { createProcessor } from "@mdx-js/mdx";
20
29
  import enhanced_resolve from "enhanced-resolve";
21
30
  import { createHash } from "node:crypto";
22
31
  import { createHead, transformHtmlTemplate } from "@unhead/react/server";
23
32
  import { mergeRsbuildConfig as core_mergeRsbuildConfig } from "@rsbuild/core";
24
33
  import { visit } from "unist-util-visit";
25
- export * from "@rspress/shared";
34
+ import { matchPath } from "@rspress/runtime/server";
35
+ var __webpack_modules__ = {
36
+ "@rspress/shared": function(module) {
37
+ module.exports = __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__;
38
+ },
39
+ child_process: function(module) {
40
+ module.exports = __WEBPACK_EXTERNAL_MODULE_child_process__;
41
+ },
42
+ fs: function(module) {
43
+ module.exports = __WEBPACK_EXTERNAL_MODULE_fs__;
44
+ },
45
+ "node:buffer": function(module) {
46
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_buffer_fb286294__;
47
+ },
48
+ "node:child_process": function(module) {
49
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_child_process_27f17141__;
50
+ },
51
+ "node:fs": function(module) {
52
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__;
53
+ },
54
+ "node:os": function(module) {
55
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__;
56
+ },
57
+ "node:path": function(module) {
58
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__;
59
+ },
60
+ "node:process": function(module) {
61
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_process_786449bf__;
62
+ },
63
+ "node:timers/promises": function(module) {
64
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_timers_promises_aedbf14c__;
65
+ },
66
+ "node:url": function(module) {
67
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__;
68
+ },
69
+ "node:util": function(module) {
70
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__;
71
+ },
72
+ path: function(module) {
73
+ module.exports = __WEBPACK_EXTERNAL_MODULE_path__;
74
+ },
75
+ stream: function(module) {
76
+ module.exports = __WEBPACK_EXTERNAL_MODULE_stream__;
77
+ }
78
+ };
79
+ var __webpack_module_cache__ = {};
80
+ function __webpack_require__(moduleId) {
81
+ var cachedModule = __webpack_module_cache__[moduleId];
82
+ if (void 0 !== cachedModule) return cachedModule.exports;
83
+ var module = __webpack_module_cache__[moduleId] = {
84
+ exports: {}
85
+ };
86
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
87
+ return module.exports;
88
+ }
89
+ __webpack_require__.m = __webpack_modules__;
90
+ (()=>{
91
+ __webpack_require__.d = (exports, definition)=>{
92
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
93
+ enumerable: true,
94
+ get: definition[key]
95
+ });
96
+ };
97
+ })();
98
+ (()=>{
99
+ __webpack_require__.f = {};
100
+ __webpack_require__.e = (chunkId)=>Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key)=>{
101
+ __webpack_require__.f[key](chunkId, promises);
102
+ return promises;
103
+ }, []));
104
+ })();
105
+ (()=>{
106
+ __webpack_require__.u = (chunkId)=>"" + chunkId + ".js";
107
+ })();
108
+ (()=>{
109
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
110
+ })();
111
+ (()=>{
112
+ var installedChunks = {
113
+ 980: 0
114
+ };
115
+ var installChunk = (data)=>{
116
+ var __webpack_ids__ = data.__webpack_ids__;
117
+ var __webpack_modules__ = data.__webpack_modules__;
118
+ var __webpack_runtime__ = data.__webpack_runtime__;
119
+ var moduleId, chunkId, i = 0;
120
+ for(moduleId in __webpack_modules__)if (__webpack_require__.o(__webpack_modules__, moduleId)) __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];
121
+ if (__webpack_runtime__) __webpack_runtime__(__webpack_require__);
122
+ for(; i < __webpack_ids__.length; i++){
123
+ chunkId = __webpack_ids__[i];
124
+ if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) installedChunks[chunkId][0]();
125
+ installedChunks[__webpack_ids__[i]] = 0;
126
+ }
127
+ };
128
+ __webpack_require__.f.j = function(chunkId, promises) {
129
+ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : void 0;
130
+ if (0 !== installedChunkData) if (installedChunkData) promises.push(installedChunkData[1]);
131
+ else {
132
+ var promise = import("./" + __webpack_require__.u(chunkId)).then(installChunk, (e)=>{
133
+ if (0 !== installedChunks[chunkId]) installedChunks[chunkId] = void 0;
134
+ throw e;
135
+ });
136
+ var promise = Promise.race([
137
+ promise,
138
+ new Promise((resolve)=>{
139
+ installedChunkData = installedChunks[chunkId] = [
140
+ resolve
141
+ ];
142
+ })
143
+ ]);
144
+ promises.push(installedChunkData[1] = promise);
145
+ }
146
+ };
147
+ })();
26
148
  class PluginDriver {
27
149
  #config;
28
150
  #configFilePath;
@@ -44,11 +166,14 @@ class PluginDriver {
44
166
  const enableLastUpdated = themeConfig?.lastUpdated || themeConfig?.locales?.some((locale)=>locale.lastUpdated);
45
167
  const mediumZoomConfig = config?.mediumZoom ?? true;
46
168
  if (enableLastUpdated) {
47
- const { pluginLastUpdated } = await import("@rspress/plugin-last-updated");
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"));
48
173
  this.addPlugin(pluginLastUpdated());
49
174
  }
50
175
  if (mediumZoomConfig) {
51
- const { pluginMediumZoom } = await import("@rspress/plugin-medium-zoom");
176
+ const { pluginMediumZoom } = await __webpack_require__.e("309").then(__webpack_require__.bind(__webpack_require__, "./src/node/medium-zoom/index.ts"));
52
177
  this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
53
178
  }
54
179
  (config.plugins || []).forEach((plugin)=>{
@@ -139,15 +264,18 @@ class PluginDriver {
139
264
  }, Promise.resolve());
140
265
  }
141
266
  }
267
+ var external_node_path_ = __webpack_require__("node:path");
268
+ var external_node_url_ = __webpack_require__("node:url");
269
+ var shared_ = __webpack_require__("@rspress/shared");
142
270
  const PLUGIN_VIRTUAL_MODULE_NAME = 'rsbuild:virtual-module';
143
271
  const pluginVirtualModule = (pluginOptions = {})=>({
144
272
  name: PLUGIN_VIRTUAL_MODULE_NAME,
145
273
  async setup (api) {
146
274
  const { virtualModules = {}, tempDir: virtualFolderName = '.rsbuild-virtual-module' } = pluginOptions;
147
- const TEMP_DIR = join(api.context.rootPath, 'node_modules', virtualFolderName);
275
+ const TEMP_DIR = (0, external_node_path_.join)(api.context.rootPath, 'node_modules', virtualFolderName);
148
276
  const virtualFileAbsolutePaths = Object.keys(virtualModules).map((i)=>{
149
- let absolutePath = join(TEMP_DIR, i);
150
- if (!extname(absolutePath)) absolutePath = `${absolutePath}.js`;
277
+ let absolutePath = (0, external_node_path_.join)(TEMP_DIR, i);
278
+ if (!(0, external_node_path_.extname)(absolutePath)) absolutePath = `${absolutePath}.js`;
151
279
  return [
152
280
  i,
153
281
  absolutePath
@@ -162,7 +290,7 @@ const pluginVirtualModule = (pluginOptions = {})=>({
162
290
  });
163
291
  api.onBeforeCreateCompiler(async ()=>{
164
292
  await Promise.all(virtualFileAbsolutePaths.map(async ([_, absolutePath])=>{
165
- const dir = dirname(absolutePath);
293
+ const dir = (0, external_node_path_.dirname)(absolutePath);
166
294
  await mkdir(dir, {
167
295
  recursive: true
168
296
  });
@@ -202,7 +330,7 @@ async function hintThemeBreakingChange(customThemeDir) {
202
330
  ];
203
331
  let useDefaultExportFilePath = null;
204
332
  for (const file of fileList){
205
- const filePath = join(customThemeDir, file);
333
+ const filePath = (0, external_node_path_.join)(customThemeDir, file);
206
334
  if (await pathExists(filePath)) {
207
335
  const content = await readFile(filePath, {
208
336
  encoding: 'utf-8'
@@ -224,6 +352,22 @@ async function hintThemeBreakingChange(customThemeDir) {
224
352
  + export * from 'rspress/theme';
225
353
  `));
226
354
  }
355
+ function hintBuilderPluginsBreakingChange(config) {
356
+ if ('builderPlugins' in config && Array.isArray(config.builderPlugins) && config.builderPlugins.length > 0) {
357
+ logger.error(`[Rspress v2] The "builderPlugins" option has been renamed to "builderConfig.plugins", please update your config accordingly (https://rspress.rs/api/config/config-build#builderconfigplugins).\n`, `
358
+ export default defineConfig({
359
+ ${picocolors.redBright(` builderPlugins: [
360
+ pluginFoo()
361
+ ],`)}
362
+ ${picocolors.greenBright(` builderConfig: {
363
+ plugins: [
364
+ pluginFoo()
365
+ ],
366
+ },`)}
367
+ });`);
368
+ process.exit(1);
369
+ }
370
+ }
227
371
  function hintSSGFailed() {
228
372
  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:
229
373
  1. Fix code to make it SSR-compatible.
@@ -239,8 +383,8 @@ function hintNavJsonChangeThenPanic(metaJson, metaJsonDir, docsDir) {
239
383
  if (metaJson.some((i)=>'object' == typeof i && ('activeMatch' in i || 'text' in i || 'link' in i || 'items' in i || 'icon' in i || 'ariaLabel' in i || 'target' in i))) {
240
384
  const error = new Error('[Rspress v2] Detected that you are still using top level `_meta.json` to configure the nav, but it has been changed to `_nav.json` in Rspress v2. Please rename the top level `_meta.json` to `_nav.json` accordingly.');
241
385
  logger.error(error);
242
- const dir = relative(docsDir, metaJsonDir);
243
- logger.info(`Please rename "${picocolors.greenBright(join(dir, '_meta.json'))}" to "${picocolors.greenBright(join(dir, '_nav.json'))}".`);
386
+ const dir = (0, external_node_path_.relative)(docsDir, metaJsonDir);
387
+ logger.info(`Please rename "${picocolors.greenBright((0, external_node_path_.join)(dir, '_meta.json'))}" to "${picocolors.greenBright((0, external_node_path_.join)(dir, '_nav.json'))}".`);
244
388
  process.exit(1);
245
389
  }
246
390
  }
@@ -251,41 +395,42 @@ function hintRelativeMarkdownLink() {
251
395
  logger.info('[Rspress v2] Markdown links without "./" prefix are now relative links, e.g: [](guide/getting-started) is equal to [](./guide/getting-started). You can rewrite it to [](/guide/getting-started) to always use absolute links, or use [](./getting-started.md)');
252
396
  }
253
397
  function getPageKey(route) {
254
- const cleanRoute = removeLeadingSlash(route);
398
+ const cleanRoute = (0, shared_.removeLeadingSlash)(route);
255
399
  return cleanRoute.replace(/\//g, '_').replace(/\.[^.]+$/, '') || 'index';
256
400
  }
257
- const isWindows = 'win32' === node_os.platform();
258
- function normalizePath_slash(p) {
401
+ var external_node_os_ = __webpack_require__("node:os");
402
+ const isWindows = 'win32' === external_node_os_["default"].platform();
403
+ function slash(p) {
259
404
  return p.replace(/\\/g, '/');
260
405
  }
261
406
  function normalizePath(id) {
262
- return node_path.posix.normalize(isWindows ? normalizePath_slash(id) : id);
407
+ return external_node_path_["default"].posix.normalize(isWindows ? slash(id) : id);
263
408
  }
264
- var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.20"}');
409
+ var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.21"}');
265
410
  const RSPRESS_VERSION = package_namespaceObject.i8;
266
- const constants_isProduction = ()=>'production' === process.env.NODE_ENV;
411
+ const isProduction = ()=>'production' === process.env.NODE_ENV;
267
412
  const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
268
413
  const inlineThemeScript = `{
269
- const saved = localStorage.getItem('${APPEARANCE_KEY}')
414
+ const saved = localStorage.getItem('${shared_.APPEARANCE_KEY}')
270
415
  const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
271
416
  const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
272
417
  document.documentElement.classList.toggle('dark', isDark)
273
418
  document.documentElement.classList.toggle('rp-dark', isDark)
274
419
  document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
275
420
  }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
276
- const constants_dirname = node_path.dirname(fileURLToPath(new URL(import.meta.url)));
277
- const PACKAGE_ROOT = node_path.join(constants_dirname, '..');
278
- const TEMPLATE_PATH = node_path.join(PACKAGE_ROOT, 'index.html');
279
- const CSR_CLIENT_ENTRY = node_path.join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
280
- const SSR_CLIENT_ENTRY = node_path.join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
281
- const SSR_SERVER_ENTRY = node_path.join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
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');
282
427
  const OUTPUT_DIR = 'doc_build';
283
428
  const APP_HTML_MARKER = '<!--<?- DOC_CONTENT ?>-->';
284
429
  const HEAD_MARKER = '<!--<?- HEAD ?>-->';
285
430
  const META_GENERATOR = '<!--<?- GENERATOR ?>-->';
286
431
  const DEFAULT_TITLE = 'Rspress';
287
432
  const PUBLIC_DIR = 'public';
288
- const constants_TEMP_DIR = node_path.join(process.cwd(), 'node_modules', RSPRESS_TEMP_DIR);
433
+ const constants_TEMP_DIR = external_node_path_["default"].join(process.cwd(), 'node_modules', shared_.RSPRESS_TEMP_DIR);
289
434
  const NODE_SSG_BUNDLE_FOLDER = '__ssg__';
290
435
  const NODE_SSG_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
291
436
  const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
@@ -312,7 +457,7 @@ const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
312
457
  return [
313
458
  versionPart,
314
459
  langPart,
315
- hasTrailSlash ? addTrailingSlash(purePathPart) : purePathPart
460
+ hasTrailSlash ? (0, shared_.addTrailingSlash)(purePathPart) : purePathPart
316
461
  ];
317
462
  };
318
463
  const normalizeRoutePath = (relativePath, lang, version, langs, versions, extensions = DEFAULT_PAGE_EXTENSIONS)=>{
@@ -322,7 +467,7 @@ const normalizeRoutePath = (relativePath, lang, version, langs, versions, extens
322
467
  const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
323
468
  routePath = purePathPart.replace(/\/index$/, '/');
324
469
  if ('index' === routePath) routePath = '';
325
- const normalizedRoutePath = addLeadingSlash([
470
+ const normalizedRoutePath = (0, shared_.addLeadingSlash)([
326
471
  ...[
327
472
  versionPart,
328
473
  langPart
@@ -462,7 +607,7 @@ ${routeMeta.map((route, index)=>{
462
607
  return absolutePathToRelativePath(absolutePath, this.#scanDir);
463
608
  }
464
609
  async #writeTempFile(index, content) {
465
- const tempFilePath = node_path.join(this.#tempDir, `temp-${index}.mdx`);
610
+ const tempFilePath = external_node_path_["default"].join(this.#tempDir, `temp-${index}.mdx`);
466
611
  await node_fs_promises.writeFile(tempFilePath, content);
467
612
  return tempFilePath;
468
613
  }
@@ -479,7 +624,7 @@ class RoutePage {
479
624
  }
480
625
  static createFromExternal(routePath, filepath, docDir) {
481
626
  const routeMeta = RoutePage.generateRouteMeta(routePath, filepath, docDir);
482
- return new RoutePage(routeMeta, node_path.dirname(filepath));
627
+ return new RoutePage(routeMeta, external_node_path_["default"].dirname(filepath));
483
628
  }
484
629
  constructor(routeMeta, docDir){
485
630
  this.routeMeta = routeMeta;
@@ -499,7 +644,7 @@ class RoutePage {
499
644
  }
500
645
  }
501
646
  function absolutePathToRelativePath(absolutePath, docsDir) {
502
- return normalizePath_slash(node_path.relative(docsDir, absolutePath));
647
+ return slash(external_node_path_["default"].relative(docsDir, absolutePath));
503
648
  }
504
649
  function absolutePathToRouteMeta(absolutePath, docsDir, routeService = RouteService.getInstance()) {
505
650
  const relativePath = absolutePathToRelativePath(absolutePath, docsDir);
@@ -517,7 +662,7 @@ function absolutePathToRoutePath(absolutePath, docsDir, routeService = RouteServ
517
662
  return absolutePathToRouteMeta(absolutePath, docsDir, routeService).routePath;
518
663
  }
519
664
  function absolutePathToRoutePrefix(absolutePath, docsDir) {
520
- const relativePath = normalizePath_slash(node_path.relative(docsDir, absolutePath.replace(node_path.extname(absolutePath), '')));
665
+ const relativePath = slash(external_node_path_["default"].relative(docsDir, absolutePath.replace(external_node_path_["default"].extname(absolutePath), '')));
521
666
  const routeService = RouteService.getInstance();
522
667
  const [versionPrefix, langPrefix] = routeService.getRoutePathParts(relativePath);
523
668
  return `${versionPrefix ? `/${versionPrefix}` : ''}${langPrefix ? `/${langPrefix}` : ''}`;
@@ -540,7 +685,7 @@ async function utils_readJson(path) {
540
685
  }
541
686
  async function extractInfoFromFrontmatterWithAbsolutePath(absolutePath, rootDir) {
542
687
  const content = await node_fs_promises.readFile(absolutePath, 'utf-8');
543
- const fileNameWithoutExt = node_path.basename(absolutePath, node_path.extname(absolutePath));
688
+ const fileNameWithoutExt = external_node_path_["default"].basename(absolutePath, external_node_path_["default"].extname(absolutePath));
544
689
  const h1RegExp = /^#\s+(.*)$/m;
545
690
  const match = content.match(h1RegExp);
546
691
  const { frontmatter } = loadFrontMatter(content, absolutePath, rootDir);
@@ -551,10 +696,16 @@ async function extractInfoFromFrontmatterWithAbsolutePath(absolutePath, rootDir)
551
696
  };
552
697
  }
553
698
  function getHmrFileKey(realPath, docsDir) {
554
- return realPath ? slash(relative(docsDir, realPath).replace(extname(realPath), '')) : '';
699
+ return realPath ? (0, shared_.slash)((0, external_node_path_.relative)(docsDir, realPath).replace((0, external_node_path_.extname)(realPath), '')) : '';
555
700
  }
556
701
  async function fsDirToMetaItems(workDir, extensions) {
557
- let subItems = await readdir(workDir);
702
+ let subItems;
703
+ try {
704
+ subItems = await readdir(workDir);
705
+ } catch (e) {
706
+ logger.error(`Failed to read directory: ${workDir}, maybe it does not exist. Please check it in "_meta.json".`);
707
+ throw e;
708
+ }
558
709
  subItems = subItems.filter((item)=>{
559
710
  const hasExtension = extensions.some((ext)=>item.endsWith(ext));
560
711
  const hasSameBaseName = subItems.some((elem)=>{
@@ -565,7 +716,7 @@ async function fsDirToMetaItems(workDir, extensions) {
565
716
  });
566
717
  const sideMeta = (await Promise.all(subItems.map(async (item)=>{
567
718
  if ('_meta.json' === item) return null;
568
- const stat = await promises_stat(join(workDir, item));
719
+ const stat = await promises_stat((0, external_node_path_.join)(workDir, item));
569
720
  if (stat.isDirectory()) return {
570
721
  type: 'dir',
571
722
  name: item
@@ -580,8 +731,8 @@ async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, isF
580
731
  if ('file' === type) return metaFileItemToSidebarItem(metaItem, workDir, docsDir, extensions);
581
732
  if ('dir' === type) {
582
733
  const { name, label, collapsible, collapsed, tag: metaJsonTag, context: metaJsonContext, overviewHeaders: metaJsonOverviewHeaders } = metaItem;
583
- const dirAbsolutePath = join(workDir, name);
584
- const dirMetaJsonPath = join(dirAbsolutePath, '_meta.json');
734
+ const dirAbsolutePath = (0, external_node_path_.join)(workDir, name);
735
+ const dirMetaJsonPath = (0, external_node_path_.join)(dirAbsolutePath, '_meta.json');
585
736
  const isMetaJsonExist = await utils_pathExists(dirMetaJsonPath);
586
737
  let dirMetaJson = [];
587
738
  dirMetaJson = isMetaJsonExist ? await utils_readJson(dirMetaJsonPath) : await fsDirToMetaItems(dirAbsolutePath, extensions);
@@ -614,10 +765,10 @@ async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, isF
614
765
  } catch (e) {
615
766
  logger.debug(e);
616
767
  const isIndexInMetaJsonIndex = dirMetaJson.find((i)=>{
617
- if ('string' == typeof i) return 'index' === i.replace(extname(i), '');
768
+ if ('string' == typeof i) return 'index' === i.replace((0, external_node_path_.extname)(i), '');
618
769
  return false;
619
770
  });
620
- const isIndexFileExists = await utils_pathExists(join(dirAbsolutePath, 'index.mdx')) || await utils_pathExists(join(dirAbsolutePath, 'index.md'));
771
+ const isIndexFileExists = await utils_pathExists((0, external_node_path_.join)(dirAbsolutePath, 'index.mdx')) || await utils_pathExists((0, external_node_path_.join)(dirAbsolutePath, 'index.md'));
621
772
  if (isMetaJsonExist && isIndexInMetaJsonIndex || !isIndexFileExists) return {
622
773
  text: label || name,
623
774
  collapsible,
@@ -648,10 +799,10 @@ async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, isF
648
799
  }
649
800
  if ('custom-link' === type) return metaCustomLinkItemToSidebarItem(metaItem, workDir, docsDir);
650
801
  if ('divider' === type || 'section-header' === type) return metaDividerToSidebarItem(metaItem);
651
- throw new Error(`Unknown meta item type: ${metaItem.type}, please check it in "${join(workDir, '_meta.json')}".`);
802
+ throw new Error(`Unknown meta item type: ${metaItem.type}, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
652
803
  }
653
804
  async function detectFilePath(absolutePath, extensions) {
654
- const ext = extname(absolutePath);
805
+ const ext = (0, external_node_path_.extname)(absolutePath);
655
806
  if (ext && extensions.includes(ext)) return absolutePath;
656
807
  for (const extension of extensions){
657
808
  const realPath = absolutePath + extension;
@@ -666,13 +817,13 @@ async function metaFileItemToSidebarItem(metaItemRaw, workDir, docsDir, extensio
666
817
  type: 'file'
667
818
  } : metaItemRaw;
668
819
  const { name, context, label, overviewHeaders, tag } = metaItem;
669
- if ('string' != typeof name) throw new Error(`The file name "${name}" is not a string, please check it in "${join(workDir, '_meta.json')}".`);
670
- const absolutePath = join(workDir, name);
820
+ if ('string' != typeof name) throw new Error(`The file name "${name}" is not a string, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
821
+ const absolutePath = (0, external_node_path_.join)(workDir, name);
671
822
  let absolutePathWithExt;
672
823
  try {
673
824
  absolutePathWithExt = await detectFilePath(absolutePath, extensions);
674
825
  } catch {
675
- throw new Error(`The file "${absolutePath}" does not exist, please check it in "${join(workDir, '_meta.json')}".`);
826
+ throw new Error(`The file "${absolutePath}" does not exist, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
676
827
  }
677
828
  const link = absolutePathToRoutePath(absolutePathWithExt, docsDir);
678
829
  const info = await extractInfoFromFrontmatterWithAbsolutePath(absolutePathWithExt, docsDir);
@@ -687,20 +838,33 @@ async function metaFileItemToSidebarItem(metaItemRaw, workDir, docsDir, extensio
687
838
  };
688
839
  }
689
840
  function metaCustomLinkItemToSidebarItem(metaItem, workDir, docsDir) {
690
- const { label, link, context, tag } = metaItem;
691
- if (void 0 === link) throw new Error(`The custom link "${label}" does not have a link, please check it in "${join(workDir, '_meta.json')}".`);
692
- if (isExternalUrl(link)) return {
693
- text: label ?? link,
694
- link,
695
- tag,
696
- context
697
- };
698
- return {
699
- text: label ?? link,
700
- link: addRoutePrefix(workDir, docsDir, link),
701
- tag,
702
- context
703
- };
841
+ if ('items' in metaItem && Array.isArray(metaItem.items) && metaItem.items.length > 0) {
842
+ const { label, link, context, items, tag } = metaItem;
843
+ return {
844
+ text: label ?? link,
845
+ context,
846
+ tag,
847
+ link,
848
+ items: items.map((subItem)=>metaCustomLinkItemToSidebarItem(subItem, workDir, docsDir))
849
+ };
850
+ }
851
+ if ('link' in metaItem && 'string' == typeof metaItem.link) {
852
+ const { label, link, context, tag } = metaItem;
853
+ if ((0, shared_.isExternalUrl)(link)) return {
854
+ text: label ?? link,
855
+ link,
856
+ tag,
857
+ context
858
+ };
859
+ return {
860
+ text: label ?? link,
861
+ link: addRoutePrefix(workDir, docsDir, link),
862
+ tag,
863
+ context
864
+ };
865
+ }
866
+ const { label } = metaItem;
867
+ throw new Error(`The custom link "${label}" does not have a link, please check it in "${(0, external_node_path_.join)(workDir, '_meta.json')}".`);
704
868
  }
705
869
  function metaDividerToSidebarItem(metaItem) {
706
870
  const { type } = metaItem;
@@ -725,7 +889,7 @@ async function scanSideMeta(workDir, docsDir, extensions) {
725
889
  }
726
890
  async function scanNav(workDir, docsDir) {
727
891
  let navConfig;
728
- const rootNavJson = node_path.resolve(workDir, '_nav.json');
892
+ const rootNavJson = external_node_path_["default"].resolve(workDir, '_nav.json');
729
893
  try {
730
894
  navConfig = await utils_readJson(rootNavJson);
731
895
  } catch (e) {
@@ -734,15 +898,15 @@ async function scanNav(workDir, docsDir) {
734
898
  }
735
899
  navConfig.forEach((navItem)=>{
736
900
  if ('items' in navItem) navItem.items.forEach((item)=>{
737
- if ('link' in item && !isExternalUrl(item.link)) item.link = addRoutePrefix(workDir, docsDir, item.link);
901
+ if ('link' in item && !(0, shared_.isExternalUrl)(item.link)) item.link = addRoutePrefix(workDir, docsDir, item.link);
738
902
  });
739
- if ('link' in navItem && !isExternalUrl(navItem.link)) navItem.link = addRoutePrefix(workDir, docsDir, navItem.link);
903
+ if ('link' in navItem && !(0, shared_.isExternalUrl)(navItem.link)) navItem.link = addRoutePrefix(workDir, docsDir, navItem.link);
740
904
  });
741
905
  return navConfig;
742
906
  }
743
907
  async function walk(workDir, docsDir, extensions) {
744
- const rootNavJson = node_path.resolve(workDir, '_nav.json');
745
- const rootMetaJson = node_path.resolve(workDir, '_meta.json');
908
+ const rootNavJson = external_node_path_["default"].resolve(workDir, '_nav.json');
909
+ const rootMetaJson = external_node_path_["default"].resolve(workDir, '_meta.json');
746
910
  const isRootNavJsonExist = await pathExists(rootNavJson);
747
911
  const isRootMetaJsonExist = await pathExists(rootMetaJson);
748
912
  if (isRootMetaJsonExist) {
@@ -751,14 +915,14 @@ async function walk(workDir, docsDir, extensions) {
751
915
  }
752
916
  if (isRootNavJsonExist) {
753
917
  const navConfig = await scanNav(workDir, docsDir);
754
- const subDirs = (await Promise.all((await node_fs_promises.readdir(workDir)).map((v)=>node_fs_promises.stat(node_path.join(workDir, v)).then((s)=>{
918
+ const subDirs = (await Promise.all((await node_fs_promises.readdir(workDir)).map((v)=>node_fs_promises.stat(external_node_path_["default"].join(workDir, v)).then((s)=>{
755
919
  if (s.isDirectory() && 'node_modules' !== v) return v;
756
920
  return false;
757
921
  })))).filter(Boolean);
758
922
  const sidebarConfig = {};
759
923
  await Promise.all(subDirs.map(async (subDir)=>{
760
924
  const sidebarGroupKey = addRoutePrefix(workDir, docsDir, subDir);
761
- sidebarConfig[sidebarGroupKey] = await scanSideMeta(node_path.join(workDir, subDir), docsDir, extensions);
925
+ sidebarConfig[sidebarGroupKey] = await scanSideMeta(external_node_path_["default"].join(workDir, subDir), docsDir, extensions);
762
926
  }));
763
927
  if (isRootMetaJsonExist) {
764
928
  const rootMetaConfig = await scanSideMeta(workDir, docsDir, extensions);
@@ -793,8 +957,8 @@ function combineWalkResult(walks, versions) {
793
957
  }
794
958
  function processLocales(langs, versions, root, extensions) {
795
959
  return Promise.all(langs.map(async (lang)=>{
796
- const walks = versions.length ? await Promise.all(versions.map((version)=>walk(node_path.join(root, version, lang), root, extensions))) : [
797
- await walk(node_path.join(root, lang), root, extensions)
960
+ const walks = versions.length ? await Promise.all(versions.map((version)=>walk(external_node_path_["default"].join(root, version, lang), root, extensions))) : [
961
+ await walk(external_node_path_["default"].join(root, lang), root, extensions)
798
962
  ];
799
963
  return combineWalkResult(walks, versions);
800
964
  }));
@@ -821,7 +985,7 @@ async function modifyConfigWithAutoNavSide(config) {
821
985
  logger.error("`lang` is configured but `locales` not, thus `auto-nav-sidebar` can not auto generate navbar level config correctly!\nplease check your config file");
822
986
  return config;
823
987
  }
824
- const walks = versions.length ? await Promise.all(versions.map((version)=>walk(node_path.join(config.root, version), config.root, extensions))) : [
988
+ const walks = versions.length ? await Promise.all(versions.map((version)=>walk(external_node_path_["default"].join(config.root, version), config.root, extensions))) : [
825
989
  await walk(config.root, config.root, extensions)
826
990
  ];
827
991
  const combined = combineWalkResult(walks, versions);
@@ -832,11 +996,12 @@ async function modifyConfigWithAutoNavSide(config) {
832
996
  }
833
997
  return config;
834
998
  }
999
+ var external_node_fs_ = __webpack_require__("node:fs");
835
1000
  let flattenMdxContent_resolver;
836
1001
  let startFlatten = false;
837
1002
  const processor = createProcessor();
838
1003
  const { CachedInputFileSystem, ResolverFactory } = enhanced_resolve;
839
- const fileSystem = node_fs;
1004
+ const fileSystem = external_node_fs_["default"];
840
1005
  async function resolveDepPath(importPath, importer, alias) {
841
1006
  if (!flattenMdxContent_resolver) flattenMdxContent_resolver = ResolverFactory.createResolver({
842
1007
  fileSystem: new CachedInputFileSystem(fileSystem, 0),
@@ -893,12 +1058,12 @@ async function flattenMdxContent(content, basePath, alias) {
893
1058
  const importPath = importNode.source.value;
894
1059
  let absoluteImportPath;
895
1060
  try {
896
- absoluteImportPath = await resolveDepPath(importPath, node_path.dirname(basePath), alias);
1061
+ absoluteImportPath = await resolveDepPath(importPath, external_node_path_["default"].dirname(basePath), alias);
897
1062
  } catch (_e) {
898
1063
  continue;
899
1064
  }
900
- if (MDX_OR_MD_REGEXP.test(absoluteImportPath)) {
901
- const importedContent = node_fs.readFileSync(absoluteImportPath, 'utf-8');
1065
+ if (shared_.MDX_OR_MD_REGEXP.test(absoluteImportPath)) {
1066
+ const importedContent = external_node_fs_["default"].readFileSync(absoluteImportPath, 'utf-8');
902
1067
  const { flattenContent: replacedValue, deps: subDeps } = await flattenMdxContent(importedContent, absoluteImportPath, alias);
903
1068
  result = result.replace(new RegExp(`import\\s+${id}\\s+from\\s+['"](${importPath})['"];?`), '').replace(new RegExp(`<${id}\\s*/>`, 'g'), ()=>replacedValue);
904
1069
  deps.push(...subDeps, absoluteImportPath);
@@ -920,7 +1085,7 @@ function applyReplaceRulesToNestedObject(obj, replaceRules) {
920
1085
  return obj;
921
1086
  }
922
1087
  async function getPageIndexInfoByRoute(route, options) {
923
- const { alias, domain, replaceRules, root, searchCodeBlocks } = options;
1088
+ const { alias, replaceRules, root, searchCodeBlocks } = options;
924
1089
  const defaultIndexInfo = {
925
1090
  title: '',
926
1091
  content: '',
@@ -929,13 +1094,12 @@ async function getPageIndexInfoByRoute(route, options) {
929
1094
  routePath: route.routePath,
930
1095
  lang: route.lang,
931
1096
  toc: [],
932
- domain,
933
1097
  frontmatter: {},
934
1098
  version: route.version,
935
1099
  _filepath: route.absolutePath,
936
- _relativePath: node_path.relative(root, route.absolutePath).split(node_path.sep).join('/')
1100
+ _relativePath: external_node_path_["default"].relative(root, route.absolutePath).split(external_node_path_["default"].sep).join('/')
937
1101
  };
938
- if (!MDX_OR_MD_REGEXP.test(route.absolutePath)) return defaultIndexInfo;
1102
+ if (!shared_.MDX_OR_MD_REGEXP.test(route.absolutePath)) return defaultIndexInfo;
939
1103
  let content = await node_fs_promises.readFile(route.absolutePath, 'utf8');
940
1104
  const { frontmatter, content: contentWithoutFrontMatter } = loadFrontMatter(content, route.absolutePath, root);
941
1105
  applyReplaceRulesToNestedObject(frontmatter, replaceRules);
@@ -1033,7 +1197,7 @@ var types_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
1033
1197
  RuntimeModuleID["RuntimeConfig"] = "virtual-runtime-config";
1034
1198
  return RuntimeModuleID;
1035
1199
  }({});
1036
- const DEFAULT_I18N_SOURCE = join(process.cwd(), 'i18n.json');
1200
+ const DEFAULT_I18N_SOURCE = (0, external_node_path_.join)(process.cwd(), 'i18n.json');
1037
1201
  function getI18nData(docConfig) {
1038
1202
  const { i18nSourcePath = DEFAULT_I18N_SOURCE } = docConfig;
1039
1203
  try {
@@ -1065,9 +1229,9 @@ function normalizeThemeConfig(docConfig) {
1065
1229
  const locales = siteLocales ?? (themeConfig?.locales || []);
1066
1230
  const i18nTextData = getI18nData(docConfig);
1067
1231
  const normalizeLinkPrefix = (link = '', currentLang = '')=>{
1068
- const normalizedLink = slash(link);
1069
- if (!currentLang || !link || normalizedLink.startsWith(`/${currentLang}`) || isExternalUrl(normalizedLink) || hasMultiVersion) return normalizedLink;
1070
- return lang === currentLang ? normalizedLink : `/${currentLang}${addLeadingSlash(normalizedLink)}`;
1232
+ const normalizedLink = (0, shared_.slash)(link);
1233
+ if (!currentLang || !link || normalizedLink.startsWith(`/${currentLang}`) || (0, shared_.isExternalUrl)(normalizedLink) || hasMultiVersion) return normalizedLink;
1234
+ return lang === currentLang ? normalizedLink : `/${currentLang}${(0, shared_.addLeadingSlash)(normalizedLink)}`;
1071
1235
  };
1072
1236
  const getI18nText = (key = '', currentLang = '')=>{
1073
1237
  const text = i18nTextData[key]?.[currentLang];
@@ -1164,17 +1328,15 @@ async function siteDataVMPlugin(context) {
1164
1328
  if (tempSearchObj) tempSearchObj.searchHooks = void 0;
1165
1329
  const replaceRules = userConfig?.replaceRules || [];
1166
1330
  const searchConfig = userConfig?.search || {};
1167
- const domain = searchConfig?.mode === 'remote' ? searchConfig.domain ?? '' : '';
1168
1331
  const searchCodeBlocks = 'codeBlocks' in searchConfig ? Boolean(searchConfig.codeBlocks) : true;
1169
1332
  const pages = await extractPageData(routeService, {
1170
1333
  replaceRules,
1171
1334
  alias,
1172
- domain,
1173
1335
  root: userDocRoot,
1174
1336
  searchCodeBlocks
1175
1337
  });
1176
1338
  await pluginDriver.modifySearchIndexData(pages);
1177
- const versioned = userConfig.search && 'remote' !== userConfig.search.mode && userConfig.search.versioned;
1339
+ const versioned = 'boolean' != typeof userConfig.search && userConfig.search?.versioned;
1178
1340
  const groupedPages = groupBy(pages, (page)=>{
1179
1341
  if (page.frontmatter?.pageType === 'home') return 'noindex';
1180
1342
  const version = versioned ? page.version : '';
@@ -1193,7 +1355,7 @@ async function siteDataVMPlugin(context) {
1193
1355
  await node_fs_promises.mkdir(constants_TEMP_DIR, {
1194
1356
  recursive: true
1195
1357
  });
1196
- await node_fs_promises.writeFile(node_path.join(constants_TEMP_DIR, `${SEARCH_INDEX_NAME}${indexVersion}${indexLang}.${indexHash}.json`), stringifiedIndex);
1358
+ await node_fs_promises.writeFile(external_node_path_["default"].join(constants_TEMP_DIR, `${shared_.SEARCH_INDEX_NAME}${indexVersion}${indexLang}.${indexHash}.json`), stringifiedIndex);
1197
1359
  }));
1198
1360
  await Promise.all(pages.map(async (pageData)=>pluginDriver.extendPageData(pageData)));
1199
1361
  const siteData = {
@@ -1215,8 +1377,8 @@ async function siteDataVMPlugin(context) {
1215
1377
  mode: 'local'
1216
1378
  },
1217
1379
  pages: pages.map((page)=>{
1218
- const { content, domain, _filepath, _html, _flattenContent, ...rest } = page;
1219
- return constants_isProduction() ? rest : {
1380
+ const { content, _filepath, _html, _flattenContent, ...rest } = page;
1381
+ return isProduction() ? rest : {
1220
1382
  ...rest,
1221
1383
  _filepath
1222
1384
  };
@@ -1308,7 +1470,7 @@ const runtimeConfigVMPlugin = (context)=>({
1308
1470
  [types_RuntimeModuleID.RuntimeConfig]: ()=>{
1309
1471
  const { config } = context;
1310
1472
  const { base } = config;
1311
- const normalizedBase = normalizeSlash(base ?? '/');
1473
+ const normalizedBase = (0, shared_.normalizeSlash)(base ?? '/');
1312
1474
  return `export const base = ${JSON.stringify(normalizedBase)};`;
1313
1475
  }
1314
1476
  });
@@ -1324,56 +1486,41 @@ async function writeSearchIndex(config) {
1324
1486
  if (config?.search === false) return;
1325
1487
  const cwd = process.cwd();
1326
1488
  const searchIndexFiles = await node_fs_promises.readdir(constants_TEMP_DIR);
1327
- const outDir = config?.outDir ?? join(cwd, OUTPUT_DIR);
1328
- const targetDir = join(outDir, 'static');
1489
+ const outDir = config?.outDir ?? (0, external_node_path_.join)(cwd, OUTPUT_DIR);
1490
+ const targetDir = (0, external_node_path_.join)(outDir, 'static');
1329
1491
  await node_fs_promises.mkdir(targetDir, {
1330
1492
  recursive: true
1331
1493
  });
1332
1494
  let searchIndexData = '[]';
1333
1495
  let scanning = false;
1334
1496
  for (const searchIndexFile of searchIndexFiles){
1335
- if (!searchIndexFile.includes(SEARCH_INDEX_NAME) || !searchIndexFile.endsWith('.json')) continue;
1336
- const source = join(constants_TEMP_DIR, searchIndexFile);
1337
- const target = join(targetDir, searchIndexFile);
1338
- const searchIndex = await node_fs_promises.readFile(join(constants_TEMP_DIR, searchIndexFile), 'utf-8');
1497
+ if (!searchIndexFile.includes(shared_.SEARCH_INDEX_NAME) || !searchIndexFile.endsWith('.json')) continue;
1498
+ const source = (0, external_node_path_.join)(constants_TEMP_DIR, searchIndexFile);
1499
+ const target = (0, external_node_path_.join)(targetDir, searchIndexFile);
1500
+ const searchIndex = await node_fs_promises.readFile((0, external_node_path_.join)(constants_TEMP_DIR, searchIndexFile), 'utf-8');
1339
1501
  searchIndexData = `${searchIndexData.slice(0, -1)}${scanning ? ',' : ''}${searchIndex.slice(1)}`;
1340
1502
  await node_fs_promises.rename(source, target);
1341
1503
  scanning = true;
1342
1504
  }
1343
- if (constants_isProduction() && isSCM() && config?.search?.mode === 'remote') {
1344
- const { apiUrl, indexName } = config.search;
1345
- try {
1346
- await fetch(`${apiUrl}?index=${indexName}`, {
1347
- method: 'PUT',
1348
- body: searchIndexData,
1349
- headers: {
1350
- 'Content-Type': 'application/json'
1351
- }
1352
- });
1353
- logger.info(picocolors.green(`[doc-tools] Search index uploaded to ${apiUrl}, indexName: ${indexName}`));
1354
- } catch (e) {
1355
- logger.info(picocolors.red(`[doc-tools] Upload search index \`${indexName}\` failed:\n ${e}`));
1356
- }
1357
- }
1358
1505
  }
1359
1506
  function serveSearchIndexMiddleware(config) {
1360
1507
  return (req, res, next)=>{
1361
- const searchIndexRequestMatch = `/${SEARCH_INDEX_NAME}.`;
1508
+ const searchIndexRequestMatch = `/${shared_.SEARCH_INDEX_NAME}.`;
1362
1509
  if (req.url?.includes(searchIndexRequestMatch)) {
1363
1510
  res.setHeader('Content-Type', 'application/json');
1364
- const outDir = config?.outDir ?? join(process.cwd(), OUTPUT_DIR);
1511
+ const outDir = config?.outDir ?? (0, external_node_path_.join)(process.cwd(), OUTPUT_DIR);
1365
1512
  const searchIndexFile = req.url.split('/').pop();
1366
- createReadStream(join(outDir, 'static', searchIndexFile), 'utf-8').pipe(res, {
1513
+ (0, external_node_fs_.createReadStream)((0, external_node_path_.join)(outDir, 'static', searchIndexFile), 'utf-8').pipe(res, {
1367
1514
  end: true
1368
1515
  });
1369
1516
  } else next?.();
1370
1517
  };
1371
1518
  }
1372
- async function pMap(iterable, mapper, { concurrency = Number.POSITIVE_INFINITY, stopOnError = true, signal } = {}) {
1519
+ async function pMap(iterable, mapper, { concurrency = 1 / 0, stopOnError = true, signal } = {}) {
1373
1520
  return new Promise((resolve_, reject_)=>{
1374
1521
  if (void 0 === iterable[Symbol.iterator] && void 0 === iterable[Symbol.asyncIterator]) throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
1375
1522
  if ('function' != typeof mapper) throw new TypeError('Mapper function is required');
1376
- if (!(Number.isSafeInteger(concurrency) && concurrency >= 1 || concurrency === Number.POSITIVE_INFINITY)) throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
1523
+ if (!(Number.isSafeInteger(concurrency) && concurrency >= 1 || concurrency === 1 / 0)) throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
1377
1524
  const result = [];
1378
1525
  const errors = [];
1379
1526
  const skippedIndexesMap = new Map();
@@ -1489,7 +1636,7 @@ async function renderPages(routeService, config, pluginDriver, ssrBundlePath, ht
1489
1636
  const startTime = Date.now();
1490
1637
  let render;
1491
1638
  try {
1492
- const { default: ssrExports } = await import(pathToFileURL(ssrBundlePath).toString());
1639
+ const { default: ssrExports } = await import((0, external_node_url_.pathToFileURL)(ssrBundlePath).toString());
1493
1640
  render = await ssrExports.render;
1494
1641
  } catch (e) {
1495
1642
  if (e instanceof Error) {
@@ -1530,7 +1677,7 @@ async function renderPages(routeService, config, pluginDriver, ssrBundlePath, ht
1530
1677
  ].join(''));
1531
1678
  const html = await transformHtmlTemplate(head, replacedHtmlTemplate);
1532
1679
  const normalizeHtmlFilePath = (path)=>{
1533
- const normalizedBase = `${normalizeSlash(config?.base || '/')}/`;
1680
+ const normalizedBase = `${(0, shared_.normalizeSlash)(config?.base || '/')}/`;
1534
1681
  if (path.endsWith('/')) return `${path}index.html`.replace(normalizedBase, '');
1535
1682
  return `${path}.html`.replace(normalizedBase, '');
1536
1683
  };
@@ -1595,14 +1742,14 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1595
1742
  }
1596
1743
  if (hasError) return;
1597
1744
  const distPath = environment.distPath;
1598
- const ssgFolderPath = join(distPath, NODE_SSG_BUNDLE_FOLDER);
1599
- const mainCjsAbsolutePath = join(ssgFolderPath, NODE_SSG_BUNDLE_NAME);
1745
+ const ssgFolderPath = (0, external_node_path_.join)(distPath, NODE_SSG_BUNDLE_FOLDER);
1746
+ const mainCjsAbsolutePath = (0, external_node_path_.join)(ssgFolderPath, NODE_SSG_BUNDLE_NAME);
1600
1747
  await mkdir(ssgFolderPath, {
1601
1748
  recursive: true
1602
1749
  });
1603
1750
  await Promise.all(Object.entries(assets).map(async ([assetName, assetSource])=>{
1604
1751
  if (assetName.startsWith(`${NODE_SSG_BUNDLE_FOLDER}/`)) {
1605
- const fileAbsolutePath = join(distPath, assetName);
1752
+ const fileAbsolutePath = (0, external_node_path_.join)(distPath, assetName);
1606
1753
  await writeFile(fileAbsolutePath, assetSource.source().toString());
1607
1754
  compilation.deleteAsset(assetName);
1608
1755
  }
@@ -1612,7 +1759,7 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1612
1759
  };
1613
1760
  await indexHtmlEmittedInWeb;
1614
1761
  await renderPages(routeService, config, pluginDriver, mainCjsAbsolutePath, htmlTemplate, emitAsset);
1615
- if (!isDebugMode()) await rm(ssgFolderPath, {
1762
+ if (!(0, shared_.isDebugMode)()) await rm(ssgFolderPath, {
1616
1763
  recursive: true
1617
1764
  });
1618
1765
  });
@@ -1622,9 +1769,9 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1622
1769
  const { CachedInputFileSystem: detectReactVersion_CachedInputFileSystem, ResolverFactory: detectReactVersion_ResolverFactory } = enhanced_resolve;
1623
1770
  async function detectPackageMajorVersion(name) {
1624
1771
  const cwd = process.cwd();
1625
- const pkgPath = node_path.join(cwd, 'node_modules', name);
1772
+ const pkgPath = external_node_path_["default"].join(cwd, 'node_modules', name);
1626
1773
  if (await pathExists(pkgPath)) {
1627
- const pkgJson = await readJson(node_path.join(pkgPath, 'package.json'));
1774
+ const pkgJson = await readJson(external_node_path_["default"].join(pkgPath, 'package.json'));
1628
1775
  const version = Number(pkgJson.version?.split('.')[0]);
1629
1776
  return version;
1630
1777
  }
@@ -1636,7 +1783,7 @@ async function detectReactVersion() {
1636
1783
  async function resolveReactRouterDomAlias() {
1637
1784
  const alias = {};
1638
1785
  const resolver = detectReactVersion_ResolverFactory.createResolver({
1639
- fileSystem: new detectReactVersion_CachedInputFileSystem(node_fs, 0),
1786
+ fileSystem: new detectReactVersion_CachedInputFileSystem(external_node_fs_["default"], 0),
1640
1787
  mainFields: [
1641
1788
  'browser',
1642
1789
  'module',
@@ -1676,7 +1823,7 @@ async function resolveReactAlias(reactVersion, isSSR) {
1676
1823
  ];
1677
1824
  const alias = {};
1678
1825
  const resolver = detectReactVersion_ResolverFactory.createResolver({
1679
- fileSystem: new detectReactVersion_CachedInputFileSystem(node_fs, 0),
1826
+ fileSystem: new detectReactVersion_CachedInputFileSystem(external_node_fs_["default"], 0),
1680
1827
  extensions: [
1681
1828
  '.js'
1682
1829
  ],
@@ -1708,15 +1855,15 @@ async function resolveReactAlias(reactVersion, isSSR) {
1708
1855
  return alias;
1709
1856
  }
1710
1857
  const detectCustomIcon = async (customThemeDir)=>{
1711
- const assetsDir = node_path.join(customThemeDir, 'assets');
1858
+ const assetsDir = external_node_path_["default"].join(customThemeDir, 'assets');
1712
1859
  const alias = {};
1713
- if (!existsSync(assetsDir)) return alias;
1860
+ if (!(0, external_node_fs_.existsSync)(assetsDir)) return alias;
1714
1861
  const files = await glob('*.svg', {
1715
1862
  cwd: assetsDir
1716
1863
  });
1717
1864
  files.forEach((file)=>{
1718
- const name = node_path.basename(file, '.svg');
1719
- alias[`@theme-assets/${name}`] = node_path.join(assetsDir, file);
1865
+ const name = external_node_path_["default"].basename(file, '.svg');
1866
+ alias[`@theme-assets/${name}`] = external_node_path_["default"].join(assetsDir, file);
1720
1867
  });
1721
1868
  return alias;
1722
1869
  };
@@ -1750,21 +1897,21 @@ function getSocialIcons(socialLinks = []) {
1750
1897
  return icons;
1751
1898
  }
1752
1899
  function isPluginIncluded(config, pluginName) {
1753
- return Boolean(config.builderPlugins?.some((plugin)=>plugin.name === pluginName) || config.builderConfig?.plugins?.some((plugin)=>plugin && plugin.name === pluginName));
1900
+ return Boolean(config.builderConfig?.plugins?.some((plugin)=>plugin && plugin.name === pluginName));
1754
1901
  }
1755
1902
  async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver) {
1756
1903
  const cwd = process.cwd();
1757
- const CUSTOM_THEME_DIR = config?.themeDir ?? node_path.join(process.cwd(), 'theme');
1904
+ const CUSTOM_THEME_DIR = config?.themeDir ?? external_node_path_["default"].join(process.cwd(), 'theme');
1758
1905
  const outDir = config?.outDir ?? OUTPUT_DIR;
1759
1906
  const DEFAULT_THEME = require.resolve('@rspress/theme-default');
1760
1907
  const base = config?.base ?? '';
1761
- const assetPrefix = constants_isProduction() ? removeTrailingSlash(config?.builderConfig?.output?.assetPrefix ?? base) : '';
1908
+ const assetPrefix = isProduction() ? (0, shared_.removeTrailingSlash)(config?.builderConfig?.output?.assetPrefix ?? base) : '';
1762
1909
  const reactVersion = await detectReactVersion();
1763
1910
  const normalizeIcon = (icon)=>{
1764
1911
  if (!icon) return;
1765
1912
  icon = icon.toString();
1766
- if (icon.startsWith('file://')) icon = fileURLToPath(icon);
1767
- else if (node_path.isAbsolute(icon)) return node_path.join(userDocRoot, PUBLIC_DIR, icon);
1913
+ if (icon.startsWith('file://')) icon = (0, external_node_url_.fileURLToPath)(icon);
1914
+ else if (external_node_path_["default"].isAbsolute(icon)) return external_node_path_["default"].join(userDocRoot, PUBLIC_DIR, icon);
1768
1915
  return icon;
1769
1916
  };
1770
1917
  await hintThemeBreakingChange(CUSTOM_THEME_DIR);
@@ -1807,12 +1954,12 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1807
1954
  ] : []
1808
1955
  ],
1809
1956
  server: {
1810
- port: !constants_isProduction() && process.env.PORT ? Number(process.env.PORT) : void 0,
1957
+ port: !isProduction() && process.env.PORT ? Number(process.env.PORT) : void 0,
1811
1958
  publicDir: {
1812
- name: node_path.join(userDocRoot, PUBLIC_DIR)
1959
+ name: external_node_path_["default"].join(userDocRoot, PUBLIC_DIR)
1813
1960
  },
1814
1961
  ...base.length > 0 ? {
1815
- base: removeTrailingSlash(base)
1962
+ base: (0, shared_.removeTrailingSlash)(base)
1816
1963
  } : {}
1817
1964
  },
1818
1965
  dev: {
@@ -1850,7 +1997,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1850
1997
  CUSTOM_THEME_DIR,
1851
1998
  DEFAULT_THEME
1852
1999
  ],
1853
- '@theme-assets': node_path.join(DEFAULT_THEME, '../assets'),
2000
+ '@theme-assets': external_node_path_["default"].join(DEFAULT_THEME, '../assets'),
1854
2001
  '@rspress/core': PACKAGE_ROOT,
1855
2002
  'react-lazy-with-preload': require.resolve('react-lazy-with-preload')
1856
2003
  }
@@ -1858,7 +2005,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1858
2005
  source: {
1859
2006
  include: [
1860
2007
  PACKAGE_ROOT,
1861
- node_path.join(cwd, 'node_modules', RSPRESS_TEMP_DIR)
2008
+ external_node_path_["default"].join(cwd, 'node_modules', shared_.RSPRESS_TEMP_DIR)
1862
2009
  ],
1863
2010
  define: {
1864
2011
  'process.env.TEST': JSON.stringify(process.env.TEST),
@@ -1866,11 +2013,23 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1866
2013
  }
1867
2014
  },
1868
2015
  performance: {
1869
- buildCache: {
1870
- buildDependencies: [
1871
- pluginDriver.getConfigFilePath()
1872
- ]
1873
- },
2016
+ ...'false' !== process.env.RSPRESS_PERSISTENT_CACHE ? {
2017
+ buildCache: {
2018
+ buildDependencies: [
2019
+ pluginDriver.getConfigFilePath()
2020
+ ],
2021
+ cacheDigest: [
2022
+ routeService.generateRoutesCode(),
2023
+ JSON.stringify(config.themeConfig?.locales?.map((i)=>({
2024
+ nav: i.nav,
2025
+ sidebar: i.sidebar
2026
+ })) ?? {
2027
+ nav: config.themeConfig?.nav,
2028
+ sidebar: config.themeConfig?.sidebar
2029
+ })
2030
+ ]
2031
+ }
2032
+ } : {},
1874
2033
  chunkSplit: {
1875
2034
  override: {
1876
2035
  cacheGroups: {
@@ -1891,7 +2050,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1891
2050
  const jsModuleRule = chain.module.rule(CHAIN_ID.RULE.JS);
1892
2051
  const swcLoaderOptions = jsModuleRule.use(CHAIN_ID.USE.SWC).get('options');
1893
2052
  const checkDeadLinks = (config?.markdown?.checkDeadLinks && !isServer) ?? false;
1894
- chain.module.rule('MDX').type("javascript/auto").test(MDX_OR_MD_REGEXP).resolve.merge({
2053
+ chain.module.rule('MDX').type("javascript/auto").test(shared_.MDX_OR_MD_REGEXP).resolve.merge({
1895
2054
  conditionNames: jsModuleRule.resolve.conditionNames.values(),
1896
2055
  mainFields: jsModuleRule.resolve.mainFields.values()
1897
2056
  }).end().oneOf('MDXCompile').use('builtin:swc-loader').loader('builtin:swc-loader').options(swcLoaderOptions).end().use('mdx-loader').loader(require.resolve('./loader.js')).options({
@@ -1905,7 +2064,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1905
2064
  options[0] ??= {};
1906
2065
  options[0].include = [
1907
2066
  /\.([cm]js|[jt]sx?|flow)$/i,
1908
- MDX_OR_MD_REGEXP
2067
+ shared_.MDX_OR_MD_REGEXP
1909
2068
  ];
1910
2069
  return options;
1911
2070
  });
@@ -1930,10 +2089,10 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1930
2089
  },
1931
2090
  source: {
1932
2091
  entry: {
1933
- index: enableSSG && constants_isProduction() ? SSR_CLIENT_ENTRY : CSR_CLIENT_ENTRY
2092
+ index: enableSSG && isProduction() ? SSR_CLIENT_ENTRY : CSR_CLIENT_ENTRY
1934
2093
  },
1935
2094
  preEntry: [
1936
- node_path.join(DEFAULT_THEME, '../styles/index.js'),
2095
+ external_node_path_["default"].join(DEFAULT_THEME, '../styles/index.js'),
1937
2096
  'virtual-global-styles'
1938
2097
  ],
1939
2098
  define: {
@@ -1978,33 +2137,32 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1978
2137
  }
1979
2138
  };
1980
2139
  }
1981
- async function initRsbuild(rootDir, _config, pluginDriver, enableSSG, extraRsbuildConfig) {
2140
+ async function initRsbuild(rootDir, config, pluginDriver, enableSSG, extraRsbuildConfig) {
1982
2141
  const cwd = process.cwd();
1983
- const userDocRoot = node_path.resolve(rootDir || _config?.root || cwd);
1984
- const builderPlugins = _config?.builderPlugins ?? [];
1985
- const runtimeTempDir = node_path.join(RSPRESS_TEMP_DIR, 'runtime');
1986
- const runtimeAbsTempDir = node_path.join(cwd, 'node_modules', runtimeTempDir);
2142
+ const userDocRoot = external_node_path_["default"].resolve(rootDir || config?.root || cwd);
2143
+ const runtimeTempDir = external_node_path_["default"].join(shared_.RSPRESS_TEMP_DIR, 'runtime');
2144
+ const runtimeAbsTempDir = external_node_path_["default"].join(cwd, 'node_modules', runtimeTempDir);
1987
2145
  await node_fs_promises.mkdir(runtimeAbsTempDir, {
1988
2146
  recursive: true
1989
2147
  });
1990
2148
  const routeService = await RouteService.create({
1991
- config: _config,
2149
+ config: config,
1992
2150
  runtimeTempDir: runtimeAbsTempDir,
1993
2151
  scanDir: userDocRoot,
1994
2152
  pluginDriver
1995
2153
  });
1996
- const config = await modifyConfigWithAutoNavSide(_config);
2154
+ const mergedConfig = await modifyConfigWithAutoNavSide(config);
2155
+ hintBuilderPluginsBreakingChange(mergedConfig);
1997
2156
  const { createRsbuild, mergeRsbuildConfig } = await import("@rsbuild/core");
1998
- const internalRsbuildConfig = await createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver);
2157
+ const internalRsbuildConfig = await createInternalBuildConfig(userDocRoot, mergedConfig, enableSSG, routeService, pluginDriver);
1999
2158
  const rsbuild = await createRsbuild({
2000
2159
  callerName: 'rspress',
2001
- rsbuildConfig: mergeRsbuildConfig(internalRsbuildConfig, ...pluginDriver.getPlugins()?.map((plugin)=>plugin.builderConfig ?? {}) || [], config?.builderConfig || {}, extraRsbuildConfig || {})
2160
+ rsbuildConfig: mergeRsbuildConfig(internalRsbuildConfig, ...pluginDriver.getPlugins()?.map((plugin)=>plugin.builderConfig ?? {}) || [], mergedConfig.builderConfig || {}, extraRsbuildConfig || {})
2002
2161
  });
2003
- rsbuild.addPlugins(builderPlugins);
2004
2162
  return rsbuild;
2005
2163
  }
2006
2164
  function checkLanguageParity_normalizePath(filePath) {
2007
- return filePath.split(node_path.sep).join('/');
2165
+ return filePath.split(external_node_path_["default"].sep).join('/');
2008
2166
  }
2009
2167
  async function getAllMarkdownFilesFrom(dirPath) {
2010
2168
  const files = await node_fs_promises.readdir(dirPath, {
@@ -2012,26 +2170,26 @@ async function getAllMarkdownFilesFrom(dirPath) {
2012
2170
  });
2013
2171
  const allFiles = [];
2014
2172
  for (const file of files){
2015
- const fullPath = node_path.join(dirPath, file.name);
2173
+ const fullPath = external_node_path_["default"].join(dirPath, file.name);
2016
2174
  if (file.isDirectory()) {
2017
2175
  const nestedFiles = await getAllMarkdownFilesFrom(fullPath);
2018
2176
  allFiles.push(...nestedFiles);
2019
2177
  } else if ([
2020
2178
  '.md',
2021
2179
  '.mdx'
2022
- ].includes(node_path.extname(file.name))) allFiles.push(fullPath);
2180
+ ].includes(external_node_path_["default"].extname(file.name))) allFiles.push(fullPath);
2023
2181
  }
2024
2182
  return allFiles;
2025
2183
  }
2026
2184
  async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs, fileLangMap) {
2027
- const langDirPath = node_path.join(contentPath, lang);
2028
- const langModuleDir = node_path.join(langDirPath, includedDir);
2185
+ const langDirPath = external_node_path_["default"].join(contentPath, lang);
2186
+ const langModuleDir = external_node_path_["default"].join(langDirPath, includedDir);
2029
2187
  try {
2030
2188
  const moduleDirStats = await node_fs_promises.stat(langModuleDir);
2031
2189
  if (!moduleDirStats.isDirectory()) return fileLangMap;
2032
2190
  const files = await getAllMarkdownFilesFrom(langModuleDir);
2033
2191
  for (const file of files){
2034
- const relativePath = checkLanguageParity_normalizePath(node_path.relative(langDirPath, file));
2192
+ const relativePath = checkLanguageParity_normalizePath(external_node_path_["default"].relative(langDirPath, file));
2035
2193
  if (excludedDirs.some((excludedDir)=>{
2036
2194
  const isFilePath = /\.(md|mdx)$/.test(excludedDir);
2037
2195
  return relativePath.includes(excludedDir + (isFilePath ? '' : '/'));
@@ -2049,7 +2207,7 @@ async function collectModuleFiles(contentPath, lang, includedDir, excludedDirs,
2049
2207
  async function checkLanguageParity(config) {
2050
2208
  if (!config?.languageParity || false === config.languageParity.enabled) return;
2051
2209
  logger.info('Checking language parity...');
2052
- const contentPath = node_path.resolve(config.root);
2210
+ const contentPath = external_node_path_["default"].resolve(config.root);
2053
2211
  const includedDirs = config.languageParity.include?.length ? config.languageParity.include : [
2054
2212
  ''
2055
2213
  ];
@@ -2065,7 +2223,7 @@ async function checkLanguageParity(config) {
2065
2223
  for (const [baseName, langs] of Object.entries(curFileLangMap)){
2066
2224
  const missingLangs = supportedLanguages.filter((lang)=>!langs.has(lang));
2067
2225
  missingLangs.forEach((lang)=>{
2068
- const missingPath = node_path.join(lang, baseName);
2226
+ const missingPath = external_node_path_["default"].join(lang, baseName);
2069
2227
  missingLanguagesFile.push(missingPath);
2070
2228
  });
2071
2229
  }
@@ -2182,7 +2340,7 @@ function normalizeLink_checkDeadLinks(internalLinks, filePath, routeService) {
2182
2340
  const cleanLinkPath = linkToRoutePath(link);
2183
2341
  if (!cleanLinkPath) return;
2184
2342
  if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
2185
- if (!routeService.isExistRoute(removeTrailingSlash(cleanLinkPath)) && !routeService.isExistRoute(addTrailingSlash(cleanLinkPath))) errorInfos.push([
2343
+ if (!routeService.isExistRoute((0, shared_.removeTrailingSlash)(cleanLinkPath)) && !routeService.isExistRoute((0, shared_.addTrailingSlash)(cleanLinkPath))) errorInfos.push([
2186
2344
  nodeUrl,
2187
2345
  link
2188
2346
  ]);
@@ -2191,37 +2349,37 @@ function normalizeLink_checkDeadLinks(internalLinks, filePath, routeService) {
2191
2349
  if (possibleBreakingChange) hintRelativeMarkdownLink();
2192
2350
  logger.error(`Dead links found in ${picocolors.cyan(filePath)}:
2193
2351
  ${errorInfos.map(([nodeUrl, link])=>` ${picocolors.green(`"[..](${nodeUrl})"`)} ${picocolors.gray(link)}`).join('\n')}`);
2194
- if (isProduction()) throw new Error('Dead link found');
2352
+ if ((0, shared_.isProduction)()) throw new Error('Dead link found');
2195
2353
  }
2196
2354
  }
2197
2355
  function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, internalLinks, __base) {
2198
2356
  if (!nodeUrl) return '';
2199
2357
  if (nodeUrl.startsWith('#')) return nodeUrl;
2200
- let { url, hash } = parseUrl(nodeUrl);
2201
- if (isExternalUrl(url)) return url + (hash ? `#${hash}` : '');
2358
+ let { url, hash } = (0, shared_.parseUrl)(nodeUrl);
2359
+ if ((0, shared_.isExternalUrl)(url)) return url + (hash ? `#${hash}` : '');
2202
2360
  if (!routeService) return nodeUrl;
2203
2361
  if (url.startsWith('/')) {
2204
2362
  const { routePath } = routeService.normalizeRoutePath(url);
2205
2363
  url = routePath;
2206
2364
  } else {
2207
- const anotherFileAbsolutePath = node_path.join(node_path.dirname(filePath), url);
2365
+ const anotherFileAbsolutePath = external_node_path_["default"].join(external_node_path_["default"].dirname(filePath), url);
2208
2366
  url = routeService.absolutePathToRoutePath(anotherFileAbsolutePath);
2209
2367
  }
2210
- if ('boolean' == typeof cleanUrls) url = normalizeHref(url, cleanUrls);
2368
+ if ('boolean' == typeof cleanUrls) url = (0, shared_.normalizeHref)(url, cleanUrls);
2211
2369
  else {
2212
- url = normalizeHref(url, false);
2370
+ url = (0, shared_.normalizeHref)(url, false);
2213
2371
  url = url.replace(/\.html$/, cleanUrls);
2214
2372
  }
2215
2373
  internalLinks.set(nodeUrl, url);
2216
2374
  if (hash) url += `#${hash}`;
2217
- if (__base) url = withBase(url, __base);
2375
+ if (__base) url = (0, shared_.withBase)(url, __base);
2218
2376
  return url;
2219
2377
  }
2220
2378
  function linkToRoutePath(routePath) {
2221
2379
  return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
2222
2380
  }
2223
2381
  const normalizeImageUrl = (imageUrl)=>{
2224
- if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) return '';
2382
+ if ((0, shared_.isExternalUrl)(imageUrl) || imageUrl.startsWith('/')) return '';
2225
2383
  return imageUrl;
2226
2384
  };
2227
2385
  const remarkPluginNormalizeLink = ({ cleanUrls, routeService, checkDeadLinks: shouldCheckDeadLinks = false, __base })=>(tree, file)=>{
@@ -2294,4 +2452,56 @@ const remarkPluginNormalizeLink = ({ cleanUrls, routeService, checkDeadLinks: sh
2294
2452
  });
2295
2453
  tree.children.unshift(...images);
2296
2454
  };
2297
- export { build, dev, mergeDocConfig, remarkPluginNormalizeLink, serve };
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 '';
2464
+ }
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
+ var __webpack_exports__RSPRESS_TEMP_DIR = shared_.RSPRESS_TEMP_DIR;
2502
+ var __webpack_exports__getSidebarDataGroup = shared_.getSidebarDataGroup;
2503
+ var __webpack_exports__normalizeHref = shared_.normalizeHref;
2504
+ var __webpack_exports__normalizePosixPath = shared_.normalizePosixPath;
2505
+ var __webpack_exports__removeTrailingSlash = shared_.removeTrailingSlash;
2506
+ 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 };