@pairdraw/kiwi 0.0.0-stage → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +28 -0
  3. package/README.md +112 -2
  4. package/dist/chunks/fig/codec.js +1371 -0
  5. package/dist/chunks/fig/codec.js.map +1 -0
  6. package/dist/fig/codec.d.ts +477 -0
  7. package/dist/fig/codec.js +2 -0
  8. package/dist/fig/container.d.ts +48 -0
  9. package/dist/fig/container.js +2 -0
  10. package/dist/fig/guid.d.ts +13 -0
  11. package/dist/fig/guid.js +31 -0
  12. package/dist/fig/guid.js.map +1 -0
  13. package/dist/fig/parse.d.ts +33 -0
  14. package/dist/fig/parse.js +83 -0
  15. package/dist/fig/parse.js.map +1 -0
  16. package/dist/fig.d.ts +185 -0
  17. package/dist/fig.js +117 -0
  18. package/dist/fig.js.map +1 -0
  19. package/dist/index.d.ts +182 -0
  20. package/dist/page-manifest.d.ts +16 -0
  21. package/dist/schema-runtime.d.ts +2 -0
  22. package/dist/schema-runtime.js +2 -0
  23. package/dist/types.d.ts +26 -0
  24. package/package.json +64 -4
  25. package/src/fig/codec.ts +536 -0
  26. package/src/fig/container.ts +180 -0
  27. package/src/fig/guid.ts +24 -0
  28. package/src/fig/index.ts +5 -0
  29. package/src/fig/page-manifest.ts +149 -0
  30. package/src/fig/parse.ts +136 -0
  31. package/src/fig/protocol.ts +237 -0
  32. package/src/fig/schema/fig.kiwi +5628 -0
  33. package/src/fig/schema.ts +7 -0
  34. package/src/fig/types.ts +25 -0
  35. package/src/fig/variable-bindings.ts +11 -0
  36. package/src/global.d.ts +4 -0
  37. package/src/schema-runtime/bb.ts +284 -0
  38. package/src/schema-runtime/binary.ts +102 -0
  39. package/src/schema-runtime/index.ts +25 -0
  40. package/src/schema-runtime/interpreter.ts +465 -0
  41. package/src/schema-runtime/parser.ts +287 -0
  42. package/src/schema-runtime/schema.ts +24 -0
  43. package/src/schema-runtime/util.ts +10 -0
  44. package/src/schema-runtime/validate.ts +88 -0
@@ -0,0 +1,536 @@
1
+ /**
2
+ * Message Encoding/Decoding for Figma Multiplayer
3
+ *
4
+ * Uses:
5
+ * - kiwi-schema: Binary serialization (by Evan Wallace, Figma co-founder)
6
+ * - fzstd: Browser-compatible Zstd decompression
7
+ */
8
+
9
+ import { compileSchema, encodeBinarySchema } from '../schema-runtime'
10
+ import { decompressFigKiwiData, loadFigDataDecompressor } from './container'
11
+ import { isZstdCompressed, getKiwiMessageType } from './protocol'
12
+ import figmaSchema from './schema'
13
+ import type { Color, GUID, Matrix, Vector } from './types'
14
+
15
+ interface CompiledSchema {
16
+ encodeMessage(message: unknown): Uint8Array
17
+ decodeMessage(data: Uint8Array): unknown
18
+ encodePaint(paint: unknown): Uint8Array
19
+ encodeNodeChange(nodeChange: unknown): Uint8Array
20
+ }
21
+
22
+ let compiledSchema: CompiledSchema | null = null
23
+
24
+ /**
25
+ * Initialize the codec (compiles Kiwi schema)
26
+ */
27
+ export async function initCodec(): Promise<void> {
28
+ if (compiledSchema) return
29
+ await loadFigDataDecompressor()
30
+ compiledSchema = compileSchema(figmaSchema) as CompiledSchema
31
+ }
32
+
33
+ export function getCompiledSchema() {
34
+ if (!compiledSchema) throw new Error('Codec not initialized')
35
+ return compiledSchema
36
+ }
37
+
38
+ export function getSchemaBytes(): Uint8Array {
39
+ return encodeBinarySchema(figmaSchema)
40
+ }
41
+
42
+ /**
43
+ * Check if codec is initialized
44
+ */
45
+ export function isCodecReady(): boolean {
46
+ return compiledSchema !== null
47
+ }
48
+
49
+ /**
50
+ * Compress data using Zstd (Bun native)
51
+ */
52
+ export function compress(data: Uint8Array): Uint8Array {
53
+ return data
54
+ }
55
+
56
+ /**
57
+ * Decompress Zstd data (Bun native)
58
+ */
59
+ export function decompress(data: Uint8Array): Uint8Array {
60
+ if (!isZstdCompressed(data)) return data
61
+ return decompressFigKiwiData(data)
62
+ }
63
+
64
+ /**
65
+ * Encode a message for sending to Figma
66
+ * Handles variable bindings in fillPaints which require custom encoding
67
+ */
68
+ export function encodeMessage(message: FigmaMessage): Uint8Array {
69
+ if (!compiledSchema) {
70
+ throw new Error('Codec not initialized. Call initCodec() first.')
71
+ }
72
+ return compress(compiledSchema.encodeMessage(message))
73
+ }
74
+
75
+ /**
76
+ * Decode a message received from Figma
77
+ */
78
+ export function decodeMessage(data: Uint8Array): FigmaMessage {
79
+ if (!compiledSchema) {
80
+ throw new Error('Codec not initialized. Call initCodec() first.')
81
+ }
82
+
83
+ const decompressed = decompress(data)
84
+ return compiledSchema.decodeMessage(decompressed) as FigmaMessage
85
+ }
86
+
87
+ /**
88
+ * Quick peek at message type without full decoding
89
+ */
90
+ export function peekMessageType(data: Uint8Array): number | null {
91
+ try {
92
+ const decompressed = decompress(data)
93
+ return getKiwiMessageType(decompressed)
94
+ } catch {
95
+ return null
96
+ }
97
+ }
98
+
99
+ // Type definitions
100
+
101
+ export interface ParentIndex {
102
+ guid: GUID
103
+ position: string
104
+ }
105
+
106
+ export interface ImageSource {
107
+ hash: string | Uint8Array
108
+ name?: string
109
+ dataBlob?: number
110
+ }
111
+
112
+ export interface Paint {
113
+ type:
114
+ | 'SOLID'
115
+ | 'GRADIENT_LINEAR'
116
+ | 'GRADIENT_RADIAL'
117
+ | 'GRADIENT_ANGULAR'
118
+ | 'GRADIENT_DIAMOND'
119
+ | 'IMAGE'
120
+ | 'VIDEO'
121
+ | 'PATTERN'
122
+ | 'NOISE'
123
+ | 'CUSTOM'
124
+ color?: Color
125
+ opacity?: number
126
+ visible?: boolean
127
+ blendMode?: string
128
+ stops?: { color: Color; position: number }[]
129
+ transform?: Matrix
130
+ image?: ImageSource
131
+ imageThumbnail?: ImageSource
132
+ animatedImage?: ImageSource
133
+ imageScaleMode?: string
134
+ /** Degrees an image turns in Fill, Fit, and Tile; a crop's transform holds its own turn. */
135
+ rotation?: number
136
+ sourceNodeId?: GUID
137
+ scale?: number
138
+ spacing?: number
139
+ patternSpacing?: Vector
140
+ patternTileType?: string
141
+ verticalAlignment?: string
142
+ horizontalAlignment?: string
143
+ id?: GUID
144
+ altText?: string
145
+ noiseType?: string
146
+ density?: number
147
+ noiseSize?: Vector
148
+ customEffectId?: { guid?: GUID }
149
+ colorVar?: {
150
+ value?: {
151
+ alias?: {
152
+ guid?: GUID
153
+ assetRef?: { key: string; version?: string }
154
+ }
155
+ }
156
+ dataType?: string
157
+ resolvedDataType?: string
158
+ }
159
+ }
160
+
161
+ export interface Effect {
162
+ type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' | 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'
163
+ color?: Color
164
+ offset?: Vector
165
+ radius?: number
166
+ visible?: boolean
167
+ spread?: number
168
+ blendMode?: string
169
+ showShadowBehindNode?: boolean
170
+ }
171
+
172
+ export interface VariableAnyValue {
173
+ boolValue?: boolean
174
+ textValue?: string
175
+ floatValue?: number
176
+ colorValue?: Color
177
+ alias?: { guid?: GUID; assetRef?: { key: string; version?: string } }
178
+ symbolIdValue?: { guid?: GUID }
179
+ // fig.kiwi PropRefValue: the component property a parameter entry points at.
180
+ propRefValue?: { defId?: GUID }
181
+ mapValue?: { values?: { key?: string; guidKey?: GUID; value?: VariableDataEntry }[] }
182
+ colorArrayValue?: { colors?: VariableDataEntry[] }
183
+ fontStyleValue?: {
184
+ asString?: VariableDataEntry
185
+ asFloat?: VariableDataEntry
186
+ asVariations?: VariableDataEntry
187
+ }
188
+ expressionValue?: {
189
+ expressionFunction?: string
190
+ expressionArguments?: VariableDataEntry[]
191
+ }
192
+ }
193
+
194
+ export interface VariableDataEntry {
195
+ value?: VariableAnyValue
196
+ dataType?: string
197
+ resolvedDataType?: string
198
+ }
199
+
200
+ export interface VariableConsumptionEntry {
201
+ nodeField?: number
202
+ variableData?: VariableDataEntry
203
+ variableField?: string
204
+ }
205
+
206
+ export interface VariableDataValuesEntry {
207
+ modeID: GUID
208
+ variableData: VariableDataEntry
209
+ }
210
+
211
+ export interface PluginData {
212
+ pluginID: string
213
+ value: string
214
+ key: string
215
+ }
216
+
217
+ export interface PluginRelaunchData {
218
+ pluginID: string
219
+ message: string
220
+ command: string
221
+ isDeleted: boolean
222
+ }
223
+
224
+ export interface AssetRef {
225
+ key: string
226
+ version?: string
227
+ }
228
+
229
+ export type StyleReference = { guid: GUID; assetRef?: never } | { guid?: never; assetRef: AssetRef }
230
+
231
+ /** One paragraph of a text: whether it is a list item, and how deeply it nests. */
232
+ export interface TextLineData {
233
+ lineType?: 'PLAIN' | 'ORDERED_LIST' | 'UNORDERED_LIST' | 'BLOCKQUOTE' | 'HEADER'
234
+ styleId?: number
235
+ indentationLevel?: number
236
+ sourceDirectionality?: string
237
+ listStartOffset?: number
238
+ isFirstLineOfList?: boolean
239
+ }
240
+
241
+ export interface NodeChange {
242
+ [key: string]: unknown
243
+ guid?: GUID
244
+ phase?: 'CREATED' | 'REMOVED'
245
+ parentIndex?: ParentIndex
246
+ type?: string
247
+ name?: string
248
+ visible?: boolean
249
+ locked?: boolean
250
+ opacity?: number
251
+ blendMode?: string
252
+ size?: Vector
253
+ transform?: Matrix
254
+ cornerRadius?: number
255
+ fillPaints?: Paint[]
256
+ strokePaints?: Paint[]
257
+ backgroundPaints?: Paint[]
258
+ strokeWeight?: number
259
+ strokeAlign?: string
260
+ strokeCap?: string
261
+ strokeJoin?: string
262
+ dashPattern?: number[]
263
+ effects?: Effect[]
264
+ mask?: boolean
265
+ maskType?: string
266
+ maskIsOutline?: boolean
267
+ exportSettings?: unknown[]
268
+ layoutGrids?: unknown[]
269
+ // Layout
270
+ stackMode?: 'NONE' | 'HORIZONTAL' | 'VERTICAL'
271
+ stackSpacing?: number
272
+ stackPadding?: number
273
+ stackPaddingRight?: number
274
+ stackPaddingBottom?: number
275
+ stackCounterAlign?: string
276
+ stackJustify?: string
277
+ stackCounterAlignItems?: string
278
+ stackPrimaryAlignItems?: string
279
+ stackPrimarySizing?: 'FIXED' | 'RESIZE_TO_FIT' | 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE'
280
+ stackCounterSizing?: 'FIXED' | 'RESIZE_TO_FIT' | 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE'
281
+ stackVerticalPadding?: number
282
+ stackHorizontalPadding?: number
283
+ stackWrap?: string
284
+ stackPositioning?: string
285
+ stackChildPrimaryGrow?: number
286
+ stackChildAlignSelf?: string
287
+ stackCounterSpacing?: number
288
+ minSize?: { value?: Vector }
289
+ maxSize?: { value?: Vector }
290
+ targetAspectRatio?: { value?: Vector }
291
+ // Frame
292
+ clipsContent?: boolean
293
+ frameMaskDisabled?: boolean
294
+ resizeToFit?: boolean
295
+ // Vector
296
+ booleanOperation?: 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'XOR'
297
+ vectorData?: unknown
298
+ fillGeometry?: Array<{ windingRule?: string; commandsBlob?: number; styleID?: number }>
299
+ strokeGeometry?: Array<{ windingRule?: string; commandsBlob?: number }>
300
+ // Text
301
+ fontSize?: number
302
+ fontWeight?: number
303
+ fontName?: { family: string; style: string; postscript?: string }
304
+ textAlignHorizontal?: string
305
+ textAlignVertical?: string
306
+ textAutoResize?: string
307
+ textData?: {
308
+ characters: string
309
+ lines?: TextLineData[]
310
+ characterStyleIDs?: number[]
311
+ styleOverrideTable?: NodeChange[]
312
+ }
313
+ derivedTextData?: {
314
+ layoutSize?: Vector
315
+ baselines?: Array<{
316
+ firstCharacter: number
317
+ endCharacter: number
318
+ position: Vector
319
+ width: number
320
+ lineY?: number
321
+ lineHeight: number
322
+ lineAscent: number
323
+ }>
324
+ glyphs?: Array<{
325
+ commandsBlob?: number
326
+ position: Vector
327
+ fontSize: number
328
+ /** The character the glyph draws; Figma leaves it out for list markers. */
329
+ firstCharacter?: number
330
+ advance: number
331
+ /** Radians along the text path; kiwi omits the field for axis-aligned text. */
332
+ rotation?: number
333
+ /** An emoji's code points; Figma draws its image in place of the glyph's placeholder. */
334
+ emojiCodePoints?: number[]
335
+ /** The image set the emoji is drawn from; left out for the default, APPLE. */
336
+ emojiImageSet?: 'APPLE' | 'NOTO'
337
+ }>
338
+ /** Underlines and strikethroughs, which Figma draws saved text's decorations from. */
339
+ decorations?: Array<{
340
+ rects: Array<{ x: number; y: number; w: number; h: number }>
341
+ /** The override table entry of the characters decorated, or 0 for the text's own style. */
342
+ styleID: number
343
+ }>
344
+ fontMetaData?: Array<{
345
+ key: { family: string; style: string; postscript?: string }
346
+ fontLineHeight: number
347
+ fontDigest?: Uint8Array | Record<string, number>
348
+ fontStyle?: string
349
+ fontWeight?: number
350
+ }>
351
+ logicalIndexToCharacterOffsetMap?: number[]
352
+ derivedLines?: Array<{ directionality: 'LTR' | 'RTL' }>
353
+ truncationStartIndex?: number
354
+ truncatedHeight?: number
355
+ }
356
+ styleType?: string
357
+ styleIdForText?: StyleReference
358
+ styleIdForFill?: StyleReference
359
+ styleIdForStrokeFill?: StyleReference
360
+ styleIdForEffect?: StyleReference
361
+ styleIdForGrid?: StyleReference
362
+ textUserLayoutVersion?: number
363
+ textExplicitLayoutVersion?: number
364
+ textBidiVersion?: number
365
+ textDecoration?: string
366
+ textDecorationSkipInk?: boolean
367
+ textDecorationFillPaints?: Paint[]
368
+ textUnderlineOffset?: { value?: number; units?: string }
369
+ textDecorationThickness?: { value?: number; units?: string }
370
+ textDecorationStyle?: string
371
+ toggledOnOTFeatures?: string[]
372
+ toggledOffOTFeatures?: string[]
373
+ fontVariations?: Array<{ axisTag?: number; axisName?: string; value?: number }>
374
+ fontVariantCommonLigatures?: boolean
375
+ fontVariantContextualLigatures?: boolean
376
+ fontVariantDiscretionaryLigatures?: boolean
377
+ fontVariantHistoricalLigatures?: boolean
378
+ fontVariantOrdinal?: boolean
379
+ fontVariantSlashedZero?: boolean
380
+ fontVariantNumericFigure?: string
381
+ fontVariantNumericSpacing?: string
382
+ fontVariantNumericFraction?: string
383
+ fontVariantCaps?: string
384
+ fontVersion?: string
385
+ emojiImageSet?: string
386
+ lineHeight?: { value: number; units: string }
387
+ letterSpacing?: { value: number; units: string }
388
+ paragraphSpacing?: number
389
+ paragraphIndent?: number
390
+ listSpacing?: number
391
+ hangingList?: boolean
392
+ // Symbol/Instance
393
+ symbolData?: { symbolID: GUID }
394
+ // ComponentSet
395
+ isStateGroup?: boolean
396
+ stateGroupPropertyValueOrders?: Array<{ property: string; values: string[] }>
397
+ // Internal
398
+ internalOnly?: boolean
399
+ // Corners
400
+ rectangleTopLeftCornerRadius?: number
401
+ rectangleTopRightCornerRadius?: number
402
+ rectangleBottomLeftCornerRadius?: number
403
+ rectangleBottomRightCornerRadius?: number
404
+ rectangleCornerRadiiIndependent?: boolean
405
+ cornerSmoothing?: number
406
+ /** A polygon's sides or a star's points. */
407
+ count?: number
408
+ /** A star's inner radius as a share of its outer one. */
409
+ starInnerScale?: number
410
+ // Constraints
411
+ horizontalConstraint?: string
412
+ verticalConstraint?: string
413
+ // Prototype
414
+ prototypeStartNodeID?: GUID
415
+ prototypeInteractions?: unknown[]
416
+ transitionInfo?: unknown
417
+ // Variables
418
+ variableData?: VariableDataEntry
419
+ variableConsumptionMap?: { entries?: VariableConsumptionEntry[] }
420
+ // fig.kiwi declares this as the same VariableDataMap as variableConsumptionMap.
421
+ parameterConsumptionMap?: { entries?: VariableConsumptionEntry[] }
422
+ variableSetModes?: Array<{ id: GUID; name: string; sortPosition?: string }>
423
+ variableSetID?: { guid?: GUID; assetRef?: { key: string; version?: string } }
424
+ variableResolvedType?: string
425
+ variableDataValues?: { entries?: VariableDataValuesEntry[] }
426
+ variableScopes?: string[]
427
+ codeSyntax?: { entries?: Array<{ platform: string; value: string }> }
428
+ description?: string
429
+ symbolDescription?: string
430
+ isPublishable?: boolean
431
+ documentColorProfile?: 'SRGB' | 'DISPLAY_P3'
432
+ pluginData?: PluginData[]
433
+ pluginRelaunchData?: PluginRelaunchData[]
434
+ }
435
+
436
+ export interface FigmaMessage {
437
+ type: string
438
+ sessionID?: number
439
+ ackID?: number
440
+ reconnectSequenceNumber?: number
441
+ nodeChanges?: NodeChange[]
442
+ blobs?: Array<{ bytes: Uint8Array }>
443
+ }
444
+
445
+ /**
446
+ * Create a NODE_CHANGES message
447
+ */
448
+ export function createNodeChangesMessage(
449
+ sessionID: number,
450
+ reconnectSequenceNumber: number,
451
+ nodeChanges: NodeChange[],
452
+ ackID = 1
453
+ ): FigmaMessage {
454
+ return {
455
+ type: 'NODE_CHANGES',
456
+ sessionID,
457
+ ackID,
458
+ reconnectSequenceNumber,
459
+ nodeChanges
460
+ }
461
+ }
462
+
463
+ /**
464
+ * Create a node change for a new shape
465
+ */
466
+ export function createNodeChange(opts: {
467
+ sessionID: number
468
+ localID: number
469
+ parentSessionID: number
470
+ parentLocalID: number
471
+ position?: string
472
+ type: string
473
+ name: string
474
+ x: number
475
+ y: number
476
+ width: number
477
+ height: number
478
+ fill?: Color
479
+ stroke?: Color
480
+ strokeWeight?: number
481
+ cornerRadius?: number
482
+ opacity?: number
483
+ }): NodeChange {
484
+ const change: NodeChange = {
485
+ guid: { sessionID: opts.sessionID, localID: opts.localID },
486
+ phase: 'CREATED',
487
+ parentIndex: {
488
+ guid: { sessionID: opts.parentSessionID, localID: opts.parentLocalID },
489
+ position: opts.position || '!'
490
+ },
491
+ type: opts.type,
492
+ name: opts.name,
493
+ visible: true,
494
+ opacity: opts.opacity ?? 1.0,
495
+ size: { x: opts.width, y: opts.height },
496
+ transform: {
497
+ m00: 1,
498
+ m01: 0,
499
+ m02: opts.x,
500
+ m10: 0,
501
+ m11: 1,
502
+ m12: opts.y
503
+ }
504
+ }
505
+
506
+ if (opts.fill) {
507
+ change.fillPaints = [
508
+ {
509
+ type: 'SOLID',
510
+ color: opts.fill,
511
+ opacity: 1.0,
512
+ visible: true,
513
+ blendMode: 'NORMAL'
514
+ }
515
+ ]
516
+ }
517
+
518
+ if (opts.stroke) {
519
+ change.strokePaints = [
520
+ {
521
+ type: 'SOLID',
522
+ color: opts.stroke,
523
+ opacity: 1.0,
524
+ visible: true,
525
+ blendMode: 'NORMAL'
526
+ }
527
+ ]
528
+ change.strokeWeight = opts.strokeWeight ?? 1
529
+ }
530
+
531
+ if (opts.cornerRadius !== undefined) {
532
+ change.cornerRadius = opts.cornerRadius
533
+ }
534
+
535
+ return change
536
+ }
@@ -0,0 +1,180 @@
1
+ import type { Zstd } from '@hpcc-js/wasm-zstd'
2
+ import { deflateSync, inflateSync } from 'fflate'
3
+
4
+ import { isZstdCompressed } from './protocol'
5
+
6
+ export const FIG_KIWI_DEFAULT_VERSION = 101
7
+
8
+ /**
9
+ * The header a canvas starts with. Figma's design files and FigJam boards differ only here:
10
+ * a board's `.jam` archive holds the same records under `fig-jam.`.
11
+ */
12
+ export const FIG_FILE_HEADERS = { design: 'fig-kiwi', board: 'fig-jam.' } as const
13
+
14
+ /** What a canvas is for, by its header. */
15
+ export type FigFileKind = keyof typeof FIG_FILE_HEADERS
16
+
17
+ /** The kind a canvas's header names, or null when it is no Figma canvas. */
18
+ export function figFileKind(binary: Uint8Array): FigFileKind | null {
19
+ const header = new TextDecoder().decode(binary.slice(0, 8))
20
+ if (header === FIG_FILE_HEADERS.design) return 'design'
21
+ if (header === FIG_FILE_HEADERS.board) return 'board'
22
+ return null
23
+ }
24
+
25
+ /** Compresses a fig-kiwi data chunk. */
26
+ export type FigDataCompressor = (data: Uint8Array) => Uint8Array
27
+
28
+ /** Decompresses a fig-kiwi data chunk, zstd or deflate. */
29
+ export type FigDataDecompressor = (data: Uint8Array) => Uint8Array
30
+
31
+ /** The zstd level Figma itself saves with. */
32
+ export const FIG_ZSTD_DEFAULT_LEVEL = 3
33
+
34
+ type BunZstdCompress = (data: Uint8Array, options?: { level?: number }) => Uint8Array
35
+ type BunZstdDecompress = (data: Uint8Array) => Uint8Array
36
+
37
+ function bunZstdCompress(): BunZstdCompress | undefined {
38
+ const g = globalThis as { Bun?: { zstdCompressSync?: BunZstdCompress } }
39
+ return g.Bun?.zstdCompressSync
40
+ }
41
+
42
+ function bunZstdDecompress(): BunZstdDecompress | undefined {
43
+ const g = globalThis as { Bun?: { zstdDecompressSync?: BunZstdDecompress } }
44
+ return g.Bun?.zstdDecompressSync
45
+ }
46
+
47
+ /**
48
+ * Bun's zstd at its default level, or deflate where zstd needs loading first. Figma reads both,
49
+ * so writers that cannot wait, such as the clipboard, use this one.
50
+ */
51
+ export const defaultFigDataCompressor: FigDataCompressor = (data) =>
52
+ bunZstdCompress()?.(data) ?? deflateSync(data)
53
+
54
+ let wasmZstd: Zstd | undefined
55
+ let wasmZstdLoading: Promise<Zstd> | undefined
56
+
57
+ /** The WebAssembly zstd, loaded once; a failed load is retried on the next call. */
58
+ function loadWasmZstd(): Promise<Zstd> {
59
+ wasmZstdLoading ??= import('@hpcc-js/wasm-zstd')
60
+ .then(({ Zstd }) => Zstd.load())
61
+ .then((zstd) => (wasmZstd = zstd))
62
+ .catch((error: unknown) => {
63
+ wasmZstdLoading = undefined
64
+ throw error
65
+ })
66
+ return wasmZstdLoading
67
+ }
68
+
69
+ /** The WebAssembly zstd encoder at `level`. */
70
+ export async function loadWasmFigDataCompressor(
71
+ level = FIG_ZSTD_DEFAULT_LEVEL
72
+ ): Promise<FigDataCompressor> {
73
+ const zstd = await loadWasmZstd()
74
+ return (data) => zstd.compress(data, level)
75
+ }
76
+
77
+ /**
78
+ * A zstd compressor at `level`: Bun's own where it runs, the WebAssembly build elsewhere. Figma
79
+ * opens every level, but only frames that declare their decompressed size, which both write.
80
+ */
81
+ export async function loadFigDataCompressor(
82
+ level = FIG_ZSTD_DEFAULT_LEVEL
83
+ ): Promise<FigDataCompressor> {
84
+ const native = bunZstdCompress()
85
+ if (native) return (data) => native(data, { level })
86
+ return loadWasmFigDataCompressor(level)
87
+ }
88
+
89
+ /** The WebAssembly zstd decoder. */
90
+ export async function loadWasmFigDataDecompressor(): Promise<FigDataDecompressor> {
91
+ const zstd = await loadWasmZstd()
92
+ return (data) => (isZstdCompressed(data) ? zstd.decompress(data) : inflate(data))
93
+ }
94
+
95
+ /**
96
+ * Makes `decompressFigKiwiData` ready for zstd chunks: Bun's own zstd needs nothing, the
97
+ * WebAssembly build elsewhere loads once. Every path that opens a `.fig` synchronously awaits
98
+ * this first, so a document session, its worker, and the patches they write never wait.
99
+ */
100
+ export async function loadFigDataDecompressor(): Promise<FigDataDecompressor> {
101
+ if (!bunZstdDecompress()) await loadWasmZstd()
102
+ return decompressFigKiwiData
103
+ }
104
+
105
+ function inflate(compressed: Uint8Array): Uint8Array {
106
+ try {
107
+ return inflateSync(compressed)
108
+ } catch {
109
+ throw new Error('Failed to decompress fig-kiwi data')
110
+ }
111
+ }
112
+
113
+ function decompressZstd(compressed: Uint8Array): Uint8Array {
114
+ const native = bunZstdDecompress()
115
+ if (native) {
116
+ // Bun returns a Node Buffer, whose `slice` is a view: a reader slicing byte arrays out of
117
+ // the message would then hand out views of the whole message, which `structuredClone`
118
+ // copies in full each time. A plain Uint8Array over the same memory slices by copying.
119
+ const buffer = native(compressed)
120
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
121
+ }
122
+ if (!wasmZstd)
123
+ throw new Error('Zstd is not loaded: await loadFigDataDecompressor() before reading')
124
+ return wasmZstd.decompress(compressed)
125
+ }
126
+
127
+ export function parseFigKiwiChunks(binary: Uint8Array): Uint8Array[] | null {
128
+ if (!figFileKind(binary)) return null
129
+
130
+ const view = new DataView(binary.buffer, binary.byteOffset, binary.byteLength)
131
+ let offset = 12
132
+
133
+ const chunks: Uint8Array[] = []
134
+ while (offset < binary.length) {
135
+ const chunkLen = view.getUint32(offset, true)
136
+ offset += 4
137
+ chunks.push(binary.slice(offset, offset + chunkLen))
138
+ offset += chunkLen
139
+ }
140
+ return chunks.length >= 2 ? chunks : null
141
+ }
142
+
143
+ /** A data chunk decompressed at once; a zstd chunk needs `loadFigDataDecompressor` first. */
144
+ export function decompressFigKiwiData(compressed: Uint8Array): Uint8Array {
145
+ return isZstdCompressed(compressed) ? decompressZstd(compressed) : inflate(compressed)
146
+ }
147
+
148
+ export async function decompressFigKiwiDataAsync(compressed: Uint8Array): Promise<Uint8Array> {
149
+ const decompress = await loadFigDataDecompressor()
150
+ return decompress(compressed)
151
+ }
152
+
153
+ export function buildFigKiwi(
154
+ schemaDeflated: Uint8Array,
155
+ dataRaw: Uint8Array,
156
+ version = FIG_KIWI_DEFAULT_VERSION,
157
+ compress: FigDataCompressor = defaultFigDataCompressor,
158
+ kind: FigFileKind = 'design'
159
+ ): Uint8Array {
160
+ const dataCompressed = compress(dataRaw)
161
+
162
+ const total = 8 + 4 + 4 + schemaDeflated.length + 4 + dataCompressed.length
163
+ const out = new Uint8Array(total)
164
+ const view = new DataView(out.buffer)
165
+
166
+ out.set(new TextEncoder().encode(FIG_FILE_HEADERS[kind]), 0)
167
+ view.setUint32(8, version, true)
168
+
169
+ let offset = 12
170
+ view.setUint32(offset, schemaDeflated.length, true)
171
+ offset += 4
172
+ out.set(schemaDeflated, offset)
173
+ offset += schemaDeflated.length
174
+
175
+ view.setUint32(offset, dataCompressed.length, true)
176
+ offset += 4
177
+ out.set(dataCompressed, offset)
178
+
179
+ return out
180
+ }