@rspress/core 2.0.0-beta.3 → 2.0.0-beta.30

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.
@@ -0,0 +1,10 @@
1
+ /**
2
+ * https://github.com/facebook/docusaurus/blob/0306d182407bb98f140cd5ec7481fa9608fe0297/packages/docusaurus/src/ssg/ssgExecutor.ts#L123
3
+ * @license MIT
4
+ */
5
+
6
+ /**
7
+ * these codes are copied from
8
+ * @link https://github.com/facebook/docusaurus/blob/45065e8d2b5831117b8d69fec1be28f5520cf105/packages/docusaurus/src/ssg/ssgEnv.ts#L11
9
+ * @license MIT
10
+ */
package/dist/loader.d.ts CHANGED
@@ -1,35 +1,33 @@
1
1
  import { AdditionalPage } from '@rspress/shared';
2
2
  import { DefaultThemeConfig } from '@rspress/shared';
3
- import type { FrontMatterMeta } from '@rspress/shared';
4
3
  import type { PageIndexInfo } from '@rspress/shared';
5
- import type { RouteMeta } from '@rspress/shared';
6
- import type { Rspack as Rspack_2 } from '@rsbuild/core';
4
+ import { RouteMeta } from '@rspress/shared';
5
+ import { Rspack as Rspack_2 } from '@rsbuild/core';
7
6
  import type { RspressPlugin } from '@rspress/shared';
8
- import type { UserConfig } from '@rspress/shared';
7
+ import { UserConfig } from '@rspress/shared';
9
8
 
10
- export declare function createCheckPageMetaUpdateFn(): (modulePath: string, pageMeta: PageMeta) => void;
11
-
12
- declare interface LoaderOptions {
9
+ declare interface InitOptions {
10
+ scanDir: string;
13
11
  config: UserConfig;
14
- docDirectory: string;
15
- checkDeadLinks: boolean;
16
- routeService: RouteService;
12
+ runtimeTempDir: string;
17
13
  pluginDriver: PluginDriver;
18
14
  }
19
15
 
20
- declare function mdxLoader(this: Rspack_2.LoaderContext<LoaderOptions>, source: string): Promise<void>;
16
+ declare function mdxLoader(this: Rspack_2.LoaderContext<MdxLoaderOptions>, source: string): Promise<void>;
21
17
  export default mdxLoader;
22
18
 
23
- export declare interface PageMeta {
24
- toc: TocItem[];
25
- title: string;
26
- headingTitle: string;
27
- frontmatter?: FrontMatterMeta;
19
+ declare interface MdxLoaderOptions {
20
+ config: UserConfig;
21
+ docDirectory: string;
22
+ checkDeadLinks: boolean;
23
+ routeService: RouteService;
24
+ pluginDriver: PluginDriver;
28
25
  }
29
26
 
30
27
  declare class PluginDriver {
31
28
  #private;
32
- constructor(config: UserConfig, isProd: boolean);
29
+ constructor(config: UserConfig, configFilePath: string, isProd: boolean);
30
+ getConfigFilePath(): string;
33
31
  init(): Promise<void>;
34
32
  addPlugin(plugin: RspressPlugin): void;
35
33
  getPlugins(): RspressPlugin[];
@@ -44,46 +42,49 @@ declare class PluginDriver {
44
42
  routeGenerated(routes: RouteMeta[]): Promise<void[]>;
45
43
  routeServiceGenerated(routeService: RouteService): Promise<void[]>;
46
44
  addRuntimeModules(): Promise<Record<string, string>>;
47
- addSSGRoutes(): Promise<({
48
- path: string;
49
- } | {
50
- path: string;
51
- })[]>;
52
45
  globalUIComponents(): (string | [string, object])[];
53
46
  globalStyles(): string[];
54
47
  _runParallelAsyncHook<H extends RspressPluginHookKeys>(hookName: H, ...args: Parameters<Required<RspressPlugin>[H]>): Promise<Awaited<ReturnType<Required<RspressPlugin>[H]>>[]>;
55
48
  _runSerialAsyncHook<H extends RspressPluginHookKeys>(hookName: H, ...args: Parameters<Required<RspressPlugin>[H]>): RspressPlugin;
56
49
  }
57
50
 
51
+ declare class RoutePage {
52
+ #private;
53
+ routeMeta: RouteMeta;
54
+ static create(absolutePath: string, docsDir: string): RoutePage;
55
+ static createFromExternal(routePath: string, filepath: string, docDir: string): RoutePage;
56
+ private constructor();
57
+ static generateRouteMeta(routePath: string, filepath: string, docDir: string): RouteMeta;
58
+ }
59
+
58
60
  declare class RouteService {
59
61
  #private;
60
- routeData: Map<string, RouteMeta>;
61
- constructor(scanDir: string, userConfig: UserConfig, tempDir: string, pluginDriver: PluginDriver);
62
+ routeData: Map<string, RoutePage>;
63
+ static __instance__: RouteService | null;
64
+ static getInstance(): RouteService;
65
+ static create(options: InitOptions): Promise<RouteService>;
66
+ private constructor();
62
67
  get extensions(): readonly string[];
63
- init(): Promise<void>;
64
- addRoute(routeInfo: RouteMeta): void;
65
- removeRoute(filePath: string): void;
68
+ addRoute(routePage: RoutePage): Promise<void>;
66
69
  getRoutes(): RouteMeta[];
67
- isExistRoute(routePath: string): boolean;
68
- isEmpty(): boolean;
69
- generateRoutesCode(isStaticImport?: boolean): string;
70
- generateRoutesCodeByRouteMeta(routeMeta: RouteMeta[], isStaticImport: boolean): string;
71
- getRoutePathParts(routePath: string): readonly [string, string, string];
72
- normalizeRoutePath(routePath: string): {
70
+ getRoutePages(): RoutePage[];
71
+ isExistRoute(link: string): boolean;
72
+ generateRoutesCode(): string;
73
+ private generateRoutesCodeByRouteMeta;
74
+ getRoutePathParts(relativePath: string): string[];
75
+ splitRoutePathParts(relativePath: string): readonly [string, string, string];
76
+ normalizeRoutePath(relativePath: string): {
77
+ pureRoutePath: string;
73
78
  routePath: string;
74
79
  lang: string;
75
80
  version: string;
76
81
  };
82
+ absolutePathToRoutePath(absolutePath: string): string;
83
+ isInDocsDir(absolutePath: string): boolean;
84
+ absolutePathToRelativePath(absolutePath: string): string;
85
+ getRoutePageByRoutePath(routePath: string): RoutePage | undefined;
77
86
  }
78
87
 
79
- declare type RspressPluginHookKeys = 'beforeBuild' | 'afterBuild' | 'addPages' | 'addRuntimeModules' | 'routeGenerated' | 'routeServiceGenerated' | 'addSSGRoutes' | 'extendPageData' | 'modifySearchIndexData';
80
-
81
- declare interface TocItem {
82
- id: string;
83
- text: string;
84
- depth: number;
85
- }
86
-
87
- export declare function updateSiteDataRuntimeModule(modulePath: string, pageMeta: PageMeta): Promise<void>;
88
+ declare type RspressPluginHookKeys = 'beforeBuild' | 'config' | 'afterBuild' | 'addPages' | 'addRuntimeModules' | 'routeGenerated' | 'routeServiceGenerated' | 'extendPageData' | 'modifySearchIndexData';
88
89
 
89
90
  export { }
package/dist/loader.js CHANGED
@@ -1,458 +1,43 @@
1
- import __rslib_shim_module__ from 'module';
2
- /*#__PURE__*/ 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 * as __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__ from "node:os";
11
- import * as __WEBPACK_EXTERNAL_MODULE_rehype_external_links_09bed11a__ from "rehype-external-links";
12
- import * as __WEBPACK_EXTERNAL_MODULE_remark_gfm_073acf21__ from "remark-gfm";
13
- import * as __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__ from "unist-util-visit";
14
- import * as __WEBPACK_EXTERNAL_MODULE_github_slugger_8e9a17cb__ from "github-slugger";
15
- import * as __WEBPACK_EXTERNAL_MODULE_hast_util_heading_rank_cff646ba__ from "hast-util-heading-rank";
16
- import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_constants_70084e62__ from "@rspress/shared/constants";
17
- import * as __WEBPACK_EXTERNAL_MODULE_unist_util_visit_children_71921007__ from "unist-util-visit-children";
18
- `{
19
- const saved = localStorage.getItem('${__WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.APPEARANCE_KEY}')
20
- const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches
21
- const isDark = !saved || saved === 'auto' ? preferDark : saved === 'dark'
22
- document.documentElement.classList.toggle('dark', isDark)
23
- document.documentElement.classList.toggle('rp-dark', isDark)
24
- document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
25
- }`.replace(/\n/g, ';').replace(/\s{2,}/g, '');
26
- const dirname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileURLToPath)(new URL(import.meta.url)));
27
- const PACKAGE_ROOT = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(dirname, '..');
28
- __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'index.html');
29
- __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'csrClientEntry.js');
30
- __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrClientEntry.js');
31
- __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(PACKAGE_ROOT, 'dist', 'runtime', 'ssrServerEntry.js');
32
- const TEMP_DIR = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(process.cwd(), 'node_modules', __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.RSPRESS_TEMP_DIR);
33
- var types_RuntimeModuleID = /*#__PURE__*/ function(RuntimeModuleID) {
34
- RuntimeModuleID["GlobalStyles"] = "virtual-global-styles";
35
- RuntimeModuleID["GlobalComponents"] = "virtual-global-components";
36
- RuntimeModuleID["RouteForClient"] = "virtual-routes";
37
- RuntimeModuleID["RouteForSSR"] = "virtual-routes-ssr";
38
- RuntimeModuleID["SiteData"] = "virtual-site-data";
39
- RuntimeModuleID["SearchIndexHash"] = "virtual-search-index-hash";
40
- RuntimeModuleID["I18nText"] = "virtual-i18n-text";
41
- RuntimeModuleID["SearchHooks"] = "virtual-search-hooks";
42
- RuntimeModuleID["PrismLanguages"] = "virtual-prism-languages";
43
- return RuntimeModuleID;
44
- }({});
45
- function applyReplaceRules(code = '', replaceRules = []) {
46
- let result = code;
47
- for (const rule of replaceRules)result = result.replace(rule.search, rule.replace);
48
- return result;
49
- }
50
- function escapeMarkdownHeadingIds(content) {
51
- const markdownHeadingRegexp = /(?:^|\n)#{1,6}(?!#).*/g;
52
- return content.replace(markdownHeadingRegexp, (substring)=>substring.replace('{#', '\\{#').replace('\\\\{#', '\\{#'));
53
- }
54
- const isWindows = 'win32' === __WEBPACK_EXTERNAL_MODULE_node_os_74b4b876__["default"].platform();
55
- function slash(p) {
56
- return p.replace(/\\/g, '/');
57
- }
58
- function normalizePath(id) {
59
- return __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.normalize(isWindows ? slash(id) : id);
60
- }
61
- const rehypePluginCodeMeta = ()=>(tree)=>{
62
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'element', (node)=>{
63
- if ('pre' === node.tagName && node.children[0]?.type === 'element' && 'code' === node.children[0].tagName) {
64
- const codeNode = node.children[0];
65
- codeNode.properties ??= {};
66
- codeNode.properties.meta = codeNode.data?.meta;
67
- }
68
- });
69
- };
70
- const rehypeHeaderAnchor = ()=>{
71
- const slugger = new __WEBPACK_EXTERNAL_MODULE_github_slugger_8e9a17cb__["default"]();
72
- return (tree)=>{
73
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'element', (node)=>{
74
- if (!(0, __WEBPACK_EXTERNAL_MODULE_hast_util_heading_rank_cff646ba__.headingRank)(node)) return;
75
- if (!node.properties?.id) {
76
- const [text, customId] = collectHeaderText(node);
77
- node.properties ??= {};
78
- node.properties.id = customId || slugger.slug(text);
79
- }
80
- node.children.unshift(create(node));
81
- });
82
- };
83
- };
84
- const collectHeaderText = (node)=>{
85
- let text = '';
86
- let id = '';
87
- node.children.forEach((child)=>{
88
- if ('text' === child.type) {
89
- const [textPart, idPart] = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.extractTextAndId)(child.value);
90
- child.value = textPart;
91
- text += textPart;
92
- id = idPart;
93
- } else if ('element' === child.type) child.children.forEach((c)=>{
94
- if ('text' === c.type) text += c.value;
95
- });
96
- });
97
- return [
98
- text,
99
- id
100
- ];
101
- };
102
- function create(node) {
103
- return {
104
- type: 'element',
105
- tagName: 'a',
106
- properties: {
107
- class: 'header-anchor',
108
- ariaHidden: 'true',
109
- href: `#${node.properties.id}`
110
- },
111
- children: [
112
- {
113
- type: 'text',
114
- value: '#'
115
- }
116
- ]
117
- };
118
- }
119
- const getASTNodeImport = (name, from)=>({
120
- type: 'mdxjsEsm',
121
- value: `import ${name} from ${JSON.stringify(from)}`,
122
- data: {
123
- estree: {
124
- type: 'Program',
125
- sourceType: 'module',
126
- body: [
127
- {
128
- type: 'ImportDeclaration',
129
- specifiers: [
130
- {
131
- type: 'ImportDefaultSpecifier',
132
- local: {
133
- type: 'Identifier',
134
- name
135
- }
136
- }
137
- ],
138
- source: {
139
- type: 'Literal',
140
- value: from,
141
- raw: `${JSON.stringify(from)}`
142
- }
143
- }
144
- ]
145
- }
146
- }
147
- });
148
- const remarkBuiltin = ({ globalComponents })=>(tree)=>{
149
- const demos = globalComponents.map((componentPath)=>{
150
- const filename = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].parse(componentPath).name;
151
- const componentName = filename[0].toUpperCase() + filename.slice(1);
152
- return getASTNodeImport(componentName, componentPath);
153
- });
154
- tree.children.unshift(...demos);
155
- };
156
- const IGNORE_REGEXP = /^(https?|mailto|tel|#)/;
157
- function checkLinks(links, filepath, root, routeService) {
158
- const errorInfos = [];
159
- links.filter((link)=>!IGNORE_REGEXP.test(link)).map((link)=>normalizePath(link)).forEach((link)=>{
160
- const relativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(root, filepath);
161
- if (!routeService.isExistRoute((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.cleanUrl)(link))) errorInfos.push(`Internal link to "${link}" is dead, check it in "${relativePath}"`);
162
- });
163
- if (errorInfos.length > 0) {
164
- errorInfos?.forEach((err)=>{
165
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(err);
166
- });
167
- if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isProduction)()) throw new Error('Dead link found');
168
- }
169
- }
170
- const remarkCheckDeadLinks = (checkLink)=>{
171
- const { root, routeService } = checkLink;
172
- return (tree, vfile)=>{
173
- const internalLinks = new Set();
174
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'link', ({ url })=>{
175
- if (!url) return;
176
- if (internalLinks.has(url)) return;
177
- if (!url.startsWith('http://') && !url.startsWith('https://')) {
178
- const { routePath: normalizeUrl } = routeService.normalizeRoutePath(url.split(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].sep).join('/')?.split('#')[0]);
179
- internalLinks.add(normalizeUrl);
180
- }
181
- });
182
- checkLinks(Array.from(internalLinks), vfile.path, root, routeService);
183
- };
184
- };
185
- function normalizeLink(nodeUrl, routeService, relativePath, cleanUrls) {
186
- if (!nodeUrl) return '';
187
- if (nodeUrl.startsWith('#')) return `#${nodeUrl.slice(1)}`;
188
- let { url, hash } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.parseUrl)(nodeUrl);
189
- if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(url)) return url + (hash ? `#${hash}` : '');
190
- const extname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(url);
191
- if ((routeService?.extensions ?? __WEBPACK_EXTERNAL_MODULE__rspress_shared_constants_70084e62__.DEFAULT_PAGE_EXTENSIONS).includes(extname)) url = url.replace(new RegExp(`\\${extname}$`), '');
192
- 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);
193
- else if (routeService) {
194
- const [pathVersion, pathLang] = routeService.getRoutePathParts((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.slash)(relativePath));
195
- const [urlVersion, urlLang, urlPath] = routeService.getRoutePathParts(url);
196
- url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.addLeadingSlash)(urlPath);
197
- if (pathLang && urlLang !== pathLang) url = `/${pathLang}${url}`;
198
- if (pathVersion && urlVersion !== pathVersion) url = `/${pathVersion}${url}`;
199
- }
200
- if ('boolean' == typeof cleanUrls) url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeHref)(url, cleanUrls);
201
- else {
202
- url = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.normalizeHref)(url, false);
203
- url = url.replace(/\.html$/, cleanUrls);
204
- }
205
- if (hash) url += `#${hash}`;
206
- return url;
207
- }
208
- const normalizeImageUrl = (imageUrl)=>{
209
- if ((0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isExternalUrl)(imageUrl) || imageUrl.startsWith('/')) return '';
210
- return imageUrl;
211
- };
212
- const remarkPluginNormalizeLink = ({ root, cleanUrls, routeService })=>(tree, file)=>{
213
- const images = [];
214
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'link', (node)=>{
215
- const { url: nodeUrl } = node;
216
- const relativePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(root, file.path);
217
- node.url = normalizeLink(nodeUrl, routeService, relativePath, cleanUrls);
218
- });
219
- const getMdxSrcAttribute = (tempVar)=>({
220
- type: 'mdxJsxAttribute',
221
- name: 'src',
222
- value: {
223
- type: 'mdxJsxAttributeValueExpression',
224
- value: tempVar,
225
- data: {
226
- estree: {
227
- type: 'Program',
228
- sourceType: 'module',
229
- body: [
230
- {
231
- type: 'ExpressionStatement',
232
- expression: {
233
- type: 'Identifier',
234
- name: tempVar
235
- }
236
- }
237
- ]
238
- }
239
- }
240
- }
241
- });
242
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'image', (node)=>{
243
- const { alt, url } = node;
244
- if (!url) return;
245
- const imagePath = normalizeImageUrl(url);
246
- if (!imagePath) return;
247
- const tempVariableName = `image${images.length}`;
248
- Object.assign(node, {
249
- type: 'mdxJsxFlowElement',
250
- name: 'img',
251
- children: [],
252
- attributes: [
253
- alt && {
254
- type: 'mdxJsxAttribute',
255
- name: 'alt',
256
- value: alt
257
- },
258
- getMdxSrcAttribute(tempVariableName)
259
- ].filter(Boolean)
260
- });
261
- images.push(getASTNodeImport(tempVariableName, imagePath));
262
- });
263
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, (node)=>{
264
- if ('mdxJsxFlowElement' !== node.type && 'mdxJsxTextElement' !== node.type || 'img' !== node.name) return;
265
- const srcAttr = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.getNodeAttribute)(node, 'src', true);
266
- if ('string' != typeof srcAttr?.value) return;
267
- const imagePath = normalizeImageUrl(srcAttr.value);
268
- if (!imagePath) return;
269
- const tempVariableName = `image${images.length}`;
270
- Object.assign(srcAttr, getMdxSrcAttribute(tempVariableName));
271
- images.push(getASTNodeImport(tempVariableName, imagePath));
272
- });
273
- tree.children.unshift(...images);
274
- };
275
- const parseToc = (tree)=>{
276
- let title = '';
277
- const toc = [];
278
- const slugger = new __WEBPACK_EXTERNAL_MODULE_github_slugger_8e9a17cb__["default"]();
279
- (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_children_71921007__.visitChildren)((node)=>{
280
- if ('heading' !== node.type || !node.depth || !node.children) return;
281
- if (node.depth >= 1 && node.depth < 5) {
282
- let customId = '';
283
- const text = node.children.map((child)=>{
284
- if ('link' === child.type) return child.children?.map((item)=>item.value).join('');
285
- if ('strong' === child.type) return `**${child.children?.map((item)=>item.value).join('')}**`;
286
- if ('emphasis' === child.type) return `*${child.children?.map((item)=>item.value).join('')}*`;
287
- if ('delete' === child.type) return `~~${child.children?.map((item)=>item.value).join('')}~~`;
288
- if ('text' === child.type) {
289
- const [textPart, idPart] = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.extractTextAndId)(child.value);
290
- customId = idPart;
291
- return textPart;
292
- }
293
- if ('inlineCode' === child.type) return `\`${child.value}\``;
294
- return '';
295
- }).join('');
296
- if (1 === node.depth) {
297
- if (!title) title = text;
298
- } else {
299
- const id = customId ? customId : slugger.slug(text);
300
- const { depth } = node;
301
- toc.push({
302
- id,
303
- text,
304
- depth
305
- });
306
- }
307
- }
308
- })(tree);
309
- return {
310
- title,
311
- toc
312
- };
313
- };
314
- const remarkPluginToc = function() {
315
- const data = this.data();
316
- return (tree)=>{
317
- const { toc, title } = parseToc(tree);
318
- data.pageMeta.toc = toc;
319
- if (title) data.pageMeta.title = title;
320
- };
321
- };
322
- async function createMDXOptions(docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver) {
323
- const cleanUrls = config?.route?.cleanUrls ?? false;
324
- const { remarkPlugins: remarkPluginsFromConfig = [], rehypePlugins: rehypePluginsFromConfig = [], globalComponents: globalComponentsFromConfig = [] } = config?.markdown || {};
325
- const rspressPlugins = pluginDriver.getPlugins();
326
- const remarkPluginsFromPlugins = rspressPlugins.flatMap((plugin)=>plugin.markdown?.remarkPlugins || []);
327
- const rehypePluginsFromPlugins = rspressPlugins.flatMap((plugin)=>plugin.markdown?.rehypePlugins || []);
328
- const globalComponents = [
329
- ...rspressPlugins.flatMap((plugin)=>plugin.markdown?.globalComponents || []),
330
- ...globalComponentsFromConfig
331
- ];
332
- return {
333
- providerImportSource: '@mdx-js/react',
334
- format: __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(filepath).slice(1),
335
- remarkPlugins: [
336
- __WEBPACK_EXTERNAL_MODULE_remark_gfm_073acf21__["default"],
337
- remarkPluginToc,
338
- [
339
- remarkPluginNormalizeLink,
340
- {
341
- cleanUrls,
342
- root: docDirectory,
343
- routeService
344
- }
345
- ],
346
- checkDeadLinks && [
347
- remarkCheckDeadLinks,
348
- {
349
- root: docDirectory,
350
- base: config?.base || '',
351
- routeService
352
- }
353
- ],
354
- globalComponents.length && [
355
- remarkBuiltin,
356
- {
357
- globalComponents
358
- }
359
- ],
360
- ...remarkPluginsFromConfig,
361
- ...remarkPluginsFromPlugins
362
- ].filter(Boolean),
363
- rehypePlugins: [
364
- rehypeHeaderAnchor,
365
- rehypePluginCodeMeta,
366
- [
367
- __WEBPACK_EXTERNAL_MODULE_rehype_external_links_09bed11a__["default"],
368
- {
369
- target: '_blank',
370
- rel: 'noopener noreferrer'
371
- }
372
- ],
373
- ...rehypePluginsFromConfig,
374
- ...rehypePluginsFromPlugins
375
- ]
376
- };
377
- }
378
- async function updateSiteDataRuntimeModule(modulePath, pageMeta) {
379
- const siteDataModulePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(TEMP_DIR, 'runtime', `${types_RuntimeModuleID.SiteData}.mjs`);
380
- const { default: siteData } = await import((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.pathToFileURL)(siteDataModulePath).href);
381
- await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].writeFile(siteDataModulePath, `export default ${JSON.stringify({
382
- ...siteData,
383
- timestamp: Date.now().toString(),
384
- pages: siteData.pages.map((page)=>page._filepath === modulePath ? {
385
- ...page,
386
- ...pageMeta
387
- } : page)
388
- }, null, 2)}`);
389
- }
390
- function createCheckPageMetaUpdateFn() {
391
- const pageMetaMap = new Map();
392
- return (modulePath, pageMeta)=>{
393
- const prevMeta = pageMetaMap.get(modulePath);
394
- const deserializedMeta = JSON.stringify(pageMeta);
395
- pageMetaMap.set(modulePath, deserializedMeta);
396
- if (!prevMeta) return;
397
- if (prevMeta !== deserializedMeta) setTimeout(async ()=>{
398
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.info('Page metadata changed, page reloading...');
399
- await updateSiteDataRuntimeModule(modulePath, pageMeta);
400
- });
401
- };
402
- }
403
- const checkPageMetaUpdate = createCheckPageMetaUpdateFn();
1
+ import { logger } from "@rsbuild/core";
2
+ import { compile, compileWithCrossCompilerCache } from "./processor.js";
404
3
  async function mdxLoader(source) {
405
4
  this.cacheable(true);
406
5
  const callback = this.async();
407
6
  const options = this.getOptions();
408
7
  const filepath = this.resourcePath;
409
- const { config, docDirectory, checkDeadLinks, routeService, pluginDriver } = options;
410
- const { frontmatter, content } = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.loadFrontMatter)(source, filepath, docDirectory, true);
411
- const replacedContent = applyReplaceRules(content, config.replaceRules);
412
- const preprocessedContent = escapeMarkdownHeadingIds(replacedContent);
8
+ const { config, docDirectory, routeService, pluginDriver } = options;
9
+ const crossCompilerCache = config?.markdown?.crossCompilerCache ?? true;
413
10
  try {
414
- let pageMeta = {
415
- title: '',
416
- toc: [],
417
- headingTitle: ''
418
- };
419
- const frontmatterTitle = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.extractTextAndId)(frontmatter.title)[0];
420
- const mdxOptions = await createMDXOptions(docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver);
421
- const compiler = (0, __WEBPACK_EXTERNAL_MODULE__mdx_js_mdx_b904bd09__.createProcessor)(mdxOptions);
422
- compiler.data('pageMeta', {
423
- toc: [],
424
- title: ''
425
- });
426
- const vFile = await compiler.process({
427
- value: preprocessedContent,
428
- path: filepath
429
- });
430
- const compileResult = String(vFile);
431
- const compilationMeta = compiler.data('pageMeta');
432
- const headingTitle = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.extractTextAndId)(compilationMeta.title)[0];
433
- pageMeta = {
434
- ...compilationMeta,
435
- title: frontmatterTitle || headingTitle,
436
- headingTitle,
437
- frontmatter
438
- };
439
- if (!(0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_baa012d0__.isProduction)()) checkPageMetaUpdate(filepath, pageMeta);
440
- const result = `const frontmatter = ${JSON.stringify(frontmatter)};
441
- ${compileResult}
442
- MDXContent.__RSPRESS_PAGE_META = {};
443
-
444
- MDXContent.__RSPRESS_PAGE_META["${encodeURIComponent(normalizePath(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].relative(docDirectory, filepath)))}"] = ${JSON.stringify(pageMeta)};
445
- `;
446
- callback(null, result);
11
+ if (crossCompilerCache && 'production' === process.env.NODE_ENV) {
12
+ const compileResult = await compileWithCrossCompilerCache({
13
+ source,
14
+ filepath,
15
+ docDirectory,
16
+ config,
17
+ pluginDriver,
18
+ routeService
19
+ });
20
+ callback(null, compileResult);
21
+ } else {
22
+ const compileResult = await compile({
23
+ source,
24
+ filepath,
25
+ docDirectory,
26
+ config,
27
+ pluginDriver,
28
+ routeService,
29
+ addDependency: this.addDependency
30
+ });
31
+ callback(null, compileResult);
32
+ }
447
33
  } catch (e) {
448
34
  if (e instanceof Error) {
449
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.error(`MDX compile error: ${e.message} in ${filepath}`);
450
- __WEBPACK_EXTERNAL_MODULE__rspress_shared_logger_4374e44a__.logger.debug(e);
35
+ logger.debug(e);
451
36
  callback({
452
- message: e.message,
37
+ message: `MDX compile error: ${e.message} in ${filepath}`,
453
38
  name: `${filepath} compile error`
454
39
  });
455
40
  }
456
41
  }
457
42
  }
458
- export { createCheckPageMetaUpdateFn, mdxLoader as default, updateSiteDataRuntimeModule };
43
+ export { mdxLoader as default };