openpencil/scripts/visual-compare.ts

297 lines
10 KiB
TypeScript
Raw Normal View History

#!/usr/bin/env bun
/**
* Visual comparison pipeline: Figma vs OpenPencil renderer.
*
* Copy an element in Figma, then run:
* bun scripts/visual-compare.ts [--scale 2] [--output /tmp/visual-compare]
*
* Or pass a node ID directly (skips clipboard):
* bun scripts/visual-compare.ts --node 1:23 [--scale 2]
*
* Outputs:
* figma.png exported from real Figma
* ours.png rendered by OpenPencil headless SkiaRenderer
* diff.png visual diff (red = changed pixels)
*/
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
import { parseArgs } from 'node:util'
import { $ } from 'bun'
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
import { SkiaRenderer } from '@open-pencil/core/canvas'
import { renderNodesToImage, initCanvasKit } from '@open-pencil/core/io'
import { computeAllLayouts } from '@open-pencil/core/layout'
import { SceneGraph } from '@open-pencil/core/scene-graph'
import { fontManager } from '@open-pencil/core/text'
import { parseFigmaClipboard, importClipboardNodes } from '#core/clipboard'
const { values: opts } = parseArgs({
options: {
scale: { type: 'string', default: '2' },
output: { type: 'string', short: 'o', default: '/tmp/visual-compare' },
node: { type: 'string', short: 'n' },
resize: { type: 'boolean', default: false },
fuzz: { type: 'string', default: '1%' },
'alpha-diff': { type: 'boolean', default: false },
'metrics-json': { type: 'string' }
}
})
const scale = Number(opts.scale)
const outputDir = opts.output ?? '/tmp/visual-compare'
const figmaPath = `${outputDir}/figma.png`
const oursPath = `${outputDir}/ours.png`
const normalizedOursPath = `${outputDir}/ours-normalized.png`
const diffPath = `${outputDir}/diff.png`
const metricsPath = opts['metrics-json'] ?? `${outputDir}/metrics.json`
const alphaFigmaPath = `${outputDir}/figma-alpha.png`
const alphaOursPath = `${outputDir}/ours-alpha.png`
const alphaDiffPath = `${outputDir}/diff-alpha.png`
if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true })
if (opts.node) {
await runWithNodeId(opts.node)
} else {
await runWithClipboard()
}
// --- Mode 1: Clipboard ---
async function runWithClipboard() {
console.log('📋 Reading clipboard…')
const html = await readClipboardHtml()
if (!html) bail('No HTML on clipboard. Copy an element in Figma first.')
const parsed = await parseFigmaClipboard(html)
if (!parsed) bail('Clipboard has no Figma data. Copy an element in Figma first.')
console.log(` ${parsed.nodes.length} node changes, ${parsed.blobs.length} blobs`)
console.log('🖼️ Rendering with OpenPencil…')
await renderOurs(html)
console.log('🎨 Pasting into Figma & exporting…')
await ensureFigmaConnected()
await renderFigmaViaPaste()
await diff()
}
// --- Mode 2: Node ID ---
async function runWithNodeId(nodeId: string) {
await ensureFigmaConnected()
console.log(`🎨 Exporting node ${nodeId} from Figma…`)
await $`figma-use export node ${nodeId} --output ${figmaPath} --scale ${String(scale)}`.quiet()
console.log(`${figmaPath}`)
console.log('📋 Exporting clipboard data from Figma…')
// Select the node, copy, read clipboard, render with our engine
const nodeIdLiteral = JSON.stringify(nodeId)
await $`figma-use eval ${`const n = figma.getNodeById(${nodeIdLiteral}); if (!n) return; let page = n.parent; while (page && page.type !== 'PAGE') page = page.parent; if (page) { await figma.setCurrentPageAsync(page); page.selection = [n]; }`}`.quiet()
await Bun.sleep(200)
await $`osascript -e 'tell application "Figma" to activate'`.quiet()
await Bun.sleep(300)
await $`osascript -e 'tell application "System Events" to keystroke "c" using command down'`.quiet()
await Bun.sleep(1000)
const html = await readClipboardHtml()
if (!html) bail('Failed to copy from Figma')
const parsed = await parseFigmaClipboard(html)
if (!parsed) bail('Clipboard has no Figma data after copy')
console.log('🖼️ Rendering with OpenPencil…')
await renderOurs(html)
await diff()
}
// --- Rendering ---
async function renderOurs(html: string) {
const result = await parseFigmaClipboard(html)
if (!result) throw new Error('Failed to parse clipboard')
const graph = new SceneGraph()
const pageId = graph.getPages()[0].id
const createdIds = importClipboardNodes(result.nodes, graph, pageId, 0, 0, result.blobs)
if (createdIds.length === 0) throw new Error('No nodes imported from clipboard')
computeAllLayouts(graph)
const families = new Set<string>()
for (const node of graph.getAllNodes()) {
if (node.fontFamily) families.add(node.fontFamily)
}
for (const family of families) {
await fontManager.loadFont(family)
}
const ck = await initCanvasKit()
const surface = ck.MakeSurface(1, 1)
if (!surface) throw new Error('Failed to create CanvasKit surface')
const renderer = new SkiaRenderer(ck, surface)
renderer.viewportWidth = 1
renderer.viewportHeight = 1
renderer.dpr = 1
const data = renderNodesToImage(ck, renderer, graph, pageId, createdIds, {
scale,
format: 'PNG'
})
surface.delete()
if (!data) throw new Error('Render produced no image')
await Bun.write(oursPath, data)
console.log(`${oursPath}`)
}
async function renderFigmaViaPaste() {
// Create temp page so we don't pollute the user's work
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
await $`figma-use eval ${'(() => { const p = figma.createPage(); p.name = "__visual_compare__"; figma.currentPage = p; return p.id; })()'} --json`.quiet()
try {
// Activate Figma and paste
await $`osascript -e 'tell application "Figma" to activate'`.quiet()
await Bun.sleep(500)
await $`osascript -e 'tell application "System Events" to keystroke "v" using command down'`.quiet()
await Bun.sleep(2000)
// Get pasted selection
const selJson = await $`figma-use selection get --json`.quiet()
const selection = JSON.parse(selJson.text().trim())
if (!selection.length) throw new Error('Nothing pasted. Ensure clipboard has Figma data.')
const nodeId = selection[0].id
// Export from Figma
await $`figma-use export node ${nodeId} --output ${figmaPath} --scale ${String(scale)}`.quiet()
console.log(`${figmaPath}`)
} finally {
// Clean up: remove temp page
await $`figma-use eval ${'(() => { const ps = figma.root.children; const tmp = ps.find(p => p.name === "__visual_compare__"); if (tmp) { const other = ps.find(p => p !== tmp); if (other) figma.currentPage = other; tmp.remove(); } })()'}`
.quiet()
.nothrow()
}
}
// --- Diff ---
async function diff() {
console.log('🔍 Computing diff…')
const figmaSize = (await $`identify -format '%wx%h' ${figmaPath}`.quiet()).text().trim()
const oursSize = (await $`identify -format '%wx%h' ${oursPath}`.quiet()).text().trim()
const compareOursPath = figmaSize === oursSize ? oursPath : normalizedOursPath
if (figmaSize !== oursSize) {
const mode = opts.resize ? 'resizing' : 'padding/cropping without scaling'
console.log(` ⚠ Size mismatch: Figma ${figmaSize}, Ours ${oursSize}${mode}`)
if (opts.resize) {
await $`magick ${oursPath} -resize ${figmaSize}! ${normalizedOursPath}`.quiet()
} else {
await $`magick ${oursPath} -background none -gravity northwest -extent ${figmaSize} ${normalizedOursPath}`.quiet()
}
}
const result =
await $`magick compare -metric AE -highlight-color red -lowlight-color '#FFFFFF33' -compose src ${figmaPath} ${compareOursPath} ${diffPath}`
.quiet()
.nothrow()
const fuzzResult =
await $`magick compare -metric AE -fuzz ${opts.fuzz} ${figmaPath} ${compareOursPath} null:`
.quiet()
.nothrow()
const rmseResult = await $`magick compare -metric RMSE ${figmaPath} ${compareOursPath} null:`
.quiet()
.nothrow()
const rmse = rmseResult.stderr.toString().trim()
2026-05-18 15:41:01 +00:00
const diffPixels = Number.parseInt(result.stderr.toString().trim(), 10) || 0
const fuzzPixels = Number.parseInt(fuzzResult.stderr.toString().trim(), 10) || 0
const [w, h] = figmaSize.split('x').map(Number)
const total = w * h
const pct = (diffPixels / total) * 100
const fuzzPct = (fuzzPixels / total) * 100
const alphaMetrics = opts['alpha-diff'] ? await diffAlpha(compareOursPath, total) : null
const metrics = {
figmaSize,
openPencilSize: oursSize,
comparedOpenPencilPath: compareOursPath,
resized: Boolean(opts.resize && figmaSize !== oursSize),
normalized: figmaSize !== oursSize,
differentPixels: diffPixels,
differentPercent: Number(pct.toFixed(2)),
fuzz: opts.fuzz,
fuzzDifferentPixels: fuzzPixels,
fuzzDifferentPercent: Number(fuzzPct.toFixed(2)),
rmse,
alpha: alphaMetrics
}
writeFileSync(metricsPath, `${JSON.stringify(metrics, null, 2)}\n`)
console.log(`${diffPath}`)
console.log(
` ${diffPixels.toLocaleString()} different pixels (${pct.toFixed(2)}% of ${total.toLocaleString()})`
)
console.log(
` ${fuzzPixels.toLocaleString()} different pixels with ${opts.fuzz} fuzz (${fuzzPct.toFixed(2)}%)`
)
console.log(` RMSE ${rmse}`)
if (alphaMetrics) {
console.log(
` Alpha AE ${alphaMetrics.differentPixels.toLocaleString()} pixels (${alphaMetrics.differentPercent.toFixed(2)}%)`
)
}
console.log(` Metrics → ${metricsPath}`)
console.log(`\n✅ Done! Images in ${outputDir}/`)
}
async function diffAlpha(compareOursPath: string, total: number) {
await $`magick ${figmaPath} -alpha extract ${alphaFigmaPath}`.quiet()
await $`magick ${compareOursPath} -alpha extract ${alphaOursPath}`.quiet()
const result =
await $`magick compare -metric AE -highlight-color red -lowlight-color '#FFFFFF33' -compose src ${alphaFigmaPath} ${alphaOursPath} ${alphaDiffPath}`
.quiet()
.nothrow()
const differentPixels = Number.parseInt(result.stderr.toString().trim(), 10) || 0
return {
path: alphaDiffPath,
differentPixels,
differentPercent: (differentPixels / total) * 100
}
}
// --- Helpers ---
async function readClipboardHtml(): Promise<string | null> {
const proc = Bun.spawn(
[
'swift',
'-e',
'import AppKit; if let h = NSPasteboard.general.string(forType: .html) { print(h) } else { exit(1) }'
],
{ stdout: 'pipe', stderr: 'pipe' }
)
const text = await new Response(proc.stdout).text()
return (await proc.exited) === 0 ? text.trim() : null
}
async function ensureFigmaConnected() {
const s = await $`figma-use status`.quiet().nothrow()
if (s.exitCode !== 0) {
bail(
'figma-use not connected. Start Figma with:\n open -a Figma --args --remote-debugging-port=9222'
)
}
}
function bail(msg: string): never {
console.error(msg)
process.exit(1)
}