|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +import { readFileSync, writeFileSync } from "node:fs" |
| 4 | +import { parse } from "node-html-parser" |
| 5 | +import Viz from "../static/js/viz-global.js" |
| 6 | + |
| 7 | +/* |
| 8 | + * This script post-processes the site as generated via Hugo, replacing the |
| 9 | + * `<pre class="graphviz">` elements with inline `<svg>` ones, pre-rendered |
| 10 | + * via `viz-js`. |
| 11 | + */ |
| 12 | +;(async () => { |
| 13 | + for (const { Path: pathInPublic } of JSON.parse(readFileSync("public/diagram-list.json", "utf-8"))) { |
| 14 | + const path = `public${pathInPublic}.html` |
| 15 | + const contents = readFileSync(path, "utf-8") |
| 16 | + const html = parse(contents) |
| 17 | + const vizImport = html.querySelector('script[src$="viz-global.js"]') |
| 18 | + if (!vizImport) { |
| 19 | + console.error(`No 'viz-global.js' import found in ${path}; skipping`) |
| 20 | + continue |
| 21 | + } |
| 22 | + vizImport.nextElementSibling.remove() // remove the inline script |
| 23 | + vizImport.remove() // remove the import |
| 24 | + |
| 25 | + for (const pre of html.querySelectorAll("pre.graphviz")) { |
| 26 | + const engine = pre.getAttribute("engine") || "dot" |
| 27 | + const svg = (await Viz.instance()).renderString(pre.textContent, { |
| 28 | + format: "svg", |
| 29 | + graphAttributes: { |
| 30 | + bgcolor: "transparent", |
| 31 | + }, |
| 32 | + engine, |
| 33 | + }) |
| 34 | + const dataURL = `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}` |
| 35 | + pre.replaceWith(`<img src="${dataURL}" />`) |
| 36 | + } |
| 37 | + console.log(`Rewriting ${path}`) |
| 38 | + writeFileSync(`${path}`, html.toString()) |
| 39 | + } |
| 40 | +})().catch((e) => { |
| 41 | + console.error(e) |
| 42 | + process.exitCode = 1 |
| 43 | +}) |
0 commit comments