|
| 1 | +import path from 'node:path'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Concept bodies link to peers with markdown `.md` paths — relative |
| 5 | + * (`../glossary/active-user.md`) or bundle-root-absolute |
| 6 | + * (`/tables/user-events.md`, the form the author-concept skill teaches). |
| 7 | + * Rewrite them to the concept's site route, prefixed with the site's base so |
| 8 | + * they work on a GitHub *project* page under `/<repo>/`. External, mailto, and |
| 9 | + * anchor links are left alone; links outside `knowledge/` are left alone. |
| 10 | + * |
| 11 | + * `base` is the Astro `base` (e.g. `/my-kb` or `/`), injected from the config. |
| 12 | + */ |
| 13 | +const KNOWLEDGE_ROOT = path.join(process.cwd(), 'knowledge'); |
| 14 | + |
| 15 | +function walk(node, fn) { |
| 16 | + if (!node || typeof node !== 'object') return; |
| 17 | + if (node.type === 'link') fn(node); |
| 18 | + if (Array.isArray(node.children)) for (const c of node.children) walk(c, fn); |
| 19 | +} |
| 20 | + |
| 21 | +export default function remarkLokfLinks({ base = '/' } = {}) { |
| 22 | + const prefix = base === '/' ? '' : base.replace(/\/$/, ''); |
| 23 | + return (tree, file) => { |
| 24 | + const filePath = file.path || (file.history && file.history[0]); |
| 25 | + const dir = filePath ? path.dirname(filePath) : KNOWLEDGE_ROOT; |
| 26 | + walk(tree, (node) => { |
| 27 | + const url = node.url || ''; |
| 28 | + if (!url.endsWith('.md') || /^(https?:|mailto:|#)/.test(url)) return; |
| 29 | + const abs = url.startsWith('/') |
| 30 | + ? path.join(KNOWLEDGE_ROOT, url.replace(/^\//, '')) |
| 31 | + : path.resolve(dir, url); |
| 32 | + const rel = path.relative(KNOWLEDGE_ROOT, abs).replace(/\.md$/, ''); |
| 33 | + if (rel.startsWith('..')) return; |
| 34 | + node.url = prefix + '/' + rel.split(path.sep).join('/'); |
| 35 | + }); |
| 36 | + }; |
| 37 | +} |
0 commit comments