@rspress/core 1.41.0 → 1.41.2

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/loader.js CHANGED
@@ -1,728 +1,596 @@
1
- import { createRequire } from "module";
2
- const { url } = import.meta;
3
- const require = createRequire(url);
4
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
- }) : x)(function(x) {
7
- if (typeof require !== "undefined")
8
- return require.apply(this, arguments);
9
- throw Error('Dynamic require of "' + x + '" is not supported');
10
- });
11
-
12
- // src/node/mdx/loader.ts
13
- import fs2 from "fs/promises";
14
- import path8 from "path";
15
- import { pathToFileURL } from "url";
16
- import { createProcessor as createProcessor2 } from "@mdx-js/mdx";
17
- import { isProduction as isProduction2 } from "@rspress/shared";
18
- import { logger as logger2 } from "@rspress/shared/logger";
19
- import { loadFrontMatter } from "@rspress/shared/node-utils";
20
-
21
- // src/node/constants.ts
22
- import path from "path";
23
- import { fileURLToPath } from "url";
24
- import { APPEARANCE_KEY, RSPRESS_TEMP_DIR } from "@rspress/shared";
25
- var importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
26
- var inlineThemeScript = `{
27
- const saved = localStorage.getItem('${APPEARANCE_KEY}')
1
+ import __rslib_shim_module__ from 'module';
2
+ const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(import.meta.url);
3
+ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__ from "node:fs/promises";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
5
+ import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
6
+ import * as __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__ from "@mdx-js/mdx";
7
+ import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__ from "@rspress/shared";
8
+ import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__ from "@rspress/shared/logger";
9
+ import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__ from "@rspress/shared/node-utils";
10
+ import "rspack-plugin-virtual-module";
11
+ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
12
+ import * as __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__ from "enhanced-resolve";
13
+ import * as __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__ from "node:os";
14
+ import * as __WEBPACK_EXTERNAL_MODULE_rehype_external_links_09bed11a__ from "rehype-external-links";
15
+ import * as __WEBPACK_EXTERNAL_MODULE_remark_gfm_073acf21__ from "remark-gfm";
16
+ import * as __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__ from "unist-util-visit";
17
+ import * as __WEBPACK_EXTERNAL_MODULE_github_slugger_8e9a17cb__ from "github-slugger";
18
+ import * as __WEBPACK_EXTERNAL_MODULE_hast_util_heading_rank_cff646ba__ from "hast-util-heading-rank";
19
+ import * as __WEBPACK_EXTERNAL_MODULE_unist_util_visit_children_71921007__ from "unist-util-visit-children";
20
+ var __webpack_modules__ = {
21
+ "@rspress/mdx-rs": function(module) {
22
+ module.exports = require("@rspress/mdx-rs");
23
+ }
24
+ };
25
+ var __webpack_module_cache__ = {};
26
+ function __webpack_require__(moduleId) {
27
+ var cachedModule = __webpack_module_cache__[moduleId];
28
+ if (void 0 !== cachedModule) return cachedModule.exports;
29
+ var module = __webpack_module_cache__[moduleId] = {
30
+ exports: {}
31
+ };
32
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
33
+ return module.exports;
34
+ }
35
+ const importStatementRegex = /import\s+(.*?)\s+from\s+(['"])(.*?)(?:"|');?/gm;
36
+ `{
37
+ const saved = localStorage.getItem('${__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.APPEARANCE_KEY}')
28
38
  const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
29
39
  const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
30
40
  document.documentElement.classList.toggle('dark', isDark)
31
41
  document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
32
- }`.replace(/\n/g, ";").replace(/\s{2,}/g, "");
33
- var dirname = path.dirname(fileURLToPath(new URL(import.meta.url)));
34
- var PACKAGE_ROOT = path.join(dirname, "..");
35
- var CLIENT_ENTRY = path.join(
36
- PACKAGE_ROOT,
37
- "dist",
38
- "runtime",
39
- "clientEntry.js"
40
- );
41
- var SSR_ENTRY = path.join(
42
- PACKAGE_ROOT,
43
- "dist",
44
- "runtime",
45
- "ssrEntry.js"
46
- );
47
- var TEMP_DIR = path.join(
48
- process.cwd(),
49
- "node_modules",
50
- RSPRESS_TEMP_DIR
51
- );
52
-
53
- // src/node/utils/normalizePath.ts
54
- import os from "os";
55
- import path2 from "path";
56
- var isWindows = os.platform() === "win32";
57
- function slash(p) {
58
- return p.replace(/\\/g, "/");
59
- }
60
- function normalizePath(id) {
61
- return path2.posix.normalize(isWindows ? slash(id) : id);
62
- }
63
-
64
- // src/node/utils/getASTNodeImport.ts
65
- var getASTNodeImport = (name, from) => ({
66
- type: "mdxjsEsm",
67
- value: `import ${name} from ${JSON.stringify(from)}`,
68
- data: {
69
- estree: {
70
- type: "Program",
71
- sourceType: "module",
72
- body: [
73
- {
74
- type: "ImportDeclaration",
75
- specifiers: [
76
- {
77
- type: "ImportDefaultSpecifier",
78
- local: { type: "Identifier", name }
79
- }
80
- ],
81
- source: {
82
- type: "Literal",
83
- value: from,
84
- raw: `${JSON.stringify(from)}`
85
- }
86
- }
87
- ]
88
- }
89
- }
90
- });
91
-
92
- // src/node/utils/flattenMdxContent.ts
93
- import fs from "fs";
94
- import path3 from "path";
95
- import { createProcessor } from "@mdx-js/mdx";
96
- import { MDX_REGEXP } from "@rspress/shared";
97
- import enhancedResolve from "enhanced-resolve";
98
- var resolver;
99
- var startFlatten = false;
100
- var processor = createProcessor();
101
- var { CachedInputFileSystem, ResolverFactory } = enhancedResolve;
42
+ }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
43
+ const dirname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileURLToPath)(new URL(import.meta.url)));
44
+ const PACKAGE_ROOT = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(dirname, '..');
45
+ __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'clientEntry.js');
46
+ __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrEntry.js');
47
+ const TEMP_DIR = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(process.cwd(), 'node_modules', __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.RSPRESS_TEMP_DIR);
48
+ var runtimeModule_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
49
+ RuntimeModuleID["GlobalStyles"] = "virtual-global-styles";
50
+ RuntimeModuleID["GlobalComponents"] = "virtual-global-components";
51
+ RuntimeModuleID["RouteForClient"] = "virtual-routes";
52
+ RuntimeModuleID["RouteForSSR"] = "virtual-routes-ssr";
53
+ RuntimeModuleID["SiteData"] = "virtual-site-data";
54
+ RuntimeModuleID["SearchIndexHash"] = "virtual-search-index-hash";
55
+ RuntimeModuleID["I18nText"] = "virtual-i18n-text";
56
+ RuntimeModuleID["SearchHooks"] = "virtual-search-hooks";
57
+ RuntimeModuleID["PrismLanguages"] = "virtual-prism-languages";
58
+ return RuntimeModuleID;
59
+ }({});
60
+ let resolver;
61
+ let startFlatten = false;
62
+ const processor = (0, __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__.createProcessor)();
63
+ const { CachedInputFileSystem, ResolverFactory } = __WEBPACK_EXTERNAL_MODULE_enhanced_resolve_bf4706da__["default"];
102
64
  async function resolveDepPath(importPath, importer, alias) {
103
- if (!resolver) {
104
- resolver = ResolverFactory.createResolver({
105
- fileSystem: new CachedInputFileSystem(fs, 0),
106
- extensions: [".mdx", ".md"],
107
- alias
65
+ if (!resolver) resolver = ResolverFactory.createResolver({
66
+ fileSystem: new CachedInputFileSystem(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"], 0),
67
+ extensions: [
68
+ '.mdx',
69
+ '.md'
70
+ ],
71
+ alias
108
72
  });
109
- }
110
- const resolveResult = await new Promise((resolve, reject) => {
111
- resolver.resolve(
112
- {
113
- importer
114
- },
115
- importer,
116
- importPath,
117
- {},
118
- (err, filePath) => {
119
- if (err) {
120
- return reject(err);
121
- }
122
- if (!filePath) {
123
- return reject(
124
- new Error(
125
- `Empty result when resolving ${importPath} from ${importer}`
126
- )
127
- );
128
- }
129
- return resolve(filePath);
130
- }
131
- );
132
- });
133
- return resolveResult;
73
+ const resolveResult = await new Promise((resolve, reject)=>{
74
+ resolver.resolve({
75
+ importer
76
+ }, importer, importPath, {}, (err, filePath)=>{
77
+ if (err) return reject(err);
78
+ if (!filePath) return reject(new Error(`Empty result when resolving ${importPath} from ${importer}`));
79
+ return resolve(filePath);
80
+ });
81
+ });
82
+ return resolveResult;
134
83
  }
135
84
  async function flattenMdxContent(content, basePath, alias) {
136
- const deps = [];
137
- const regex = new RegExp(importStatementRegex);
138
- if (!regex.test(content)) {
139
- return { flattenContent: content, deps };
140
- }
141
- if (!startFlatten) {
142
- resolver = ResolverFactory.createResolver({
143
- fileSystem: new CachedInputFileSystem(fs, 0),
144
- extensions: [".mdx", ".md", ".js"],
145
- alias
146
- });
147
- startFlatten = true;
148
- }
149
- let ast;
150
- let result = content;
151
- try {
152
- ast = processor.parse(content);
153
- } catch (e) {
154
- return { flattenContent: content, deps };
155
- }
156
- const importNodes = ast.children.filter((node) => node.type === "mdxjsEsm").flatMap((node) => node.data?.estree?.body || []).filter((node) => node.type === "ImportDeclaration");
157
- for (const importNode of importNodes) {
158
- const id = importNode.specifiers[0].local.name;
159
- const importPath = importNode.source.value;
160
- let absoluteImportPath;
85
+ const deps = [];
86
+ const regex = new RegExp(importStatementRegex);
87
+ if (!regex.test(content)) return {
88
+ flattenContent: content,
89
+ deps
90
+ };
91
+ if (!startFlatten) {
92
+ resolver = ResolverFactory.createResolver({
93
+ fileSystem: new CachedInputFileSystem(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"], 0),
94
+ extensions: [
95
+ '.mdx',
96
+ '.md',
97
+ '.js'
98
+ ],
99
+ alias
100
+ });
101
+ startFlatten = true;
102
+ }
103
+ let ast;
104
+ let result = content;
161
105
  try {
162
- absoluteImportPath = await resolveDepPath(
163
- importPath,
164
- path3.dirname(basePath),
165
- alias
166
- );
106
+ ast = processor.parse(content);
167
107
  } catch (e) {
168
- continue;
108
+ return {
109
+ flattenContent: content,
110
+ deps
111
+ };
169
112
  }
170
- if (MDX_REGEXP.test(absoluteImportPath)) {
171
- const importedContent = fs.readFileSync(absoluteImportPath, "utf-8");
172
- const { flattenContent: replacedValue, deps: subDeps } = await flattenMdxContent(importedContent, absoluteImportPath, alias);
173
- result = result.replace(
174
- new RegExp(`import\\s+${id}\\s+from\\s+['"](${importPath})['"];?`),
175
- ""
176
- ).replace(new RegExp(`<${id}\\s*/>`, "g"), () => replacedValue);
177
- deps.push(...subDeps, absoluteImportPath);
113
+ const importNodes = ast.children.filter((node)=>'mdxjsEsm' === node.type).flatMap((node)=>{
114
+ var _node_data_estree, _node_data;
115
+ return (null === (_node_data = node.data) || void 0 === _node_data ? void 0 : null === (_node_data_estree = _node_data.estree) || void 0 === _node_data_estree ? void 0 : _node_data_estree.body) || [];
116
+ }).filter((node)=>'ImportDeclaration' === node.type);
117
+ for (const importNode of importNodes){
118
+ const id = importNode.specifiers[0].local.name;
119
+ const importPath = importNode.source.value;
120
+ let absoluteImportPath;
121
+ try {
122
+ absoluteImportPath = await resolveDepPath(importPath, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(basePath), alias);
123
+ } catch (e) {
124
+ continue;
125
+ }
126
+ if (__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.MDX_REGEXP.test(absoluteImportPath)) {
127
+ const importedContent = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(absoluteImportPath, 'utf-8');
128
+ const { flattenContent: replacedValue, deps: subDeps } = await flattenMdxContent(importedContent, absoluteImportPath, alias);
129
+ result = result.replace(new RegExp(`import\\s+${id}\\s+from\\s+['"](${importPath})['"];?`), '').replace(new RegExp(`<${id}\\s*/>`, 'g'), ()=>replacedValue);
130
+ deps.push(...subDeps, absoluteImportPath);
131
+ }
178
132
  }
179
- }
180
- return { flattenContent: result, deps };
133
+ return {
134
+ flattenContent: result,
135
+ deps
136
+ };
181
137
  }
182
-
183
- // src/node/utils/applyReplaceRules.ts
184
- function applyReplaceRules(code = "", replaceRules = []) {
185
- let result = code;
186
- for (const rule of replaceRules) {
187
- result = result.replace(rule.search, rule.replace);
188
- }
189
- return result;
138
+ function applyReplaceRules(code = '', replaceRules = []) {
139
+ let result = code;
140
+ for (const rule of replaceRules)result = result.replace(rule.search, rule.replace);
141
+ return result;
190
142
  }
191
-
192
- // src/node/utils/extractTextAndId.ts
193
- var extractTextAndId = (title) => {
194
- const customIdReg = /{#.*}/;
195
- const text = title.replace(customIdReg, "").trimEnd();
196
- const customId = title.match(customIdReg)?.[0]?.slice(2, -1) || "";
197
- return [text, customId];
198
- };
199
-
200
- // src/node/utils/escapeHeadingIds.ts
201
143
  function escapeMarkdownHeadingIds(content) {
202
- const markdownHeadingRegexp = /(?:^|\n)#{1,6}(?!#).*/g;
203
- return content.replace(
204
- markdownHeadingRegexp,
205
- (substring) => substring.replace("{#", "\\{#").replace("\\\\{#", "\\{#")
206
- );
144
+ const markdownHeadingRegexp = /(?:^|\n)#{1,6}(?!#).*/g;
145
+ return content.replace(markdownHeadingRegexp, (substring)=>substring.replace('{#', '\\{#').replace('\\\\{#', '\\{#'));
207
146
  }
208
-
209
- // src/node/mdx/options.ts
210
- import path7 from "path";
211
- import rehypePluginExternalLinks from "rehype-external-links";
212
- import remarkGFM from "remark-gfm";
213
-
214
- // src/node/mdx/rehypePlugins/codeMeta.ts
215
- import { visit } from "unist-util-visit";
216
- var rehypePluginCodeMeta = () => {
217
- return (tree) => {
218
- visit(tree, "element", (node) => {
219
- if (node.tagName === "pre" && node.children[0]?.type === "element" && node.children[0].tagName === "code") {
220
- const codeNode = node.children[0];
221
- const meta = codeNode.data?.meta || "";
222
- codeNode.properties.meta = meta;
223
- }
224
- });
225
- };
147
+ const isWindows = 'win32' === __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__["default"].platform();
148
+ function slash(p) {
149
+ return p.replace(/\\/g, '/');
150
+ }
151
+ function normalizePath(id) {
152
+ return __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.normalize(isWindows ? slash(id) : id);
153
+ }
154
+ const rehypePluginCodeMeta = ()=>(tree)=>{
155
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'element', (node)=>{
156
+ var _node_children_;
157
+ 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) {
158
+ var _codeNode_data;
159
+ const codeNode = node.children[0];
160
+ const meta = (null === (_codeNode_data = codeNode.data) || void 0 === _codeNode_data ? void 0 : _codeNode_data.meta) || '';
161
+ codeNode.properties.meta = meta;
162
+ }
163
+ });
164
+ };
165
+ const extractTextAndId = (title)=>{
166
+ var _title_match_, _title_match;
167
+ const customIdReg = /{#.*}/;
168
+ const text = title.replace(customIdReg, '').trimEnd();
169
+ 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)) || '';
170
+ return [
171
+ text,
172
+ customId
173
+ ];
226
174
  };
227
-
228
- // src/node/mdx/rehypePlugins/headerAnchor.ts
229
- import GithubSlugger from "github-slugger";
230
- import { headingRank } from "hast-util-heading-rank";
231
- import { visit as visit2 } from "unist-util-visit";
232
- var rehypeHeaderAnchor = () => {
233
- const slugger = new GithubSlugger();
234
- return function(tree) {
235
- visit2(tree, "element", function(node) {
236
- if (headingRank(node)) {
237
- if (!node.properties.id) {
238
- const [text, customId] = collectHeaderText(node);
239
- node.properties.id = customId || slugger.slug(text);
240
- }
241
- node.children.unshift(create(node));
242
- }
243
- });
244
- };
175
+ const rehypeHeaderAnchor = ()=>{
176
+ const slugger = new __WEBPACK_EXTERNAL_MODULE_github_slugger_8e9a17cb__["default"]();
177
+ return function(tree) {
178
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'element', function(node) {
179
+ if ((0, __WEBPACK_EXTERNAL_MODULE_hast_util_heading_rank_cff646ba__.headingRank)(node)) {
180
+ if (!node.properties.id) {
181
+ const [text, customId] = collectHeaderText(node);
182
+ node.properties.id = customId || slugger.slug(text);
183
+ }
184
+ node.children.unshift(create(node));
185
+ }
186
+ });
187
+ };
245
188
  };
246
- var collectHeaderText = (node) => {
247
- let text = "";
248
- let id = "";
249
- node.children.forEach((child) => {
250
- if (child.type === "text") {
251
- const [textPart, idPart] = extractTextAndId(child.value);
252
- child.value = textPart;
253
- text += textPart;
254
- id = idPart;
255
- }
256
- if (child.type === "element") {
257
- child.children.forEach((c) => {
258
- if (c.type === "text") {
259
- text += c.value;
189
+ const collectHeaderText = (node)=>{
190
+ let text = '';
191
+ let id = '';
192
+ node.children.forEach((child)=>{
193
+ if ('text' === child.type) {
194
+ const [textPart, idPart] = extractTextAndId(child.value);
195
+ child.value = textPart;
196
+ text += textPart;
197
+ id = idPart;
260
198
  }
261
- });
262
- }
263
- });
264
- return [text, id];
199
+ if ('element' === child.type) child.children.forEach((c)=>{
200
+ if ('text' === c.type) text += c.value;
201
+ });
202
+ });
203
+ return [
204
+ text,
205
+ id
206
+ ];
265
207
  };
266
208
  function create(node) {
267
- return {
268
- type: "element",
269
- tagName: "a",
270
- properties: {
271
- class: "header-anchor",
272
- ariaHidden: "true",
273
- href: `#${node.properties.id}`
274
- },
275
- children: [
276
- {
277
- type: "text",
278
- value: "#"
279
- }
280
- ]
281
- };
209
+ return {
210
+ type: 'element',
211
+ tagName: 'a',
212
+ properties: {
213
+ class: 'header-anchor',
214
+ ariaHidden: 'true',
215
+ href: `#${node.properties.id}`
216
+ },
217
+ children: [
218
+ {
219
+ type: 'text',
220
+ value: '#'
221
+ }
222
+ ]
223
+ };
282
224
  }
283
-
284
- // src/node/mdx/remarkPlugins/builtin.ts
285
- import path4 from "path";
286
- var remarkBuiltin = ({
287
- globalComponents
288
- }) => {
289
- return (tree) => {
290
- const demos = globalComponents.map((componentPath) => {
291
- const filename = path4.parse(componentPath).name;
292
- const componentName = filename[0].toUpperCase() + filename.slice(1);
293
- return getASTNodeImport(componentName, componentPath);
225
+ const getASTNodeImport = (name, from)=>({
226
+ type: 'mdxjsEsm',
227
+ value: `import ${name} from ${JSON.stringify(from)}`,
228
+ data: {
229
+ estree: {
230
+ type: 'Program',
231
+ sourceType: 'module',
232
+ body: [
233
+ {
234
+ type: 'ImportDeclaration',
235
+ specifiers: [
236
+ {
237
+ type: 'ImportDefaultSpecifier',
238
+ local: {
239
+ type: 'Identifier',
240
+ name
241
+ }
242
+ }
243
+ ],
244
+ source: {
245
+ type: 'Literal',
246
+ value: from,
247
+ raw: `${JSON.stringify(from)}`
248
+ }
249
+ }
250
+ ]
251
+ }
252
+ }
294
253
  });
295
- tree.children.unshift(...demos);
296
- };
297
- };
298
-
299
- // src/node/mdx/remarkPlugins/checkDeadLink.ts
300
- import path5 from "path";
301
- import { cleanUrl, isProduction } from "@rspress/shared";
302
- import { logger } from "@rspress/shared/logger";
303
- import { visit as visit3 } from "unist-util-visit";
304
- var IGNORE_REGEXP = /^(https?|mailto|tel|#)/;
254
+ const remarkBuiltin = ({ globalComponents })=>(tree)=>{
255
+ const demos = globalComponents.map((componentPath)=>{
256
+ const filename = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].parse(componentPath).name;
257
+ const componentName = filename[0].toUpperCase() + filename.slice(1);
258
+ return getASTNodeImport(componentName, componentPath);
259
+ });
260
+ tree.children.unshift(...demos);
261
+ };
262
+ const IGNORE_REGEXP = /^(https?|mailto|tel|#)/;
305
263
  function checkLinks(links, filepath, root, routeService) {
306
- const errorInfos = [];
307
- links.filter((link) => !IGNORE_REGEXP.test(link)).map((link) => normalizePath(link)).forEach((link) => {
308
- const relativePath = path5.relative(root, filepath);
309
- if (!routeService.isExistRoute(cleanUrl(link))) {
310
- errorInfos.push(
311
- `Internal link to ${link} is dead, check it in ${relativePath}`
312
- );
313
- }
314
- });
315
- if (errorInfos.length > 0) {
316
- errorInfos?.forEach((err) => {
317
- logger.error(err);
264
+ const errorInfos = [];
265
+ links.filter((link)=>!IGNORE_REGEXP.test(link)).map((link)=>normalizePath(link)).forEach((link)=>{
266
+ const relativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(root, filepath);
267
+ if (!routeService.isExistRoute((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.cleanUrl)(link))) errorInfos.push(`Internal link to ${link} is dead, check it in ${relativePath}`);
318
268
  });
319
- if (isProduction()) {
320
- throw new Error("Dead link found");
269
+ if (errorInfos.length > 0) {
270
+ null == errorInfos || errorInfos.forEach((err)=>{
271
+ __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(err);
272
+ });
273
+ if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isProduction)()) throw new Error('Dead link found');
321
274
  }
322
- }
323
275
  }
324
- var remarkCheckDeadLinks = (checkLink) => {
325
- const { root, routeService } = checkLink;
326
- return (tree, vfile) => {
327
- const internalLinks = /* @__PURE__ */ new Set();
328
- visit3(tree, "link", (node) => {
329
- const { url } = node;
330
- if (!url) {
331
- return;
332
- }
333
- if (internalLinks.has(url)) {
334
- return;
335
- }
336
- if (!url.startsWith("http") && !url.startsWith("https")) {
337
- const { routePath: normalizeUrl } = routeService.normalizeRoutePath(
338
- // fix: windows path
339
- url.split(path5.sep).join("/")?.split("#")[0]
340
- );
341
- internalLinks.add(normalizeUrl);
342
- }
343
- });
344
- checkLinks(Array.from(internalLinks), vfile.path, root, routeService);
345
- };
276
+ const remarkCheckDeadLinks = (checkLink)=>{
277
+ const { root, routeService } = checkLink;
278
+ return (tree, vfile)=>{
279
+ const internalLinks = new Set();
280
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'link', (node)=>{
281
+ const { url } = node;
282
+ if (!url) return;
283
+ if (internalLinks.has(url)) return;
284
+ if (!url.startsWith('http') && !url.startsWith('https')) {
285
+ var _url_split_join;
286
+ const { routePath: normalizeUrl } = routeService.normalizeRoutePath(null === (_url_split_join = url.split(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].sep).join('/')) || void 0 === _url_split_join ? void 0 : _url_split_join.split('#')[0]);
287
+ internalLinks.add(normalizeUrl);
288
+ }
289
+ });
290
+ checkLinks(Array.from(internalLinks), vfile.path, root, routeService);
291
+ };
346
292
  };
347
-
348
- // src/node/mdx/remarkPlugins/normalizeLink.ts
349
- import path6 from "path";
350
- import { isExternalUrl, normalizeHref, parseUrl, slash as slash2 } from "@rspress/shared";
351
- import { visit as visit4 } from "unist-util-visit";
352
- var remarkPluginNormalizeLink = ({ base, root, cleanUrls }) => (tree, file) => {
353
- const images = [];
354
- visit4(
355
- tree,
356
- (node) => node.type === "link",
357
- (node) => {
358
- if (!node.url) {
359
- return;
360
- }
361
- if (node.url.startsWith("#")) {
362
- node.url = `#${node.url.slice(1)}`;
363
- return;
364
- }
365
- let { url, hash } = parseUrl(node.url);
366
- if (isExternalUrl(url)) {
367
- node.url = url + (hash ? `#${hash}` : "");
368
- return;
369
- }
370
- const extname = path6.extname(url);
371
- if (extname === ".md" || extname === ".mdx") {
372
- url = url.replace(extname, "");
373
- }
374
- const relativePath = path6.relative(root, file.path);
375
- if (url.startsWith(".")) {
376
- url = path6.posix.join(slash2(path6.dirname(relativePath)), url);
377
- }
378
- url = normalizeHref(url, cleanUrls);
379
- if (hash) {
380
- url += `#${hash}`;
381
- }
382
- node.url = path6.posix.join(base, url);
383
- }
384
- );
385
- const normalizeImageUrl = (imageUrl) => {
386
- if (isExternalUrl(imageUrl) || imageUrl.startsWith("/")) {
387
- return "";
388
- }
389
- return imageUrl;
390
- };
391
- const getMdxSrcAttribute = (tempVar) => {
392
- return {
393
- type: "mdxJsxAttribute",
394
- name: "src",
395
- value: {
396
- type: "mdxJsxAttributeValueExpression",
397
- value: tempVar,
398
- data: {
399
- estree: {
400
- type: "Program",
401
- sourceType: "module",
402
- body: [
403
- {
404
- type: "ExpressionStatement",
405
- expression: {
406
- type: "Identifier",
407
- name: tempVar
293
+ const remarkPluginNormalizeLink = ({ base, root, cleanUrls })=>(tree, file)=>{
294
+ const images = [];
295
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, (node)=>'link' === node.type, (node)=>{
296
+ if (!node.url) return;
297
+ if (node.url.startsWith('#')) {
298
+ node.url = `#${node.url.slice(1)}`;
299
+ return;
300
+ }
301
+ let { url, hash } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.parseUrl)(node.url);
302
+ if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(url)) {
303
+ node.url = url + (hash ? `#${hash}` : '');
304
+ return;
305
+ }
306
+ const extname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(url);
307
+ if ('.md' === extname || '.mdx' === extname) url = url.replace(extname, '');
308
+ const relativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(root, file.path);
309
+ if (url.startsWith('.')) url = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.join((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.slash)(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(relativePath)), url);
310
+ url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeHref)(url, cleanUrls);
311
+ if (hash) url += `#${hash}`;
312
+ node.url = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.join(base, url);
313
+ });
314
+ const normalizeImageUrl = (imageUrl)=>{
315
+ if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(imageUrl) || imageUrl.startsWith('/')) return '';
316
+ return imageUrl;
317
+ };
318
+ const getMdxSrcAttribute = (tempVar)=>({
319
+ type: 'mdxJsxAttribute',
320
+ name: 'src',
321
+ value: {
322
+ type: 'mdxJsxAttributeValueExpression',
323
+ value: tempVar,
324
+ data: {
325
+ estree: {
326
+ type: 'Program',
327
+ sourceType: 'module',
328
+ body: [
329
+ {
330
+ type: 'ExpressionStatement',
331
+ expression: {
332
+ type: 'Identifier',
333
+ name: tempVar
334
+ }
335
+ }
336
+ ]
337
+ }
338
+ }
408
339
  }
409
- }
410
- ]
411
- }
412
- }
413
- }
340
+ });
341
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'image', (node)=>{
342
+ const { url } = node;
343
+ if (!url) return;
344
+ const imagePath = normalizeImageUrl(url);
345
+ if (!imagePath) return;
346
+ const tempVariableName = `image${images.length}`;
347
+ Object.assign(node, {
348
+ type: 'mdxJsxFlowElement',
349
+ name: 'img',
350
+ children: [],
351
+ attributes: [
352
+ node.alt && {
353
+ type: 'mdxJsxAttribute',
354
+ name: 'alt',
355
+ value: node.alt
356
+ },
357
+ getMdxSrcAttribute(tempVariableName)
358
+ ].filter(Boolean)
359
+ });
360
+ images.push(getASTNodeImport(tempVariableName, imagePath));
361
+ });
362
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, [
363
+ 'mdxJsxFlowElement',
364
+ 'mdxJsxTextElement'
365
+ ], (node)=>{
366
+ if ('img' !== node.name) return;
367
+ const src = node.attributes.find((attr)=>'src' === attr.name);
368
+ if (!(null == src ? void 0 : src.value) || 'string' != typeof (null == src ? void 0 : src.value)) return;
369
+ const imagePath = normalizeImageUrl(src.value);
370
+ if (!imagePath) return;
371
+ const tempVariableName = `image${images.length}`;
372
+ Object.assign(src, getMdxSrcAttribute(tempVariableName));
373
+ images.push(getASTNodeImport(tempVariableName, imagePath));
374
+ });
375
+ tree.children.unshift(...images);
414
376
  };
415
- };
416
- visit4(tree, "image", (node) => {
417
- const { url } = node;
418
- if (!url) {
419
- return;
420
- }
421
- const imagePath = normalizeImageUrl(url);
422
- if (!imagePath) {
423
- return;
424
- }
425
- const tempVariableName = `image${images.length}`;
426
- Object.assign(node, {
427
- type: "mdxJsxFlowElement",
428
- name: "img",
429
- children: [],
430
- attributes: [
431
- node.alt && {
432
- type: "mdxJsxAttribute",
433
- name: "alt",
434
- value: node.alt
435
- },
436
- getMdxSrcAttribute(tempVariableName)
437
- ].filter(Boolean)
438
- });
439
- images.push(getASTNodeImport(tempVariableName, imagePath));
440
- });
441
- visit4(tree, ["mdxJsxFlowElement", "mdxJsxTextElement"], (node) => {
442
- if (node.name !== "img") {
443
- return;
444
- }
445
- const src = node.attributes.find((attr) => attr.name === "src");
446
- if (!src?.value || typeof src?.value !== "string") {
447
- return;
448
- }
449
- const imagePath = normalizeImageUrl(src.value);
450
- if (!imagePath) {
451
- return;
452
- }
453
- const tempVariableName = `image${images.length}`;
454
- Object.assign(src, getMdxSrcAttribute(tempVariableName));
455
- images.push(getASTNodeImport(tempVariableName, imagePath));
456
- });
457
- tree.children.unshift(...images);
458
- };
459
-
460
- // src/node/mdx/remarkPlugins/toc.ts
461
- import Slugger from "github-slugger";
462
- import { visitChildren } from "unist-util-visit-children";
463
- var parseToc = (tree) => {
464
- let title = "";
465
- const toc = [];
466
- const slugger = new Slugger();
467
- visitChildren((node) => {
468
- if (node.type !== "heading" || !node.depth || !node.children) {
469
- return;
470
- }
471
- if (node.depth >= 1 && node.depth < 5) {
472
- let customId = "";
473
- const text = node.children.map((child) => {
474
- if (child.type === "link") {
475
- return child.children?.map((item) => item.value).join("");
476
- }
477
- if (child.type === "strong") {
478
- return `**${child.children?.map((item) => item.value).join("")}**`;
479
- }
480
- if (child.type === "text") {
481
- const [textPart, idPart] = extractTextAndId(child.value);
482
- customId = idPart;
483
- return textPart;
484
- }
485
- if (child.type === "inlineCode") {
486
- return `\`${child.value}\``;
377
+ const parseToc = (tree)=>{
378
+ let title = '';
379
+ const toc = [];
380
+ const slugger = new __WEBPACK_EXTERNAL_MODULE_github_slugger_8e9a17cb__["default"]();
381
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_children_71921007__.visitChildren)((node)=>{
382
+ if ('heading' !== node.type || !node.depth || !node.children) return;
383
+ if (node.depth >= 1 && node.depth < 5) {
384
+ let customId = '';
385
+ const text = node.children.map((child)=>{
386
+ if ('link' === child.type) {
387
+ var _child_children;
388
+ return null === (_child_children = child.children) || void 0 === _child_children ? void 0 : _child_children.map((item)=>item.value).join('');
389
+ }
390
+ if ('strong' === child.type) {
391
+ var _child_children1;
392
+ return `**${null === (_child_children1 = child.children) || void 0 === _child_children1 ? void 0 : _child_children1.map((item)=>item.value).join('')}**`;
393
+ }
394
+ if ('text' === child.type) {
395
+ const [textPart, idPart] = extractTextAndId(child.value);
396
+ customId = idPart;
397
+ return textPart;
398
+ }
399
+ if ('inlineCode' === child.type) return `\`${child.value}\``;
400
+ return '';
401
+ }).join('');
402
+ if (1 === node.depth) {
403
+ if (!title) title = text;
404
+ } else {
405
+ const id = customId ? customId : slugger.slug(text);
406
+ const { depth } = node;
407
+ toc.push({
408
+ id,
409
+ text,
410
+ depth
411
+ });
412
+ }
487
413
  }
488
- return "";
489
- }).join("");
490
- if (node.depth === 1) {
491
- if (!title)
492
- title = text;
493
- } else {
494
- const id = customId ? customId : slugger.slug(text);
495
- const { depth } = node;
496
- toc.push({ id, text, depth });
497
- }
498
- }
499
- })(tree);
500
- return {
501
- title,
502
- toc
503
- };
414
+ })(tree);
415
+ return {
416
+ title,
417
+ toc
418
+ };
504
419
  };
505
- var remarkPluginToc = function() {
506
- const data = this.data();
507
- return (tree) => {
508
- const { toc, title } = parseToc(tree);
509
- data.pageMeta.toc = toc;
510
- if (title) {
511
- data.pageMeta.title = title;
512
- }
513
- };
420
+ const remarkPluginToc = function() {
421
+ const data = this.data();
422
+ return (tree)=>{
423
+ const { toc, title } = parseToc(tree);
424
+ data.pageMeta.toc = toc;
425
+ if (title) data.pageMeta.title = title;
426
+ };
514
427
  };
515
-
516
- // src/node/mdx/options.ts
517
428
  async function createMDXOptions(docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver) {
518
- const cleanUrls = Boolean(config?.route?.cleanUrls);
519
- const {
520
- remarkPlugins: remarkPluginsFromConfig = [],
521
- rehypePlugins: rehypePluginsFromConfig = [],
522
- globalComponents: globalComponentsFromConfig = []
523
- } = config?.markdown || {};
524
- const rspressPlugins = pluginDriver.getPlugins();
525
- const remarkPluginsFromPlugins = rspressPlugins.flatMap(
526
- (plugin) => plugin.markdown?.remarkPlugins || []
527
- );
528
- const rehypePluginsFromPlugins = rspressPlugins.flatMap(
529
- (plugin) => plugin.markdown?.rehypePlugins || []
530
- );
531
- const globalComponents = [
532
- ...rspressPlugins.flatMap(
533
- (plugin) => plugin.markdown?.globalComponents || []
534
- ),
535
- ...globalComponentsFromConfig
536
- ];
537
- const defaultLang = config?.lang || "";
538
- return {
539
- providerImportSource: "@mdx-js/react",
540
- format: path7.extname(filepath).slice(1),
541
- remarkPlugins: [
542
- remarkGFM,
543
- remarkPluginToc,
544
- [
545
- remarkPluginNormalizeLink,
546
- {
547
- base: config?.base || "",
548
- cleanUrls,
549
- defaultLang,
550
- root: docDirectory
551
- }
552
- ],
553
- checkDeadLinks && [
554
- remarkCheckDeadLinks,
555
- {
556
- root: docDirectory,
557
- base: config?.base || "",
558
- routeService
559
- }
560
- ],
561
- globalComponents.length && [
562
- remarkBuiltin,
563
- {
564
- globalComponents
565
- }
566
- ],
567
- ...remarkPluginsFromConfig,
568
- ...remarkPluginsFromPlugins
569
- ].filter(Boolean),
570
- rehypePlugins: [
571
- rehypeHeaderAnchor,
572
- rehypePluginCodeMeta,
573
- [
574
- rehypePluginExternalLinks,
575
- {
576
- target: "_blank",
577
- rel: "noopener noreferrer"
578
- }
579
- ],
580
- ...rehypePluginsFromConfig,
581
- ...rehypePluginsFromPlugins
582
- ]
583
- };
429
+ var _config_route;
430
+ const cleanUrls = Boolean(null == config ? void 0 : null === (_config_route = config.route) || void 0 === _config_route ? void 0 : _config_route.cleanUrls);
431
+ const { remarkPlugins: remarkPluginsFromConfig = [], rehypePlugins: rehypePluginsFromConfig = [], globalComponents: globalComponentsFromConfig = [] } = (null == config ? void 0 : config.markdown) || {};
432
+ const rspressPlugins = pluginDriver.getPlugins();
433
+ const remarkPluginsFromPlugins = rspressPlugins.flatMap((plugin)=>{
434
+ var _plugin_markdown;
435
+ return (null === (_plugin_markdown = plugin.markdown) || void 0 === _plugin_markdown ? void 0 : _plugin_markdown.remarkPlugins) || [];
436
+ });
437
+ const rehypePluginsFromPlugins = rspressPlugins.flatMap((plugin)=>{
438
+ var _plugin_markdown;
439
+ return (null === (_plugin_markdown = plugin.markdown) || void 0 === _plugin_markdown ? void 0 : _plugin_markdown.rehypePlugins) || [];
440
+ });
441
+ const globalComponents = [
442
+ ...rspressPlugins.flatMap((plugin)=>{
443
+ var _plugin_markdown;
444
+ return (null === (_plugin_markdown = plugin.markdown) || void 0 === _plugin_markdown ? void 0 : _plugin_markdown.globalComponents) || [];
445
+ }),
446
+ ...globalComponentsFromConfig
447
+ ];
448
+ const defaultLang = (null == config ? void 0 : config.lang) || '';
449
+ return {
450
+ providerImportSource: '@mdx-js/react',
451
+ format: __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(filepath).slice(1),
452
+ remarkPlugins: [
453
+ __WEBPACK_EXTERNAL_MODULE_remark_gfm_073acf21__["default"],
454
+ remarkPluginToc,
455
+ [
456
+ remarkPluginNormalizeLink,
457
+ {
458
+ base: (null == config ? void 0 : config.base) || '',
459
+ cleanUrls,
460
+ defaultLang,
461
+ root: docDirectory
462
+ }
463
+ ],
464
+ checkDeadLinks && [
465
+ remarkCheckDeadLinks,
466
+ {
467
+ root: docDirectory,
468
+ base: (null == config ? void 0 : config.base) || '',
469
+ routeService
470
+ }
471
+ ],
472
+ globalComponents.length && [
473
+ remarkBuiltin,
474
+ {
475
+ globalComponents
476
+ }
477
+ ],
478
+ ...remarkPluginsFromConfig,
479
+ ...remarkPluginsFromPlugins
480
+ ].filter(Boolean),
481
+ rehypePlugins: [
482
+ rehypeHeaderAnchor,
483
+ rehypePluginCodeMeta,
484
+ [
485
+ __WEBPACK_EXTERNAL_MODULE_rehype_external_links_09bed11a__["default"],
486
+ {
487
+ target: '_blank',
488
+ rel: 'noopener noreferrer'
489
+ }
490
+ ],
491
+ ...rehypePluginsFromConfig,
492
+ ...rehypePluginsFromPlugins
493
+ ]
494
+ };
584
495
  }
585
-
586
- // src/node/mdx/loader.ts
587
496
  async function updateSiteDataRuntimeModule(modulePath, pageMeta) {
588
- const siteDataModulePath = path8.join(
589
- TEMP_DIR,
590
- "runtime",
591
- `${"virtual-site-data" /* SiteData */}.mjs`
592
- );
593
- const { default: siteData } = await import(pathToFileURL(siteDataModulePath).href);
594
- await fs2.writeFile(
595
- siteDataModulePath,
596
- `export default ${JSON.stringify(
597
- {
497
+ const siteDataModulePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(TEMP_DIR, 'runtime', `${runtimeModule_RuntimeModuleID.SiteData}.mjs`);
498
+ const { default: siteData } = await import((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.pathToFileURL)(siteDataModulePath).href);
499
+ await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].writeFile(siteDataModulePath, `export default ${JSON.stringify({
598
500
  ...siteData,
599
501
  timestamp: Date.now().toString(),
600
- pages: siteData.pages.map(
601
- (page) => (
602
- // Update page meta if the page is updated
603
- page._filepath === modulePath ? { ...page, ...pageMeta } : page
604
- )
605
- )
606
- },
607
- null,
608
- 2
609
- )}`
610
- );
502
+ pages: siteData.pages.map((page)=>page._filepath === modulePath ? {
503
+ ...page,
504
+ ...pageMeta
505
+ } : page)
506
+ }, null, 2)}`);
611
507
  }
612
508
  function createCheckPageMetaUpdateFn() {
613
- const pageMetaMap = /* @__PURE__ */ new Map();
614
- return (modulePath, pageMeta) => {
615
- const prevMeta = pageMetaMap.get(modulePath);
616
- const deserializedMeta = JSON.stringify(pageMeta);
617
- pageMetaMap.set(modulePath, deserializedMeta);
618
- if (!prevMeta) {
619
- return;
620
- }
621
- if (prevMeta !== deserializedMeta) {
622
- setTimeout(async () => {
623
- logger2.info("Page metadata changed, page reloading...");
624
- await updateSiteDataRuntimeModule(modulePath, pageMeta);
625
- });
626
- }
627
- };
509
+ const pageMetaMap = new Map();
510
+ return (modulePath, pageMeta)=>{
511
+ const prevMeta = pageMetaMap.get(modulePath);
512
+ const deserializedMeta = JSON.stringify(pageMeta);
513
+ pageMetaMap.set(modulePath, deserializedMeta);
514
+ if (!prevMeta) return;
515
+ if (prevMeta !== deserializedMeta) setTimeout(async ()=>{
516
+ __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info('Page metadata changed, page reloading...');
517
+ await updateSiteDataRuntimeModule(modulePath, pageMeta);
518
+ });
519
+ };
628
520
  }
629
- var checkPageMetaUpdate = createCheckPageMetaUpdateFn();
630
- async function mdxLoader(context, source, callback) {
631
- context.cacheable(true);
632
- const options = context.getOptions();
633
- const filepath = context.resourcePath;
634
- const { alias } = context._compiler.options.resolve;
635
- const { config, docDirectory, checkDeadLinks, routeService, pluginDriver } = options;
636
- const { frontmatter, content } = loadFrontMatter(
637
- source,
638
- filepath,
639
- docDirectory,
640
- true
641
- );
642
- const { flattenContent, deps } = await flattenMdxContent(
643
- content,
644
- filepath,
645
- alias
646
- );
647
- deps.forEach((dep) => context.addDependency(dep));
648
- const replacedContent = applyReplaceRules(
649
- flattenContent,
650
- config.replaceRules
651
- );
652
- const preprocessedContent = escapeMarkdownHeadingIds(replacedContent);
653
- let enableMdxRs;
654
- const mdxRs = config?.markdown?.mdxRs ?? true;
655
- if (typeof mdxRs === "object") {
656
- enableMdxRs = typeof mdxRs?.include === "function" ? mdxRs.include(filepath) : true;
657
- } else {
658
- enableMdxRs = mdxRs;
659
- }
660
- try {
661
- let compileResult;
662
- let pageMeta = { title: "", toc: [] };
663
- if (!enableMdxRs) {
664
- const mdxOptions = await createMDXOptions(
665
- docDirectory,
666
- config,
667
- checkDeadLinks,
668
- routeService,
669
- filepath,
670
- pluginDriver
671
- );
672
- const compiler = createProcessor2(mdxOptions);
673
- compiler.data("pageMeta", { toc: [], title: "" });
674
- const vFile = await compiler.process({
675
- value: preprocessedContent,
676
- path: filepath
677
- });
678
- compileResult = String(vFile);
679
- const compilationMeta = compiler.data("pageMeta");
680
- pageMeta = {
681
- ...compilationMeta,
682
- title: frontmatter.title || compilationMeta.title || "",
683
- headingTitle: compilationMeta.title,
684
- frontmatter
685
- };
686
- } else {
687
- const { compile } = __require("@rspress/mdx-rs");
688
- const { toc, links, title, code } = await compile({
689
- value: preprocessedContent,
690
- filepath,
691
- root: docDirectory,
692
- development: process.env.NODE_ENV !== "production"
693
- });
694
- compileResult = code;
695
- pageMeta = {
696
- toc,
697
- title: frontmatter.title || title || "",
698
- headingTitle: title,
699
- frontmatter
700
- };
701
- if (checkDeadLinks) {
702
- checkLinks(links, filepath, docDirectory, routeService);
703
- }
704
- }
705
- if (!isProduction2()) {
706
- checkPageMetaUpdate(filepath, pageMeta);
707
- }
708
- const result = `const frontmatter = ${JSON.stringify(frontmatter)};
521
+ const checkPageMetaUpdate = createCheckPageMetaUpdateFn();
522
+ async function mdxLoader(source) {
523
+ var _config_markdown;
524
+ this.cacheable(true);
525
+ const callback = this.async();
526
+ const options = this.getOptions();
527
+ const filepath = this.resourcePath;
528
+ const { alias } = this._compiler.options.resolve;
529
+ const { config, docDirectory, checkDeadLinks, routeService, pluginDriver } = options;
530
+ const { frontmatter, content } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.loadFrontMatter)(source, filepath, docDirectory, true);
531
+ const { flattenContent, deps } = await flattenMdxContent(content, filepath, alias);
532
+ deps.forEach((dep)=>this.addDependency(dep));
533
+ const replacedContent = applyReplaceRules(flattenContent, config.replaceRules);
534
+ const preprocessedContent = escapeMarkdownHeadingIds(replacedContent);
535
+ let enableMdxRs;
536
+ const mdxRs = (null == config ? void 0 : null === (_config_markdown = config.markdown) || void 0 === _config_markdown ? void 0 : _config_markdown.mdxRs) ?? true;
537
+ enableMdxRs = 'object' == typeof mdxRs ? 'function' != typeof (null == mdxRs ? void 0 : mdxRs.include) || mdxRs.include(filepath) : mdxRs;
538
+ try {
539
+ let compileResult;
540
+ let pageMeta = {
541
+ title: '',
542
+ toc: []
543
+ };
544
+ if (enableMdxRs) {
545
+ const { compile } = __webpack_require__("@rspress/mdx-rs");
546
+ const { toc, links, title, code } = await compile({
547
+ value: preprocessedContent,
548
+ filepath,
549
+ root: docDirectory,
550
+ development: 'production' !== process.env.NODE_ENV
551
+ });
552
+ compileResult = code;
553
+ pageMeta = {
554
+ toc,
555
+ title: frontmatter.title || title || '',
556
+ headingTitle: title,
557
+ frontmatter
558
+ };
559
+ if (checkDeadLinks) checkLinks(links, filepath, docDirectory, routeService);
560
+ } else {
561
+ const mdxOptions = await createMDXOptions(docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver);
562
+ const compiler = (0, __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__.createProcessor)(mdxOptions);
563
+ compiler.data('pageMeta', {
564
+ toc: [],
565
+ title: ''
566
+ });
567
+ const vFile = await compiler.process({
568
+ value: preprocessedContent,
569
+ path: filepath
570
+ });
571
+ compileResult = String(vFile);
572
+ const compilationMeta = compiler.data('pageMeta');
573
+ pageMeta = {
574
+ ...compilationMeta,
575
+ title: frontmatter.title || compilationMeta.title || '',
576
+ headingTitle: compilationMeta.title,
577
+ frontmatter
578
+ };
579
+ }
580
+ if (!(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isProduction)()) checkPageMetaUpdate(filepath, pageMeta);
581
+ const result = `const frontmatter = ${JSON.stringify(frontmatter)};
709
582
  ${compileResult}
710
583
  MDXContent.__RSPRESS_PAGE_META = {};
711
584
 
712
- MDXContent.__RSPRESS_PAGE_META["${encodeURIComponent(
713
- normalizePath(path8.relative(docDirectory, filepath))
714
- )}"] = ${JSON.stringify(pageMeta)};
585
+ MDXContent.__RSPRESS_PAGE_META["${encodeURIComponent(normalizePath(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(docDirectory, filepath)))}"] = ${JSON.stringify(pageMeta)};
715
586
  `;
716
- callback(null, result);
717
- } catch (e) {
718
- logger2.error(`MDX compile error: ${e.message} in ${filepath}`);
719
- callback({ message: e.message, name: `${filepath} compile error` });
720
- }
587
+ callback(null, result);
588
+ } catch (e) {
589
+ __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`MDX compile error: ${e.message} in ${filepath}`);
590
+ callback({
591
+ message: e.message,
592
+ name: `${filepath} compile error`
593
+ });
594
+ }
721
595
  }
722
- export {
723
- createCheckPageMetaUpdateFn,
724
- mdxLoader as default,
725
- updateSiteDataRuntimeModule
726
- };
727
-
728
- //# sourceMappingURL=loader.js.map
596
+ export { createCheckPageMetaUpdateFn, mdxLoader as default, updateSiteDataRuntimeModule };