@rspress/core 1.42.0 → 1.42.1-canary-20240226

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
@@ -23,131 +23,9 @@ import * as __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__ from "@mdx-js/mdx";
23
23
  import * as __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__ from "enhanced-resolve";
24
24
  import * as __WEBPACK_EXTERNAL_MODULE_node_module_ab9f2194__ from "node:module";
25
25
  import * as __WEBPACK_EXTERNAL_MODULE_picocolors__ from "picocolors";
26
+ import * as __WEBPACK_EXTERNAL_MODULE_react_helmet_async_048d06c6__ from "react-helmet-async";
26
27
  import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__ from "@rsbuild/core";
27
28
  export * from "@rspress/shared";
28
- var __webpack_modules__ = {};
29
- var __webpack_module_cache__ = {};
30
- function __webpack_require__(moduleId) {
31
- var cachedModule = __webpack_module_cache__[moduleId];
32
- if (void 0 !== cachedModule) return cachedModule.exports;
33
- var module = __webpack_module_cache__[moduleId] = {
34
- exports: {}
35
- };
36
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
37
- return module.exports;
38
- }
39
- __webpack_require__.m = __webpack_modules__;
40
- (()=>{
41
- var getProto = Object.getPrototypeOf ? function(obj) {
42
- return Object.getPrototypeOf(obj);
43
- } : function(obj) {
44
- return obj.__proto__;
45
- };
46
- var leafPrototypes;
47
- __webpack_require__.t = function(value, mode) {
48
- if (1 & mode) value = this(value);
49
- if (8 & mode) return value;
50
- if ('object' == typeof value && value) {
51
- if (4 & mode && value.__esModule) return value;
52
- if (16 & mode && 'function' == typeof value.then) return value;
53
- }
54
- var ns = Object.create(null);
55
- __webpack_require__.r(ns);
56
- var def = {};
57
- leafPrototypes = leafPrototypes || [
58
- null,
59
- getProto({}),
60
- getProto([]),
61
- getProto(getProto)
62
- ];
63
- for(var current = 2 & mode && value; 'object' == typeof current && !~leafPrototypes.indexOf(current); current = getProto(current))Object.getOwnPropertyNames(current).forEach(function(key) {
64
- def[key] = function() {
65
- return value[key];
66
- };
67
- });
68
- def['default'] = function() {
69
- return value;
70
- };
71
- __webpack_require__.d(ns, def);
72
- return ns;
73
- };
74
- })();
75
- (()=>{
76
- __webpack_require__.d = function(exports, definition) {
77
- for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
78
- enumerable: true,
79
- get: definition[key]
80
- });
81
- };
82
- })();
83
- (()=>{
84
- __webpack_require__.f = {};
85
- __webpack_require__.e = function(chunkId) {
86
- return Promise.all(Object.keys(__webpack_require__.f).reduce(function(promises, key) {
87
- __webpack_require__.f[key](chunkId, promises);
88
- return promises;
89
- }, []));
90
- };
91
- })();
92
- (()=>{
93
- __webpack_require__.u = function(chunkId) {
94
- return "" + chunkId + ".js";
95
- };
96
- })();
97
- (()=>{
98
- __webpack_require__.o = function(obj, prop) {
99
- return Object.prototype.hasOwnProperty.call(obj, prop);
100
- };
101
- })();
102
- (()=>{
103
- __webpack_require__.r = function(exports) {
104
- if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports, Symbol.toStringTag, {
105
- value: 'Module'
106
- });
107
- Object.defineProperty(exports, '__esModule', {
108
- value: true
109
- });
110
- };
111
- })();
112
- (()=>{
113
- var installedChunks = {
114
- 980: 0
115
- };
116
- var installChunk = function(data) {
117
- var ids = data.ids;
118
- var modules = data.modules;
119
- var runtime = data.runtime;
120
- var moduleId, chunkId, i = 0;
121
- for(moduleId in modules)if (__webpack_require__.o(modules, moduleId)) __webpack_require__.m[moduleId] = modules[moduleId];
122
- if (runtime) runtime(__webpack_require__);
123
- for(; i < ids.length; i++){
124
- chunkId = ids[i];
125
- if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) installedChunks[chunkId][0]();
126
- installedChunks[ids[i]] = 0;
127
- }
128
- };
129
- __webpack_require__.f.j = function(chunkId, promises) {
130
- var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : void 0;
131
- if (0 !== installedChunkData) {
132
- if (installedChunkData) promises.push(installedChunkData[1]);
133
- else {
134
- var promise = import("./" + __webpack_require__.u(chunkId)).then(installChunk, function(e) {
135
- if (0 !== installedChunks[chunkId]) installedChunks[chunkId] = void 0;
136
- throw e;
137
- });
138
- var promise = Promise.race([
139
- promise,
140
- new Promise(function(resolve) {
141
- installedChunkData = installedChunks[chunkId] = [
142
- resolve
143
- ];
144
- })
145
- ]);
146
- promises.push(installedChunkData[1] = promise);
147
- }
148
- }
149
- };
150
- })();
151
29
  function _check_private_redeclaration(obj, privateCollection) {
152
30
  if (privateCollection.has(obj)) throw new TypeError("Cannot initialize the same private elements twice on an object");
153
31
  }
@@ -258,7 +136,7 @@ class PluginDriver {
258
136
  return result.flat();
259
137
  }
260
138
  async routeGenerated(routes) {
261
- return this._runParallelAsyncHook('routeGenerated', routes);
139
+ return this._runParallelAsyncHook('routeGenerated', routes, _class_private_field_get(this, _isProd));
262
140
  }
263
141
  async addRuntimeModules() {
264
142
  const result = await this._runParallelAsyncHook('addRuntimeModules', _class_private_field_get(this, _config) || {}, _class_private_field_get(this, _isProd));
@@ -279,7 +157,10 @@ class PluginDriver {
279
157
  return _class_private_field_get(this, _plugins).filter((plugin)=>'string' == typeof plugin.globalStyles).map((plugin)=>plugin.globalStyles);
280
158
  }
281
159
  _runParallelAsyncHook(hookName, ...args) {
282
- return Promise.all(_class_private_field_get(this, _plugins).filter((plugin)=>'function' == typeof plugin[hookName]).map((plugin)=>plugin[hookName](...args)));
160
+ return Promise.all(_class_private_field_get(this, _plugins).filter((plugin)=>'function' == typeof plugin[hookName]).map((plugin)=>{
161
+ var _plugin_hookName;
162
+ return null === (_plugin_hookName = plugin[hookName]) || void 0 === _plugin_hookName ? void 0 : _plugin_hookName.call(plugin, ...args);
163
+ }));
283
164
  }
284
165
  _runSerialAsyncHook(hookName, ...args) {
285
166
  return _class_private_field_get(this, _plugins).reduce(async (prev, plugin)=>{
@@ -415,6 +296,16 @@ function _class_private_method_init(obj, privateSet) {
415
296
  RouteService_check_private_redeclaration(obj, privateSet);
416
297
  privateSet.add(obj);
417
298
  }
299
+ function _define_property(obj, key, value) {
300
+ if (key in obj) Object.defineProperty(obj, key, {
301
+ value: value,
302
+ enumerable: true,
303
+ configurable: true,
304
+ writable: true
305
+ });
306
+ else obj[key] = value;
307
+ return obj;
308
+ }
418
309
  var _scanDir = /*#__PURE__*/ new WeakMap(), _defaultLang = /*#__PURE__*/ new WeakMap(), _defaultVersion = /*#__PURE__*/ new WeakMap(), _extensions = /*#__PURE__*/ new WeakMap(), _langs = /*#__PURE__*/ new WeakMap(), _versions = /*#__PURE__*/ new WeakMap(), _include = /*#__PURE__*/ new WeakMap(), _exclude = /*#__PURE__*/ new WeakMap(), _base = /*#__PURE__*/ new WeakMap(), _tempDir = /*#__PURE__*/ new WeakMap(), _pluginDriver = /*#__PURE__*/ new WeakMap(), _writeTempFile = /*#__PURE__*/ new WeakSet(), _generateRouteInfo = /*#__PURE__*/ new WeakSet();
419
310
  class RouteService {
420
311
  async init() {
@@ -514,6 +405,7 @@ ${routeMeta.map((route, index)=>{
514
405
  var _userConfig_themeConfig;
515
406
  _class_private_method_init(this, _writeTempFile);
516
407
  _class_private_method_init(this, _generateRouteInfo);
408
+ _define_property(this, "routeData", new Map());
517
409
  RouteService_class_private_field_init(this, _scanDir, {
518
410
  writable: true,
519
411
  value: void 0
@@ -524,49 +416,40 @@ ${routeMeta.map((route, index)=>{
524
416
  });
525
417
  RouteService_class_private_field_init(this, _defaultVersion, {
526
418
  writable: true,
527
- value: void 0
419
+ value: ''
528
420
  });
529
421
  RouteService_class_private_field_init(this, _extensions, {
530
422
  writable: true,
531
- value: void 0
423
+ value: []
532
424
  });
533
425
  RouteService_class_private_field_init(this, _langs, {
534
426
  writable: true,
535
- value: void 0
427
+ value: []
536
428
  });
537
429
  RouteService_class_private_field_init(this, _versions, {
538
430
  writable: true,
539
- value: void 0
431
+ value: []
540
432
  });
541
433
  RouteService_class_private_field_init(this, _include, {
542
434
  writable: true,
543
- value: void 0
435
+ value: []
544
436
  });
545
437
  RouteService_class_private_field_init(this, _exclude, {
546
438
  writable: true,
547
- value: void 0
439
+ value: []
548
440
  });
549
441
  RouteService_class_private_field_init(this, _base, {
550
442
  writable: true,
551
- value: void 0
443
+ value: ''
552
444
  });
553
445
  RouteService_class_private_field_init(this, _tempDir, {
554
446
  writable: true,
555
- value: void 0
447
+ value: ''
556
448
  });
557
449
  RouteService_class_private_field_init(this, _pluginDriver, {
558
450
  writable: true,
559
451
  value: void 0
560
452
  });
561
- this.routeData = new Map();
562
- RouteService_class_private_field_set(this, _defaultVersion, '');
563
- RouteService_class_private_field_set(this, _extensions, []);
564
- RouteService_class_private_field_set(this, _langs, []);
565
- RouteService_class_private_field_set(this, _versions, []);
566
- RouteService_class_private_field_set(this, _include, []);
567
- RouteService_class_private_field_set(this, _exclude, []);
568
- RouteService_class_private_field_set(this, _base, '');
569
- RouteService_class_private_field_set(this, _tempDir, '');
570
453
  const routeOptions = (null == userConfig ? void 0 : userConfig.route) || {};
571
454
  RouteService_class_private_field_set(this, _scanDir, scanDir);
572
455
  RouteService_class_private_field_set(this, _extensions, routeOptions.extensions || __WEBPACK_EXTERNAL_MODULE__rspress_shared_constants_70084e62__.DEFAULT_PAGE_EXTENSIONS);
@@ -696,9 +579,10 @@ let flattenMdxContent_resolver;
696
579
  let startFlatten = false;
697
580
  const processor = (0, __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__.createProcessor)();
698
581
  const { CachedInputFileSystem, ResolverFactory } = __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__["default"];
582
+ const fileSystem = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"];
699
583
  async function resolveDepPath(importPath, importer, alias) {
700
584
  if (!flattenMdxContent_resolver) flattenMdxContent_resolver = ResolverFactory.createResolver({
701
- fileSystem: new CachedInputFileSystem(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"], 0),
585
+ fileSystem: new CachedInputFileSystem(fileSystem, 0),
702
586
  extensions: [
703
587
  '.mdx',
704
588
  '.md'
@@ -725,7 +609,7 @@ async function flattenMdxContent(content, basePath, alias) {
725
609
  };
726
610
  if (!startFlatten) {
727
611
  flattenMdxContent_resolver = ResolverFactory.createResolver({
728
- fileSystem: new CachedInputFileSystem(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"], 0),
612
+ fileSystem: new CachedInputFileSystem(fileSystem, 0),
729
613
  extensions: [
730
614
  '.mdx',
731
615
  '.md',
@@ -756,7 +640,7 @@ async function flattenMdxContent(content, basePath, alias) {
756
640
  let absoluteImportPath;
757
641
  try {
758
642
  absoluteImportPath = await resolveDepPath(importPath, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(basePath), alias);
759
- } catch (e) {
643
+ } catch (_e) {
760
644
  continue;
761
645
  }
762
646
  if (__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.MDX_REGEXP.test(absoluteImportPath)) {
@@ -778,7 +662,7 @@ function applyReplaceRules(code = '', replaceRules = []) {
778
662
  }
779
663
  function applyReplaceRulesToNestedObject(obj, replaceRules) {
780
664
  for(const key in obj)if ('string' == typeof obj[key]) obj[key] = applyReplaceRules(obj[key], replaceRules);
781
- else if ('object' == typeof obj[key]) obj[key] = applyReplaceRulesToNestedObject(obj[key], replaceRules);
665
+ else if ('object' == typeof obj[key] && null !== obj[key]) obj[key] = applyReplaceRulesToNestedObject(obj[key], replaceRules);
782
666
  return obj;
783
667
  }
784
668
  async function extractPageData(replaceRules, alias, domain, root, routeService, highlighterLangs, searchCodeBlocks) {
@@ -804,14 +688,20 @@ async function extractPageData(replaceRules, alias, domain, root, routeService,
804
688
  applyReplaceRulesToNestedObject(frontmatter, replaceRules);
805
689
  const { flattenContent } = await flattenMdxContent(applyReplaceRules(strippedFrontMatter, replaceRules), route.absolutePath, alias);
806
690
  content = flattenContent.replace(importStatementRegex, '');
807
- const { html, title, toc: rawToc, languages } = await (0, __WEBPACK_EXTERNAL_MODULE__rspress_mdx_rs_d2f3021f__.compile)({
691
+ const { html: rawHtml, title, toc: rawToc, languages } = await (0, __WEBPACK_EXTERNAL_MODULE__rspress_mdx_rs_d2f3021f__.compile)({
808
692
  value: content,
809
693
  filepath: route.absolutePath,
810
694
  development: 'production' !== process.env.NODE_ENV,
811
695
  root
812
696
  });
813
- if (!(null == title ? void 0 : title.length) && !frontmatter && !(null === (_frontmatter_title = frontmatter.title) || void 0 === _frontmatter_title ? void 0 : _frontmatter_title.length)) return null;
814
- content = (0, __WEBPACK_EXTERNAL_MODULE_html_to_text_2c51ed38__.htmlToText)(String(html), {
697
+ if (!(null == title ? void 0 : title.length) && !(null == frontmatter ? void 0 : null === (_frontmatter_title = frontmatter.title) || void 0 === _frontmatter_title ? void 0 : _frontmatter_title.length)) return null;
698
+ function encodeHtml(html) {
699
+ return html.replace(/<code>([\s\S]*?)<\/\s?code>/gm, function(_match, innerContent) {
700
+ return `<code>${innerContent.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code>`;
701
+ });
702
+ }
703
+ const html = encodeHtml(String(rawHtml));
704
+ content = (0, __WEBPACK_EXTERNAL_MODULE_html_to_text_2c51ed38__.htmlToText)(html, {
815
705
  wordwrap: 80,
816
706
  selectors: [
817
707
  {
@@ -956,7 +846,7 @@ function normalizeThemeConfig(docConfig, pages = []) {
956
846
  return {
957
847
  text: applyReplaceRules((null == page ? void 0 : page.title) || '', replaceRules),
958
848
  link: normalizedItem,
959
- _fileKey: page._relativePath.replace(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(page._relativePath), '')
849
+ _fileKey: null == page ? void 0 : page._relativePath.replace(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(page._relativePath), '')
960
850
  };
961
851
  }
962
852
  return {
@@ -1023,13 +913,11 @@ function deletePrivateField(obj) {
1023
913
  const newObj = {
1024
914
  ...obj
1025
915
  };
1026
- Object.keys(newObj).forEach((key)=>{
1027
- if (key.startsWith('_')) delete newObj[key];
1028
- });
916
+ for(const key in newObj)if (key.startsWith('_')) delete newObj[key];
1029
917
  return newObj;
1030
918
  }
1031
919
  async function siteDataVMPlugin(context) {
1032
- var _userConfig_themeConfig, _userConfig_multiVersion, _userConfig_multiVersion1, _userConfig_markdown, _userConfig_markdown1, _userConfig_markdown2, _siteData_pages__extraHighlightLanguages, _siteData_pages_;
920
+ var _userConfig_themeConfig, _userConfig_multiVersion, _userConfig_multiVersion1, _userConfig_markdown, _userConfig_markdown1, _userConfig_markdown2, _siteData_pages_;
1033
921
  const { config, alias, userDocRoot, routeService, pluginDriver } = context;
1034
922
  const userConfig = config;
1035
923
  const tempSearchObj = Object.assign({}, userConfig.search);
@@ -1038,7 +926,7 @@ async function siteDataVMPlugin(context) {
1038
926
  const replaceRules = (null == userConfig ? void 0 : userConfig.replaceRules) || [];
1039
927
  const searchConfig = (null == userConfig ? void 0 : userConfig.search) || {};
1040
928
  const domain = (null == searchConfig ? void 0 : searchConfig.mode) === 'remote' ? searchConfig.domain ?? '' : '';
1041
- const searchCodeBlocks = 'codeBlocks' in searchConfig && searchConfig.codeBlocks;
929
+ const searchCodeBlocks = 'codeBlocks' in searchConfig ? Boolean(searchConfig.codeBlocks) : false;
1042
930
  const pages = await extractPageData(replaceRules, alias, domain, userDocRoot, routeService, highlightLanguages, searchCodeBlocks);
1043
931
  await pluginDriver.modifySearchIndexData(pages);
1044
932
  const versioned = userConfig.search && 'remote' !== userConfig.search.mode && userConfig.search.versioned;
@@ -1068,7 +956,7 @@ async function siteDataVMPlugin(context) {
1068
956
  title: (null == userConfig ? void 0 : userConfig.title) || '',
1069
957
  description: (null == userConfig ? void 0 : userConfig.description) || '',
1070
958
  icon: (null == userConfig ? void 0 : userConfig.icon) || '',
1071
- route: null == userConfig ? void 0 : userConfig.route,
959
+ route: (null == userConfig ? void 0 : userConfig.route) || {},
1072
960
  themeConfig: normalizeThemeConfig(userConfig, pages),
1073
961
  base: (null == userConfig ? void 0 : userConfig.base) || '/',
1074
962
  lang: (null == userConfig ? void 0 : userConfig.lang) || '',
@@ -1097,7 +985,7 @@ async function siteDataVMPlugin(context) {
1097
985
  }
1098
986
  };
1099
987
  const { highlightLanguages: defaultLanguages = [] } = config.markdown || {};
1100
- if (null === (_siteData_pages_ = siteData.pages[0]) || void 0 === _siteData_pages_ ? void 0 : null === (_siteData_pages__extraHighlightLanguages = _siteData_pages_.extraHighlightLanguages) || void 0 === _siteData_pages__extraHighlightLanguages ? void 0 : _siteData_pages__extraHighlightLanguages.length) siteData.pages[0].extraHighlightLanguages.forEach((lang)=>highlightLanguages.add(lang));
988
+ if (Array.isArray(null === (_siteData_pages_ = siteData.pages[0]) || void 0 === _siteData_pages_ ? void 0 : _siteData_pages_.extraHighlightLanguages)) siteData.pages[0].extraHighlightLanguages.forEach((lang)=>highlightLanguages.add(lang));
1101
989
  const aliases = handleHighlightLanguages(highlightLanguages, defaultLanguages);
1102
990
  const sortedAliases = Object.fromEntries(Object.entries(aliases).sort());
1103
991
  const sortedHighlightLanguages = Array.from(highlightLanguages).sort();
@@ -1201,10 +1089,9 @@ function serveSearchIndexMiddleware(config) {
1201
1089
  var _req_url;
1202
1090
  const searchIndexRequestMatch = `/${__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.SEARCH_INDEX_NAME}.`;
1203
1091
  if (null === (_req_url = req.url) || void 0 === _req_url ? void 0 : _req_url.includes(searchIndexRequestMatch)) {
1204
- var _req_url1;
1205
1092
  res.setHeader('Content-Type', 'application/json');
1206
1093
  const outDir = (null == config ? void 0 : config.outDir) ?? (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(process.cwd(), OUTPUT_DIR);
1207
- const searchIndexFile = null === (_req_url1 = req.url) || void 0 === _req_url1 ? void 0 : _req_url1.split('/').pop();
1094
+ const searchIndexFile = req.url.split('/').pop();
1208
1095
  (0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.createReadStream)((0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(outDir, 'static', searchIndexFile), 'utf-8').pipe(res, {
1209
1096
  end: true
1210
1097
  });
@@ -1266,7 +1153,7 @@ async function resolveReactAlias(reactVersion, isSSR) {
1266
1153
  resolver.resolve({
1267
1154
  importer: basedir
1268
1155
  }, basedir, lib, {}, (err, filePath)=>{
1269
- if (err || false === filePath) return reject(err);
1156
+ if (err || !filePath) return reject(err);
1270
1157
  return resolve(filePath);
1271
1158
  });
1272
1159
  });
@@ -1320,10 +1207,10 @@ function getSocialIcons(socialLinks = []) {
1320
1207
  }
1321
1208
  function isPluginIncluded(config, pluginName) {
1322
1209
  var _config_builderPlugins, _config_builderConfig_plugins, _config_builderConfig;
1323
- return (null === (_config_builderPlugins = config.builderPlugins) || void 0 === _config_builderPlugins ? void 0 : _config_builderPlugins.some((plugin)=>plugin.name === pluginName)) || (null === (_config_builderConfig = config.builderConfig) || void 0 === _config_builderConfig ? void 0 : null === (_config_builderConfig_plugins = _config_builderConfig.plugins) || void 0 === _config_builderConfig_plugins ? void 0 : _config_builderConfig_plugins.some((plugin)=>plugin && plugin.name === pluginName));
1210
+ return Boolean((null === (_config_builderPlugins = config.builderPlugins) || void 0 === _config_builderPlugins ? void 0 : _config_builderPlugins.some((plugin)=>plugin.name === pluginName)) || (null === (_config_builderConfig = config.builderConfig) || void 0 === _config_builderConfig ? void 0 : null === (_config_builderConfig_plugins = _config_builderConfig.plugins) || void 0 === _config_builderConfig_plugins ? void 0 : _config_builderConfig_plugins.some((plugin)=>plugin && plugin.name === pluginName)));
1324
1211
  }
1325
1212
  async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeService, pluginDriver, runtimeTempDir) {
1326
- var _config_builderConfig_output, _config_builderConfig, _config_themeConfig;
1213
+ var _config_builderConfig_output, _config_builderConfig, _config_themeConfig, _config_themeConfig1;
1327
1214
  const cwd = process.cwd();
1328
1215
  const CUSTOM_THEME_DIR = (null == config ? void 0 : config.themeDir) ?? __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(process.cwd(), 'theme');
1329
1216
  const baseOutDir = (null == config ? void 0 : config.outDir) ?? OUTPUT_DIR;
@@ -1385,11 +1272,11 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1385
1272
  favicon: normalizeIcon(null == config ? void 0 : config.icon),
1386
1273
  template: __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'index.html'),
1387
1274
  tags: [
1388
- (null === (_config_themeConfig = config.themeConfig) || void 0 === _config_themeConfig ? void 0 : _config_themeConfig.darkMode) !== false && {
1275
+ (null === (_config_themeConfig = config.themeConfig) || void 0 === _config_themeConfig ? void 0 : _config_themeConfig.darkMode) !== false ? {
1389
1276
  tag: "script",
1390
1277
  children: inlineThemeScript,
1391
1278
  append: false
1392
- }
1279
+ } : null
1393
1280
  ].filter(Boolean)
1394
1281
  },
1395
1282
  output: {
@@ -1420,7 +1307,7 @@ async function createInternalBuildConfig(userDocRoot, config, enableSSG, routeSe
1420
1307
  define: {
1421
1308
  'process.env.__REACT_GTE_18__': JSON.stringify(reactVersion >= 18),
1422
1309
  'process.env.TEST': JSON.stringify(process.env.TEST),
1423
- 'process.env.RSPRESS_SOCIAL_ICONS': JSON.stringify(getSocialIcons(config.themeConfig.socialLinks))
1310
+ 'process.env.RSPRESS_SOCIAL_ICONS': JSON.stringify(getSocialIcons(null === (_config_themeConfig1 = config.themeConfig) || void 0 === _config_themeConfig1 ? void 0 : _config_themeConfig1.socialLinks))
1424
1311
  }
1425
1312
  },
1426
1313
  performance: {
@@ -1654,6 +1541,7 @@ async function dev(options) {
1654
1541
  await checkLanguageParity(modifiedConfig);
1655
1542
  }
1656
1543
  }
1544
+ var package_namespaceObject = JSON.parse('{"i8":"1.42.1-canary-20240226"}');
1657
1545
  async function renderFrontmatterHead(route) {
1658
1546
  if (!isRouteMeta(route)) return '';
1659
1547
  const content = await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readFile(route.absolutePath, {
@@ -1685,7 +1573,7 @@ function renderAttrs(attrs) {
1685
1573
  }).join('');
1686
1574
  }
1687
1575
  function isRouteMeta(route) {
1688
- return 'routePath' in route && 'absolutePath' in route;
1576
+ return !!route && 'object' == typeof route && 'routePath' in route && 'absolutePath' in route;
1689
1577
  }
1690
1578
  async function bundle(docDirectory, config, pluginDriver, enableSSG) {
1691
1579
  try {
@@ -1708,8 +1596,7 @@ async function renderPages(appDirectory, config, pluginDriver, ssgConfig) {
1708
1596
  const outputPath = (null == config ? void 0 : config.outDir) ?? (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(appDirectory, OUTPUT_DIR);
1709
1597
  const ssrBundlePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(outputPath, 'ssr', 'main.cjs');
1710
1598
  try {
1711
- const { version } = await __webpack_require__.e("193").then(__webpack_require__.t.bind(__webpack_require__, "./package.json", 19));
1712
- let render = null;
1599
+ let render;
1713
1600
  if (ssgConfig) try {
1714
1601
  const { default: ssrExports } = await import((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.pathToFileURL)(ssrBundlePath).toString());
1715
1602
  ({ render } = ssrExports);
@@ -1737,10 +1624,7 @@ async function renderPages(appDirectory, config, pluginDriver, ssgConfig) {
1737
1624
  routePath: '/404'
1738
1625
  });
1739
1626
  await Promise.all(allRoutes.filter((route)=>!route.routePath.includes(':')).map(async (route)=>{
1740
- var _helmet_title, _helmet_meta, _helmet_link, _helmet_style, _helmet_script;
1741
- const helmetContext = {
1742
- context: {}
1743
- };
1627
+ const helmetContext = new __WEBPACK_EXTERNAL_MODULE_react_helmet_async_048d06c6__.HelmetData({});
1744
1628
  const { routePath } = route;
1745
1629
  let appHtml = '';
1746
1630
  if (render) try {
@@ -1753,22 +1637,22 @@ async function renderPages(appDirectory, config, pluginDriver, ssgConfig) {
1753
1637
  __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.warn(`Page "${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].yellow(routePath)}" SSG rendering error, fallback to CSR.`, e);
1754
1638
  }
1755
1639
  const { helmet } = helmetContext.context;
1756
- let html = htmlTemplate.replace(/<title>(.*?)<\/title>/gi, '').replace(APP_HTML_MARKER, ()=>appHtml).replace(META_GENERATOR, ()=>`<meta name="generator" content="Rspress v${version}">`).replace(HEAD_MARKER, [
1640
+ let html = htmlTemplate.replace(/<title>(.*?)<\/title>/gi, '').replace(APP_HTML_MARKER, ()=>appHtml).replace(META_GENERATOR, ()=>`<meta name="generator" content="Rspress v${package_namespaceObject.i8}">`).replace(HEAD_MARKER, [
1757
1641
  await renderConfigHead(config, route),
1758
- null == helmet ? void 0 : null === (_helmet_title = helmet.title) || void 0 === _helmet_title ? void 0 : _helmet_title.toString(),
1759
- null == helmet ? void 0 : null === (_helmet_meta = helmet.meta) || void 0 === _helmet_meta ? void 0 : _helmet_meta.toString(),
1760
- null == helmet ? void 0 : null === (_helmet_link = helmet.link) || void 0 === _helmet_link ? void 0 : _helmet_link.toString(),
1761
- null == helmet ? void 0 : null === (_helmet_style = helmet.style) || void 0 === _helmet_style ? void 0 : _helmet_style.toString(),
1762
- null == helmet ? void 0 : null === (_helmet_script = helmet.script) || void 0 === _helmet_script ? void 0 : _helmet_script.toString(),
1642
+ helmet.title.toString(),
1643
+ helmet.meta.toString(),
1644
+ helmet.link.toString(),
1645
+ helmet.style.toString(),
1646
+ helmet.script.toString(),
1763
1647
  await renderFrontmatterHead(route)
1764
1648
  ].join(''));
1765
- if (null == helmet ? void 0 : helmet.htmlAttributes) {
1649
+ if (helmet.htmlAttributes) {
1766
1650
  var _helmet_htmlAttributes;
1767
- html = html.replace(HTML_START_TAG, `${HTML_START_TAG} ${null == helmet ? void 0 : null === (_helmet_htmlAttributes = helmet.htmlAttributes) || void 0 === _helmet_htmlAttributes ? void 0 : _helmet_htmlAttributes.toString()}`);
1651
+ html = html.replace(HTML_START_TAG, `${HTML_START_TAG} ${null === (_helmet_htmlAttributes = helmet.htmlAttributes) || void 0 === _helmet_htmlAttributes ? void 0 : _helmet_htmlAttributes.toString()}`);
1768
1652
  }
1769
- if (null == helmet ? void 0 : helmet.bodyAttributes) {
1653
+ if (helmet.bodyAttributes) {
1770
1654
  var _helmet_bodyAttributes;
1771
- html = html.replace(BODY_START_TAG, `${BODY_START_TAG} ${null == helmet ? void 0 : null === (_helmet_bodyAttributes = helmet.bodyAttributes) || void 0 === _helmet_bodyAttributes ? void 0 : _helmet_bodyAttributes.toString()}`);
1655
+ html = html.replace(BODY_START_TAG, `${BODY_START_TAG} ${null === (_helmet_bodyAttributes = helmet.bodyAttributes) || void 0 === _helmet_bodyAttributes ? void 0 : _helmet_bodyAttributes.toString()}`);
1772
1656
  }
1773
1657
  const normalizeHtmlFilePath = (path)=>{
1774
1658
  const normalizedBase = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeSlash)((null == config ? void 0 : config.base) || '/');
@@ -1786,7 +1670,7 @@ async function renderPages(appDirectory, config, pluginDriver, ssgConfig) {
1786
1670
  const totalTime = Date.now() - startTime;
1787
1671
  __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.success(`Pages rendered in ${__WEBPACK_EXTERNAL_MODULE_picocolors__["default"].yellow(totalTime)} ms.`);
1788
1672
  } catch (e) {
1789
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`Pages render error: ${e.stack}`);
1673
+ if (e instanceof Error) __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`Pages render error: ${e.stack}`);
1790
1674
  throw e;
1791
1675
  }
1792
1676
  }
package/dist/loader.d.ts CHANGED
@@ -1,4 +1,6 @@
1
+ import { AdditionalPage } from '@rspress/shared';
1
2
  import { DefaultThemeConfig } from '@rspress/shared';
3
+ import type { FrontMatterMeta } from '@rspress/shared';
2
4
  import type { PageIndexInfo } from '@rspress/shared';
3
5
  import type { RouteMeta } from '@rspress/shared';
4
6
  import type { Rspack as Rspack_2 } from '@rsbuild/core';
@@ -22,7 +24,7 @@ export declare interface PageMeta {
22
24
  toc: TocItem[];
23
25
  title: string;
24
26
  headingTitle: string;
25
- frontmatter?: Record<string, any>;
27
+ frontmatter?: FrontMatterMeta;
26
28
  }
27
29
 
28
30
  declare class PluginDriver {
@@ -34,18 +36,22 @@ declare class PluginDriver {
34
36
  clearPlugins(): void;
35
37
  removePlugin(pluginName: string): void;
36
38
  modifyConfig(): Promise<UserConfig<DefaultThemeConfig>>;
37
- beforeBuild(): Promise<any>;
38
- afterBuild(): Promise<any>;
39
- modifySearchIndexData(pages: PageIndexInfo[]): Promise<PageIndexInfo[]>;
40
- extendPageData(pageData: PageIndexInfo): Promise<any>;
41
- addPages(): Promise<any>;
42
- routeGenerated(routes: RouteMeta[]): Promise<any>;
39
+ beforeBuild(): Promise<void[]>;
40
+ afterBuild(): Promise<void[]>;
41
+ modifySearchIndexData(pages: PageIndexInfo[]): Promise<void[]>;
42
+ extendPageData(pageData: PageIndexInfo): Promise<void[]>;
43
+ addPages(): Promise<AdditionalPage[]>;
44
+ routeGenerated(routes: RouteMeta[]): Promise<void[]>;
43
45
  addRuntimeModules(): Promise<Record<string, string>>;
44
- addSSGRoutes(): Promise<any>;
46
+ addSSGRoutes(): Promise<({
47
+ path: string;
48
+ } | {
49
+ path: string;
50
+ })[]>;
45
51
  globalUIComponents(): (string | [string, object])[];
46
52
  globalStyles(): string[];
47
- _runParallelAsyncHook(hookName: string, ...args: unknown[]): Promise<any>;
48
- _runSerialAsyncHook(hookName: string, ...args: unknown[]): Promise<any>;
53
+ _runParallelAsyncHook<H extends RspressPluginHookKeys>(hookName: H, ...args: Parameters<Required<RspressPlugin>[H]>): Promise<Awaited<ReturnType<Required<RspressPlugin>[H]>>[]>;
54
+ _runSerialAsyncHook<H extends RspressPluginHookKeys>(hookName: H, ...args: Parameters<Required<RspressPlugin>[H]>): RspressPlugin;
49
55
  }
50
56
 
51
57
  declare class RouteService {
@@ -67,6 +73,8 @@ declare class RouteService {
67
73
  };
68
74
  }
69
75
 
76
+ declare type RspressPluginHookKeys = 'beforeBuild' | 'afterBuild' | 'addPages' | 'addRuntimeModules' | 'routeGenerated' | 'addSSGRoutes' | 'extendPageData' | 'modifySearchIndexData';
77
+
70
78
  declare interface TocItem {
71
79
  id: string;
72
80
  text: string;
package/dist/loader.js CHANGED
@@ -46,9 +46,10 @@ let resolver;
46
46
  let startFlatten = false;
47
47
  const processor = (0, __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__.createProcessor)();
48
48
  const { CachedInputFileSystem, ResolverFactory } = __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__["default"];
49
+ const fileSystem = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"];
49
50
  async function resolveDepPath(importPath, importer, alias) {
50
51
  if (!resolver) resolver = ResolverFactory.createResolver({
51
- fileSystem: new CachedInputFileSystem(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"], 0),
52
+ fileSystem: new CachedInputFileSystem(fileSystem, 0),
52
53
  extensions: [
53
54
  '.mdx',
54
55
  '.md'
@@ -75,7 +76,7 @@ async function flattenMdxContent(content, basePath, alias) {
75
76
  };
76
77
  if (!startFlatten) {
77
78
  resolver = ResolverFactory.createResolver({
78
- fileSystem: new CachedInputFileSystem(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"], 0),
79
+ fileSystem: new CachedInputFileSystem(fileSystem, 0),
79
80
  extensions: [
80
81
  '.mdx',
81
82
  '.md',
@@ -106,7 +107,7 @@ async function flattenMdxContent(content, basePath, alias) {
106
107
  let absoluteImportPath;
107
108
  try {
108
109
  absoluteImportPath = await resolveDepPath(importPath, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(basePath), alias);
109
- } catch (e) {
110
+ } catch (_e) {
110
111
  continue;
111
112
  }
112
113
  if (__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.MDX_REGEXP.test(absoluteImportPath)) {
@@ -143,32 +144,23 @@ const rehypePluginCodeMeta = ()=>(tree)=>{
143
144
  if ('pre' === node.tagName && (null === (_node_children_ = node.children[0]) || void 0 === _node_children_ ? void 0 : _node_children_.type) === 'element' && 'code' === node.children[0].tagName) {
144
145
  var _codeNode_data;
145
146
  const codeNode = node.children[0];
146
- const meta = (null === (_codeNode_data = codeNode.data) || void 0 === _codeNode_data ? void 0 : _codeNode_data.meta) || '';
147
- codeNode.properties.meta = meta;
147
+ codeNode.properties ??= {};
148
+ codeNode.properties.meta = null === (_codeNode_data = codeNode.data) || void 0 === _codeNode_data ? void 0 : _codeNode_data.meta;
148
149
  }
149
150
  });
150
151
  };
151
- const extractTextAndId = (title)=>{
152
- var _title_match_, _title_match;
153
- const customIdReg = /{#.*}/;
154
- const text = title.replace(customIdReg, '').trimEnd();
155
- const customId = (null === (_title_match = title.match(customIdReg)) || void 0 === _title_match ? void 0 : null === (_title_match_ = _title_match[0]) || void 0 === _title_match_ ? void 0 : _title_match_.slice(2, -1)) || '';
156
- return [
157
- text,
158
- customId
159
- ];
160
- };
161
152
  const rehypeHeaderAnchor = ()=>{
162
153
  const slugger = new __WEBPACK_EXTERNAL_MODULE_github_slugger_8e9a17cb__["default"]();
163
- return function(tree) {
164
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'element', function(node) {
165
- if ((0, __WEBPACK_EXTERNAL_MODULE_hast_util_heading_rank_cff646ba__.headingRank)(node)) {
166
- if (!node.properties.id) {
167
- const [text, customId] = collectHeaderText(node);
168
- node.properties.id = customId || slugger.slug(text);
169
- }
170
- node.children.unshift(create(node));
154
+ return (tree)=>{
155
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'element', (node)=>{
156
+ var _node_properties;
157
+ if (!(0, __WEBPACK_EXTERNAL_MODULE_hast_util_heading_rank_cff646ba__.headingRank)(node)) return;
158
+ if (!(null === (_node_properties = node.properties) || void 0 === _node_properties ? void 0 : _node_properties.id)) {
159
+ const [text, customId] = collectHeaderText(node);
160
+ node.properties ??= {};
161
+ node.properties.id = customId || slugger.slug(text);
171
162
  }
163
+ node.children.unshift(create(node));
172
164
  });
173
165
  };
174
166
  };
@@ -177,7 +169,7 @@ const collectHeaderText = (node)=>{
177
169
  let id = '';
178
170
  node.children.forEach((child)=>{
179
171
  if ('text' === child.type) {
180
- const [textPart, idPart] = extractTextAndId(child.value);
172
+ const [textPart, idPart] = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.extractTextAndId)(child.value);
181
173
  child.value = textPart;
182
174
  text += textPart;
183
175
  id = idPart;
@@ -263,8 +255,7 @@ const remarkCheckDeadLinks = (checkLink)=>{
263
255
  const { root, routeService } = checkLink;
264
256
  return (tree, vfile)=>{
265
257
  const internalLinks = new Set();
266
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'link', (node)=>{
267
- const { url } = node;
258
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'link', ({ url })=>{
268
259
  if (!url) return;
269
260
  if (internalLinks.has(url)) return;
270
261
  if (!url.startsWith('http') && !url.startsWith('https')) {
@@ -278,7 +269,7 @@ const remarkCheckDeadLinks = (checkLink)=>{
278
269
  };
279
270
  const remarkPluginNormalizeLink = ({ base, root, cleanUrls })=>(tree, file)=>{
280
271
  const images = [];
281
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, (node)=>'link' === node.type, (node)=>{
272
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'link', (node)=>{
282
273
  if (!node.url) return;
283
274
  if (node.url.startsWith('#')) {
284
275
  node.url = `#${node.url.slice(1)}`;
@@ -325,7 +316,7 @@ const remarkPluginNormalizeLink = ({ base, root, cleanUrls })=>(tree, file)=>{
325
316
  }
326
317
  });
327
318
  (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'image', (node)=>{
328
- const { url } = node;
319
+ const { alt, url } = node;
329
320
  if (!url) return;
330
321
  const imagePath = normalizeImageUrl(url);
331
322
  if (!imagePath) return;
@@ -335,24 +326,21 @@ const remarkPluginNormalizeLink = ({ base, root, cleanUrls })=>(tree, file)=>{
335
326
  name: 'img',
336
327
  children: [],
337
328
  attributes: [
338
- node.alt && {
329
+ alt && {
339
330
  type: 'mdxJsxAttribute',
340
331
  name: 'alt',
341
- value: node.alt
332
+ value: alt
342
333
  },
343
334
  getMdxSrcAttribute(tempVariableName)
344
335
  ].filter(Boolean)
345
336
  });
346
337
  images.push(getASTNodeImport(tempVariableName, imagePath));
347
338
  });
348
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, [
349
- 'mdxJsxFlowElement',
350
- 'mdxJsxTextElement'
351
- ], (node)=>{
352
- if ('img' !== node.name) return;
353
- const src = node.attributes.find((attr)=>'src' === attr.name);
354
- if (!(null == src ? void 0 : src.value) || 'string' != typeof (null == src ? void 0 : src.value)) return;
355
- const imagePath = normalizeImageUrl(src.value);
339
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, (node)=>{
340
+ if ('mdxJsxFlowElement' !== node.type && 'mdxJsxTextElement' !== node.type || 'img' !== node.name) return;
341
+ const src = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.getNodeAttribute)(node, 'src');
342
+ if ('string' != typeof src) return;
343
+ const imagePath = normalizeImageUrl(src);
356
344
  if (!imagePath) return;
357
345
  const tempVariableName = `image${images.length}`;
358
346
  Object.assign(src, getMdxSrcAttribute(tempVariableName));
@@ -386,7 +374,7 @@ const parseToc = (tree)=>{
386
374
  return `~~${null === (_child_children3 = child.children) || void 0 === _child_children3 ? void 0 : _child_children3.map((item)=>item.value).join('')}~~`;
387
375
  }
388
376
  if ('text' === child.type) {
389
- const [textPart, idPart] = extractTextAndId(child.value);
377
+ const [textPart, idPart] = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.extractTextAndId)(child.value);
390
378
  customId = idPart;
391
379
  return textPart;
392
380
  }
@@ -421,7 +409,7 @@ const remarkPluginToc = function() {
421
409
  };
422
410
  async function createMDXOptions(docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver) {
423
411
  var _config_route;
424
- const cleanUrls = Boolean(null == config ? void 0 : null === (_config_route = config.route) || void 0 === _config_route ? void 0 : _config_route.cleanUrls);
412
+ const cleanUrls = (null == config ? void 0 : null === (_config_route = config.route) || void 0 === _config_route ? void 0 : _config_route.cleanUrls) ?? false;
425
413
  const { remarkPlugins: remarkPluginsFromConfig = [], rehypePlugins: rehypePluginsFromConfig = [], globalComponents: globalComponentsFromConfig = [] } = (null == config ? void 0 : config.markdown) || {};
426
414
  const rspressPlugins = pluginDriver.getPlugins();
427
415
  const remarkPluginsFromPlugins = rspressPlugins.flatMap((plugin)=>{
@@ -528,13 +516,15 @@ async function mdxLoader(source) {
528
516
  const preprocessedContent = escapeMarkdownHeadingIds(replacedContent);
529
517
  let enableMdxRs;
530
518
  const mdxRs = (null == config ? void 0 : null === (_config_markdown = config.markdown) || void 0 === _config_markdown ? void 0 : _config_markdown.mdxRs) ?? true;
531
- enableMdxRs = 'object' == typeof mdxRs ? 'function' != typeof (null == mdxRs ? void 0 : mdxRs.include) || mdxRs.include(filepath) : mdxRs;
519
+ enableMdxRs = 'object' == typeof mdxRs ? 'function' == typeof (null == mdxRs ? void 0 : mdxRs.include) ? mdxRs.include(filepath) : true : mdxRs;
532
520
  try {
533
521
  let compileResult;
534
522
  let pageMeta = {
535
523
  title: '',
536
- toc: []
524
+ toc: [],
525
+ headingTitle: ''
537
526
  };
527
+ const frontmatterTitle = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.extractTextAndId)(frontmatter.title)[0];
538
528
  if (enableMdxRs) {
539
529
  const { compile } = await import("@rspress/mdx-rs");
540
530
  const { toc, links, title, code } = await compile({
@@ -544,10 +534,11 @@ async function mdxLoader(source) {
544
534
  development: 'production' !== process.env.NODE_ENV
545
535
  });
546
536
  compileResult = code;
537
+ const headingTitle = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.extractTextAndId)(title)[0];
547
538
  pageMeta = {
548
539
  toc,
549
- title: frontmatter.title || title || '',
550
- headingTitle: title,
540
+ title: frontmatterTitle || headingTitle,
541
+ headingTitle,
551
542
  frontmatter
552
543
  };
553
544
  if (checkDeadLinks) checkLinks(links, filepath, docDirectory, routeService);
@@ -564,10 +555,11 @@ async function mdxLoader(source) {
564
555
  });
565
556
  compileResult = String(vFile);
566
557
  const compilationMeta = compiler.data('pageMeta');
558
+ const headingTitle = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.extractTextAndId)(compilationMeta.title)[0];
567
559
  pageMeta = {
568
560
  ...compilationMeta,
569
- title: frontmatter.title || compilationMeta.title || '',
570
- headingTitle: compilationMeta.title,
561
+ title: frontmatterTitle || headingTitle,
562
+ headingTitle,
571
563
  frontmatter
572
564
  };
573
565
  }
@@ -580,12 +572,14 @@ MDXContent.__RSPRESS_PAGE_META["${encodeURIComponent(normalizePath(__WEBPACK_EXT
580
572
  `;
581
573
  callback(null, result);
582
574
  } catch (e) {
583
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`MDX compile error: ${e.message} in ${filepath}`);
584
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug(e);
585
- callback({
586
- message: e.message,
587
- name: `${filepath} compile error`
588
- });
575
+ if (e instanceof Error) {
576
+ __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`MDX compile error: ${e.message} in ${filepath}`);
577
+ __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug(e);
578
+ callback({
579
+ message: e.message,
580
+ name: `${filepath} compile error`
581
+ });
582
+ }
589
583
  }
590
584
  }
591
585
  export { createCheckPageMetaUpdateFn, mdxLoader as default, updateSiteDataRuntimeModule };
@@ -79,7 +79,7 @@ function App({ helmetContext }) {
79
79
  async function refetchData() {
80
80
  try {
81
81
  const pageData = await initPageData(pathname);
82
- setPageData(pageData);
82
+ null == setPageData || setPageData(pageData);
83
83
  } catch (e) {
84
84
  console.log(e);
85
85
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rspress/core",
3
- "version": "1.42.0",
3
+ "version": "1.42.1-canary-20240226",
4
4
  "description": "The Rspress Documentation Framework",
5
5
  "bugs": "https://github.com/web-infra-dev/rspress/issues",
6
6
  "repository": {
@@ -15,8 +15,7 @@
15
15
  "*.sass",
16
16
  "*.scss",
17
17
  "**/virtual-global-styles.js",
18
- "virtual-global-styles",
19
- "./src/theme-default/styles/index.ts"
18
+ "virtual-global-styles"
20
19
  ],
21
20
  "type": "module",
22
21
  "exports": {
@@ -29,7 +28,6 @@
29
28
  "./theme": {
30
29
  "default": "./theme.ts"
31
30
  },
32
- "./theme.css": "./theme.css",
33
31
  "./runtime": {
34
32
  "default": "./runtime.ts"
35
33
  }
@@ -39,9 +37,6 @@
39
37
  "types": "./dist/index.d.ts",
40
38
  "files": [
41
39
  "dist",
42
- "src/runtime",
43
- "src/theme-default",
44
- "src/shared",
45
40
  "index.html",
46
41
  "runtime.ts",
47
42
  "theme.ts"
@@ -58,7 +53,7 @@
58
53
  "enhanced-resolve": "5.18.0",
59
54
  "github-slugger": "^2.0.0",
60
55
  "hast-util-from-html": "^2.0.3",
61
- "hast-util-heading-rank": "^3.0.0",
56
+ "hast-util-heading-rank": "^2.1.1",
62
57
  "html-to-text": "^9.0.5",
63
58
  "htmr": "^1.0.2",
64
59
  "lodash-es": "^4.17.21",
@@ -77,20 +72,20 @@
77
72
  "tinyglobby": "^0.2.10",
78
73
  "unified": "^10.1.2",
79
74
  "unist-util-visit": "^4.1.2",
80
- "unist-util-visit-children": "^3.0.0",
81
- "@rspress/plugin-auto-nav-sidebar": "1.42.0",
82
- "@rspress/plugin-container-syntax": "1.42.0",
83
- "@rspress/plugin-last-updated": "1.42.0",
84
- "@rspress/plugin-medium-zoom": "1.42.0",
85
- "@rspress/runtime": "1.42.0",
86
- "@rspress/shared": "1.42.0",
87
- "@rspress/theme-default": "1.42.0"
75
+ "unist-util-visit-children": "^2.0.2",
76
+ "@rspress/plugin-auto-nav-sidebar": "1.42.1-canary-20240226",
77
+ "@rspress/plugin-last-updated": "1.42.1-canary-20240226",
78
+ "@rspress/plugin-medium-zoom": "1.42.1-canary-20240226",
79
+ "@rspress/plugin-container-syntax": "1.42.1-canary-20240226",
80
+ "@rspress/runtime": "1.42.1-canary-20240226",
81
+ "@rspress/shared": "1.42.1-canary-20240226",
82
+ "@rspress/theme-default": "1.42.1-canary-20240226"
88
83
  },
89
84
  "devDependencies": {
90
85
  "@microsoft/api-extractor": "^7.49.2",
91
- "@modern-js/tsconfig": "2.64.0",
92
- "@rslib/core": "0.4.1",
93
- "@types/hast": "3.0.4",
86
+ "@rslib/core": "0.5.2",
87
+ "@rspress-dev/plugin-preview": "link:../plugin-preview",
88
+ "@types/hast": "^2.3.10",
94
89
  "@types/html-to-text": "^9.0.4",
95
90
  "@types/jest": "~29.5.14",
96
91
  "@types/lodash-es": "^4.17.12",
@@ -104,7 +99,8 @@
104
99
  "remark-rehype": "^10.1.0",
105
100
  "rimraf": "^3.0.2",
106
101
  "tailwindcss": "^3.4.17",
107
- "typescript": "^5.5.3"
102
+ "typescript": "^5.5.3",
103
+ "@rspress/config": "1.0.0"
108
104
  },
109
105
  "engines": {
110
106
  "node": ">=14.17.6"
@@ -114,7 +110,6 @@
114
110
  "provenance": true,
115
111
  "registry": "https://registry.npmjs.org/"
116
112
  },
117
- "jsnext:source": "./src/index.ts",
118
113
  "scripts": {
119
114
  "build": "rslib build",
120
115
  "dev": "rslib build -w",
package/dist/193.js DELETED
@@ -1,12 +0,0 @@
1
- import __rslib_shim_module__ from 'module';
2
- /*#__PURE__*/ import.meta.url;
3
- export const ids = [
4
- '193'
5
- ];
6
- export const modules = {
7
- "./package.json": function(module) {
8
- module.exports = {
9
- version: "1.42.0"
10
- };
11
- }
12
- };
@@ -1,176 +0,0 @@
1
- import {
2
- DataContext,
3
- isEqualPath,
4
- pathnameToRouteService,
5
- useLocation,
6
- } from '@rspress/runtime';
7
- import {
8
- type Header,
9
- MDX_REGEXP,
10
- type PageData,
11
- cleanUrl,
12
- } from '@rspress/shared';
13
- import Theme from '@theme';
14
- import React, { useContext, useLayoutEffect } from 'react';
15
- import { HelmetProvider } from 'react-helmet-async';
16
- import globalComponents from 'virtual-global-components';
17
- import siteData from 'virtual-site-data';
18
- import 'virtual-global-styles';
19
-
20
- export enum QueryStatus {
21
- Show = '1',
22
- Hide = '0',
23
- }
24
-
25
- type PageMeta = {
26
- title: string;
27
- headingTitle: string;
28
- toc: Header[];
29
- frontmatter: Record<string, any>;
30
- };
31
-
32
- export async function initPageData(routePath: string): Promise<PageData> {
33
- const matchedRoute = pathnameToRouteService(routePath)!;
34
- if (matchedRoute) {
35
- // Preload route component
36
- const mod = await matchedRoute.preload();
37
- const pagePath = cleanUrl(matchedRoute.filePath);
38
- const extractPageInfo = siteData.pages.find(page => {
39
- const normalize = (p: string) =>
40
- // compat the path that has no / suffix and ignore case
41
- p
42
- .replace(/\/$/, '')
43
- .toLowerCase();
44
- return isEqualPath(
45
- normalize(page.routePath),
46
- normalize(matchedRoute.path),
47
- );
48
- });
49
-
50
- // FIXME: when sidebar item is configured as link string, the sidebar text won't updated when page title changed
51
- // Reason: The sidebar item text depends on pageData, which is not updated when page title changed, because the pageData is computed once when build
52
- const encodedPagePath = encodeURIComponent(pagePath);
53
- const meta: PageMeta =
54
- (
55
- mod.default as unknown as {
56
- __RSPRESS_PAGE_META: Record<string, PageMeta>;
57
- }
58
- ).__RSPRESS_PAGE_META?.[encodedPagePath] || ({} as PageMeta);
59
- // mdx loader will generate __RSPRESS_PAGE_META,
60
- // if the filePath don't match it, we can get meta from j(t)sx if we customize it
61
- const {
62
- toc = [],
63
- title = '',
64
- frontmatter = {},
65
- ...rest
66
- } = MDX_REGEXP.test(matchedRoute.filePath)
67
- ? meta
68
- : (mod as unknown as PageMeta);
69
- return {
70
- siteData,
71
- page: {
72
- ...rest,
73
- pagePath,
74
- ...extractPageInfo,
75
- pageType: frontmatter?.pageType || 'doc',
76
- title,
77
- frontmatter,
78
- toc,
79
- },
80
- };
81
- }
82
-
83
- let lang = siteData.lang || '';
84
- let version = siteData.multiVersion?.default || '';
85
-
86
- if (siteData.lang && typeof window !== 'undefined') {
87
- const path = location.pathname
88
- .replace(siteData.base, '')
89
- .split('/')
90
- .slice(0, 2);
91
-
92
- if (siteData.locales.length) {
93
- const result = siteData.locales.find(({ lang }) => path.includes(lang));
94
-
95
- if (result) {
96
- lang = result.lang;
97
- }
98
- }
99
-
100
- if (siteData.multiVersion.versions) {
101
- const result = siteData.multiVersion.versions.find(version =>
102
- path.includes(version),
103
- );
104
-
105
- if (result) {
106
- version = result;
107
- }
108
- }
109
- }
110
-
111
- // 404 Page
112
- return {
113
- siteData,
114
- page: {
115
- pagePath: '',
116
- pageType: '404',
117
- routePath: '/404',
118
- lang,
119
- frontmatter: {},
120
- title: '404',
121
- toc: [],
122
- version,
123
- _filepath: '',
124
- _relativePath: '',
125
- },
126
- };
127
- }
128
-
129
- export function App({ helmetContext }: { helmetContext?: object }) {
130
- const { setData: setPageData, data } = useContext(DataContext);
131
- const frontmatter = data.page.frontmatter || {};
132
- const { pathname, search } = useLocation();
133
- const query = new URLSearchParams(search);
134
- const GLOBAL_COMPONENTS_KEY = 'globalUIComponents';
135
- const hideGlobalUIComponents =
136
- // Disable global components in frontmatter or query
137
- frontmatter[GLOBAL_COMPONENTS_KEY] === false ||
138
- query.get(GLOBAL_COMPONENTS_KEY) === QueryStatus.Hide;
139
- useLayoutEffect(() => {
140
- async function refetchData() {
141
- try {
142
- const pageData = await initPageData(pathname);
143
- setPageData(pageData);
144
- } catch (e) {
145
- console.log(e);
146
- }
147
- }
148
- refetchData();
149
- }, [pathname, setPageData]);
150
-
151
- return (
152
- <HelmetProvider context={helmetContext}>
153
- <Theme.Layout />
154
- {
155
- // Global UI
156
- !hideGlobalUIComponents &&
157
- globalComponents.map((componentInfo, index) => {
158
- if (Array.isArray(componentInfo)) {
159
- const [component, props] = componentInfo;
160
- return React.createElement(component, {
161
- // The component order is stable
162
- // eslint-disable-next-line react/no-array-index-key
163
- key: index,
164
- ...props,
165
- });
166
- }
167
-
168
- return React.createElement(componentInfo, {
169
- // eslint-disable-next-line react/no-array-index-key
170
- key: index,
171
- });
172
- })
173
- }
174
- </HelmetProvider>
175
- );
176
- }
@@ -1,56 +0,0 @@
1
- import { BrowserRouter, DataContext, ThemeContext } from '@rspress/runtime';
2
- import { isProduction } from '@rspress/shared';
3
- import { useMemo, useState } from 'react';
4
- import siteData from 'virtual-site-data';
5
- import { App, initPageData } from './App';
6
-
7
- const enableSSG = siteData.ssg;
8
-
9
- // eslint-disable-next-line import/no-commonjs
10
- const { default: Theme, useThemeState } = require('@theme');
11
-
12
- export async function renderInBrowser() {
13
- const container = document.getElementById('root')!;
14
-
15
- const enhancedApp = async () => {
16
- const initialPageData = await initPageData(window.location.pathname);
17
-
18
- return function RootApp() {
19
- const [data, setData] = useState(initialPageData);
20
- const [theme, setTheme] = useThemeState();
21
- return (
22
- <ThemeContext.Provider
23
- value={useMemo(() => ({ theme, setTheme }), [theme, setTheme])}
24
- >
25
- <DataContext.Provider
26
- value={useMemo(() => ({ data, setData }), [data, setData])}
27
- >
28
- <BrowserRouter>
29
- <App />
30
- </BrowserRouter>
31
- </DataContext.Provider>
32
- </ThemeContext.Provider>
33
- );
34
- };
35
- };
36
- const RootApp = await enhancedApp();
37
- if (process.env.__REACT_GTE_18__) {
38
- const { createRoot, hydrateRoot } = require('react-dom/client');
39
- if (isProduction() && enableSSG) {
40
- hydrateRoot(container, <RootApp />);
41
- } else {
42
- createRoot(container).render(<RootApp />);
43
- }
44
- } else {
45
- const ReactDOM = require('react-dom');
46
- if (isProduction()) {
47
- ReactDOM.hydrate(<RootApp />, container);
48
- } else {
49
- ReactDOM.render(<RootApp />, container);
50
- }
51
- }
52
- }
53
-
54
- renderInBrowser().then(() => {
55
- Theme.setup();
56
- });
@@ -1,52 +0,0 @@
1
- declare module 'virtual-routes' {
2
- export { Route } from '@rspress/shared';
3
-
4
- export const routes: Route[];
5
- }
6
-
7
- declare module 'virtual-routes-ssr' {
8
- export { Route } from '@rspress/shared';
9
-
10
- export const routes: Route[];
11
- }
12
-
13
- declare module 'virtual-site-data' {
14
- import { SiteData, DefaultThemeConfig } from '@rspress/shared';
15
-
16
- const data: SiteData<DefaultThemeConfig>;
17
- export default data;
18
- }
19
-
20
- declare module 'virtual-search-index-hash' {
21
- const hash: string;
22
- export default hash;
23
- }
24
-
25
- declare module 'virtual-global-components' {
26
- import { ComponentType } from 'react';
27
-
28
- const components: (ComponentType | [ComponentType, any])[];
29
- export default components;
30
- }
31
-
32
- declare module 'virtual-global-styles';
33
-
34
- declare module 'virtual-i18n-text';
35
-
36
- declare module 'virtual-search-hooks' {
37
- export const onSearch: (query: string) => void | Promise<void>;
38
- }
39
-
40
- declare module '*.module.scss' {
41
- const classes: { [key: string]: string };
42
- export default classes;
43
- }
44
-
45
- declare module '*.svg' {
46
- export const ReactComponent: React.SFC<React.SVGProps<SVGSVGElement>>;
47
- export default ReactComponent;
48
- }
49
-
50
- declare module '@theme' {
51
- export * from '@rspress/theme-default';
52
- }
@@ -1,31 +0,0 @@
1
- import { DataContext, ThemeContext } from '@rspress/runtime';
2
- import { StaticRouter } from '@rspress/runtime/server';
3
- import type { PageData } from '@rspress/shared';
4
- import { renderToString } from 'react-dom/server';
5
- import { App, initPageData } from './App';
6
-
7
- const DEFAULT_THEME = 'light';
8
-
9
- export async function render(
10
- pagePath: string,
11
- helmetContext: object,
12
- ): Promise<{ appHtml: string; pageData: PageData }> {
13
- const initialPageData = await initPageData(pagePath);
14
-
15
- const appHtml = renderToString(
16
- <ThemeContext.Provider value={{ theme: DEFAULT_THEME }}>
17
- <DataContext.Provider value={{ data: initialPageData }}>
18
- <StaticRouter location={pagePath}>
19
- <App helmetContext={helmetContext} />
20
- </StaticRouter>
21
- </DataContext.Provider>
22
- </ThemeContext.Provider>,
23
- );
24
-
25
- return {
26
- appHtml,
27
- pageData: initialPageData,
28
- };
29
- }
30
-
31
- export { routes } from 'virtual-routes-ssr';
@@ -1,10 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "rootDir": ".",
4
- "baseUrl": ".",
5
- "skipLibCheck": true,
6
- "jsx": "react-jsx",
7
- "esModuleInterop": true
8
- },
9
- "include": ["./**/*"]
10
- }