import { Marked } from "marked"; export interface DocLink { readonly slug: string; readonly title: string; } export interface DocSection { readonly title: string; readonly pages: readonly DocLink[]; } export interface DocHeading { readonly id: string; readonly text: string; } export interface DocPage { readonly slug: string; readonly title: string; readonly summary: string; readonly html: string; readonly headings: readonly DocHeading[]; } const SECTIONS: readonly { title: string; slugs: readonly string[] }[] = [ { title: "Get started", slugs: ["overview", "quickstart", "concepts"] }, { title: "Guides", slugs: ["git", "connect-an-agent", "work-with-agents", "hosted-agents", "pull-requests", "tasks", "ci", "organizations"] }, { title: "Reference", slugs: ["decision-records", "ci-config", "protocol", "cli", "permissions-and-limits", "glossary"] }, ]; const SOURCES = import.meta.glob("../docs/*.md", { query: "?raw", import: "default", eager: true }); function slugify(text: string): string { return text.toLowerCase().replace(/<[^>]+>|`/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); } function parse(slug: string, source: string): DocPage { const [, title = slug, rest = ""] = /^# (.+)\n+([\s\S]*)$/.exec(source) ?? []; const summary = rest.split("\n\n")[0]?.replace(/\n/g, " ").replace(/[`*]|\[([^\]]+)\]\([^)]+\)/g, "$1") ?? ""; const headings: DocHeading[] = []; const marked = new Marked({ gfm: true, renderer: { heading({ tokens, depth, text }) { const id = slugify(text); if (depth === 2) headings.push({ id, text: text.replace(/`/g, "") }); return `${this.parser.parseInline(tokens)}\n`; }, }, }); const html = marked.parse(rest, { async: false }); return { slug, title, summary, html, headings }; } const PAGES = new Map( Object.entries(SOURCES).map(([path, source]) => { const slug = path.slice(path.lastIndexOf("/") + 1, -".md".length); return [slug, parse(slug, source)] as const; }), ); export const DOC_SECTIONS: readonly DocSection[] = SECTIONS.map(({ title, slugs }) => ({ title, pages: slugs.map((slug) => { const page = PAGES.get(slug); if (!page) throw new Error(`The docs page ${slug}.md is missing.`); return { slug, title: page.title }; }), })); const ORDER = DOC_SECTIONS.flatMap((section) => section.pages); export function docPage(slug: string): { page: DocPage; previous: DocLink | null; next: DocLink | null } | null { const page = PAGES.get(slug); const index = ORDER.findIndex((link) => link.slug === slug); if (!page || index < 0) return null; return { page, previous: ORDER[index - 1] ?? null, next: ORDER[index + 1] ?? null }; }