@rspress/core 2.0.0-beta.17 → 2.0.0-beta.19

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.d.ts CHANGED
@@ -123,9 +123,10 @@ declare class PluginDriver {
123
123
  */
124
124
  export declare const remarkPluginNormalizeLink: Plugin_2<[
125
125
  {
126
- root: string;
127
126
  cleanUrls: boolean | string;
128
- routeService?: RouteService;
127
+ routeService: RouteService | null;
128
+ checkDeadLinks?: boolean;
129
+ __base?: string;
129
130
  }
130
131
  ], Root>;
131
132
 
@@ -159,9 +160,12 @@ declare type RootContent = RootContentMap[keyof RootContentMap];
159
160
  declare interface RootData extends Data {}
160
161
 
161
162
  declare class RoutePage {
163
+ #private;
162
164
  routeMeta: RouteMeta;
163
- static create(routeMeta: RouteMeta): RoutePage;
164
- constructor(routeMeta: RouteMeta);
165
+ static create(absolutePath: string, docsDir: string): RoutePage;
166
+ static createFromExternal(routePath: string, filepath: string, docDir: string): RoutePage;
167
+ private constructor();
168
+ static generateRouteMeta(routePath: string, filepath: string, docDir: string): RouteMeta;
165
169
  }
166
170
 
167
171
  export declare class RouteService {
@@ -170,21 +174,23 @@ export declare class RouteService {
170
174
  static __instance__: RouteService | null;
171
175
  static getInstance(): RouteService;
172
176
  static create(options: InitOptions): Promise<RouteService>;
173
- constructor(scanDir: string, userConfig: UserConfig, tempDir: string, pluginDriver: PluginDriver);
177
+ private constructor();
174
178
  get extensions(): readonly string[];
175
- addRoute(routeMeta: RouteMeta): Promise<void>;
176
- removeRoute(filePath: string): void;
179
+ addRoute(routePage: RoutePage): Promise<void>;
177
180
  getRoutes(): RouteMeta[];
178
181
  getRoutePages(): RoutePage[];
179
182
  isExistRoute(routePath: string): boolean;
180
183
  generateRoutesCode(): string;
181
184
  generateRoutesCodeByRouteMeta(routeMeta: RouteMeta[]): string;
182
- getRoutePathParts(routePath: string): readonly [string, string, string, string];
183
- normalizeRoutePath(routePath: string): {
185
+ getRoutePathParts(relativePath: string): readonly [string, string, string];
186
+ normalizeRoutePath(relativePath: string): {
187
+ pureRoutePath: string;
184
188
  routePath: string;
185
189
  lang: string;
186
190
  version: string;
187
191
  };
192
+ absolutePathToRoutePath(absolutePath: string): string;
193
+ absolutePathToRelativePath(absolutePath: string): string;
188
194
  getRoutePageByRoutePath(routePath: string): RoutePage | undefined;
189
195
  }
190
196
 
package/dist/index.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import __rslib_shim_module__ from 'module';
2
2
  const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(import.meta.url);
3
- import { pluginContainerSyntax } from "@rspress/plugin-container-syntax";
4
3
  import node_fs_promises, { mkdir, readFile, readdir, rm, stat as promises_stat, writeFile } from "node:fs/promises";
5
- import node_path, { dirname, extname as external_node_path_extname, join, relative } from "node:path";
4
+ import node_path, { dirname, extname, join, relative } from "node:path";
6
5
  import { fileURLToPath, pathToFileURL } from "node:url";
7
6
  import { PLUGIN_REACT_NAME, pluginReact } from "@rsbuild/plugin-react";
8
- import { APPEARANCE_KEY, MDX_OR_MD_REGEXP, RSPRESS_TEMP_DIR, SEARCH_INDEX_NAME, addLeadingSlash, addTrailingSlash, isDebugMode, isExternalUrl, isSCM, normalizeHref, normalizeSlash, parseUrl, removeLeadingSlash, removeTrailingSlash, slash, withBase, withoutBase } from "@rspress/shared";
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";
9
8
  import { DEFAULT_PAGE_EXTENSIONS } from "@rspress/shared/constants";
10
9
  import { logger } from "@rspress/shared/logger";
11
10
  import picocolors from "picocolors";
@@ -47,7 +46,6 @@ class PluginDriver {
47
46
  const { pluginMediumZoom } = await import("@rspress/plugin-medium-zoom");
48
47
  this.addPlugin(pluginMediumZoom('object' == typeof mediumZoomConfig ? mediumZoomConfig : void 0));
49
48
  }
50
- this.addPlugin(pluginContainerSyntax());
51
49
  (config.plugins || []).forEach((plugin)=>{
52
50
  this.addPlugin(plugin);
53
51
  });
@@ -144,7 +142,7 @@ const pluginVirtualModule = (pluginOptions = {})=>({
144
142
  const TEMP_DIR = join(api.context.rootPath, 'node_modules', virtualFolderName);
145
143
  const virtualFileAbsolutePaths = Object.keys(virtualModules).map((i)=>{
146
144
  let absolutePath = join(TEMP_DIR, i);
147
- if (!external_node_path_extname(absolutePath)) absolutePath = `${absolutePath}.js`;
145
+ if (!extname(absolutePath)) absolutePath = `${absolutePath}.js`;
148
146
  return [
149
147
  i,
150
148
  absolutePath
@@ -241,9 +239,26 @@ function hintNavJsonChangeThenPanic(metaJson, metaJsonDir, docsDir) {
241
239
  process.exit(1);
242
240
  }
243
241
  }
244
- var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.17"}');
242
+ let isLogged = false;
243
+ function hintRelativeMarkdownLink() {
244
+ if (isLogged) return;
245
+ isLogged = true;
246
+ 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)');
247
+ }
248
+ function getPageKey(route) {
249
+ const cleanRoute = removeLeadingSlash(route);
250
+ return cleanRoute.replace(/\//g, '_').replace(/\.[^.]+$/, '') || 'index';
251
+ }
252
+ const isWindows = 'win32' === node_os.platform();
253
+ function normalizePath_slash(p) {
254
+ return p.replace(/\\/g, '/');
255
+ }
256
+ function normalizePath(id) {
257
+ return node_path.posix.normalize(isWindows ? normalizePath_slash(id) : id);
258
+ }
259
+ var package_namespaceObject = JSON.parse('{"i8":"2.0.0-beta.19"}');
245
260
  const RSPRESS_VERSION = package_namespaceObject.i8;
246
- const isProduction = ()=>'production' === process.env.NODE_ENV;
261
+ const constants_isProduction = ()=>'production' === process.env.NODE_ENV;
247
262
  const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
248
263
  const inlineThemeScript = `{
249
264
  const saved = localStorage.getItem('${APPEARANCE_KEY}')
@@ -268,25 +283,12 @@ const PUBLIC_DIR = 'public';
268
283
  const constants_TEMP_DIR = node_path.join(process.cwd(), 'node_modules', RSPRESS_TEMP_DIR);
269
284
  const NODE_SSG_BUNDLE_FOLDER = '__ssg__';
270
285
  const NODE_SSG_BUNDLE_NAME = 'rspress-ssg-entry.cjs';
271
- function getPageKey(route) {
272
- const cleanRoute = removeLeadingSlash(route);
273
- return cleanRoute.replace(/\//g, '_').replace(/\.[^.]+$/, '') || 'index';
274
- }
275
- class RoutePage {
276
- routeMeta;
277
- static create(routeMeta) {
278
- return new RoutePage(routeMeta);
279
- }
280
- constructor(routeMeta){
281
- this.routeMeta = routeMeta;
282
- }
283
- }
284
- const getRoutePathParts = (routePath, base, lang, version, langs, versions)=>{
285
- const hasTrailSlash = routePath.endsWith('/');
286
+ const getRoutePathParts = (relativePath, lang, version, langs, versions)=>{
287
+ const hasTrailSlash = relativePath.endsWith('/');
286
288
  let versionPart = '';
287
289
  let langPart = '';
288
290
  let purePathPart = '';
289
- const parts = routePath.split('/').filter(Boolean);
291
+ const parts = relativePath.split('/').filter(Boolean);
290
292
  if (version) {
291
293
  const versionToMatch = parts[0];
292
294
  if (versions.includes(versionToMatch)) {
@@ -303,22 +305,28 @@ const getRoutePathParts = (routePath, base, lang, version, langs, versions)=>{
303
305
  }
304
306
  purePathPart = parts.join('/');
305
307
  return [
306
- base,
307
308
  versionPart,
308
309
  langPart,
309
310
  hasTrailSlash ? addTrailingSlash(purePathPart) : purePathPart
310
311
  ];
311
312
  };
312
- const normalizeRoutePath = (routePath, base, lang, version, langs, versions, extensions = DEFAULT_PAGE_EXTENSIONS)=>{
313
- const [_, versionPart, langPart, purePathPart] = getRoutePathParts(routePath, base, lang, version, langs, versions);
313
+ const normalizeRoutePath = (relativePath, lang, version, langs, versions, extensions = DEFAULT_PAGE_EXTENSIONS)=>{
314
314
  const extensionsWithoutDot = extensions.map((i)=>i.slice(1));
315
315
  const cleanExtensionPattern = new RegExp(`\\.(${extensionsWithoutDot.join('|')})$`, 'i');
316
+ let routePath = relativePath.replace(cleanExtensionPattern, '').replace(/\.html$/, '');
317
+ const [versionPart, langPart, purePathPart] = getRoutePathParts(routePath, lang, version, langs, versions);
318
+ routePath = purePathPart.replace(/\/index$/, '/');
319
+ if ('index' === routePath) routePath = '';
316
320
  const normalizedRoutePath = addLeadingSlash([
317
- versionPart,
318
- langPart
319
- ].filter(Boolean).join('/') + addLeadingSlash(purePathPart)).replace(cleanExtensionPattern, '').replace(/\.html$/, '').replace(/\/index$/, '/');
321
+ ...[
322
+ versionPart,
323
+ langPart
324
+ ].filter(Boolean),
325
+ routePath
326
+ ].join('/'));
320
327
  return {
321
- routePath: withBase(normalizedRoutePath, base),
328
+ pureRoutePath: `/${routePath}`,
329
+ routePath: normalizedRoutePath,
322
330
  lang: langPart || lang,
323
331
  version: versionPart || version
324
332
  };
@@ -333,7 +341,6 @@ class RouteService {
333
341
  #versions = [];
334
342
  #include = [];
335
343
  #exclude = [];
336
- #base = '';
337
344
  #tempDir = '';
338
345
  #pluginDriver;
339
346
  static __instance__ = null;
@@ -343,9 +350,9 @@ class RouteService {
343
350
  static async create(options) {
344
351
  const { scanDir, config, runtimeTempDir, pluginDriver } = options;
345
352
  const routeService = new RouteService(scanDir, config, runtimeTempDir, pluginDriver);
353
+ RouteService.__instance__ = routeService;
346
354
  await routeService.#init();
347
355
  await pluginDriver.routeServiceGenerated(routeService);
348
- RouteService.__instance__ = routeService;
349
356
  return routeService;
350
357
  }
351
358
  constructor(scanDir, userConfig, tempDir, pluginDriver){
@@ -356,7 +363,6 @@ class RouteService {
356
363
  this.#exclude = routeOptions.exclude || [];
357
364
  this.#defaultLang = userConfig?.lang || '';
358
365
  this.#langs = (userConfig?.locales ?? userConfig?.themeConfig?.locales ?? []).map((item)=>item.lang);
359
- this.#base = userConfig?.base || '';
360
366
  this.#tempDir = tempDir;
361
367
  this.#pluginDriver = pluginDriver;
362
368
  if (userConfig.multiVersion) {
@@ -385,46 +391,30 @@ class RouteService {
385
391
  ]
386
392
  })).sort();
387
393
  files.forEach((filePath)=>{
388
- const fileRelativePath = normalizePath(node_path.relative(this.#scanDir, filePath));
389
- const { routePath, lang, version } = this.normalizeRoutePath(fileRelativePath);
390
- const absolutePath = node_path.join(this.#scanDir, fileRelativePath);
391
- const routeMeta = {
392
- routePath,
393
- absolutePath: normalizePath(absolutePath),
394
- relativePath: fileRelativePath,
395
- pageName: getPageKey(fileRelativePath),
396
- lang,
397
- version
398
- };
399
- this.addRoute(routeMeta);
394
+ const routePage = RoutePage.create(filePath, this.#scanDir);
395
+ this.addRoute(routePage);
400
396
  });
401
397
  const externalPages = await this.#pluginDriver.addPages();
402
398
  await Promise.all(externalPages.map(async (route, index)=>{
403
399
  const { routePath, content, filepath } = route;
404
400
  if (filepath) {
405
- const routeMeta = this.#generateRouteMeta(routePath, filepath);
406
- this.addRoute(routeMeta);
401
+ const routePage = RoutePage.createFromExternal(routePath, filepath, this.#scanDir);
402
+ this.addRoute(routePage);
407
403
  return;
408
404
  }
409
405
  if (content) {
410
406
  const filepath = await this.#writeTempFile(index, content);
411
- const routeMeta = this.#generateRouteMeta(routePath, filepath);
412
- this.addRoute(routeMeta);
407
+ const routePage = RoutePage.createFromExternal(routePath, filepath, this.#scanDir);
408
+ this.addRoute(routePage);
413
409
  }
414
410
  }));
415
411
  await this.#pluginDriver.routeGenerated(this.getRoutes());
416
412
  }
417
- async addRoute(routeMeta) {
418
- const { routePath } = routeMeta;
413
+ async addRoute(routePage) {
414
+ const { routeMeta: { routePath } } = routePage;
419
415
  if (this.routeData.has(routePath)) throw new Error(`routePath ${routePath} has already been added`);
420
- const routePage = RoutePage.create(routeMeta);
421
416
  this.routeData.set(routePath, routePage);
422
417
  }
423
- removeRoute(filePath) {
424
- const fileRelativePath = node_path.relative(this.#scanDir, filePath);
425
- const { routePath } = this.normalizeRoutePath(fileRelativePath);
426
- this.routeData.delete(routePath);
427
- }
428
418
  getRoutes() {
429
419
  return Array.from(this.routeData.values()).map((i)=>i.routeMeta);
430
420
  }
@@ -432,8 +422,7 @@ class RouteService {
432
422
  return Array.from(this.routeData.values());
433
423
  }
434
424
  isExistRoute(routePath) {
435
- const { routePath: normalizedRoute } = this.normalizeRoutePath(routePath);
436
- return Boolean(this.routeData.get(normalizedRoute));
425
+ return this.routeData.has(routePath);
437
426
  }
438
427
  generateRoutesCode() {
439
428
  return this.generateRoutesCodeByRouteMeta(this.getRoutes());
@@ -455,49 +444,78 @@ ${routeMeta.map((route, index)=>{
455
444
  ];
456
445
  `;
457
446
  }
458
- getRoutePathParts(routePath) {
459
- return getRoutePathParts(routePath, this.#base, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
447
+ getRoutePathParts(relativePath) {
448
+ return getRoutePathParts(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions);
449
+ }
450
+ normalizeRoutePath(relativePath) {
451
+ return normalizeRoutePath(relativePath, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions, this.#extensions);
460
452
  }
461
- normalizeRoutePath(routePath) {
462
- return normalizeRoutePath(routePath, this.#base, this.#defaultLang, this.#defaultVersion, this.#langs, this.#versions, this.#extensions);
453
+ absolutePathToRoutePath(absolutePath) {
454
+ return absolutePathToRoutePath(absolutePath, this.#scanDir, this);
455
+ }
456
+ absolutePathToRelativePath(absolutePath) {
457
+ return absolutePathToRelativePath(absolutePath, this.#scanDir);
463
458
  }
464
459
  async #writeTempFile(index, content) {
465
460
  const tempFilePath = node_path.join(this.#tempDir, `temp-${index}.mdx`);
466
461
  await node_fs_promises.writeFile(tempFilePath, content);
467
462
  return tempFilePath;
468
463
  }
469
- #generateRouteMeta(routePath, filepath) {
470
- const { routePath: normalizedPath, lang, version } = this.normalizeRoutePath(routePath);
464
+ getRoutePageByRoutePath(routePath) {
465
+ return this.routeData.get(routePath);
466
+ }
467
+ }
468
+ class RoutePage {
469
+ routeMeta;
470
+ #docDir;
471
+ static create(absolutePath, docsDir) {
472
+ const routeMeta = absolutePathToRouteMeta(absolutePath, docsDir, RouteService.getInstance());
473
+ return new RoutePage(routeMeta, docsDir);
474
+ }
475
+ static createFromExternal(routePath, filepath, docDir) {
476
+ const routeMeta = RoutePage.generateRouteMeta(routePath, filepath, docDir);
477
+ return new RoutePage(routeMeta, node_path.dirname(filepath));
478
+ }
479
+ constructor(routeMeta, docDir){
480
+ this.routeMeta = routeMeta;
481
+ this.#docDir = docDir;
482
+ }
483
+ static generateRouteMeta(routePath, filepath, docDir) {
484
+ const routeService = RouteService.getInstance();
485
+ const { routePath: normalizedPath, lang, version } = routeService.normalizeRoutePath(routePath);
471
486
  return {
472
487
  routePath: normalizedPath,
473
488
  absolutePath: normalizePath(filepath),
474
- relativePath: normalizePath(node_path.relative(this.#scanDir, filepath)),
489
+ relativePath: absolutePathToRelativePath(filepath, docDir),
475
490
  pageName: getPageKey(routePath),
476
491
  lang,
477
492
  version
478
493
  };
479
494
  }
480
- getRoutePageByRoutePath(routePath) {
481
- return this.routeData.get(routePath);
482
- }
483
495
  }
484
- const isWindows = 'win32' === node_os.platform();
485
- function normalizePath_slash(p) {
486
- return p.replace(/\\/g, '/');
496
+ function absolutePathToRelativePath(absolutePath, docsDir) {
497
+ return normalizePath_slash(node_path.relative(docsDir, absolutePath));
487
498
  }
488
- function normalizePath(id) {
489
- return node_path.posix.normalize(isWindows ? normalizePath_slash(id) : id);
499
+ function absolutePathToRouteMeta(absolutePath, docsDir, routeService = RouteService.getInstance()) {
500
+ const relativePath = absolutePathToRelativePath(absolutePath, docsDir);
501
+ const { lang, routePath, version } = routeService.normalizeRoutePath(relativePath);
502
+ return {
503
+ pageName: getPageKey(relativePath),
504
+ absolutePath,
505
+ lang,
506
+ version,
507
+ routePath,
508
+ relativePath
509
+ };
490
510
  }
491
- function absolutePathToLink(absolutePath, docsDir) {
492
- const relativePath = normalizePath_slash(node_path.relative(docsDir, absolutePath.replace(node_path.extname(absolutePath), '')));
493
- const routeService = RouteService.getInstance();
494
- return routeService.normalizeRoutePath(relativePath).routePath;
511
+ function absolutePathToRoutePath(absolutePath, docsDir, routeService = RouteService.getInstance()) {
512
+ return absolutePathToRouteMeta(absolutePath, docsDir, routeService).routePath;
495
513
  }
496
514
  function absolutePathToRoutePrefix(absolutePath, docsDir) {
497
515
  const relativePath = normalizePath_slash(node_path.relative(docsDir, absolutePath.replace(node_path.extname(absolutePath), '')));
498
516
  const routeService = RouteService.getInstance();
499
- const [basePrefix, versionPrefix, langPrefix] = routeService.getRoutePathParts(relativePath);
500
- return `${basePrefix}${versionPrefix ? `/${versionPrefix}` : ''}${langPrefix ? `/${langPrefix}` : ''}`;
517
+ const [versionPrefix, langPrefix] = routeService.getRoutePathParts(relativePath);
518
+ return `${versionPrefix ? `/${versionPrefix}` : ''}${langPrefix ? `/${langPrefix}` : ''}`;
501
519
  }
502
520
  function addRoutePrefix(workDir, docsDir, link) {
503
521
  const routePrefix = absolutePathToRoutePrefix(workDir, docsDir);
@@ -528,7 +546,7 @@ async function extractInfoFromFrontmatterWithAbsolutePath(absolutePath, rootDir)
528
546
  };
529
547
  }
530
548
  function getHmrFileKey(realPath, docsDir) {
531
- return realPath ? slash(relative(docsDir, realPath).replace(external_node_path_extname(realPath), '')) : '';
549
+ return realPath ? slash(relative(docsDir, realPath).replace(extname(realPath), '')) : '';
532
550
  }
533
551
  async function fsDirToMetaItems(workDir, extensions) {
534
552
  let subItems = await readdir(workDir);
@@ -591,7 +609,7 @@ async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, isF
591
609
  } catch (e) {
592
610
  logger.debug(e);
593
611
  const isIndexInMetaJsonIndex = dirMetaJson.find((i)=>{
594
- if ('string' == typeof i) return 'index' === i.replace(external_node_path_extname(i), '');
612
+ if ('string' == typeof i) return 'index' === i.replace(extname(i), '');
595
613
  return false;
596
614
  });
597
615
  const isIndexFileExists = await utils_pathExists(join(dirAbsolutePath, 'index.mdx')) || await utils_pathExists(join(dirAbsolutePath, 'index.md'));
@@ -628,7 +646,7 @@ async function metaItemToSidebarItem(metaItem, workDir, docsDir, extensions, isF
628
646
  throw new Error(`Unknown meta item type: ${metaItem.type}, please check it in "${join(workDir, '_meta.json')}".`);
629
647
  }
630
648
  async function detectFilePath(absolutePath, extensions) {
631
- const ext = external_node_path_extname(absolutePath);
649
+ const ext = extname(absolutePath);
632
650
  if (ext && extensions.includes(ext)) return absolutePath;
633
651
  for (const extension of extensions){
634
652
  const realPath = absolutePath + extension;
@@ -651,7 +669,7 @@ async function metaFileItemToSidebarItem(metaItemRaw, workDir, docsDir, extensio
651
669
  } catch {
652
670
  throw new Error(`The file "${absolutePath}" does not exist, please check it in "${join(workDir, '_meta.json')}".`);
653
671
  }
654
- const link = absolutePathToLink(absolutePathWithExt, docsDir);
672
+ const link = absolutePathToRoutePath(absolutePathWithExt, docsDir);
655
673
  const info = await extractInfoFromFrontmatterWithAbsolutePath(absolutePathWithExt, docsDir);
656
674
  const title = label || info.title;
657
675
  return {
@@ -1007,6 +1025,7 @@ var types_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
1007
1025
  RuntimeModuleID["SearchIndexHash"] = "virtual-search-index-hash";
1008
1026
  RuntimeModuleID["I18nText"] = "virtual-i18n-text";
1009
1027
  RuntimeModuleID["SearchHooks"] = "virtual-search-hooks";
1028
+ RuntimeModuleID["RuntimeConfig"] = "virtual-runtime-config";
1010
1029
  return RuntimeModuleID;
1011
1030
  }({});
1012
1031
  const DEFAULT_I18N_SOURCE = join(process.cwd(), 'i18n.json');
@@ -1033,7 +1052,7 @@ const i18nVMPlugin = (context)=>{
1033
1052
  };
1034
1053
  };
1035
1054
  function normalizeThemeConfig(docConfig) {
1036
- const { locales: siteLocales, base = '', lang, replaceRules = [], multiVersion } = docConfig;
1055
+ const { locales: siteLocales, lang, replaceRules = [], multiVersion } = docConfig;
1037
1056
  const { versions = [] } = multiVersion || {};
1038
1057
  const hasMultiVersion = versions.length > 0;
1039
1058
  docConfig.themeConfig = docConfig.themeConfig || {};
@@ -1042,7 +1061,7 @@ function normalizeThemeConfig(docConfig) {
1042
1061
  const i18nTextData = getI18nData(docConfig);
1043
1062
  const normalizeLinkPrefix = (link = '', currentLang = '')=>{
1044
1063
  const normalizedLink = slash(link);
1045
- if (!currentLang || !link || withoutBase(normalizedLink, base).startsWith(`/${currentLang}`) || isExternalUrl(normalizedLink) || hasMultiVersion) return normalizedLink;
1064
+ if (!currentLang || !link || normalizedLink.startsWith(`/${currentLang}`) || isExternalUrl(normalizedLink) || hasMultiVersion) return normalizedLink;
1046
1065
  return lang === currentLang ? normalizedLink : `/${currentLang}${addLeadingSlash(normalizedLink)}`;
1047
1066
  };
1048
1067
  const getI18nText = (key = '', currentLang = '')=>{
@@ -1178,7 +1197,6 @@ async function siteDataVMPlugin(context) {
1178
1197
  icon: getIconUrlPath(userConfig?.icon) || '',
1179
1198
  route: userConfig?.route || {},
1180
1199
  themeConfig: normalizeThemeConfig(userConfig),
1181
- base: userConfig?.base || '/',
1182
1200
  lang: userConfig?.lang || '',
1183
1201
  locales: userConfig?.locales || userConfig.themeConfig?.locales || [],
1184
1202
  logo: userConfig?.logo || '',
@@ -1193,7 +1211,7 @@ async function siteDataVMPlugin(context) {
1193
1211
  },
1194
1212
  pages: pages.map((page)=>{
1195
1213
  const { content, domain, _filepath, _html, _flattenContent, ...rest } = page;
1196
- return isProduction() ? rest : {
1214
+ return constants_isProduction() ? rest : {
1197
1215
  ...rest,
1198
1216
  _filepath
1199
1217
  };
@@ -1281,6 +1299,14 @@ const routeListVMPlugin = (context)=>{
1281
1299
  [types_RuntimeModuleID.Routes]: ()=>routeService.generateRoutesCode()
1282
1300
  };
1283
1301
  };
1302
+ const runtimeConfigVMPlugin = (context)=>({
1303
+ [types_RuntimeModuleID.RuntimeConfig]: ()=>{
1304
+ const { config } = context;
1305
+ const { base } = config;
1306
+ const normalizedBase = normalizeSlash(base ?? '/');
1307
+ return `export const base = ${JSON.stringify(normalizedBase)};`;
1308
+ }
1309
+ });
1284
1310
  const searchHookVMPlugin = (context)=>({
1285
1311
  [`${types_RuntimeModuleID.SearchHooks}`]: ()=>{
1286
1312
  const { config } = context;
@@ -1309,7 +1335,7 @@ async function writeSearchIndex(config) {
1309
1335
  await node_fs_promises.rename(source, target);
1310
1336
  scanning = true;
1311
1337
  }
1312
- if (isProduction() && isSCM() && config?.search?.mode === 'remote') {
1338
+ if (constants_isProduction() && isSCM() && config?.search?.mode === 'remote') {
1313
1339
  const { apiUrl, indexName } = config.search;
1314
1340
  try {
1315
1341
  await fetch(`${apiUrl}?index=${indexName}`, {
@@ -1470,9 +1496,8 @@ async function renderPages(routeService, config, pluginDriver, ssrBundlePath, ht
1470
1496
  }
1471
1497
  try {
1472
1498
  const routes = routeService.getRoutes();
1473
- const base = config?.base ?? '';
1474
1499
  const additionalRoutes = (await pluginDriver.addSSGRoutes()).map((route)=>({
1475
- routePath: withBase(route.path, base)
1500
+ routePath: route.path
1476
1501
  }));
1477
1502
  const allRoutes = [
1478
1503
  ...routes,
@@ -1525,6 +1550,7 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1525
1550
  async setup (api) {
1526
1551
  api.onBeforeBuild(()=>{
1527
1552
  let htmlTemplate = '';
1553
+ let hasError = false;
1528
1554
  const indexHtmlEmittedInWeb = new Promise((resolve, reject)=>{
1529
1555
  api.processAssets({
1530
1556
  stage: 'report',
@@ -1533,6 +1559,10 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1533
1559
  ]
1534
1560
  }, ({ assets, compilation, environment })=>{
1535
1561
  if ('web' !== environment.name) return;
1562
+ if (compilation.errors.length > 0) {
1563
+ hasError = true;
1564
+ return;
1565
+ }
1536
1566
  for (const [assetName, assetSource] of Object.entries(assets))if ('index.html' === assetName) {
1537
1567
  htmlTemplate = assetSource.source().toString();
1538
1568
  compilation.deleteAsset(assetName);
@@ -1554,6 +1584,11 @@ const rsbuildPluginSSG = ({ routeService, config, pluginDriver })=>({
1554
1584
  ]
1555
1585
  }, async ({ assets, compilation, environment, compiler })=>{
1556
1586
  if ('node' !== environment.name) return;
1587
+ if (compilation.errors.length > 0) {
1588
+ hasError = true;
1589
+ return;
1590
+ }
1591
+ if (hasError) return;
1557
1592
  const distPath = environment.distPath;
1558
1593
  const ssgFolderPath = join(distPath, NODE_SSG_BUNDLE_FOLDER);
1559
1594
  const mainCjsAbsolutePath = join(ssgFolderPath, NODE_SSG_BUNDLE_NAME);
@@ -1718,7 +1753,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1718
1753
  const outDir = config?.outDir ?? OUTPUT_DIR;
1719
1754
  const DEFAULT_THEME = require.resolve('@rspress/theme-default');
1720
1755
  const base = config?.base ?? '';
1721
- const assetPrefix = isProduction() ? removeTrailingSlash(config?.builderConfig?.output?.assetPrefix ?? base) : '';
1756
+ const assetPrefix = constants_isProduction() ? removeTrailingSlash(config?.builderConfig?.output?.assetPrefix ?? base) : '';
1722
1757
  const reactVersion = await detectReactVersion();
1723
1758
  const normalizeIcon = (icon)=>{
1724
1759
  if (!icon) return;
@@ -1754,7 +1789,8 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1754
1789
  ...globalStylesVMPlugin(context),
1755
1790
  ...searchHookVMPlugin(context),
1756
1791
  ...routeListVMPlugin(context),
1757
- ...await getVirtualModulesFromPlugins(pluginDriver)
1792
+ ...await getVirtualModulesFromPlugins(pluginDriver),
1793
+ ...runtimeConfigVMPlugin(context)
1758
1794
  }
1759
1795
  }),
1760
1796
  ...enableSSG ? [
@@ -1766,7 +1802,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1766
1802
  ] : []
1767
1803
  ],
1768
1804
  server: {
1769
- port: !isProduction() && process.env.PORT ? Number(process.env.PORT) : void 0,
1805
+ port: !constants_isProduction() && process.env.PORT ? Number(process.env.PORT) : void 0,
1770
1806
  publicDir: {
1771
1807
  name: node_path.join(userDocRoot, PUBLIC_DIR)
1772
1808
  },
@@ -1884,7 +1920,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1884
1920
  },
1885
1921
  source: {
1886
1922
  entry: {
1887
- index: enableSSG && isProduction() ? SSR_CLIENT_ENTRY : CSR_CLIENT_ENTRY
1923
+ index: enableSSG && constants_isProduction() ? SSR_CLIENT_ENTRY : CSR_CLIENT_ENTRY
1888
1924
  },
1889
1925
  preEntry: [
1890
1926
  node_path.join(DEFAULT_THEME, '../styles/index.js'),
@@ -2127,45 +2163,71 @@ const getASTNodeImport = (name, from)=>({
2127
2163
  }
2128
2164
  }
2129
2165
  });
2130
- function normalizeLink(nodeUrl, routeService, relativePath, cleanUrls) {
2166
+ function normalizeLink_checkDeadLinks(internalLinks, filePath, routeService) {
2167
+ const errorInfos = [];
2168
+ let possibleBreakingChange = false;
2169
+ [
2170
+ ...internalLinks.entries()
2171
+ ].forEach(([nodeUrl, link])=>{
2172
+ const cleanLinkPath = linkToRoutePath(link);
2173
+ if (!cleanLinkPath) return;
2174
+ if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
2175
+ if (!routeService.isExistRoute(removeTrailingSlash(cleanLinkPath)) && !routeService.isExistRoute(addTrailingSlash(cleanLinkPath))) errorInfos.push([
2176
+ nodeUrl,
2177
+ link
2178
+ ]);
2179
+ });
2180
+ if (errorInfos.length > 0) {
2181
+ if (possibleBreakingChange) hintRelativeMarkdownLink();
2182
+ logger.error(`Dead links found in ${picocolors.cyan(filePath)}:
2183
+ ${errorInfos.map(([nodeUrl, link])=>` ${picocolors.green(`"[..](${nodeUrl})"`)} ${picocolors.gray(link)}`).join('\n')}`);
2184
+ if (isProduction()) throw new Error('Dead link found');
2185
+ }
2186
+ }
2187
+ function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, internalLinks, __base) {
2131
2188
  if (!nodeUrl) return '';
2132
- if (nodeUrl.startsWith('#')) return `#${nodeUrl.slice(1)}`;
2189
+ if (nodeUrl.startsWith('#')) return nodeUrl;
2133
2190
  let { url, hash } = parseUrl(nodeUrl);
2134
2191
  if (isExternalUrl(url)) return url + (hash ? `#${hash}` : '');
2135
- const extname = node_path.extname(url);
2136
- if ((routeService?.extensions ?? DEFAULT_PAGE_EXTENSIONS).includes(extname)) url = url.replace(new RegExp(`\\${extname}$`), '');
2137
- if (url.startsWith('.')) url = node_path.posix.join(slash(node_path.dirname(relativePath)), url);
2138
- else if (routeService) {
2139
- const [_, pathVersion, pathLang] = routeService.getRoutePathParts(slash(relativePath));
2140
- const [__, urlVersion, urlLang, urlPath] = routeService.getRoutePathParts(url);
2141
- url = addLeadingSlash(urlPath);
2142
- if (pathLang && urlLang !== pathLang) url = `/${pathLang}${url}`;
2143
- if (pathVersion && urlVersion !== pathVersion) url = `/${pathVersion}${url}`;
2192
+ if (!routeService) return nodeUrl;
2193
+ if (url.startsWith('/')) {
2194
+ const { routePath } = routeService.normalizeRoutePath(url);
2195
+ url = routePath;
2196
+ } else {
2197
+ const anotherFileAbsolutePath = node_path.join(node_path.dirname(filePath), url);
2198
+ url = routeService.absolutePathToRoutePath(anotherFileAbsolutePath);
2144
2199
  }
2145
2200
  if ('boolean' == typeof cleanUrls) url = normalizeHref(url, cleanUrls);
2146
2201
  else {
2147
2202
  url = normalizeHref(url, false);
2148
2203
  url = url.replace(/\.html$/, cleanUrls);
2149
2204
  }
2205
+ internalLinks.set(nodeUrl, url);
2150
2206
  if (hash) url += `#${hash}`;
2207
+ if (__base) url = withBase(url, __base);
2151
2208
  return url;
2152
2209
  }
2210
+ function linkToRoutePath(routePath) {
2211
+ return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
2212
+ }
2153
2213
  const normalizeImageUrl = (imageUrl)=>{
2154
2214
  if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) return '';
2155
2215
  return imageUrl;
2156
2216
  };
2157
- const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, file)=>{
2158
- const images = [];
2217
+ const remarkPluginNormalizeLink = ({ cleanUrls, routeService, checkDeadLinks: shouldCheckDeadLinks = false, __base })=>(tree, file)=>{
2218
+ const internalLinks = new Map();
2159
2219
  visit(tree, 'link', (node)=>{
2160
2220
  const { url: nodeUrl } = node;
2161
- const relativePath = node_path.relative(root, file.path);
2162
- node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
2221
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
2222
+ node.url = link;
2163
2223
  });
2164
2224
  visit(tree, 'definition', (node)=>{
2165
2225
  const { url: nodeUrl } = node;
2166
- const relativePath = node_path.relative(root, file.path);
2167
- node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
2226
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
2227
+ node.url = link;
2168
2228
  });
2229
+ if (shouldCheckDeadLinks && routeService) normalizeLink_checkDeadLinks(internalLinks, file.path, routeService);
2230
+ const images = [];
2169
2231
  const getMdxSrcAttribute = (tempVar)=>({
2170
2232
  type: 'mdxJsxAttribute',
2171
2233
  name: 'src',
package/dist/loader.d.ts CHANGED
@@ -2,7 +2,7 @@ import { AdditionalPage } from '@rspress/shared';
2
2
  import { DefaultThemeConfig } from '@rspress/shared';
3
3
  import type { PageIndexInfo } from '@rspress/shared';
4
4
  import type { RouteMeta } from '@rspress/shared';
5
- import type { Rspack as Rspack_2 } from '@rsbuild/core';
5
+ import { Rspack as Rspack_2 } from '@rsbuild/core';
6
6
  import type { RspressPlugin } from '@rspress/shared';
7
7
  import type { UserConfig } from '@rspress/shared';
8
8
 
@@ -53,9 +53,12 @@ declare class PluginDriver {
53
53
  }
54
54
 
55
55
  declare class RoutePage {
56
+ #private;
56
57
  routeMeta: RouteMeta;
57
- static create(routeMeta: RouteMeta): RoutePage;
58
- constructor(routeMeta: RouteMeta);
58
+ static create(absolutePath: string, docsDir: string): RoutePage;
59
+ static createFromExternal(routePath: string, filepath: string, docDir: string): RoutePage;
60
+ private constructor();
61
+ static generateRouteMeta(routePath: string, filepath: string, docDir: string): RouteMeta;
59
62
  }
60
63
 
61
64
  declare class RouteService {
@@ -64,21 +67,23 @@ declare class RouteService {
64
67
  static __instance__: RouteService | null;
65
68
  static getInstance(): RouteService;
66
69
  static create(options: InitOptions): Promise<RouteService>;
67
- constructor(scanDir: string, userConfig: UserConfig, tempDir: string, pluginDriver: PluginDriver);
70
+ private constructor();
68
71
  get extensions(): readonly string[];
69
- addRoute(routeMeta: RouteMeta): Promise<void>;
70
- removeRoute(filePath: string): void;
72
+ addRoute(routePage: RoutePage): Promise<void>;
71
73
  getRoutes(): RouteMeta[];
72
74
  getRoutePages(): RoutePage[];
73
75
  isExistRoute(routePath: string): boolean;
74
76
  generateRoutesCode(): string;
75
77
  generateRoutesCodeByRouteMeta(routeMeta: RouteMeta[]): string;
76
- getRoutePathParts(routePath: string): readonly [string, string, string, string];
77
- normalizeRoutePath(routePath: string): {
78
+ getRoutePathParts(relativePath: string): readonly [string, string, string];
79
+ normalizeRoutePath(relativePath: string): {
80
+ pureRoutePath: string;
78
81
  routePath: string;
79
82
  lang: string;
80
83
  version: string;
81
84
  };
85
+ absolutePathToRoutePath(absolutePath: string): string;
86
+ absolutePathToRelativePath(absolutePath: string): string;
82
87
  getRoutePageByRoutePath(routePath: string): RoutePage | undefined;
83
88
  }
84
89
 
package/dist/loader.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import 'module';
2
2
  /*#__PURE__*/ import.meta.url;
3
- import { logger } from "@rspress/shared/logger";
3
+ import { logger } from "@rsbuild/core";
4
4
  import { compile, compileWithCrossCompilerCache } from "./processor.js";
5
5
  async function mdxLoader(source) {
6
6
  this.cacheable(true);
@@ -35,10 +35,9 @@ async function mdxLoader(source) {
35
35
  }
36
36
  } catch (e) {
37
37
  if (e instanceof Error) {
38
- logger.error(`MDX compile error: ${e.message} in ${filepath}`);
39
38
  logger.debug(e);
40
39
  callback({
41
- message: e.message,
40
+ message: `MDX compile error: ${e.message} in ${filepath}`,
42
41
  name: `${filepath} compile error`
43
42
  });
44
43
  }
@@ -55,9 +55,12 @@ declare class PluginDriver {
55
55
  }
56
56
 
57
57
  declare class RoutePage {
58
+ #private;
58
59
  routeMeta: RouteMeta;
59
- static create(routeMeta: RouteMeta): RoutePage;
60
- constructor(routeMeta: RouteMeta);
60
+ static create(absolutePath: string, docsDir: string): RoutePage;
61
+ static createFromExternal(routePath: string, filepath: string, docDir: string): RoutePage;
62
+ private constructor();
63
+ static generateRouteMeta(routePath: string, filepath: string, docDir: string): RouteMeta;
61
64
  }
62
65
 
63
66
  declare class RouteService {
@@ -66,21 +69,23 @@ declare class RouteService {
66
69
  static __instance__: RouteService | null;
67
70
  static getInstance(): RouteService;
68
71
  static create(options: InitOptions): Promise<RouteService>;
69
- constructor(scanDir: string, userConfig: UserConfig, tempDir: string, pluginDriver: PluginDriver);
72
+ private constructor();
70
73
  get extensions(): readonly string[];
71
- addRoute(routeMeta: RouteMeta): Promise<void>;
72
- removeRoute(filePath: string): void;
74
+ addRoute(routePage: RoutePage): Promise<void>;
73
75
  getRoutes(): RouteMeta[];
74
76
  getRoutePages(): RoutePage[];
75
77
  isExistRoute(routePath: string): boolean;
76
78
  generateRoutesCode(): string;
77
79
  generateRoutesCodeByRouteMeta(routeMeta: RouteMeta[]): string;
78
- getRoutePathParts(routePath: string): readonly [string, string, string, string];
79
- normalizeRoutePath(routePath: string): {
80
+ getRoutePathParts(relativePath: string): readonly [string, string, string];
81
+ normalizeRoutePath(relativePath: string): {
82
+ pureRoutePath: string;
80
83
  routePath: string;
81
84
  lang: string;
82
85
  version: string;
83
86
  };
87
+ absolutePathToRoutePath(absolutePath: string): string;
88
+ absolutePathToRelativePath(absolutePath: string): string;
84
89
  getRoutePageByRoutePath(routePath: string): RoutePage | undefined;
85
90
  }
86
91
 
package/dist/processor.js CHANGED
@@ -2,7 +2,6 @@ import 'module';
2
2
  /*#__PURE__*/ import.meta.url;
3
3
  import node_path from "node:path";
4
4
  import { createProcessor, nodeTypes } from "@mdx-js/mdx";
5
- import { logger } from "@rspress/shared/logger";
6
5
  import { extractTextAndId, getNodeAttribute, loadFrontMatter } from "@rspress/shared/node-utils";
7
6
  import node_os from "node:os";
8
7
  import rehype_external_links from "rehype-external-links";
@@ -11,8 +10,10 @@ import remark_gfm from "remark-gfm";
11
10
  import github_slugger from "github-slugger";
12
11
  import { headingRank } from "hast-util-heading-rank";
13
12
  import { visit } from "unist-util-visit";
14
- import { addLeadingSlash, cleanUrl, isExternalUrl, isProduction, normalizeHref, parseUrl, slash as shared_slash } from "@rspress/shared";
15
- import { DEFAULT_PAGE_EXTENSIONS } from "@rspress/shared/constants";
13
+ import { addTrailingSlash, isExternalUrl, isProduction, normalizeHref, parseUrl, removeTrailingSlash, withBase } from "@rspress/shared";
14
+ import { logger as logger_logger } from "@rspress/shared/logger";
15
+ import picocolors_0 from "picocolors";
16
+ import "node:fs/promises";
16
17
  import { visitChildren } from "unist-util-visit-children";
17
18
  import rehype from "@shikijs/rehype";
18
19
  import { createCssVariablesTheme } from "shiki";
@@ -118,74 +119,77 @@ const remarkBuiltin = ({ globalComponents })=>(tree)=>{
118
119
  });
119
120
  tree.children.unshift(...demos);
120
121
  };
121
- const IGNORE_REGEXP = /^(https?|mailto|tel|#)/;
122
- function checkLinks(links, filepath, root, routeService) {
122
+ let isLogged = false;
123
+ function hintRelativeMarkdownLink() {
124
+ if (isLogged) return;
125
+ isLogged = true;
126
+ logger_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)');
127
+ }
128
+ function normalizeLink_checkDeadLinks(internalLinks, filePath, routeService) {
123
129
  const errorInfos = [];
124
- links.filter((link)=>!IGNORE_REGEXP.test(link)).map((link)=>normalizePath(link)).forEach((link)=>{
125
- const relativePath = node_path.relative(root, filepath);
126
- if (!routeService.isExistRoute(cleanUrl(link))) errorInfos.push(`Internal link to "${link}" is dead, check it in "${relativePath}"`);
130
+ let possibleBreakingChange = false;
131
+ [
132
+ ...internalLinks.entries()
133
+ ].forEach(([nodeUrl, link])=>{
134
+ const cleanLinkPath = linkToRoutePath(link);
135
+ if (!cleanLinkPath) return;
136
+ if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
137
+ if (!routeService.isExistRoute(removeTrailingSlash(cleanLinkPath)) && !routeService.isExistRoute(addTrailingSlash(cleanLinkPath))) errorInfos.push([
138
+ nodeUrl,
139
+ link
140
+ ]);
127
141
  });
128
142
  if (errorInfos.length > 0) {
129
- errorInfos?.forEach((err)=>{
130
- logger.error(err);
131
- });
143
+ if (possibleBreakingChange) hintRelativeMarkdownLink();
144
+ logger_logger.error(`Dead links found in ${picocolors_0.cyan(filePath)}:
145
+ ${errorInfos.map(([nodeUrl, link])=>` ${picocolors_0.green(`"[..](${nodeUrl})"`)} ${picocolors_0.gray(link)}`).join('\n')}`);
132
146
  if (isProduction()) throw new Error('Dead link found');
133
147
  }
134
148
  }
135
- const remarkCheckDeadLinks = (checkLink)=>{
136
- const { root, routeService } = checkLink;
137
- return (tree, vfile)=>{
138
- const internalLinks = new Set();
139
- visit(tree, 'link', ({ url })=>{
140
- if (!url) return;
141
- if (internalLinks.has(url)) return;
142
- if (!url.startsWith('http://') && !url.startsWith('https://')) {
143
- const { routePath: normalizeUrl } = routeService.normalizeRoutePath(url.split(node_path.sep).join('/')?.split('#')[0]);
144
- internalLinks.add(normalizeUrl);
145
- }
146
- });
147
- checkLinks(Array.from(internalLinks), vfile.path, root, routeService);
148
- };
149
- };
150
- function normalizeLink(nodeUrl, routeService, relativePath, cleanUrls) {
149
+ function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, internalLinks, __base) {
151
150
  if (!nodeUrl) return '';
152
- if (nodeUrl.startsWith('#')) return `#${nodeUrl.slice(1)}`;
151
+ if (nodeUrl.startsWith('#')) return nodeUrl;
153
152
  let { url, hash } = parseUrl(nodeUrl);
154
153
  if (isExternalUrl(url)) return url + (hash ? `#${hash}` : '');
155
- const extname = node_path.extname(url);
156
- if ((routeService?.extensions ?? DEFAULT_PAGE_EXTENSIONS).includes(extname)) url = url.replace(new RegExp(`\\${extname}$`), '');
157
- if (url.startsWith('.')) url = node_path.posix.join(shared_slash(node_path.dirname(relativePath)), url);
158
- else if (routeService) {
159
- const [_, pathVersion, pathLang] = routeService.getRoutePathParts(shared_slash(relativePath));
160
- const [__, urlVersion, urlLang, urlPath] = routeService.getRoutePathParts(url);
161
- url = addLeadingSlash(urlPath);
162
- if (pathLang && urlLang !== pathLang) url = `/${pathLang}${url}`;
163
- if (pathVersion && urlVersion !== pathVersion) url = `/${pathVersion}${url}`;
154
+ if (!routeService) return nodeUrl;
155
+ if (url.startsWith('/')) {
156
+ const { routePath } = routeService.normalizeRoutePath(url);
157
+ url = routePath;
158
+ } else {
159
+ const anotherFileAbsolutePath = node_path.join(node_path.dirname(filePath), url);
160
+ url = routeService.absolutePathToRoutePath(anotherFileAbsolutePath);
164
161
  }
165
162
  if ('boolean' == typeof cleanUrls) url = normalizeHref(url, cleanUrls);
166
163
  else {
167
164
  url = normalizeHref(url, false);
168
165
  url = url.replace(/\.html$/, cleanUrls);
169
166
  }
167
+ internalLinks.set(nodeUrl, url);
170
168
  if (hash) url += `#${hash}`;
169
+ if (__base) url = withBase(url, __base);
171
170
  return url;
172
171
  }
172
+ function linkToRoutePath(routePath) {
173
+ return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
174
+ }
173
175
  const normalizeImageUrl = (imageUrl)=>{
174
176
  if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) return '';
175
177
  return imageUrl;
176
178
  };
177
- const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, file)=>{
178
- const images = [];
179
+ const remarkPluginNormalizeLink = ({ cleanUrls, routeService, checkDeadLinks: shouldCheckDeadLinks = false, __base })=>(tree, file)=>{
180
+ const internalLinks = new Map();
179
181
  visit(tree, 'link', (node)=>{
180
182
  const { url: nodeUrl } = node;
181
- const relativePath = node_path.relative(root, file.path);
182
- node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
183
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
184
+ node.url = link;
183
185
  });
184
186
  visit(tree, 'definition', (node)=>{
185
187
  const { url: nodeUrl } = node;
186
- const relativePath = node_path.relative(root, file.path);
187
- node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
188
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
189
+ node.url = link;
188
190
  });
191
+ if (shouldCheckDeadLinks && routeService) normalizeLink_checkDeadLinks(internalLinks, file.path, routeService);
192
+ const images = [];
189
193
  const getMdxSrcAttribute = (tempVar)=>({
190
194
  type: 'mdxJsxAttribute',
191
195
  name: 'src',
@@ -360,6 +364,204 @@ function createRehypeShikiOptions(showLineNumbers, options) {
360
364
  transformers: newTransformers
361
365
  };
362
366
  }
367
+ const DIRECTIVE_TYPES = [
368
+ 'tip',
369
+ 'note',
370
+ 'warning',
371
+ 'caution',
372
+ 'danger',
373
+ 'info',
374
+ 'details'
375
+ ];
376
+ const REGEX_BEGIN = /^\s*:::\s*(\w+)\s*(.*)?/;
377
+ const REGEX_END = /\s*:::$/;
378
+ const REGEX_GH_BEGIN = /^\s*\s*\[!(\w+)\]\s*(.*)?/;
379
+ const TITLE_REGEX_IN_MD = /{\s*title=["']?(.+)}\s*/;
380
+ const TITLE_REGEX_IN_MDX = /\s*title=["']?(.+)\s*/;
381
+ const trimTailingQuote = (str)=>str.replace(/['"]$/g, '');
382
+ const parseTitle = (rawTitle = '', isMDX = false)=>{
383
+ const matched = rawTitle?.match(isMDX ? TITLE_REGEX_IN_MDX : TITLE_REGEX_IN_MD);
384
+ return trimTailingQuote(matched?.[1] || rawTitle);
385
+ };
386
+ const createContainer = (type, title, children)=>{
387
+ const isDetails = 'details' === type;
388
+ const rootHName = isDetails ? 'details' : 'div';
389
+ const titleHName = isDetails ? 'summary' : 'div';
390
+ return {
391
+ type: 'containerDirective',
392
+ data: {
393
+ hName: rootHName,
394
+ hProperties: {
395
+ class: `rspress-directive ${type}`
396
+ }
397
+ },
398
+ children: [
399
+ {
400
+ type: 'paragraph',
401
+ data: {
402
+ hName: titleHName,
403
+ hProperties: {
404
+ class: 'rspress-directive-title'
405
+ }
406
+ },
407
+ children: [
408
+ {
409
+ type: 'text',
410
+ value: title || type.toUpperCase()
411
+ }
412
+ ]
413
+ },
414
+ {
415
+ type: 'paragraph',
416
+ data: {
417
+ hName: 'div',
418
+ hProperties: {
419
+ class: 'rspress-directive-content'
420
+ }
421
+ },
422
+ children: children
423
+ }
424
+ ]
425
+ };
426
+ };
427
+ function transformer(tree) {
428
+ let i = 0;
429
+ try {
430
+ while(i < tree.children.length){
431
+ const node = tree.children[i];
432
+ if ('children' in node) transformer(node);
433
+ if ('containerDirective' === node.type) {
434
+ const type = node.name;
435
+ if (DIRECTIVE_TYPES.includes(type)) tree.children.splice(i, 1, createContainer(type, node.attributes?.title ?? type.toUpperCase(), node.children));
436
+ } else if ('blockquote' === node.type && node.children[0]?.type === 'paragraph' && node.children[0].children?.[0] && 'value' in node.children[0].children[0]) {
437
+ const initiatorTag = node.children[0].children[0].value;
438
+ const match = initiatorTag.match(REGEX_GH_BEGIN);
439
+ if (match) {
440
+ const [, type] = match;
441
+ if (!DIRECTIVE_TYPES.includes(type.toLowerCase())) {
442
+ i++;
443
+ continue;
444
+ }
445
+ if (1 === node.children.length && 'paragraph' === node.children[0].type) node.children[0].children[0].value = match[2] ?? '';
446
+ const newChild = createContainer(type.toLowerCase(), type.toUpperCase(), 0 === node.children.slice(1).length ? node.children.slice(0) : node.children.slice(1));
447
+ tree.children.splice(i, 1, newChild);
448
+ }
449
+ }
450
+ if ('paragraph' !== node.type || 'text' !== node.children[0].type) {
451
+ i++;
452
+ continue;
453
+ }
454
+ const firstTextNode = node.children[0];
455
+ const text = firstTextNode.value;
456
+ const metaText = text.split('\n')[0];
457
+ const content = text.slice(metaText.length);
458
+ const match = metaText.match(REGEX_BEGIN);
459
+ if (!match) {
460
+ i++;
461
+ continue;
462
+ }
463
+ const [, type, rawTitle] = match;
464
+ let title = parseTitle(rawTitle);
465
+ const titleExpressionNode = node.children[1] && 'mdxTextExpression' === node.children[1].type ? node.children[1] : null;
466
+ if (titleExpressionNode) {
467
+ title = parseTitle(titleExpressionNode.value, true);
468
+ node.children.splice(1, 1);
469
+ }
470
+ if (!DIRECTIVE_TYPES.includes(type)) {
471
+ i++;
472
+ continue;
473
+ }
474
+ const wrappedChildren = [];
475
+ if (content?.endsWith(':::')) {
476
+ wrappedChildren.push({
477
+ type: 'paragraph',
478
+ children: [
479
+ {
480
+ type: 'text',
481
+ value: content.replace(REGEX_END, '')
482
+ }
483
+ ]
484
+ });
485
+ const newChild = createContainer(type, title, wrappedChildren);
486
+ tree.children.splice(i, 1, newChild);
487
+ } else {
488
+ const paragraphChild = {
489
+ type: 'paragraph',
490
+ children: []
491
+ };
492
+ wrappedChildren.push(paragraphChild);
493
+ if (content.length) paragraphChild.children.push({
494
+ type: 'text',
495
+ value: content
496
+ });
497
+ paragraphChild.children.push(...node.children.slice(1, -1));
498
+ if (0 === paragraphChild.children.length) wrappedChildren.pop();
499
+ const lastChildInNode = node.children[node.children.length - 1];
500
+ if ('text' === lastChildInNode.type && REGEX_END.test(lastChildInNode.value)) {
501
+ const lastChildInNodeText = lastChildInNode.value;
502
+ const matchedEndContent = lastChildInNodeText.slice(0, -3).trimEnd();
503
+ if (wrappedChildren.length) wrappedChildren[0].children.push({
504
+ type: 'text',
505
+ value: matchedEndContent
506
+ });
507
+ else if (matchedEndContent) wrappedChildren.push({
508
+ type: 'paragraph',
509
+ children: [
510
+ {
511
+ type: 'text',
512
+ value: matchedEndContent
513
+ }
514
+ ]
515
+ });
516
+ const newChild = createContainer(type, title, wrappedChildren);
517
+ tree.children.splice(i, 1, newChild);
518
+ i++;
519
+ continue;
520
+ }
521
+ if (lastChildInNode !== firstTextNode && wrappedChildren.length) wrappedChildren[0].children.push(lastChildInNode);
522
+ let j = i + 1;
523
+ while(j < tree.children.length){
524
+ const currentParagraph = tree.children[j];
525
+ if ('paragraph' !== currentParagraph.type) {
526
+ wrappedChildren.push(currentParagraph);
527
+ j++;
528
+ continue;
529
+ }
530
+ const lastChild = currentParagraph.children[currentParagraph.children.length - 1];
531
+ if (lastChild === firstTextNode || 'text' === lastChild.type && REGEX_END.test(lastChild.value)) {
532
+ const lastChildText = lastChild.value;
533
+ const matchedEndContent = lastChildText.slice(0, -3).trimEnd();
534
+ const filteredChildren = currentParagraph.children.filter((child)=>child !== firstTextNode && child !== lastChild);
535
+ if (matchedEndContent) wrappedChildren.push({
536
+ type: 'paragraph',
537
+ children: [
538
+ ...filteredChildren,
539
+ {
540
+ type: 'text',
541
+ value: matchedEndContent
542
+ }
543
+ ]
544
+ });
545
+ else wrappedChildren.push(...filteredChildren);
546
+ const newChild = createContainer(type, title, wrappedChildren);
547
+ tree.children.splice(i, j - i + 1, newChild);
548
+ break;
549
+ }
550
+ wrappedChildren.push({
551
+ ...currentParagraph,
552
+ children: currentParagraph.children.filter((child)=>child !== firstTextNode)
553
+ });
554
+ j++;
555
+ }
556
+ }
557
+ i++;
558
+ }
559
+ } catch (e) {
560
+ console.log(e);
561
+ throw e;
562
+ }
563
+ }
564
+ const remarkContainerSyntax = ()=>transformer;
363
565
  async function createMDXOptions(options) {
364
566
  const { docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver } = options;
365
567
  const format = node_path.extname(filepath).slice(1);
@@ -378,20 +580,14 @@ async function createMDXOptions(options) {
378
580
  remarkPlugins: [
379
581
  remark_gfm,
380
582
  remarkPluginToc,
583
+ remarkContainerSyntax,
381
584
  [
382
585
  remarkPluginNormalizeLink,
383
586
  {
384
587
  cleanUrls,
385
588
  root: docDirectory,
386
- routeService
387
- }
388
- ],
389
- checkDeadLinks && routeService && [
390
- remarkCheckDeadLinks,
391
- {
392
- root: docDirectory,
393
- base: config?.base || '',
394
- routeService
589
+ routeService,
590
+ checkDeadLinks
395
591
  }
396
592
  ],
397
593
  globalComponents.length && [
@@ -478,7 +674,6 @@ MDXContent.__RSPRESS_PAGE_META["${encodeURIComponent(normalizePath(node_path.rel
478
674
  return result;
479
675
  } catch (e) {
480
676
  if (e instanceof Error) throw e;
481
- logger.error(`MDX compile error: ${e} in ${filepath}`);
482
677
  throw new Error(`MDX compile error: ${e} in ${filepath}`);
483
678
  }
484
679
  }
@@ -3,6 +3,7 @@ import { BrowserRouter, DataContext, ThemeContext } from "@rspress/runtime";
3
3
  import { useThemeState } from "@theme";
4
4
  import { UnheadProvider, createHead } from "@unhead/react/client";
5
5
  import { useMemo, useState } from "react";
6
+ import { base } from "virtual-runtime-config";
6
7
  import { App } from "./App.js";
7
8
  const head = createHead();
8
9
  function ClientApp({ initialPageData = null }) {
@@ -29,6 +30,7 @@ function ClientApp({ initialPageData = null }) {
29
30
  v7_relativeSplatPath: true,
30
31
  v7_startTransition: true
31
32
  },
33
+ basename: base,
32
34
  children: /*#__PURE__*/ jsx(UnheadProvider, {
33
35
  head: head,
34
36
  children: /*#__PURE__*/ jsx(App, {})
@@ -1,5 +1,6 @@
1
1
  import { isEqualPath, pathnameToRouteService } from "@rspress/runtime";
2
2
  import { MDX_OR_MD_REGEXP, cleanUrl } from "@rspress/shared";
3
+ import { base } from "virtual-runtime-config";
3
4
  import virtual_site_data from "virtual-site-data";
4
5
  async function initPageData(routePath) {
5
6
  const matchedRoute = pathnameToRouteService(routePath);
@@ -27,7 +28,7 @@ async function initPageData(routePath) {
27
28
  let lang = virtual_site_data.lang || '';
28
29
  let version = virtual_site_data.multiVersion?.default || '';
29
30
  if (virtual_site_data.lang && 'undefined' != typeof window) {
30
- const path = location.pathname.replace(virtual_site_data.base, '').split('/').slice(0, 2);
31
+ const path = location.pathname.replace(base, '').split('/').slice(0, 2);
31
32
  if (virtual_site_data.locales.length) {
32
33
  const result = virtual_site_data.locales.find(({ lang })=>path.includes(lang));
33
34
  if (result) lang = result.lang;
@@ -1,6 +1,6 @@
1
1
  import type { PageData } from '@rspress/shared';
2
2
  import { type Unhead } from '@unhead/react/server';
3
- export declare function render(pagePath: string, head: Unhead): Promise<{
3
+ export declare function render(routePath: string, head: Unhead): Promise<{
4
4
  appHtml: string;
5
5
  pageData: PageData;
6
6
  }>;
@@ -1,10 +1,11 @@
1
1
  import { jsx } from "react/jsx-runtime";
2
- import { DataContext, ThemeContext, pathnameToRouteService } from "@rspress/runtime";
2
+ import { DataContext, ThemeContext, pathnameToRouteService, withBase } from "@rspress/runtime";
3
3
  import { StaticRouter } from "@rspress/runtime/server";
4
4
  import { UnheadProvider } from "@unhead/react/server";
5
5
  import { renderToPipeableStream } from "react-dom/server";
6
6
  import { PassThrough } from "node:stream";
7
7
  import { text as consumers_text } from "node:stream/consumers";
8
+ import { base } from "virtual-runtime-config";
8
9
  import { App } from "./App.js";
9
10
  import { initPageData } from "./initPageData.js";
10
11
  import { routes } from "virtual-routes";
@@ -27,9 +28,9 @@ function renderToHtml(app) {
27
28
  });
28
29
  });
29
30
  }
30
- async function render(pagePath, head) {
31
- const initialPageData = await initPageData(pagePath);
32
- await preloadRoute(pagePath);
31
+ async function render(routePath, head) {
32
+ const initialPageData = await initPageData(routePath);
33
+ await preloadRoute(routePath);
33
34
  const appHtml = await renderToHtml(/*#__PURE__*/ jsx(ThemeContext.Provider, {
34
35
  value: {
35
36
  theme: DEFAULT_THEME
@@ -39,7 +40,8 @@ async function render(pagePath, head) {
39
40
  data: initialPageData
40
41
  },
41
42
  children: /*#__PURE__*/ jsx(StaticRouter, {
42
- location: pagePath,
43
+ location: withBase(routePath),
44
+ basename: base,
43
45
  children: /*#__PURE__*/ jsx(UnheadProvider, {
44
46
  value: head,
45
47
  children: /*#__PURE__*/ jsx(App, {})
@@ -1,6 +1,4 @@
1
1
  /*! For license information please see shiki-transformers.js.LICENSE.txt */
2
- import 'module';
3
- /*#__PURE__*/ import.meta.url;
4
2
  const SHIKI_TRANSFORMER_LINE_NUMBER = 'shiki-transformer:line-number';
5
3
  function transformerLineNumber(options = {}) {
6
4
  const { classActiveLine = 'line-number', classActivePre = 'has-line-number' } = options;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rspress/core",
3
- "version": "2.0.0-beta.17",
3
+ "version": "2.0.0-beta.19",
4
4
  "description": "The Rspress Documentation Framework",
5
5
  "bugs": "https://github.com/web-infra-dev/rspress/issues",
6
6
  "repository": {
@@ -47,13 +47,13 @@
47
47
  "@mdx-js/loader": "^3.1.0",
48
48
  "@mdx-js/mdx": "^3.1.0",
49
49
  "@mdx-js/react": "^3.1.0",
50
- "@rsbuild/core": "~1.4.0-rc.0",
50
+ "@rsbuild/core": "~1.4.2",
51
51
  "@rsbuild/plugin-react": "~1.3.2",
52
52
  "@rspress/mdx-rs": "0.6.6",
53
53
  "@shikijs/rehype": "^3.4.2",
54
54
  "@types/unist": "^3.0.3",
55
- "@unhead/react": "^2.0.10",
56
- "enhanced-resolve": "5.18.1",
55
+ "@unhead/react": "^2.0.11",
56
+ "enhanced-resolve": "5.18.2",
57
57
  "github-slugger": "^2.0.0",
58
58
  "hast-util-from-html": "^2.0.3",
59
59
  "hast-util-heading-rank": "^3.0.0",
@@ -75,16 +75,15 @@
75
75
  "unified": "^11.0.5",
76
76
  "unist-util-visit": "^5.0.0",
77
77
  "unist-util-visit-children": "^3.0.0",
78
- "@rspress/plugin-last-updated": "2.0.0-beta.17",
79
- "@rspress/plugin-medium-zoom": "2.0.0-beta.17",
80
- "@rspress/runtime": "2.0.0-beta.17",
81
- "@rspress/shared": "2.0.0-beta.17",
82
- "@rspress/theme-default": "2.0.0-beta.17",
83
- "@rspress/plugin-container-syntax": "2.0.0-beta.17"
78
+ "@rspress/plugin-last-updated": "2.0.0-beta.19",
79
+ "@rspress/shared": "2.0.0-beta.19",
80
+ "@rspress/plugin-medium-zoom": "2.0.0-beta.19",
81
+ "@rspress/runtime": "2.0.0-beta.19",
82
+ "@rspress/theme-default": "2.0.0-beta.19"
84
83
  },
85
84
  "devDependencies": {
86
85
  "@microsoft/api-extractor": "^7.52.8",
87
- "@rslib/core": "0.10.2",
86
+ "@rslib/core": "0.10.4",
88
87
  "@rspress-dev/plugin-preview": "link:../plugin-preview",
89
88
  "@types/hast": "^3.0.4",
90
89
  "@types/html-to-text": "^9.0.4",
@@ -94,10 +93,12 @@
94
93
  "@types/node": "^22.8.1",
95
94
  "@types/react": "^19.1.8",
96
95
  "@types/react-dom": "^19.1.6",
96
+ "mdast-util-mdx-expression": "^2.0.1",
97
97
  "memfs": "^4.17.2",
98
98
  "p-map": "^7.0.3",
99
99
  "postcss": "8.5.6",
100
100
  "rehype-stringify": "^10.0.1",
101
+ "remark-directive": "^4.0.0",
101
102
  "remark-mdx": "^3.1.0",
102
103
  "remark-parse": "^11.0.0",
103
104
  "remark-rehype": "^11.1.2",