@rspress/core 2.0.0-beta.21 → 2.0.0-beta.23

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/processor.js CHANGED
@@ -4,19 +4,19 @@ import node_path from "node:path";
4
4
  import { createProcessor, nodeTypes } from "@mdx-js/mdx";
5
5
  import { extractTextAndId, getNodeAttribute, loadFrontMatter } from "@rspress/shared/node-utils";
6
6
  import node_os from "node:os";
7
+ import rehype from "@shikijs/rehype";
7
8
  import rehype_external_links from "rehype-external-links";
8
9
  import rehype_raw from "rehype-raw";
9
10
  import remark_gfm from "remark-gfm";
11
+ import { visit } from "unist-util-visit";
10
12
  import github_slugger from "github-slugger";
11
13
  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 { createCssVariablesTheme } from "shiki";
15
+ import { readFile as promises_readFile } from "node:fs/promises";
14
16
  import { logger as logger_logger } from "@rspress/shared/logger";
15
17
  import picocolors_0 from "picocolors";
16
- import { readFile as promises_readFile } from "node:fs/promises";
18
+ import { addLeadingSlash, addTrailingSlash, isExternalUrl, isProduction, normalizeHref, parseUrl, removeTrailingSlash, withBase } from "@rspress/shared";
17
19
  import { visitChildren } from "unist-util-visit-children";
18
- import rehype from "@shikijs/rehype";
19
- import { createCssVariablesTheme } from "shiki";
20
20
  function applyReplaceRules(code = '', replaceRules = []) {
21
21
  let result = code;
22
22
  for (const rule of replaceRules)result = result.replace(rule.search, rule.replace);
@@ -33,6 +33,14 @@ function slash(p) {
33
33
  function normalizePath(id) {
34
34
  return node_path.posix.normalize(isWindows ? slash(id) : id);
35
35
  }
36
+ const rehypeCodeMeta = ()=>(tree)=>{
37
+ visit(tree, 'element', (node)=>{
38
+ if ('pre' === node.tagName && node.children[0]?.type === 'element' && 'code' === node.children[0].tagName) {
39
+ const codeNode = node.children[0];
40
+ codeNode.properties.metastring = codeNode.data?.meta;
41
+ }
42
+ });
43
+ };
36
44
  const rehypeHeaderAnchor = ()=>{
37
45
  const slugger = new github_slugger();
38
46
  return (tree)=>{
@@ -82,225 +90,6 @@ function create(node) {
82
90
  ]
83
91
  };
84
92
  }
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
93
  const SHIKI_TRANSFORMER_LINE_NUMBER = 'shiki-transformer:line-number';
305
94
  function transformerLineNumber(options = {}) {
306
95
  const { classActiveLine = 'line-number', classActivePre = 'has-line-number' } = options;
@@ -319,7 +108,7 @@ function parseTitleFromMeta(meta) {
319
108
  if (!meta) return '';
320
109
  const kvList = meta.split(' ').filter(Boolean);
321
110
  for (const item of kvList){
322
- const [k, v] = item.split('=');
111
+ const [k, v = ''] = item.split('=').filter(Boolean);
323
112
  if ('title' === k && v.length > 0) return v.replace(/["'`]/g, '');
324
113
  }
325
114
  return '';
@@ -364,6 +153,43 @@ function createRehypeShikiOptions(showLineNumbers, options) {
364
153
  transformers: newTransformers
365
154
  };
366
155
  }
156
+ const getASTNodeImport = (name, from)=>({
157
+ type: 'mdxjsEsm',
158
+ value: `import ${name} from ${JSON.stringify(from)}`,
159
+ data: {
160
+ estree: {
161
+ type: 'Program',
162
+ sourceType: 'module',
163
+ body: [
164
+ {
165
+ type: 'ImportDeclaration',
166
+ specifiers: [
167
+ {
168
+ type: 'ImportDefaultSpecifier',
169
+ local: {
170
+ type: 'Identifier',
171
+ name
172
+ }
173
+ }
174
+ ],
175
+ source: {
176
+ type: 'Literal',
177
+ value: from,
178
+ raw: `${JSON.stringify(from)}`
179
+ }
180
+ }
181
+ ]
182
+ }
183
+ }
184
+ });
185
+ const remarkBuiltin = ({ globalComponents })=>(tree)=>{
186
+ const demos = globalComponents.map((componentPath)=>{
187
+ const filename = node_path.parse(componentPath).name;
188
+ const componentName = filename[0].toUpperCase() + filename.slice(1);
189
+ return getASTNodeImport(componentName, componentPath);
190
+ });
191
+ tree.children.unshift(...demos);
192
+ };
367
193
  const DIRECTIVE_TYPES = [
368
194
  'tip',
369
195
  'note',
@@ -389,6 +215,7 @@ const createContainer = (type, title, children)=>{
389
215
  const titleHName = isDetails ? 'summary' : 'div';
390
216
  return {
391
217
  type: 'containerDirective',
218
+ name: type,
392
219
  data: {
393
220
  hName: rootHName,
394
221
  hProperties: {
@@ -567,21 +394,22 @@ function parseFileFromMeta(meta) {
567
394
  if (!meta) return '';
568
395
  const kvList = meta.split(' ').filter(Boolean);
569
396
  for (const item of kvList){
570
- const [k, v] = item.split('=');
397
+ const [k, v = ''] = item.split('=');
571
398
  if ('file' === k && v.length > 0) return v.replace(/["'`]/g, '');
572
399
  }
573
400
  return '';
574
401
  }
575
- const remarkFileCodeBlock = ({ filepath })=>async (tree)=>{
402
+ const remarkFileCodeBlock = ({ filepath, addDependency })=>async (tree)=>{
576
403
  const promiseList = [];
577
404
  visit(tree, 'code', (node)=>{
578
- const { meta, value } = node;
405
+ const { meta, value, lang } = node;
579
406
  const file = parseFileFromMeta(meta ?? '');
580
407
  if (!file) return;
408
+ const originalMetaForErrorInfo = picocolors_0.cyan(`\`\`\`${lang} ${meta}`);
581
409
  if (file.startsWith('./') || file.startsWith('../')) {
582
410
  const resolvedFilePath = node_path.join(node_path.dirname(filepath), file);
583
411
  if ('' !== value.trim()) {
584
- logger_logger.error(`${ERROR_PREFIX} The content of file code block should be empty.
412
+ logger_logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.
585
413
 
586
414
  \`\`\`tsx file="./filename"
587
415
  content
@@ -592,24 +420,233 @@ this usage is not allowed, please use below:
592
420
  \`\`\`tsx file="./filename"
593
421
  \`\`\`
594
422
  `);
595
- throw new Error(`${ERROR_PREFIX} The content of file code block should be empty.`);
423
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.`);
596
424
  }
597
425
  const promise = promises_readFile(resolvedFilePath, 'utf-8').then((fileContent)=>{
426
+ addDependency?.(resolvedFilePath);
598
427
  node.value = fileContent;
599
428
  }).catch((e)=>{
600
- logger_logger.error(`${ERROR_PREFIX} The file does not exist.
601
- \`file="${file}"\` is resolved to ${resolvedFilePath}"`);
429
+ const message = `${ERROR_PREFIX} ${originalMetaForErrorInfo} introduces another file in "${resolvedFilePath}", but the file does not exist.`;
430
+ logger_logger.error(message);
431
+ e.message = `${message}\n${e.message}`;
602
432
  throw e;
603
433
  });
604
434
  promiseList.push(promise);
605
435
  return;
606
436
  }
607
- throw new Error(`${ERROR_PREFIX} The file path should use relative path "./" or "../"`);
437
+ logger_logger.error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block:
438
+ Please use below:
439
+
440
+ \`\`\`tsx file="./filename"
441
+ \`\`\`
442
+ `);
443
+ throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} syntax error of file code block`);
608
444
  });
609
445
  await Promise.all(promiseList);
610
446
  };
447
+ const normalizeImageUrl = (imageUrl)=>{
448
+ if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) return '';
449
+ return imageUrl;
450
+ };
451
+ const remarkImage = ()=>(tree, _file)=>{
452
+ const images = [];
453
+ const getMdxSrcAttribute = (tempVar)=>({
454
+ type: 'mdxJsxAttribute',
455
+ name: 'src',
456
+ value: {
457
+ type: 'mdxJsxAttributeValueExpression',
458
+ value: tempVar,
459
+ data: {
460
+ estree: {
461
+ type: 'Program',
462
+ sourceType: 'module',
463
+ body: [
464
+ {
465
+ type: 'ExpressionStatement',
466
+ expression: {
467
+ type: 'Identifier',
468
+ name: tempVar
469
+ }
470
+ }
471
+ ]
472
+ }
473
+ }
474
+ }
475
+ });
476
+ visit(tree, 'image', (node)=>{
477
+ const { alt, url } = node;
478
+ if (!url) return;
479
+ const imagePath = normalizeImageUrl(url);
480
+ if (!imagePath) return;
481
+ const tempVariableName = `image${images.length}`;
482
+ Object.assign(node, {
483
+ type: 'mdxJsxFlowElement',
484
+ name: 'img',
485
+ children: [],
486
+ attributes: [
487
+ alt && {
488
+ type: 'mdxJsxAttribute',
489
+ name: 'alt',
490
+ value: alt
491
+ },
492
+ getMdxSrcAttribute(tempVariableName)
493
+ ].filter(Boolean)
494
+ });
495
+ images.push(getASTNodeImport(tempVariableName, imagePath));
496
+ });
497
+ visit(tree, (node)=>{
498
+ if ('mdxJsxFlowElement' !== node.type && 'mdxJsxTextElement' !== node.type || 'img' !== node.name) return;
499
+ const srcAttr = getNodeAttribute(node, 'src', true);
500
+ if ('string' != typeof srcAttr?.value) return;
501
+ const imagePath = normalizeImageUrl(srcAttr.value);
502
+ if (!imagePath) return;
503
+ const tempVariableName = `image${images.length}`;
504
+ Object.assign(srcAttr, getMdxSrcAttribute(tempVariableName));
505
+ images.push(getASTNodeImport(tempVariableName, imagePath));
506
+ });
507
+ tree.children.unshift(...images);
508
+ };
509
+ let isLogged = false;
510
+ function hintRelativeMarkdownLink() {
511
+ if (isLogged) return;
512
+ isLogged = true;
513
+ 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)');
514
+ }
515
+ function link_checkDeadLinks(checkDeadLinks, internalLinks, filePath, routeService) {
516
+ const errorInfos = [];
517
+ const excludes = 'object' == typeof checkDeadLinks ? checkDeadLinks.excludes : void 0;
518
+ const excludesUrl = Array.isArray(excludes) ? new Set(excludes) : void 0;
519
+ const excludesFn = 'function' == typeof excludes ? excludes : void 0;
520
+ let possibleBreakingChange = false;
521
+ [
522
+ ...internalLinks.entries()
523
+ ].forEach(([nodeUrl, link])=>{
524
+ if (excludesUrl?.has(nodeUrl)) return;
525
+ if (excludesFn?.(nodeUrl)) return;
526
+ const cleanLinkPath = linkToRoutePath(link);
527
+ if (!cleanLinkPath) return;
528
+ if (!nodeUrl.startsWith('/') && /^\w/.test(nodeUrl)) possibleBreakingChange = true;
529
+ if (!routeService.isExistRoute(removeTrailingSlash(cleanLinkPath)) && !routeService.isExistRoute(addTrailingSlash(cleanLinkPath))) errorInfos.push([
530
+ nodeUrl,
531
+ link
532
+ ]);
533
+ });
534
+ if (errorInfos.length > 0) {
535
+ if (possibleBreakingChange) hintRelativeMarkdownLink();
536
+ logger_logger.error(`Dead links found in ${picocolors_0.cyan(filePath)}:
537
+ ${errorInfos.map(([nodeUrl, link])=>` ${picocolors_0.green(`"[..](${nodeUrl})"`)} ${picocolors_0.gray(link)}`).join('\n')}`);
538
+ if (isProduction()) throw new Error('Dead link found');
539
+ }
540
+ }
541
+ function looseMarkdownLink(url, routeService, filePath) {
542
+ if (!routeService.isInDocsDir(filePath)) return url;
543
+ const [versionPart, langPart, pureRoute] = routeService.splitRoutePathParts(url);
544
+ const relativePath = routeService.absolutePathToRelativePath(filePath);
545
+ const [versionPartCurrFile, langPartCurrFile] = routeService.getRoutePathParts(relativePath);
546
+ if ('' === versionPart) {
547
+ if ('' === langPart) return addLeadingSlash(`${[
548
+ versionPartCurrFile,
549
+ langPartCurrFile
550
+ ].filter(Boolean).join('/')}${addLeadingSlash(pureRoute.replace(/^\/*/, ''))}`);
551
+ return addLeadingSlash(`${[
552
+ versionPartCurrFile,
553
+ langPart
554
+ ].filter(Boolean).join('/')}${addLeadingSlash(pureRoute.replace(/^\/*/, ''))}`);
555
+ }
556
+ return url;
557
+ }
558
+ function normalizeLink(nodeUrl, routeService, filePath, cleanUrls, autoPrefix, internalLinks, __base) {
559
+ if (!nodeUrl) return '';
560
+ if (nodeUrl.startsWith('#')) return nodeUrl;
561
+ let { url, hash } = parseUrl(nodeUrl);
562
+ if (isExternalUrl(url)) return url + (hash ? `#${hash}` : '');
563
+ if (!routeService) return nodeUrl;
564
+ if (url.startsWith('/')) {
565
+ if (autoPrefix) url = looseMarkdownLink(url, routeService, filePath);
566
+ const { routePath } = routeService.normalizeRoutePath(url);
567
+ url = routePath;
568
+ } else {
569
+ const anotherFileAbsolutePath = node_path.join(node_path.dirname(filePath), url);
570
+ url = routeService.absolutePathToRoutePath(anotherFileAbsolutePath);
571
+ }
572
+ if ('boolean' == typeof cleanUrls) url = normalizeHref(url, cleanUrls);
573
+ else {
574
+ url = normalizeHref(url, false);
575
+ url = url.replace(/\.html$/, cleanUrls);
576
+ }
577
+ internalLinks.set(nodeUrl, url);
578
+ if (hash) url += `#${hash}`;
579
+ if (__base) url = withBase(url, __base);
580
+ return url;
581
+ }
582
+ function linkToRoutePath(routePath) {
583
+ return decodeURIComponent(routePath.split('#')[0]).replace(/\.html$/, '').replace(/\/index$/, '/');
584
+ }
585
+ const remarkLink = ({ cleanUrls, routeService, remarkLinkOptions, __base })=>(tree, file)=>{
586
+ const { checkDeadLinks: shouldCheckDeadLinks = true, autoPrefix = true } = remarkLinkOptions ?? {};
587
+ const internalLinks = new Map();
588
+ visit(tree, 'link', (node)=>{
589
+ const { url: nodeUrl } = node;
590
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, autoPrefix, internalLinks, __base);
591
+ node.url = link;
592
+ });
593
+ visit(tree, 'definition', (node)=>{
594
+ const { url: nodeUrl } = node;
595
+ const link = normalizeLink(nodeUrl, routeService, file.path, cleanUrls, autoPrefix, internalLinks, __base);
596
+ node.url = link;
597
+ });
598
+ if (shouldCheckDeadLinks && routeService) link_checkDeadLinks(shouldCheckDeadLinks, internalLinks, file.path, routeService);
599
+ };
600
+ const parseToc = (tree)=>{
601
+ let title = '';
602
+ const toc = [];
603
+ const slugger = new github_slugger();
604
+ visitChildren((node)=>{
605
+ if ('heading' !== node.type || !node.depth || !node.children) return;
606
+ if (node.depth >= 1 && node.depth < 5) {
607
+ let customId = '';
608
+ const text = node.children.map((child)=>{
609
+ if ('link' === child.type) return child.children?.map((item)=>item.value).join('');
610
+ if ('strong' === child.type) return `**${child.children?.map((item)=>item.value).join('')}**`;
611
+ if ('emphasis' === child.type) return `*${child.children?.map((item)=>item.value).join('')}*`;
612
+ if ('delete' === child.type) return `~~${child.children?.map((item)=>item.value).join('')}~~`;
613
+ if ('text' === child.type) {
614
+ const [textPart, idPart] = extractTextAndId(child.value);
615
+ customId = idPart;
616
+ return textPart;
617
+ }
618
+ if ('inlineCode' === child.type) return `\`${child.value}\``;
619
+ return '';
620
+ }).join('');
621
+ if (1 === node.depth) {
622
+ if (!title) title = text;
623
+ } else {
624
+ const id = customId ? customId : slugger.slug(text.trim());
625
+ const { depth } = node;
626
+ toc.push({
627
+ id,
628
+ text,
629
+ depth
630
+ });
631
+ }
632
+ }
633
+ })(tree);
634
+ return {
635
+ title,
636
+ toc
637
+ };
638
+ };
639
+ const remarkToc = function() {
640
+ const data = this.data();
641
+ return (tree)=>{
642
+ const { toc, title } = parseToc(tree);
643
+ data.pageMeta.toc = toc;
644
+ if (title) data.pageMeta.title = title;
645
+ };
646
+ };
611
647
  async function createMDXOptions(options) {
612
- const { docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver } = options;
648
+ const { docDirectory, config, routeService, filepath, pluginDriver, addDependency } = options;
649
+ const remarkLinkOptions = config?.markdown?.link;
613
650
  const format = node_path.extname(filepath).slice(1);
614
651
  const cleanUrls = config?.route?.cleanUrls ?? false;
615
652
  const { remarkPlugins: remarkPluginsFromConfig = [], rehypePlugins: rehypePluginsFromConfig = [], globalComponents: globalComponentsFromConfig = [], showLineNumbers = false, shiki } = config?.markdown || {};
@@ -625,23 +662,25 @@ async function createMDXOptions(options) {
625
662
  format,
626
663
  remarkPlugins: [
627
664
  remark_gfm,
628
- remarkPluginToc,
665
+ remarkToc,
629
666
  remarkContainerSyntax,
630
667
  [
631
668
  remarkFileCodeBlock,
632
669
  {
633
- filepath
670
+ filepath,
671
+ addDependency
634
672
  }
635
673
  ],
636
674
  [
637
- remarkPluginNormalizeLink,
675
+ remarkLink,
638
676
  {
639
677
  cleanUrls,
640
678
  root: docDirectory,
641
679
  routeService,
642
- checkDeadLinks
680
+ remarkLinkOptions
643
681
  }
644
682
  ],
683
+ remarkImage,
645
684
  globalComponents.length && [
646
685
  remarkBuiltin,
647
686
  {
@@ -679,14 +718,14 @@ async function createMDXOptions(options) {
679
718
  };
680
719
  }
681
720
  async function compile(options) {
682
- const { source, filepath, docDirectory, checkDeadLinks, config, routeService, pluginDriver } = options;
721
+ const { source, filepath, docDirectory, config, routeService, pluginDriver, addDependency } = options;
683
722
  const mdxOptions = await createMDXOptions({
684
- checkDeadLinks,
685
723
  config,
686
724
  docDirectory,
687
725
  filepath,
688
726
  pluginDriver,
689
- routeService
727
+ routeService,
728
+ addDependency
690
729
  });
691
730
  const { frontmatter, emptyLinesSource } = loadFrontMatter(source, filepath, docDirectory, true);
692
731
  const { replaceRules } = config ?? {};
@@ -731,10 +770,14 @@ MDXContent.__RSPRESS_PAGE_META["${encodeURIComponent(normalizePath(node_path.rel
731
770
  }
732
771
  const cache = new Map();
733
772
  async function compileWithCrossCompilerCache(options) {
734
- const task = cache.get(options.filepath);
735
- if (task) return task;
773
+ const filepath = options.filepath;
774
+ const task = cache.get(filepath);
775
+ if (task) {
776
+ cache.delete(filepath);
777
+ return task;
778
+ }
736
779
  const promise = compile(options);
737
- cache.set(options.filepath, promise);
780
+ cache.set(filepath, promise);
738
781
  return promise;
739
782
  }
740
783
  export { compile, compileWithCrossCompilerCache };