#!/usr/bin/env node // Renders a Markdown doc with Mermaid diagrams to a shareable PDF. // // pnpm docs:pdf docs/security/openwork-architecture.md [output.pdf] // // Uses only dependencies already locked in this repository (`marked` and // `mermaid`, resolved through apps/app) plus an installed Google Chrome or // Chromium for printing. Nothing is downloaded at build time. Set CHROME_PATH // to choose a browser. The default output is `/dist/.pdf`, // which git ignores. import { spawnSync } from "node:child_process" import { createHash } from "node:crypto" import { existsSync } from "node:fs" import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises" import { createRequire } from "node:module" import { tmpdir } from "node:os" import { basename, dirname, extname, join, relative, resolve } from "node:path" import { fileURLToPath, pathToFileURL } from "node:url" const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..") const appRequire = createRequire(join(repoRoot, "apps/app/package.json")) function fail(message) { console.error(`docs:pdf: ${message}`) process.exit(1) } const [inputArg, outputArg] = process.argv.slice(2) if (!inputArg) fail("usage: pnpm docs:pdf [output.pdf]") const input = resolve(process.cwd(), inputArg) if (!existsSync(input)) fail(`not found: ${inputArg}`) const output = outputArg ? resolve(process.cwd(), outputArg) : join(dirname(input), "dist", `${basename(input, extname(input))}.pdf`) function resolvePackageFile(name, file) { try { return join(dirname(appRequire.resolve(`${name}/package.json`)), file) } catch { fail(`cannot find ${name}; run pnpm install first`) } } function findChrome() { const candidates = [ process.env.CHROME_PATH, "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", ] for (const candidate of candidates) if (candidate && existsSync(candidate)) return candidate for (const name of ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]) { const found = spawnSync("which", [name], { encoding: "utf8" }) if (found.status === 0 && found.stdout.trim()) return found.stdout.trim() } fail("Chrome or Chromium not found; set CHROME_PATH") } function escapeHtml(text) { return text.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """) } /** GitHub-style heading anchor, so in-document links work in the PDF too. */ function slug(text) { return text .toLowerCase() .replace(/<[^>]*>/g, "") .replace(/[^\p{L}\p{N}\s-]/gu, "") .trim() .replace(/\s/g, "-") } function gitStamp(file) { const run = (args) => spawnSync("git", args, { cwd: repoRoot, encoding: "utf8" }) const sha = run(["rev-parse", "--short", "HEAD"]).stdout.trim() || "unknown" const path = relative(repoRoot, file) const dirty = run(["status", "--porcelain", "--", path]).stdout.trim() !== "" return { sha, path, dirty } } const { Marked } = await import(pathToFileURL(resolvePackageFile("marked", "lib/marked.esm.js")).href) const mermaidSource = await readFile(resolvePackageFile("mermaid", "dist/mermaid.min.js"), "utf8") const markdown = await readFile(input, "utf8") let diagramCount = 0 /** Only plain web, mail and in-document links survive; anything else (javascript:, data:, file:) renders as text. */ const SAFE_HREF = /^(https?:|mailto:|#)/i const marked = new Marked({ gfm: true, renderer: { code({ text, lang }) { if (lang !== "mermaid") return false diagramCount += 1 return `
${escapeHtml(text)}
\n` }, heading({ tokens, depth, text }) { return `${this.parser.parseInline(tokens)}\n` }, // The doc is rendered in a browser: raw HTML is shown as text, never executed. html({ text }) { return escapeHtml(text) }, link({ href, title, tokens }) { const label = this.parser.parseInline(tokens) if (!SAFE_HREF.test(href.trim())) return label return `${label}` }, image({ text }) { return escapeHtml(text) }, }, }) const body = marked.parse(markdown) const title = markdown.match(/^#\s+(.+)$/m)?.[1] ?? basename(input) const stamp = gitStamp(input) const built = new Date().toISOString().slice(0, 10) const cssString = (text) => `"${text.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, " ")}"` const mermaidScript = mermaidSource.replace(/<\/script/gi, "<\\/script") const layoutScript = ` mermaid.initialize({ startOnLoad: false, securityLevel: "strict", theme: "default", flowchart: { useMaxWidth: true }, sequence: { useMaxWidth: true } }) const isHeading = (node) => /^H[1-3]$/.test(node.tagName) mermaid.run({ querySelector: "pre.mermaid" }) .then(() => { for (const diagram of document.querySelectorAll(".diagram")) { // The heading and lead-in text that introduce this diagram. const lead = [] let node = diagram.previousElementSibling while (node && !node.classList.contains("diagram")) { lead.unshift(node) if (isHeading(node)) break node = node.previousElementSibling } const heading = lead.length && isHeading(lead[0]) ? lead[0] : null const box = diagram.querySelector("svg")?.viewBox?.baseVal if (box && box.width >= box.height * 1.8) { // Very wide diagrams print on their own landscape page, with their heading. diagram.classList.add("landscape") if (heading) diagram.prepend(...lead) } else if (heading && heading.tagName === "H2") { // Every other diagram section starts on a fresh page. heading.classList.add("page-start") } } document.body.dataset.rendered = String(document.querySelectorAll(".diagram svg").length) }) .catch((error) => { document.body.dataset.renderError = String(error && error.message || error) }) ` const scriptHash = (source) => `'sha256-${createHash("sha256").update(source).digest("base64")}'` const csp = `default-src 'none'; script-src ${scriptHash(mermaidScript)} ${scriptHash(layoutScript)}; style-src 'unsafe-inline'; img-src data:; font-src data:` const footer = `font: 7.5pt -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; color: #94a3b8;` const html = ` ${escapeHtml(title)}
${escapeHtml(stamp.path)} · commit ${escapeHtml(stamp.sha)}${stamp.dirty ? " + uncommitted changes" : ""} · built ${built}
${body} ` const chrome = findChrome() const work = await mkdtemp(join(tmpdir(), "docs-pdf-")) try { const htmlFile = join(work, "doc.html") await writeFile(htmlFile, html) const chromeArgs = [ "--headless=new", "--disable-gpu", "--no-first-run", "--no-default-browser-check", `--user-data-dir=${join(work, "profile")}`, "--virtual-time-budget=20000", ] const url = pathToFileURL(htmlFile).href // Check every diagram rendered before printing. const dom = spawnSync(chrome, [...chromeArgs, "--dump-dom", url], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }) if (dom.status !== 0) fail(`Chrome failed: ${dom.stderr.trim().split("\n").pop()}`) const renderError = dom.stdout.match(/data-render-error="([^"]*)"/)?.[1] if (renderError) fail(`Mermaid error: ${renderError}`) const rendered = Number(dom.stdout.match(/data-rendered="(\d+)"/)?.[1] ?? "0") if (rendered !== diagramCount) fail(`rendered ${rendered} of ${diagramCount} diagrams`) await mkdir(dirname(output), { recursive: true }) const pdf = spawnSync(chrome, [...chromeArgs, "--no-pdf-header-footer", `--print-to-pdf=${output}`, url], { encoding: "utf8" }) if (pdf.status !== 0 || !existsSync(output)) fail(`Chrome could not print the PDF: ${pdf.stderr.trim().split("\n").pop()}`) console.log(`docs:pdf: ${relative(process.cwd(), output)} (${rendered} diagrams, commit ${stamp.sha}${stamp.dirty ? "+dirty" : ""})`) } finally { await rm(work, { recursive: true, force: true }) }