AI-native design editor. Open-source Figma alternative.
refactor(kiwi): move FIG parse helpers
Danila Poyarkovd068237ee42f
diff --git a/bun.lock b/bun.lockindex 3e93b2c53..58c1ee9be 100644--- a/bun.lock+++ b/bun.lock@@ -180,6 +180,7 @@"name": "@open-pencil/kiwi","version": "0.13.2","dependencies": {+ "fflate": "^0.8.2","fzstd": "^0.1.1",},"devDependencies": {diff --git a/packages/core/src/kiwi/fig/parse/core.ts b/packages/core/src/kiwi/fig/parse/core.tsindex cc82d59a6..67de00a71 100644--- a/packages/core/src/kiwi/fig/parse/core.ts+++ b/packages/core/src/kiwi/fig/parse/core.ts@@ -1,158 +1,6 @@-import { unzipSync, inflateSync } from 'fflate'-import { decompress as zstdDecompress } from 'fzstd'--import { isZstdCompressed } from '@open-pencil/kiwi/fig'-import { decodeBinarySchema, compileSchema, ByteBuffer } from '@open-pencil/kiwi/schema-runtime'--import type { FigmaMessage, NodeChange } from '#core/kiwi/fig/codec'--/**- * Deduplicates pluginData/pluginRelaunchData entries on raw NodeChange objects.- * Some .fig files have millions of identical entries where only a small- * fraction are unique by full triple.- * Full-triple key (id+key+value) preserves multi-entry subsystems like OkHCL.- */-export function deduplicateNodeChangePluginData(nodeChanges: NodeChange[]): void {- for (const nc of nodeChanges) {- if (nc.pluginData && nc.pluginData.length > 1) {- const map = new Map<string, (typeof nc.pluginData)[number]>()- for (const entry of nc.pluginData) {- map.set(`${entry.pluginID}\0${entry.key}\0${entry.value}`, entry)- }- if (map.size < nc.pluginData.length) {- nc.pluginData = [...map.values()]- }- }- if (nc.pluginRelaunchData && nc.pluginRelaunchData.length > 1) {- const map = new Map<string, (typeof nc.pluginRelaunchData)[number]>()- for (const entry of nc.pluginRelaunchData) {- map.set(`${entry.pluginID}\0${entry.command}\0${entry.message}\0${entry.isDeleted}`, entry)- }- if (map.size < nc.pluginRelaunchData.length) {- nc.pluginRelaunchData = [...map.values()]- }- }- }-}--interface FigKiwiPayload {- schemaDeflated: Uint8Array- dataRaw: Uint8Array- version: number-}--interface CompiledKiwiSchema {- decodeMessage(data: Uint8Array): unknown-}--export function parseFigKiwiContainer(data: Uint8Array): FigKiwiPayload | null {- const header = new TextDecoder().decode(data.slice(0, 8))- if (header !== 'fig-kiwi') return null-- const view = new DataView(data.buffer, data.byteOffset, data.byteLength)- const version = view.getUint32(8, true)- let offset = 12-- const chunks: Uint8Array[] = []- while (offset < data.length) {- if (offset + 4 > data.length) break- const len = view.getUint32(offset, true)- offset += 4- if (offset + len > data.length) {- throw new Error(- `Corrupted .fig file: chunk at offset ${offset - 4} declares length ${len} but only ${data.length - offset} bytes remain`- )- }- chunks.push(data.slice(offset, offset + len))- offset += len- }- if (chunks.length < 2) return null-- const compressed = chunks[1]- let dataRaw: Uint8Array- if (isZstdCompressed(compressed)) {- dataRaw = zstdDecompress(compressed)- } else {- dataRaw = inflateSync(compressed)- }-- return { schemaDeflated: chunks[0], dataRaw, version }-}--export interface FigParseResult {- nodeChanges: NodeChange[]- blobs: Uint8Array[]- images: Array<[string, Uint8Array]>- figKiwiVersion: number- /** Deflated kiwi schema bytes from the original file (for roundtrip fidelity). */- figSchemaDeflated: Uint8Array-}--export function parseFigBuffer(buffer: ArrayBuffer): FigParseResult {- const zip = unzipSync(new Uint8Array(buffer), {- filter: (file) =>- file.name === 'canvas.fig' ||- file.name === 'canvas' ||- (file.name.startsWith('images/') && file.name !== 'images/')- })- const entries = Object.keys(zip)-- let canvasData: Uint8Array | null = null- for (const name of entries) {- if (name === 'canvas.fig' || name === 'canvas') {- canvasData = zip[name]- break- }- }- if (!canvasData) {- let maxSize = 0- for (const name of entries) {- const lower = name.toLowerCase()- if (lower.endsWith('.png') || lower.endsWith('.jpg') || lower.endsWith('.json')) continue- if (zip[name].byteLength > maxSize) {- maxSize = zip[name].byteLength- canvasData = zip[name]- }- }- }-- if (!canvasData) {- throw new Error(`No canvas data found in .fig file. Entries: ${entries.join(', ')}`)- }-- const payload = parseFigKiwiContainer(canvasData)- if (!payload) throw new Error('Invalid fig-kiwi container')-- const schemaBytes = inflateSync(payload.schemaDeflated)- const schema = decodeBinarySchema(new ByteBuffer(schemaBytes))- const compiled = compileSchema(schema) as CompiledKiwiSchema- const message = compiled.decodeMessage(payload.dataRaw) as FigmaMessage-- const nodeChanges = message.nodeChanges- if (!nodeChanges || nodeChanges.length === 0) {- throw new Error('No nodes found in .fig file')- }-- // Deduplicate before returning — critical for worker path where raw- // nodeChanges are serialized via postMessage before extractPluginData runs- deduplicateNodeChangePluginData(nodeChanges)-- const blobs: Uint8Array[] = (message.blobs ?? []).map((b) =>- b.bytes instanceof Uint8Array ? b.bytes : new Uint8Array(Object.values(b.bytes))- )-- const images: Array<[string, Uint8Array]> = []- for (const name of entries) {- if (name.startsWith('images/') && name !== 'images/') {- images.push([name.replace('images/', ''), zip[name]])- }- }-- return {- nodeChanges,- blobs,- images,- figKiwiVersion: payload.version,- figSchemaDeflated: payload.schemaDeflated- }-}+export {+ deduplicateNodeChangePluginData,+ parseFigKiwiContainer,+ parseFigBuffer+} from '@open-pencil/kiwi/fig/parse'+export type { FigParseResult } from '@open-pencil/kiwi/fig/parse'diff --git a/packages/kiwi/package.json b/packages/kiwi/package.jsonindex e6927020b..25ab7e16c 100644--- a/packages/kiwi/package.json+++ b/packages/kiwi/package.json@@ -27,6 +27,12 @@"bun": "./src/fig/codec.ts","import": "./dist/fig/codec.js","default": "./dist/fig/codec.js"+ },+ "./fig/parse": {+ "types": "./dist/src/fig/parse.d.ts",+ "bun": "./src/fig/parse.ts",+ "import": "./dist/fig/parse.js",+ "default": "./dist/fig/parse.js"}},"main": "./dist/index.js",@@ -54,6 +60,7 @@"provenance": true},"dependencies": {+ "fflate": "^0.8.2","fzstd": "^0.1.1"},"devDependencies": {diff --git a/packages/kiwi/scripts/smoke-dist.ts b/packages/kiwi/scripts/smoke-dist.tsindex 82f399645..05647c85d 100644--- a/packages/kiwi/scripts/smoke-dist.ts+++ b/packages/kiwi/scripts/smoke-dist.ts@@ -1,4 +1,5 @@import { getSchemaBytes, initCodec, isCodecReady } from '../dist/fig/codec.js'+import { parseFigKiwiContainer } from '../dist/fig/parse.js'import { figmaSchema, getKiwiMessageType, parseSchema, validateSchema } from '../dist/index.js'const schema = parseSchema(`@@ -22,3 +23,7 @@ await initCodec()if (!isCodecReady() || getSchemaBytes().length === 0) {throw new Error('Failed to initialize built FIG codec')}++if (parseFigKiwiContainer(new TextEncoder().encode('not-fig-kiwi')) !== null) {+ throw new Error('Failed to reject invalid FIG Kiwi container')+}diff --git a/packages/kiwi/src/fig/parse.ts b/packages/kiwi/src/fig/parse.tsnew file mode 100644index 000000000..3f4baeafd--- /dev/null+++ b/packages/kiwi/src/fig/parse.ts@@ -0,0 +1,163 @@+import { unzipSync, inflateSync } from 'fflate'+import { decompress as zstdDecompress } from 'fzstd'++import { decodeBinarySchema, compileSchema, ByteBuffer } from '../schema-runtime'+import type { FigmaMessage, NodeChange } from './codec'+import { isZstdCompressed } from './protocol'++export type { NodeChange } from './codec'++/**+ * Deduplicates pluginData/pluginRelaunchData entries on raw NodeChange objects.+ * Some .fig files have millions of identical entries where only a small+ * fraction are unique by full triple.+ * Full-triple key (id+key+value) preserves multi-entry subsystems like OkHCL.+ */+export function deduplicateNodeChangePluginData(nodeChanges: NodeChange[]): void {+ for (const nc of nodeChanges) {+ if (nc.pluginData && nc.pluginData.length > 1) {+ const map = new Map<string, (typeof nc.pluginData)[number]>()+ for (const entry of nc.pluginData) {+ map.set(`${entry.pluginID}\0${entry.key}\0${entry.value}`, entry)+ }+ if (map.size < nc.pluginData.length) {+ nc.pluginData = [...map.values()]+ }+ }+ if (nc.pluginRelaunchData && nc.pluginRelaunchData.length > 1) {+ const map = new Map<string, (typeof nc.pluginRelaunchData)[number]>()+ for (const entry of nc.pluginRelaunchData) {+ map.set(`${entry.pluginID}\0${entry.command}\0${entry.message}\0${entry.isDeleted}`, entry)+ }+ if (map.size < nc.pluginRelaunchData.length) {+ nc.pluginRelaunchData = [...map.values()]+ }+ }+ }+}++interface FigKiwiPayload {+ schemaDeflated: Uint8Array+ dataRaw: Uint8Array+ version: number+}++interface CompiledKiwiSchema {+ decodeMessage(data: Uint8Array): unknown+}++export function parseFigKiwiContainer(data: Uint8Array): FigKiwiPayload | null {+ const header = new TextDecoder().decode(data.slice(0, 8))+ if (header !== 'fig-kiwi') return null++ const view = new DataView(data.buffer, data.byteOffset, data.byteLength)+ const version = view.getUint32(8, true)+ let offset = 12++ const chunks: Uint8Array[] = []+ while (offset < data.length) {+ if (offset + 4 > data.length) break+ const len = view.getUint32(offset, true)+ offset += 4+ if (offset + len > data.length) {+ throw new Error(+ `Corrupted .fig file: chunk at offset ${offset - 4} declares length ${len} but only ${data.length - offset} bytes remain`+ )+ }+ chunks.push(data.slice(offset, offset + len))+ offset += len+ }+ if (chunks.length < 2) return null++ const compressed = chunks[1]+ let dataRaw: Uint8Array+ if (isZstdCompressed(compressed)) {+ dataRaw = zstdDecompress(compressed)+ } else {+ try {+ dataRaw = inflateSync(compressed)+ } catch {+ dataRaw = compressed+ }+ }++ return { schemaDeflated: chunks[0], dataRaw, version }+}++export interface FigParseResult {+ nodeChanges: NodeChange[]+ blobs: Uint8Array[]+ images: Array<[string, Uint8Array]>+ figKiwiVersion: number+ /** Deflated kiwi schema bytes from the original file (for roundtrip fidelity). */+ figSchemaDeflated: Uint8Array+}++export function parseFigBuffer(buffer: ArrayBuffer): FigParseResult {+ const zip = unzipSync(new Uint8Array(buffer), {+ filter: (file) =>+ file.name === 'canvas.fig' ||+ file.name === 'canvas' ||+ (file.name.startsWith('images/') && file.name !== 'images/')+ })+ const entries = Object.keys(zip)++ let canvasData: Uint8Array | null = null+ for (const name of entries) {+ if (name === 'canvas.fig' || name === 'canvas') {+ canvasData = zip[name]+ break+ }+ }+ if (!canvasData) {+ let maxSize = 0+ for (const name of entries) {+ const lower = name.toLowerCase()+ if (lower.endsWith('.png') || lower.endsWith('.jpg') || lower.endsWith('.json')) continue+ if (zip[name].byteLength > maxSize) {+ maxSize = zip[name].byteLength+ canvasData = zip[name]+ }+ }+ }++ if (!canvasData) {+ throw new Error(`No canvas data found in .fig file. Entries: ${entries.join(', ')}`)+ }++ const payload = parseFigKiwiContainer(canvasData)+ if (!payload) throw new Error('Invalid fig-kiwi container')++ const schemaBytes = inflateSync(payload.schemaDeflated)+ const schema = decodeBinarySchema(new ByteBuffer(schemaBytes))+ const compiled = compileSchema(schema) as CompiledKiwiSchema+ const message = compiled.decodeMessage(payload.dataRaw) as FigmaMessage++ const nodeChanges = message.nodeChanges+ if (!nodeChanges || nodeChanges.length === 0) {+ throw new Error('No nodes found in .fig file')+ }++ // Deduplicate before returning — critical for worker path where raw+ // nodeChanges are serialized via postMessage before extractPluginData runs+ deduplicateNodeChangePluginData(nodeChanges)++ const blobs: Uint8Array[] = (message.blobs ?? []).map((b) =>+ b.bytes instanceof Uint8Array ? b.bytes : new Uint8Array(Object.values(b.bytes))+ )++ const images: Array<[string, Uint8Array]> = []+ for (const name of entries) {+ if (name.startsWith('images/') && name !== 'images/') {+ images.push([name.replace('images/', ''), zip[name]])+ }+ }++ return {+ nodeChanges,+ blobs,+ images,+ figKiwiVersion: payload.version,+ figSchemaDeflated: payload.schemaDeflated+ }+}diff --git a/packages/kiwi/tests/parse.test.ts b/packages/kiwi/tests/parse.test.tsnew file mode 100644index 000000000..138070889--- /dev/null+++ b/packages/kiwi/tests/parse.test.ts@@ -0,0 +1,35 @@+import { describe, expect, test } from 'bun:test'++import {+ deduplicateNodeChangePluginData,+ parseFigKiwiContainer,+ type NodeChange+} from '../src/fig/parse'++describe('Figma FIG parse helpers', () => {+ test('rejects non fig-kiwi containers', () => {+ expect(parseFigKiwiContainer(new TextEncoder().encode('not-fig-kiwi'))).toBeNull()+ })++ test('deduplicates plugin data entries by full triple', () => {+ const changes: NodeChange[] = [+ {+ pluginData: [+ { pluginID: 'plugin', key: 'a', value: '1' },+ { pluginID: 'plugin', key: 'a', value: '1' },+ { pluginID: 'plugin', key: 'a', value: '2' }+ ],+ pluginRelaunchData: [+ { pluginID: 'plugin', command: 'run', message: 'Run', isDeleted: false },+ { pluginID: 'plugin', command: 'run', message: 'Run', isDeleted: false },+ { pluginID: 'plugin', command: 'run', message: 'Gone', isDeleted: true }+ ]+ }+ ]++ deduplicateNodeChangePluginData(changes)++ expect(changes[0]?.pluginData).toHaveLength(2)+ expect(changes[0]?.pluginRelaunchData).toHaveLength(2)+ })+})diff --git a/packages/kiwi/tsdown.config.ts b/packages/kiwi/tsdown.config.tsindex 294db9078..eb538a96d 100644--- a/packages/kiwi/tsdown.config.ts+++ b/packages/kiwi/tsdown.config.ts@@ -20,7 +20,8 @@ export default defineConfig({index: './src/index.ts','schema-runtime': './src/schema-runtime/index.ts',fig: './src/fig/index.ts',- 'fig/codec': './src/fig/codec.ts'+ 'fig/codec': './src/fig/codec.ts',+ 'fig/parse': './src/fig/parse.ts'},plugins: [rawText()],platform: 'neutral',