AI-native design editor. Open-source Figma alternative.
Add @open-pencil/cli with headless .fig file operations
Danila Poyarkov1975fae36ee3
diff --git a/bun.lock b/bun.lockindex 06c4bd56d..b7b5b8c77 100644--- a/bun.lock+++ b/bun.lock@@ -37,6 +37,22 @@"vite": "^7.0.4",},},+ "packages/cli": {+ "name": "@open-pencil/cli",+ "version": "0.1.0",+ "bin": {+ "open-pencil": "./src/index.ts",+ },+ "dependencies": {+ "@open-pencil/core": "workspace:*",+ "agentfmt": "^0.1.3",+ "canvaskit-wasm": "^0.40.0",+ "citty": "^0.1.6",+ },+ "devDependencies": {+ "@types/bun": "^1.2.9",+ },+ },"packages/core": {"name": "@open-pencil/core","version": "0.1.0",@@ -143,6 +159,8 @@"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],+ "@open-pencil/cli": ["@open-pencil/cli@workspace:packages/cli"],+"@open-pencil/core": ["@open-pencil/core@workspace:packages/core"],"@oxfmt/binding-android-arm-eabi": ["@oxfmt/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-BaRKlM3DyG81y/xWTsE6gZiv89F/3pHe2BqX2H4JbiB8HNVlWWtplzgATAE5IDSdwChdeuWLDTQzJ92Lglw3ZA=="],@@ -343,6 +361,8 @@"@tauri-apps/plugin-opener": ["@tauri-apps/[email protected]", "", { "dependencies": { "@tauri-apps/api": "^2.8.0" } }, "sha512-CCcUltXMOfUEArbf3db3kCE7Ggy1ExBEBl51Ko2ODJ6GDYHRp1nSNlQm5uNCFY5k7/ufaK5Ib3Du/Zir19IYQQ=="],+ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.9" } }, "sha512-KQ571yULOdWJiMH+RIWIOZ7B2RXQGpL1YQrBtLIV3FqDcCu6FsbFUBwhdKUlCKUpS3PJDsHlJ1QKlpxoVR+xtw=="],+"@types/culori": ["@types/[email protected]", "", {}, "sha512-43M51r/22CjhbOXyGT361GZ9vncSVQ39u62x5eJdBQFviI8zWp2X5jzqg7k4M6PVgDQAClpy2bUe2dtwEgEDVQ=="],"@types/estree": ["@types/[email protected]", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],@@ -397,14 +417,22 @@"acorn": ["[email protected]", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="],+ "agentfmt": ["[email protected]", "", { "dependencies": { "picocolors": "^1.1.1" } }, "sha512-BVSZr8ovigxjYewuBx42Ep4RJj00HURaQYUQ+id41sgb7r0PMUSEWsnD/+h96xj6t6v2WVyPuGPH0K6RtjftKQ=="],+"aria-hidden": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],+ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg=="],+"canvaskit-wasm": ["[email protected]", "", { "dependencies": { "@webgpu/types": "0.1.21" } }, "sha512-Od2o+ZmoEw9PBdN/yCGvzfu0WVqlufBPEWNG452wY7E9aT8RBE+ChpZF526doOlg7zumO4iCS+RAeht4P0Gbpw=="],"chokidar": ["[email protected]", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="],+ "citty": ["[email protected]", "", { "dependencies": { "consola": "^3.2.3" } }, "sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ=="],+"confbox": ["[email protected]", "", {}, "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ=="],+ "consola": ["[email protected]", "", {}, "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA=="],+"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],"culori": ["[email protected]", "", {}, "sha512-1+BhOB8ahCn4O0cep0Sh2l9KCOfOdY+BXJnKMHFFzDEouSr/el18QwXEMRlOj9UY5nCeA8UN3a/82rUWRBeyBw=="],diff --git a/packages/cli/package.json b/packages/cli/package.jsonnew file mode 100644index 000000000..3193d2203--- /dev/null+++ b/packages/cli/package.json@@ -0,0 +1,17 @@+{+ "name": "@open-pencil/cli",+ "version": "0.1.0",+ "type": "module",+ "bin": {+ "open-pencil": "./src/index.ts"+ },+ "devDependencies": {+ "@types/bun": "^1.2.9"+ },+ "dependencies": {+ "@open-pencil/core": "workspace:*",+ "agentfmt": "^0.1.3",+ "canvaskit-wasm": "^0.40.0",+ "citty": "^0.1.6"+ }+}diff --git a/packages/cli/src/commands/export.ts b/packages/cli/src/commands/export.tsnew file mode 100644index 000000000..0c3117279--- /dev/null+++ b/packages/cli/src/commands/export.ts@@ -0,0 +1,67 @@+import { defineCommand } from 'citty'+import { basename, extname, resolve } from 'node:path'++import { loadDocument, loadFonts, exportNodes, exportThumbnail } from '../headless'+import { ok, printError } from '../format'+import type { ExportFormat } from '@open-pencil/core'++export default defineCommand({+ meta: { description: 'Export a .fig file to PNG, JPG, or WEBP' },+ args: {+ file: { type: 'positional', description: '.fig file path', required: true },+ output: { type: 'string', alias: 'o', description: 'Output file path (default: <name>.<format>)' },+ format: { type: 'string', alias: 'f', description: 'Export format: png, jpg, webp (default: png)', default: 'png' },+ scale: { type: 'string', alias: 's', description: 'Export scale (default: 1)', default: '1' },+ quality: { type: 'string', alias: 'q', description: 'Quality 0-100 for JPG/WEBP (default: 90)' },+ page: { type: 'string', description: 'Page name (default: first page)' },+ node: { type: 'string', description: 'Node ID to export (default: all top-level nodes)' },+ thumbnail: { type: 'boolean', description: 'Export page thumbnail instead of full render' },+ width: { type: 'string', description: 'Thumbnail width (default: 1920)', default: '1920' },+ height: { type: 'string', description: 'Thumbnail height (default: 1080)', default: '1080' }+ },+ async run({ args }) {+ const format = args.format.toUpperCase() as ExportFormat+ if (!['PNG', 'JPG', 'WEBP'].includes(format)) {+ printError(`Invalid format "${args.format}". Use png, jpg, or webp.`)+ process.exit(1)+ }++ const graph = await loadDocument(args.file)+ await loadFonts(graph)++ const pages = graph.getPages()+ const page = args.page+ ? pages.find((p) => p.name === args.page)+ : pages[0]++ if (!page) {+ printError(`Page "${args.page}" not found.`)+ process.exit(1)+ }++ const ext = format.toLowerCase() === 'jpg' ? 'jpg' : format.toLowerCase()+ const defaultName = basename(args.file, extname(args.file))+ const output = resolve(args.output ?? `${defaultName}.${ext}`)++ let data: Uint8Array | null++ if (args.thumbnail) {+ data = await exportThumbnail(graph, page.id, Number(args.width), Number(args.height))+ } else {+ const nodeIds = args.node ? [args.node] : page.childIds+ data = await exportNodes(graph, page.id, nodeIds, {+ scale: Number(args.scale),+ format,+ quality: args.quality ? Number(args.quality) : undefined+ })+ }++ if (!data) {+ printError('Nothing to export (empty page or no visible nodes).')+ process.exit(1)+ }++ await Bun.write(output, data)+ console.log(ok(`Exported ${output} (${(data.length / 1024).toFixed(1)} KB)`))+ }+})diff --git a/packages/cli/src/commands/find.ts b/packages/cli/src/commands/find.tsnew file mode 100644index 000000000..d2823cd61--- /dev/null+++ b/packages/cli/src/commands/find.ts@@ -0,0 +1,69 @@+import { defineCommand } from 'citty'++import { loadDocument } from '../headless'+import { fmtList, nodeToListItem, printError, bold } from '../format'+import type { SceneNode } from '@open-pencil/core'++export default defineCommand({+ meta: { description: 'Find nodes by name or type' },+ args: {+ file: { type: 'positional', description: '.fig file path', required: true },+ name: { type: 'string', description: 'Node name (partial match, case-insensitive)' },+ type: { type: 'string', description: 'Node type: FRAME, TEXT, RECTANGLE, INSTANCE, etc.' },+ page: { type: 'string', description: 'Page name (default: all pages)' },+ limit: { type: 'string', description: 'Max results (default: 100)', default: '100' },+ json: { type: 'boolean', description: 'Output as JSON' }+ },+ async run({ args }) {+ const graph = await loadDocument(args.file)+ const pages = graph.getPages()+ const max = Number(args.limit)+ const namePattern = args.name?.toLowerCase()+ const typeFilter = args.type?.toUpperCase()++ const results: SceneNode[] = []++ const searchPage = (pageNode: SceneNode) => {+ const walk = (id: string) => {+ if (results.length >= max) return+ const node = graph.getNode(id)+ if (!node) return+ const matchesName = !namePattern || node.name.toLowerCase().includes(namePattern)+ const matchesType = !typeFilter || node.type === typeFilter+ if (matchesName && matchesType) results.push(node)+ for (const childId of node.childIds) walk(childId)+ }+ for (const childId of pageNode.childIds) walk(childId)+ }++ if (args.page) {+ const page = pages.find((p) => p.name === args.page)+ if (!page) {+ printError(`Page "${args.page}" not found.`)+ process.exit(1)+ }+ searchPage(page)+ } else {+ for (const page of pages) searchPage(page)+ }++ if (args.json) {+ console.log(JSON.stringify(results.map((n) => ({+ id: n.id, name: n.name, type: n.type,+ width: Math.round(n.width), height: Math.round(n.height)+ })), null, 2))+ return+ }++ if (results.length === 0) {+ console.log('No nodes found.')+ return+ }++ console.log('')+ console.log(bold(` Found ${results.length} node${results.length > 1 ? 's' : ''}`))+ console.log('')+ console.log(fmtList(results.map(nodeToListItem)))+ console.log('')+ }+})diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.tsnew file mode 100644index 000000000..808380822--- /dev/null+++ b/packages/cli/src/commands/info.ts@@ -0,0 +1,58 @@+import { defineCommand } from 'citty'++import { loadDocument } from '../headless'+import { bold, fmtHistogram, fmtSummary, kv } from '../format'+import type { SceneNode } from '@open-pencil/core'++export default defineCommand({+ meta: { description: 'Show document info (pages, node counts, fonts)' },+ args: {+ file: { type: 'positional', description: '.fig file path', required: true },+ json: { type: 'boolean', description: 'Output as JSON' }+ },+ async run({ args }) {+ const graph = await loadDocument(args.file)+ const pages = graph.getPages()++ let totalNodes = 0+ const types: Record<string, number> = {}+ const fonts = new Set<string>()+ const pageCounts: Record<string, number> = {}++ for (const page of pages) {+ let pageCount = 0+ const walk = (id: string) => {+ const node = graph.getNode(id) as SceneNode | undefined+ if (!node) return+ totalNodes+++ pageCount+++ types[node.type] = (types[node.type] ?? 0) + 1+ if (node.fontFamily) fonts.add(node.fontFamily)+ for (const childId of node.childIds) walk(childId)+ }+ for (const childId of page.childIds) walk(childId)+ pageCounts[page.name] = pageCount+ }++ if (args.json) {+ console.log(JSON.stringify({ pages: pages.length, totalNodes, types, fonts: [...fonts].sort(), pageCounts }, null, 2))+ return+ }++ console.log('')+ console.log(bold(` ${pages.length} pages, ${totalNodes} nodes`))+ console.log('')++ const pageItems = Object.entries(pageCounts).map(([label, value]) => ({ label, value }))+ console.log(fmtHistogram(pageItems, { unit: 'nodes' }))++ console.log('')+ console.log(fmtSummary(types))++ if (fonts.size > 0) {+ console.log('')+ console.log(kv('Fonts', [...fonts].sort().join(', ')))+ }+ console.log('')+ }+})diff --git a/packages/cli/src/commands/tree.ts b/packages/cli/src/commands/tree.tsnew file mode 100644index 000000000..7ef634878--- /dev/null+++ b/packages/cli/src/commands/tree.ts@@ -0,0 +1,63 @@+import { defineCommand } from 'citty'++import { loadDocument } from '../headless'+import { fmtTree, nodeToTreeNode, printError, entity, formatType } from '../format'+import type { SceneNode } from '@open-pencil/core'++export default defineCommand({+ meta: { description: 'Print the node tree' },+ args: {+ file: { type: 'positional', description: '.fig file path', required: true },+ page: { type: 'string', description: 'Page name (default: first page)' },+ depth: { type: 'string', description: 'Max depth (default: unlimited)' },+ json: { type: 'boolean', description: 'Output as JSON' }+ },+ async run({ args }) {+ const graph = await loadDocument(args.file)+ const pages = graph.getPages()+ const maxDepth = args.depth ? Number(args.depth) : Infinity++ const page = args.page+ ? pages.find((p) => p.name === args.page)+ : pages[0]++ if (!page) {+ printError(`Page "${args.page}" not found. Available: ${pages.map((p) => p.name).join(', ')}`)+ process.exit(1)+ }++ if (args.json) {+ const buildJson = (id: string, depth: number): unknown => {+ const node = graph.getNode(id)+ if (!node) return null+ const result: Record<string, unknown> = {+ id: node.id,+ name: node.name,+ type: node.type,+ x: Math.round(node.x),+ y: Math.round(node.y),+ width: Math.round(node.width),+ height: Math.round(node.height)+ }+ if (node.childIds.length > 0 && depth < maxDepth) {+ result.children = node.childIds.map((cid) => buildJson(cid, depth + 1)).filter(Boolean)+ }+ return result+ }+ console.log(JSON.stringify(page.childIds.map((id) => buildJson(id, 0)), null, 2))+ return+ }++ const root = {+ header: entity(formatType(page.type), page.name, page.id),+ children: page.childIds+ .map((id) => graph.getNode(id))+ .filter((n): n is SceneNode => n !== undefined)+ .map((child) => nodeToTreeNode(graph, child, maxDepth))+ }++ console.log('')+ console.log(fmtTree(root, { maxDepth }))+ console.log('')+ }+})diff --git a/packages/cli/src/format.ts b/packages/cli/src/format.tsnew file mode 100644index 000000000..c71d22b7e--- /dev/null+++ b/packages/cli/src/format.ts@@ -0,0 +1,156 @@+import {+ ok,+ fail,+ dim,+ bold,+ cyan,+ box as fmtBox,+ entity,+ kv,+ tree as fmtTree,+ list as fmtList,+ node as fmtNode,+ histogram as fmtHistogram,+ summary as fmtSummary+} from 'agentfmt'+import type { TreeNode, ListItem, NodeData } from 'agentfmt'+import type { SceneNode, SceneGraph } from '@open-pencil/core'++export { ok, fail, dim, bold, cyan, entity, kv, fmtTree, fmtList, fmtNode, fmtHistogram, fmtSummary }++const TYPE_LABELS: Record<string, string> = {+ FRAME: 'frame',+ RECTANGLE: 'rect',+ ROUNDED_RECTANGLE: 'rounded-rect',+ ELLIPSE: 'ellipse',+ TEXT: 'text',+ COMPONENT: 'component',+ COMPONENT_SET: 'component-set',+ INSTANCE: 'instance',+ GROUP: 'group',+ VECTOR: 'vector',+ LINE: 'line',+ POLYGON: 'polygon',+ STAR: 'star',+ BOOLEAN_OPERATION: 'boolean',+ SECTION: 'section',+ CANVAS: 'page'+}++export function formatType(type: string): string {+ return TYPE_LABELS[type] ?? type.toLowerCase()+}++export function formatBox(node: SceneNode): string {+ return fmtBox(Math.round(node.width), Math.round(node.height), Math.round(node.x), Math.round(node.y))+}++function formatFill(node: SceneNode): string | null {+ if (!node.fills.length) return null+ const solid = node.fills.find((f) => f.type === 'SOLID' && f.visible)+ if (!solid || solid.type !== 'SOLID') return null+ const { r, g, b } = solid.color+ const hex = '#' + [r, g, b].map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('')+ return solid.opacity < 1 ? `${hex} ${Math.round(solid.opacity * 100)}%` : hex+}++function formatStroke(node: SceneNode): string | null {+ if (!node.strokes.length) return null+ const s = node.strokes[0]!+ const { r, g, b } = s.color+ const hex = '#' + [r, g, b].map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('')+ return `${hex} ${s.weight}px`+}++export function nodeToData(node: SceneNode): NodeData {+ return {+ type: formatType(node.type),+ name: node.name,+ id: node.id,+ width: Math.round(node.width),+ height: Math.round(node.height),+ x: Math.round(node.x),+ y: Math.round(node.y)+ }+}++export function nodeDetails(node: SceneNode): Record<string, unknown> {+ const details: Record<string, unknown> = {}++ const fill = formatFill(node)+ if (fill) details.fill = fill++ const stroke = formatStroke(node)+ if (stroke) details.stroke = stroke++ if (node.cornerRadius) details.radius = `${node.cornerRadius}px`++ if (node.effects.length > 0) {+ details.effects = node.effects+ .map((e) => {+ if (e.type === 'DROP_SHADOW') return `shadow(${e.radius}px)`+ if (e.type === 'INNER_SHADOW') return `inner-shadow(${e.radius}px)`+ if (e.type === 'LAYER_BLUR') return `blur(${e.radius}px)`+ if (e.type === 'BACKGROUND_BLUR') return `backdrop-blur(${e.radius}px)`+ return e.type.toLowerCase()+ })+ .join(', ')+ }++ if (node.rotation) details.rotate = `${Math.round(node.rotation)}°`+ if (node.opacity < 1) details.opacity = node.opacity+ if (node.blendMode !== 'PASS_THROUGH' && node.blendMode !== 'NORMAL') {+ details.blend = node.blendMode.toLowerCase().replace(/_/g, '-')+ }+ if (node.clipsContent) details.overflow = 'hidden'+ if (!node.visible) details.visible = false+ if (node.locked) details.locked = true++ if (node.fontFamily) {+ details.font = `${node.fontSize}px ${node.fontFamily}`+ }++ if (node.layoutMode !== 'NONE') {+ let layout = node.layoutMode.toLowerCase()+ if (node.layoutWrap === 'WRAP') layout += ' wrap'+ if (node.itemSpacing) layout += ` gap=${node.itemSpacing}`+ details.layout = layout+ }++ if (node.componentId) details.componentId = node.componentId++ return details+}++export function nodeToTreeNode(graph: SceneGraph, node: SceneNode, maxDepth: number, depth = 0): TreeNode {+ const treeNode: TreeNode = {+ header: entity(formatType(node.type), node.name, node.id),+ details: nodeDetails(node)+ }++ if (depth < maxDepth && node.childIds.length > 0) {+ treeNode.children = node.childIds+ .map((id) => graph.getNode(id))+ .filter((n): n is SceneNode => n !== undefined)+ .map((child) => nodeToTreeNode(graph, child, maxDepth, depth + 1))+ }++ return treeNode+}++export function nodeToListItem(node: SceneNode): ListItem {+ const details = nodeDetails(node)+ return {+ header: entity(formatType(node.type), node.name, node.id),+ details: Object.keys(details).length > 0 ? details : undefined+ }+}++export function formatNodeSingle(node: SceneNode): string {+ return fmtNode(nodeToData(node), nodeDetails(node))+}++export function printError(error: unknown): void {+ const message = error instanceof Error ? error.message : String(error)+ console.error(fail(message))+}diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.tsnew file mode 100644index 000000000..323e470bf--- /dev/null+++ b/packages/cli/src/headless.ts@@ -0,0 +1,76 @@+import CanvasKitInit from 'canvaskit-wasm/full'+import type { CanvasKit } from 'canvaskit-wasm'+import {+ parseFigFile,+ SceneGraph,+ SkiaRenderer,+ computeAllLayouts,+ loadFont,+ renderNodesToImage,+ renderThumbnail+} from '@open-pencil/core'+import type { ExportFormat } from '@open-pencil/core'++let ck: CanvasKit | null = null++export async function initCanvasKit(): Promise<CanvasKit> {+ if (ck) return ck+ const ckPath = import.meta.resolve('canvaskit-wasm/full')+ const binDir = new URL('.', ckPath).pathname+ ck = await CanvasKitInit({+ locateFile: (file) => binDir + file+ })+ return ck+}++export async function loadDocument(filePath: string): Promise<SceneGraph> {+ const data = await Bun.file(filePath).arrayBuffer()+ const graph = await parseFigFile(data)+ computeAllLayouts(graph)+ return graph+}++export async function loadFonts(graph: SceneGraph): Promise<void> {+ const families = new Set<string>()+ for (const node of graph.getAllNodes()) {+ if (node.fontFamily) families.add(node.fontFamily)+ }+ for (const family of families) {+ await loadFont(family)+ }+}++function createRenderer(ckInstance: CanvasKit, width: number, height: number): SkiaRenderer {+ const surface = ckInstance.MakeSurface(width, height)!+ const renderer = new SkiaRenderer(ckInstance, surface)+ renderer.viewportWidth = width+ renderer.viewportHeight = height+ renderer.dpr = 1+ return renderer+}++export async function exportNodes(+ graph: SceneGraph,+ pageId: string,+ nodeIds: string[],+ options: { scale?: number; format?: ExportFormat; quality?: number }+): Promise<Uint8Array | null> {+ const ckInstance = await initCanvasKit()+ const renderer = createRenderer(ckInstance, 1, 1)+ return renderNodesToImage(ckInstance, renderer, graph, pageId, nodeIds, {+ scale: options.scale ?? 1,+ format: options.format ?? 'PNG',+ quality: options.quality+ })+}++export async function exportThumbnail(+ graph: SceneGraph,+ pageId: string,+ width: number,+ height: number+): Promise<Uint8Array | null> {+ const ckInstance = await initCanvasKit()+ const renderer = createRenderer(ckInstance, width, height)+ return renderThumbnail(ckInstance, renderer, graph, pageId, width, height)+}diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsnew file mode 100644index 000000000..19a8e9059--- /dev/null+++ b/packages/cli/src/index.ts@@ -0,0 +1,23 @@+#!/usr/bin/env bun+import { defineCommand, runMain } from 'citty'++import exportCmd from './commands/export'+import info from './commands/info'+import find from './commands/find'+import tree from './commands/tree'++const main = defineCommand({+ meta: {+ name: 'open-pencil',+ description: 'OpenPencil CLI — inspect, export, and lint .fig design files',+ version: '0.1.0'+ },+ subCommands: {+ export: exportCmd,+ info,+ find,+ tree+ }+})++runMain(main)diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.jsonnew file mode 100644index 000000000..b565a4097--- /dev/null+++ b/packages/cli/tsconfig.json@@ -0,0 +1,13 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "skipLibCheck": true,+ "declaration": true,+ "outDir": "dist",+ "rootDir": "src"+ },+ "include": ["src", "../core/src"]+}diff --git a/packages/core/src/fonts.ts b/packages/core/src/fonts.tsindex bce9df6cb..3f1b4df7b 100644--- a/packages/core/src/fonts.ts+++ b/packages/core/src/fonts.ts@@ -19,7 +19,7 @@ export function getFontProvider(): TypefaceFontProvider | null {}export async function queryFonts(): Promise<FontInfo[]> {- if (!window.queryLocalFonts) return []+ if (typeof window === 'undefined' || !window.queryLocalFonts) return []try {const fonts = await window.queryLocalFonts()const seen = new Set<string>()@@ -59,8 +59,8 @@ export async function loadFont(family: string, style = 'Regular'): Promise<Arrayreturn cached}- // Try local font access API first- if (window.queryLocalFonts) {+ // Try local font access API first (browser only)+ if (typeof window !== 'undefined' && window.queryLocalFonts) {try {const fonts = await window.queryLocalFonts()const match =@@ -105,6 +105,7 @@ function registerFontInCanvasKit(family: string, data: ArrayBuffer) {}function registerFontInBrowser(family: string, style: string, data: ArrayBuffer) {+ if (typeof document === 'undefined') returnconst weight = styleToWeight(style)const italic = style.toLowerCase().includes('italic') ? 'italic' : 'normal'const face = new FontFace(family, data, {diff --git a/packages/core/src/global.d.ts b/packages/core/src/global.d.tsnew file mode 100644index 000000000..587425001--- /dev/null+++ b/packages/core/src/global.d.ts@@ -0,0 +1,11 @@+interface FontData {+ family: string+ fullName: string+ postscriptName: string+ style: string+ blob(): Promise<Blob>+}++interface Window {+ queryLocalFonts?(): Promise<FontData[]>+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex ce8f2aa60..7669b9ce4 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -60,7 +60,7 @@ export {prefetchFigmaSchema} from './clipboard'-export { readFigFile } from './kiwi/fig-file'+export { readFigFile, parseFigFile } from './kiwi/fig-file'export { importNodeChanges } from './kiwi/fig-import'export {initCodec,diff --git a/packages/core/src/kiwi/codec.ts b/packages/core/src/kiwi/codec.tsindex 68116b8bc..2ae170eb6 100644--- a/packages/core/src/kiwi/codec.ts+++ b/packages/core/src/kiwi/codec.ts@@ -11,8 +11,8 @@ import { decompress as zstdDecompress } from 'fzstd'import { parseColor } from '../color'import { compileSchema, encodeBinarySchema } from './kiwi-schema'-import { isZstdCompressed, getKiwiMessageType } from './protocol.ts'-import figmaSchema from './schema.ts'+import { isZstdCompressed, getKiwiMessageType } from './protocol'+import figmaSchema from './schema'import type { Schema } from './kiwi-schema'diff --git a/packages/core/src/render-image.ts b/packages/core/src/render-image.tsindex ac731e1db..ca2cac8ec 100644--- a/packages/core/src/render-image.ts+++ b/packages/core/src/render-image.ts@@ -33,6 +33,17 @@ function computeContentBounds(return { minX, minY, maxX, maxY }}+function ckImageFormat(ck: CanvasKit, format: ExportFormat) {+ switch (format) {+ case 'JPG':+ return ck.ImageFormat.JPEG+ case 'WEBP':+ return ck.ImageFormat.WEBP+ default:+ return ck.ImageFormat.PNG+ }+}+function renderToSurface(ck: CanvasKit,renderer: SkiaRenderer,@@ -40,6 +51,8 @@ function renderToSurface(pageId: string,width: number,height: number,+ format: ExportFormat,+ quality: number,setup: (canvas: import('canvaskit-wasm').Canvas) => void): Uint8Array | null {const surface = ck.MakeSurface(width, height)@@ -51,7 +64,7 @@ function renderToSurface(renderer.renderSceneToCanvas(canvas, graph, pageId)surface.flush()const image = surface.makeImageSnapshot()- const encoded = image.encodeToBytes(ck.ImageFormat.PNG, 100)+ const encoded = image.encodeToBytes(ckImageFormat(ck, format), quality)image.delete()return encoded ? new Uint8Array(encoded) : null} finally {@@ -59,53 +72,14 @@ function renderToSurface(}}-function mimeForFormat(format: ExportFormat): string {- switch (format) {- case 'JPG':- return 'image/jpeg'- case 'WEBP':- return 'image/webp'- default:- return 'image/png'- }-}--async function reencodeImage(- pngBytes: Uint8Array,- format: ExportFormat,- quality: number-): Promise<Uint8Array> {- if (format === 'PNG') return pngBytes-- const blob = new Blob([new Uint8Array(pngBytes)], { type: 'image/png' })- const bitmap = await createImageBitmap(blob)- const canvas = new OffscreenCanvas(bitmap.width, bitmap.height)- const ctx = canvas.getContext('2d')- if (!ctx) return pngBytes-- if (format === 'JPG') {- ctx.fillStyle = '#ffffff'- ctx.fillRect(0, 0, bitmap.width, bitmap.height)- }-- ctx.drawImage(bitmap, 0, 0)- bitmap.close()-- const outBlob = await canvas.convertToBlob({- type: mimeForFormat(format),- quality: quality / 100- })- return new Uint8Array(await outBlob.arrayBuffer())-}--export async function renderNodesToImage(+export function renderNodesToImage(ck: CanvasKit,renderer: SkiaRenderer,graph: SceneGraph,pageId: string,nodeIds: string[],options: RenderOptions-): Promise<Uint8Array | null> {+): Uint8Array | null {const bounds = computeContentBounds(graph, nodeIds)if (!bounds) return null@@ -117,15 +91,12 @@ export async function renderNodesToImage(const pixelH = Math.ceil(contentH * options.scale)if (pixelW <= 0 || pixelH <= 0) return null- const png = renderToSurface(ck, renderer, graph, pageId, pixelW, pixelH, (canvas) => {+ const quality = options.quality ?? (options.format === 'PNG' ? 100 : 90)+ return renderToSurface(ck, renderer, graph, pageId, pixelW, pixelH, options.format, quality, (canvas) => {canvas.clear(ck.TRANSPARENT)canvas.scale(options.scale, options.scale)canvas.translate(-bounds.minX, -bounds.minY)})- if (!png) return null-- const quality = options.quality ?? (options.format === 'PNG' ? 100 : 90)- return reencodeImage(png, options.format, quality)}export function renderThumbnail(@@ -148,7 +119,7 @@ export function renderThumbnail(const scale = Math.min(width / contentW, height / contentH, 2)- return renderToSurface(ck, renderer, graph, pageId, width, height, (canvas) => {+ return renderToSurface(ck, renderer, graph, pageId, width, height, 'PNG', 100, (canvas) => {canvas.clear(ck.Color4f(renderer.pageColor.r, renderer.pageColor.g, renderer.pageColor.b, 1))const offsetX = (width - contentW * scale) / 2 - bounds.minX * scaleconst offsetY = (height - contentH * scale) / 2 - bounds.minY * scalediff --git a/packages/core/src/scene-graph.ts b/packages/core/src/scene-graph.tsindex ff3d8004f..026895d1e 100644--- a/packages/core/src/scene-graph.ts+++ b/packages/core/src/scene-graph.ts@@ -341,6 +341,10 @@ export class SceneGraph {return this.getChildren(this.rootId).filter((n) => n.type === 'CANVAS')}+ getAllNodes(): Iterable<SceneNode> {+ return this.nodes.values()+ }+getNode(id: string): SceneNode | undefined {return this.nodes.get(id)}diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.jsonindex 32f2561ce..4d835f41b 100644--- a/packages/core/tsconfig.json+++ b/packages/core/tsconfig.json@@ -5,6 +5,7 @@"moduleResolution": "bundler","strict": true,"skipLibCheck": true,+"declaration": true,"outDir": "dist","rootDir": "src"