Debian Codegraph @

www/src/lib/content.js

raw symbols SCIP
1 /**
2 * lib/content.js
3 *
4 * Filesystem-first content tree builder.
5 *
6 * Provides a clean API for navigating content as folders and files.
7 * Data objects (ContentFile, ContentFolder) are plain data with
8 * pre-computed derived fields. render() is a separate action.
9 *
10 * Built on import.meta.glob for md/mdx (keys for path enumeration at module
11 * init, lazy imports for content) and direct fs reads for yaml/json data files.
12 */
13
14 import { readFileSync } from 'node:fs';
15 import { join, dirname, resolve } from 'node:path';
16 import yaml from 'js-yaml';
17 import integrity from '../data/integrity.json';
18
19 /**
20 * @typedef {Object} Breadcrumb
21 * @property {string} label
22 * @property {string} [href]
23 */
24
25 /**
26 * @typedef {Object} ContentFile
27 * @property {string} path
28 * @property {string} folder
29 * @property {string} slug
30 * @property {string} url
31 * @property {Record<string, any>} frontmatter
32 * @property {Breadcrumb[]} breadcrumbs
33 * @property {ContentFile} [prev]
34 * @property {ContentFile} [next]
35 */
36
37 /**
38 * @typedef {Object} ContentFolder
39 * @property {string} path
40 * @property {string} folder
41 * @property {string} slug
42 * @property {string} url
43 * @property {Record<string, any>} frontmatter
44 * @property {Breadcrumb[]} breadcrumbs
45 * @property {ContentFile[]} files
46 * @property {ContentFolder[]} folders
47 * @property {ContentFile[]} allFiles
48 */
49
50 // Case-preserving filesystem paths (strings only, no modules loaded, no circular dependency)
51 const allPaths = Object.keys(import.meta.glob('/src/content/**/*.{md,mdx}'));
52
53 // Lazy module loaders, called inside async functions, not at module init
54 /** @type {Record<string, () => Promise<any>>} */
55 const lazyModules = import.meta.glob('/src/content/**/*.{md,mdx}');
56
57 // Raw authored sources, eagerly loaded. Used by fileAsMarkdown to serve the
58 // `.md` companion endpoint for every prose page.
59 /** @type {Record<string, string>} */
60 const rawSources = import.meta.glob('/src/content/**/*.{md,mdx}', {
61 query: '?raw',
62 import: 'default',
63 eager: true,
64 });
65
66
67 // Cache for loaded modules to avoid re-importing
68 const moduleCache = new Map();
69
70 async function loadModule(fullPath) {
71 if (moduleCache.has(fullPath)) return moduleCache.get(fullPath);
72 const loader = lazyModules[fullPath];
73 if (!loader) return null;
74 const mod = await loader();
75 moduleCache.set(fullPath, mod);
76 return mod;
77 }
78
79 /**
80 * Convention: a file with slug `full` in a collection is the aggregate view
81 * of that collection. It's excluded from sidebar lists and prev/next nav,
82 * and its body is synthesised at content-load time by
83 * aggregateCollectionMarkdown().
84 * @param {{ slug: string }} file
85 */
86 export function isAggregate(file) {
87 return file.slug === 'full';
88 }
89
90 export function readRaw(fullPath) {
91 try {
92 return readFileSync(join(process.cwd(), fullPath.replace(/^\//, '')), 'utf-8');
93 } catch {
94 return '';
95 }
96 }
97
98 function rawBody(fullPath) {
99 return readRaw(fullPath)
100 .replace(/^---[\s\S]*?---\n*/, '')
101 .replace(/<script>[\s\S]*?server\.start[\s\S]*?<\/script>\s*/g, '')
102 .trim();
103 }
104
105 function rawTitle(fullPath) {
106 const raw = readRaw(fullPath);
107 const fmMatch = raw.match(/^---\s*\n([\s\S]*?)\n---/);
108 const titleMatch = fmMatch?.[1].match(/^title:\s*(.+)$/m);
109 return titleMatch?.[1].replace(/^["']|["']$/g, '').trim() || '';
110 }
111
112 /**
113 * Strip MDX-only constructs from a body so it reads as plain markdown:
114 * top-level `import` lines, `{/* ... *\/}` comments, `<Code lang="X"
115 * code={`Y`} ... />` components (unwrapped to fenced blocks), and
116 * `${data.field}` interpolations (resolved against any JSON imports).
117 *
118 * Fence-aware: never touches lines inside ``` / ~~~ code blocks.
119 */
120 function stripMdxForMarkdown(body, sourcePath) {
121 const baseDir = dirname(join(process.cwd(), 'src', 'content', sourcePath));
122 /** @type {Record<string, any>} */
123 const data = {};
124 const out = [];
125 let inFence = false;
126
127 for (const line of body.split('\n')) {
128 if (/^(`{3,}|~{3,})/.test(line)) {
129 inFence = !inFence;
130 out.push(line);
131 continue;
132 }
133 if (inFence) { out.push(line); continue; }
134
135 const jsonImport = line.match(/^import\s+(\w+)\s+from\s+['"](.+\.json)['"];?\s*$/);
136 if (jsonImport) {
137 const [, name, path] = jsonImport;
138 try { data[name] = JSON.parse(readFileSync(resolve(baseDir, path), 'utf-8')); } catch {}
139 continue;
140 }
141 if (/^import\s+/.test(line)) continue;
142
143 out.push(line);
144 }
145
146 return out.join('\n')
147 .replace(/\{\/\*[\s\S]*?\*\/\}\s*/g, '')
148 .replace(
149 /<Code\s+lang=["']([^"']+)["']\s+code=\{`([\s\S]*?)`\}[^>]*\/>/g,
150 (_, lang, code) => `\`\`\`${lang}\n${code}\n\`\`\``
151 )
152 .replace(/\$\{(\w+)(?:\.(\w+))?\}/g, (match, name, field) => {
153 if (!(name in data)) return match;
154 const v = field !== undefined ? data[name][field] : data[name];
155 return v !== undefined && v !== null ? String(v) : match;
156 })
157 .trim();
158 }
159
160 /**
161 * Return a content file's authored markdown as a standalone document:
162 * `# <title>` prepended (unless the body already starts with an H1),
163 * frontmatter and inline demo-server scripts stripped, and MDX-only
164 * constructs reduced to plain markdown. Consumed by the `.md` companion
165 * endpoint for every prose page.
166 * @param {string} path
167 * @returns {string}
168 */
169 export function fileAsMarkdown(path) {
170 const fullPath = `/src/content/${path}`;
171 let body = rawBody(fullPath);
172 if (!body) return '';
173 if (path.endsWith('.mdx')) body = stripMdxForMarkdown(body, path);
174 // Resolve the CDN/npm version token (single source: integrity.json); the
175 // remark plugin handles the rendered HTML, this covers raw-markdown exports.
176 body = body.split('__VERSION__').join(integrity.version);
177 const title = rawTitle(fullPath);
178 return title && !/^#\s/.test(body) ? `# ${title}\n\n${body}` : body;
179 }
180
181 function isDataFile(path) {
182 return /\.(yaml|yml|json)$/.test(path);
183 }
184
185
186 // --- Helpers ---
187
188 function getFolderName(path) {
189 return path.split('/')[0];
190 }
191
192 function cleanPath(path) {
193 return path
194 .split('/')
195 .map(segment => segment.replace(/^\d+-/, '').replace(/\.(md|mdx)$/, ''))
196 .join('/');
197 }
198
199 /**
200 * @param {ContentFile} a
201 * @param {ContentFile} b
202 */
203 function sortContentFiles(a, b) {
204 const aCreated = a.frontmatter?.created;
205 const bCreated = b.frontmatter?.created;
206 if (aCreated && bCreated) {
207 return new Date(bCreated).getTime() - new Date(aCreated).getTime();
208 }
209 return a.path.localeCompare(b.path);
210 }
211
212
213 // --- Constants ---
214
215 export const COLLECTIONS = ['home', 'about', 'docs', 'reference', 'extensions', 'patterns', 'essays', 'interviews', 'podcasts', 'memes'];
216
217 export const TAG_ORDER = [
218 {tag: 'foundations', label: 'Foundations'},
219 {tag: 'the-case-for-hypermedia', label: 'The Case for Hypermedia'},
220 {tag: 'case-studies', label: 'Case Studies'},
221 {tag: 'guides', label: 'Guides'},
222 {tag: 'simplicity', label: 'Simplicity'},
223 ];
224
225 // --- Actions ---
226
227 /**
228 * Render a content file or folder. Separate from data, this is I/O.
229 *
230 * @param {ContentFile | ContentFolder} item
231 * @returns {Promise<{ Content: any; headings: any[] }>}
232 */
233 export async function render(item) {
234 const mod = await loadModule(`/src/content/${item.path}`);
235 if (!mod) return {Content: null, headings: []};
236 return {
237 Content: mod.default,
238 headings: mod.getHeadings?.() || []
239 };
240 }
241
242 // --- Functions ---
243
244 /**
245 * Get content folder tree.
246 *
247 * @param {string} path - Folder path (e.g., 'docs', 'reference')
248 * @returns {Promise<ContentFolder>} ContentFolder representing the folder with nested structure
249 */
250 export async function getFolder(path) {
251 // Handle root-level files (e.g. 'home' → index.mdx, 'about' → about.mdx)
252 /** @type {Record<string, string>} */
253 const rootFileMap = {home: 'index'};
254 const rootFileName = rootFileMap[path] ?? path;
255 const rootFullPath = allPaths.find(p =>
256 p === `/src/content/${rootFileName}.mdx` || p === `/src/content/${rootFileName}.md`
257 );
258 const hasFolder = allPaths.some(p =>
259 p.startsWith(`/src/content/${path}/index.md`) || p.startsWith(`/src/content/${path}/index.mdx`)
260 );
261
262 if (rootFullPath && !hasFolder) {
263 const rootRelPath = rootFullPath.replace('/src/content/', '');
264 const isHome = path === 'home';
265 /** @type {Record<string, any>} */
266 let rootFrontmatter = {};
267 try {
268 const raw = readFileSync(join(process.cwd(), 'src', 'content', rootRelPath), 'utf-8');
269 const match = raw.match(/^---\s*\n([\s\S]*?)\n---/);
270 if (match) rootFrontmatter = /** @type {Record<string, any>} */ (yaml.load(match[1])) ?? {};
271 } catch {}
272 return {
273 path: rootRelPath,
274 folder: path,
275 slug: '',
276 url: isHome ? '/' : `/${path}`,
277 frontmatter: rootFrontmatter,
278 files: [],
279 folders: [],
280 allFiles: [],
281 breadcrumbs: []
282 };
283 }
284
285 const folderName = path.split('/')[0];
286 const prefix = `/src/content/${folderName}/`;
287
288 // All paths under this folder
289 const folderPaths = allPaths.filter(p => p.startsWith(prefix));
290
291 /**
292 * @param {string} basePath
293 * @param {Breadcrumb[]} parentBreadcrumbs
294 * @returns {Promise<ContentFolder | null>}
295 */
296 const buildFolder = async (basePath, parentBreadcrumbs = []) => {
297 const indexPath = basePath ? `${basePath}/index` : `${folderName}/index`;
298
299 // Find the index file
300 const indexFullPath = folderPaths.find(p => {
301 const rel = p.replace('/src/content/', '').replace(/\.(md|mdx)$/, '');
302 return rel === indexPath;
303 });
304 if (!indexFullPath) return null;
305
306 const indexRelPath = indexFullPath.replace('/src/content/', '');
307
308 // Read frontmatter from disk to avoid executing MDX module bodies.
309 // Index .mdx files may call getFolder() themselves, loading them
310 // as modules here would create a circular call.
311 /** @type {Record<string, any>} */
312 let indexFrontmatter = {};
313 try {
314 const raw = readFileSync(join(process.cwd(), 'src', 'content', indexRelPath), 'utf-8');
315 const match = raw.match(/^---\s*\n([\s\S]*?)\n---/);
316 if (match) indexFrontmatter = /** @type {Record<string, any>} */ (yaml.load(match[1])) ?? {};
317 } catch {}
318
319 // Compute slug and URL
320 const pathWithoutIndex = indexRelPath.replace(/\/index\.(md|mdx)$/, '');
321 const pathWithoutFolder = pathWithoutIndex === folderName ? '' : pathWithoutIndex.replace(`${folderName}/`, '');
322 const slug = cleanPath(pathWithoutFolder);
323 const folderUrl = slug ? `/${folderName}/${slug}` : `/${folderName}`;
324
325 // Breadcrumbs
326 /** @type {Breadcrumb} */
327 const thisFolderBreadcrumb = {
328 label: indexFrontmatter.title,
329 href: folderUrl
330 };
331 const breadcrumbsWithHref = [...parentBreadcrumbs, thisFolderBreadcrumb];
332 const folderBreadcrumbs = parentBreadcrumbs.length > 0
333 ? [...parentBreadcrumbs, {label: indexFrontmatter.title}]
334 : [{label: indexFrontmatter.title}];
335
336 // Direct child files (not in subfolders, excluding index)
337 const directFilePaths = folderPaths
338 .filter(p => {
339 const rel = p.replace('/src/content/', '');
340 if (rel.endsWith('index.md') || rel.endsWith('index.mdx')) return false;
341 const withoutExt = rel.replace(/\.(md|mdx)$/, '');
342 const fileFolder = withoutExt.substring(0, withoutExt.lastIndexOf('/'));
343 return fileFolder === basePath;
344 })
345 .sort();
346
347 // Direct child folders
348 const childFolderPaths = new Set();
349 for (const p of folderPaths) {
350 const rel = p.replace('/src/content/', '');
351 if (!basePath || rel.startsWith(basePath + '/')) {
352 const afterBase = basePath ? rel.substring(basePath.length + 1) : rel;
353 const firstSlash = afterBase.indexOf('/');
354 if (firstSlash > 0) {
355 const folderPath = basePath ? `${basePath}/${afterBase.substring(0, firstSlash)}` : afterBase.substring(0, firstSlash);
356 childFolderPaths.add(folderPath);
357 }
358 }
359 }
360
361 /** @type {ContentFolder[]} */
362 const childFolders = [];
363 for (const childPath of Array.from(childFolderPaths).sort()) {
364 const child = await buildFolder(/** @type {string} */ (childPath), breadcrumbsWithHref);
365 if (child) childFolders.push(child);
366 }
367
368 // Load files, read frontmatter from disk to avoid triggering the Vite
369 // module runner during content sync (it closes before lazy imports resolve)
370 /** @type {ContentFile[]} */
371 const files = directFilePaths.map((fullPath) => {
372 const relPath = fullPath.replace('/src/content/', '');
373 const folder = getFolderName(relPath);
374 const slug = cleanPath(relPath.replace(`${folder}/`, ''));
375
376 /** @type {Record<string, any>} */
377 let frontmatter = {};
378 try {
379 const raw = readFileSync(join(process.cwd(), 'src', 'content', relPath), 'utf-8');
380 const match = raw.match(/^---\s*\n([\s\S]*?)\n---/);
381 if (match) frontmatter = /** @type {Record<string, any>} */ (yaml.load(match[1])) ?? {};
382 } catch {}
383
384 return {
385 path: relPath,
386 folder,
387 slug,
388 url: `/${folder}/${slug}`,
389 frontmatter,
390 breadcrumbs: [...breadcrumbsWithHref, {label: frontmatter?.title}]
391 };
392 });
393
394 // allFiles includes hidden files (for routing); files (sidebar) excludes them.
395 const allFilesFlat = [...files.sort(sortContentFiles), ...childFolders.flatMap(f => f.allFiles)];
396
397 return {
398 path: indexRelPath,
399 folder: folderName,
400 slug,
401 url: folderUrl,
402 frontmatter: indexFrontmatter || {},
403 breadcrumbs: folderBreadcrumbs,
404 files: files.filter(f => !f.frontmatter?.hidden).sort(sortContentFiles),
405 folders: childFolders,
406 allFiles: allFilesFlat
407 };
408 };
409
410 const rootPath = path === folderName ? folderName : path;
411 const folder = await buildFolder(rootPath.replace(/^\//, ''));
412
413 if (!folder) {
414 throw new Error(`No index.md found for folder: ${path}`);
415 }
416
417 // Add prev/next links, hidden and soon files are excluded from the nav sequence
418 const navFiles = folder.allFiles.filter(f => !f.frontmatter?.hidden && !f.frontmatter?.soon);
419 for (let i = 0; i < navFiles.length; i++) {
420 if (i > 0) navFiles[i].prev = navFiles[i - 1];
421 if (i < navFiles.length - 1) navFiles[i].next = navFiles[i + 1];
422 }
423
424 return folder;
425 }
426
427 /**
428 * Get a single content file.
429 *
430 * @param {string} path - File path with extension, relative to src/content/
431 * e.g., 'reference/01-attributes/01-hx-get.md' or 'team.yaml'
432 * @returns {Promise<ContentFile | null>} ContentFile or null if not found
433 */
434 export async function getFile(path) {
435 // YAML/JSON data files, read from disk, parse, resolve images
436 if (isDataFile(path)) {
437 try {
438 const diskPath = join(process.cwd(), 'src', 'content', path);
439 const raw = readFileSync(diskPath, 'utf-8');
440 const data = path.endsWith('.json') ? JSON.parse(raw) : yaml.load(raw);
441 return {
442 path,
443 folder: '',
444 slug: '',
445 url: '',
446 frontmatter: /** @type {Record<string, any>} */ (data),
447 breadcrumbs: []
448 };
449 } catch {
450 return null;
451 }
452 }
453
454 // MD/MDX content files, read frontmatter from disk (avoids Vite module runner)
455 const fullPath = `/src/content/${path}`;
456 if (!allPaths.includes(fullPath)) return null;
457
458 /** @type {Record<string, any>} */
459 let frontmatter = {};
460 try {
461 const raw = readFileSync(join(process.cwd(), 'src', 'content', path), 'utf-8');
462 const match = raw.match(/^---\s*\n([\s\S]*?)\n---/);
463 if (match) frontmatter = /** @type {Record<string, any>} */ (yaml.load(match[1])) ?? {};
464 } catch {
465 return null;
466 }
467 const folder = getFolderName(path);
468 const slug = cleanPath(path.replace(`${folder}/`, ''));
469 const fileUrl = `/${folder}/${slug}`;
470
471 // Build breadcrumbs and prev/next from folder tree
472 const rootFolder = await getFolder(folder);
473 /** @type {Breadcrumb[]} */
474 const breadcrumbs = [
475 {label: rootFolder.frontmatter.title, href: rootFolder.url}
476 ];
477
478 const slugParts = slug.split('/');
479 if (slugParts.length > 1) {
480 let currentFolder = rootFolder;
481 for (let i = 0; i < slugParts.length - 1; i++) {
482 const partialSlug = slugParts.slice(0, i + 1).join('/');
483 const subfolder = currentFolder.folders.find(sf => sf.slug === partialSlug);
484 if (subfolder) {
485 breadcrumbs.push({label: subfolder.frontmatter.title, href: subfolder.url});
486 currentFolder = subfolder;
487 }
488 }
489 }
490
491 breadcrumbs.push({label: frontmatter.title});
492
493 const allFiles = rootFolder.allFiles;
494 const fileIndex = allFiles.findIndex(f => f.path === path);
495 const prev = fileIndex > 0 ? allFiles[fileIndex - 1] : undefined;
496 const next = fileIndex < allFiles.length - 1 ? allFiles[fileIndex + 1] : undefined;
497
498 return {
499 path,
500 folder,
501 slug,
502 url: fileUrl,
503 frontmatter,
504 breadcrumbs,
505 prev,
506 next
507 };
508 }
509