A fast, helpful, and open-source document parser
missing files
Logan Markewichdaad84261a67
diff --git a/src/processing/gridDebugLogger.ts b/src/processing/gridDebugLogger.tsnew file mode 100644index 0000000..8cd0e73--- /dev/null+++ b/src/processing/gridDebugLogger.ts@@ -0,0 +1,498 @@+import { mkdirSync, writeFileSync } from "fs";+import { mkdir, writeFile } from "fs/promises";+import { dirname } from "path";+import { ProjectionTextBox } from "../core/types.js";++/**+ * Configuration for grid projection debug logging.+ *+ * When enabled, logs detailed information about how text elements are+ * snapped, anchored, and projected during grid layout. Use filters to+ * narrow output to specific elements you're investigating.+ */+export interface GridDebugConfig {+ /**+ * Enable debug logging for grid projection.+ * @defaultValue `false`+ */+ enabled: boolean;++ /**+ * Only log elements whose text contains one of these substrings (case-insensitive).+ * If empty, all elements are logged.+ */+ textFilter?: string[];++ /**+ * Only log elements on these line indices (0-based within the page).+ */+ lineFilter?: number[];++ /**+ * Only log elements on this page number (1-indexed).+ */+ pageFilter?: number;++ /**+ * Only log elements within this bounding region (PDF coordinates).+ */+ regionFilter?: { x1: number; y1: number; x2: number; y2: number };++ /**+ * Write log output to a file path instead of stderr. If not set, logs to stderr.+ */+ outputPath?: string;++ /**+ * Generate PNG visualizations of the grid projection showing text boxes+ * color-coded by snap type (left/right/center/floating/flowing) with+ * anchor lines overlaid.+ * @defaultValue `false`+ */+ visualize?: boolean;++ /**+ * Directory to save visualization PNGs. Each page produces a file+ * named `page-{N}-grid.png`.+ * @defaultValue `"./debug-output"`+ */+ visualizePath?: string;+}++export const DEFAULT_DEBUG_CONFIG: GridDebugConfig = {+ enabled: false,+};++type LogEntry = {+ phase: string;+ lineIndex?: number;+ boxIndex?: number;+ text?: string;+ message: string;+ data?: Record<string, unknown>;+};++/** Captured data for a single page, used by the grid visualizer. */+export interface VisualizerPageData {+ pageNum: number;+ width: number;+ height: number;+ boxes: VisualizerBox[];+ anchors: {+ left: number[];+ right: number[];+ center: number[];+ };+ flowingLines: Set<number>;+ blocks: Array<{ start: number; end: number; flowing: boolean }>;+}++export interface VisualizerBox {+ text: string;+ x: number;+ y: number;+ w: number;+ h: number;+ lineIndex: number;+ snap?: "left" | "right" | "center";+ isFlowing: boolean;+ forceUnsnapped?: boolean;+}++/**+ * Debug logger for grid projection. Provides targeted logging to trace+ * exactly why specific text elements are projected the way they are.+ *+ * Usage from LiteParse config:+ * ```typescript+ * const parser = new LiteParse({+ * debug: {+ * enabled: true,+ * textFilter: ["Total", "Revenue"], // only log elements containing these strings+ * pageFilter: 2, // only page 2+ * visualize: true, // generate PNG overlays+ * }+ * });+ * ```+ */+export class GridDebugLogger {+ private config: GridDebugConfig;+ private entries: LogEntry[] = [];+ private currentPage: number = 0;+ private writeOutput: (msg: string) => void;++ // Visualization data collection+ private vizPages: VisualizerPageData[] = [];+ private currentVizPage?: VisualizerPageData;++ constructor(config: GridDebugConfig) {+ this.config = config;+ if (config.outputPath) {+ // Defer file writing to flush()+ this.writeOutput = () => {};+ } else {+ this.writeOutput = (msg: string) => process.stderr.write(msg + "\n");+ }+ }++ get enabled(): boolean {+ return this.config.enabled;+ }++ get shouldVisualize(): boolean {+ return this.config.visualize ?? false;+ }++ get visualizerPages(): VisualizerPageData[] {+ return this.vizPages;+ }++ get debugConfig(): GridDebugConfig {+ return this.config;+ }++ setPage(pageNum: number, width: number, height: number): void {+ this.currentPage = pageNum;+ if (this.config.pageFilter && pageNum !== this.config.pageFilter) {+ return;+ }+ this.emit({ phase: "page", message: `=== Page ${pageNum} ===` });++ if (this.shouldVisualize) {+ this.currentVizPage = {+ pageNum,+ width,+ height,+ boxes: [],+ anchors: { left: [], right: [], center: [] },+ flowingLines: new Set(),+ blocks: [],+ };+ this.vizPages.push(this.currentVizPage);+ }+ }++ private isPageFiltered(): boolean {+ return !!this.config.pageFilter && this.currentPage !== this.config.pageFilter;+ }++ /** Check if a bbox passes the configured filters */+ matchesBbox(bbox: ProjectionTextBox, lineIndex?: number): boolean {+ if (!this.config.enabled) return false;+ if (this.isPageFiltered()) return false;++ if (this.config.textFilter?.length) {+ const text = bbox.str.toLowerCase();+ if (!this.config.textFilter.some((f) => text.includes(f.toLowerCase()))) {+ return false;+ }+ }++ if (this.config.lineFilter?.length && lineIndex !== undefined) {+ if (!this.config.lineFilter.includes(lineIndex)) {+ return false;+ }+ }++ if (this.config.regionFilter) {+ const r = this.config.regionFilter;+ if (bbox.x + bbox.w < r.x1 || bbox.x > r.x2 || bbox.y + bbox.h < r.y1 || bbox.y > r.y2) {+ return false;+ }+ }++ return true;+ }++ /** Log which block a line range was assigned to */+ logBlock(blockIndex: number, start: number, end: number): void {+ if (!this.config.enabled || this.isPageFiltered()) return;+ this.emit({+ phase: "blocks",+ message: `Block ${blockIndex}: lines ${start}-${end - 1}`,+ });+ }++ /** Log flowing text classification */+ logFlowingBlock(start: number, end: number): void {+ if (!this.config.enabled || this.isPageFiltered()) return;+ this.emit({+ phase: "flowing",+ message: `Block lines ${start}-${end - 1} classified as flowing text`,+ });+ if (this.currentVizPage) {+ this.currentVizPage.blocks.push({ start, end, flowing: true });+ }+ }++ /** Log non-flowing block */+ logStructuredBlock(start: number, end: number): void {+ if (this.currentVizPage) {+ this.currentVizPage.blocks.push({ start, end, flowing: false });+ }+ }++ /** Log flowing line detection */+ logFlowingLine(lineIndex: number, reason: string): void {+ if (!this.config.enabled || this.isPageFiltered()) return;+ if (this.config.lineFilter?.length && !this.config.lineFilter.includes(lineIndex)) return;+ this.emit({+ phase: "flowing",+ lineIndex,+ message: `Line ${lineIndex} marked flowing: ${reason}`,+ });+ if (this.currentVizPage) {+ this.currentVizPage.flowingLines.add(lineIndex);+ }+ }++ /** Log anchor extraction results for a block */+ logAnchors(+ anchorLeft: Record<number, ProjectionTextBox[]>,+ anchorRight: Record<number, ProjectionTextBox[]>,+ anchorCenter: Record<number, ProjectionTextBox[]>+ ): void {+ if (!this.config.enabled || this.isPageFiltered()) return;++ const leftKeys = Object.keys(anchorLeft).map(Number);+ const rightKeys = Object.keys(anchorRight).map(Number);+ const centerKeys = Object.keys(anchorCenter).map(Number);++ this.emit({+ phase: "anchors",+ message: `Anchors: left=[${leftKeys.join(", ")}] right=[${rightKeys.join(", ")}] center=[${centerKeys.join(", ")}]`,+ });++ // Capture for visualization+ if (this.currentVizPage) {+ this.currentVizPage.anchors.left.push(...leftKeys);+ this.currentVizPage.anchors.right.push(...rightKeys);+ this.currentVizPage.anchors.center.push(...centerKeys);+ }++ // Log which elements are in each anchor, but only if they match filters+ for (const key of leftKeys) {+ const items = anchorLeft[key];+ const matchingItems = this.config.textFilter?.length+ ? items.filter((b) => this.matchesBbox(b))+ : items;+ if (matchingItems.length > 0) {+ this.emit({+ phase: "anchors",+ message: ` left@${key}: ${matchingItems.map((b) => `"${b.str.substring(0, 30)}" (x=${b.x.toFixed(1)}, y=${b.y.toFixed(1)})`).join(", ")}`,+ });+ }+ }+ for (const key of rightKeys) {+ const items = anchorRight[key];+ const matchingItems = this.config.textFilter?.length+ ? items.filter((b) => this.matchesBbox(b))+ : items;+ if (matchingItems.length > 0) {+ this.emit({+ phase: "anchors",+ message: ` right@${key}: ${matchingItems.map((b) => `"${b.str.substring(0, 30)}" (x=${b.x.toFixed(1)}, y=${b.y.toFixed(1)})`).join(", ")}`,+ });+ }+ }+ for (const key of centerKeys) {+ const items = anchorCenter[key];+ const matchingItems = this.config.textFilter?.length+ ? items.filter((b) => this.matchesBbox(b))+ : items;+ if (matchingItems.length > 0) {+ this.emit({+ phase: "anchors",+ message: ` center@${key}: ${matchingItems.map((b) => `"${b.str.substring(0, 30)}" (x=${b.x.toFixed(1)}, y=${b.y.toFixed(1)})`).join(", ")}`,+ });+ }+ }+ }++ /** Log snap assignment for a bbox */+ logSnapAssignment(bbox: ProjectionTextBox, lineIndex: number, boxIndex: number): void {+ if (!this.matchesBbox(bbox, lineIndex)) return;+ this.emit({+ phase: "snap",+ lineIndex,+ boxIndex,+ text: bbox.str,+ message: `"${bbox.str.substring(0, 40)}" snap=${bbox.snap ?? "none"} leftAnchor=${bbox.leftAnchor ?? "-"} rightAnchor=${bbox.rightAnchor ?? "-"} centerAnchor=${bbox.centerAnchor ?? "-"} forceUnsnapped=${bbox.forceUnsnapped ?? false}`,+ data: {+ x: round2(bbox.x),+ y: round2(bbox.y),+ w: round2(bbox.w),+ h: round2(bbox.h),+ shouldSpace: bbox.shouldSpace,+ },+ });+ }++ /** Capture all boxes on a line for visualization (called after snap assignment) */+ captureLineBoxes(lineIndex: number, line: ProjectionTextBox[], isFlowing: boolean): void {+ if (!this.currentVizPage) return;+ for (const bbox of line) {+ this.currentVizPage.boxes.push({+ text: bbox.str,+ x: bbox.x,+ y: bbox.y,+ w: bbox.w,+ h: bbox.h,+ lineIndex,+ snap: bbox.snap,+ isFlowing,+ forceUnsnapped: bbox.forceUnsnapped,+ });+ }+ }++ /** Log the rendering of a bbox to a target column position */+ logRender(bbox: ProjectionTextBox, lineIndex: number, targetX: number, reason: string): void {+ if (!this.matchesBbox(bbox, lineIndex)) return;+ this.emit({+ phase: "render",+ lineIndex,+ text: bbox.str,+ message: `"${bbox.str.substring(0, 40)}" → col ${targetX} (${reason})`,+ data: {+ pdfX: round2(bbox.x),+ snap: bbox.snap ?? "none",+ shouldSpace: bbox.shouldSpace,+ },+ });+ }++ /** Log forward anchor updates */+ logForwardAnchor(+ type: "left" | "right" | "center" | "floating",+ pdfX: number,+ gridCol: number+ ): void {+ if (!this.config.enabled || this.isPageFiltered()) return;+ // Only log if no text filter (forward anchors aren't bbox-specific) or if we've been logging+ if (this.config.textFilter?.length) return;+ this.emit({+ phase: "forward-anchor",+ message: `${type}@${round2(pdfX)} → col ${gridCol}`,+ });+ }++ /** Log duplicate resolution for multi-anchor elements */+ logDuplicateResolution(bbox: ProjectionTextBox, resolvedTo: string): void {+ if (!this.matchesBbox(bbox)) return;+ this.emit({+ phase: "dedup",+ text: bbox.str,+ message: `"${bbox.str.substring(0, 40)}" multi-anchor resolved to ${resolvedTo} (left=${bbox.leftAnchor ?? "-"} right=${bbox.rightAnchor ?? "-"} center=${bbox.centerAnchor ?? "-"})`,+ });+ }++ /** Log line composition (the full set of bboxes on a line) */+ logLineComposition(lineIndex: number, line: ProjectionTextBox[]): void {+ if (!this.config.enabled || this.isPageFiltered()) return;+ if (this.config.lineFilter?.length && !this.config.lineFilter.includes(lineIndex)) return;+ // If text filter is set, only log lines that contain a matching bbox+ if (this.config.textFilter?.length) {+ if (!line.some((b) => this.matchesBbox(b, lineIndex))) return;+ }+ const items = line.map((b) => `"${b.str.substring(0, 20)}"@(${round2(b.x)},${round2(b.y)})`);+ this.emit({+ phase: "lines",+ lineIndex,+ message: `Line ${lineIndex} [${line.length} items]: ${items.join(" ")}`,+ });+ }++ private emit(entry: LogEntry): void {+ this.entries.push(entry);+ if (!this.config.outputPath) {+ const prefix = `[grid-debug][${entry.phase}]`;+ const loc =+ entry.lineIndex !== undefined+ ? ` L${entry.lineIndex}${entry.boxIndex !== undefined ? `:${entry.boxIndex}` : ""}`+ : "";+ let line = `${prefix}${loc} ${entry.message}`;+ if (entry.data) {+ line += ` ${JSON.stringify(entry.data)}`;+ }+ this.writeOutput(line);+ }+ }++ private formatEntries(): string {+ return (+ this.entries+ .map((entry) => {+ const prefix = `[${entry.phase}]`;+ const loc =+ entry.lineIndex !== undefined+ ? ` L${entry.lineIndex}${entry.boxIndex !== undefined ? `:${entry.boxIndex}` : ""}`+ : "";+ let line = `${prefix}${loc} ${entry.message}`;+ if (entry.data) {+ line += ` ${JSON.stringify(entry.data)}`;+ }+ return line;+ })+ .join("\n") + "\n"+ );+ }++ /** Synchronous flush of log entries to file. */+ flushSync(): void {+ if (!this.config.outputPath || this.entries.length === 0) return;+ mkdirSync(dirname(this.config.outputPath), { recursive: true });+ writeFileSync(this.config.outputPath, this.formatEntries(), "utf-8");+ this.entries = [];+ }++ /** Flush entries to file if outputPath is configured */+ async flush(): Promise<void> {+ if (!this.config.outputPath || this.entries.length === 0) return;+ await mkdir(dirname(this.config.outputPath), { recursive: true });+ await writeFile(this.config.outputPath, this.formatEntries(), "utf-8");+ this.entries = [];+ }+}++/** No-op logger that skips all checks. Use when debug is disabled. */+class NoopGridDebugLogger extends GridDebugLogger {+ constructor() {+ super({ enabled: false });+ }+ override get enabled(): boolean {+ return false;+ }+ override get shouldVisualize(): boolean {+ return false;+ }+ override matchesBbox(): boolean {+ return false;+ }+ override setPage(): void {}+ override logBlock(): void {}+ override logFlowingBlock(): void {}+ override logStructuredBlock(): void {}+ override logFlowingLine(): void {}+ override logAnchors(): void {}+ override logSnapAssignment(): void {}+ override captureLineBoxes(): void {}+ override logRender(): void {}+ override logForwardAnchor(): void {}+ override logDuplicateResolution(): void {}+ override logLineComposition(): void {}+ override flushSync(): void {}+ override async flush(): Promise<void> {}+}++/** Singleton no-op instance for zero-overhead when debug is off */+export const NOOP_LOGGER = new NoopGridDebugLogger();++export function createGridDebugLogger(config?: GridDebugConfig): GridDebugLogger {+ if (!config?.enabled) return NOOP_LOGGER;+ return new GridDebugLogger(config);+}++function round2(n: number): number {+ return Math.round(n * 100) / 100;+}diff --git a/src/processing/gridVisualizer.ts b/src/processing/gridVisualizer.tsnew file mode 100644index 0000000..1767a60--- /dev/null+++ b/src/processing/gridVisualizer.ts@@ -0,0 +1,249 @@+import sharp from "sharp";+import { mkdirSync } from "fs";+import { VisualizerPageData } from "./gridDebugLogger.js";++/** Maximum image dimension in pixels to prevent excessive memory usage. */+const MAX_IMAGE_DIM = 4000;++/** Padding around content bounding box in PDF points. */+const CROP_PADDING = 15;++/** Color scheme for snap types */+const COLORS = {+ left: { fill: "rgba(59,130,246,0.15)", stroke: "#3b82f6", anchor: "#3b82f6" },+ right: { fill: "rgba(239,68,68,0.15)", stroke: "#ef4444", anchor: "#ef4444" },+ center: { fill: "rgba(34,197,94,0.15)", stroke: "#22c55e", anchor: "#22c55e" },+ floating: { fill: "rgba(156,163,175,0.15)", stroke: "#9ca3af", anchor: "#9ca3af" },+ flowing: { fill: "rgba(234,179,8,0.15)", stroke: "#eab308", anchor: "#eab308" },+} as const;++function escapeXml(s: string): string {+ return s+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """)+ .replace(/'/g, "'");+}++/**+ * Compute the bounding box of all content in PDF coordinates.+ * Returns { x, y, w, h } clamped to page dimensions.+ */+function getContentBounds(data: VisualizerPageData): {+ x: number;+ y: number;+ w: number;+ h: number;+} {+ if (data.boxes.length === 0) {+ return { x: 0, y: 0, w: data.width, h: data.height };+ }++ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;++ for (const box of data.boxes) {+ minX = Math.min(minX, box.x);+ minY = Math.min(minY, box.y);+ maxX = Math.max(maxX, box.x + box.w);+ maxY = Math.max(maxY, box.y + box.h);+ }++ // Also include anchor lines in the horizontal extent+ for (const x of data.anchors.left) {+ minX = Math.min(minX, x);+ maxX = Math.max(maxX, x);+ }+ for (const x of data.anchors.right) {+ minX = Math.min(minX, x);+ maxX = Math.max(maxX, x);+ }+ for (const x of data.anchors.center) {+ minX = Math.min(minX, x);+ maxX = Math.max(maxX, x);+ }++ // Add padding and clamp to page+ minX = Math.max(0, minX - CROP_PADDING);+ minY = Math.max(0, minY - CROP_PADDING);+ maxX = Math.min(data.width, maxX + CROP_PADDING);+ maxY = Math.min(data.height, maxY + CROP_PADDING);++ return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };+}++/**+ * Render a grid visualization for a single page as a PNG.+ *+ * Draws text boxes as colored rectangles (by snap type), anchor positions+ * as vertical lines, and text labels inside each box. Auto-crops to the+ * content bounding box to avoid large empty regions.+ */+export async function renderGridVisualization(+ data: VisualizerPageData,+ outputPath: string+): Promise<void> {+ // Compute content bounds for cropping+ const bounds = getContentBounds(data);++ // Calculate scale to fit within MAX_IMAGE_DIM based on cropped size+ const scale = Math.min(MAX_IMAGE_DIM / bounds.w, MAX_IMAGE_DIM / bounds.h, 2);+ const imgWidth = Math.round(bounds.w * scale);+ const imgHeight = Math.round(bounds.h * scale);++ // Offset: shift all coordinates so content starts at (0,0)+ const ox = bounds.x;+ const oy = bounds.y;++ // Build SVG overlay+ const svgParts: string[] = [];+ svgParts.push(+ `<svg xmlns="http://www.w3.org/2000/svg" width="${imgWidth}" height="${imgHeight}" viewBox="0 0 ${imgWidth} ${imgHeight}">`+ );++ // Font size scales with image+ const fontSize = Math.max(6, Math.min(10, Math.round(8 * scale)));++ // Draw anchor lines (behind boxes)+ const drawnAnchors = new Set<string>();++ for (const x of data.anchors.left) {+ const key = `left-${x}`;+ if (drawnAnchors.has(key)) continue;+ drawnAnchors.add(key);+ const sx = Math.round((x - ox) * scale);+ svgParts.push(+ `<line x1="${sx}" y1="0" x2="${sx}" y2="${imgHeight}" stroke="${COLORS.left.anchor}" stroke-width="1" stroke-dasharray="4,4" opacity="0.5"/>`+ );+ }+ for (const x of data.anchors.right) {+ const key = `right-${x}`;+ if (drawnAnchors.has(key)) continue;+ drawnAnchors.add(key);+ const sx = Math.round((x - ox) * scale);+ svgParts.push(+ `<line x1="${sx}" y1="0" x2="${sx}" y2="${imgHeight}" stroke="${COLORS.right.anchor}" stroke-width="1" stroke-dasharray="4,4" opacity="0.5"/>`+ );+ }+ for (const x of data.anchors.center) {+ const key = `center-${x}`;+ if (drawnAnchors.has(key)) continue;+ drawnAnchors.add(key);+ const sx = Math.round((x - ox) * scale);+ svgParts.push(+ `<line x1="${sx}" y1="0" x2="${sx}" y2="${imgHeight}" stroke="${COLORS.center.anchor}" stroke-width="1" stroke-dasharray="2,6" opacity="0.5"/>`+ );+ }++ // Draw block boundaries+ for (const block of data.blocks) {+ const blockBoxes = data.boxes.filter(+ (b) => b.lineIndex >= block.start && b.lineIndex < block.end+ );+ if (blockBoxes.length === 0) continue;+ const minY = Math.min(...blockBoxes.map((b) => b.y));+ const maxY = Math.max(...blockBoxes.map((b) => b.y + b.h));+ const sy = Math.round((minY - oy) * scale) - 2;+ const ey = Math.round((maxY - oy) * scale) + 2;+ const blockColor = block.flowing ? COLORS.flowing.stroke : "#6b7280";+ svgParts.push(+ `<rect x="0" y="${sy}" width="${imgWidth}" height="${ey - sy}" fill="none" stroke="${blockColor}" stroke-width="1" stroke-dasharray="6,3" opacity="0.3"/>`+ );+ }++ // Draw text boxes+ for (const box of data.boxes) {+ const sx = Math.round((box.x - ox) * scale);+ const sy = Math.round((box.y - oy) * scale);+ const sw = Math.max(Math.round(box.w * scale), 1);+ const sh = Math.max(Math.round(box.h * scale), 1);++ let color: (typeof COLORS)[keyof typeof COLORS];+ if (box.isFlowing) {+ color = COLORS.flowing;+ } else if (box.snap === "left") {+ color = COLORS.left;+ } else if (box.snap === "right") {+ color = COLORS.right;+ } else if (box.snap === "center") {+ color = COLORS.center;+ } else {+ color = COLORS.floating;+ }++ svgParts.push(+ `<rect x="${sx}" y="${sy}" width="${sw}" height="${sh}" fill="${color.fill}" stroke="${color.stroke}" stroke-width="0.75"/>`+ );++ // Text label (truncated to fit)+ const maxChars = Math.max(1, Math.floor(sw / (fontSize * 0.55)));+ const label =+ box.text.length > maxChars ? box.text.substring(0, maxChars - 1) + "\u2026" : box.text;+ if (label.length > 0 && sh >= fontSize) {+ svgParts.push(+ `<text x="${sx + 2}" y="${sy + sh - 2}" font-family="monospace" font-size="${fontSize}" fill="${color.stroke}" clip-path="url(#clip-${sx}-${sy})">${escapeXml(label)}</text>`+ );+ }+ }++ // Legend (top-right corner of cropped image)+ const legendY = 10;+ const legendX = imgWidth - 200;+ svgParts.push(+ `<rect x="${legendX - 5}" y="${legendY - 5}" width="195" height="95" fill="white" stroke="#d1d5db" stroke-width="1" rx="3"/>`+ );+ const legendItems = [+ { label: "Left snap", color: COLORS.left },+ { label: "Right snap", color: COLORS.right },+ { label: "Center snap", color: COLORS.center },+ { label: "Floating", color: COLORS.floating },+ { label: "Flowing text", color: COLORS.flowing },+ ];+ for (let i = 0; i < legendItems.length; i++) {+ const ly = legendY + i * 17;+ svgParts.push(+ `<rect x="${legendX}" y="${ly}" width="12" height="12" fill="${legendItems[i].color.fill}" stroke="${legendItems[i].color.stroke}" stroke-width="1"/>`+ );+ svgParts.push(+ `<text x="${legendX + 18}" y="${ly + 10}" font-family="sans-serif" font-size="11" fill="#374151">${legendItems[i].label}</text>`+ );+ }++ svgParts.push("</svg>");++ const svgBuffer = Buffer.from(svgParts.join("\n"));++ // Create white background image and composite SVG+ await sharp({+ create: {+ width: imgWidth,+ height: imgHeight,+ channels: 4,+ background: { r: 255, g: 255, b: 255, alpha: 1 },+ },+ })+ .composite([{ input: svgBuffer, top: 0, left: 0 }])+ .png({ compressionLevel: 6 })+ .toFile(outputPath);+}++/**+ * Render all captured visualization pages to PNG files.+ */+export async function renderAllVisualizations(+ pages: VisualizerPageData[],+ outputDir: string+): Promise<string[]> {+ mkdirSync(outputDir, { recursive: true });++ const paths: string[] = [];+ for (const page of pages) {+ const filePath = `${outputDir}/page-${page.pageNum}-grid.png`;+ await renderGridVisualization(page, filePath);+ paths.push(filePath);+ }+ return paths;+}