#!/usr/bin/env node // Builds the docs site: every page in docs/ becomes site/docs/.html in the // albedo.sh style, next to docs.css, openapi.yaml and the API reference. import { execFileSync } from 'node:child_process'; import { copyFileSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { Marked } from 'marked'; import * as pagefind from 'pagefind'; import { createCssVariablesTheme, createHighlighter } from 'shiki'; const site = dirname(fileURLToPath(import.meta.url)); const root = dirname(site); const source = join(root, 'docs'); const out = join(site, 'docs'); const repo = 'https://tangled.org/okami.mom/albedo/blob/main'; // The sidebar, in order. A page in docs/ missing here fails the build, so none is dropped silently. const pages = [ { file: 'readme.md', out: 'index.html', group: 'guide', label: 'overview' }, { file: 'daemon-lifecycle.md', group: 'guide', label: 'daemon lifecycle' }, { file: 'extensions.md', group: 'guide', label: 'extensions' }, { file: 'client-api.md', group: 'api', label: 'client api' }, { file: 'http-api-design.md', group: 'api', label: 'http api design' }, { file: 'http-api-architecture.md', group: 'api', label: 'api architecture' }, ].map((page) => ({ ...page, out: page.out ?? page.file.replace(/\.md$/, '.html') })); const reference = { label: 'api reference', out: 'api-reference.html' }; const escape = (text) => text.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]); const slug = (text) => text.toLowerCase().trim().replace(/<[^>]+>/g, '').replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-'); // Rewrites a link written for the repository into one that works on the site. function siteHref(href) { const [path, hash] = href.split('#'); if (/^[a-z]+:|^#/.test(href) || !path) return href; const page = pages.find((p) => p.file === path); if (page) return page.out + (hash ? `#${hash}` : ''); if (path === 'api-reference.html' || path === 'openapi.yaml') return href; return `${repo}/${join('docs', path)}${hash ? `#${hash}` : ''}`; } const highlighter = await createHighlighter({ themes: [createCssVariablesTheme({ name: 'madoromi', variablePrefix: '--shiki-' })], langs: ['gleam', 'python', 'json', 'go', 'sh', 'yaml', 'toml'], }); function render(markdown) { const headings = []; const seen = new Map(); let title = ''; const marked = new Marked({ gfm: true, renderer: { heading({ tokens, depth, text }) { const html = this.parser.parseInline(tokens); if (depth === 1 && !title) { title = text; return `

${html}

\n`; } const level = Math.max(depth, 2); let id = slug(text); const count = seen.get(id) ?? 0; seen.set(id, count + 1); if (count) id += `-${count}`; if (level === 2) headings.push({ id, html }); return `${html}\n`; }, code({ text, lang }) { const language = highlighter.getLoadedLanguages().includes(lang) ? lang : 'text'; return highlighter.codeToHtml(text, { lang: language, theme: 'madoromi' }) + '\n'; }, link({ href, title: linkTitle, tokens }) { const target = siteHref(href); const external = /^https?:/.test(target) ? ' rel="noopener"' : ''; const titled = linkTitle ? ` title="${escape(linkTitle)}"` : ''; return `${this.parser.parseInline(tokens)}`; }, table({ header, rows }) { const labels = header.map((cell) => escape(cell.text)); const head = header.map((cell) => `${this.parser.parseInline(cell.tokens)}`).join(''); // Long paths in a cell may wrap after a slash, never inside a word. const cell = (tokens) => this.parser.parseInline(tokens).replace(/([^<]*)<\/code>/g, (_, text) => `${text.replaceAll('/', '/')}`); const body = rows .map((row) => `${row.map((item, i) => `${cell(item.tokens)}`).join('')}`) .join('\n'); return `
${head}${body}
\n`; }, }, }); return { html: marked.parse(markdown), headings, title }; } function nav(current) { const groups = [...new Set(pages.map((page) => page.group))]; const link = (page) => `${page.label}`; const site = groups .map((group) => `

${group}

\n` + pages.filter((page) => page.group === group).map(link).join('')) .join('\n'); return { site: `${site}${reference.label} ↗`, line: pages.map(link).join('') + `${reference.label}`, }; } function toc(headings) { if (headings.length < 2) return { aside: '', line: '' }; const links = headings.map((h) => `${h.html.replace(/<\/?a[^>]*>/g, '')}`); const sentence = links.length === 2 ? links.join(' and ') : `${links.slice(0, -1).join(', ')}, and ${links.at(-1)}`; return { aside: ``, line: `

On this page: ${sentence}.

`, }; } function pager(index) { const [previous, next] = [pages[index - 1], pages[index + 1]]; if (!previous && !next) return ''; const part = (word, page) => (page ? `${word} ${page.label} ` : ''); return `

${part('Previous', previous)}${part('Next', next)}

`; } // Search over the pagefind index, shown as text in place of the page while there is a query. const search = `(()=>{const field=document.querySelector('.search input'),article=document.querySelector('article'),found=document.querySelector('.results');let engine,shown='',timer; const words=(n,one,many)=>n+' '+(n===1?one:many); async function show(query){query=query.trim();if(query===shown)return;shown=query;history.replaceState(null,'',query?'?q='+encodeURIComponent(query):location.pathname); if(!query){article.classList.remove('searching');return} engine??=await import('./pagefind/pagefind.js');const result=await engine.debouncedSearch(query,{},120);if(!result||query!==shown)return; const pages=await Promise.all(result.results.slice(0,8).map((r)=>r.data())); found.innerHTML='

'+(pages.length?words(result.results.length,'page','pages')+' mention '+query.replace(/[&<>]/g,''):'Nothing mentions '+query.replace(/[&<>]/g,'')+'.')+'

'+pages.map((page)=>'
'+page.meta.title+''+(page.sub_results.length?page.sub_results.slice(0,3).map((s)=>''+(s.title===page.meta.title?'':''+s.title+'')+s.excerpt+'').join(''):'

'+page.excerpt+'

')+'
').join(''); article.classList.add('searching')} field.addEventListener('input',()=>show(field.value)); field.addEventListener('keydown',(e)=>{if(e.key==='Escape'){field.value='';show('');field.blur()}}); addEventListener('keydown',(e)=>{if(e.key==='/'&&document.activeElement!==field){e.preventDefault();field.focus()}}); const q=new URLSearchParams(location.search).get('q');if(q){field.value=q;show(q)}})()`; // Marks the section being read in the right-hand list; the page works the same without it. const spy = `const links=[...document.querySelectorAll('.toc a')];if(links.length){const mark=(id)=>links.forEach((a)=>a.classList.toggle('on',a.hash==='#'+id));mark(links[0].hash.slice(1));const watch=new IntersectionObserver((seen)=>seen.forEach((e)=>e.isIntersecting&&mark(e.target.id)),{rootMargin:'0px 0px -70% 0px'});document.querySelectorAll('h2[id]').forEach((h)=>watch.observe(h))}`; function page(entry, index) { const { html, headings, title } = render(readFileSync(join(source, entry.file), 'utf8')); const links = nav(entry); const contents = toc(headings); const body = html.replace(/(<\/h1>\n(?:

[\s\S]*?<\/p>\n)?)/, `$1${contents.line}\n`); return ` ${escape(title)} · albedo docs

albedo docs

${body}${pager(index)}
${contents.aside}
`; } /** Writes every page, the search index, docs.css, openapi.yaml and the API reference into site/docs. */ export async function build() { const unlisted = readdirSync(source).filter((name) => name.endsWith('.md') && !pages.some((page) => page.file === name)); if (unlisted.length) throw new Error(`docs/ pages missing from the sidebar in build-docs.mjs: ${unlisted.join(', ')}`); rmSync(out, { recursive: true, force: true }); mkdirSync(out, { recursive: true }); const { index, errors } = await pagefind.createIndex({ forceLanguage: 'en', includeCharacters: '_' }); if (!index) throw new Error(`pagefind: ${errors.join('; ')}`); for (const [position, entry] of pages.entries()) { const html = page(entry, position); writeFileSync(join(out, entry.out), html); await index.addHTMLFile({ url: `/${entry.out}`, content: html }); } await index.writeFiles({ outputPath: join(out, 'pagefind') }); await pagefind.close(); copyFileSync(join(site, 'docs.css'), join(out, 'docs.css')); copyFileSync(join(source, 'openapi.yaml'), join(out, 'openapi.yaml')); execFileSync('python3', [join(root, 'scripts', 'api-reference.py'), '--output', join(out, reference.out)], { stdio: 'inherit' }); console.log(`built ${pages.length} pages, their search index and the API reference into ${out}`); } if (process.argv[1] === fileURLToPath(import.meta.url)) await build();