@rspress/core 2.0.0-beta.22 → 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/loader.d.ts CHANGED
@@ -71,7 +71,8 @@ declare class RouteService {
71
71
  isExistRoute(routePath: string): boolean;
72
72
  generateRoutesCode(): string;
73
73
  private generateRoutesCodeByRouteMeta;
74
- getRoutePathParts(relativePath: string): readonly [string, string, string];
74
+ getRoutePathParts(relativePath: string): string[];
75
+ splitRoutePathParts(relativePath: string): readonly [string, string, string];
75
76
  normalizeRoutePath(relativePath: string): {
76
77
  pureRoutePath: string;
77
78
  routePath: string;
@@ -79,6 +80,7 @@ declare class RouteService {
79
80
  version: string;
80
81
  };
81
82
  absolutePathToRoutePath(absolutePath: string): string;
83
+ isInDocsDir(absolutePath: string): boolean;
82
84
  absolutePathToRelativePath(absolutePath: string): string;
83
85
  getRoutePageByRoutePath(routePath: string): RoutePage | undefined;
84
86
  }
package/dist/loader.js CHANGED
@@ -7,7 +7,7 @@ async function mdxLoader(source) {
7
7
  const callback = this.async();
8
8
  const options = this.getOptions();
9
9
  const filepath = this.resourcePath;
10
- const { config, docDirectory, checkDeadLinks, routeService, pluginDriver } = options;
10
+ const { config, docDirectory, routeService, pluginDriver } = options;
11
11
  const crossCompilerCache = config?.markdown?.crossCompilerCache ?? true;
12
12
  try {
13
13
  if (crossCompilerCache && 'production' === process.env.NODE_ENV) {
@@ -15,7 +15,6 @@ async function mdxLoader(source) {
15
15
  source,
16
16
  filepath,
17
17
  docDirectory,
18
- checkDeadLinks,
19
18
  config,
20
19
  pluginDriver,
21
20
  routeService
@@ -26,10 +25,10 @@ async function mdxLoader(source) {
26
25
  source,
27
26
  filepath,
28
27
  docDirectory,
29
- checkDeadLinks,
30
28
  config,
31
29
  pluginDriver,
32
- routeService
30
+ routeService,
31
+ addDependency: this.addDependency
33
32
  });
34
33
  callback(null, compileResult);
35
34
  }
@@ -2,6 +2,7 @@ import { AdditionalPage } from '@rspress/shared';
2
2
  import { DefaultThemeConfig } from '@rspress/shared';
3
3
  import type { PageIndexInfo } from '@rspress/shared';
4
4
  import type { RouteMeta } from '@rspress/shared';
5
+ import type { Rspack as Rspack_2 } from '@rsbuild/core';
5
6
  import type { RspressPlugin } from '@rspress/shared';
6
7
  import type { UserConfig } from '@rspress/shared';
7
8
 
@@ -10,11 +11,11 @@ export declare function compile(options: CompileOptions): Promise<string>;
10
11
  declare interface CompileOptions {
11
12
  source: string;
12
13
  filepath: string;
13
- checkDeadLinks: boolean;
14
14
  docDirectory: string;
15
15
  config: UserConfig | null;
16
16
  routeService: RouteService | null;
17
17
  pluginDriver: PluginDriver | null;
18
+ addDependency?: Rspack_2.LoaderContext['addDependency'];
18
19
  }
19
20
 
20
21
  export declare function compileWithCrossCompilerCache(options: CompileOptions): Promise<string>;
@@ -73,7 +74,8 @@ declare class RouteService {
73
74
  isExistRoute(routePath: string): boolean;
74
75
  generateRoutesCode(): string;
75
76
  private generateRoutesCodeByRouteMeta;
76
- getRoutePathParts(relativePath: string): readonly [string, string, string];
77
+ getRoutePathParts(relativePath: string): string[];
78
+ splitRoutePathParts(relativePath: string): readonly [string, string, string];
77
79
  normalizeRoutePath(relativePath: string): {
78
80
  pureRoutePath: string;
79
81
  routePath: string;
@@ -81,6 +83,7 @@ declare class RouteService {
81
83
  version: string;
82
84
  };
83
85
  absolutePathToRoutePath(absolutePath: string): string;
86
+ isInDocsDir(absolutePath: string): boolean;
84
87
  absolutePathToRelativePath(absolutePath: string): string;
85
88
  getRoutePageByRoutePath(routePath: string): RoutePage | undefined;
86
89
  }
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;
@@ -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',
@@ -573,7 +399,7 @@ function parseFileFromMeta(meta) {
573
399
  }
574
400
  return '';
575
401
  }
576
- const remarkFileCodeBlock = ({ filepath })=>async (tree)=>{
402
+ const remarkFileCodeBlock = ({ filepath, addDependency })=>async (tree)=>{
577
403
  const promiseList = [];
578
404
  visit(tree, 'code', (node)=>{
579
405
  const { meta, value, lang } = node;
@@ -597,6 +423,7 @@ this usage is not allowed, please use below:
597
423
  throw new Error(`${ERROR_PREFIX} ${originalMetaForErrorInfo} The content of file code block should be empty.`);
598
424
  }
599
425
  const promise = promises_readFile(resolvedFilePath, 'utf-8').then((fileContent)=>{
426
+ addDependency?.(resolvedFilePath);
600
427
  node.value = fileContent;
601
428
  }).catch((e)=>{
602
429
  const message = `${ERROR_PREFIX} ${originalMetaForErrorInfo} introduces another file in "${resolvedFilePath}", but the file does not exist.`;
@@ -617,8 +444,209 @@ Please use below:
617
444
  });
618
445
  await Promise.all(promiseList);
619
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
+ };
620
647
  async function createMDXOptions(options) {
621
- const { docDirectory, config, checkDeadLinks, routeService, filepath, pluginDriver } = options;
648
+ const { docDirectory, config, routeService, filepath, pluginDriver, addDependency } = options;
649
+ const remarkLinkOptions = config?.markdown?.link;
622
650
  const format = node_path.extname(filepath).slice(1);
623
651
  const cleanUrls = config?.route?.cleanUrls ?? false;
624
652
  const { remarkPlugins: remarkPluginsFromConfig = [], rehypePlugins: rehypePluginsFromConfig = [], globalComponents: globalComponentsFromConfig = [], showLineNumbers = false, shiki } = config?.markdown || {};
@@ -634,23 +662,25 @@ async function createMDXOptions(options) {
634
662
  format,
635
663
  remarkPlugins: [
636
664
  remark_gfm,
637
- remarkPluginToc,
665
+ remarkToc,
638
666
  remarkContainerSyntax,
639
667
  [
640
668
  remarkFileCodeBlock,
641
669
  {
642
- filepath
670
+ filepath,
671
+ addDependency
643
672
  }
644
673
  ],
645
674
  [
646
- remarkPluginNormalizeLink,
675
+ remarkLink,
647
676
  {
648
677
  cleanUrls,
649
678
  root: docDirectory,
650
679
  routeService,
651
- checkDeadLinks
680
+ remarkLinkOptions
652
681
  }
653
682
  ],
683
+ remarkImage,
654
684
  globalComponents.length && [
655
685
  remarkBuiltin,
656
686
  {
@@ -688,14 +718,14 @@ async function createMDXOptions(options) {
688
718
  };
689
719
  }
690
720
  async function compile(options) {
691
- const { source, filepath, docDirectory, checkDeadLinks, config, routeService, pluginDriver } = options;
721
+ const { source, filepath, docDirectory, config, routeService, pluginDriver, addDependency } = options;
692
722
  const mdxOptions = await createMDXOptions({
693
- checkDeadLinks,
694
723
  config,
695
724
  docDirectory,
696
725
  filepath,
697
726
  pluginDriver,
698
- routeService
727
+ routeService,
728
+ addDependency
699
729
  });
700
730
  const { frontmatter, emptyLinesSource } = loadFrontMatter(source, filepath, docDirectory, true);
701
731
  const { replaceRules } = config ?? {};
@@ -740,10 +770,14 @@ MDXContent.__RSPRESS_PAGE_META["${encodeURIComponent(normalizePath(node_path.rel
740
770
  }
741
771
  const cache = new Map();
742
772
  async function compileWithCrossCompilerCache(options) {
743
- const task = cache.get(options.filepath);
744
- 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
+ }
745
779
  const promise = compile(options);
746
- cache.set(options.filepath, promise);
780
+ cache.set(filepath, promise);
747
781
  return promise;
748
782
  }
749
783
  export { compile, compileWithCrossCompilerCache };