@rspress/core 2.0.0-beta.2 → 2.0.0-beta.20
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/README.md +1 -1
- package/dist/index.d.ts +40 -14
- package/dist/index.js +994 -548
- package/dist/loader.d.ts +38 -34
- package/dist/loader.js +30 -525
- package/dist/processor.d.ts +95 -0
- package/dist/processor.js +688 -0
- package/dist/runtime/App.d.ts +1 -4
- package/dist/runtime/App.js +17 -20
- package/dist/runtime/ClientApp.js +24 -13
- package/dist/runtime/csrClientEntry.js +5 -13
- package/dist/runtime/initPageData.d.ts +0 -1
- package/dist/runtime/initPageData.js +18 -18
- package/dist/runtime/ssrClientEntry.js +14 -14
- package/dist/runtime/ssrServerEntry.d.ts +3 -2
- package/dist/runtime/ssrServerEntry.js +41 -17
- package/dist/shiki-transformers.d.ts +38 -0
- package/dist/shiki-transformers.js +77 -0
- package/dist/shiki-transformers.js.LICENSE.txt +5 -0
- package/package.json +34 -28
- package/dist/runtime/tsconfig.js +0 -4
|
@@ -0,0 +1,688 @@
|
|
|
1
|
+
import 'module';
|
|
2
|
+
/*#__PURE__*/ import.meta.url;
|
|
3
|
+
import node_path from "node:path";
|
|
4
|
+
import { createProcessor, nodeTypes } from "@mdx-js/mdx";
|
|
5
|
+
import { extractTextAndId, getNodeAttribute, loadFrontMatter } from "@rspress/shared/node-utils";
|
|
6
|
+
import node_os from "node:os";
|
|
7
|
+
import rehype_external_links from "rehype-external-links";
|
|
8
|
+
import rehype_raw from "rehype-raw";
|
|
9
|
+
import remark_gfm from "remark-gfm";
|
|
10
|
+
import github_slugger from "github-slugger";
|
|
11
|
+
import { headingRank } from "hast-util-heading-rank";
|
|
12
|
+
import { visit } from "unist-util-visit";
|
|
13
|
+
import { addTrailingSlash, isExternalUrl, isProduction, normalizeHref, parseUrl, removeTrailingSlash, withBase } from "@rspress/shared";
|
|
14
|
+
import { logger as logger_logger } from "@rspress/shared/logger";
|
|
15
|
+
import picocolors_0 from "picocolors";
|
|
16
|
+
import "node:fs/promises";
|
|
17
|
+
import { visitChildren } from "unist-util-visit-children";
|
|
18
|
+
import rehype from "@shikijs/rehype";
|
|
19
|
+
import { createCssVariablesTheme } from "shiki";
|
|
20
|
+
function applyReplaceRules(code = '', replaceRules = []) {
|
|
21
|
+
let result = code;
|
|
22
|
+
for (const rule of replaceRules)result = result.replace(rule.search, rule.replace);
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
function escapeMarkdownHeadingIds(content) {
|
|
26
|
+
const markdownHeadingRegexp = /(?:^|\n)#{1,6}(?!#).*/g;
|
|
27
|
+
return content.replace(markdownHeadingRegexp, (substring)=>substring.replace('{#', '\\{#').replace('\\\\{#', '\\{#'));
|
|
28
|
+
}
|
|
29
|
+
const isWindows = 'win32' === node_os.platform();
|
|
30
|
+
function slash(p) {
|
|
31
|
+
return p.replace(/\\/g, '/');
|
|
32
|
+
}
|
|
33
|
+
function normalizePath(id) {
|
|
34
|
+
return node_path.posix.normalize(isWindows ? slash(id) : id);
|
|
35
|
+
}
|
|
36
|
+
const rehypeHeaderAnchor = ()=>{
|
|
37
|
+
const slugger = new github_slugger();
|
|
38
|
+
return (tree)=>{
|
|
39
|
+
visit(tree, 'element', (node)=>{
|
|
40
|
+
if (!headingRank(node)) return;
|
|
41
|
+
if (!node.properties?.id) {
|
|
42
|
+
const [text, customId] = collectHeaderText(node);
|
|
43
|
+
node.properties ??= {};
|
|
44
|
+
node.properties.id = customId || slugger.slug(text.trim());
|
|
45
|
+
}
|
|
46
|
+
node.children.unshift(create(node));
|
|
47
|
+
});
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
const collectHeaderText = (node)=>{
|
|
51
|
+
let text = '';
|
|
52
|
+
let id = '';
|
|
53
|
+
node.children.forEach((child)=>{
|
|
54
|
+
if ('text' === child.type) {
|
|
55
|
+
const [textPart, idPart] = extractTextAndId(child.value);
|
|
56
|
+
child.value = textPart;
|
|
57
|
+
text += textPart;
|
|
58
|
+
id = idPart;
|
|
59
|
+
} else if ('element' === child.type) child.children.forEach((c)=>{
|
|
60
|
+
if ('text' === c.type) text += c.value;
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
return [
|
|
64
|
+
text,
|
|
65
|
+
id
|
|
66
|
+
];
|
|
67
|
+
};
|
|
68
|
+
function create(node) {
|
|
69
|
+
return {
|
|
70
|
+
type: 'element',
|
|
71
|
+
tagName: 'a',
|
|
72
|
+
properties: {
|
|
73
|
+
class: 'header-anchor',
|
|
74
|
+
ariaHidden: 'true',
|
|
75
|
+
href: `#${node.properties.id}`
|
|
76
|
+
},
|
|
77
|
+
children: [
|
|
78
|
+
{
|
|
79
|
+
type: 'text',
|
|
80
|
+
value: '#'
|
|
81
|
+
}
|
|
82
|
+
]
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
const getASTNodeImport = (name, from)=>({
|
|
86
|
+
type: 'mdxjsEsm',
|
|
87
|
+
value: `import ${name} from ${JSON.stringify(from)}`,
|
|
88
|
+
data: {
|
|
89
|
+
estree: {
|
|
90
|
+
type: 'Program',
|
|
91
|
+
sourceType: 'module',
|
|
92
|
+
body: [
|
|
93
|
+
{
|
|
94
|
+
type: 'ImportDeclaration',
|
|
95
|
+
specifiers: [
|
|
96
|
+
{
|
|
97
|
+
type: 'ImportDefaultSpecifier',
|
|
98
|
+
local: {
|
|
99
|
+
type: 'Identifier',
|
|
100
|
+
name
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
],
|
|
104
|
+
source: {
|
|
105
|
+
type: 'Literal',
|
|
106
|
+
value: from,
|
|
107
|
+
raw: `${JSON.stringify(from)}`
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
]
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
const remarkBuiltin = ({ globalComponents })=>(tree)=>{
|
|
115
|
+
const demos = globalComponents.map((componentPath)=>{
|
|
116
|
+
const filename = node_path.parse(componentPath).name;
|
|
117
|
+
const componentName = filename[0].toUpperCase() + filename.slice(1);
|
|
118
|
+
return getASTNodeImport(componentName, componentPath);
|
|
119
|
+
});
|
|
120
|
+
tree.children.unshift(...demos);
|
|
121
|
+
};
|
|
122
|
+
let isLogged = false;
|
|
123
|
+
function hintRelativeMarkdownLink() {
|
|
124
|
+
if (isLogged) return;
|
|
125
|
+
isLogged = true;
|
|
126
|
+
logger_logger.info('[Rspress v2] Markdown links without "./" prefix are now relative links, e.g: [](guide/getting-started) is equal to [](./guide/getting-started). You can rewrite it to [](/guide/getting-started) to always use absolute links, or use [](./getting-started.md)');
|
|
127
|
+
}
|
|
128
|
+
function normalizeLink_checkDeadLinks(internalLinks, filePath, routeService) {
|
|
129
|
+
const errorInfos = [];
|
|
130
|
+
let possibleBreakingChange = false;
|
|
131
|
+
[
|
|
132
|
+
...internalLinks.entries()
|
|
133
|
+
].forEach(([nodeUrl, link])=>{
|
|
134
|
+
const cleanLinkPath = linkToRoutePath(link);
|
|
135
|
+
if (!cleanLinkPath) return;
|
|
136
|
+
if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
|
|
137
|
+
if (!routeService.isExistRoute(removeTrailingSlash(cleanLinkPath)) && !routeService.isExistRoute(addTrailingSlash(cleanLinkPath))) errorInfos.push([
|
|
138
|
+
nodeUrl,
|
|
139
|
+
link
|
|
140
|
+
]);
|
|
141
|
+
});
|
|
142
|
+
if (errorInfos.length > 0) {
|
|
143
|
+
if (possibleBreakingChange) hintRelativeMarkdownLink();
|
|
144
|
+
logger_logger.error(`Dead links found in ${picocolors_0.cyan(filePath)}:
|
|
145
|
+
${errorInfos.map(([nodeUrl, link])=>` ${picocolors_0.green(`"[..](${nodeUrl})"`)} ${picocolors_0.gray(link)}`).join('\n')}`);
|
|
146
|
+
if (isProduction()) throw new Error('Dead link found');
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, internalLinks, __base) {
|
|
150
|
+
if (!nodeUrl) return '';
|
|
151
|
+
if (nodeUrl.startsWith('#')) return nodeUrl;
|
|
152
|
+
let { url, hash } = parseUrl(nodeUrl);
|
|
153
|
+
if (isExternalUrl(url)) return url + (hash ? `#${hash}` : '');
|
|
154
|
+
if (!routeService) return nodeUrl;
|
|
155
|
+
if (url.startsWith('/')) {
|
|
156
|
+
const { routePath } = routeService.normalizeRoutePath(url);
|
|
157
|
+
url = routePath;
|
|
158
|
+
} else {
|
|
159
|
+
const anotherFileAbsolutePath = node_path.join(node_path.dirname(filePath), url);
|
|
160
|
+
url = routeService.absolutePathToRoutePath(anotherFileAbsolutePath);
|
|
161
|
+
}
|
|
162
|
+
if ('boolean' == typeof cleanUrls) url = normalizeHref(url, cleanUrls);
|
|
163
|
+
else {
|
|
164
|
+
url = normalizeHref(url, false);
|
|
165
|
+
url = url.replace(/\.html$/, cleanUrls);
|
|
166
|
+
}
|
|
167
|
+
internalLinks.set(nodeUrl, url);
|
|
168
|
+
if (hash) url += `#${hash}`;
|
|
169
|
+
if (__base) url = withBase(url, __base);
|
|
170
|
+
return url;
|
|
171
|
+
}
|
|
172
|
+
function linkToRoutePath(routePath) {
|
|
173
|
+
return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
|
|
174
|
+
}
|
|
175
|
+
const normalizeImageUrl = (imageUrl)=>{
|
|
176
|
+
if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) return '';
|
|
177
|
+
return imageUrl;
|
|
178
|
+
};
|
|
179
|
+
const remarkPluginNormalizeLink = ({ cleanUrls, routeService, checkDeadLinks: shouldCheckDeadLinks = false, __base })=>(tree, file)=>{
|
|
180
|
+
const internalLinks = new Map();
|
|
181
|
+
visit(tree, 'link', (node)=>{
|
|
182
|
+
const { url: nodeUrl } = node;
|
|
183
|
+
const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
|
|
184
|
+
node.url = link;
|
|
185
|
+
});
|
|
186
|
+
visit(tree, 'definition', (node)=>{
|
|
187
|
+
const { url: nodeUrl } = node;
|
|
188
|
+
const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, internalLinks, __base);
|
|
189
|
+
node.url = link;
|
|
190
|
+
});
|
|
191
|
+
if (shouldCheckDeadLinks && routeService) normalizeLink_checkDeadLinks(internalLinks, file.path, routeService);
|
|
192
|
+
const images = [];
|
|
193
|
+
const getMdxSrcAttribute = (tempVar)=>({
|
|
194
|
+
type: 'mdxJsxAttribute',
|
|
195
|
+
name: 'src',
|
|
196
|
+
value: {
|
|
197
|
+
type: 'mdxJsxAttributeValueExpression',
|
|
198
|
+
value: tempVar,
|
|
199
|
+
data: {
|
|
200
|
+
estree: {
|
|
201
|
+
type: 'Program',
|
|
202
|
+
sourceType: 'module',
|
|
203
|
+
body: [
|
|
204
|
+
{
|
|
205
|
+
type: 'ExpressionStatement',
|
|
206
|
+
expression: {
|
|
207
|
+
type: 'Identifier',
|
|
208
|
+
name: tempVar
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
]
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
visit(tree, 'image', (node)=>{
|
|
217
|
+
const { alt, url } = node;
|
|
218
|
+
if (!url) return;
|
|
219
|
+
const imagePath = normalizeImageUrl(url);
|
|
220
|
+
if (!imagePath) return;
|
|
221
|
+
const tempVariableName = `image${images.length}`;
|
|
222
|
+
Object.assign(node, {
|
|
223
|
+
type: 'mdxJsxFlowElement',
|
|
224
|
+
name: 'img',
|
|
225
|
+
children: [],
|
|
226
|
+
attributes: [
|
|
227
|
+
alt && {
|
|
228
|
+
type: 'mdxJsxAttribute',
|
|
229
|
+
name: 'alt',
|
|
230
|
+
value: alt
|
|
231
|
+
},
|
|
232
|
+
getMdxSrcAttribute(tempVariableName)
|
|
233
|
+
].filter(Boolean)
|
|
234
|
+
});
|
|
235
|
+
images.push(getASTNodeImport(tempVariableName, imagePath));
|
|
236
|
+
});
|
|
237
|
+
visit(tree, (node)=>{
|
|
238
|
+
if ('mdxJsxFlowElement' !== node.type && 'mdxJsxTextElement' !== node.type || 'img' !== node.name) return;
|
|
239
|
+
const srcAttr = getNodeAttribute(node, 'src', true);
|
|
240
|
+
if ('string' != typeof srcAttr?.value) return;
|
|
241
|
+
const imagePath = normalizeImageUrl(srcAttr.value);
|
|
242
|
+
if (!imagePath) return;
|
|
243
|
+
const tempVariableName = `image${images.length}`;
|
|
244
|
+
Object.assign(srcAttr, getMdxSrcAttribute(tempVariableName));
|
|
245
|
+
images.push(getASTNodeImport(tempVariableName, imagePath));
|
|
246
|
+
});
|
|
247
|
+
tree.children.unshift(...images);
|
|
248
|
+
};
|
|
249
|
+
const parseToc = (tree)=>{
|
|
250
|
+
let title = '';
|
|
251
|
+
const toc = [];
|
|
252
|
+
const slugger = new github_slugger();
|
|
253
|
+
visitChildren((node)=>{
|
|
254
|
+
if ('heading' !== node.type || !node.depth || !node.children) return;
|
|
255
|
+
if (node.depth >= 1 && node.depth < 5) {
|
|
256
|
+
let customId = '';
|
|
257
|
+
const text = node.children.map((child)=>{
|
|
258
|
+
if ('link' === child.type) return child.children?.map((item)=>item.value).join('');
|
|
259
|
+
if ('strong' === child.type) return `**${child.children?.map((item)=>item.value).join('')}**`;
|
|
260
|
+
if ('emphasis' === child.type) return `*${child.children?.map((item)=>item.value).join('')}*`;
|
|
261
|
+
if ('delete' === child.type) return `~~${child.children?.map((item)=>item.value).join('')}~~`;
|
|
262
|
+
if ('text' === child.type) {
|
|
263
|
+
const [textPart, idPart] = extractTextAndId(child.value);
|
|
264
|
+
customId = idPart;
|
|
265
|
+
return textPart;
|
|
266
|
+
}
|
|
267
|
+
if ('inlineCode' === child.type) return `\`${child.value}\``;
|
|
268
|
+
return '';
|
|
269
|
+
}).join('');
|
|
270
|
+
if (1 === node.depth) {
|
|
271
|
+
if (!title) title = text;
|
|
272
|
+
} else {
|
|
273
|
+
const id = customId ? customId : slugger.slug(text.trim());
|
|
274
|
+
const { depth } = node;
|
|
275
|
+
toc.push({
|
|
276
|
+
id,
|
|
277
|
+
text,
|
|
278
|
+
depth
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
})(tree);
|
|
283
|
+
return {
|
|
284
|
+
title,
|
|
285
|
+
toc
|
|
286
|
+
};
|
|
287
|
+
};
|
|
288
|
+
const remarkPluginToc = function() {
|
|
289
|
+
const data = this.data();
|
|
290
|
+
return (tree)=>{
|
|
291
|
+
const { toc, title } = parseToc(tree);
|
|
292
|
+
data.pageMeta.toc = toc;
|
|
293
|
+
if (title) data.pageMeta.title = title;
|
|
294
|
+
};
|
|
295
|
+
};
|
|
296
|
+
const rehypeCodeMeta = ()=>(tree)=>{
|
|
297
|
+
visit(tree, 'element', (node)=>{
|
|
298
|
+
if ('pre' === node.tagName && node.children[0]?.type === 'element' && 'code' === node.children[0].tagName) {
|
|
299
|
+
const codeNode = node.children[0];
|
|
300
|
+
codeNode.properties.metastring = codeNode.data?.meta;
|
|
301
|
+
}
|
|
302
|
+
});
|
|
303
|
+
};
|
|
304
|
+
const SHIKI_TRANSFORMER_LINE_NUMBER = 'shiki-transformer:line-number';
|
|
305
|
+
function transformerLineNumber(options = {}) {
|
|
306
|
+
const { classActiveLine = 'line-number', classActivePre = 'has-line-number' } = options;
|
|
307
|
+
return {
|
|
308
|
+
name: SHIKI_TRANSFORMER_LINE_NUMBER,
|
|
309
|
+
pre (pre) {
|
|
310
|
+
return this.addClassToHast(pre, classActivePre);
|
|
311
|
+
},
|
|
312
|
+
line (node) {
|
|
313
|
+
this.addClassToHast(node, classActiveLine);
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
const SHIKI_TRANSFORMER_ADD_TITLE = 'shiki-transformer:add-title';
|
|
318
|
+
function parseTitleFromMeta(meta) {
|
|
319
|
+
if (!meta) return '';
|
|
320
|
+
let result = meta;
|
|
321
|
+
const highlightReg = /{[\d,-]*}/i;
|
|
322
|
+
const highlightMeta = highlightReg.exec(meta)?.[0];
|
|
323
|
+
if (highlightMeta) result = meta.replace(highlightReg, '').trim();
|
|
324
|
+
result = result.split('=')[1] ?? '';
|
|
325
|
+
return result?.replace(/["'`]/g, '');
|
|
326
|
+
}
|
|
327
|
+
function transformerAddTitle() {
|
|
328
|
+
return {
|
|
329
|
+
name: SHIKI_TRANSFORMER_ADD_TITLE,
|
|
330
|
+
pre (pre) {
|
|
331
|
+
const title = parseTitleFromMeta(this.options.meta?.__raw);
|
|
332
|
+
if (title.length > 0) pre.properties = {
|
|
333
|
+
...pre.properties,
|
|
334
|
+
title
|
|
335
|
+
};
|
|
336
|
+
return pre;
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
const cssVariablesTheme = createCssVariablesTheme({
|
|
341
|
+
name: 'css-variables',
|
|
342
|
+
variablePrefix: '--shiki-',
|
|
343
|
+
variableDefaults: {},
|
|
344
|
+
fontStyle: true
|
|
345
|
+
});
|
|
346
|
+
function createRehypeShikiOptions(showLineNumbers, options) {
|
|
347
|
+
const { transformers = [], ...restOptions } = options || {};
|
|
348
|
+
const newTransformers = [
|
|
349
|
+
transformerAddTitle(),
|
|
350
|
+
...transformers
|
|
351
|
+
];
|
|
352
|
+
if (showLineNumbers && !newTransformers.some((transformerItem)=>transformerItem.name === SHIKI_TRANSFORMER_LINE_NUMBER)) newTransformers.push(transformerLineNumber());
|
|
353
|
+
return {
|
|
354
|
+
theme: cssVariablesTheme,
|
|
355
|
+
defaultLanguage: 'txt',
|
|
356
|
+
lazy: true,
|
|
357
|
+
langs: [
|
|
358
|
+
'tsx',
|
|
359
|
+
'ts',
|
|
360
|
+
'js'
|
|
361
|
+
],
|
|
362
|
+
...restOptions,
|
|
363
|
+
addLanguageClass: true,
|
|
364
|
+
transformers: newTransformers
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
const DIRECTIVE_TYPES = [
|
|
368
|
+
'tip',
|
|
369
|
+
'note',
|
|
370
|
+
'warning',
|
|
371
|
+
'caution',
|
|
372
|
+
'danger',
|
|
373
|
+
'info',
|
|
374
|
+
'details'
|
|
375
|
+
];
|
|
376
|
+
const REGEX_BEGIN = /^\s*:::\s*(\w+)\s*(.*)?/;
|
|
377
|
+
const REGEX_END = /\s*:::$/;
|
|
378
|
+
const REGEX_GH_BEGIN = /^\s*\s*\[!(\w+)\]\s*(.*)?/;
|
|
379
|
+
const TITLE_REGEX_IN_MD = /{\s*title=["']?(.+)}\s*/;
|
|
380
|
+
const TITLE_REGEX_IN_MDX = /\s*title=["']?(.+)\s*/;
|
|
381
|
+
const trimTailingQuote = (str)=>str.replace(/['"]$/g, '');
|
|
382
|
+
const parseTitle = (rawTitle = '', isMDX = false)=>{
|
|
383
|
+
const matched = rawTitle?.match(isMDX ? TITLE_REGEX_IN_MDX : TITLE_REGEX_IN_MD);
|
|
384
|
+
return trimTailingQuote(matched?.[1] || rawTitle);
|
|
385
|
+
};
|
|
386
|
+
const createContainer = (type, title, children)=>{
|
|
387
|
+
const isDetails = 'details' === type;
|
|
388
|
+
const rootHName = isDetails ? 'details' : 'div';
|
|
389
|
+
const titleHName = isDetails ? 'summary' : 'div';
|
|
390
|
+
return {
|
|
391
|
+
type: 'containerDirective',
|
|
392
|
+
data: {
|
|
393
|
+
hName: rootHName,
|
|
394
|
+
hProperties: {
|
|
395
|
+
class: `rspress-directive ${type}`
|
|
396
|
+
}
|
|
397
|
+
},
|
|
398
|
+
children: [
|
|
399
|
+
{
|
|
400
|
+
type: 'paragraph',
|
|
401
|
+
data: {
|
|
402
|
+
hName: titleHName,
|
|
403
|
+
hProperties: {
|
|
404
|
+
class: 'rspress-directive-title'
|
|
405
|
+
}
|
|
406
|
+
},
|
|
407
|
+
children: [
|
|
408
|
+
{
|
|
409
|
+
type: 'text',
|
|
410
|
+
value: title || type.toUpperCase()
|
|
411
|
+
}
|
|
412
|
+
]
|
|
413
|
+
},
|
|
414
|
+
{
|
|
415
|
+
type: 'paragraph',
|
|
416
|
+
data: {
|
|
417
|
+
hName: 'div',
|
|
418
|
+
hProperties: {
|
|
419
|
+
class: 'rspress-directive-content'
|
|
420
|
+
}
|
|
421
|
+
},
|
|
422
|
+
children: children
|
|
423
|
+
}
|
|
424
|
+
]
|
|
425
|
+
};
|
|
426
|
+
};
|
|
427
|
+
function transformer(tree) {
|
|
428
|
+
let i = 0;
|
|
429
|
+
try {
|
|
430
|
+
while(i < tree.children.length){
|
|
431
|
+
const node = tree.children[i];
|
|
432
|
+
if ('children' in node) transformer(node);
|
|
433
|
+
if ('containerDirective' === node.type) {
|
|
434
|
+
const type = node.name;
|
|
435
|
+
if (DIRECTIVE_TYPES.includes(type)) tree.children.splice(i, 1, createContainer(type, node.attributes?.title ?? type.toUpperCase(), node.children));
|
|
436
|
+
} else if ('blockquote' === node.type && node.children[0]?.type === 'paragraph' && node.children[0].children?.[0] && 'value' in node.children[0].children[0]) {
|
|
437
|
+
const initiatorTag = node.children[0].children[0].value;
|
|
438
|
+
const match = initiatorTag.match(REGEX_GH_BEGIN);
|
|
439
|
+
if (match) {
|
|
440
|
+
const [, type] = match;
|
|
441
|
+
if (!DIRECTIVE_TYPES.includes(type.toLowerCase())) {
|
|
442
|
+
i++;
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
if (1 === node.children.length && 'paragraph' === node.children[0].type) node.children[0].children[0].value = match[2] ?? '';
|
|
446
|
+
const newChild = createContainer(type.toLowerCase(), type.toUpperCase(), 0 === node.children.slice(1).length ? node.children.slice(0) : node.children.slice(1));
|
|
447
|
+
tree.children.splice(i, 1, newChild);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
if ('paragraph' !== node.type || 'text' !== node.children[0].type) {
|
|
451
|
+
i++;
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
const firstTextNode = node.children[0];
|
|
455
|
+
const text = firstTextNode.value;
|
|
456
|
+
const metaText = text.split('\n')[0];
|
|
457
|
+
const content = text.slice(metaText.length);
|
|
458
|
+
const match = metaText.match(REGEX_BEGIN);
|
|
459
|
+
if (!match) {
|
|
460
|
+
i++;
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
const [, type, rawTitle] = match;
|
|
464
|
+
let title = parseTitle(rawTitle);
|
|
465
|
+
const titleExpressionNode = node.children[1] && 'mdxTextExpression' === node.children[1].type ? node.children[1] : null;
|
|
466
|
+
if (titleExpressionNode) {
|
|
467
|
+
title = parseTitle(titleExpressionNode.value, true);
|
|
468
|
+
node.children.splice(1, 1);
|
|
469
|
+
}
|
|
470
|
+
if (!DIRECTIVE_TYPES.includes(type)) {
|
|
471
|
+
i++;
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
const wrappedChildren = [];
|
|
475
|
+
if (content?.endsWith(':::')) {
|
|
476
|
+
wrappedChildren.push({
|
|
477
|
+
type: 'paragraph',
|
|
478
|
+
children: [
|
|
479
|
+
{
|
|
480
|
+
type: 'text',
|
|
481
|
+
value: content.replace(REGEX_END, '')
|
|
482
|
+
}
|
|
483
|
+
]
|
|
484
|
+
});
|
|
485
|
+
const newChild = createContainer(type, title, wrappedChildren);
|
|
486
|
+
tree.children.splice(i, 1, newChild);
|
|
487
|
+
} else {
|
|
488
|
+
const paragraphChild = {
|
|
489
|
+
type: 'paragraph',
|
|
490
|
+
children: []
|
|
491
|
+
};
|
|
492
|
+
wrappedChildren.push(paragraphChild);
|
|
493
|
+
if (content.length) paragraphChild.children.push({
|
|
494
|
+
type: 'text',
|
|
495
|
+
value: content
|
|
496
|
+
});
|
|
497
|
+
paragraphChild.children.push(...node.children.slice(1, -1));
|
|
498
|
+
if (0 === paragraphChild.children.length) wrappedChildren.pop();
|
|
499
|
+
const lastChildInNode = node.children[node.children.length - 1];
|
|
500
|
+
if ('text' === lastChildInNode.type && REGEX_END.test(lastChildInNode.value)) {
|
|
501
|
+
const lastChildInNodeText = lastChildInNode.value;
|
|
502
|
+
const matchedEndContent = lastChildInNodeText.slice(0, -3).trimEnd();
|
|
503
|
+
if (wrappedChildren.length) wrappedChildren[0].children.push({
|
|
504
|
+
type: 'text',
|
|
505
|
+
value: matchedEndContent
|
|
506
|
+
});
|
|
507
|
+
else if (matchedEndContent) wrappedChildren.push({
|
|
508
|
+
type: 'paragraph',
|
|
509
|
+
children: [
|
|
510
|
+
{
|
|
511
|
+
type: 'text',
|
|
512
|
+
value: matchedEndContent
|
|
513
|
+
}
|
|
514
|
+
]
|
|
515
|
+
});
|
|
516
|
+
const newChild = createContainer(type, title, wrappedChildren);
|
|
517
|
+
tree.children.splice(i, 1, newChild);
|
|
518
|
+
i++;
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
if (lastChildInNode !== firstTextNode && wrappedChildren.length) wrappedChildren[0].children.push(lastChildInNode);
|
|
522
|
+
let j = i + 1;
|
|
523
|
+
while(j < tree.children.length){
|
|
524
|
+
const currentParagraph = tree.children[j];
|
|
525
|
+
if ('paragraph' !== currentParagraph.type) {
|
|
526
|
+
wrappedChildren.push(currentParagraph);
|
|
527
|
+
j++;
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
530
|
+
const lastChild = currentParagraph.children[currentParagraph.children.length - 1];
|
|
531
|
+
if (lastChild === firstTextNode || 'text' === lastChild.type && REGEX_END.test(lastChild.value)) {
|
|
532
|
+
const lastChildText = lastChild.value;
|
|
533
|
+
const matchedEndContent = lastChildText.slice(0, -3).trimEnd();
|
|
534
|
+
const filteredChildren = currentParagraph.children.filter((child)=>child !== firstTextNode && child !== lastChild);
|
|
535
|
+
if (matchedEndContent) wrappedChildren.push({
|
|
536
|
+
type: 'paragraph',
|
|
537
|
+
children: [
|
|
538
|
+
...filteredChildren,
|
|
539
|
+
{
|
|
540
|
+
type: 'text',
|
|
541
|
+
value: matchedEndContent
|
|
542
|
+
}
|
|
543
|
+
]
|
|
544
|
+
});
|
|
545
|
+
else wrappedChildren.push(...filteredChildren);
|
|
546
|
+
const newChild = createContainer(type, title, wrappedChildren);
|
|
547
|
+
tree.children.splice(i, j - i + 1, newChild);
|
|
548
|
+
break;
|
|
549
|
+
}
|
|
550
|
+
wrappedChildren.push({
|
|
551
|
+
...currentParagraph,
|
|
552
|
+
children: currentParagraph.children.filter((child)=>child !== firstTextNode)
|
|
553
|
+
});
|
|
554
|
+
j++;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
i++;
|
|
558
|
+
}
|
|
559
|
+
} catch (e) {
|
|
560
|
+
console.log(e);
|
|
561
|
+
throw e;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
const remarkContainerSyntax = ()=>transformer;
|
|
565
|
+
async function createMDXOptions(options) {
|
|
566
|
+
const { docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver } = options;
|
|
567
|
+
const format = node_path.extname(filepath).slice(1);
|
|
568
|
+
const cleanUrls = config?.route?.cleanUrls ?? false;
|
|
569
|
+
const { remarkPlugins: remarkPluginsFromConfig = [], rehypePlugins: rehypePluginsFromConfig = [], globalComponents: globalComponentsFromConfig = [], showLineNumbers = false, shiki } = config?.markdown || {};
|
|
570
|
+
const rspressPlugins = pluginDriver?.getPlugins() ?? [];
|
|
571
|
+
const remarkPluginsFromPlugins = rspressPlugins.flatMap((plugin)=>plugin.markdown?.remarkPlugins || []);
|
|
572
|
+
const rehypePluginsFromPlugins = rspressPlugins.flatMap((plugin)=>plugin.markdown?.rehypePlugins || []);
|
|
573
|
+
const globalComponents = [
|
|
574
|
+
...rspressPlugins.flatMap((plugin)=>plugin.markdown?.globalComponents || []),
|
|
575
|
+
...globalComponentsFromConfig
|
|
576
|
+
];
|
|
577
|
+
return {
|
|
578
|
+
providerImportSource: '@mdx-js/react',
|
|
579
|
+
format,
|
|
580
|
+
remarkPlugins: [
|
|
581
|
+
remark_gfm,
|
|
582
|
+
remarkPluginToc,
|
|
583
|
+
remarkContainerSyntax,
|
|
584
|
+
[
|
|
585
|
+
remarkPluginNormalizeLink,
|
|
586
|
+
{
|
|
587
|
+
cleanUrls,
|
|
588
|
+
root: docDirectory,
|
|
589
|
+
routeService,
|
|
590
|
+
checkDeadLinks
|
|
591
|
+
}
|
|
592
|
+
],
|
|
593
|
+
globalComponents.length && [
|
|
594
|
+
remarkBuiltin,
|
|
595
|
+
{
|
|
596
|
+
globalComponents
|
|
597
|
+
}
|
|
598
|
+
],
|
|
599
|
+
...remarkPluginsFromConfig,
|
|
600
|
+
...remarkPluginsFromPlugins
|
|
601
|
+
].filter(Boolean),
|
|
602
|
+
rehypePlugins: [
|
|
603
|
+
rehypeHeaderAnchor,
|
|
604
|
+
...'md' === format ? [
|
|
605
|
+
rehypeCodeMeta,
|
|
606
|
+
[
|
|
607
|
+
rehype_raw,
|
|
608
|
+
{
|
|
609
|
+
passThrough: nodeTypes
|
|
610
|
+
}
|
|
611
|
+
]
|
|
612
|
+
] : [],
|
|
613
|
+
[
|
|
614
|
+
rehype,
|
|
615
|
+
createRehypeShikiOptions(showLineNumbers, shiki)
|
|
616
|
+
],
|
|
617
|
+
[
|
|
618
|
+
rehype_external_links,
|
|
619
|
+
{
|
|
620
|
+
target: '_blank',
|
|
621
|
+
rel: 'noopener noreferrer'
|
|
622
|
+
}
|
|
623
|
+
],
|
|
624
|
+
...rehypePluginsFromConfig,
|
|
625
|
+
...rehypePluginsFromPlugins
|
|
626
|
+
]
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
async function compile(options) {
|
|
630
|
+
const { source, filepath, docDirectory, checkDeadLinks, config, routeService, pluginDriver } = options;
|
|
631
|
+
const mdxOptions = await createMDXOptions({
|
|
632
|
+
checkDeadLinks,
|
|
633
|
+
config,
|
|
634
|
+
docDirectory,
|
|
635
|
+
filepath,
|
|
636
|
+
pluginDriver,
|
|
637
|
+
routeService
|
|
638
|
+
});
|
|
639
|
+
const { frontmatter, emptyLinesSource } = loadFrontMatter(source, filepath, docDirectory, true);
|
|
640
|
+
const { replaceRules } = config ?? {};
|
|
641
|
+
const replacedSource = applyReplaceRules(emptyLinesSource, replaceRules);
|
|
642
|
+
const preprocessedContent = escapeMarkdownHeadingIds(replacedSource);
|
|
643
|
+
try {
|
|
644
|
+
let pageMeta = {
|
|
645
|
+
title: '',
|
|
646
|
+
toc: [],
|
|
647
|
+
headingTitle: ''
|
|
648
|
+
};
|
|
649
|
+
const frontmatterTitle = extractTextAndId(frontmatter.title)[0];
|
|
650
|
+
const compiler = createProcessor(mdxOptions);
|
|
651
|
+
compiler.data('pageMeta', {
|
|
652
|
+
toc: [],
|
|
653
|
+
title: ''
|
|
654
|
+
});
|
|
655
|
+
const vFile = await compiler.process({
|
|
656
|
+
value: preprocessedContent,
|
|
657
|
+
path: filepath
|
|
658
|
+
});
|
|
659
|
+
const compileResult = String(vFile);
|
|
660
|
+
const compilationMeta = compiler.data('pageMeta');
|
|
661
|
+
const headingTitle = extractTextAndId(compilationMeta.title)[0];
|
|
662
|
+
pageMeta = {
|
|
663
|
+
...compilationMeta,
|
|
664
|
+
title: frontmatterTitle || headingTitle,
|
|
665
|
+
headingTitle,
|
|
666
|
+
frontmatter
|
|
667
|
+
};
|
|
668
|
+
const result = `const frontmatter = ${JSON.stringify(frontmatter)};
|
|
669
|
+
${compileResult}
|
|
670
|
+
MDXContent.__RSPRESS_PAGE_META = {};
|
|
671
|
+
|
|
672
|
+
MDXContent.__RSPRESS_PAGE_META["${encodeURIComponent(normalizePath(node_path.relative(docDirectory, filepath)))}"] = ${JSON.stringify(pageMeta)};
|
|
673
|
+
`;
|
|
674
|
+
return result;
|
|
675
|
+
} catch (e) {
|
|
676
|
+
if (e instanceof Error) throw e;
|
|
677
|
+
throw new Error(`MDX compile error: ${e} in ${filepath}`);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
const cache = new Map();
|
|
681
|
+
async function compileWithCrossCompilerCache(options) {
|
|
682
|
+
const task = cache.get(options.filepath);
|
|
683
|
+
if (task) return task;
|
|
684
|
+
const promise = compile(options);
|
|
685
|
+
cache.set(options.filepath, promise);
|
|
686
|
+
return promise;
|
|
687
|
+
}
|
|
688
|
+
export { compile, compileWithCrossCompilerCache };
|
package/dist/runtime/App.d.ts
CHANGED