AI-native design editor. Open-source Figma alternative.
refactor(kiwi): split schema text from runtime
Danila Poyarkov54310308dc6f
diff --git a/AGENTS.md b/AGENTS.mdindex 94314f781..0a1aed874 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -268,7 +268,7 @@ OpenPencil follows a Reka UI-inspired component namespace structure:- No module-level mutable state in components — use the editor store- Prefer `tw-animate-css` for animations — don't hand-write `<style>` transition keyframes- No duplicated component logic — if two components share data (icon maps, util functions, constants), export from one place and import in both-- `packages/core/src/kiwi/kiwi-schema/` is vendored — don't modify+- `packages/core/src/kiwi/schema-runtime/` contains the vendored Kiwi codec runtime; keep runtime changes minimal and prefer wrappers/helpers for project-specific validation- Core code must guard browser APIs: `typeof window !== 'undefined'`, `typeof document === 'undefined'`- Constants in `src/constants.ts` — no magic numbers in components or composablesdiff --git a/oxlint.json b/oxlint.jsonindex 49e4c8c58..cda2b9241 100644--- a/oxlint.json+++ b/oxlint.json@@ -415,7 +415,7 @@},{"files": [- "**/kiwi/kiwi-schema/**"+ "**/kiwi/schema-runtime/**"],"rules": {"typescript/no-explicit-any": "off",diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.tsindex 909215c6c..c9c3bc635 100644--- a/packages/core/src/clipboard.ts+++ b/packages/core/src/clipboard.ts@@ -4,7 +4,7 @@ import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/binary/codeimport type { NodeChange as KiwiNodeChange } from './kiwi/binary/codec'import { populateAndApplyOverrides } from './kiwi/instance-overrides'import type { InstanceNodeChange } from './kiwi/instance-overrides'-import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi/kiwi-schema'+import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi/schema-runtime'import { nodeChangeToProps, sortChildren } from './kiwi/node-change/convert'import {sceneNodeToKiwi,diff --git a/packages/core/src/global.d.ts b/packages/core/src/global.d.tsindex e6d75afed..7eda4fa08 100644--- a/packages/core/src/global.d.ts+++ b/packages/core/src/global.d.ts@@ -22,3 +22,8 @@ declare module '*.md' {const content: stringexport default content}++declare module '*?raw' {+ const content: string+ export default content+}diff --git a/packages/core/src/kiwi/binary/codec.ts b/packages/core/src/kiwi/binary/codec.tsindex 14a28325d..0b3fa19cf 100644--- a/packages/core/src/kiwi/binary/codec.ts+++ b/packages/core/src/kiwi/binary/codec.ts@@ -10,7 +10,7 @@import { decompress as zstdDecompress } from 'fzstd'import { parseColor } from '#core/color'-import { compileSchema, encodeBinarySchema } from '#core/kiwi/kiwi-schema'+import { compileSchema, encodeBinarySchema } from '#core/kiwi/schema-runtime'import { isZstdCompressed, getKiwiMessageType } from './protocol'import figmaSchema from './schema'diff --git a/packages/core/src/kiwi/binary/schema.ts b/packages/core/src/kiwi/binary/schema/fig.kiwisimilarity index 99%rename from packages/core/src/kiwi/binary/schema.tsrename to packages/core/src/kiwi/binary/schema/fig.kiwiindex 7095d4b21..393dcb833 100644--- a/packages/core/src/kiwi/binary/schema.ts+++ b/packages/core/src/kiwi/binary/schema/fig.kiwi@@ -1,7 +1,3 @@-/* eslint-disable max-lines -- generated kiwi schema definition */-import { parseSchema } from '#core/kiwi/kiwi-schema'--const schemaText = `package Fig;enum MessageType {@@ -905,7 +901,9 @@ message Glyph {float fontSize = 4;uint firstCharacter = 5;float advance = 6;- float rotation = 7;+ uint[] emojiCodePoints = 7;+ EmojiImageSet emojiImageSet = 8;+ float rotation = 9;}message Decoration {@@ -1537,8 +1535,8 @@ message NodeChange {float gridColumnGap = 438;GridTrackSize[] gridColumnSizes = 474;GridTrackSize[] gridRowSizes = 475;- StackWrap stackWrap = 476;- float stackCounterSpacing = 477;+ StackWrap stackWrap = 323;+ float stackCounterSpacing = 324;}message VideoPlayback {@@ -2395,6 +2393,3 @@ enum ARIARole {ALERTDIALOG = 80;DIALOG = 81;}-`--export default parseSchema(schemaText)diff --git a/packages/core/src/kiwi/binary/schema/index.ts b/packages/core/src/kiwi/binary/schema/index.tsnew file mode 100644index 000000000..5785d9b73--- /dev/null+++ b/packages/core/src/kiwi/binary/schema/index.ts@@ -0,0 +1,8 @@+import { parseSchema, validateSchema } from '#core/kiwi/schema-runtime'++import schemaText from './fig.kiwi?raw'++const schema = parseSchema(schemaText)+validateSchema(schema)++export default schemadiff --git a/packages/core/src/kiwi/fig/parse/core.ts b/packages/core/src/kiwi/fig/parse/core.tsindex f5fbed11a..dc5d5d884 100644--- a/packages/core/src/kiwi/fig/parse/core.ts+++ b/packages/core/src/kiwi/fig/parse/core.ts@@ -3,7 +3,7 @@ import { decompress as zstdDecompress } from 'fzstd'import type { FigmaMessage, NodeChange } from '#core/kiwi/binary/codec'import { isZstdCompressed } from '#core/kiwi/binary/protocol'-import { decodeBinarySchema, compileSchema, ByteBuffer } from '#core/kiwi/kiwi-schema'+import { decodeBinarySchema, compileSchema, ByteBuffer } from '#core/kiwi/schema-runtime'/*** Deduplicates pluginData/pluginRelaunchData entries on raw NodeChange objects.diff --git a/packages/core/src/kiwi/kiwi-schema/bb.ts b/packages/core/src/kiwi/schema-runtime/bb.tssimilarity index 100%rename from packages/core/src/kiwi/kiwi-schema/bb.tsrename to packages/core/src/kiwi/schema-runtime/bb.tsdiff --git a/packages/core/src/kiwi/kiwi-schema/binary.ts b/packages/core/src/kiwi/schema-runtime/binary.tssimilarity index 100%rename from packages/core/src/kiwi/kiwi-schema/binary.tsrename to packages/core/src/kiwi/schema-runtime/binary.tsdiff --git a/packages/core/src/kiwi/kiwi-schema/index.ts b/packages/core/src/kiwi/schema-runtime/index.tssimilarity index 68%rename from packages/core/src/kiwi/kiwi-schema/index.tsrename to packages/core/src/kiwi/schema-runtime/index.tsindex 7d45da2f9..ac279b743 100644--- a/packages/core/src/kiwi/kiwi-schema/index.ts+++ b/packages/core/src/kiwi/schema-runtime/index.ts@@ -3,3 +3,4 @@ export { ByteBuffer } from './bb'export { compileSchema } from './js'export { decodeBinarySchema, encodeBinarySchema } from './binary'export { parseSchema } from './parser'+export { validateSchema, expectFieldNumber, expectEnumValue, findDefinition, findField } from './validate'diff --git a/packages/core/src/kiwi/kiwi-schema/js.ts b/packages/core/src/kiwi/schema-runtime/js.tssimilarity index 100%rename from packages/core/src/kiwi/kiwi-schema/js.tsrename to packages/core/src/kiwi/schema-runtime/js.tsdiff --git a/packages/core/src/kiwi/kiwi-schema/parser.ts b/packages/core/src/kiwi/schema-runtime/parser.tssimilarity index 100%rename from packages/core/src/kiwi/kiwi-schema/parser.tsrename to packages/core/src/kiwi/schema-runtime/parser.tsdiff --git a/packages/core/src/kiwi/kiwi-schema/schema.ts b/packages/core/src/kiwi/schema-runtime/schema.tssimilarity index 100%rename from packages/core/src/kiwi/kiwi-schema/schema.tsrename to packages/core/src/kiwi/schema-runtime/schema.tsdiff --git a/packages/core/src/kiwi/kiwi-schema/util.ts b/packages/core/src/kiwi/schema-runtime/util.tssimilarity index 100%rename from packages/core/src/kiwi/kiwi-schema/util.tsrename to packages/core/src/kiwi/schema-runtime/util.tsdiff --git a/packages/core/src/kiwi/schema-runtime/validate.ts b/packages/core/src/kiwi/schema-runtime/validate.tsnew file mode 100644index 000000000..a28f3300d--- /dev/null+++ b/packages/core/src/kiwi/schema-runtime/validate.ts@@ -0,0 +1,86 @@+import type { Definition, Field, Schema } from './schema'+import { error, quote } from './util'++export function findDefinition(schema: Schema, name: string): Definition | null {+ return schema.definitions.find((definition) => definition.name === name) ?? null+}++export function findField(schema: Schema, definitionName: string, fieldName: string): Field | null {+ return findDefinition(schema, definitionName)?.fields.find((field) => field.name === fieldName) ?? null+}++export function expectFieldNumber(+ schema: Schema,+ definitionName: string,+ fieldName: string,+ expectedValue: number+): void {+ const field = findField(schema, definitionName, fieldName)+ if (!field) {+ throw new Error(`Missing field ${definitionName}.${fieldName}`)+ }+ if (field.value !== expectedValue) {+ throw new Error(+ `Expected ${definitionName}.${fieldName} to use field ${expectedValue}, got ${field.value}`+ )+ }+}++export function expectEnumValue(+ schema: Schema,+ enumName: string,+ memberName: string,+ expectedValue: number+): void {+ const definition = findDefinition(schema, enumName)+ if (!definition) {+ throw new Error(`Missing enum ${enumName}`)+ }+ if (definition.kind !== 'ENUM') {+ throw new Error(`${enumName} is a ${definition.kind}, not an enum`)+ }+ const field = definition.fields.find((candidate) => candidate.name === memberName)+ if (!field) {+ throw new Error(`Missing enum member ${enumName}.${memberName}`)+ }+ if (field.value !== expectedValue) {+ throw new Error(+ `Expected ${enumName}.${memberName} to use value ${expectedValue}, got ${field.value}`+ )+ }+}++export function validateSchema(schema: Schema): void {+ for (const definition of schema.definitions) {+ validateUniqueFieldNames(definition)+ if (definition.kind === 'ENUM') validateUniqueEnumValues(definition)+ }+}++function validateUniqueFieldNames(definition: Definition): void {+ const fieldsByName = new Set<string>()+ for (const field of definition.fields) {+ if (fieldsByName.has(field.name)) {+ error(+ `The field ${quote(field.name)} is defined twice in ${quote(definition.name)}`,+ field.line,+ field.column+ )+ }+ fieldsByName.add(field.name)+ }+}++function validateUniqueEnumValues(definition: Definition): void {+ const fieldsByValue = new Set<number>()+ for (const field of definition.fields) {+ if (fieldsByValue.has(field.value)) {+ error(+ `The enum value ${field.value} is used twice in ${quote(definition.name)}`,+ field.line,+ field.column+ )+ }+ fieldsByValue.add(field.value)+ }+}diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.jsonindex 716238992..7c9c2d41a 100644--- a/packages/core/tsconfig.json+++ b/packages/core/tsconfig.json@@ -4,6 +4,7 @@"lib": ["ESNext", "DOM"],"module": "ESNext","moduleResolution": "bundler",+ "allowArbitraryExtensions": true,"types": ["node", "bun"],"strict": true,diff --git a/scripts/steiger-rules.ts b/scripts/steiger-rules.tsindex 57e5028b7..dce22c128 100644--- a/scripts/steiger-rules.ts+++ b/scripts/steiger-rules.ts@@ -346,10 +346,11 @@ const noPrototypeOrGeneratedImports = createImportRule(return 'Do not import generated desktop artifacts from TypeScript/app code.'}if (- resolved.startsWith('packages/core/src/kiwi/kiwi-schema/') &&- !sourceRel.startsWith('packages/core/src/kiwi/kiwi-schema/')+ resolved.startsWith('packages/core/src/kiwi/schema-runtime/') &&+ resolved !== 'packages/core/src/kiwi/schema-runtime/index.ts' &&+ !sourceRel.startsWith('packages/core/src/kiwi/schema-runtime/')) {- return 'Do not import vendored Kiwi schema internals directly; use the supported Kiwi APIs.'+ return 'Do not import Kiwi schema runtime internals directly; use the supported Kiwi APIs.'}return null}diff --git a/tests/engine/io/fig/export/text.test.ts b/tests/engine/io/fig/export/text.test.tsindex fd1874114..73df42e37 100644--- a/tests/engine/io/fig/export/text.test.ts+++ b/tests/engine/io/fig/export/text.test.ts@@ -61,7 +61,7 @@ describe('text node export', () => {await initCodec()const { unzipSync, inflateSync } = await import('fflate')- const { decodeBinarySchema, compileSchema, ByteBuffer } = await import('#core/kiwi/kiwi-schema')+ const { decodeBinarySchema, compileSchema, ByteBuffer } = await import('#core/kiwi/schema-runtime')const { parseFigKiwiChunks } = await import('@open-pencil/core')const graph = new SceneGraph()@@ -122,7 +122,7 @@ describe('text node export', () => {await initCodec()const { unzipSync, inflateSync } = await import('fflate')- const { decodeBinarySchema, compileSchema, ByteBuffer } = await import('#core/kiwi/kiwi-schema')+ const { decodeBinarySchema, compileSchema, ByteBuffer } = await import('#core/kiwi/schema-runtime')const { parseFigKiwiChunks } = await import('@open-pencil/core')const graph = new SceneGraph()@@ -162,7 +162,7 @@ describe('text node export', () => {await initCodec()const { unzipSync, inflateSync } = await import('fflate')- const { decodeBinarySchema, compileSchema, ByteBuffer } = await import('#core/kiwi/kiwi-schema')+ const { decodeBinarySchema, compileSchema, ByteBuffer } = await import('#core/kiwi/schema-runtime')const { parseFigKiwiChunks } = await import('@open-pencil/core')const graph = new SceneGraph()@@ -205,7 +205,7 @@ describe('text node export', () => {await initCodec()const { unzipSync, inflateSync } = await import('fflate')- const { decodeBinarySchema, compileSchema, ByteBuffer } = await import('#core/kiwi/kiwi-schema')+ const { decodeBinarySchema, compileSchema, ByteBuffer } = await import('#core/kiwi/schema-runtime')const { parseFigKiwiChunks } = await import('@open-pencil/core')const graph = new SceneGraph()diff --git a/tests/engine/kiwi/schema-runtime.test.ts b/tests/engine/kiwi/schema-runtime.test.tsnew file mode 100644index 000000000..019edf8e1--- /dev/null+++ b/tests/engine/kiwi/schema-runtime.test.ts@@ -0,0 +1,24 @@+import { describe, test } from 'bun:test'++import figSchema from '#core/kiwi/binary/schema'+import { expectEnumValue, expectFieldNumber, validateSchema } from '#core/kiwi/schema-runtime'++describe('Kiwi schema runtime', () => {+ test('validates the static Figma schema', () => {+ validateSchema(figSchema)+ })++ test('keeps Figma clipboard-derived field numbers for fragile roundtrip fields', () => {+ expectFieldNumber(figSchema, 'NodeChange', 'stackWrap', 323)+ expectFieldNumber(figSchema, 'NodeChange', 'stackCounterSpacing', 324)+ expectFieldNumber(figSchema, 'Glyph', 'emojiCodePoints', 7)+ expectFieldNumber(figSchema, 'Glyph', 'emojiImageSet', 8)+ expectFieldNumber(figSchema, 'Glyph', 'rotation', 9)+ expectFieldNumber(figSchema, 'Paint', 'colorVar', 21)+ expectFieldNumber(figSchema, 'TextLineData', 'sourceDirectionality', 9)++ expectEnumValue(figSchema, 'VariableField', 'TEXT_DATA', 11)+ expectEnumValue(figSchema, 'VariableField', 'STACK_COUNTER_SPACING', 23)+ expectEnumValue(figSchema, 'VariableField', 'OVERRIDDEN_SYMBOL_ID', 37)+ })+})diff --git a/tests/engine/render/canvas/silhouette-autopsy.test.ts b/tests/engine/render/canvas/silhouette-autopsy.test.tsindex 8162b57a4..f343f8951 100644--- a/tests/engine/render/canvas/silhouette-autopsy.test.ts+++ b/tests/engine/render/canvas/silhouette-autopsy.test.ts@@ -34,7 +34,7 @@ const rendererPath = coreSourcePath('canvas/renderer.ts')const sgTypesPath = coreSourcePath('scene-graph/types.ts')const nodeExportPath = coreSourcePath('kiwi/node-change/export-node.ts')const convertPath = coreSourcePath('kiwi/node-change/paint.ts')-const schemaPath = coreSourcePath('kiwi/binary/schema.ts')+const schemaPath = coreSourcePath('kiwi/binary/schema/fig.kiwi')const codecPath = coreSourcePath('kiwi/binary/codec.ts')const lifecyclePath = coreSourcePath('canvas/renderer/lifecycle.ts')diff --git a/tsconfig.json b/tsconfig.jsonindex e58c215bc..ff64a00d0 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -7,6 +7,7 @@"skipLibCheck": true,"moduleResolution": "bundler","allowImportingTsExtensions": true,+ "allowArbitraryExtensions": true,"resolveJsonModule": true,"isolatedModules": true,"noEmit": true,diff --git a/vite/raw-markdown.ts b/vite/raw-markdown.tsindex b1fdd670e..d8ed342d7 100644--- a/vite/raw-markdown.ts+++ b/vite/raw-markdown.ts@@ -2,9 +2,9 @@ import type { Plugin } from 'vite'export function rawMarkdownPlugin(): Plugin {return {- name: 'raw-md',+ name: 'raw-text-assets',transform(code: string, id: string) {- if (id.endsWith('.md')) {+ if (id.endsWith('.md') || id.endsWith('.kiwi')) {return { code: `export default ${JSON.stringify(code)}`, map: null }}}