feat(webui): render Mermaid diagrams with Pele (#6302)

* feat(webui): render Mermaid diagrams with Pele

* fix(webui): reserve diagram replacement capacity

* fix(webui): prebundle lazy diagram worker dependencies

* fix(webui): account diagram capacity by encoded size

* fix(webui): use shared hover hints for diagram actions

* docs(webui): focus diagram guide on usage
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-19 17:16:20 +08:00
1 parent 0f3b47bc3a
commit f57018aa7f
40 files changed
+2335 -1458

No files matched your search

@@ -0,0 +1,27 @@
import { Component, lazy, Suspense, useContext, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { CodeBlock } from "@/components/CodeBlock";
import { MarkdownCodeContext } from "./context";
const MermaidBlock = lazy(() => import("./MermaidBlock"));
class DiagramBoundary extends Component<{ children: ReactNode; fallback: ReactNode }, { failed: boolean }> {
state = { failed: false };
static getDerivedStateFromError() { return { failed: true }; }
render() { return this.state.failed ? this.props.fallback : this.props.children; }
}
export function MarkdownCodeBlock({ code, language }: { code: string; language?: string }) {
const { t } = useTranslation();
const { streaming, highlight } = useContext(MarkdownCodeContext);
const source = <CodeBlock language={language || "text"} code={code} className="my-3" highlight={highlight} showLineNumbers={code.includes("\n")} />;
if (language?.toLowerCase() !== "mermaid") return source;
const preparing = <div aria-busy={streaming}>
<p className="my-1 text-xs text-muted-foreground" role="status">{t("diagram.preparing")}</p>{source}
</div>;
if (streaming) return preparing;
return <DiagramBoundary key={code} fallback={<><p className="text-xs text-muted-foreground" role="status">{t("diagram.errors.load")}</p>{source}</>}>
<Suspense fallback={preparing}><MermaidBlock source={code} /></Suspense>
</DiagramBoundary>;
}
@@ -0,0 +1,148 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { Check, Copy, Maximize2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { CodeBlock } from "@/components/CodeBlock";
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { HoverHint } from "@/components/ui/hover-hint";
import { ImageViewport } from "@/components/ui/image-viewport";
import { copyTextToClipboard } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
import { useDiagramScope } from "./context";
import { requestDiagram, type DiagramPalette, type DiagramRequest, type DiagramState } from "./runtime";
import type { DiagramInput } from "./types";
function readPalette(element: HTMLElement): DiagramPalette {
const style = getComputedStyle(element);
const color = (token: string) => `hsl(${style.getPropertyValue(token).trim()})`;
return {
"--pele-bg": color("--background"), "--pele-fg": color("--foreground"),
"--pele-muted": color("--muted-foreground"), "--pele-line": color("--foreground"),
"--pele-surface": color("--muted"), "--pele-surface-alt": color("--secondary"),
"--pele-border": color("--border"), "--pele-accent": color("--primary"),
"--pele-critical": color("--destructive"),
};
}
export default function MermaidBlock({ source }: { source: string }) {
const { t } = useTranslation();
const scope = useDiagramScope();
const container = useRef<HTMLDivElement>(null);
const mono = useRef<HTMLSpanElement>(null);
const request = useRef<DiagramRequest | null>(null);
const palette = useRef<DiagramPalette>({});
const visible = useRef(false);
const height = useRef(0);
const [input, setInput] = useState<Omit<DiagramInput, "source"> | null>(null);
const [state, setState] = useState<DiagramState>({ kind: "waiting" });
const [view, setView] = useState<"diagram" | "source">("diagram");
const [open, setOpen] = useState(false);
const [copied, setCopied] = useState(false);
const copyTimer = useRef<ReturnType<typeof setTimeout>>();
const demand = useRef({ view, open });
demand.current = { view, open };
const updateDemand = useCallback(() => request.current?.setDemand(document.hidden || demand.current.view === "source"
? "none" : demand.current.open ? "dialog" : visible.current ? "visible" : "none"), []);
useEffect(() => {
const element = container.current;
if (!element) return;
let active = true;
let frame = 0;
const measure = () => {
if (!active) return;
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
const width = Math.floor(element.clientWidth);
if (width <= 0) return;
const style = getComputedStyle(element);
const next = { width, fonts: { sans: style.fontFamily, mono: getComputedStyle(mono.current!).fontFamily, size: 16 } };
// The open viewer fits its existing image; defer layout changes until it closes.
if (!demand.current.open) setInput((previous) => JSON.stringify(previous) === JSON.stringify(next) ? previous : next);
palette.current = readPalette(element);
request.current?.setPalette(palette.current);
});
};
const resize = new ResizeObserver(measure);
resize.observe(element);
const intersection = new IntersectionObserver(([entry]) => {
visible.current = entry.isIntersecting;
updateDemand();
});
intersection.observe(element);
const appearance = new MutationObserver(measure);
appearance.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style"] });
document.addEventListener("visibilitychange", updateDemand);
void document.fonts.ready.then(measure);
measure();
return () => {
active = false;
resize.disconnect(); intersection.disconnect(); appearance.disconnect();
document.removeEventListener("visibilitychange", updateDemand);
cancelAnimationFrame(frame);
};
}, [updateDemand, open]);
useLayoutEffect(() => { setOpen(false); }, [source, scope]);
useLayoutEffect(() => {
setState({ kind: "waiting" });
if (!input) return;
const controller = new AbortController();
const handle = requestDiagram({ ...input, source }, controller.signal, (next) => {
if (controller.signal.aborted) return;
if (next.kind === "ready") height.current = Math.min(448, next.image.height * Math.min(1, input.width / next.image.width));
setState(next);
});
request.current = handle;
handle.setPalette(palette.current);
updateDemand();
return () => { controller.abort(); request.current = null; };
}, [source, scope, input, updateDemand]);
useEffect(() => { updateDemand(); }, [view, open, updateDemand]);
useEffect(() => () => clearTimeout(copyTimer.current), []);
const copy = async () => {
if (!await copyTextToClipboard(source)) return;
setCopied(true);
clearTimeout(copyTimer.current);
copyTimer.current = setTimeout(() => setCopied(false), 2000);
};
const buttonClass = "rounded px-2 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
const showSource = view === "source" || state.kind === "failed";
const image = state.kind === "ready" ? state.image : null;
return <div ref={container} className="not-prose my-3 min-w-0 overflow-hidden rounded-lg border border-border/60" data-testid="mermaid-block">
<span ref={mono} className="hidden font-mono" aria-hidden />
<div className="flex flex-wrap items-center gap-1 border-b border-border/60 px-2 py-1">
<span className="mr-auto px-1 text-xs text-muted-foreground">Mermaid</span>
<button type="button" aria-pressed={view === "diagram"} className={cn(buttonClass, view === "diagram" && "bg-muted text-foreground")} onClick={() => setView("diagram")}>{t("diagram.graph")}</button>
<button type="button" aria-pressed={view === "source"} className={cn(buttonClass, view === "source" && "bg-muted text-foreground")} onClick={() => setView("source")}>{t("diagram.source")}</button>
<HoverHint content={t("diagram.copy")}>
<button type="button" className={buttonClass} aria-label={t("diagram.copy")} onClick={() => void copy()}>
{copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
</button>
</HoverHint>
<Dialog open={open && !!image} onOpenChange={setOpen}>
<HoverHint content={t("diagram.enlarge")}>
<DialogTrigger asChild><button type="button" className={buttonClass} aria-label={t("diagram.enlarge")} disabled={!image}><Maximize2 className="h-3.5 w-3.5" /></button></DialogTrigger>
</HoverHint>
<DialogContent className="h-[85dvh] max-w-[min(96vw,90rem)] gap-0 overflow-hidden p-3 sm:p-4" aria-describedby={undefined}>
<DialogTitle className="sr-only">{t("diagram.title")}</DialogTitle>
{image && <div className="flex h-full min-h-0 flex-col gap-2 pt-6"><ImageViewport src={image.url} alt={image.label || t("diagram.title")} className="flex-1" /></div>}
</DialogContent>
</Dialog>
</div>
{state.kind === "failed" && <div className="flex items-center gap-2 px-3 py-2 text-xs text-muted-foreground" role="status">
<span>{t(`diagram.errors.${state.reason}`)}</span>
{["load", "worker", "deadline", "image"].includes(state.reason) && <button type="button" className={buttonClass} onClick={() => request.current?.retry()}>{t("common.retry")}</button>}
</div>}
{showSource ? <CodeBlock language="mermaid" code={source} chrome="none" highlight={false} showLineNumbers={source.includes("\n")} />
: image ? <div className="flex justify-center p-3"><img src={image.url} alt={image.label || t("diagram.title")} width={image.width} height={image.height} className="max-h-[28rem] max-w-full object-contain" /></div>
: <div className="px-3 py-2" style={{ minHeight: height.current || undefined }}>
<p className="m-0 py-1 text-xs text-muted-foreground" role="status">{t("diagram.preparing")}</p>
{!height.current && <CodeBlock language="mermaid" code={source} chrome="none" highlight={false} />}
</div>}
</div>;
}
@@ -0,0 +1,14 @@
import { createContext, useContext, useMemo, type ReactNode } from "react";
export const MarkdownCodeContext = createContext({ streaming: false, highlight: true });
const ScopeContext = createContext<object | null>(null);
// Context invalidates resource effects even through memoized Markdown fences.
export function DiagramScope({ identity, children }: { identity: string | null; children: ReactNode }) {
const scope = useMemo(() => ({ identity }), [identity]);
return <ScopeContext.Provider value={scope}>{children}</ScopeContext.Provider>;
}
export function useDiagramScope() {
return useContext(ScopeContext);
}
@@ -0,0 +1,42 @@
import { detectType, load, render, PeleError } from "pele/lazy";
import { canvasTextMeasurer } from "./render";
import { diagramImageTemplate, DiagramImageError } from "./svg-image";
import {
MAX_DIMENSION, OUTPUT_LIMIT, SOURCE_LIMIT,
type DiagramInput, type DiagramReply,
} from "./types";
self.onmessage = async (event: MessageEvent<DiagramInput>) => {
// One attempt per Worker. The parent owns watchdogs, termination, URLs and revisions.
self.onmessage = null;
const reply = (message: DiagramReply) => self.postMessage(message);
let started = false;
try {
const input = event.data;
if (input.source.length > SOURCE_LIMIT || !Number.isFinite(input.width)
|| input.width <= 0 || input.width > MAX_DIMENSION) throw new DiagramImageError("limit");
// detectType preprocesses source config synchronously. The parent's loading
// watchdog is already active here; it also covers all lazy module loading.
const type = detectType(input.source);
if (!await load(type)) throw new DiagramImageError("unsupported");
const measurer = canvasTextMeasurer(input.fonts);
reply({ kind: "started" });
started = true;
const result = render(input.source, {
measurer, fontFamily: input.fonts.sans, fontFamilyMono: input.fonts.mono,
fontSize: input.fonts.size, maxWidth: input.width, responsive: false,
links: false, images: false, limit: SOURCE_LIMIT, outputLimit: OUTPUT_LIMIT,
maxEdges: 500,
});
const template = diagramImageTemplate(result.svg, input.fonts);
if (template.width !== result.width || template.height !== result.height) throw new DiagramImageError("policy");
reply({ kind: "image", template });
} catch (error) {
if (error instanceof DiagramImageError) reply({ kind: "failed", reason: error.reason });
else if (error instanceof PeleError) reply({
kind: "failed", reason: error.code === "limit" ? "limit"
: error.code === "unsupported-diagram" ? "unsupported" : "syntax",
});
else reply({ kind: "failed", reason: started ? "worker" : "load" });
}
};
@@ -0,0 +1,29 @@
import { DiagramImageError } from "./svg-image";
import type { DiagramInput } from "./types";
// Pele's public TextMeasurer contract; the engine import stays in the Worker entry.
export function canvasTextMeasurer(fonts: DiagramInput["fonts"]): {
width(text: string, size: number, style: number): number;
} {
let context: OffscreenCanvasRenderingContext2D | null = null;
try {
if (typeof OffscreenCanvas !== "undefined") context = new OffscreenCanvas(1, 1).getContext("2d");
} catch { /* Capability failure, never Pele's approximate metrics fallback. */ }
if (!context) throw new DiagramImageError("capability");
const canvas = context;
return {
width(text, size, style) {
if (!Number.isFinite(size) || size <= 0 || size > 200 || (style & ~7) !== 0) {
throw new DiagramImageError("unsupported");
}
const font = `${style & 2 ? "italic " : ""}${style & 1 ? "bold " : ""}${size}px ${style & 4 ? fonts.mono : fonts.sans}`;
// Reset first so an invalid canvas font cannot reuse the preceding measurement.
canvas.font = "1px serif";
canvas.font = font;
if (canvas.font === "1px serif") throw new DiagramImageError("capability");
const width = canvas.measureText(text).width;
if (!Number.isFinite(width) || width < 0) throw new DiagramImageError("capability");
return width;
},
};
}
@@ -0,0 +1,311 @@
import { MAX_DIMENSION, MAX_PIXELS, OUTPUT_LIMIT, SOURCE_LIMIT } from "./types";
import type { DiagramFailure, DiagramInput, DiagramTemplate } from "./types";
export interface DiagramImage {
url: string;
width: number;
height: number;
label: string;
}
export type DiagramState = { kind: "waiting" | "rendering" }
| { kind: "ready"; image: DiagramImage }
| { kind: "failed"; reason: DiagramFailure };
export type DiagramPalette = Readonly<Record<string, string>>;
export interface DiagramRequest {
setDemand(demand: "none" | "visible" | "dialog"): void;
setPalette(palette: DiagramPalette): void;
retry(): void;
dispose(): void;
}
const RUNNING_LIMIT = 2;
const QUEUE_LIMIT = 4;
const BYTE_LIMIT = 8 * OUTPUT_LIMIT;
const PIXEL_LIMIT = 32_000_000;
const PALETTE_LIMIT = 4096;
// Reserve one largest replacement inside the totals so retained images can always be recolored.
const ADMISSION_BYTE_LIMIT = BYTE_LIMIT - OUTPUT_LIMIT;
const ADMISSION_PIXEL_LIMIT = PIXEL_LIMIT - MAX_PIXELS;
const tasks = new Set<Task>();
const queue: Task[] = [];
let capacityWakePending = false;
let running = 0;
let retainedBytes = 0;
let retainedPixels = 0;
function pump() {
queue.length = 0;
// Prioritize before bounding admission, including a viewer opened behind a full queue.
for (const demand of ["dialog", "visible"] as const) {
for (const task of tasks) {
if (queue.length >= QUEUE_LIMIT) break;
if (task.eligible && task.demand === demand) queue.push(task);
}
}
while (running < RUNNING_LIMIT && queue.length) {
const task = queue.shift()!;
if (task.eligible) task.run();
}
}
function capacityChanged() {
if (capacityWakePending) return;
capacityWakePending = true;
queueMicrotask(() => {
capacityWakePending = false;
for (const task of tasks) task.resumeCapacity();
pump();
});
}
function imageTemplate(value: unknown): value is DiagramTemplate {
if (!value || typeof value !== "object") return false;
const template = value as Partial<DiagramTemplate>;
return typeof template.content === "string" && template.content.length <= OUTPUT_LIMIT
&& typeof template.style === "string" && template.style.length <= 4096
&& typeof template.label === "string" && template.label.length <= 4096
&& typeof template.width === "number" && Number.isFinite(template.width)
&& typeof template.height === "number" && Number.isFinite(template.height)
&& template.width > 0 && template.width <= MAX_DIMENSION
&& template.height > 0 && template.height <= MAX_DIMENSION
&& template.width * template.height <= MAX_PIXELS;
}
const failures = new Set<DiagramFailure>(["syntax", "unsupported", "policy", "limit", "load", "deadline", "worker", "image", "capability"]);
const escapeAttribute = (value: string) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
function paletteStyle(palette: DiagramPalette): string {
return Object.entries(palette).map(([key, value]) => {
if (!/^--pele-(?:bg|fg|muted|line|surface|surface-alt|border|accent|critical|series-[1-8])$/.test(key)
|| !/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\([\d\s%,./+-]+\))$/i.test(value)) {
throw new Error("Invalid diagram palette");
}
return `${key}:${value}`;
}).join(";");
}
class Task implements DiagramRequest {
demand: "none" | "visible" | "dialog" = "none";
private worker: Worker | null = null;
private timer: ReturnType<typeof setTimeout> | undefined;
private disposed = false;
private failed = false;
private capacityBlocked = false;
private template: DiagramTemplate | null = null;
private templateBytes = 0;
private asset: { image: DiagramImage; release: () => void } | null = null;
private decoding: (() => void) | null = null;
private attempt = 0;
private palette: DiagramPalette = {};
constructor(private input: DiagramInput, private signal: AbortSignal, private publish: (state: DiagramState) => void) {
tasks.add(this);
signal.addEventListener("abort", this.dispose, { once: true });
}
get eligible() {
return !this.disposed && this.demand !== "none" && !this.failed && !this.capacityBlocked
&& !this.worker && !this.template && !this.decoding;
}
setDemand(demand: "none" | "visible" | "dialog") {
if (this.disposed || demand === this.demand) return;
this.demand = demand;
if (demand === "none") {
this.capacityBlocked = false;
this.cancel();
this.clearTemplate();
this.asset?.release();
this.asset = null;
if (!this.failed) this.publish({ kind: "waiting" });
}
pump();
}
setPalette(palette: DiagramPalette) {
if (this.disposed || JSON.stringify(palette) === JSON.stringify(this.palette)) return;
this.palette = palette;
if (this.template && !this.failed) this.decode();
}
retry() {
if (this.disposed || !this.failed) return;
this.failed = false;
this.clearTemplate();
this.publish({ kind: "waiting" });
pump();
}
private stopWorker() {
clearTimeout(this.timer);
if (this.worker) {
this.worker.onmessage = null;
this.worker.onerror = null;
this.worker.onmessageerror = null;
this.worker.terminate();
this.worker = null;
running--;
}
}
private cancel() {
this.attempt++;
const index = queue.indexOf(this);
if (index !== -1) queue.splice(index, 1);
this.stopWorker();
this.decoding?.();
this.decoding = null;
}
private clearTemplate() {
if (this.templateBytes) {
retainedBytes -= this.templateBytes;
capacityChanged();
}
this.templateBytes = 0;
this.template = null;
}
private waitForCapacity() {
this.capacityBlocked = true;
if (!this.asset) this.publish({ kind: "waiting" });
}
resumeCapacity() {
if (!this.capacityBlocked || this.disposed) return;
this.capacityBlocked = false;
if (this.template && this.demand !== "none" && !this.failed) this.decode();
}
private fail(reason: DiagramFailure) {
this.cancel();
this.failed = true;
this.clearTemplate();
this.asset?.release();
this.asset = null;
this.publish({ kind: "failed", reason });
queueMicrotask(pump);
}
run() {
if (this.input.source.length > SOURCE_LIMIT) { this.fail("limit"); return; }
if (typeof Worker === "undefined") { this.fail("capability"); return; }
this.publish({ kind: "rendering" });
try {
const worker = new Worker(new URL("./pele.worker.ts", import.meta.url), { type: "module" });
this.worker = worker;
running++;
const attempt = ++this.attempt;
this.timer = setTimeout(() => this.fail("load"), 10_000);
worker.onmessage = ({ data }: MessageEvent<unknown>) => {
if (this.disposed || this.worker !== worker || attempt !== this.attempt) return;
if (!data || typeof data !== "object" || !("kind" in data)) { this.fail("worker"); return; }
if (data.kind === "started") {
clearTimeout(this.timer);
this.timer = setTimeout(() => this.fail("deadline"), 2000);
} else if (data.kind === "image" && "template" in data && imageTemplate(data.template)) {
this.stopWorker();
const bytes = new Blob([data.template.content, data.template.style]).size;
if (bytes > OUTPUT_LIMIT) { this.fail("limit"); return; }
if (retainedBytes + bytes > ADMISSION_BYTE_LIMIT) { this.waitForCapacity(); pump(); return; }
this.template = data.template;
this.templateBytes = bytes;
retainedBytes += bytes;
this.decode();
pump();
} else if (data.kind === "failed" && "reason" in data && failures.has(data.reason as DiagramFailure)) {
this.fail(data.reason as DiagramFailure);
} else this.fail("worker");
};
worker.onerror = worker.onmessageerror = () => this.fail("worker");
worker.postMessage(this.input);
} catch { this.fail("worker"); }
}
private decode() {
const template = this.template;
if (!template || this.disposed || this.demand === "none") return;
this.decoding?.();
const attempt = ++this.attempt;
let blob: Blob;
let paletteBytes: number;
try {
const palette = paletteStyle(this.palette);
paletteBytes = new Blob([palette]).size;
if (paletteBytes > PALETTE_LIMIT) { this.fail("limit"); return; }
const style = escapeAttribute(`${template.style};${palette}`);
blob = new Blob([`<svg xmlns="http://www.w3.org/2000/svg" width="${template.width}" height="${template.height}" viewBox="0 0 ${template.width} ${template.height}" fill="var(--_fg)" style="${style}">${template.content}</svg>`], { type: "image/svg+xml" });
} catch { this.fail("image"); return; }
const pixels = template.width * template.height;
// Only the bounded palette can vary for this template. Its envelope stays constant
// across themes, preserving replacement headroom without charging small SVGs 1 MiB.
const reservedBytes = Math.min(blob.size - paletteBytes + PALETTE_LIMIT, OUTPUT_LIMIT);
const byteLimit = this.asset ? BYTE_LIMIT : ADMISSION_BYTE_LIMIT;
const pixelLimit = this.asset ? PIXEL_LIMIT : ADMISSION_PIXEL_LIMIT;
if (blob.size > OUTPUT_LIMIT) { this.fail("limit"); return; }
if (retainedBytes + reservedBytes > byteLimit || retainedPixels + pixels > pixelLimit) {
this.waitForCapacity(); return;
}
this.capacityBlocked = false;
retainedBytes += reservedBytes;
retainedPixels += pixels;
let url: string;
try { url = URL.createObjectURL(blob); }
catch {
retainedBytes -= reservedBytes;
retainedPixels -= pixels;
this.fail("image"); return;
}
let released = false;
const release = () => {
if (released) return;
released = true;
URL.revokeObjectURL(url);
retainedBytes -= reservedBytes;
retainedPixels -= pixels;
capacityChanged();
};
const image = new Image();
image.decoding = "async";
const cleanup = () => {
clearTimeout(timer);
image.onload = image.onerror = null;
};
const finish = () => {
if (this.disposed || attempt !== this.attempt || this.demand === "none") { cleanup(); release(); return; }
cleanup();
this.decoding = null;
const previous = this.asset;
this.asset = { image: { url, width: template.width, height: template.height, label: template.label }, release };
this.publish({ kind: "ready", image: this.asset.image });
previous?.release();
};
const timer = setTimeout(() => this.fail("image"), 5000);
this.decoding = () => { cleanup(); image.removeAttribute("src"); release(); };
image.onerror = () => this.fail("image");
image.onload = () => {
if (typeof image.decode === "function") void image.decode().then(finish, () => {
if (attempt === this.attempt && !this.disposed) this.fail("image");
});
else finish();
};
image.src = url;
}
dispose = () => {
if (this.disposed) return;
this.disposed = true;
this.signal.removeEventListener("abort", this.dispose);
tasks.delete(this);
this.cancel();
this.asset?.release();
this.asset = null;
this.clearTemplate();
pump();
};
}
export function requestDiagram(input: DiagramInput, signal: AbortSignal, publish: (state: DiagramState) => void): DiagramRequest {
const task = new Task(input, signal, publish);
if (signal.aborted) task.dispose();
return task;
}
@@ -0,0 +1,342 @@
// Worker-only policy for Pele 1.6 image documents. This is NOT an inline-SVG sanitizer.
import { SaxesParser } from "saxes";
import type * as CssTree from "css-tree";
// css-tree publishes these split entry points, but @types/css-tree declares only the barrel.
// @ts-expect-error No declaration for the public parser entry point.
import parse from "css-tree/parser";
// @ts-expect-error No declaration for the public walker entry point.
import walk from "css-tree/walker";
// @ts-expect-error No declaration for the public generator entry point.
import generate from "css-tree/generator";
import {
MAX_DIMENSION, MAX_PIXELS, OUTPUT_LIMIT,
type DiagramFailure, type DiagramInput, type DiagramTemplate,
} from "./types";
const parseCss: typeof CssTree.parse = parse;
const walkCss: typeof CssTree.walk = walk;
const generateCss: typeof CssTree.generate = generate;
const SVG_NS = "http://www.w3.org/2000/svg";
const XML_NS = "http://www.w3.org/XML/1998/namespace";
const XMLNS_NS = "http://www.w3.org/2000/xmlns/";
const ELEMENT_LIMIT = 10_000;
const encoder = new TextEncoder();
export class DiagramImageError extends Error {
constructor(readonly reason: DiagramFailure) {
super(`Diagram ${reason}`);
}
}
function fail(reason: DiagramFailure = "policy"): never {
throw new DiagramImageError(reason);
}
// Reviewed against the published 1.6.0 string renderer, including nested icon geometry.
// Local marker/clip structures are accepted, but never <use>, links, images or paint servers.
const ELEMENTS = new Set([
"svg", "g", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon",
"text", "tspan", "title", "desc", "defs", "marker", "clipPath",
]);
const ATTRIBUTES = new Set([
"id", "class", "data-id", "data-icon", "role", "aria-hidden", "aria-roledescription",
"aria-labelledby", "aria-describedby", "style", "viewBox", "preserveAspectRatio",
"x", "y", "x1", "x2", "y1", "y2", "cx", "cy", "r", "rx", "ry", "width", "height",
"dx", "dy", "d", "points", "transform", "pathLength", "markerWidth", "markerHeight",
"refX", "refY", "orient", "markerUnits", "clipPathUnits",
]);
const NUMERIC_ATTRIBUTES = new Set([
"x", "y", "x1", "x2", "y1", "y2", "cx", "cy", "r", "rx", "ry", "width", "height",
"dx", "dy", "pathLength", "markerWidth", "markerHeight", "refX", "refY",
]);
const DRAWING_PROPERTIES = new Set([
"fill", "fill-opacity", "fill-rule", "stroke", "stroke-width", "stroke-opacity",
"stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
"stroke-miterlimit", "opacity", "color", "rx", "ry", "text-anchor", "text-decoration",
"dominant-baseline", "alignment-baseline", "visibility", "display", "vector-effect",
"marker-start", "marker-mid", "marker-end", "clip-path", "clip-rule",
]);
const TYPOGRAPHY_PROPERTIES = new Set([
"font", "font-family", "font-size", "font-weight", "font-style", "letter-spacing",
"word-spacing", "text-transform", "direction",
]);
const ROOT_ALIASES: Readonly<Record<string, string>> = {
"--_bg": "var(--pele-bg,#fff)", "--_fg": "var(--pele-fg,#1f1f1f)",
"--_m": "var(--pele-muted,#6e6e6e)", "--_l": "var(--pele-line,#1f1f1f)",
"--_s": "var(--pele-surface,#f3f3f3)", "--_a": "var(--pele-surface-alt,#e6e6e6)",
"--_b": "var(--pele-border,#8a8a8a)", "--_c": "var(--pele-accent,#5b7bd5)",
"--_r": "var(--pele-radius,4px)", "--_tw": "var(--pele-title-weight,bold)",
"--_hw": "var(--pele-heading-weight,bold)", "--_w": "var(--pele-bold-weight,bold)",
};
const VARIABLES = new Set([
...Object.keys(ROOT_ALIASES), "--_fm", "--pele-bg", "--pele-fg", "--pele-muted",
"--pele-line", "--pele-surface", "--pele-surface-alt", "--pele-border", "--pele-accent",
"--pele-critical", ...Array.from({ length: 8 }, (_, i) => `--pele-series-${i + 1}`),
]);
const FUNCTIONS = new Set([
"rgb", "rgba", "hsl", "hsla", "hwb", "lab", "lch", "oklab", "oklch", "color",
"color-mix", "calc", "min", "max", "clamp",
]);
interface Reference { id: string; target: "marker" | "clipPath" }
function css(source: string, context: "value" | "declarationList"): CssTree.CssNode {
try {
return parseCss(source, {
context, parseCustomProperty: true,
onParseError: () => fail(),
});
} catch (error) {
if (error instanceof DiagramImageError) throw error;
return fail();
}
}
function family(source: string): string {
const ast = css(source, "value");
if (ast.type !== "Value" || ast.children.isEmpty) fail("capability");
for (const node of ast.children) {
if (node.type === "Identifier" && !/^(?:inherit|initial|unset|revert)$/i.test(node.name)) continue;
if (node.type === "String" && node.value.length > 0) continue;
if (node.type === "Operator" && node.value === ",") continue;
fail("capability");
}
return generateCss(ast);
}
function fontSize(node: CssTree.CssNode, allowUnitless: boolean): number {
if (node.type !== "Value" || node.children.size !== 1) return fail("unsupported");
const size = node.children.first;
if (size?.type !== "Dimension" && !(allowUnitless && size?.type === "Number")) return fail("unsupported");
if (size.type === "Dimension" && size.unit !== "px") return fail("unsupported");
const value = Number(size.value);
if (!Number.isFinite(value) || value <= 0 || value > 200) return fail("unsupported");
return value;
}
function typography(
property: string, value: CssTree.CssNode, root: boolean,
fonts: DiagramInput["fonts"], attribute: boolean,
): string {
const text = generateCss(value);
switch (property) {
case "font":
if (!root || text !== `${fonts.size}px sans-serif`) fail("unsupported");
break;
case "font-family":
if (root) {
const expected = generateCss(css(`var(--pele-font,${fonts.sans})`, "value"));
if (text !== expected) fail("unsupported");
return family(fonts.sans);
}
// Pele measures its built-in monospace sections with Style.Mono. Author style
// font-family is NOT measured, even when it happens to name our mono font.
if (!attribute || text !== "var(--_fm)") fail("unsupported");
break;
case "font-size":
fontSize(value, attribute);
break;
case "font-weight":
if (!["normal", "400", "bold", "700", "var(--_w)", "var(--_hw)", "var(--_tw)"].includes(text)) fail("unsupported");
break;
case "font-style":
if (text !== "normal" && text !== "italic") fail("unsupported");
break;
case "letter-spacing":
case "word-spacing":
if (text !== "normal") fail("unsupported");
break;
case "text-transform":
if (text !== "none") fail("unsupported");
break;
case "direction":
if (text !== "ltr") fail("unsupported");
}
return text;
}
function drawingValue(property: string, value: CssTree.CssNode, refs: Reference[]): string {
walkCss(value, (node) => {
if (node.type === "Raw") fail();
if (node.type === "Url") {
const target = property === "clip-path" ? "clipPath"
: property.startsWith("marker-") ? "marker" : fail();
if (!/^#[A-Za-z0-9_.:-]+$/.test(node.value)) fail();
refs.push({ id: node.value.slice(1), target });
}
if (node.type === "Function") {
if (node.name === "var") {
const name = node.children.first;
if (name?.type !== "Identifier" || !VARIABLES.has(name.name)) fail();
} else if (!FUNCTIONS.has(node.name.toLowerCase())) fail();
}
if ((node.type === "Number" || node.type === "Dimension" || node.type === "Percentage")
&& !Number.isFinite(Number(node.value))) fail("limit");
});
return generateCss(value);
}
function style(
source: string, root: boolean, fonts: DiagramInput["fonts"], refs: Reference[],
): string {
const ast = css(source, "declarationList");
if (ast.type !== "DeclarationList") return fail();
const declarations: string[] = [];
const properties = new Set<string>();
for (const declaration of ast.children) {
if (declaration.type !== "Declaration" || declaration.important) fail();
const { property, value } = declaration;
if (root && properties.has(property)) fail();
properties.add(property);
let accepted: string;
if (property === "--_fm") {
if (!root || generateCss(value) !== generateCss(css(`var(--pele-font-mono,${fonts.mono})`, "value"))) fail("unsupported");
accepted = family(fonts.mono);
} else if (Object.hasOwn(ROOT_ALIASES, property)) {
if (!root || generateCss(value) !== ROOT_ALIASES[property]) fail();
// Font weights and radius are layout constants, never theme-controlled values.
accepted = property === "--_r" ? "4px"
: ["--_tw", "--_hw", "--_w"].includes(property) ? "bold" : generateCss(value);
} else if (TYPOGRAPHY_PROPERTIES.has(property)) {
accepted = typography(property, value, root, fonts, false);
} else if (DRAWING_PROPERTIES.has(property)) {
accepted = drawingValue(property, value, refs);
} else if (root && ((property === "max-width" && generateCss(value) === "100%")
|| (property === "height" && generateCss(value) === "auto"))) {
accepted = generateCss(value);
} else fail();
declarations.push(`${property}:${accepted}`);
}
if (root) {
for (const required of [
"--_bg", "--_fg", "--_m", "--_l", "--_s", "--_a", "--_b", "--_c", "--_fm",
"font", "font-family", "letter-spacing", "word-spacing", "text-transform", "direction",
]) if (!properties.has(required)) fail();
}
return declarations.join(";");
}
const NUMBER = /[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/g;
function numbers(value: string, letters = ""): number[] {
if (new RegExp(`[^\\s,\\d.eE+\\-${letters}]`).test(value)) fail();
const values = Array.from(value.matchAll(NUMBER), (match) => Number(match[0]));
if (values.length === 0 || values.some((value) => !Number.isFinite(value))) fail("limit");
return values;
}
function dimension(value: string | undefined): number {
if (!value || !/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(value)) return fail("limit");
const number = Number(value);
if (!Number.isFinite(number) || number <= 0 || number > MAX_DIMENSION) return fail("limit");
return number;
}
function geometry(name: string, value: string): void {
if (NUMERIC_ATTRIBUTES.has(name)) {
const values = numbers(value);
if (values.length !== 1) fail();
if (["r", "rx", "ry", "width", "height", "markerWidth", "markerHeight", "pathLength"].includes(name)
&& values[0] < 0) fail("limit");
} else if (name === "d") numbers(value, "MmLlHhVvCcSsQqTtAaZz");
else if (name === "points" || name === "viewBox") numbers(value);
else if (name === "transform") {
const rest = value.replace(/(?:matrix|translate|scale|rotate|skewX|skewY)\(([^()]*)\)/g, (_, args: string) => {
numbers(args);
return "";
});
if (rest.trim() !== "") fail();
} else if (name === "orient" && value !== "auto" && value !== "auto-start-reverse") numbers(value);
}
function escapeXml(value: string): string {
return value.replace(/[&<>"\r\n\t]/g, (character) => ({
"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;",
"\r": "&#13;", "\n": "&#10;", "\t": "&#9;",
})[character]!);
}
export function diagramImageTemplate(svg: string, fonts: DiagramInput["fonts"]): DiagramTemplate {
if (svg.length > OUTPUT_LIMIT || encoder.encode(svg).byteLength > OUTPUT_LIMIT) fail("limit");
family(fonts.sans);
family(fonts.mono);
if (!Number.isFinite(fonts.size) || fonts.size <= 0 || fonts.size > 200) fail("capability");
const parser = new SaxesParser({ xmlns: true });
const content: string[] = [];
const stack: string[] = [];
const ids = new Map<string, string>();
const refs: Reference[] = [];
let elements = 0;
let width = 0;
let height = 0;
let rootStyle = "";
let title = "";
let description = "";
parser.on("error", () => fail());
parser.on("doctype", () => fail());
parser.on("processinginstruction", () => fail());
parser.on("xmldecl", () => fail());
parser.on("opentag", (tag) => {
if (++elements > ELEMENT_LIMIT) fail("limit");
if (tag.uri !== SVG_NS || tag.prefix !== "" || !ELEMENTS.has(tag.local)) fail();
const root = stack.length === 0;
if (root && (elements !== 1 || tag.local !== "svg")) fail();
if (stack.at(-1) === "title" || stack.at(-1) === "desc") fail();
const attributes: string[] = [];
const rootDrawing: string[] = [];
for (const attribute of Object.values(tag.attributes)) {
const { name, value, uri } = attribute;
if (uri === XMLNS_NS) {
if (name !== "xmlns" || value !== SVG_NS) fail();
continue;
}
if (uri !== "" && !(uri === XML_NS && name === "xml:space")) fail();
let accepted = value;
if (name === "xml:space") {
if (value !== "preserve" && value !== "default") fail();
} else if (name === "style") accepted = style(value, root, fonts, refs);
else if (DRAWING_PROPERTIES.has(name)) accepted = drawingValue(name, css(value, "value"), refs);
else if (TYPOGRAPHY_PROPERTIES.has(name)) accepted = typography(name, css(value, "value"), root, fonts, true);
else if (!ATTRIBUTES.has(name)) fail();
else geometry(name, value);
if (name === "id") {
if (!/^[A-Za-z0-9_.:-]+$/.test(value) || ids.has(value)) fail();
ids.set(value, tag.local);
}
if (!root) attributes.push(` ${name}="${escapeXml(accepted)}"`);
else if (name === "style") rootStyle = accepted;
else if (DRAWING_PROPERTIES.has(name)) rootDrawing.push(`${name}:${accepted}`);
}
if (root) {
if (!rootStyle) fail();
rootStyle += rootDrawing.length ? `;${rootDrawing.join(";")}` : "";
width = dimension(tag.attributes.width?.value);
height = dimension(tag.attributes.height?.value);
if (width * height > MAX_PIXELS) fail("limit");
const viewBox = numbers(tag.attributes.viewBox?.value ?? "");
if (viewBox.length !== 4 || viewBox[0] !== 0 || viewBox[1] !== 0
|| viewBox[2] !== width || viewBox[3] !== height) fail("limit");
if (!rootStyle) fail();
} else content.push(`<${tag.local}${attributes.join("")}>`);
stack.push(tag.local);
});
const text = (value: string) => {
const element = stack.at(-1);
if (element === "title") title += value.slice(0, Math.max(0, 1000 - title.length));
if (element === "desc") description += value.slice(0, Math.max(0, 1000 - description.length));
if (stack.length > 1) {
if (value.trim() && !["title", "desc", "text", "tspan"].includes(element ?? "")) fail();
content.push(escapeXml(value));
} else if (value.trim()) fail();
};
parser.on("text", text);
parser.on("cdata", text);
parser.on("closetag", (tag) => {
if (stack.length > 1) content.push(`</${tag.local}>`);
stack.pop();
});
parser.write(svg).close();
for (const ref of refs) if (ids.get(ref.id) !== ref.target) fail();
const body = content.join("");
if (encoder.encode(body + rootStyle).byteLength > OUTPUT_LIMIT) fail("limit");
return {
content: body, style: rootStyle, width, height,
label: [title, description].filter(Boolean).join(". ").replace(/\s+/g, " ").trim().slice(0, 1000),
};
}
@@ -0,0 +1,27 @@
// Private feature contracts. Only the Worker imports Pele and the XML/CSS parsers.
export interface DiagramInput {
source: string;
width: number;
fonts: { sans: string; mono: string; size: number };
}
export type DiagramFailure = "syntax" | "unsupported" | "policy" | "limit"
| "load" | "deadline" | "worker" | "image" | "capability";
// Image-context only; never insert this content into the page DOM.
export interface DiagramTemplate {
content: string;
style: string;
width: number;
height: number;
label: string;
}
export type DiagramReply = { kind: "started" }
| { kind: "image"; template: DiagramTemplate }
| { kind: "failed"; reason: DiagramFailure };
export const SOURCE_LIMIT = 50_000;
export const OUTPUT_LIMIT = 1_048_576;
export const MAX_DIMENSION = 8192;
export const MAX_PIXELS = 8_000_000;