Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189#!/usr/bin/env node// Builds the docs site: every page in docs/ becomes site/docs/<name>.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 `<h1>${html}</h1>\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 `<h${level} id="${id}"><a class="anchor" href="#${id}" aria-hidden="true" data-pagefind-ignore>#</a>${html}</h${level}>\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 `<a href="${escape(target)}"${titled}${external}>${this.parser.parseInline(tokens)}</a>`; }, table({ header, rows }) { const labels = header.map((cell) => escape(cell.text)); const head = header.map((cell) => `<th>${this.parser.parseInline(cell.tokens)}</th>`).join(''); // Long paths in a cell may wrap after a slash, never inside a word. const cell = (tokens) => this.parser.parseInline(tokens).replace(/<code>([^<]*)<\/code>/g, (_, text) => `<code>${text.replaceAll('/', '/<wbr>')}</code>`); const body = rows .map((row) => `<tr>${row.map((item, i) => `<td data-label="${labels[i]}">${cell(item.tokens)}</td>`).join('')}</tr>`) .join('\n'); return `<div class="table"><table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table></div>\n`; }, }, }); return { html: marked.parse(markdown), headings, title };}
function nav(current) { const groups = [...new Set(pages.map((page) => page.group))]; const link = (page) => `<a href="${page.out}"${page === current ? ' aria-current="page"' : ''}>${page.label}</a>`; const site = groups .map((group) => `<p class="grp">${group}</p>\n` + pages.filter((page) => page.group === group).map(link).join('')) .join('\n'); return { site: `${site}<a href="${reference.out}">${reference.label} <i>↗</i></a>`, line: pages.map(link).join('') + `<a href="${reference.out}">${reference.label}</a>`, };}
function toc(headings) { if (headings.length < 2) return { aside: '', line: '' }; const links = headings.map((h) => `<a href="#${h.id}">${h.html.replace(/<\/?a[^>]*>/g, '')}</a>`); const sentence = links.length === 2 ? links.join(' and ') : `${links.slice(0, -1).join(', ')}, and ${links.at(-1)}`; return { aside: `<aside class="toc"><p class="grp">on this page</p>${links.join('')}</aside>`, line: `<p class="tocline" data-pagefind-ignore>On this page: ${sentence}.</p>`, };}
function pager(index) { const [previous, next] = [pages[index - 1], pages[index + 1]]; if (!previous && !next) return ''; const part = (word, page) => (page ? `<span>${word}</span> <a href="${page.out}">${page.label}</a> ` : ''); return `<p class="pager" data-pagefind-ignore>${part('Previous', previous)}${part('Next', next)}</p>`;}
// 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='<p class="count">'+(pages.length?words(result.results.length,'page','pages')+' mention '+query.replace(/[&<>]/g,''):'Nothing mentions '+query.replace(/[&<>]/g,'')+'.')+'</p>'+pages.map((page)=>'<div class="hit"><a class="title" href="'+page.url+'">'+page.meta.title+'</a>'+(page.sub_results.length?page.sub_results.slice(0,3).map((s)=>'<a class="part" href="'+s.url+'">'+(s.title===page.meta.title?'':'<span>'+s.title+'</span>')+s.excerpt+'</a>').join(''):'<p class="part">'+page.excerpt+'</p>')+'</div>').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(?:<p>[\s\S]*?<\/p>\n)?)/, `$1${contents.line}\n`); return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(title)} · albedo docs</title><meta name="theme-color" content="#1c1e2a"><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Hanken+Grotesk:wght@400;500;600&display=swap" rel="stylesheet"><link rel="stylesheet" href="docs.css"><script>document.documentElement.classList.add('js')</script></head><body><div class="page"><header class="top"><p class="mark"><a href="../">albedo</a> <a href="index.html">docs</a></p><nav class="navline">${links.line}</nav><label class="search"><input type="search" placeholder="search" aria-label="search the docs" autocomplete="off" spellcheck="false"><kbd>/</kbd></label></header><nav class="site" aria-label="docs">${links.site}</nav><article data-pagefind-body><div class="results" aria-live="polite" data-pagefind-ignore></div>${body}${pager(index)}</article>${contents.aside}</div><script>${spy}</script><script>${search}</script></body></html>`;}
/** 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();