Debian Codegraph @

web/docs/plugins/remark-strip-md-extension.mjs

raw
1 /**
2 * Remark plugin to strip .md extensions from relative links and resolve paths.
3 *
4 * This allows markdown files to use links like [text](other-file.md) which
5 * work on GitHub, while producing clean URLs like /other-file/ in the built site.
6 *
7 * Links are kept relative (not absolute) so they work with any base path
8 * configuration. The key insight is that Starlight serves pages with trailing
9 * slashes (e.g., /guides/divergence/), which browsers treat as directories.
10 * For non-index files, we prepend ../ to counteract this behavior.
11 *
12 * Handles both inline links [text](url) and reference definitions [ref]: url
13 */
14
15 import { visit } from 'unist-util-visit';
16 import path from 'node:path';
17
18 export default function remarkStripMdExtension() {
19 return (tree, file) => {
20 // Get the file's path relative to the content directory
21 const filePath = file.history[0];
22 const contentDocsMatch = filePath.match(/src\/content\/docs\/(.+)$/);
23 const relativePath = contentDocsMatch[1];
24 const currentDir = path.dirname(relativePath);
25
26 // Check if current file is an index file
27 const isIndex = path.basename(relativePath) === 'index.md';
28
29 // Calculate directory depth for absolute link conversion
30 const dirParts = currentDir === '.' ? [] : currentDir.split(path.sep);
31 const depth = dirParts.length;
32 visit(tree, ['link', 'definition'], (node) => {
33 const url = node.url;
34 if (!url || typeof url !== 'string') return;
35
36 // Skip external links and anchors
37 if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('#')) {
38 return;
39 }
40
41 // Separate the path from hash/query
42 const hashIndex = url.indexOf('#');
43 const queryIndex = url.indexOf('?');
44 let pathEnd = url.length;
45 if (hashIndex !== -1) pathEnd = Math.min(pathEnd, hashIndex);
46 if (queryIndex !== -1) pathEnd = Math.min(pathEnd, queryIndex);
47
48 const linkPath = url.slice(0, pathEnd);
49 const suffix = url.slice(pathEnd); // hash or query string
50
51 // Only process links with .md extension in the path (not in hash/query)
52 if (!linkPath.endsWith('.md')) {
53 return;
54 }
55
56 // Strip .md extension
57 const pathWithoutMd = linkPath.slice(0, -3);
58
59 let resultPath;
60
61 if (pathWithoutMd.startsWith('/')) {
62 // Absolute link: convert to relative
63 const targetPath = pathWithoutMd.slice(1); // Remove leading /
64 // Non-index files are served at an extra level due to trailing slash
65 const effectiveDepth = isIndex ? depth : depth + 1;
66 const prefix = '../'.repeat(effectiveDepth);
67 resultPath = prefix + targetPath;
68 } else {
69 // Relative link: prepend ../ for non-index files to counteract trailing slash
70 if (isIndex) {
71 resultPath = pathWithoutMd;
72 } else {
73 resultPath = '../' + pathWithoutMd;
74 }
75 }
76
77 // Normalize the path to resolve ../ sequences
78 // But keep it relative (don't let it become absolute)
79 resultPath = path.posix.normalize(resultPath);
80
81 // Handle index file targets: foo/index -> foo
82 resultPath = resultPath.replace(/\/index$/, '');
83
84 // Add trailing slash for Starlight's URL structure
85 if (!resultPath.endsWith('/')) {
86 resultPath += '/';
87 }
88
89 node.url = resultPath + suffix;
90 });
91 };
92 }