vizmatic 0.3.2 → 0.5.0

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 (150) hide show
  1. package/PROMPT.md +75 -525
  2. package/README.md +87 -578
  3. package/ROADMAP.md +49 -67
  4. package/SCIENCE.md +250 -0
  5. package/assets/THIRD_PARTY_LICENSES.md +40 -1
  6. package/assets/fonts/InstrumentSerif-Italic.ttf +0 -0
  7. package/assets/fonts/InstrumentSerif-Regular.ttf +0 -0
  8. package/assets/licenses/raster-codecs-MIT.txt +74 -0
  9. package/dist/chunk-3F2VQ7NW.js +1 -0
  10. package/dist/chunk-4XE64I2U.js +755 -0
  11. package/dist/chunk-JHHPLALU.js +79 -0
  12. package/dist/chunk-LTX44BAE.js +112 -0
  13. package/dist/chunk-MLKGABMK.js +9 -0
  14. package/dist/chunk-PSBF4TEK.js +1 -0
  15. package/dist/chunk-RPAHMKAR.js +605 -0
  16. package/dist/chunk-RWF4VBUL.js +3617 -0
  17. package/dist/chunk-WHT6HRMX.js +4201 -0
  18. package/dist/cli.js +371 -10
  19. package/dist/index.cjs +11129 -2922
  20. package/dist/index.d.cts +1225 -369
  21. package/dist/index.d.ts +1225 -369
  22. package/dist/index.js +6220 -3015
  23. package/dist/math-LXB4FH4E.js +7 -0
  24. package/dist/math-QVCETQDQ.js +1 -0
  25. package/dist/scene-browser-assets.d.ts +38 -0
  26. package/dist/scene-browser-assets.js +53 -0
  27. package/dist/scene-browser-chunks/chunk-5MVLYGXM.js +70 -0
  28. package/dist/scene-browser-chunks/chunk-ASXKN3NU.js +1 -0
  29. package/dist/scene-browser-chunks/chunk-CM5Y5LZP.js +1 -0
  30. package/dist/scene-browser-chunks/chunk-DP7NB4EW.js +6 -0
  31. package/dist/scene-browser-chunks/emscripten-module.browser-M5AEKJGE.js +1 -0
  32. package/dist/scene-browser-chunks/ffi-FL6ORJU3.js +1 -0
  33. package/dist/scene-browser-chunks/module-ES6BEMUI-JD5S5VKR.js +1 -0
  34. package/dist/scene-browser-chunks/module-asyncify-2EFITU5U-HWPFJFJC.js +1 -0
  35. package/dist/scene-browser-chunks/scene-browser-layout-M3XSXMV4.js +27 -0
  36. package/dist/scene-browser.d.ts +117 -0
  37. package/dist/scene-browser.js +220 -0
  38. package/dist/scene-cli.d.ts +1 -0
  39. package/dist/scene-cli.js +4 -0
  40. package/dist/scene-runtime.cjs +995 -0
  41. package/dist/scene-runtime.d.cts +81 -0
  42. package/dist/scene-runtime.d.ts +81 -0
  43. package/dist/scene-runtime.js +22 -0
  44. package/dist/server-2FYHZ4UO.js +331 -0
  45. package/dist/stage-browser/browser.d.ts +2482 -0
  46. package/dist/stage-browser/chunk-SQE76S5B.js +1 -0
  47. package/dist/stage-browser/chunk-VZNL6JY2.js +59 -0
  48. package/dist/stage-browser/dagre.esm-N2NIVIAZ.js +6 -0
  49. package/dist/stage-browser/math-4WFNHVV2.js +18 -0
  50. package/dist/stage-browser/stage.js +19 -0
  51. package/dist/stage-export.cjs +4950 -0
  52. package/dist/stage-export.d.cts +112 -0
  53. package/dist/stage-export.d.ts +112 -0
  54. package/dist/stage-export.js +544 -0
  55. package/dist/stage.cjs +9745 -0
  56. package/dist/stage.d.cts +1678 -0
  57. package/dist/stage.d.ts +1678 -0
  58. package/dist/stage.js +5404 -0
  59. package/dist/svg-import-Djj2q7Pc.d.cts +742 -0
  60. package/dist/svg-import-Djj2q7Pc.d.ts +742 -0
  61. package/dist/video-CcHW1qhV.d.cts +532 -0
  62. package/dist/video-CcHW1qhV.d.ts +532 -0
  63. package/examples/README.md +18 -0
  64. package/examples/agent-pipeline.tsx +4 -4
  65. package/examples/animated-pipeline.tsx +1 -5
  66. package/examples/attention-head.tsx +12 -12
  67. package/examples/aurora-incident.tsx +4 -3
  68. package/examples/building-blocks.tsx +8 -9
  69. package/examples/catalog-charts.tsx +4 -4
  70. package/examples/catalog-content.tsx +7 -9
  71. package/examples/catalog-convolution-kernel.tsx +116 -0
  72. package/examples/catalog-data.tsx +2 -8
  73. package/examples/catalog-dataflow.tsx +5 -9
  74. package/examples/catalog-dense.tsx +80 -0
  75. package/examples/catalog-deployment.tsx +5 -11
  76. package/examples/catalog-diagrams.tsx +13 -16
  77. package/examples/catalog-drawing.tsx +7 -7
  78. package/examples/catalog-flows.tsx +4 -4
  79. package/examples/catalog-foundations.tsx +11 -11
  80. package/examples/catalog-gaussian-blur.tsx +146 -0
  81. package/examples/catalog-image-tensors.tsx +115 -0
  82. package/examples/catalog-ml.tsx +36 -31
  83. package/examples/catalog-numeric-matrices.tsx +93 -0
  84. package/examples/catalog-photo-blur.tsx +209 -0
  85. package/examples/catalog-science-ai.tsx +130 -0
  86. package/examples/catalog-science-chemistry.tsx +103 -0
  87. package/examples/catalog-science-math.tsx +93 -0
  88. package/examples/catalog-science-physics.tsx +84 -0
  89. package/examples/catalog-sequence.tsx +59 -38
  90. package/examples/data-pipeline-lineage-presentation.tsx +5 -0
  91. package/examples/data-pipeline-lineage.tsx +85 -0
  92. package/examples/daybreak-launch.tsx +1 -0
  93. package/examples/desired-quadrant.tsx +7 -8
  94. package/examples/engineering-dashboard-presentation.tsx +13 -0
  95. package/examples/engineering-dashboard.tsx +160 -0
  96. package/examples/engineering-flow.tsx +2 -4
  97. package/examples/eval-dashboard.tsx +6 -6
  98. package/examples/films/attention.ts +278 -0
  99. package/examples/films/cache-miss.ts +431 -0
  100. package/examples/films/catalog.json +132 -0
  101. package/examples/films/central-limit.ts +269 -0
  102. package/examples/films/complex-maps.ts +273 -0
  103. package/examples/films/deck-example.ts +224 -0
  104. package/examples/films/euler-circle.ts +179 -0
  105. package/examples/films/fourier-epicycles.ts +265 -0
  106. package/examples/films/gradient-descent.ts +345 -0
  107. package/examples/films/linear-maps.ts +175 -0
  108. package/examples/films/lorenz.ts +207 -0
  109. package/examples/films/pythagoras.ts +185 -0
  110. package/examples/films/taylor-series.ts +159 -0
  111. package/examples/films/vizmatic-title.ts +117 -0
  112. package/examples/llm-serving-stack-presentation.tsx +5 -0
  113. package/examples/llm-serving-stack.tsx +94 -0
  114. package/examples/model-garden.tsx +1 -0
  115. package/examples/model-router.tsx +6 -6
  116. package/examples/nccl-all-gather.tsx +3 -3
  117. package/examples/nccl-all-reduce.tsx +3 -3
  118. package/examples/nccl-all-to-all.tsx +1 -1
  119. package/examples/nccl-broadcast.tsx +1 -1
  120. package/examples/nccl-reduce-scatter.tsx +5 -5
  121. package/examples/orthogonal-routing.tsx +4 -4
  122. package/examples/pareto-frontier.tsx +9 -10
  123. package/examples/presentation-frame.tsx +6 -6
  124. package/examples/pressure-mechanism.scene.json +14 -0
  125. package/examples/production-system-map-presentation.tsx +5 -0
  126. package/examples/production-system-map.tsx +130 -0
  127. package/examples/rag-graph.tsx +7 -7
  128. package/examples/release-card.tsx +5 -5
  129. package/examples/spec-anatomy.tsx +5 -5
  130. package/examples/system-architecture.tsx +19 -32
  131. package/examples/theme-system.tsx +1 -1
  132. package/examples/token-matrix.tsx +4 -2
  133. package/examples/transparent-badge.tsx +1 -2
  134. package/examples/videos/README.md +62 -0
  135. package/examples/videos/calculus-tangent.tsx +101 -0
  136. package/examples/videos/catalyst-pathway.tsx +56 -0
  137. package/examples/videos/causal-attention.tsx +91 -0
  138. package/examples/videos/convolution-kernel.tsx +34 -0
  139. package/examples/videos/gaussian-blur.tsx +32 -0
  140. package/examples/videos/image-to-matrix.tsx +22 -0
  141. package/examples/videos/matrix-multiplication.tsx +128 -0
  142. package/examples/videos/photo-gaussian-blur.tsx +39 -0
  143. package/examples/videos/request-lifecycle.tsx +99 -0
  144. package/examples/videos/signal-to-story.tsx +126 -0
  145. package/examples/videos/wave-interference.tsx +80 -0
  146. package/examples/vizmatic-bare.d.ts +1 -0
  147. package/examples/vizmatic-hero.tsx +9 -18
  148. package/examples/website-workflow.tsx +7 -7
  149. package/examples/weekend-field-notes.tsx +3 -2
  150. package/package.json +77 -12
@@ -0,0 +1,4950 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/stage-export.ts
31
+ var stage_export_exports = {};
32
+ __export(stage_export_exports, {
33
+ captionsToVtt: () => captionsToVtt,
34
+ fromComponent: () => fromComponent,
35
+ planRender: () => planRender,
36
+ posterTime: () => posterTime,
37
+ renderFilmFrame: () => renderFilmFrame,
38
+ renderFilmFrames: () => renderFilmFrames,
39
+ renderFilmGif: () => renderFilmGif,
40
+ renderFilmSvg: () => renderFilmSvg,
41
+ renderFilmVideo: () => renderFilmVideo
42
+ });
43
+ module.exports = __toCommonJS(stage_export_exports);
44
+
45
+ // src/stage/export.ts
46
+ var import_promises3 = require("fs/promises");
47
+ var import_node_os2 = require("os");
48
+ var import_node_path = require("path");
49
+
50
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/png_decoder.js
51
+ var import_fflate = require("fflate");
52
+
53
+ // node_modules/.pnpm/iobuffer@6.0.1/node_modules/iobuffer/lib/text.js
54
+ function decode(bytes, encoding = "utf8") {
55
+ const decoder = new TextDecoder(encoding);
56
+ return decoder.decode(bytes);
57
+ }
58
+ var encoder = new TextEncoder();
59
+ function encode(str) {
60
+ return encoder.encode(str);
61
+ }
62
+
63
+ // node_modules/.pnpm/iobuffer@6.0.1/node_modules/iobuffer/lib/iobuffer.js
64
+ var defaultByteLength = 1024 * 8;
65
+ var hostBigEndian = (() => {
66
+ const array = new Uint8Array(4);
67
+ const view = new Uint32Array(array.buffer);
68
+ return !((view[0] = 1) & array[0]);
69
+ })();
70
+ var typedArrays = {
71
+ int8: globalThis.Int8Array,
72
+ uint8: globalThis.Uint8Array,
73
+ int16: globalThis.Int16Array,
74
+ uint16: globalThis.Uint16Array,
75
+ int32: globalThis.Int32Array,
76
+ uint32: globalThis.Uint32Array,
77
+ uint64: globalThis.BigUint64Array,
78
+ int64: globalThis.BigInt64Array,
79
+ float32: globalThis.Float32Array,
80
+ float64: globalThis.Float64Array
81
+ };
82
+ var IOBuffer = class _IOBuffer {
83
+ /**
84
+ * Reference to the internal ArrayBuffer object.
85
+ */
86
+ buffer;
87
+ /**
88
+ * Byte length of the internal ArrayBuffer.
89
+ */
90
+ byteLength;
91
+ /**
92
+ * Byte offset of the internal ArrayBuffer.
93
+ */
94
+ byteOffset;
95
+ /**
96
+ * Byte length of the internal ArrayBuffer.
97
+ */
98
+ length;
99
+ /**
100
+ * The current offset of the buffer's pointer.
101
+ */
102
+ offset;
103
+ lastWrittenByte;
104
+ littleEndian;
105
+ _data;
106
+ _mark;
107
+ _marks;
108
+ /**
109
+ * Create a new IOBuffer.
110
+ * @param data - The data to construct the IOBuffer with.
111
+ * If data is a number, it will be the new buffer's length<br>
112
+ * If data is `undefined`, the buffer will be initialized with a default length of 8Kb<br>
113
+ * If data is an ArrayBuffer, SharedArrayBuffer, an ArrayBufferView (Typed Array), an IOBuffer instance,
114
+ * or a Node.js Buffer, a view will be created over the underlying ArrayBuffer.
115
+ * @param options - An object for the options.
116
+ * @returns A new IOBuffer instance.
117
+ */
118
+ constructor(data = defaultByteLength, options = {}) {
119
+ let dataIsGiven = false;
120
+ if (typeof data === "number") {
121
+ data = new ArrayBuffer(data);
122
+ } else {
123
+ dataIsGiven = true;
124
+ this.lastWrittenByte = data.byteLength;
125
+ }
126
+ const offset = options.offset ? options.offset >>> 0 : 0;
127
+ const byteLength = data.byteLength - offset;
128
+ let dvOffset = offset;
129
+ if (ArrayBuffer.isView(data) || data instanceof _IOBuffer) {
130
+ if (data.byteLength !== data.buffer.byteLength) {
131
+ dvOffset = data.byteOffset + offset;
132
+ }
133
+ data = data.buffer;
134
+ }
135
+ if (dataIsGiven) {
136
+ this.lastWrittenByte = byteLength;
137
+ } else {
138
+ this.lastWrittenByte = 0;
139
+ }
140
+ this.buffer = data;
141
+ this.length = byteLength;
142
+ this.byteLength = byteLength;
143
+ this.byteOffset = dvOffset;
144
+ this.offset = 0;
145
+ this.littleEndian = true;
146
+ this._data = new DataView(this.buffer, dvOffset, byteLength);
147
+ this._mark = 0;
148
+ this._marks = [];
149
+ }
150
+ /**
151
+ * Checks if the memory allocated to the buffer is sufficient to store more
152
+ * bytes after the offset.
153
+ * @param byteLength - The needed memory in bytes.
154
+ * @returns `true` if there is sufficient space and `false` otherwise.
155
+ */
156
+ available(byteLength = 1) {
157
+ return this.offset + byteLength <= this.length;
158
+ }
159
+ /**
160
+ * Check if little-endian mode is used for reading and writing multi-byte
161
+ * values.
162
+ * @returns `true` if little-endian mode is used, `false` otherwise.
163
+ */
164
+ isLittleEndian() {
165
+ return this.littleEndian;
166
+ }
167
+ /**
168
+ * Set little-endian mode for reading and writing multi-byte values.
169
+ * @returns This.
170
+ */
171
+ setLittleEndian() {
172
+ this.littleEndian = true;
173
+ return this;
174
+ }
175
+ /**
176
+ * Check if big-endian mode is used for reading and writing multi-byte values.
177
+ * @returns `true` if big-endian mode is used, `false` otherwise.
178
+ */
179
+ isBigEndian() {
180
+ return !this.littleEndian;
181
+ }
182
+ /**
183
+ * Switches to big-endian mode for reading and writing multi-byte values.
184
+ * @returns This.
185
+ */
186
+ setBigEndian() {
187
+ this.littleEndian = false;
188
+ return this;
189
+ }
190
+ /**
191
+ * Move the pointer n bytes forward.
192
+ * @param n - Number of bytes to skip.
193
+ * @returns This.
194
+ */
195
+ skip(n = 1) {
196
+ this.offset += n;
197
+ return this;
198
+ }
199
+ /**
200
+ * Move the pointer n bytes backward.
201
+ * @param n - Number of bytes to move back.
202
+ * @returns This.
203
+ */
204
+ back(n = 1) {
205
+ this.offset -= n;
206
+ return this;
207
+ }
208
+ /**
209
+ * Move the pointer to the given offset.
210
+ * @param offset - The offset to move to.
211
+ * @returns This.
212
+ */
213
+ seek(offset) {
214
+ this.offset = offset;
215
+ return this;
216
+ }
217
+ /**
218
+ * Store the current pointer offset.
219
+ * @see {@link IOBuffer#reset}
220
+ * @returns This.
221
+ */
222
+ mark() {
223
+ this._mark = this.offset;
224
+ return this;
225
+ }
226
+ /**
227
+ * Move the pointer back to the last pointer offset set by mark.
228
+ * @see {@link IOBuffer#mark}
229
+ * @returns This.
230
+ */
231
+ reset() {
232
+ this.offset = this._mark;
233
+ return this;
234
+ }
235
+ /**
236
+ * Push the current pointer offset to the mark stack.
237
+ * @see {@link IOBuffer#popMark}
238
+ * @returns This.
239
+ */
240
+ pushMark() {
241
+ this._marks.push(this.offset);
242
+ return this;
243
+ }
244
+ /**
245
+ * Pop the last pointer offset from the mark stack, and set the current
246
+ * pointer offset to the popped value.
247
+ * @see {@link IOBuffer#pushMark}
248
+ * @returns This.
249
+ */
250
+ popMark() {
251
+ const offset = this._marks.pop();
252
+ if (offset === void 0) {
253
+ throw new Error("Mark stack empty");
254
+ }
255
+ this.seek(offset);
256
+ return this;
257
+ }
258
+ /**
259
+ * Move the pointer offset back to 0.
260
+ * @returns This.
261
+ */
262
+ rewind() {
263
+ this.offset = 0;
264
+ return this;
265
+ }
266
+ /**
267
+ * Make sure the buffer has sufficient memory to write a given byteLength at
268
+ * the current pointer offset.
269
+ * If the buffer's memory is insufficient, this method will create a new
270
+ * buffer (a copy) with a length that is twice (byteLength + current offset).
271
+ * @param byteLength - The needed memory in bytes.
272
+ * @returns This.
273
+ */
274
+ ensureAvailable(byteLength = 1) {
275
+ if (!this.available(byteLength)) {
276
+ const lengthNeeded = this.offset + byteLength;
277
+ const newLength = lengthNeeded * 2;
278
+ const newArray = new Uint8Array(newLength);
279
+ newArray.set(new Uint8Array(this.buffer));
280
+ this.buffer = newArray.buffer;
281
+ this.length = newLength;
282
+ this.byteLength = newLength;
283
+ this._data = new DataView(this.buffer);
284
+ }
285
+ return this;
286
+ }
287
+ /**
288
+ * Read a byte and return false if the byte's value is 0, or true otherwise.
289
+ * Moves pointer forward by one byte.
290
+ * @returns The read boolean.
291
+ */
292
+ readBoolean() {
293
+ return this.readUint8() !== 0;
294
+ }
295
+ /**
296
+ * Read a signed 8-bit integer and move pointer forward by 1 byte.
297
+ * @returns The read byte.
298
+ */
299
+ readInt8() {
300
+ return this._data.getInt8(this.offset++);
301
+ }
302
+ /**
303
+ * Read an unsigned 8-bit integer and move pointer forward by 1 byte.
304
+ * @returns The read byte.
305
+ */
306
+ readUint8() {
307
+ return this._data.getUint8(this.offset++);
308
+ }
309
+ /**
310
+ * Alias for {@link IOBuffer#readUint8}.
311
+ * @returns The read byte.
312
+ */
313
+ readByte() {
314
+ return this.readUint8();
315
+ }
316
+ /**
317
+ * Read `n` bytes and move pointer forward by `n` bytes.
318
+ * @param n - Number of bytes to read.
319
+ * @returns The read bytes.
320
+ */
321
+ readBytes(n = 1) {
322
+ return this.readArray(n, "uint8");
323
+ }
324
+ /**
325
+ * Creates an array of corresponding to the type `type` and size `size`.
326
+ * For example, type `uint8` will create a `Uint8Array`.
327
+ * @param size - size of the resulting array
328
+ * @param type - number type of elements to read
329
+ * @returns The read array.
330
+ */
331
+ readArray(size, type) {
332
+ const bytes = typedArrays[type].BYTES_PER_ELEMENT * size;
333
+ const offset = this.byteOffset + this.offset;
334
+ const slice = this.buffer.slice(offset, offset + bytes);
335
+ if (this.littleEndian === hostBigEndian && type !== "uint8" && type !== "int8") {
336
+ const slice2 = new Uint8Array(this.buffer.slice(offset, offset + bytes));
337
+ slice2.reverse();
338
+ const returnArray2 = new typedArrays[type](slice2.buffer);
339
+ this.offset += bytes;
340
+ returnArray2.reverse();
341
+ return returnArray2;
342
+ }
343
+ const returnArray = new typedArrays[type](slice);
344
+ this.offset += bytes;
345
+ return returnArray;
346
+ }
347
+ /**
348
+ * Read a 16-bit signed integer and move pointer forward by 2 bytes.
349
+ * @returns The read value.
350
+ */
351
+ readInt16() {
352
+ const value = this._data.getInt16(this.offset, this.littleEndian);
353
+ this.offset += 2;
354
+ return value;
355
+ }
356
+ /**
357
+ * Read a 16-bit unsigned integer and move pointer forward by 2 bytes.
358
+ * @returns The read value.
359
+ */
360
+ readUint16() {
361
+ const value = this._data.getUint16(this.offset, this.littleEndian);
362
+ this.offset += 2;
363
+ return value;
364
+ }
365
+ /**
366
+ * Read a 32-bit signed integer and move pointer forward by 4 bytes.
367
+ * @returns The read value.
368
+ */
369
+ readInt32() {
370
+ const value = this._data.getInt32(this.offset, this.littleEndian);
371
+ this.offset += 4;
372
+ return value;
373
+ }
374
+ /**
375
+ * Read a 32-bit unsigned integer and move pointer forward by 4 bytes.
376
+ * @returns The read value.
377
+ */
378
+ readUint32() {
379
+ const value = this._data.getUint32(this.offset, this.littleEndian);
380
+ this.offset += 4;
381
+ return value;
382
+ }
383
+ /**
384
+ * Read a 32-bit floating number and move pointer forward by 4 bytes.
385
+ * @returns The read value.
386
+ */
387
+ readFloat32() {
388
+ const value = this._data.getFloat32(this.offset, this.littleEndian);
389
+ this.offset += 4;
390
+ return value;
391
+ }
392
+ /**
393
+ * Read a 64-bit floating number and move pointer forward by 8 bytes.
394
+ * @returns The read value.
395
+ */
396
+ readFloat64() {
397
+ const value = this._data.getFloat64(this.offset, this.littleEndian);
398
+ this.offset += 8;
399
+ return value;
400
+ }
401
+ /**
402
+ * Read a 64-bit signed integer number and move pointer forward by 8 bytes.
403
+ * @returns The read value.
404
+ */
405
+ readBigInt64() {
406
+ const value = this._data.getBigInt64(this.offset, this.littleEndian);
407
+ this.offset += 8;
408
+ return value;
409
+ }
410
+ /**
411
+ * Read a 64-bit unsigned integer number and move pointer forward by 8 bytes.
412
+ * @returns The read value.
413
+ */
414
+ readBigUint64() {
415
+ const value = this._data.getBigUint64(this.offset, this.littleEndian);
416
+ this.offset += 8;
417
+ return value;
418
+ }
419
+ /**
420
+ * Read a 1-byte ASCII character and move pointer forward by 1 byte.
421
+ * @returns The read character.
422
+ */
423
+ readChar() {
424
+ return String.fromCharCode(this.readInt8());
425
+ }
426
+ /**
427
+ * Read `n` 1-byte ASCII characters and move pointer forward by `n` bytes.
428
+ * @param n - Number of characters to read.
429
+ * @returns The read characters.
430
+ */
431
+ readChars(n = 1) {
432
+ let result = "";
433
+ for (let i = 0; i < n; i++) {
434
+ result += this.readChar();
435
+ }
436
+ return result;
437
+ }
438
+ /**
439
+ * Read the next `n` bytes, return a UTF-8 decoded string and move pointer
440
+ * forward by `n` bytes.
441
+ * @param n - Number of bytes to read.
442
+ * @returns The decoded string.
443
+ */
444
+ readUtf8(n = 1) {
445
+ return decode(this.readBytes(n));
446
+ }
447
+ /**
448
+ * Read the next `n` bytes, return a string decoded with `encoding` and move pointer
449
+ * forward by `n` bytes.
450
+ * If no encoding is passed, the function is equivalent to @see {@link IOBuffer#readUtf8}
451
+ * @param n - Number of bytes to read.
452
+ * @param encoding - The encoding to use. Default is 'utf8'.
453
+ * @returns The decoded string.
454
+ */
455
+ decodeText(n = 1, encoding = "utf8") {
456
+ return decode(this.readBytes(n), encoding);
457
+ }
458
+ /**
459
+ * Write 0xff if the passed value is truthy, 0x00 otherwise and move pointer
460
+ * forward by 1 byte.
461
+ * @param value - The value to write.
462
+ * @returns This.
463
+ */
464
+ writeBoolean(value) {
465
+ this.writeUint8(value ? 255 : 0);
466
+ return this;
467
+ }
468
+ /**
469
+ * Write `value` as an 8-bit signed integer and move pointer forward by 1 byte.
470
+ * @param value - The value to write.
471
+ * @returns This.
472
+ */
473
+ writeInt8(value) {
474
+ this.ensureAvailable(1);
475
+ this._data.setInt8(this.offset++, value);
476
+ this._updateLastWrittenByte();
477
+ return this;
478
+ }
479
+ /**
480
+ * Write `value` as an 8-bit unsigned integer and move pointer forward by 1
481
+ * byte.
482
+ * @param value - The value to write.
483
+ * @returns This.
484
+ */
485
+ writeUint8(value) {
486
+ this.ensureAvailable(1);
487
+ this._data.setUint8(this.offset++, value);
488
+ this._updateLastWrittenByte();
489
+ return this;
490
+ }
491
+ /**
492
+ * An alias for {@link IOBuffer#writeUint8}.
493
+ * @param value - The value to write.
494
+ * @returns This.
495
+ */
496
+ writeByte(value) {
497
+ return this.writeUint8(value);
498
+ }
499
+ /**
500
+ * Write all elements of `bytes` as uint8 values and move pointer forward by
501
+ * `bytes.length` bytes.
502
+ * @param bytes - The array of bytes to write.
503
+ * @returns This.
504
+ */
505
+ writeBytes(bytes) {
506
+ this.ensureAvailable(bytes.length);
507
+ for (let i = 0; i < bytes.length; i++) {
508
+ this._data.setUint8(this.offset++, bytes[i]);
509
+ }
510
+ this._updateLastWrittenByte();
511
+ return this;
512
+ }
513
+ /**
514
+ * Write `value` as a 16-bit signed integer and move pointer forward by 2
515
+ * bytes.
516
+ * @param value - The value to write.
517
+ * @returns This.
518
+ */
519
+ writeInt16(value) {
520
+ this.ensureAvailable(2);
521
+ this._data.setInt16(this.offset, value, this.littleEndian);
522
+ this.offset += 2;
523
+ this._updateLastWrittenByte();
524
+ return this;
525
+ }
526
+ /**
527
+ * Write `value` as a 16-bit unsigned integer and move pointer forward by 2
528
+ * bytes.
529
+ * @param value - The value to write.
530
+ * @returns This.
531
+ */
532
+ writeUint16(value) {
533
+ this.ensureAvailable(2);
534
+ this._data.setUint16(this.offset, value, this.littleEndian);
535
+ this.offset += 2;
536
+ this._updateLastWrittenByte();
537
+ return this;
538
+ }
539
+ /**
540
+ * Write `value` as a 32-bit signed integer and move pointer forward by 4
541
+ * bytes.
542
+ * @param value - The value to write.
543
+ * @returns This.
544
+ */
545
+ writeInt32(value) {
546
+ this.ensureAvailable(4);
547
+ this._data.setInt32(this.offset, value, this.littleEndian);
548
+ this.offset += 4;
549
+ this._updateLastWrittenByte();
550
+ return this;
551
+ }
552
+ /**
553
+ * Write `value` as a 32-bit unsigned integer and move pointer forward by 4
554
+ * bytes.
555
+ * @param value - The value to write.
556
+ * @returns This.
557
+ */
558
+ writeUint32(value) {
559
+ this.ensureAvailable(4);
560
+ this._data.setUint32(this.offset, value, this.littleEndian);
561
+ this.offset += 4;
562
+ this._updateLastWrittenByte();
563
+ return this;
564
+ }
565
+ /**
566
+ * Write `value` as a 32-bit floating number and move pointer forward by 4
567
+ * bytes.
568
+ * @param value - The value to write.
569
+ * @returns This.
570
+ */
571
+ writeFloat32(value) {
572
+ this.ensureAvailable(4);
573
+ this._data.setFloat32(this.offset, value, this.littleEndian);
574
+ this.offset += 4;
575
+ this._updateLastWrittenByte();
576
+ return this;
577
+ }
578
+ /**
579
+ * Write `value` as a 64-bit floating number and move pointer forward by 8
580
+ * bytes.
581
+ * @param value - The value to write.
582
+ * @returns This.
583
+ */
584
+ writeFloat64(value) {
585
+ this.ensureAvailable(8);
586
+ this._data.setFloat64(this.offset, value, this.littleEndian);
587
+ this.offset += 8;
588
+ this._updateLastWrittenByte();
589
+ return this;
590
+ }
591
+ /**
592
+ * Write `value` as a 64-bit signed bigint and move pointer forward by 8
593
+ * bytes.
594
+ * @param value - The value to write.
595
+ * @returns This.
596
+ */
597
+ writeBigInt64(value) {
598
+ this.ensureAvailable(8);
599
+ this._data.setBigInt64(this.offset, value, this.littleEndian);
600
+ this.offset += 8;
601
+ this._updateLastWrittenByte();
602
+ return this;
603
+ }
604
+ /**
605
+ * Write `value` as a 64-bit unsigned bigint and move pointer forward by 8
606
+ * bytes.
607
+ * @param value - The value to write.
608
+ * @returns This.
609
+ */
610
+ writeBigUint64(value) {
611
+ this.ensureAvailable(8);
612
+ this._data.setBigUint64(this.offset, value, this.littleEndian);
613
+ this.offset += 8;
614
+ this._updateLastWrittenByte();
615
+ return this;
616
+ }
617
+ /**
618
+ * Write the charCode of `str`'s first character as an 8-bit unsigned integer
619
+ * and move pointer forward by 1 byte.
620
+ * @param str - The character to write.
621
+ * @returns This.
622
+ */
623
+ writeChar(str) {
624
+ return this.writeUint8(str.charCodeAt(0));
625
+ }
626
+ /**
627
+ * Write the charCodes of all `str`'s characters as 8-bit unsigned integers
628
+ * and move pointer forward by `str.length` bytes.
629
+ * @param str - The characters to write.
630
+ * @returns This.
631
+ */
632
+ writeChars(str) {
633
+ for (let i = 0; i < str.length; i++) {
634
+ this.writeUint8(str.charCodeAt(i));
635
+ }
636
+ return this;
637
+ }
638
+ /**
639
+ * UTF-8 encode and write `str` to the current pointer offset and move pointer
640
+ * forward according to the encoded length.
641
+ * @param str - The string to write.
642
+ * @returns This.
643
+ */
644
+ writeUtf8(str) {
645
+ return this.writeBytes(encode(str));
646
+ }
647
+ /**
648
+ * Export a Uint8Array view of the internal buffer.
649
+ * The view starts at the byte offset and its length
650
+ * is calculated to stop at the last written byte or the original length.
651
+ * @returns A new Uint8Array view.
652
+ */
653
+ toArray() {
654
+ return new Uint8Array(this.buffer, this.byteOffset, this.lastWrittenByte);
655
+ }
656
+ /**
657
+ * Get the total number of bytes written so far, regardless of the current offset.
658
+ * @returns - Total number of bytes.
659
+ */
660
+ getWrittenByteLength() {
661
+ return this.lastWrittenByte - this.byteOffset;
662
+ }
663
+ /**
664
+ * Update the last written byte offset
665
+ * @private
666
+ */
667
+ _updateLastWrittenByte() {
668
+ if (this.offset > this.lastWrittenByte) {
669
+ this.lastWrittenByte = this.offset;
670
+ }
671
+ }
672
+ };
673
+
674
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/helpers/crc.js
675
+ var crcTable = [];
676
+ for (let n = 0; n < 256; n++) {
677
+ let c = n;
678
+ for (let k = 0; k < 8; k++) {
679
+ if (c & 1) {
680
+ c = 3988292384 ^ c >>> 1;
681
+ } else {
682
+ c = c >>> 1;
683
+ }
684
+ }
685
+ crcTable[n] = c;
686
+ }
687
+ var initialCrc = 4294967295;
688
+ function updateCrc(currentCrc, data, length) {
689
+ let c = currentCrc;
690
+ for (let n = 0; n < length; n++) {
691
+ c = crcTable[(c ^ data[n]) & 255] ^ c >>> 8;
692
+ }
693
+ return c;
694
+ }
695
+ function crc(data, length) {
696
+ return (updateCrc(initialCrc, data, length) ^ initialCrc) >>> 0;
697
+ }
698
+ function writeCrc(buffer, length) {
699
+ buffer.writeUint32(crc(new Uint8Array(buffer.buffer, buffer.byteOffset + buffer.offset - length, length), length));
700
+ }
701
+
702
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/helpers/decode_interlace_adam7.js
703
+ var uint16 = new Uint16Array([255]);
704
+ var uint8 = new Uint8Array(uint16.buffer);
705
+ var osIsLittleEndian = uint8[0] === 255;
706
+
707
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/helpers/decode_interlace_null.js
708
+ var uint162 = new Uint16Array([255]);
709
+ var uint82 = new Uint8Array(uint162.buffer);
710
+ var osIsLittleEndian2 = uint82[0] === 255;
711
+ var empty = new Uint8Array(0);
712
+
713
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/helpers/signature.js
714
+ var pngSignature = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);
715
+ function writeSignature(buffer) {
716
+ buffer.writeBytes(pngSignature);
717
+ }
718
+
719
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/helpers/text.js
720
+ var textChunkName = "tEXt";
721
+ var NULL = 0;
722
+ var latin1Decoder = new TextDecoder("latin1");
723
+ function validateKeyword(keyword) {
724
+ validateLatin1(keyword);
725
+ if (keyword.length === 0 || keyword.length > 79) {
726
+ throw new Error("keyword length must be between 1 and 79");
727
+ }
728
+ }
729
+ var latin1Regex = /^[\u0000-\u00FF]*$/;
730
+ function validateLatin1(text2) {
731
+ if (!latin1Regex.test(text2)) {
732
+ throw new Error("invalid latin1 text");
733
+ }
734
+ }
735
+ function encodetEXt(buffer, keyword, text2) {
736
+ validateKeyword(keyword);
737
+ validateLatin1(text2);
738
+ const length = keyword.length + 1 + text2.length;
739
+ buffer.writeUint32(length);
740
+ buffer.writeChars(textChunkName);
741
+ buffer.writeChars(keyword);
742
+ buffer.writeByte(NULL);
743
+ buffer.writeChars(text2);
744
+ writeCrc(buffer, length + 4);
745
+ }
746
+
747
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/internal_types.js
748
+ var ColorType = {
749
+ UNKNOWN: -1,
750
+ GREYSCALE: 0,
751
+ TRUECOLOUR: 2,
752
+ INDEXED_COLOUR: 3,
753
+ GREYSCALE_ALPHA: 4,
754
+ TRUECOLOUR_ALPHA: 6
755
+ };
756
+ var CompressionMethod = {
757
+ UNKNOWN: -1,
758
+ DEFLATE: 0
759
+ };
760
+ var FilterMethod = {
761
+ UNKNOWN: -1,
762
+ ADAPTIVE: 0
763
+ };
764
+ var InterlaceMethod = {
765
+ UNKNOWN: -1,
766
+ NO_INTERLACE: 0,
767
+ ADAM7: 1
768
+ };
769
+
770
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/png_encoder.js
771
+ var import_fflate2 = require("fflate");
772
+ var defaultZlibOptions = {
773
+ level: 3
774
+ };
775
+ var PngEncoder = class extends IOBuffer {
776
+ _png;
777
+ _zlibOptions;
778
+ _colorType;
779
+ _interlaceMethod;
780
+ constructor(data, options = {}) {
781
+ super();
782
+ this._colorType = ColorType.UNKNOWN;
783
+ this._zlibOptions = { ...defaultZlibOptions, ...options.zlib };
784
+ this._png = this._checkData(data);
785
+ this._interlaceMethod = (options.interlace === "Adam7" ? InterlaceMethod.ADAM7 : InterlaceMethod.NO_INTERLACE) ?? InterlaceMethod.NO_INTERLACE;
786
+ this.setBigEndian();
787
+ }
788
+ encode() {
789
+ writeSignature(this);
790
+ this.encodeIHDR();
791
+ if (this._png.palette) {
792
+ this.encodePLTE();
793
+ if (this._png.palette[0].length === 4) {
794
+ this.encodeTRNS();
795
+ }
796
+ }
797
+ this.encodeData();
798
+ if (this._png.text) {
799
+ for (const [keyword, text2] of Object.entries(this._png.text)) {
800
+ encodetEXt(this, keyword, text2);
801
+ }
802
+ }
803
+ this.encodeIEND();
804
+ return this.toArray();
805
+ }
806
+ // https://www.w3.org/TR/PNG/#11IHDR
807
+ encodeIHDR() {
808
+ this.writeUint32(13);
809
+ this.writeChars("IHDR");
810
+ this.writeUint32(this._png.width);
811
+ this.writeUint32(this._png.height);
812
+ this.writeByte(this._png.depth);
813
+ this.writeByte(this._colorType);
814
+ this.writeByte(CompressionMethod.DEFLATE);
815
+ this.writeByte(FilterMethod.ADAPTIVE);
816
+ this.writeByte(this._interlaceMethod);
817
+ writeCrc(this, 17);
818
+ }
819
+ // https://www.w3.org/TR/PNG/#11IEND
820
+ encodeIEND() {
821
+ this.writeUint32(0);
822
+ this.writeChars("IEND");
823
+ writeCrc(this, 4);
824
+ }
825
+ encodePLTE() {
826
+ const paletteLength = this._png.palette?.length * 3;
827
+ this.writeUint32(paletteLength);
828
+ this.writeChars("PLTE");
829
+ for (const color of this._png.palette) {
830
+ this.writeByte(color[0]);
831
+ this.writeByte(color[1]);
832
+ this.writeByte(color[2]);
833
+ }
834
+ writeCrc(this, 4 + paletteLength);
835
+ }
836
+ encodeTRNS() {
837
+ const alpha = this._png.palette.filter((color) => {
838
+ return color.at(-1) !== 255;
839
+ });
840
+ this.writeUint32(alpha.length);
841
+ this.writeChars("tRNS");
842
+ for (const el of alpha) {
843
+ this.writeByte(el.at(-1));
844
+ }
845
+ writeCrc(this, 4 + alpha.length);
846
+ }
847
+ // https://www.w3.org/TR/PNG/#11IDAT
848
+ encodeIDAT(data) {
849
+ this.writeUint32(data.length);
850
+ this.writeChars("IDAT");
851
+ this.writeBytes(data);
852
+ writeCrc(this, data.length + 4);
853
+ }
854
+ encodeData() {
855
+ const { width, height, channels, depth, data } = this._png;
856
+ const slotsPerLine = depth <= 8 ? Math.ceil(width * depth / 8) * channels : Math.ceil(width * depth / 8 * channels / 2);
857
+ const newData = new IOBuffer().setBigEndian();
858
+ let offset = 0;
859
+ if (this._interlaceMethod === InterlaceMethod.NO_INTERLACE) {
860
+ for (let i = 0; i < height; i++) {
861
+ newData.writeByte(0);
862
+ if (depth === 16) {
863
+ offset = writeDataUint16(data, newData, slotsPerLine, offset);
864
+ } else {
865
+ offset = writeDataBytes(data, newData, slotsPerLine, offset);
866
+ }
867
+ }
868
+ } else if (this._interlaceMethod === InterlaceMethod.ADAM7) {
869
+ offset = writeDataInterlaced(this._png, data, newData, offset);
870
+ }
871
+ const buffer = newData.toArray();
872
+ const compressed = (0, import_fflate2.zlibSync)(buffer, this._zlibOptions);
873
+ this.encodeIDAT(compressed);
874
+ }
875
+ _checkData(data) {
876
+ const { colorType, channels, depth } = getColorType(data, data.palette);
877
+ const png = {
878
+ width: checkInteger(data.width, "width"),
879
+ height: checkInteger(data.height, "height"),
880
+ channels,
881
+ data: data.data,
882
+ depth,
883
+ text: data.text,
884
+ palette: data.palette
885
+ };
886
+ this._colorType = colorType;
887
+ const expectedSize = depth < 8 ? Math.ceil(png.width * depth / 8) * png.height * channels : png.width * png.height * channels;
888
+ if (png.data.length !== expectedSize) {
889
+ throw new RangeError(`wrong data size. Found ${png.data.length}, expected ${expectedSize}`);
890
+ }
891
+ return png;
892
+ }
893
+ };
894
+ function checkInteger(value, name) {
895
+ if (Number.isInteger(value) && value > 0) {
896
+ return value;
897
+ }
898
+ throw new TypeError(`${name} must be a positive integer`);
899
+ }
900
+ function getColorType(data, palette) {
901
+ const { channels = 4, depth = 8 } = data;
902
+ if (channels !== 4 && channels !== 3 && channels !== 2 && channels !== 1) {
903
+ throw new RangeError(`unsupported number of channels: ${channels}`);
904
+ }
905
+ const returnValue = {
906
+ channels,
907
+ depth,
908
+ colorType: ColorType.UNKNOWN
909
+ };
910
+ switch (channels) {
911
+ case 4:
912
+ returnValue.colorType = ColorType.TRUECOLOUR_ALPHA;
913
+ break;
914
+ case 3:
915
+ returnValue.colorType = ColorType.TRUECOLOUR;
916
+ break;
917
+ case 1:
918
+ if (palette) {
919
+ returnValue.colorType = ColorType.INDEXED_COLOUR;
920
+ } else {
921
+ returnValue.colorType = ColorType.GREYSCALE;
922
+ }
923
+ break;
924
+ case 2:
925
+ returnValue.colorType = ColorType.GREYSCALE_ALPHA;
926
+ break;
927
+ default:
928
+ throw new Error("unsupported number of channels");
929
+ }
930
+ return returnValue;
931
+ }
932
+ function writeDataBytes(data, newData, slotsPerLine, offset) {
933
+ for (let j = 0; j < slotsPerLine; j++) {
934
+ newData.writeByte(data[offset++]);
935
+ }
936
+ return offset;
937
+ }
938
+ function writeDataInterlaced(imageData, data, newData, offset) {
939
+ const passes = [
940
+ { x: 0, y: 0, xStep: 8, yStep: 8 },
941
+ { x: 4, y: 0, xStep: 8, yStep: 8 },
942
+ { x: 0, y: 4, xStep: 4, yStep: 8 },
943
+ { x: 2, y: 0, xStep: 4, yStep: 4 },
944
+ { x: 0, y: 2, xStep: 2, yStep: 4 },
945
+ { x: 1, y: 0, xStep: 2, yStep: 2 },
946
+ { x: 0, y: 1, xStep: 1, yStep: 2 }
947
+ ];
948
+ const { width, height, channels, depth } = imageData;
949
+ let pixelSize;
950
+ if (depth === 16) {
951
+ pixelSize = channels * depth / 8 / 2;
952
+ } else {
953
+ pixelSize = channels * depth / 8;
954
+ }
955
+ for (let passIndex = 0; passIndex < 7; passIndex++) {
956
+ const pass = passes[passIndex];
957
+ const passWidth = Math.floor((width - pass.x + pass.xStep - 1) / pass.xStep);
958
+ const passHeight = Math.floor((height - pass.y + pass.yStep - 1) / pass.yStep);
959
+ if (passWidth <= 0 || passHeight <= 0)
960
+ continue;
961
+ const passLineBytes = passWidth * pixelSize;
962
+ for (let y = 0; y < passHeight; y++) {
963
+ const imageY = pass.y + y * pass.yStep;
964
+ const rawScanline = depth <= 8 ? new Uint8Array(passLineBytes) : new Uint16Array(passLineBytes);
965
+ let rawOffset = 0;
966
+ for (let x = 0; x < passWidth; x++) {
967
+ const imageX = pass.x + x * pass.xStep;
968
+ if (imageX < width && imageY < height) {
969
+ const srcPos = (imageY * width + imageX) * pixelSize;
970
+ for (let i = 0; i < pixelSize; i++) {
971
+ rawScanline[rawOffset++] = data[srcPos + i];
972
+ }
973
+ }
974
+ }
975
+ newData.writeByte(0);
976
+ if (depth === 8) {
977
+ newData.writeBytes(rawScanline);
978
+ } else if (depth === 16) {
979
+ for (const value of rawScanline) {
980
+ newData.writeByte(value >> 8 & 255);
981
+ newData.writeByte(value & 255);
982
+ }
983
+ }
984
+ }
985
+ }
986
+ return offset;
987
+ }
988
+ function writeDataUint16(data, newData, slotsPerLine, offset) {
989
+ for (let j = 0; j < slotsPerLine; j++) {
990
+ newData.writeUint16(data[offset++]);
991
+ }
992
+ return offset;
993
+ }
994
+
995
+ // node_modules/.pnpm/fast-png@8.0.0/node_modules/fast-png/lib/index.js
996
+ function encodePng(png, options) {
997
+ const encoder2 = new PngEncoder(png, options);
998
+ return encoder2.encode();
999
+ }
1000
+
1001
+ // src/stage/export.ts
1002
+ var gifenc = __toESM(require("gifenc"), 1);
1003
+
1004
+ // src/video.ts
1005
+ var import_child_process = require("child_process");
1006
+ var import_crypto = require("crypto");
1007
+ var import_promises2 = require("fs/promises");
1008
+ var import_path2 = require("path");
1009
+ var import_resvg_js2 = require("@resvg/resvg-js");
1010
+ var import_parse_css_color = __toESM(require("parse-css-color"), 1);
1011
+
1012
+ // src/render.ts
1013
+ var import_resvg_js = require("@resvg/resvg-js");
1014
+ var import_os = require("os");
1015
+ var import_promises = require("fs/promises");
1016
+ var import_path = require("path");
1017
+ var import_fs = require("fs");
1018
+ var import_url = require("url");
1019
+ var import_zlib = require("zlib");
1020
+
1021
+ // src/brand.ts
1022
+ var import_react = __toESM(require("react"), 1);
1023
+ var DEFAULT_WATERMARK_TEXT = "Vizmatic";
1024
+ var WATERMARK_COLOR_DARK = "#a5a7ad";
1025
+ var WATERMARK_COLOR_LIGHT = "#5e5a50";
1026
+ function VizmaticIcon({ size = 14, color }) {
1027
+ return import_react.default.createElement(
1028
+ "svg",
1029
+ {
1030
+ xmlns: "http://www.w3.org/2000/svg",
1031
+ width: size,
1032
+ height: size,
1033
+ viewBox: "0 0 28 28",
1034
+ fill: "none"
1035
+ },
1036
+ import_react.default.createElement("rect", { x: 2.5, y: 2.5, width: 23, height: 23, rx: 6.5, stroke: color, strokeWidth: 2, opacity: 0.54 }),
1037
+ import_react.default.createElement("rect", { x: 7, y: 7, width: 5.5, height: 5.5, rx: 1.8, fill: color, opacity: 0.35 }),
1038
+ import_react.default.createElement("rect", { x: 15.5, y: 7, width: 5.5, height: 5.5, rx: 1.8, fill: color }),
1039
+ import_react.default.createElement("rect", { x: 7, y: 15.5, width: 5.5, height: 5.5, rx: 1.8, fill: color, opacity: 0.82 }),
1040
+ import_react.default.createElement("rect", { x: 15.5, y: 15.5, width: 5.5, height: 5.5, rx: 1.8, stroke: color, strokeWidth: 1.5, opacity: 0.72 }),
1041
+ import_react.default.createElement("path", { d: "M9.75 9.75h8.5M9.75 18.25h8.5M9.75 9.75v8.5M18.25 9.75v8.5", stroke: color, strokeWidth: 1.6, strokeLinecap: "round", opacity: 0.88 })
1042
+ );
1043
+ }
1044
+ function normalizeWatermark(watermark) {
1045
+ if (watermark == null || watermark === false) return void 0;
1046
+ if (watermark === true) return {};
1047
+ if (typeof watermark === "string") return { text: watermark };
1048
+ if (import_react.default.isValidElement(watermark)) {
1049
+ if (watermark.type !== Watermark) return { element: watermark };
1050
+ const { children, ...props } = watermark.props;
1051
+ return {
1052
+ ...props,
1053
+ element: children ?? props.element
1054
+ };
1055
+ }
1056
+ return watermark;
1057
+ }
1058
+ function Watermark(_props) {
1059
+ return null;
1060
+ }
1061
+ function positionStyle(position) {
1062
+ switch (position) {
1063
+ case "top-left":
1064
+ return { top: 8, left: 10 };
1065
+ case "bottom-left":
1066
+ return { bottom: 8, left: 10 };
1067
+ case "bottom-right":
1068
+ return { bottom: 8, right: 10 };
1069
+ case "top-right":
1070
+ default:
1071
+ return { top: 8, right: 10 };
1072
+ }
1073
+ }
1074
+ function imageNode(image) {
1075
+ if (!image) return void 0;
1076
+ const imageOptions = typeof image === "string" ? { src: image } : image;
1077
+ return import_react.default.createElement("img", {
1078
+ src: imageOptions.src,
1079
+ alt: imageOptions.alt ?? "",
1080
+ width: imageOptions.width ?? 14,
1081
+ height: imageOptions.height ?? 14,
1082
+ style: {
1083
+ display: "block",
1084
+ width: imageOptions.width ?? 14,
1085
+ height: imageOptions.height ?? 14,
1086
+ objectFit: "contain"
1087
+ }
1088
+ });
1089
+ }
1090
+ function iconNode(icon, color) {
1091
+ if (icon === false) return void 0;
1092
+ if (icon == null) return import_react.default.createElement(VizmaticIcon, { size: 13, color });
1093
+ if (typeof icon !== "string") return icon;
1094
+ return import_react.default.createElement("div", {
1095
+ style: {
1096
+ minWidth: 13,
1097
+ height: 13,
1098
+ display: "flex",
1099
+ alignItems: "center",
1100
+ justifyContent: "center",
1101
+ color,
1102
+ fontSize: icon.length > 2 ? 8 : 10,
1103
+ fontWeight: 800,
1104
+ fontFamily: "Inter",
1105
+ lineHeight: 1
1106
+ }
1107
+ }, icon);
1108
+ }
1109
+ function wrapWithWatermark(element, width, height, theme = "dark", watermark = true) {
1110
+ const isDark = theme === "dark";
1111
+ const options = normalizeWatermark(watermark);
1112
+ const color = options?.color ?? (isDark ? WATERMARK_COLOR_DARK : WATERMARK_COLOR_LIGHT);
1113
+ const position = options?.position ?? "top-right";
1114
+ const opacity = options?.opacity ?? (isDark ? 0.55 : 0.4);
1115
+ const icon = options ? imageNode(options.image) ?? iconNode(options.icon, color) : void 0;
1116
+ const text2 = options?.text ?? DEFAULT_WATERMARK_TEXT;
1117
+ const content = options?.element ?? [
1118
+ icon,
1119
+ text2 !== false && text2 && import_react.default.createElement("div", {
1120
+ key: "text",
1121
+ style: {
1122
+ fontSize: 11,
1123
+ fontWeight: 600,
1124
+ color,
1125
+ fontFamily: "Inter",
1126
+ letterSpacing: 0.3
1127
+ }
1128
+ }, text2)
1129
+ ];
1130
+ return import_react.default.createElement(
1131
+ "div",
1132
+ {
1133
+ style: {
1134
+ width,
1135
+ height,
1136
+ display: "flex",
1137
+ position: "relative"
1138
+ }
1139
+ },
1140
+ element,
1141
+ options && import_react.default.createElement(
1142
+ "div",
1143
+ {
1144
+ style: {
1145
+ position: "absolute",
1146
+ ...positionStyle(position),
1147
+ display: "flex",
1148
+ alignItems: "center",
1149
+ gap: 5,
1150
+ opacity
1151
+ }
1152
+ },
1153
+ content
1154
+ )
1155
+ );
1156
+ }
1157
+
1158
+ // src/renderContext.ts
1159
+ var import_async_hooks = require("async_hooks");
1160
+
1161
+ // src/density.ts
1162
+ var sharedKey = /* @__PURE__ */ Symbol.for("vizmatic.density");
1163
+ var globals = globalThis;
1164
+ var shared = globals[sharedKey] ??= { resolvers: /* @__PURE__ */ new Set() };
1165
+ function setDensityResolver(resolver) {
1166
+ shared.resolvers.add(resolver);
1167
+ }
1168
+
1169
+ // src/renderContext.ts
1170
+ var RENDER_CONTEXT_KEY = /* @__PURE__ */ Symbol.for("vizmatic.renderContext");
1171
+ var globalRenderContext = globalThis;
1172
+ var renderContext = globalRenderContext[RENDER_CONTEXT_KEY] ??= new import_async_hooks.AsyncLocalStorage();
1173
+ setDensityResolver(() => renderContext.getStore()?.density);
1174
+ async function withRenderContext(context, render) {
1175
+ const parent = renderContext.getStore();
1176
+ return renderContext.run({ ...parent, ...context }, render);
1177
+ }
1178
+
1179
+ // src/satori.ts
1180
+ var satoriModule = __toESM(require("satori"), 1);
1181
+
1182
+ // src/canvas-chart-fit.ts
1183
+ var import_react2 = __toESM(require("react"), 1);
1184
+ var FIT_PROP = "__vizmaticCanvasChartFit";
1185
+ var SCOPE_PROP = "data-vizmatic-chart-fit-scope";
1186
+ var VIEWPORT_PROP = "data-vizmatic-chart-fit-viewport";
1187
+ function prepareChartFits(element) {
1188
+ const sizes = /* @__PURE__ */ new Map();
1189
+ const hasText = (node) => {
1190
+ if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") return true;
1191
+ if (Array.isArray(node)) return node.some(hasText);
1192
+ return (0, import_react2.isValidElement)(node) && node.type === import_react2.default.Fragment && hasText(node.props.children);
1193
+ };
1194
+ const visit = (node, scope) => {
1195
+ if (Array.isArray(node)) return node.map((child) => visit(child, scope));
1196
+ if (!(0, import_react2.isValidElement)(node)) return node;
1197
+ const forwarded = node.type;
1198
+ const render = typeof node.type === "function" ? node.type : forwarded?.$$typeof === /* @__PURE__ */ Symbol.for("react.forward_ref") ? forwarded.render : void 0;
1199
+ if (render) {
1200
+ const resolved = visit(render(node.props), scope);
1201
+ return node.key != null && (0, import_react2.isValidElement)(resolved) ? import_react2.default.cloneElement(resolved, { key: node.key }) : resolved;
1202
+ }
1203
+ const size = node.props[FIT_PROP];
1204
+ const props = { ...node.props };
1205
+ delete props[FIT_PROP];
1206
+ let childScope = scope;
1207
+ if (size) {
1208
+ const id = String(sizes.size);
1209
+ sizes.set(id, size);
1210
+ props[VIEWPORT_PROP] = id;
1211
+ childScope = id;
1212
+ } else if (scope !== void 0 && typeof node.type === "string") {
1213
+ props[SCOPE_PROP] = scope;
1214
+ }
1215
+ const children = node.props.children;
1216
+ const preparedChildren = children === void 0 ? void 0 : visit(children, childScope);
1217
+ if (typeof node.type === "string") {
1218
+ const style = node.props.style;
1219
+ props.style = {
1220
+ minWidth: 0,
1221
+ minHeight: 0,
1222
+ ...style?.flex === void 0 ? { flexShrink: hasText(preparedChildren) ? 1 : 0 } : {},
1223
+ ...style
1224
+ };
1225
+ }
1226
+ return children === void 0 ? import_react2.default.cloneElement(node, props) : import_react2.default.cloneElement(node, props, preparedChildren);
1227
+ };
1228
+ return { element: visit(element), sizes };
1229
+ }
1230
+ function fittedTree(element, geometry) {
1231
+ if (Array.isArray(element)) return element.map((child) => fittedTree(child, geometry));
1232
+ if (!(0, import_react2.isValidElement)(element)) return element;
1233
+ const id = element.props[VIEWPORT_PROP];
1234
+ const children = element.props.children;
1235
+ if (typeof id === "string") {
1236
+ const fit = geometry.get(id);
1237
+ const content = import_react2.default.Children.only(children);
1238
+ return import_react2.default.cloneElement(element, {}, import_react2.default.cloneElement(content, { style: {
1239
+ ...content.props.style,
1240
+ left: fit.left,
1241
+ top: fit.top,
1242
+ transform: `scale(${fit.scale})`,
1243
+ transformOrigin: "top left"
1244
+ } }));
1245
+ }
1246
+ return children === void 0 ? element : import_react2.default.cloneElement(element, {}, fittedTree(children, geometry));
1247
+ }
1248
+ async function renderWithCanvasChartFit(render, element, options) {
1249
+ const prepared = prepareChartFits(element);
1250
+ if (!prepared.sizes.size) return render(prepared.element, options);
1251
+ const viewports = /* @__PURE__ */ new Map();
1252
+ const bounds = /* @__PURE__ */ new Map();
1253
+ await render(prepared.element, { ...options, onNodeDetected(node) {
1254
+ const viewport = node.props[VIEWPORT_PROP];
1255
+ if (typeof viewport === "string") viewports.set(viewport, node);
1256
+ const id = node.props[SCOPE_PROP];
1257
+ if (typeof id !== "string" || node.width < 0 || node.height < 0) return;
1258
+ const prior = bounds.get(id);
1259
+ bounds.set(id, {
1260
+ left: Math.min(prior?.left ?? Infinity, node.left),
1261
+ top: Math.min(prior?.top ?? Infinity, node.top),
1262
+ right: Math.max(prior?.right ?? -Infinity, node.left + node.width),
1263
+ bottom: Math.max(prior?.bottom ?? -Infinity, node.top + node.height)
1264
+ });
1265
+ } });
1266
+ const geometry = /* @__PURE__ */ new Map();
1267
+ for (const [id, size] of prepared.sizes) {
1268
+ const viewport = viewports.get(id);
1269
+ const measured = bounds.get(id);
1270
+ if (!viewport || !measured) throw new Error("Could not measure the chart inside CanvasItem.");
1271
+ const width = measured.right - measured.left, height = measured.bottom - measured.top;
1272
+ const scale = Math.min(size.width / width, size.height / height);
1273
+ if (!Number.isFinite(scale) || scale <= 0) throw new Error("CanvasItem charts require positive, finite dimensions.");
1274
+ geometry.set(id, {
1275
+ ...size,
1276
+ scale,
1277
+ left: (size.width - width * scale) / 2 - (measured.left - viewport.left) * scale,
1278
+ top: (size.height - height * scale) / 2 - (measured.top - viewport.top) * scale
1279
+ });
1280
+ }
1281
+ const finalViewports = /* @__PURE__ */ new Map();
1282
+ return render(fittedTree(prepared.element, geometry), { ...options, onNodeDetected(node) {
1283
+ const viewport = node.props[VIEWPORT_PROP];
1284
+ if (typeof viewport === "string") finalViewports.set(viewport, node);
1285
+ const id = node.props[SCOPE_PROP];
1286
+ const fit = typeof id === "string" ? geometry.get(id) : void 0;
1287
+ const origin = typeof id === "string" ? finalViewports.get(id) : void 0;
1288
+ if (fit && origin) {
1289
+ const left = origin.left + fit.left, top = origin.top + fit.top;
1290
+ const style = node.props.style ?? {};
1291
+ options.onNodeDetected?.({
1292
+ ...node,
1293
+ left: left + (node.left - left) * fit.scale,
1294
+ top: top + (node.top - top) * fit.scale,
1295
+ width: node.width * fit.scale,
1296
+ height: node.height * fit.scale,
1297
+ props: { ...node.props, style: { ...style, ...typeof style.fontSize === "number" ? { fontSize: style.fontSize * fit.scale } : {} } }
1298
+ });
1299
+ } else options.onNodeDetected?.(node);
1300
+ } });
1301
+ }
1302
+
1303
+ // src/satori.ts
1304
+ function resolveSatori(api) {
1305
+ if (typeof api === "function") return api;
1306
+ if (api && typeof api === "object") {
1307
+ const fallback = api.default;
1308
+ if (typeof fallback === "function") return fallback;
1309
+ if (fallback && typeof fallback === "object") {
1310
+ const nestedFallback = fallback.default;
1311
+ if (typeof nestedFallback === "function") return nestedFallback;
1312
+ }
1313
+ }
1314
+ throw new Error("satori export could not be resolved");
1315
+ }
1316
+ var renderSatori = resolveSatori(satoriModule);
1317
+ var satori = (element, options) => renderWithCanvasChartFit(renderSatori, element, options);
1318
+
1319
+ // src/svg-accessibility.ts
1320
+ var import_react3 = require("react");
1321
+ var SVG_ACCESSIBILITY_COMPONENT = /* @__PURE__ */ Symbol.for("vizmatic.svgAccessibilityComponent");
1322
+ function componentHasSvgMetadata(type) {
1323
+ return typeof type === "function" && type[SVG_ACCESSIBILITY_COMPONENT] === true;
1324
+ }
1325
+ function svgToken(value) {
1326
+ if (value.length === 0) return "empty";
1327
+ return Array.from(value, (character) => {
1328
+ const codePoint = character.codePointAt(0) ?? 0;
1329
+ return /^[A-Za-z0-9.-]$/.test(character) ? character : `_u${codePoint.toString(16)}_`;
1330
+ }).join("");
1331
+ }
1332
+ function textProperty(props, name) {
1333
+ const value = props[name];
1334
+ return typeof value === "string" ? value : "";
1335
+ }
1336
+ function encodedTextProperty(props, name) {
1337
+ const value = textProperty(props, name);
1338
+ try {
1339
+ return decodeURIComponent(value);
1340
+ } catch {
1341
+ return value;
1342
+ }
1343
+ }
1344
+ function prepareAccessibleSvg(element) {
1345
+ const graphs = [];
1346
+ const explicitIds = /* @__PURE__ */ new Set();
1347
+ const visit = (node, graph) => {
1348
+ if (Array.isArray(node)) return node.map((child) => visit(child, graph));
1349
+ if (!(0, import_react3.isValidElement)(node)) return node;
1350
+ const component = node.type;
1351
+ if (componentHasSvgMetadata(component)) {
1352
+ return visit(component(node.props), graph);
1353
+ }
1354
+ const props = node.props;
1355
+ const title = textProperty(props, "data-vizmatic-svg-title");
1356
+ const isGraphRoot = title.length > 0;
1357
+ let activeGraph = graph;
1358
+ let elementKey = node.key;
1359
+ if (isGraphRoot) {
1360
+ const explicitId = textProperty(props, "data-vizmatic-svg-id");
1361
+ if (explicitId) {
1362
+ if (explicitIds.has(explicitId)) {
1363
+ throw new Error(`GraphDiagram SVG id "${explicitId}" must be unique in one exported SVG.`);
1364
+ }
1365
+ explicitIds.add(explicitId);
1366
+ }
1367
+ const index = graphs.length;
1368
+ const token = explicitId ? `id-${svgToken(explicitId)}` : `index-${index}`;
1369
+ activeGraph = {
1370
+ index,
1371
+ token,
1372
+ detectionKey: `vizmatic-graph-${index}`,
1373
+ title,
1374
+ description: textProperty(props, "data-vizmatic-svg-description"),
1375
+ nodes: [],
1376
+ edges: []
1377
+ };
1378
+ graphs.push(activeGraph);
1379
+ elementKey = activeGraph.detectionKey;
1380
+ }
1381
+ let nextProps;
1382
+ if (activeGraph && Object.hasOwn(props, "data-vizmatic-graph-node-id")) {
1383
+ const id = textProperty(props, "data-vizmatic-graph-node-id");
1384
+ const label = textProperty(props, "data-vizmatic-graph-node-label") || id;
1385
+ const detail = textProperty(props, "data-vizmatic-graph-node-detail");
1386
+ activeGraph.nodes.push({
1387
+ id,
1388
+ label,
1389
+ detail,
1390
+ title: textProperty(props, "data-vizmatic-graph-node-title") || label,
1391
+ href: textProperty(props, "data-vizmatic-graph-node-href") || void 0
1392
+ });
1393
+ elementKey = `${activeGraph.detectionKey}-node-${svgToken(id)}`;
1394
+ } else if (activeGraph && textProperty(props, "data-vizmatic-graph-edge-id")) {
1395
+ const id = encodedTextProperty(props, "data-vizmatic-graph-edge-id");
1396
+ activeGraph.edges.push({
1397
+ id,
1398
+ from: encodedTextProperty(props, "data-vizmatic-graph-edge-from"),
1399
+ to: encodedTextProperty(props, "data-vizmatic-graph-edge-to"),
1400
+ label: encodedTextProperty(props, "data-vizmatic-graph-edge-label"),
1401
+ title: encodedTextProperty(props, "data-vizmatic-graph-edge-title"),
1402
+ path: textProperty(props, "d"),
1403
+ href: encodedTextProperty(props, "data-vizmatic-graph-edge-href") || void 0
1404
+ });
1405
+ elementKey = `${activeGraph.detectionKey}-edge-${svgToken(id)}`;
1406
+ }
1407
+ const children = props.children;
1408
+ if (children === void 0) {
1409
+ if (isGraphRoot) {
1410
+ nextProps = { ...props, "data-vizmatic-svg-instance": activeGraph?.token };
1411
+ return (0, import_react3.cloneElement)(node, { ...nextProps, key: elementKey });
1412
+ }
1413
+ return node;
1414
+ }
1415
+ const preparedChildren = visit(children, activeGraph);
1416
+ nextProps = isGraphRoot ? { ...props, "data-vizmatic-svg-instance": activeGraph?.token } : { ...props };
1417
+ return (0, import_react3.cloneElement)(
1418
+ node,
1419
+ { ...nextProps, key: elementKey },
1420
+ preparedChildren
1421
+ );
1422
+ };
1423
+ return { element: visit(element), graphs };
1424
+ }
1425
+ function escapeXml(value) {
1426
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1427
+ }
1428
+ function attribute(name, value) {
1429
+ return `${name}="${escapeXml(value)}"`;
1430
+ }
1431
+ function graphBaseId(graph) {
1432
+ return `vizmatic-graph-${graph.token}`;
1433
+ }
1434
+ function nodeId(graph, node) {
1435
+ return `${graphBaseId(graph)}-node-${svgToken(node.id)}`;
1436
+ }
1437
+ function edgeId(graph, edge) {
1438
+ return `${graphBaseId(graph)}-edge-${svgToken(edge.id)}`;
1439
+ }
1440
+ function labelForEdge(graph, edge) {
1441
+ const nodes = new Map(graph.nodes.map((node) => [node.id, node.label]));
1442
+ const from = nodes.get(edge.from) ?? edge.from;
1443
+ const to = nodes.get(edge.to) ?? edge.to;
1444
+ return edge.title || (edge.label ? `${from} to ${to}: ${edge.label}` : `${from} to ${to}`);
1445
+ }
1446
+ function descriptionForEdge(graph, edge) {
1447
+ const nodes = new Map(graph.nodes.map((node) => [node.id, node.label]));
1448
+ const from = nodes.get(edge.from) ?? edge.from;
1449
+ const to = nodes.get(edge.to) ?? edge.to;
1450
+ return `Relationship from ${from} to ${to}${edge.label ? `, labeled ${edge.label}` : ""}.`;
1451
+ }
1452
+ function nodeGroup(graph, node, layout) {
1453
+ const id = nodeId(graph, node);
1454
+ const label = node.detail ? `${node.label}: ${node.detail}` : node.label;
1455
+ const description = node.detail || node.label;
1456
+ const titleId = `${id}-title`;
1457
+ const descriptionId = `${id}-description`;
1458
+ const accessible = `<g ${attribute("id", id)} role="group" aria-labelledby="${titleId}" aria-describedby="${descriptionId}"><title id="${titleId}">${escapeXml(node.title || node.label)}</title><desc id="${descriptionId}">${escapeXml(description)}</desc>`;
1459
+ if (!layout) return `${accessible}</g>`;
1460
+ const rect = `<rect x="${layout.left}" y="${layout.top}" width="${layout.width}" height="${layout.height}" fill="transparent" pointer-events="all"/>`;
1461
+ const hitTarget = node.href ? `<a ${attribute("href", node.href)} role="link" tabindex="0" ${attribute("aria-label", label)}>${rect}</a>` : rect;
1462
+ return `${accessible}${hitTarget}</g>`;
1463
+ }
1464
+ function edgeGroup(graph, edge, root) {
1465
+ const id = edgeId(graph, edge);
1466
+ const title = labelForEdge(graph, edge);
1467
+ const titleId = `${id}-title`;
1468
+ const descriptionId = `${id}-description`;
1469
+ const accessible = `<g ${attribute("id", id)} role="group" aria-labelledby="${titleId}" aria-describedby="${descriptionId}"><title id="${titleId}">${escapeXml(title)}</title><desc id="${descriptionId}">${escapeXml(descriptionForEdge(graph, edge))}</desc>`;
1470
+ if (!root || !edge.path) return `${accessible}</g>`;
1471
+ const path = `<path d="${escapeXml(edge.path)}" transform="translate(${root.left} ${root.top})" fill="none" stroke="transparent" stroke-width="14" stroke-linecap="round" pointer-events="stroke"/>`;
1472
+ const hitTarget = edge.href ? `<a ${attribute("href", edge.href)} role="link" tabindex="0" ${attribute("aria-label", title)}>${path}</a>` : path;
1473
+ return `${accessible}${hitTarget}</g>`;
1474
+ }
1475
+ function addSvgAccessibility(svg, graphs, layoutNodes) {
1476
+ if (graphs.length === 0) return svg;
1477
+ const title = graphs.map((graph) => graph.title).join(". ");
1478
+ const description = graphs.map((graph) => `${graph.title}. ${graph.description}`).join(" ");
1479
+ const hasLinks = graphs.some(
1480
+ (graph) => graph.nodes.some((node) => node.href) || graph.edges.some((edge) => edge.href)
1481
+ );
1482
+ const rootTitleId = "vizmatic-svg-title";
1483
+ const rootDescriptionId = "vizmatic-svg-description";
1484
+ const groupMarkup = graphs.map((graph) => {
1485
+ const baseId = graphBaseId(graph);
1486
+ const titleId = `${baseId}-title`;
1487
+ const descriptionId = `${baseId}-description`;
1488
+ const root = layoutNodes.find((node) => node.key === graph.detectionKey);
1489
+ const nodes = graph.nodes.map((item) => {
1490
+ const layout = layoutNodes.find((node) => node.key === `${graph.detectionKey}-node-${svgToken(item.id)}`);
1491
+ if (item.href && !layout) {
1492
+ throw new Error(`Could not resolve GraphDiagram node "${item.id}" bounds for SVG link export.`);
1493
+ }
1494
+ return nodeGroup(graph, item, layout);
1495
+ }).join("");
1496
+ const edges = graph.edges.map((item) => {
1497
+ if (item.href && !root) {
1498
+ throw new Error(`Could not resolve GraphDiagram bounds for SVG edge link export: "${item.id}".`);
1499
+ }
1500
+ return edgeGroup(graph, item, root);
1501
+ }).join("");
1502
+ return `<g ${attribute("id", baseId)} role="group" aria-labelledby="${titleId}" aria-describedby="${descriptionId}"><title id="${titleId}">${escapeXml(graph.title)}</title><desc id="${descriptionId}">${escapeXml(graph.description)}</desc>${nodes}${edges}</g>`;
1503
+ }).join("");
1504
+ const metadata = `<title id="${rootTitleId}">${escapeXml(title)}</title><desc id="${rootDescriptionId}">${escapeXml(description)}</desc>`;
1505
+ return svg.replace(
1506
+ /^<svg\b([^>]*)>/,
1507
+ (_match, attrs) => `<svg${attrs} role="${hasLinks ? "group" : "img"}" aria-labelledby="${rootTitleId}" aria-describedby="${rootDescriptionId}">${metadata}`
1508
+ ).replace(/<\/svg>\s*$/, `${groupMarkup}</svg>`);
1509
+ }
1510
+
1511
+ // src/render.ts
1512
+ var FONT_CACHE_DIR = process.env.VIZMATIC_FONT_DIR ?? (0, import_path.join)(process.env.XDG_CACHE_HOME ?? (0, import_path.join)((0, import_os.homedir)(), ".cache"), "vizmatic", "fonts");
1513
+ var NETWORK_FALLBACK_DISABLED = process.env.VIZMATIC_DISABLE_NETWORK === "1" || process.env.VIZMATIC_OFFLINE === "1";
1514
+ function moduleDirectory() {
1515
+ if (typeof __dirname !== "undefined") return __dirname;
1516
+ return (0, import_path.dirname)((0, import_url.fileURLToPath)(void 0));
1517
+ }
1518
+ function unique(values) {
1519
+ return [...new Set(values.filter((value) => Boolean(value)))];
1520
+ }
1521
+ function resolveAssetDir() {
1522
+ const moduleDir = moduleDirectory();
1523
+ const candidates = unique([
1524
+ process.env.VIZMATIC_ASSET_DIR,
1525
+ (0, import_path.join)(moduleDir, "..", "assets"),
1526
+ (0, import_path.join)(moduleDir, "assets"),
1527
+ (0, import_path.join)(process.cwd(), "assets")
1528
+ ]);
1529
+ return candidates.find((candidate) => (0, import_fs.existsSync)(candidate));
1530
+ }
1531
+ var ASSET_DIR = resolveAssetDir();
1532
+ var VENDORED_FONT_DIR = ASSET_DIR ? (0, import_path.join)(ASSET_DIR, "fonts") : void 0;
1533
+ var VENDORED_EMOJI_DIR = ASSET_DIR ? (0, import_path.join)(ASSET_DIR, "emoji") : void 0;
1534
+ var VENDORED_EMOJI_BUNDLE = ASSET_DIR ? (0, import_path.join)(ASSET_DIR, "emoji.json.br") : void 0;
1535
+ var FONT_URLS = {
1536
+ interRegular: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuLyfMZg.ttf",
1537
+ interSemiBold: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuGKYMZg.ttf",
1538
+ interBold: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuFuYMZg.ttf",
1539
+ jetbrainsMono: "https://fonts.gstatic.com/s/jetbrainsmono/v24/tDbY2o-flEEny0FZhsfKu5WU4zr3E_BX0PnT8RD8yKxjPQ.ttf",
1540
+ // Noto Sans (544KB from gstatic): fallback for Phonetic Extensions
1541
+ // (ᵀ U+1D40, ᵢ U+1D62) and extended Latin/Greek not covered by Inter.
1542
+ notoSans: "https://fonts.gstatic.com/s/notosans/v42/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A99d.ttf",
1543
+ // Noto Sans Math (766KB from gstatic): math operators (√, ∞, ≠, ×, ≫),
1544
+ // Greek letters (τ, Σ), and arrows (→, ←)
1545
+ notoSansMath: "https://fonts.gstatic.com/s/notosansmath/v18/7Aump_cpkSecTWaHRlH2hyV5UHkG.ttf",
1546
+ instrumentSerifRegular: "https://raw.githubusercontent.com/google/fonts/main/ofl/instrumentserif/InstrumentSerif-Regular.ttf",
1547
+ instrumentSerifItalic: "https://raw.githubusercontent.com/google/fonts/main/ofl/instrumentserif/InstrumentSerif-Italic.ttf"
1548
+ };
1549
+ function fontReadPaths(filename) {
1550
+ return unique([
1551
+ process.env.VIZMATIC_FONT_DIR ? (0, import_path.join)(process.env.VIZMATIC_FONT_DIR, filename) : void 0,
1552
+ VENDORED_FONT_DIR ? (0, import_path.join)(VENDORED_FONT_DIR, filename) : void 0,
1553
+ (0, import_path.join)(FONT_CACHE_DIR, filename)
1554
+ ]);
1555
+ }
1556
+ async function ensureFont(filename, url) {
1557
+ for (const localPath of fontReadPaths(filename)) {
1558
+ if ((0, import_fs.existsSync)(localPath)) return (0, import_promises.readFile)(localPath);
1559
+ }
1560
+ if (NETWORK_FALLBACK_DISABLED) {
1561
+ throw new Error(`Font ${filename} was not found in local Vizmatic assets and network fallback is disabled`);
1562
+ }
1563
+ console.log(` \u2193 Downloading font: ${filename}`);
1564
+ const response = await fetch(url);
1565
+ if (!response.ok) {
1566
+ throw new Error(`Failed to download font ${filename}: ${response.statusText}`);
1567
+ }
1568
+ const buffer = Buffer.from(await response.arrayBuffer());
1569
+ await (0, import_promises.mkdir)(FONT_CACHE_DIR, { recursive: true });
1570
+ await (0, import_promises.writeFile)((0, import_path.join)(FONT_CACHE_DIR, filename), buffer);
1571
+ return buffer;
1572
+ }
1573
+ function toArrayBuffer(buffer) {
1574
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
1575
+ }
1576
+ async function loadFonts() {
1577
+ await (0, import_promises.mkdir)(FONT_CACHE_DIR, { recursive: true });
1578
+ const fonts2 = [];
1579
+ try {
1580
+ const [regular, semiBold, bold] = await Promise.all([
1581
+ ensureFont("Inter-Regular.ttf", FONT_URLS.interRegular),
1582
+ ensureFont("Inter-SemiBold.ttf", FONT_URLS.interSemiBold),
1583
+ ensureFont("Inter-Bold.ttf", FONT_URLS.interBold)
1584
+ ]);
1585
+ fonts2.push(
1586
+ { name: "Inter", data: toArrayBuffer(regular), weight: 400, style: "normal" },
1587
+ { name: "Inter", data: toArrayBuffer(semiBold), weight: 600, style: "normal" },
1588
+ { name: "Inter", data: toArrayBuffer(bold), weight: 700, style: "normal" }
1589
+ );
1590
+ } catch (e) {
1591
+ console.warn("Warning: Could not load Inter font:", e);
1592
+ }
1593
+ try {
1594
+ const jetbrains = await ensureFont("JetBrainsMono-Regular.ttf", FONT_URLS.jetbrainsMono);
1595
+ fonts2.push({ name: "JetBrains Mono", data: toArrayBuffer(jetbrains), weight: 400, style: "normal" });
1596
+ } catch (e) {
1597
+ console.warn("Warning: Could not load JetBrains Mono font:", e);
1598
+ }
1599
+ try {
1600
+ const [serif, serifItalic] = await Promise.all([
1601
+ ensureFont("InstrumentSerif-Regular.ttf", FONT_URLS.instrumentSerifRegular),
1602
+ ensureFont("InstrumentSerif-Italic.ttf", FONT_URLS.instrumentSerifItalic)
1603
+ ]);
1604
+ fonts2.push(
1605
+ { name: "Instrument Serif", data: toArrayBuffer(serif), weight: 400, style: "normal" },
1606
+ { name: "Instrument Serif", data: toArrayBuffer(serifItalic), weight: 400, style: "italic" }
1607
+ );
1608
+ } catch (e) {
1609
+ console.warn("Warning: Could not load Instrument Serif font:", e);
1610
+ }
1611
+ try {
1612
+ const notoSans = await ensureFont("NotoSans-Regular.ttf", FONT_URLS.notoSans);
1613
+ fonts2.push(
1614
+ { name: "Noto Sans", data: toArrayBuffer(notoSans), weight: 400, style: "normal" }
1615
+ );
1616
+ } catch (e) {
1617
+ console.warn("Warning: Could not load Noto Sans font:", e);
1618
+ }
1619
+ try {
1620
+ const notoMath = await ensureFont("NotoSansMath-Regular.ttf", FONT_URLS.notoSansMath);
1621
+ fonts2.push(
1622
+ { name: "Noto Sans Math", data: toArrayBuffer(notoMath), weight: 400, style: "normal" }
1623
+ );
1624
+ } catch (e) {
1625
+ console.warn("Warning: Could not load Noto Sans Math font:", e);
1626
+ }
1627
+ return fonts2;
1628
+ }
1629
+ var EMOJI_CACHE_DIR = (0, import_path.join)(FONT_CACHE_DIR, "emoji");
1630
+ function emojiCodepoints(segment) {
1631
+ return [...segment].map((c) => c.codePointAt(0).toString(16));
1632
+ }
1633
+ function emojiFilenames(segment) {
1634
+ const codepoints = emojiCodepoints(segment);
1635
+ const full = codepoints.join("-");
1636
+ const withoutVariationSelectors = codepoints.filter((cp) => cp !== "fe0f").join("-");
1637
+ return unique([full, withoutVariationSelectors]).map((codepoints2) => `${codepoints2}.svg`);
1638
+ }
1639
+ async function svgFileToDataUri(path) {
1640
+ const svgData = await (0, import_promises.readFile)(path, "utf8");
1641
+ return `data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`;
1642
+ }
1643
+ var bundledEmoji;
1644
+ async function loadBundledEmoji(filename) {
1645
+ if (!VENDORED_EMOJI_BUNDLE || !(0, import_fs.existsSync)(VENDORED_EMOJI_BUNDLE)) return void 0;
1646
+ bundledEmoji ??= JSON.parse(
1647
+ (0, import_zlib.brotliDecompressSync)(await (0, import_promises.readFile)(VENDORED_EMOJI_BUNDLE)).toString("utf8")
1648
+ );
1649
+ const svg = bundledEmoji[filename];
1650
+ return svg ? `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}` : void 0;
1651
+ }
1652
+ async function loadEmoji(segment) {
1653
+ const filenames = emojiFilenames(segment);
1654
+ for (const filename2 of filenames) {
1655
+ const paths = unique([
1656
+ VENDORED_EMOJI_DIR ? (0, import_path.join)(VENDORED_EMOJI_DIR, filename2) : void 0,
1657
+ (0, import_path.join)(EMOJI_CACHE_DIR, filename2)
1658
+ ]);
1659
+ for (const localPath of paths) {
1660
+ if ((0, import_fs.existsSync)(localPath)) return svgFileToDataUri(localPath);
1661
+ }
1662
+ const bundled = await loadBundledEmoji(filename2);
1663
+ if (bundled) return bundled;
1664
+ }
1665
+ if (NETWORK_FALLBACK_DISABLED) {
1666
+ console.warn(`Warning: Emoji asset not found locally: ${filenames.join(" or ")}`);
1667
+ return "";
1668
+ }
1669
+ const filename = filenames[0];
1670
+ if (!filename) return "";
1671
+ const url = `https://cdn.jsdelivr.net/npm/@twemoji/svg@15.0.0/${filename}`;
1672
+ try {
1673
+ console.log(` \u2193 Downloading emoji: ${filename}`);
1674
+ const response = await fetch(url);
1675
+ if (!response.ok) {
1676
+ console.warn(`Warning: Could not download emoji ${filename}: ${response.statusText}`);
1677
+ return "";
1678
+ }
1679
+ const svgData = await response.text();
1680
+ await (0, import_promises.mkdir)(EMOJI_CACHE_DIR, { recursive: true });
1681
+ await (0, import_promises.writeFile)((0, import_path.join)(EMOJI_CACHE_DIR, filename), svgData);
1682
+ return `data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`;
1683
+ } catch (e) {
1684
+ console.warn(`Warning: Could not fetch emoji ${filename}:`, e);
1685
+ return "";
1686
+ }
1687
+ }
1688
+ async function loadAdditionalAsset(code, segment) {
1689
+ if (code === "emoji") {
1690
+ return loadEmoji(segment);
1691
+ }
1692
+ return [];
1693
+ }
1694
+ var cachedFonts = null;
1695
+ async function getFonts() {
1696
+ if (!cachedFonts) {
1697
+ cachedFonts = await loadFonts();
1698
+ }
1699
+ return cachedFonts;
1700
+ }
1701
+ function sanitizeSvg(svg) {
1702
+ return svg.replace(/width="0"/g, 'width="1"').replace(/height="0"/g, 'height="1"');
1703
+ }
1704
+ function resolveWatermark(options) {
1705
+ return options.watermark ?? options.brand;
1706
+ }
1707
+ async function renderToSvg(element, width, height, options = {}) {
1708
+ return withRenderContext(
1709
+ { background: options.background ?? "transparent", ...options.density !== void 0 ? { density: options.density } : {} },
1710
+ () => renderToSvgInContext(element, width, height, options)
1711
+ );
1712
+ }
1713
+ async function renderToSvgInContext(element, width, height, options) {
1714
+ const fonts2 = await getFonts();
1715
+ const watermark = resolveWatermark(options);
1716
+ const outputElement = watermark ? wrapWithWatermark(
1717
+ element,
1718
+ width,
1719
+ height,
1720
+ options.theme ?? "dark",
1721
+ watermark
1722
+ ) : element;
1723
+ const prepared = prepareAccessibleSvg(outputElement);
1724
+ const layoutNodes = [];
1725
+ const svg = await satori(prepared.element, {
1726
+ width,
1727
+ height,
1728
+ fonts: fonts2,
1729
+ loadAdditionalAsset,
1730
+ onNodeDetected: (node) => {
1731
+ layoutNodes.push(node);
1732
+ options.onNodeDetected?.(node);
1733
+ }
1734
+ });
1735
+ return addSvgAccessibility(sanitizeSvg(svg), prepared.graphs, layoutNodes);
1736
+ }
1737
+
1738
+ // src/video.ts
1739
+ var MAX_STDERR_CHARS = 8192;
1740
+ var COLOR_FILTER = "scale=in_range=pc:out_range=tv:out_color_matrix=bt709:flags=lanczos+accurate_rnd+full_chroma_int,format=yuv420p,setparams=range=tv:color_primaries=bt709:color_trc=bt709:colorspace=bt709";
1741
+ var COLOR_TAGS = ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv"];
1742
+ function validateTiming(duration, fps) {
1743
+ if (!Number.isFinite(duration) || duration <= 0) {
1744
+ throw new Error("duration must be a positive finite number");
1745
+ }
1746
+ if (!Number.isInteger(fps) || fps < 1 || fps > 120) {
1747
+ throw new Error("fps must be an integer between 1 and 120");
1748
+ }
1749
+ const count = Math.round(duration * fps / 1e3);
1750
+ if (!Number.isSafeInteger(count) || count < 1) {
1751
+ throw new Error("duration must round to at least one frame and no more than Number.MAX_SAFE_INTEGER frames");
1752
+ }
1753
+ return { count, duration: count * 1e3 / fps };
1754
+ }
1755
+ function frameInfo(index, schedule, fps) {
1756
+ return {
1757
+ index,
1758
+ count: schedule.count,
1759
+ time: index * 1e3 / fps,
1760
+ duration: schedule.duration,
1761
+ progress: index / schedule.count,
1762
+ fps
1763
+ };
1764
+ }
1765
+ function abortError() {
1766
+ const error = new Error("Video export was aborted.");
1767
+ error.name = "AbortError";
1768
+ return error;
1769
+ }
1770
+ function withAbort(promise, signal) {
1771
+ if (!signal) return promise;
1772
+ if (signal.aborted) return Promise.reject(abortError());
1773
+ return new Promise((resolvePromise, rejectPromise) => {
1774
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
1775
+ const onAbort = () => {
1776
+ cleanup();
1777
+ rejectPromise(abortError());
1778
+ };
1779
+ signal.addEventListener("abort", onAbort, { once: true });
1780
+ promise.then(
1781
+ (value) => {
1782
+ cleanup();
1783
+ resolvePromise(value);
1784
+ },
1785
+ (error) => {
1786
+ cleanup();
1787
+ rejectPromise(error);
1788
+ }
1789
+ );
1790
+ });
1791
+ }
1792
+ function formatSeconds(durationMs) {
1793
+ return (durationMs / 1e3).toFixed(12).replace(/0+$/, "").replace(/\.$/, "");
1794
+ }
1795
+ function describeExit(code, signal, stderr) {
1796
+ const status = signal ? `signal ${signal}` : `exit code ${code}`;
1797
+ const detail = stderr.trim();
1798
+ return new Error(`FFmpeg failed (${status})${detail ? `: ${detail}` : ""}`);
1799
+ }
1800
+ async function stopEncoder(child, exited) {
1801
+ if (child.exitCode !== null || child.signalCode !== null) return;
1802
+ child.kill("SIGTERM");
1803
+ let timer;
1804
+ const terminated = await Promise.race([
1805
+ exited.then(() => true),
1806
+ new Promise((resolvePromise) => {
1807
+ timer = setTimeout(() => resolvePromise(false), 1e3);
1808
+ })
1809
+ ]);
1810
+ if (timer) clearTimeout(timer);
1811
+ if (!terminated) {
1812
+ child.kill("SIGKILL");
1813
+ await exited;
1814
+ }
1815
+ }
1816
+ async function renderRgbaVideo(renderFrame, options) {
1817
+ const fps = options.fps ?? 30;
1818
+ const schedule = validateTiming(options.duration, fps);
1819
+ const { width, height } = options;
1820
+ if (!Number.isSafeInteger(width) || width <= 0 || width % 2 !== 0) {
1821
+ throw new Error("width must be a positive even integer");
1822
+ }
1823
+ if (!Number.isSafeInteger(height) || height <= 0 || height % 2 !== 0) {
1824
+ throw new Error("height must be a positive even integer");
1825
+ }
1826
+ const expectedBytes = width * height * 4;
1827
+ if (!Number.isSafeInteger(expectedBytes)) {
1828
+ throw new Error("frame dimensions are too large");
1829
+ }
1830
+ if (typeof renderFrame !== "function") throw new Error("renderFrame must be a function");
1831
+ if (typeof options.outputPath !== "string" || options.outputPath.length === 0) {
1832
+ throw new Error("outputPath must be a non-empty path");
1833
+ }
1834
+ const ffmpegPath = options.ffmpegPath ?? "ffmpeg";
1835
+ const codec = options.codec ?? "h264";
1836
+ if (codec !== "h264" && codec !== "vp9") throw new Error("codec must be h264 or vp9");
1837
+ const preset = options.preset ?? "fast";
1838
+ const crf = options.crf ?? (codec === "vp9" ? 30 : 18);
1839
+ const threads = options.threads ?? 4;
1840
+ if (typeof ffmpegPath !== "string" || ffmpegPath.length === 0) throw new Error("ffmpegPath must be a non-empty path");
1841
+ if (typeof preset !== "string" || preset.length === 0) throw new Error("preset must be a non-empty string");
1842
+ const maxCrf = codec === "vp9" ? 63 : 51;
1843
+ if (!Number.isInteger(crf) || crf < 0 || crf > maxCrf) throw new Error(`crf must be an integer between 0 and ${maxCrf}`);
1844
+ if (options.tune !== void 0 && (typeof options.tune !== "string" || options.tune.length === 0)) {
1845
+ throw new Error("tune must be a non-empty string when provided");
1846
+ }
1847
+ if (options.audioOffset !== void 0 && (!Number.isFinite(options.audioOffset) || options.audioOffset < 0)) {
1848
+ throw new Error("audioOffset must be a non-negative finite number of seconds");
1849
+ }
1850
+ if (!Number.isSafeInteger(threads) || threads < 1) throw new Error("threads must be a positive safe integer");
1851
+ if (options.audioPath !== void 0 && (typeof options.audioPath !== "string" || options.audioPath.length === 0)) {
1852
+ throw new Error("audioPath must be a non-empty path when provided");
1853
+ }
1854
+ if (options.signal?.aborted) throw abortError();
1855
+ const outputPath = (0, import_path2.resolve)(options.outputPath);
1856
+ const outputDirectory = (0, import_path2.dirname)(outputPath);
1857
+ await (0, import_promises2.mkdir)(outputDirectory, { recursive: true });
1858
+ const extension = codec === "vp9" ? "webm" : "mp4";
1859
+ const tempPath = (0, import_path2.join)(outputDirectory, `.${(0, import_path2.basename)(outputPath)}.${(0, import_crypto.randomUUID)()}.tmp.${extension}`);
1860
+ const tempFile = await (0, import_promises2.open)(tempPath, "wx", 384);
1861
+ try {
1862
+ await tempFile.close();
1863
+ } catch (error) {
1864
+ await (0, import_promises2.rm)(tempPath, { force: true });
1865
+ throw error;
1866
+ }
1867
+ const seconds = formatSeconds(schedule.duration);
1868
+ const args = [
1869
+ "-hide_banner",
1870
+ "-loglevel",
1871
+ "error",
1872
+ "-nostdin",
1873
+ "-y",
1874
+ "-f",
1875
+ "rawvideo",
1876
+ "-pixel_format",
1877
+ "rgba",
1878
+ "-video_size",
1879
+ `${width}x${height}`,
1880
+ "-framerate",
1881
+ String(fps),
1882
+ "-i",
1883
+ "pipe:0"
1884
+ ];
1885
+ if (options.audioPath) {
1886
+ if (options.audioOffset) args.push("-ss", String(options.audioOffset));
1887
+ args.push("-i", (0, import_path2.resolve)(options.audioPath));
1888
+ }
1889
+ args.push("-map", "0:v:0");
1890
+ if (options.audioPath) args.push("-map", "1:a:0", "-af", `asetpts=PTS-STARTPTS,apad,atrim=duration=${seconds}`);
1891
+ args.push("-frames:v", String(schedule.count), "-t", seconds, "-vf", COLOR_FILTER);
1892
+ if (codec === "vp9") {
1893
+ args.push("-c:v", "libvpx-vp9", "-crf", String(crf), "-b:v", "0", "-deadline", "good", "-cpu-used", "2", "-row-mt", "1", "-threads:v", String(threads));
1894
+ } else {
1895
+ args.push("-c:v", "libx264", "-preset", preset);
1896
+ if (options.tune) args.push("-tune", options.tune);
1897
+ args.push("-crf", String(crf), "-threads:v", String(threads));
1898
+ }
1899
+ args.push("-pix_fmt", "yuv420p", ...COLOR_TAGS);
1900
+ if (options.audioPath) {
1901
+ if (codec === "vp9") args.push("-c:a", "libopus", "-b:a", "160k", "-ar", "48000", "-ac", "2");
1902
+ else args.push("-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2");
1903
+ }
1904
+ if (codec === "h264") args.push("-movflags", "+faststart");
1905
+ args.push(tempPath);
1906
+ let stderr = "";
1907
+ let inputError;
1908
+ let child;
1909
+ try {
1910
+ child = (0, import_child_process.spawn)(ffmpegPath, args, { stdio: ["pipe", "ignore", "pipe"] });
1911
+ } catch (error) {
1912
+ await (0, import_promises2.rm)(tempPath, { force: true });
1913
+ throw error;
1914
+ }
1915
+ child.stderr?.on("data", (chunk) => {
1916
+ stderr += chunk.toString();
1917
+ if (stderr.length > MAX_STDERR_CHARS) stderr = stderr.slice(-MAX_STDERR_CHARS);
1918
+ });
1919
+ child.stdin?.on("error", (error) => {
1920
+ inputError = error;
1921
+ });
1922
+ let exitResult;
1923
+ const exited = new Promise((resolvePromise) => {
1924
+ child.once("error", (error) => {
1925
+ exitResult = { code: null, signal: null, error };
1926
+ resolvePromise(exitResult);
1927
+ });
1928
+ child.once("close", (code, signal) => {
1929
+ exitResult = { code, signal };
1930
+ resolvePromise(exitResult);
1931
+ });
1932
+ });
1933
+ function observeEncoder(operation, index, finishAfterSuccess) {
1934
+ const lastFrame = index === schedule.count - 1;
1935
+ const completed = (exit) => {
1936
+ if (!exit.error && exit.code === 0 && lastFrame) {
1937
+ return finishAfterSuccess ? Promise.resolve(void 0) : operation;
1938
+ }
1939
+ if (exit.error) return Promise.reject(new Error(`Unable to start FFmpeg: ${exit.error.message}`, { cause: exit.error }));
1940
+ return Promise.reject(describeExit(exit.code, exit.signal, stderr));
1941
+ };
1942
+ if (exitResult) return completed(exitResult);
1943
+ return new Promise((resolvePromise, rejectPromise) => {
1944
+ const cleanup = () => {
1945
+ child.removeListener("error", onError);
1946
+ child.removeListener("close", onClose);
1947
+ };
1948
+ const onError = (error) => {
1949
+ cleanup();
1950
+ rejectPromise(new Error(`Unable to start FFmpeg: ${error.message}`, { cause: error }));
1951
+ };
1952
+ const onClose = (code, signal) => {
1953
+ cleanup();
1954
+ void completed({ code, signal }).then(resolvePromise, rejectPromise);
1955
+ };
1956
+ child.once("error", onError);
1957
+ child.once("close", onClose);
1958
+ operation.then(
1959
+ (value) => {
1960
+ cleanup();
1961
+ resolvePromise(value);
1962
+ },
1963
+ (error) => {
1964
+ cleanup();
1965
+ rejectPromise(error);
1966
+ }
1967
+ );
1968
+ });
1969
+ }
1970
+ try {
1971
+ const input = child.stdin;
1972
+ if (!input) throw new Error("FFmpeg did not provide a frame input stream");
1973
+ for (let index = 0; index < schedule.count; index++) {
1974
+ const info = frameInfo(index, schedule, fps);
1975
+ const rendered = await withAbort(observeEncoder(Promise.resolve(renderFrame(info)), index, false), options.signal);
1976
+ if (!(rendered instanceof Uint8Array) || rendered.byteLength !== expectedBytes) {
1977
+ throw new Error(`Frame ${index} must contain exactly ${expectedBytes} RGBA bytes`);
1978
+ }
1979
+ if (inputError) throw describeExit(null, null, inputError.message || stderr);
1980
+ const pixels = Buffer.from(rendered.buffer, rendered.byteOffset, rendered.byteLength);
1981
+ const write = new Promise((resolvePromise, rejectPromise) => {
1982
+ input.write(pixels, (error) => error ? rejectPromise(error) : resolvePromise());
1983
+ });
1984
+ await withAbort(observeEncoder(write, index, true), options.signal);
1985
+ if (options.onProgress) {
1986
+ await withAbort(observeEncoder(Promise.resolve(options.onProgress(info)), index, false), options.signal);
1987
+ }
1988
+ }
1989
+ input.end();
1990
+ const exit = await withAbort(exited, options.signal);
1991
+ if (exit.error) throw new Error(`Unable to start FFmpeg: ${exit.error.message}`, { cause: exit.error });
1992
+ if (exit.code !== 0) throw describeExit(exit.code, exit.signal, stderr);
1993
+ const outputStat = await (0, import_promises2.stat)(tempPath);
1994
+ await (0, import_promises2.chmod)(tempPath, 420);
1995
+ await (0, import_promises2.rename)(tempPath, outputPath);
1996
+ return {
1997
+ width,
1998
+ height,
1999
+ frameCount: schedule.count,
2000
+ duration: schedule.duration,
2001
+ fps,
2002
+ bytes: outputStat.size,
2003
+ outputPath,
2004
+ audioIncluded: options.audioPath !== void 0
2005
+ };
2006
+ } catch (error) {
2007
+ await stopEncoder(child, exited);
2008
+ if (inputError && error instanceof Error && (error.message === "write EPIPE" || error.code === "EPIPE")) {
2009
+ throw describeExit(null, null, stderr || inputError.message);
2010
+ }
2011
+ throw error;
2012
+ } finally {
2013
+ await (0, import_promises2.rm)(tempPath, { force: true });
2014
+ }
2015
+ }
2016
+
2017
+ // src/stage/color.ts
2018
+ var import_parse_css_color2 = __toESM(require("parse-css-color"), 1);
2019
+
2020
+ // src/stage/look.ts
2021
+ var midnight = {
2022
+ name: "midnight",
2023
+ dark: true,
2024
+ background: "#0b0c10",
2025
+ bloom: 0.2,
2026
+ colors: {
2027
+ bg: "#0b0c10",
2028
+ surface: "#15171d",
2029
+ ink: "#f2efe6",
2030
+ dim: "#a5a7ad",
2031
+ faint: "#5c5f68",
2032
+ grid: "#23303d",
2033
+ gridStrong: "#3d5266",
2034
+ blue: "#5cc4f0",
2035
+ teal: "#4fd8c4",
2036
+ green: "#8fe08a",
2037
+ yellow: "#ffd75e",
2038
+ gold: "#f2b84b",
2039
+ orange: "#ff9d57",
2040
+ red: "#ff6b6b",
2041
+ pink: "#ff8fc0",
2042
+ purple: "#b49cff"
2043
+ }
2044
+ };
2045
+
2046
+ // src/stage/color.ts
2047
+ var TRANSPARENT = [0, 0, 0, 0];
2048
+ var cache = /* @__PURE__ */ new Map();
2049
+ var tokens = midnight.colors;
2050
+ function parseColor(input) {
2051
+ const token = tokens[input];
2052
+ const value = token ?? input;
2053
+ const cached = cache.get(value);
2054
+ if (cached) return cached;
2055
+ const parsed = (0, import_parse_css_color2.default)(value);
2056
+ if (!parsed) throw new Error(`Unknown color: ${JSON.stringify(input)}. Use a look token such as "blue" or a CSS color.`);
2057
+ let [r, g, b] = parsed.values;
2058
+ if (parsed.type === "hsl") [r, g, b] = hslToRgb(r, g, b);
2059
+ const result = [r, g, b, parsed.alpha];
2060
+ cache.set(value, result);
2061
+ return result;
2062
+ }
2063
+ function hslToRgb(h, s, l) {
2064
+ const a = s / 100 * Math.min(l / 100, 1 - l / 100);
2065
+ const f = (n) => {
2066
+ const k = (n + h / 30) % 12;
2067
+ return 255 * (l / 100 - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)));
2068
+ };
2069
+ return [f(0), f(8), f(4)];
2070
+ }
2071
+ function toPaint(input) {
2072
+ if (typeof input === "string") return parseColor(input);
2073
+ return input;
2074
+ }
2075
+ function isGradient(paint) {
2076
+ return !Array.isArray(paint);
2077
+ }
2078
+ function css(color, alpha = 1) {
2079
+ const a = color[3] * alpha;
2080
+ const r = Math.round(color[0]), g = Math.round(color[1]), b = Math.round(color[2]);
2081
+ if (a >= 1) return `rgb(${r},${g},${b})`;
2082
+ return `rgba(${r},${g},${b},${Math.round(a * 1e3) / 1e3})`;
2083
+ }
2084
+ function srgbToLinear(v) {
2085
+ const x = v / 255;
2086
+ return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
2087
+ }
2088
+ function linearToSrgb(v) {
2089
+ const x = v <= 31308e-7 ? 12.92 * v : 1.055 * Math.pow(v, 1 / 2.4) - 0.055;
2090
+ return Math.max(0, Math.min(255, x * 255));
2091
+ }
2092
+ function toOklab(c) {
2093
+ const r = srgbToLinear(c[0]), g = srgbToLinear(c[1]), b = srgbToLinear(c[2]);
2094
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
2095
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
2096
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
2097
+ return [
2098
+ 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
2099
+ 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
2100
+ 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s
2101
+ ];
2102
+ }
2103
+ function fromOklab(lab, alpha) {
2104
+ const l = lab[0] + 0.3963377774 * lab[1] + 0.2158037573 * lab[2];
2105
+ const m = lab[0] - 0.1055613458 * lab[1] - 0.0638541728 * lab[2];
2106
+ const s = lab[0] - 0.0894841775 * lab[1] - 1.291485548 * lab[2];
2107
+ const ll = l * l * l, mm = m * m * m, ss = s * s * s;
2108
+ return [
2109
+ linearToSrgb(4.0767416621 * ll - 3.3077115913 * mm + 0.2309699292 * ss),
2110
+ linearToSrgb(-1.2684380046 * ll + 2.6097574011 * mm - 0.3413193965 * ss),
2111
+ linearToSrgb(-0.0041960863 * ll - 0.7034186147 * mm + 1.707614701 * ss),
2112
+ alpha
2113
+ ];
2114
+ }
2115
+ function mixColor(a, b, t) {
2116
+ if (t <= 0) return a;
2117
+ if (t >= 1) return b;
2118
+ const x = toOklab(a), y = toOklab(b);
2119
+ return fromOklab([x[0] + (y[0] - x[0]) * t, x[1] + (y[1] - x[1]) * t, x[2] + (y[2] - x[2]) * t], a[3] + (b[3] - a[3]) * t);
2120
+ }
2121
+ function mixPaint(a, b, t) {
2122
+ if (t <= 0) return a;
2123
+ if (t >= 1) return b;
2124
+ const ga = isGradient(a), gb = isGradient(b);
2125
+ if (!ga && !gb) return mixColor(a, b, t);
2126
+ if (ga && gb && a.type === b.type && a.stops.length === b.stops.length) {
2127
+ const stops = a.stops.map((stop, i) => [
2128
+ stop[0] + (b.stops[i][0] - stop[0]) * t,
2129
+ mixColor(stop[1], b.stops[i][1], t)
2130
+ ]);
2131
+ if (a.type === "linear" && b.type === "linear") {
2132
+ return {
2133
+ type: "linear",
2134
+ stops,
2135
+ from: [a.from[0] + (b.from[0] - a.from[0]) * t, a.from[1] + (b.from[1] - a.from[1]) * t],
2136
+ to: [a.to[0] + (b.to[0] - a.to[0]) * t, a.to[1] + (b.to[1] - a.to[1]) * t]
2137
+ };
2138
+ }
2139
+ if (a.type === "radial" && b.type === "radial") {
2140
+ return {
2141
+ type: "radial",
2142
+ stops,
2143
+ center: [a.center[0] + (b.center[0] - a.center[0]) * t, a.center[1] + (b.center[1] - a.center[1]) * t],
2144
+ radius: a.radius + (b.radius - a.radius) * t
2145
+ };
2146
+ }
2147
+ return { type: "along", stops };
2148
+ }
2149
+ const solidA = ga ? sampleStops(a.stops, 0.5) : a;
2150
+ const solidB = gb ? sampleStops(b.stops, 0.5) : b;
2151
+ return mixColor(solidA, solidB, t);
2152
+ }
2153
+ function sampleStops(stops, at) {
2154
+ if (stops.length === 0) return TRANSPARENT;
2155
+ if (at <= stops[0][0]) return stops[0][1];
2156
+ for (let i = 1; i < stops.length; i++) {
2157
+ if (at <= stops[i][0]) {
2158
+ const [p0, c0] = stops[i - 1], [p1, c1] = stops[i];
2159
+ return mixColor(c0, c1, p1 > p0 ? (at - p0) / (p1 - p0) : 0);
2160
+ }
2161
+ }
2162
+ return stops[stops.length - 1][1];
2163
+ }
2164
+
2165
+ // src/stage/geometry.ts
2166
+ var IDENTITY = [1, 0, 0, 1, 0, 0];
2167
+ var EMPTY_BOUNDS = { x: 0, y: 0, width: 0, height: 0 };
2168
+ var KAPPA = 0.5522847498307936;
2169
+ var LUT_STEPS = 10;
2170
+ function mul(m, n) {
2171
+ return [
2172
+ m[0] * n[0] + m[2] * n[1],
2173
+ m[1] * n[0] + m[3] * n[1],
2174
+ m[0] * n[2] + m[2] * n[3],
2175
+ m[1] * n[2] + m[3] * n[3],
2176
+ m[0] * n[4] + m[2] * n[5] + m[4],
2177
+ m[1] * n[4] + m[3] * n[5] + m[5]
2178
+ ];
2179
+ }
2180
+ function invert(m) {
2181
+ const det = m[0] * m[3] - m[1] * m[2];
2182
+ if (Math.abs(det) < 1e-12) return IDENTITY;
2183
+ const i = 1 / det;
2184
+ return [
2185
+ m[3] * i,
2186
+ -m[1] * i,
2187
+ -m[2] * i,
2188
+ m[0] * i,
2189
+ (m[2] * m[5] - m[3] * m[4]) * i,
2190
+ (m[1] * m[4] - m[0] * m[5]) * i
2191
+ ];
2192
+ }
2193
+ function apply(m, x, y) {
2194
+ return [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
2195
+ }
2196
+ function compose(x, y, rotation, sx, sy, px, py) {
2197
+ const cos = rotation === 0 ? 1 : Math.cos(rotation);
2198
+ const sin = rotation === 0 ? 0 : Math.sin(rotation);
2199
+ const a = cos * sx;
2200
+ const b = sin * sx;
2201
+ const c = -sin * sy;
2202
+ const d = cos * sy;
2203
+ return [a, b, c, d, x - a * px - c * py, y - b * px - d * py];
2204
+ }
2205
+ function matScale(m) {
2206
+ return Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));
2207
+ }
2208
+ function ring(points, closed = false) {
2209
+ return { p: points instanceof Float64Array ? points : Float64Array.from(points), closed };
2210
+ }
2211
+ function segmentCount(r) {
2212
+ return Math.max(0, (r.p.length - 2) / 6);
2213
+ }
2214
+ function lineInto(out, x0, y0, x1, y1) {
2215
+ out.push(x0 + (x1 - x0) / 3, y0 + (y1 - y0) / 3, x0 + (x1 - x0) * 2 / 3, y0 + (y1 - y0) * 2 / 3, x1, y1);
2216
+ }
2217
+ function polyPath(points, closed = false) {
2218
+ if (points.length === 0) return [];
2219
+ const first = points[0];
2220
+ const out = [first[0], first[1]];
2221
+ for (let i = 1; i < points.length; i++) lineInto(out, points[i - 1][0], points[i - 1][1], points[i][0], points[i][1]);
2222
+ if (closed) {
2223
+ const last = points[points.length - 1];
2224
+ if (last[0] !== first[0] || last[1] !== first[1]) lineInto(out, last[0], last[1], first[0], first[1]);
2225
+ }
2226
+ return [ring(out, closed)];
2227
+ }
2228
+ function arcPath(cx, cy, rx, ry, from, to) {
2229
+ const sweep = to - from;
2230
+ if (sweep === 0) return [];
2231
+ const closed = Math.abs(Math.abs(sweep) - Math.PI * 2) < 1e-9;
2232
+ const count = Math.max(1, Math.ceil(Math.abs(sweep) / (Math.PI / 4) - 1e-9));
2233
+ const step = sweep / count;
2234
+ const k = 4 / 3 * Math.tan(step / 4);
2235
+ const out = [cx + Math.cos(from) * rx, cy + Math.sin(from) * ry];
2236
+ for (let i = 0; i < count; i++) {
2237
+ const a0 = from + i * step, a1 = a0 + step;
2238
+ const c0 = Math.cos(a0), s0 = Math.sin(a0), c1 = Math.cos(a1), s1 = Math.sin(a1);
2239
+ out.push(cx + (c0 - k * s0) * rx, cy + (s0 + k * c0) * ry, cx + (c1 + k * s1) * rx, cy + (s1 - k * c1) * ry, cx + c1 * rx, cy + s1 * ry);
2240
+ }
2241
+ if (closed) {
2242
+ out[out.length - 2] = out[0];
2243
+ out[out.length - 1] = out[1];
2244
+ }
2245
+ return [ring(out, closed)];
2246
+ }
2247
+ function rectPath(x, y, width, height, radius = 0) {
2248
+ const r = Math.max(0, Math.min(radius, Math.abs(width) / 2, Math.abs(height) / 2));
2249
+ if (r === 0) return polyPath([[x, y], [x + width, y], [x + width, y + height], [x, y + height]], true);
2250
+ const k = r * (1 - KAPPA);
2251
+ const right = x + width, bottom = y + height;
2252
+ const out = [x + r, y];
2253
+ lineInto(out, x + r, y, right - r, y);
2254
+ out.push(right - k, y, right, y + k, right, y + r);
2255
+ lineInto(out, right, y + r, right, bottom - r);
2256
+ out.push(right, bottom - k, right - k, bottom, right - r, bottom);
2257
+ lineInto(out, right - r, bottom, x + r, bottom);
2258
+ out.push(x + k, bottom, x, bottom - k, x, bottom - r);
2259
+ lineInto(out, x, bottom - r, x, y + r);
2260
+ out.push(x, y + k, x + k, y, x + r, y);
2261
+ return [ring(out, true)];
2262
+ }
2263
+ function transformPath(path, m) {
2264
+ if (m === IDENTITY) return path;
2265
+ const out = new Array(path.length);
2266
+ for (let r = 0; r < path.length; r++) {
2267
+ const src = path[r].p;
2268
+ const dst = new Float64Array(src.length);
2269
+ for (let i = 0; i < src.length; i += 2) {
2270
+ const x = src[i], y = src[i + 1];
2271
+ dst[i] = m[0] * x + m[2] * y + m[4];
2272
+ dst[i + 1] = m[1] * x + m[3] * y + m[5];
2273
+ }
2274
+ out[r] = { p: dst, closed: path[r].closed };
2275
+ }
2276
+ return out;
2277
+ }
2278
+ var measures = /* @__PURE__ */ new WeakMap();
2279
+ function measure(r) {
2280
+ const cached = measures.get(r);
2281
+ if (cached) return cached;
2282
+ const count = segmentCount(r);
2283
+ const total = new Float64Array(count);
2284
+ const lut = new Float64Array(count * LUT_STEPS);
2285
+ let sum = 0;
2286
+ const p = r.p;
2287
+ for (let i = 0; i < count; i++) {
2288
+ const o = i * 6;
2289
+ const x0 = p[o], y0 = p[o + 1], x1 = p[o + 2], y1 = p[o + 3], x2 = p[o + 4], y2 = p[o + 5], x3 = p[o + 6], y3 = p[o + 7];
2290
+ let lastX = x0, lastY = y0, acc = 0;
2291
+ for (let k = 1; k <= LUT_STEPS; k++) {
2292
+ const t = k / LUT_STEPS, u = 1 - t;
2293
+ const a = u * u * u, b = 3 * u * u * t, c = 3 * u * t * t, d = t * t * t;
2294
+ const x = a * x0 + b * x1 + c * x2 + d * x3;
2295
+ const y = a * y0 + b * y1 + c * y2 + d * y3;
2296
+ acc += Math.hypot(x - lastX, y - lastY);
2297
+ lut[i * LUT_STEPS + k - 1] = acc;
2298
+ lastX = x;
2299
+ lastY = y;
2300
+ }
2301
+ sum += acc;
2302
+ total[i] = sum;
2303
+ }
2304
+ const result = { total, lut, length: sum };
2305
+ measures.set(r, result);
2306
+ return result;
2307
+ }
2308
+ function ringLength(r) {
2309
+ return measure(r).length;
2310
+ }
2311
+ function pathLength(path) {
2312
+ let sum = 0;
2313
+ for (const r of path) sum += measure(r).length;
2314
+ return sum;
2315
+ }
2316
+ function extendCubicAxis(range, p0, p1, p2, p3) {
2317
+ range[0] = Math.min(range[0], p0, p3);
2318
+ range[1] = Math.max(range[1], p0, p3);
2319
+ if (p1 >= range[0] && p1 <= range[1] && p2 >= range[0] && p2 <= range[1]) return;
2320
+ const a = -p0 + 3 * p1 - 3 * p2 + p3;
2321
+ const b = 2 * (p0 - 2 * p1 + p2);
2322
+ const c = p1 - p0;
2323
+ const roots = [];
2324
+ if (Math.abs(a) < 1e-9) {
2325
+ if (Math.abs(b) > 1e-9) roots.push(-c / b);
2326
+ } else {
2327
+ const disc = b * b - 4 * a * c;
2328
+ if (disc >= 0) {
2329
+ const s = Math.sqrt(disc);
2330
+ roots.push((-b + s) / (2 * a), (-b - s) / (2 * a));
2331
+ }
2332
+ }
2333
+ for (const t of roots) {
2334
+ if (t <= 0 || t >= 1) continue;
2335
+ const u = 1 - t;
2336
+ const value = u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3;
2337
+ range[0] = Math.min(range[0], value);
2338
+ range[1] = Math.max(range[1], value);
2339
+ }
2340
+ }
2341
+ var ringBounds = /* @__PURE__ */ new WeakMap();
2342
+ function boundsOfRing(r) {
2343
+ const cached = ringBounds.get(r);
2344
+ if (cached) return cached;
2345
+ const p = r.p;
2346
+ if (p.length < 2) return EMPTY_BOUNDS;
2347
+ const xs = [p[0], p[0]];
2348
+ const ys = [p[1], p[1]];
2349
+ for (let o = 0; o + 7 < p.length; o += 6) {
2350
+ extendCubicAxis(xs, p[o], p[o + 2], p[o + 4], p[o + 6]);
2351
+ extendCubicAxis(ys, p[o + 1], p[o + 3], p[o + 5], p[o + 7]);
2352
+ }
2353
+ const bounds = { x: xs[0], y: ys[0], width: xs[1] - xs[0], height: ys[1] - ys[0] };
2354
+ ringBounds.set(r, bounds);
2355
+ return bounds;
2356
+ }
2357
+ function pathBounds(path) {
2358
+ if (path.length === 0) return null;
2359
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
2360
+ for (const r of path) {
2361
+ if (r.p.length < 2) continue;
2362
+ const b = boundsOfRing(r);
2363
+ minX = Math.min(minX, b.x);
2364
+ minY = Math.min(minY, b.y);
2365
+ maxX = Math.max(maxX, b.x + b.width);
2366
+ maxY = Math.max(maxY, b.y + b.height);
2367
+ }
2368
+ if (minX === Infinity) return null;
2369
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
2370
+ }
2371
+ function unionBounds(a, b) {
2372
+ if (!a) return b;
2373
+ if (!b) return a;
2374
+ const x = Math.min(a.x, b.x), y = Math.min(a.y, b.y);
2375
+ return { x, y, width: Math.max(a.x + a.width, b.x + b.width) - x, height: Math.max(a.y + a.height, b.y + b.height) - y };
2376
+ }
2377
+ function signedArea(r) {
2378
+ const p = r.p;
2379
+ let sum = 0;
2380
+ for (let o = 0; o + 7 < p.length; o += 6) {
2381
+ sum += p[o] * p[o + 7] - p[o + 6] * p[o + 1];
2382
+ }
2383
+ return sum / 2;
2384
+ }
2385
+ function ringCenter(r) {
2386
+ const b = boundsOfRing(r);
2387
+ return [b.x + b.width / 2, b.y + b.height / 2];
2388
+ }
2389
+ function reverseRing(r) {
2390
+ const p = r.p;
2391
+ const out = new Float64Array(p.length);
2392
+ for (let i = 0; i < p.length; i += 2) {
2393
+ out[i] = p[p.length - 2 - i];
2394
+ out[i + 1] = p[p.length - 1 - i];
2395
+ }
2396
+ return { p: out, closed: r.closed };
2397
+ }
2398
+ function parseSvgPath(d) {
2399
+ const tokens2 = d.match(/[a-zA-Z]|[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/g);
2400
+ if (!tokens2) return [];
2401
+ const rings = [];
2402
+ let out = [];
2403
+ let i = 0, x = 0, y = 0, startX = 0, startY = 0;
2404
+ let lastCmd = "", lastCx = 0, lastCy = 0;
2405
+ const num = () => Number(tokens2[i++]);
2406
+ const flags = () => {
2407
+ const token = tokens2[i];
2408
+ if (token.length > 1 && (token[0] === "0" || token[0] === "1") && !token.startsWith("0.") && !token.startsWith("1.")) {
2409
+ tokens2[i] = token.slice(1);
2410
+ return Number(token[0]);
2411
+ }
2412
+ i++;
2413
+ return Number(token);
2414
+ };
2415
+ const flush = (closed) => {
2416
+ if (out.length >= 8) rings.push(ring(out, closed));
2417
+ out = [];
2418
+ };
2419
+ const begin = (px, py) => {
2420
+ if (out.length === 0) out.push(px, py);
2421
+ };
2422
+ let cmd = "";
2423
+ while (i < tokens2.length) {
2424
+ const token = tokens2[i];
2425
+ if (/^[a-zA-Z]$/.test(token)) {
2426
+ cmd = token;
2427
+ i++;
2428
+ } else if (cmd === "M") {
2429
+ cmd = "L";
2430
+ } else if (cmd === "m") {
2431
+ cmd = "l";
2432
+ } else if (cmd === "") {
2433
+ throw new Error(`Invalid SVG path data: ${d.slice(0, 40)}`);
2434
+ }
2435
+ const rel = cmd >= "a";
2436
+ switch (cmd.toUpperCase()) {
2437
+ case "M": {
2438
+ flush(false);
2439
+ x = (rel ? x : 0) + num();
2440
+ y = (rel ? y : 0) + num();
2441
+ startX = x;
2442
+ startY = y;
2443
+ out.push(x, y);
2444
+ break;
2445
+ }
2446
+ case "L": {
2447
+ const nx = (rel ? x : 0) + num(), ny = (rel ? y : 0) + num();
2448
+ begin(x, y);
2449
+ lineInto(out, x, y, nx, ny);
2450
+ x = nx;
2451
+ y = ny;
2452
+ break;
2453
+ }
2454
+ case "H": {
2455
+ const nx = (rel ? x : 0) + num();
2456
+ begin(x, y);
2457
+ lineInto(out, x, y, nx, y);
2458
+ x = nx;
2459
+ break;
2460
+ }
2461
+ case "V": {
2462
+ const ny = (rel ? y : 0) + num();
2463
+ begin(x, y);
2464
+ lineInto(out, x, y, x, ny);
2465
+ y = ny;
2466
+ break;
2467
+ }
2468
+ case "C": {
2469
+ const ox = rel ? x : 0, oy = rel ? y : 0;
2470
+ const c1x = ox + num(), c1y = oy + num(), c2x = ox + num(), c2y = oy + num(), nx = ox + num(), ny = oy + num();
2471
+ begin(x, y);
2472
+ out.push(c1x, c1y, c2x, c2y, nx, ny);
2473
+ lastCx = c2x;
2474
+ lastCy = c2y;
2475
+ x = nx;
2476
+ y = ny;
2477
+ break;
2478
+ }
2479
+ case "S": {
2480
+ const ox = rel ? x : 0, oy = rel ? y : 0;
2481
+ const smooth = "CScs".includes(lastCmd);
2482
+ const c1x = smooth ? 2 * x - lastCx : x, c1y = smooth ? 2 * y - lastCy : y;
2483
+ const c2x = ox + num(), c2y = oy + num(), nx = ox + num(), ny = oy + num();
2484
+ begin(x, y);
2485
+ out.push(c1x, c1y, c2x, c2y, nx, ny);
2486
+ lastCx = c2x;
2487
+ lastCy = c2y;
2488
+ x = nx;
2489
+ y = ny;
2490
+ break;
2491
+ }
2492
+ case "Q": {
2493
+ const ox = rel ? x : 0, oy = rel ? y : 0;
2494
+ const qx = ox + num(), qy = oy + num(), nx = ox + num(), ny = oy + num();
2495
+ begin(x, y);
2496
+ out.push(x + (qx - x) * 2 / 3, y + (qy - y) * 2 / 3, nx + (qx - nx) * 2 / 3, ny + (qy - ny) * 2 / 3, nx, ny);
2497
+ lastCx = qx;
2498
+ lastCy = qy;
2499
+ x = nx;
2500
+ y = ny;
2501
+ break;
2502
+ }
2503
+ case "T": {
2504
+ const ox = rel ? x : 0, oy = rel ? y : 0;
2505
+ const smooth = "QTqt".includes(lastCmd);
2506
+ const qx = smooth ? 2 * x - lastCx : x, qy = smooth ? 2 * y - lastCy : y;
2507
+ const nx = ox + num(), ny = oy + num();
2508
+ begin(x, y);
2509
+ out.push(x + (qx - x) * 2 / 3, y + (qy - y) * 2 / 3, nx + (qx - nx) * 2 / 3, ny + (qy - ny) * 2 / 3, nx, ny);
2510
+ lastCx = qx;
2511
+ lastCy = qy;
2512
+ x = nx;
2513
+ y = ny;
2514
+ break;
2515
+ }
2516
+ case "A": {
2517
+ const rx = num(), ry = num(), angle = num(), large = flags(), sweep = flags();
2518
+ const nx = (rel ? x : 0) + num(), ny = (rel ? y : 0) + num();
2519
+ begin(x, y);
2520
+ arcInto(out, x, y, rx, ry, angle, large === 1, sweep === 1, nx, ny);
2521
+ x = nx;
2522
+ y = ny;
2523
+ break;
2524
+ }
2525
+ case "Z": {
2526
+ if (out.length > 0) {
2527
+ if (x !== startX || y !== startY) lineInto(out, x, y, startX, startY);
2528
+ flush(true);
2529
+ }
2530
+ x = startX;
2531
+ y = startY;
2532
+ break;
2533
+ }
2534
+ default:
2535
+ throw new Error(`Unsupported SVG path command: ${cmd}`);
2536
+ }
2537
+ lastCmd = cmd;
2538
+ }
2539
+ flush(false);
2540
+ return rings;
2541
+ }
2542
+ function arcInto(out, x0, y0, rxIn, ryIn, degrees, large, sweep, x1, y1) {
2543
+ let rx = Math.abs(rxIn), ry = Math.abs(ryIn);
2544
+ if (rx === 0 || ry === 0 || x0 === x1 && y0 === y1) {
2545
+ lineInto(out, x0, y0, x1, y1);
2546
+ return;
2547
+ }
2548
+ const phi = degrees * Math.PI / 180;
2549
+ const cos = Math.cos(phi), sin = Math.sin(phi);
2550
+ const dx = (x0 - x1) / 2, dy = (y0 - y1) / 2;
2551
+ const xp = cos * dx + sin * dy, yp = -sin * dx + cos * dy;
2552
+ const lambda = xp * xp / (rx * rx) + yp * yp / (ry * ry);
2553
+ if (lambda > 1) {
2554
+ const scale = Math.sqrt(lambda);
2555
+ rx *= scale;
2556
+ ry *= scale;
2557
+ }
2558
+ const numerator = rx * rx * ry * ry - rx * rx * yp * yp - ry * ry * xp * xp;
2559
+ const denominator = rx * rx * yp * yp + ry * ry * xp * xp;
2560
+ const factor = (large === sweep ? -1 : 1) * Math.sqrt(Math.max(0, numerator / denominator));
2561
+ const cxp = factor * rx * yp / ry, cyp = -factor * ry * xp / rx;
2562
+ const cx = cos * cxp - sin * cyp + (x0 + x1) / 2;
2563
+ const cy = sin * cxp + cos * cyp + (y0 + y1) / 2;
2564
+ const start = Math.atan2((yp - cyp) / ry, (xp - cxp) / rx);
2565
+ let delta = Math.atan2((-yp - cyp) / ry, (-xp - cxp) / rx) - start;
2566
+ if (sweep && delta < 0) delta += Math.PI * 2;
2567
+ if (!sweep && delta > 0) delta -= Math.PI * 2;
2568
+ const count = Math.max(1, Math.ceil(Math.abs(delta) / (Math.PI / 2) - 1e-9));
2569
+ const step = delta / count;
2570
+ const k = 4 / 3 * Math.tan(step / 4);
2571
+ for (let i = 0; i < count; i++) {
2572
+ const a0 = start + i * step, a1 = a0 + step;
2573
+ const c0 = Math.cos(a0), s0 = Math.sin(a0), c1 = Math.cos(a1), s1 = Math.sin(a1);
2574
+ const q1x = (c0 - k * s0) * rx, q1y = (s0 + k * c0) * ry;
2575
+ const q2x = (c1 + k * s1) * rx, q2y = (s1 - k * c1) * ry;
2576
+ const ex = c1 * rx, ey = s1 * ry;
2577
+ out.push(
2578
+ cos * q1x - sin * q1y + cx,
2579
+ sin * q1x + cos * q1y + cy,
2580
+ cos * q2x - sin * q2y + cx,
2581
+ sin * q2x + cos * q2y + cy,
2582
+ i === count - 1 ? x1 : cos * ex - sin * ey + cx,
2583
+ i === count - 1 ? y1 : sin * ex + cos * ey + cy
2584
+ );
2585
+ }
2586
+ }
2587
+ function fmt(value) {
2588
+ const rounded = Math.round(value * 100) / 100;
2589
+ return rounded === 0 ? "0" : String(rounded);
2590
+ }
2591
+ function pathToD(path) {
2592
+ const parts = [];
2593
+ for (const r of path) {
2594
+ const p = r.p;
2595
+ if (p.length < 2) continue;
2596
+ parts.push("M", fmt(p[0]), " ", fmt(p[1]));
2597
+ if (r.straight) {
2598
+ for (let o = 2; o + 5 < p.length; o += 6) parts.push("L", fmt(p[o + 4]), " ", fmt(p[o + 5]));
2599
+ if (r.closed) parts.push("Z");
2600
+ continue;
2601
+ }
2602
+ for (let o = 2; o + 5 < p.length; o += 6) {
2603
+ parts.push("C", fmt(p[o]), " ", fmt(p[o + 1]), " ", fmt(p[o + 2]), " ", fmt(p[o + 3]), " ", fmt(p[o + 4]), " ", fmt(p[o + 5]));
2604
+ }
2605
+ if (r.closed) parts.push("Z");
2606
+ }
2607
+ return parts.join("");
2608
+ }
2609
+
2610
+ // src/stage/track.ts
2611
+ var clock = {
2612
+ now: 0,
2613
+ mode: "free",
2614
+ /** Increments once per rendered frame and invalidates per-frame overlays. */
2615
+ frame: 0,
2616
+ /** While set, writes to mounted nodes collect here instead of creating keys. */
2617
+ capture: null
2618
+ };
2619
+ var Track = class {
2620
+ constructor(initial) {
2621
+ this.initial = initial;
2622
+ }
2623
+ initial;
2624
+ keys = [];
2625
+ sample(t) {
2626
+ const keys = this.keys;
2627
+ let lo = 0, hi = keys.length - 1, index = -1;
2628
+ while (lo <= hi) {
2629
+ const mid = lo + hi >> 1;
2630
+ if (keys[mid].t0 <= t) {
2631
+ index = mid;
2632
+ lo = mid + 1;
2633
+ } else {
2634
+ hi = mid - 1;
2635
+ }
2636
+ }
2637
+ if (index < 0) return this.initial;
2638
+ const key = keys[index];
2639
+ if (t >= key.t1 || !key.at) return key.to;
2640
+ const span = key.t1 - key.t0;
2641
+ const raw = span > 0 ? (t - key.t0) / span : 1;
2642
+ return key.at(key.ease ? key.ease(raw) : raw);
2643
+ }
2644
+ add(key) {
2645
+ const keys = this.keys;
2646
+ let index = keys.length;
2647
+ while (index > 0 && keys[index - 1].t0 > key.t0) index--;
2648
+ keys.splice(index, 0, key);
2649
+ }
2650
+ step(t, value) {
2651
+ this.add({ t0: t, t1: t, ease: null, to: value, at: null });
2652
+ }
2653
+ /** Last time this track changes. */
2654
+ get end() {
2655
+ let end = 0;
2656
+ for (const key of this.keys) if (key.t1 > end) end = key.t1;
2657
+ return end;
2658
+ }
2659
+ };
2660
+
2661
+ // src/stage/display.ts
2662
+ var GLOW_PASSES = 7;
2663
+ function glowPasses(glow, width) {
2664
+ const out = [];
2665
+ for (let i = GLOW_PASSES; i >= 1; i--) {
2666
+ const k = i / GLOW_PASSES;
2667
+ out.push({ width: width + glow * 2 * k, alpha: 0.16 * (1 - k) * (1 - k) + 0.018 });
2668
+ }
2669
+ return out;
2670
+ }
2671
+ function glowOf(op) {
2672
+ if (op.glowColor) return op.glowColor;
2673
+ const paint = op.stroke ?? op.fill;
2674
+ if (!paint) return null;
2675
+ return isGradient(paint) ? sampleStops(paint.stops, 0.5) : paint;
2676
+ }
2677
+ var dCache = /* @__PURE__ */ new WeakMap();
2678
+ function pathData(path) {
2679
+ let d = dCache.get(path);
2680
+ if (d === void 0) {
2681
+ d = pathToD(path);
2682
+ dCache.set(path, d);
2683
+ }
2684
+ return d;
2685
+ }
2686
+ function fmt2(value) {
2687
+ return String(Math.round(value * 1e3) / 1e3);
2688
+ }
2689
+ function gradientDef(id, paint) {
2690
+ const stops = paint.stops.map(([at, color]) => `<stop offset="${fmt2(at)}" stop-color="${css([color[0], color[1], color[2], 1])}"${color[3] < 1 ? ` stop-opacity="${fmt2(color[3])}"` : ""}/>`).join("");
2691
+ if (paint.type === "linear") {
2692
+ return `<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${fmt2(paint.from[0])}" y1="${fmt2(paint.from[1])}" x2="${fmt2(paint.to[0])}" y2="${fmt2(paint.to[1])}">${stops}</linearGradient>`;
2693
+ }
2694
+ if (paint.type === "radial") {
2695
+ return `<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${fmt2(paint.center[0])}" cy="${fmt2(paint.center[1])}" r="${fmt2(paint.radius)}">${stops}</radialGradient>`;
2696
+ }
2697
+ return "";
2698
+ }
2699
+ function strokeAttrs(op) {
2700
+ let attrs = ` stroke-linecap="${op.cap}" stroke-linejoin="${op.join}"`;
2701
+ if (op.dash) attrs += ` stroke-dasharray="${op.dash.map(fmt2).join(" ")}" stroke-dashoffset="${fmt2(op.dashOffset)}"`;
2702
+ return attrs;
2703
+ }
2704
+ function escapeAttr(value) {
2705
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
2706
+ }
2707
+ function frameToSvg(frame, options = {}) {
2708
+ const scale = options.scale ?? 1;
2709
+ const w = frame.width, h = frame.height;
2710
+ const defs = [];
2711
+ const body = [];
2712
+ let gradientCount = 0;
2713
+ const paintAttr = (paint, attr, alpha) => {
2714
+ if (isGradient(paint)) {
2715
+ const id = `g${gradientCount++}`;
2716
+ defs.push(gradientDef(id, paint));
2717
+ return `${attr}="url(#${id})"${alpha < 1 ? ` ${attr}-opacity="${fmt2(alpha)}"` : ""}`;
2718
+ }
2719
+ const rgba = paint;
2720
+ const a = rgba[3] * alpha;
2721
+ return `${attr}="${css([rgba[0], rgba[1], rgba[2], 1])}"${a < 1 ? ` ${attr}-opacity="${fmt2(a)}"` : ""}`;
2722
+ };
2723
+ if (frame.background && !options.transparent) body.push(`<rect width="${w}" height="${h}" fill="${frame.background}"/>`);
2724
+ for (const op of frame.ops) {
2725
+ if (op.kind === "image") {
2726
+ const m = op.matrix;
2727
+ body.push(`<image href="${escapeAttr(op.image.src)}" width="${op.image.width}" height="${op.image.height}" transform="matrix(${m.map(fmt2).join(" ")})"${op.alpha < 1 ? ` opacity="${fmt2(op.alpha)}"` : ""} preserveAspectRatio="none"/>`);
2728
+ continue;
2729
+ }
2730
+ const style = op.blend !== "normal" ? ` style="mix-blend-mode:${op.blend}"` : "";
2731
+ if (op.glow > 0) {
2732
+ const color = glowOf(op);
2733
+ const glowD = pathData(op.strokePath.length ? op.strokePath : op.path);
2734
+ if (color && glowD) {
2735
+ const base = Math.max(op.fillAlpha, op.strokeAlpha);
2736
+ const mode = frame.dark ? ' style="mix-blend-mode:screen"' : "";
2737
+ const passes = glowPasses(op.glow, op.stroke ? op.strokeWidth : 0).map((pass) => `<path d="${glowD}" fill="none" stroke="${css([color[0], color[1], color[2], 1])}" stroke-opacity="${fmt2(pass.alpha * base)}" stroke-width="${fmt2(pass.width)}" stroke-linecap="round" stroke-linejoin="round"/>`).join("");
2738
+ body.push(`<g${mode}>${passes}</g>`);
2739
+ }
2740
+ }
2741
+ if (op.fill && op.stroke && op.strokePath === op.path) {
2742
+ body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill, "fill", op.fillAlpha)} ${paintAttr(op.stroke, "stroke", op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`);
2743
+ continue;
2744
+ }
2745
+ if (op.fill) body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill, "fill", op.fillAlpha)}${style}/>`);
2746
+ if (op.stroke && op.strokePath.length) {
2747
+ body.push(`<path d="${pathData(op.strokePath)}" fill="none" ${paintAttr(op.stroke, "stroke", op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`);
2748
+ }
2749
+ }
2750
+ const defsBlock = defs.length ? `<defs>${defs.join("")}</defs>` : "";
2751
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${w * scale}" height="${h * scale}" viewBox="0 0 ${w} ${h}">${defsBlock}${body.join("")}</svg>`;
2752
+ }
2753
+
2754
+ // src/stage/raster.ts
2755
+ var import_node_module = require("module");
2756
+ var import_node_os = require("os");
2757
+ var import_node_worker_threads = require("worker_threads");
2758
+ var import_node_url = require("url");
2759
+ var RASTER_WORKER_SOURCE = String.raw`
2760
+ const { parentPort, workerData } = require('node:worker_threads')
2761
+ const { Resvg } = require(workerData.resvgPath)
2762
+
2763
+ function downsample(src, w, h, factor) {
2764
+ const dw = Math.max(1, Math.floor(w / factor)), dh = Math.max(1, Math.floor(h / factor))
2765
+ const out = new Float32Array(dw * dh * 3)
2766
+ const norm = 1 / (factor * factor)
2767
+ for (let y = 0; y < dh; y++) {
2768
+ for (let x = 0; x < dw; x++) {
2769
+ let r = 0, g = 0, b = 0
2770
+ for (let yy = 0; yy < factor; yy++) {
2771
+ let o = ((y * factor + yy) * w + x * factor) * 4
2772
+ for (let xx = 0; xx < factor; xx++) { r += src[o]; g += src[o + 1]; b += src[o + 2]; o += 4 }
2773
+ }
2774
+ const i = (y * dw + x) * 3
2775
+ out[i] = r * norm; out[i + 1] = g * norm; out[i + 2] = b * norm
2776
+ }
2777
+ }
2778
+ return { data: out, w: dw, h: dh }
2779
+ }
2780
+
2781
+ function boxBlur(img, radius) {
2782
+ const { data, w, h } = img
2783
+ const tmp = new Float32Array(data.length)
2784
+ const norm = 1 / (radius * 2 + 1)
2785
+ for (let y = 0; y < h; y++) {
2786
+ for (let c = 0; c < 3; c++) {
2787
+ let sum = 0
2788
+ for (let k = -radius; k <= radius; k++) sum += data[(y * w + Math.min(w - 1, Math.max(0, k))) * 3 + c]
2789
+ for (let x = 0; x < w; x++) {
2790
+ tmp[(y * w + x) * 3 + c] = sum * norm
2791
+ sum += data[(y * w + Math.min(w - 1, x + radius + 1)) * 3 + c] - data[(y * w + Math.max(0, x - radius)) * 3 + c]
2792
+ }
2793
+ }
2794
+ }
2795
+ for (let x = 0; x < w; x++) {
2796
+ for (let c = 0; c < 3; c++) {
2797
+ let sum = 0
2798
+ for (let k = -radius; k <= radius; k++) sum += tmp[(Math.min(h - 1, Math.max(0, k)) * w + x) * 3 + c]
2799
+ for (let y = 0; y < h; y++) {
2800
+ data[(y * w + x) * 3 + c] = sum * norm
2801
+ sum += tmp[(Math.min(h - 1, y + radius + 1) * w + x) * 3 + c] - tmp[(Math.max(0, y - radius) * w + x) * 3 + c]
2802
+ }
2803
+ }
2804
+ }
2805
+ }
2806
+
2807
+ // Bloom: bright marks spill soft light. Blurred layers add on top of the sharp image.
2808
+ function bloom(pixels, w, h, amount, background) {
2809
+ const [br, bg, bb] = background
2810
+ const layers = []
2811
+ // The spread follows output width, so a small preview and a 4K master look alike.
2812
+ const k = w / 1920
2813
+ for (const [base, radius, weight] of [[4, 3, 0.55], [8, 4, 0.3], [16, 4, 0.15]]) {
2814
+ const factor = Math.max(1, Math.round(base * k))
2815
+ const layer = downsample(pixels, w, h, factor)
2816
+ const d = layer.data
2817
+ for (let i = 0; i < d.length; i += 3) {
2818
+ // Only light above the background contributes, so the page never lifts or fogs.
2819
+ d[i] = Math.max(0, d[i] - br); d[i + 1] = Math.max(0, d[i + 1] - bg); d[i + 2] = Math.max(0, d[i + 2] - bb)
2820
+ }
2821
+ boxBlur(layer, radius); boxBlur(layer, radius)
2822
+ layers.push({ ...layer, factor, weight })
2823
+ }
2824
+ for (let y = 0; y < h; y++) {
2825
+ for (let x = 0; x < w; x++) {
2826
+ const o = (y * w + x) * 4
2827
+ let r = 0, g = 0, b = 0
2828
+ for (const layer of layers) {
2829
+ const fx = (x + 0.5) / layer.factor - 0.5, fy = (y + 0.5) / layer.factor - 0.5
2830
+ const x0 = Math.max(0, Math.floor(fx)), y0 = Math.max(0, Math.floor(fy))
2831
+ const x1 = Math.min(layer.w - 1, x0 + 1), y1 = Math.min(layer.h - 1, y0 + 1)
2832
+ const tx = Math.max(0, fx - x0), ty = Math.max(0, fy - y0)
2833
+ const d = layer.data, lw = layer.w
2834
+ for (let c = 0; c < 3; c++) {
2835
+ const v = (d[(y0 * lw + x0) * 3 + c] * (1 - tx) + d[(y0 * lw + x1) * 3 + c] * tx) * (1 - ty)
2836
+ + (d[(y1 * lw + x0) * 3 + c] * (1 - tx) + d[(y1 * lw + x1) * 3 + c] * tx) * ty
2837
+ if (c === 0) r += v * layer.weight
2838
+ else if (c === 1) g += v * layer.weight
2839
+ else b += v * layer.weight
2840
+ }
2841
+ }
2842
+ // Screen blend keeps highlights from clipping harshly.
2843
+ pixels[o] = 255 - (255 - pixels[o]) * (255 - Math.min(255, r * amount * 2.4)) / 255
2844
+ pixels[o + 1] = 255 - (255 - pixels[o + 1]) * (255 - Math.min(255, g * amount * 2.4)) / 255
2845
+ pixels[o + 2] = 255 - (255 - pixels[o + 2]) * (255 - Math.min(255, b * amount * 2.4)) / 255
2846
+ }
2847
+ }
2848
+ }
2849
+
2850
+ function raster(svg, width, height) {
2851
+ const image = new Resvg(svg, { fitTo: { mode: 'width', value: width }, font: { loadSystemFonts: false } }).render()
2852
+ if (image.height === height) return image.pixels
2853
+ // Rounding can differ by a row at unusual sizes. Keep the requested size exactly.
2854
+ const out = new Uint8Array(width * height * 4)
2855
+ for (let y = 0; y < height; y++) {
2856
+ const row = Math.min(image.height - 1, y) * width * 4
2857
+ out.set(image.pixels.subarray(row, row + width * 4), y * width * 4)
2858
+ }
2859
+ return out
2860
+ }
2861
+
2862
+ parentPort.on('message', (job) => {
2863
+ try {
2864
+ let out
2865
+ if (job.svgs.length === 1) {
2866
+ out = new Uint8Array(raster(job.svgs[0], job.width, job.height))
2867
+ } else {
2868
+ // Motion blur: average sub-frames across the shutter.
2869
+ const n = job.svgs.length
2870
+ // Sixteen bits hold 257 full-white sub-frames, at half the memory of thirty-two.
2871
+ let sum = null
2872
+ for (const svg of job.svgs) {
2873
+ const px = raster(svg, job.width, job.height)
2874
+ if (!sum) sum = n <= 257 ? new Uint16Array(px.length) : new Uint32Array(px.length)
2875
+ for (let i = 0; i < px.length; i++) sum[i] += px[i]
2876
+ }
2877
+ out = new Uint8Array(sum.length)
2878
+ for (let i = 0; i < sum.length; i++) out[i] = sum[i] / n + 0.5
2879
+ }
2880
+ if (job.bloom > 0) bloom(out, job.width, job.height, job.bloom, job.background)
2881
+ parentPort.postMessage({ id: job.id, pixels: out }, [out.buffer])
2882
+ } catch (error) {
2883
+ parentPort.postMessage({ id: job.id, error: String(error && error.message || error) })
2884
+ }
2885
+ })
2886
+ `;
2887
+ function resolveResvg() {
2888
+ const here = typeof __filename !== "undefined" ? __filename : (0, import_node_url.fileURLToPath)(void 0);
2889
+ return (0, import_node_module.createRequire)(here).resolve("@resvg/resvg-js");
2890
+ }
2891
+ var RasterPool = class {
2892
+ workers = [];
2893
+ idle = [];
2894
+ queue = [];
2895
+ pending = /* @__PURE__ */ new Map();
2896
+ nextId = 1;
2897
+ failure = null;
2898
+ constructor(size = defaultPoolSize()) {
2899
+ const resvgPath = resolveResvg();
2900
+ for (let i = 0; i < size; i++) {
2901
+ const worker = new import_node_worker_threads.Worker(RASTER_WORKER_SOURCE, { eval: true, workerData: { resvgPath } });
2902
+ worker.on("message", (message) => {
2903
+ const entry = this.pending.get(message.id);
2904
+ this.pending.delete(message.id);
2905
+ this.idle.push(worker);
2906
+ this.pump();
2907
+ if (!entry) return;
2908
+ if (message.error || !message.pixels) entry.reject(new Error(`Frame rasterization failed: ${message.error}`));
2909
+ else entry.resolve(message.pixels);
2910
+ });
2911
+ worker.on("error", (error) => this.fail(error instanceof Error ? error : new Error(String(error))));
2912
+ this.workers.push(worker);
2913
+ this.idle.push(worker);
2914
+ }
2915
+ }
2916
+ get size() {
2917
+ return this.workers.length;
2918
+ }
2919
+ fail(error) {
2920
+ this.failure = error;
2921
+ for (const entry of this.pending.values()) entry.reject(error);
2922
+ this.pending.clear();
2923
+ }
2924
+ pump() {
2925
+ while (this.idle.length > 0 && this.queue.length > 0) {
2926
+ const worker = this.idle.pop();
2927
+ const { job, id } = this.queue.shift();
2928
+ worker.postMessage({ id, ...job });
2929
+ }
2930
+ }
2931
+ run(job) {
2932
+ if (this.failure) return Promise.reject(this.failure);
2933
+ const id = this.nextId++;
2934
+ return new Promise((resolve3, reject) => {
2935
+ this.pending.set(id, { resolve: resolve3, reject });
2936
+ this.queue.push({ job, id });
2937
+ this.pump();
2938
+ });
2939
+ }
2940
+ async close() {
2941
+ this.failure ??= new Error("The raster pool was closed.");
2942
+ for (const entry of this.pending.values()) entry.reject(this.failure);
2943
+ this.pending.clear();
2944
+ this.queue.length = 0;
2945
+ await Promise.all(this.workers.map((worker) => worker.terminate()));
2946
+ }
2947
+ };
2948
+ function defaultPoolSize() {
2949
+ return Math.max(1, Math.min(12, (0, import_node_os.cpus)().length - 2));
2950
+ }
2951
+ function framesToJob(frames, width, parseBackground, height) {
2952
+ const first = frames[0];
2953
+ const scale = width / first.width;
2954
+ return {
2955
+ svgs: frames.map((frame) => frameToSvg(frame)),
2956
+ width,
2957
+ height: height ?? Math.round(first.height * scale),
2958
+ bloom: first.dark ? first.bloom : 0,
2959
+ background: parseBackground(first.background)
2960
+ };
2961
+ }
2962
+
2963
+ // src/stage/morph.ts
2964
+ function growTo(r, target) {
2965
+ const count = segmentCount(r);
2966
+ if (count >= target || count === 0) return r;
2967
+ const segments = [];
2968
+ for (let i = 0; i < count; i++) {
2969
+ const o = i * 6;
2970
+ const pts = Array.from(r.p.subarray(o, o + 8));
2971
+ segments.push({ pts, length: chord(pts) });
2972
+ }
2973
+ while (segments.length < target) {
2974
+ let longest = 0;
2975
+ for (let i = 1; i < segments.length; i++) if (segments[i].length > segments[longest].length) longest = i;
2976
+ const [a, b] = bisect(segments[longest].pts);
2977
+ segments.splice(longest, 1, { pts: a, length: chord(a) }, { pts: b, length: chord(b) });
2978
+ }
2979
+ const out = new Float64Array(2 + target * 6);
2980
+ out[0] = r.p[0];
2981
+ out[1] = r.p[1];
2982
+ for (let i = 0; i < target; i++) {
2983
+ const pts = segments[i].pts;
2984
+ for (let k = 0; k < 6; k++) out[2 + i * 6 + k] = pts[2 + k];
2985
+ }
2986
+ return { p: out, closed: r.closed };
2987
+ }
2988
+ function chord(pts) {
2989
+ return Math.hypot(pts[2] - pts[0], pts[3] - pts[1]) + Math.hypot(pts[4] - pts[2], pts[5] - pts[3]) + Math.hypot(pts[6] - pts[4], pts[7] - pts[5]);
2990
+ }
2991
+ function bisect(p) {
2992
+ const ax = (p[0] + p[2]) / 2, ay = (p[1] + p[3]) / 2;
2993
+ const bx = (p[2] + p[4]) / 2, by = (p[3] + p[5]) / 2;
2994
+ const cx = (p[4] + p[6]) / 2, cy = (p[5] + p[7]) / 2;
2995
+ const dx = (ax + bx) / 2, dy = (ay + by) / 2;
2996
+ const ex = (bx + cx) / 2, ey = (by + cy) / 2;
2997
+ const fx = (dx + ex) / 2, fy = (dy + ey) / 2;
2998
+ return [[p[0], p[1], ax, ay, dx, dy, fx, fy], [fx, fy, ex, ey, cx, cy, p[6], p[7]]];
2999
+ }
3000
+ function bestRotation(a, b) {
3001
+ const count = segmentCount(b);
3002
+ if (!a.closed || !b.closed || count < 2) return b;
3003
+ const [ax, ay] = ringCenter(a), [bx, by] = ringCenter(b);
3004
+ const stride = Math.max(1, Math.floor(count / 48));
3005
+ let best = 0, bestCost = Infinity;
3006
+ for (let shift = 0; shift < count; shift += stride) {
3007
+ let cost = 0;
3008
+ for (let i = 0; i < count; i += stride) {
3009
+ const j = (i + shift) % count;
3010
+ const dx = a.p[i * 6] - ax - (b.p[j * 6] - bx);
3011
+ const dy = a.p[i * 6 + 1] - ay - (b.p[j * 6 + 1] - by);
3012
+ cost += dx * dx + dy * dy;
3013
+ }
3014
+ if (cost < bestCost) {
3015
+ bestCost = cost;
3016
+ best = shift;
3017
+ }
3018
+ }
3019
+ if (best === 0) return b;
3020
+ const out = new Float64Array(b.p.length);
3021
+ out[0] = b.p[best * 6];
3022
+ out[1] = b.p[best * 6 + 1];
3023
+ for (let i = 0; i < count; i++) {
3024
+ const j = (i + best) % count;
3025
+ for (let k = 0; k < 6; k++) out[2 + i * 6 + k] = b.p[2 + j * 6 + k];
3026
+ }
3027
+ return { p: out, closed: b.closed };
3028
+ }
3029
+ function pointRing(x, y, count, closed) {
3030
+ const out = new Float64Array(2 + count * 6);
3031
+ for (let i = 0; i < out.length; i += 2) {
3032
+ out[i] = x;
3033
+ out[i + 1] = y;
3034
+ }
3035
+ return { p: out, closed };
3036
+ }
3037
+ function pairRings(from, to) {
3038
+ const rank = (path) => [...path].sort((a2, b2) => Math.abs(signedArea(b2)) + ringLength(b2) * 0.01 - (Math.abs(signedArea(a2)) + ringLength(a2) * 0.01));
3039
+ const a = rank(from), b = rank(to);
3040
+ const pairs = [];
3041
+ const free = b.slice();
3042
+ for (const ringA of a) {
3043
+ if (free.length === 0) {
3044
+ const [x, y] = ringCenter(ringA);
3045
+ pairs.push([ringA, pointRing(x, y, segmentCount(ringA), ringA.closed)]);
3046
+ continue;
3047
+ }
3048
+ const [ax, ay] = ringCenter(ringA);
3049
+ let bestIndex = 0, bestCost = Infinity;
3050
+ for (let i = 0; i < Math.min(free.length, 3); i++) {
3051
+ const [bx, by] = ringCenter(free[i]);
3052
+ const cost = Math.hypot(ax - bx, ay - by) + i * 40;
3053
+ if (cost < bestCost) {
3054
+ bestCost = cost;
3055
+ bestIndex = i;
3056
+ }
3057
+ }
3058
+ pairs.push([ringA, free[bestIndex]]);
3059
+ free.splice(bestIndex, 1);
3060
+ }
3061
+ for (const ringB of free) {
3062
+ const [x, y] = ringCenter(ringB);
3063
+ pairs.push([pointRing(x, y, segmentCount(ringB), ringB.closed), ringB]);
3064
+ }
3065
+ return pairs;
3066
+ }
3067
+ function alignPaths(from, to, minSegments = 12) {
3068
+ const pairs = pairRings(from, to);
3069
+ const a = [], b = [], closed = [];
3070
+ for (const [ra, rb] of pairs) {
3071
+ const target = Math.max(segmentCount(ra), segmentCount(rb), ra.closed && rb.closed ? minSegments : 1);
3072
+ let x = growTo(ra, target);
3073
+ let y = growTo(rb, target);
3074
+ if (x.closed && y.closed) {
3075
+ if (Math.sign(signedArea(x)) !== Math.sign(signedArea(y)) && signedArea(x) !== 0 && signedArea(y) !== 0) y = reverseRing(y);
3076
+ y = bestRotation(x, y);
3077
+ } else if (!x.closed && !y.closed) {
3078
+ const n = x.p.length;
3079
+ const straight = Math.hypot(x.p[0] - y.p[0], x.p[1] - y.p[1]) + Math.hypot(x.p[n - 2] - y.p[n - 2], x.p[n - 1] - y.p[n - 1]);
3080
+ const flipped = Math.hypot(x.p[0] - y.p[n - 2], x.p[1] - y.p[n - 1]) + Math.hypot(x.p[n - 2] - y.p[0], x.p[n - 1] - y.p[1]);
3081
+ if (flipped < straight) y = reverseRing(y);
3082
+ }
3083
+ a.push(x.p);
3084
+ b.push(y.p);
3085
+ closed.push(x.closed && y.closed);
3086
+ }
3087
+ return { from: a, to: b, closed };
3088
+ }
3089
+ function pathMixer(from, to) {
3090
+ if (from === to) return () => to;
3091
+ if (pathLength(from) === 0 && from.length === 0) return (alpha) => alpha >= 1 ? to : from;
3092
+ const aligned = alignPaths(from, to);
3093
+ return (alpha) => {
3094
+ if (alpha <= 0) return from;
3095
+ if (alpha >= 1) return to;
3096
+ const rings = new Array(aligned.from.length);
3097
+ for (let r = 0; r < rings.length; r++) {
3098
+ const a = aligned.from[r], b = aligned.to[r];
3099
+ const out = new Float64Array(a.length);
3100
+ for (let i = 0; i < a.length; i++) out[i] = a[i] + (b[i] - a[i]) * alpha;
3101
+ rings[r] = { p: out, closed: aligned.closed[r] };
3102
+ }
3103
+ return rings;
3104
+ };
3105
+ }
3106
+
3107
+ // src/stage/node.ts
3108
+ var DEFAULT_PROPS = {
3109
+ x: 0,
3110
+ y: 0,
3111
+ rotation: 0,
3112
+ sx: 1,
3113
+ sy: 1,
3114
+ px: 0,
3115
+ py: 0,
3116
+ opacity: 1,
3117
+ visible: true,
3118
+ z: 0,
3119
+ path: null,
3120
+ fill: null,
3121
+ fillOpacity: 1,
3122
+ stroke: null,
3123
+ strokeOpacity: 1,
3124
+ strokeWidth: 3,
3125
+ cap: "round",
3126
+ join: "round",
3127
+ dash: null,
3128
+ dashOffset: 0,
3129
+ trimFrom: 0,
3130
+ trimTo: 1,
3131
+ trimEach: false,
3132
+ glow: 0,
3133
+ glowColor: null,
3134
+ blend: "normal",
3135
+ fixed: false,
3136
+ image: null
3137
+ };
3138
+ var NUMERIC = /* @__PURE__ */ new Set([
3139
+ "x",
3140
+ "y",
3141
+ "rotation",
3142
+ "sx",
3143
+ "sy",
3144
+ "px",
3145
+ "py",
3146
+ "opacity",
3147
+ "z",
3148
+ "fillOpacity",
3149
+ "strokeOpacity",
3150
+ "strokeWidth",
3151
+ "dashOffset",
3152
+ "trimFrom",
3153
+ "trimTo",
3154
+ "glow"
3155
+ ]);
3156
+ function mixer(prop, from, to) {
3157
+ if (NUMERIC.has(prop)) {
3158
+ const a = from, b = to;
3159
+ return ((alpha) => a + (b - a) * alpha);
3160
+ }
3161
+ if (prop === "fill" || prop === "stroke") {
3162
+ const a = from, b = to;
3163
+ if (a && b) return ((alpha) => mixPaint(a, b, alpha));
3164
+ return null;
3165
+ }
3166
+ if (prop === "glowColor") {
3167
+ const a = from, b = to;
3168
+ if (a && b) return ((alpha) => mixColor(a, b, alpha));
3169
+ return null;
3170
+ }
3171
+ if (prop === "path") {
3172
+ const a = from, b = to;
3173
+ if (a && b) return pathMixer(a, b);
3174
+ return null;
3175
+ }
3176
+ return null;
3177
+ }
3178
+ var nextId = 1;
3179
+ var Node = class _Node {
3180
+ id = nextId++;
3181
+ parent = null;
3182
+ children = [];
3183
+ /** Free-form metadata, such as the source character of a glyph. */
3184
+ data = {};
3185
+ /** Label shown in timelines and diagnostics. */
3186
+ label = "";
3187
+ base = Object.create(DEFAULT_PROPS);
3188
+ tracks = null;
3189
+ overlay = null;
3190
+ overlayFrame = -1;
3191
+ /** On stage: writes become timeline keys instead of initial state. */
3192
+ mounted = false;
3193
+ /** Rebuilt on every frame from timeline values. */
3194
+ draw = null;
3195
+ /** Emits draw operations directly, for objects with thousands of marks such as 3D meshes. */
3196
+ rawOps = null;
3197
+ constructor(path) {
3198
+ if (path) this.base.path = path;
3199
+ }
3200
+ // ── Raw property access ───────────────────────────────────────────────
3201
+ get(prop) {
3202
+ const overlay = this.overlay;
3203
+ if (overlay !== null && overlay.has(prop) && (this.overlayFrame === clock.frame || clock.capture !== null)) {
3204
+ return overlay.get(prop);
3205
+ }
3206
+ const track = this.tracks?.get(prop);
3207
+ if (track) return track.sample(clock.now);
3208
+ return this.base[prop];
3209
+ }
3210
+ set(prop, value) {
3211
+ if (clock.capture) {
3212
+ this.overlay ??= /* @__PURE__ */ new Map();
3213
+ this.overlay.set(prop, value);
3214
+ clock.capture.add(this);
3215
+ return this;
3216
+ }
3217
+ if (!this.mounted) {
3218
+ this.base[prop] = value;
3219
+ return this;
3220
+ }
3221
+ if (clock.mode === "render") {
3222
+ this.overlay ??= /* @__PURE__ */ new Map();
3223
+ if (this.overlayFrame !== clock.frame) {
3224
+ this.overlay.clear();
3225
+ this.overlayFrame = clock.frame;
3226
+ }
3227
+ this.overlay.set(prop, value);
3228
+ return this;
3229
+ }
3230
+ this.track(prop).step(clock.now, value);
3231
+ return this;
3232
+ }
3233
+ track(prop) {
3234
+ this.tracks ??= /* @__PURE__ */ new Map();
3235
+ let track = this.tracks.get(prop);
3236
+ if (!track) {
3237
+ track = new Track(this.base[prop]);
3238
+ this.tracks.set(prop, track);
3239
+ }
3240
+ return track;
3241
+ }
3242
+ /** Record a change from the current value to `to` over [t0, t1]. */
3243
+ tween(prop, to, t0, t1, ease) {
3244
+ const previous = clock.now;
3245
+ clock.now = t0;
3246
+ const from = this.get(prop);
3247
+ clock.now = previous;
3248
+ const at = t1 > t0 ? mixer(prop, from, to) : null;
3249
+ const key = { t0, t1, ease, to, at };
3250
+ this.track(prop).add(key);
3251
+ }
3252
+ // ── Tree ──────────────────────────────────────────────────────────────
3253
+ add(...nodes) {
3254
+ for (const child of nodes) {
3255
+ if (child.parent === this) continue;
3256
+ child.parent?.drop(child);
3257
+ child.parent = this;
3258
+ this.children.push(child);
3259
+ if (this.mounted) mountTree(child, clock.now);
3260
+ }
3261
+ return this;
3262
+ }
3263
+ drop(child) {
3264
+ const index = this.children.indexOf(child);
3265
+ if (index >= 0) this.children.splice(index, 1);
3266
+ child.parent = null;
3267
+ return this;
3268
+ }
3269
+ /** Self and all descendants, parents first. */
3270
+ all() {
3271
+ const out = [];
3272
+ const visit = (node) => {
3273
+ out.push(node);
3274
+ for (const child of node.children) visit(child);
3275
+ };
3276
+ visit(this);
3277
+ return out;
3278
+ }
3279
+ /** Descendants that draw something. A leaf group returns itself if it draws. */
3280
+ leaves() {
3281
+ return this.all().filter((node) => node.get("path") !== null || node.draw !== null || node.get("image") !== null);
3282
+ }
3283
+ /** A static copy of the current state, off stage. */
3284
+ clone() {
3285
+ const copy = Object.create(Object.getPrototypeOf(this));
3286
+ Object.assign(copy, this);
3287
+ copy.id = nextId++;
3288
+ copy.parent = null;
3289
+ copy.mounted = false;
3290
+ copy.tracks = null;
3291
+ copy.overlay = null;
3292
+ copy.overlayFrame = -1;
3293
+ copy.data = { ...this.data };
3294
+ copy.base = Object.create(DEFAULT_PROPS);
3295
+ for (const key of Object.keys(DEFAULT_PROPS)) {
3296
+ ;
3297
+ copy.base[key] = this.get(key);
3298
+ }
3299
+ copy.children = this.children.map((child) => {
3300
+ const next = child.clone();
3301
+ next.parent = copy;
3302
+ return next;
3303
+ });
3304
+ return copy;
3305
+ }
3306
+ // ── Transforms ────────────────────────────────────────────────────────
3307
+ localMatrix() {
3308
+ return compose(this.get("x"), this.get("y"), this.get("rotation"), this.get("sx"), this.get("sy"), this.get("px"), this.get("py"));
3309
+ }
3310
+ worldMatrix() {
3311
+ let m = this.localMatrix();
3312
+ for (let node = this.parent; node; node = node.parent) m = mul(node.localMatrix(), m);
3313
+ return m;
3314
+ }
3315
+ toWorld(x, y) {
3316
+ return apply(this.worldMatrix(), x, y);
3317
+ }
3318
+ /** Stage-space bounds of this node and its descendants. */
3319
+ bounds() {
3320
+ return this.boundsFrom(this.parent ? this.parent.worldMatrix() : IDENTITY) ?? { x: 0, y: 0, width: 0, height: 0 };
3321
+ }
3322
+ boundsFrom(parent) {
3323
+ const m = mul(parent, this.localMatrix());
3324
+ let result = null;
3325
+ const path = this.get("path");
3326
+ if (path) result = pathBounds(transformPath(path, m));
3327
+ const image = this.get("image");
3328
+ if (image) result = unionBounds(result, boundsOfRect(m, image.width, image.height));
3329
+ if (this.draw) {
3330
+ const built = this.draw(clock.now);
3331
+ const list = built === null ? [] : Array.isArray(built) ? built : [built];
3332
+ for (const child of list) result = unionBounds(result, child.boundsFrom(m));
3333
+ }
3334
+ for (const child of this.children) {
3335
+ if (child.get("visible")) result = unionBounds(result, child.boundsFrom(m));
3336
+ }
3337
+ return result;
3338
+ }
3339
+ get center() {
3340
+ const b = this.bounds();
3341
+ return [b.x + b.width / 2, b.y + b.height / 2];
3342
+ }
3343
+ get top() {
3344
+ const b = this.bounds();
3345
+ return [b.x + b.width / 2, b.y];
3346
+ }
3347
+ get bottom() {
3348
+ const b = this.bounds();
3349
+ return [b.x + b.width / 2, b.y + b.height];
3350
+ }
3351
+ get left() {
3352
+ const b = this.bounds();
3353
+ return [b.x, b.y + b.height / 2];
3354
+ }
3355
+ get right() {
3356
+ const b = this.bounds();
3357
+ return [b.x + b.width, b.y + b.height / 2];
3358
+ }
3359
+ get width() {
3360
+ return this.bounds().width;
3361
+ }
3362
+ get height() {
3363
+ return this.bounds().height;
3364
+ }
3365
+ /** Set the local position of the origin. */
3366
+ at(x, y) {
3367
+ const [px, py] = typeof x === "number" ? [x, y ?? 0] : x;
3368
+ this.set("x", px);
3369
+ this.set("y", py);
3370
+ return this;
3371
+ }
3372
+ shift(dx, dy) {
3373
+ const [ox, oy] = typeof dx === "number" ? [dx, dy ?? 0] : dx;
3374
+ this.set("x", this.get("x") + ox);
3375
+ this.set("y", this.get("y") + oy);
3376
+ return this;
3377
+ }
3378
+ /** Move so the center of the bounds lands on a stage point or on another node's center. */
3379
+ moveTo(target) {
3380
+ const destination = target instanceof _Node ? target.center : target;
3381
+ const [cx, cy] = this.center;
3382
+ const inverse = this.parent ? invert(this.parent.worldMatrix()) : IDENTITY;
3383
+ const [lx0, ly0] = apply(inverse, cx, cy);
3384
+ const [lx1, ly1] = apply(inverse, destination[0], destination[1]);
3385
+ return this.shift(lx1 - lx0, ly1 - ly0);
3386
+ }
3387
+ /** Move the origin to a stage point without changing how anything looks. */
3388
+ pivotAt(point) {
3389
+ const parent = this.parent ? this.parent.worldMatrix() : IDENTITY;
3390
+ const before = mul(parent, this.localMatrix());
3391
+ const [lx, ly] = apply(invert(before), point[0], point[1]);
3392
+ const [nx, ny] = apply(invert(parent), point[0], point[1]);
3393
+ this.set("px", lx);
3394
+ this.set("py", ly);
3395
+ this.set("x", nx);
3396
+ this.set("y", ny);
3397
+ return this;
3398
+ }
3399
+ /** Scale around the center, or around a given stage point. */
3400
+ scale(factor, about) {
3401
+ const [fx, fy] = typeof factor === "number" ? [factor, factor] : factor;
3402
+ this.pivotAt(about ?? this.center);
3403
+ this.set("sx", this.get("sx") * fx);
3404
+ this.set("sy", this.get("sy") * fy);
3405
+ return this;
3406
+ }
3407
+ /** Rotate around the center, or around a given stage point. */
3408
+ rotate(radians, about) {
3409
+ this.pivotAt(about ?? this.center);
3410
+ this.set("rotation", this.get("rotation") + radians);
3411
+ return this;
3412
+ }
3413
+ /** Scale to an exact on-screen width or height, keeping proportions. */
3414
+ fitTo(size) {
3415
+ const b = this.bounds();
3416
+ const scales = [];
3417
+ if (size.width !== void 0 && b.width > 0) scales.push(size.width / b.width);
3418
+ if (size.height !== void 0 && b.height > 0) scales.push(size.height / b.height);
3419
+ return scales.length ? this.scale(Math.min(...scales)) : this;
3420
+ }
3421
+ // ── Layout ────────────────────────────────────────────────────────────
3422
+ /** Place beside another node or stage point, with a gap measured between bounds. */
3423
+ nextTo(target, side = "right", gap = 28) {
3424
+ const [dx, dy] = direction(side);
3425
+ const b = target instanceof _Node ? target.bounds() : { x: target[0], y: target[1], width: 0, height: 0 };
3426
+ const own = this.bounds();
3427
+ const cx = b.x + b.width / 2, cy = b.y + b.height / 2;
3428
+ const anchorX = cx + dx * (b.width / 2 + gap + own.width / 2);
3429
+ const anchorY = cy + dy * (b.height / 2 + gap + own.height / 2);
3430
+ return this.moveTo([anchorX, anchorY]);
3431
+ }
3432
+ /** Line up one edge with another node's same edge. */
3433
+ alignTo(target, edge) {
3434
+ const own = this.bounds();
3435
+ const b = target instanceof _Node ? target.bounds() : { x: target[0], y: target[1], width: 0, height: 0 };
3436
+ if (edge === "left") return this.shift(b.x - own.x, 0);
3437
+ if (edge === "right") return this.shift(b.x + b.width - own.x - own.width, 0);
3438
+ if (edge === "top") return this.shift(0, b.y - own.y);
3439
+ return this.shift(0, b.y + b.height - own.y - own.height);
3440
+ }
3441
+ /** Lay out children in a row or column, keeping the group's center. */
3442
+ arrange(side = "right", gap = 24) {
3443
+ const [dx, dy] = direction(side);
3444
+ const center = this.center;
3445
+ let previous = null;
3446
+ for (const child of this.children) {
3447
+ if (previous) {
3448
+ const b = previous.bounds(), own = child.bounds();
3449
+ const px = b.x + b.width / 2 + dx * (b.width / 2 + gap + own.width / 2);
3450
+ const py = b.y + b.height / 2 + dy * (b.height / 2 + gap + own.height / 2);
3451
+ child.moveTo([dx === 0 ? b.x + b.width / 2 : px, dy === 0 ? b.y + b.height / 2 : py]);
3452
+ }
3453
+ previous = child;
3454
+ }
3455
+ return this.moveTo(center);
3456
+ }
3457
+ // ── Paint ─────────────────────────────────────────────────────────────
3458
+ fill(color, opacity) {
3459
+ this.set("fill", color === null ? null : toPaint(color));
3460
+ if (opacity !== void 0) this.set("fillOpacity", opacity);
3461
+ return this;
3462
+ }
3463
+ stroke(color, width, opacity) {
3464
+ this.set("stroke", color === null ? null : toPaint(color));
3465
+ if (width !== void 0) this.set("strokeWidth", width);
3466
+ if (opacity !== void 0) this.set("strokeOpacity", opacity);
3467
+ return this;
3468
+ }
3469
+ /** Recolor this node and its descendants, keeping whichever paints exist. */
3470
+ color(color) {
3471
+ const paint = toPaint(color);
3472
+ for (const node of this.all()) {
3473
+ if (node.get("stroke")) node.set("stroke", paint);
3474
+ if (node.get("fill")) node.set("fill", paint);
3475
+ if (node.get("glowColor") && !isGradient(paint)) node.set("glowColor", paint);
3476
+ }
3477
+ return this;
3478
+ }
3479
+ opacity(value) {
3480
+ return this.set("opacity", value);
3481
+ }
3482
+ /** Soft light around the shape. The radius is in stage pixels. */
3483
+ glow(radius, color) {
3484
+ this.set("glow", radius);
3485
+ if (color !== void 0) {
3486
+ const paint = toPaint(color);
3487
+ this.set("glowColor", isGradient(paint) ? null : paint);
3488
+ }
3489
+ return this;
3490
+ }
3491
+ dash(pattern, offset = 0) {
3492
+ this.set("dash", pattern);
3493
+ return this.set("dashOffset", offset);
3494
+ }
3495
+ zIndex(value) {
3496
+ return this.set("z", value);
3497
+ }
3498
+ /** Pin to the screen so the camera does not move this node. */
3499
+ pin() {
3500
+ return this.set("fixed", true);
3501
+ }
3502
+ hide() {
3503
+ return this.set("visible", false);
3504
+ }
3505
+ show() {
3506
+ return this.set("visible", true);
3507
+ }
3508
+ named(label) {
3509
+ this.label = label;
3510
+ return this;
3511
+ }
3512
+ };
3513
+ function boundsOfRect(m, width, height) {
3514
+ const corners = [apply(m, 0, 0), apply(m, width, 0), apply(m, width, height), apply(m, 0, height)];
3515
+ const xs = corners.map((c) => c[0]), ys = corners.map((c) => c[1]);
3516
+ const x = Math.min(...xs), y = Math.min(...ys);
3517
+ return { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y };
3518
+ }
3519
+ function direction(side) {
3520
+ if (typeof side !== "string") return side;
3521
+ if (side === "left") return [-1, 0];
3522
+ if (side === "right") return [1, 0];
3523
+ if (side === "top" || side === "up") return [0, -1];
3524
+ return [0, 1];
3525
+ }
3526
+ function mountTree(node, time) {
3527
+ const wasVisible = node.base.visible;
3528
+ for (const entry of node.all()) entry.mounted = true;
3529
+ if (time > 0 || !wasVisible) {
3530
+ const track = node.track("visible");
3531
+ track.initial = false;
3532
+ if (wasVisible) track.step(time, true);
3533
+ }
3534
+ }
3535
+
3536
+ // src/stage/stage.ts
3537
+ function isFilm(value) {
3538
+ return !!value && typeof value === "object" && value.kind === "vizmatic.film";
3539
+ }
3540
+ var Suspend = class {
3541
+ constructor(promise) {
3542
+ this.promise = promise;
3543
+ }
3544
+ promise;
3545
+ /** Lets a second copy of the engine recognize this without instanceof. */
3546
+ isVizmaticSuspend = true;
3547
+ };
3548
+ function isSuspend(error) {
3549
+ return typeof error === "object" && error !== null && error.isVizmaticSuspend === true;
3550
+ }
3551
+
3552
+ // src/stage/font-types.ts
3553
+ function curveFree(contours) {
3554
+ return { contours: contours.filter((contour) => contour.length >= 8) };
3555
+ }
3556
+
3557
+ // src/stage/assets.ts
3558
+ var assetBase = null;
3559
+ var isNode = typeof process !== "undefined" && !!process.versions?.node && typeof globalThis.document === "undefined";
3560
+ function moduleUrl() {
3561
+ const url = void 0;
3562
+ if (url) return url;
3563
+ return `file://${typeof __filename !== "undefined" ? __filename : ""}`;
3564
+ }
3565
+ async function nodeRead(relative) {
3566
+ const fsName = "node:fs/promises", pathName = "node:path", urlName = "node:url";
3567
+ const [fs, path, url] = await Promise.all([import(fsName), import(pathName), import(urlName)]);
3568
+ let directory = path.dirname(url.fileURLToPath(moduleUrl()));
3569
+ for (let depth = 0; depth < 6; depth++) {
3570
+ const candidate = path.join(directory, "assets", relative);
3571
+ try {
3572
+ const bytes = await fs.readFile(candidate);
3573
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
3574
+ } catch (error) {
3575
+ if (error.code !== "ENOENT") throw error;
3576
+ }
3577
+ directory = path.dirname(directory);
3578
+ }
3579
+ throw new Error(`Bundled asset not found: assets/${relative}`);
3580
+ }
3581
+ async function loadBinaryAsset(relative) {
3582
+ if (isNode) return nodeRead(relative);
3583
+ const base = assetBase ?? new URL("./assets/", moduleUrl()).href;
3584
+ const response = await fetch(new URL(relative, base));
3585
+ const type = response.headers.get("content-type") ?? "";
3586
+ if (!response.ok || type.includes("text/html")) {
3587
+ throw new Error(`Could not load ${relative} from ${response.url} (HTTP ${response.status}, ${type || "no content type"}). Call setAssetBase() with the folder that holds fonts/.`);
3588
+ }
3589
+ return response.arrayBuffer();
3590
+ }
3591
+
3592
+ // src/stage/font.ts
3593
+ var Reader = class {
3594
+ constructor(bytes, offset = 0) {
3595
+ this.bytes = bytes;
3596
+ this.offset = offset;
3597
+ this.view = new DataView(bytes);
3598
+ }
3599
+ bytes;
3600
+ offset;
3601
+ view;
3602
+ seek(offset) {
3603
+ this.offset = offset;
3604
+ return this;
3605
+ }
3606
+ get position() {
3607
+ return this.offset;
3608
+ }
3609
+ u8() {
3610
+ return this.view.getUint8(this.offset++);
3611
+ }
3612
+ i8() {
3613
+ return this.view.getInt8(this.offset++);
3614
+ }
3615
+ u16() {
3616
+ const v = this.view.getUint16(this.offset);
3617
+ this.offset += 2;
3618
+ return v;
3619
+ }
3620
+ i16() {
3621
+ const v = this.view.getInt16(this.offset);
3622
+ this.offset += 2;
3623
+ return v;
3624
+ }
3625
+ u32() {
3626
+ const v = this.view.getUint32(this.offset);
3627
+ this.offset += 4;
3628
+ return v;
3629
+ }
3630
+ tag() {
3631
+ let out = "";
3632
+ for (let i = 0; i < 4; i++) out += String.fromCharCode(this.u8());
3633
+ return out;
3634
+ }
3635
+ };
3636
+ function parseFont(bytes) {
3637
+ const r = new Reader(bytes);
3638
+ const version = r.u32();
3639
+ if (version !== 65536 && version !== 1953658213) {
3640
+ throw new Error("Stage text needs a TrueType (.ttf) font with glyf outlines.");
3641
+ }
3642
+ const tableCount = r.u16();
3643
+ r.seek(12);
3644
+ const tables = /* @__PURE__ */ new Map();
3645
+ for (let i = 0; i < tableCount; i++) {
3646
+ const tag = r.tag();
3647
+ r.u32();
3648
+ tables.set(tag, { offset: r.u32(), length: r.u32() });
3649
+ }
3650
+ const need = (tag) => {
3651
+ const table = tables.get(tag);
3652
+ if (!table) throw new Error(`Font is missing its ${tag} table.`);
3653
+ return table;
3654
+ };
3655
+ const head = need("head");
3656
+ r.seek(head.offset + 18);
3657
+ const unitsPerEm = r.u16();
3658
+ r.seek(head.offset + 50);
3659
+ const longLoca = r.i16() === 1;
3660
+ const hhea = need("hhea");
3661
+ r.seek(hhea.offset + 4);
3662
+ const ascent = r.i16();
3663
+ const descent = r.i16();
3664
+ const lineGap = r.i16();
3665
+ r.seek(hhea.offset + 34);
3666
+ const hMetrics = r.u16();
3667
+ r.seek(need("maxp").offset + 4);
3668
+ const glyphCount = r.u16();
3669
+ const hmtx = need("hmtx");
3670
+ const loca = need("loca");
3671
+ const glyf = need("glyf");
3672
+ const cmap = parseCmap(r, need("cmap").offset);
3673
+ const kerning = tables.has("GPOS") ? parseKerning(r, tables.get("GPOS").offset) : () => 0;
3674
+ const advance = (glyph) => {
3675
+ const index = Math.min(glyph, hMetrics - 1);
3676
+ r.seek(hmtx.offset + index * 4);
3677
+ return r.u16();
3678
+ };
3679
+ const outlines = /* @__PURE__ */ new Map();
3680
+ const contours = (glyph, depth) => {
3681
+ if (glyph >= glyphCount || depth > 6) return [];
3682
+ r.seek(loca.offset + (longLoca ? glyph * 4 : glyph * 2));
3683
+ const start = longLoca ? r.u32() : r.u16() * 2;
3684
+ const end = longLoca ? r.u32() : r.u16() * 2;
3685
+ if (start === end) return [];
3686
+ r.seek(glyf.offset + start);
3687
+ const count = r.i16();
3688
+ r.seek(r.position + 8);
3689
+ if (count < 0) return composite(glyph, depth);
3690
+ const ends = [];
3691
+ for (let i = 0; i < count; i++) ends.push(r.u16());
3692
+ const instructionLength = r.u16();
3693
+ r.seek(r.position + instructionLength);
3694
+ const total = (ends[ends.length - 1] ?? -1) + 1;
3695
+ const flags = [];
3696
+ while (flags.length < total) {
3697
+ const flag = r.u8();
3698
+ flags.push(flag);
3699
+ if (flag & 8) {
3700
+ let repeat = r.u8();
3701
+ while (repeat-- > 0) flags.push(flag);
3702
+ }
3703
+ }
3704
+ const xs = new Array(total);
3705
+ let x = 0;
3706
+ for (let i = 0; i < total; i++) {
3707
+ const flag = flags[i];
3708
+ if (flag & 2) {
3709
+ const dx = r.u8();
3710
+ x += flag & 16 ? dx : -dx;
3711
+ } else if (!(flag & 16)) {
3712
+ x += r.i16();
3713
+ }
3714
+ xs[i] = x;
3715
+ }
3716
+ const ys = new Array(total);
3717
+ let y = 0;
3718
+ for (let i = 0; i < total; i++) {
3719
+ const flag = flags[i];
3720
+ if (flag & 4) {
3721
+ const dy = r.u8();
3722
+ y += flag & 32 ? dy : -dy;
3723
+ } else if (!(flag & 32)) {
3724
+ y += r.i16();
3725
+ }
3726
+ ys[i] = y;
3727
+ }
3728
+ const out = [];
3729
+ let first = 0;
3730
+ for (const last of ends) {
3731
+ out.push(contourToCubics(xs, ys, flags, first, last));
3732
+ first = last + 1;
3733
+ }
3734
+ return out;
3735
+ };
3736
+ function composite(_glyph, depth) {
3737
+ const parts = [];
3738
+ let more = true;
3739
+ while (more) {
3740
+ const flags = r.u16();
3741
+ const glyph = r.u16();
3742
+ const words = (flags & 1) !== 0;
3743
+ const xy = (flags & 2) !== 0;
3744
+ let dx = 0, dy = 0;
3745
+ if (words) {
3746
+ dx = r.i16();
3747
+ dy = r.i16();
3748
+ } else {
3749
+ dx = r.i8();
3750
+ dy = r.i8();
3751
+ }
3752
+ if (!xy) {
3753
+ dx = 0;
3754
+ dy = 0;
3755
+ }
3756
+ let a = 1, b = 0, c = 0, d = 1;
3757
+ const f2 = () => r.i16() / 16384;
3758
+ if (flags & 8) {
3759
+ a = d = f2();
3760
+ } else if (flags & 64) {
3761
+ a = f2();
3762
+ d = f2();
3763
+ } else if (flags & 128) {
3764
+ a = f2();
3765
+ b = f2();
3766
+ c = f2();
3767
+ d = f2();
3768
+ }
3769
+ parts.push({ glyph, m: [a, b, c, d, dx, dy] });
3770
+ more = (flags & 32) !== 0;
3771
+ }
3772
+ const out = [];
3773
+ for (const part of parts) {
3774
+ for (const contour of contours(part.glyph, depth + 1)) {
3775
+ const moved = new Array(contour.length);
3776
+ const [a, b, c, d, e, f] = part.m;
3777
+ for (let i = 0; i < contour.length; i += 2) {
3778
+ moved[i] = a * contour[i] + c * contour[i + 1] + e;
3779
+ moved[i + 1] = b * contour[i] + d * contour[i + 1] + f;
3780
+ }
3781
+ out.push(moved);
3782
+ }
3783
+ }
3784
+ return out;
3785
+ }
3786
+ return {
3787
+ unitsPerEm,
3788
+ ascent,
3789
+ descent,
3790
+ lineGap,
3791
+ glyphFor(code) {
3792
+ return cmap(code);
3793
+ },
3794
+ advance,
3795
+ kern(left, right) {
3796
+ return kerning(left, right);
3797
+ },
3798
+ outline(glyph) {
3799
+ if (outlines.has(glyph)) return outlines.get(glyph);
3800
+ const raw = contours(glyph, 0);
3801
+ const result = raw.length ? curveFree(raw) : null;
3802
+ outlines.set(glyph, result);
3803
+ return result;
3804
+ }
3805
+ };
3806
+ }
3807
+ function contourToCubics(xs, ys, flags, first, last) {
3808
+ const count = last - first + 1;
3809
+ if (count < 2) return [];
3810
+ const at = (i) => first + (i % count + count) % count;
3811
+ const on = (i) => (flags[at(i)] & 1) !== 0;
3812
+ let startIndex = 0;
3813
+ while (startIndex < count && !on(startIndex)) startIndex++;
3814
+ let sx, sy;
3815
+ if (startIndex === count) {
3816
+ sx = (xs[at(0)] + xs[at(count - 1)]) / 2;
3817
+ sy = (ys[at(0)] + ys[at(count - 1)]) / 2;
3818
+ startIndex = 0;
3819
+ } else {
3820
+ sx = xs[at(startIndex)];
3821
+ sy = ys[at(startIndex)];
3822
+ startIndex += 1;
3823
+ }
3824
+ const out = [sx, sy];
3825
+ let cx = sx, cy = sy;
3826
+ let controlX = 0, controlY = 0, hasControl = false;
3827
+ const quad = (qx, qy, ex, ey) => {
3828
+ out.push(cx + (qx - cx) * 2 / 3, cy + (qy - cy) * 2 / 3, ex + (qx - ex) * 2 / 3, ey + (qy - ey) * 2 / 3, ex, ey);
3829
+ cx = ex;
3830
+ cy = ey;
3831
+ };
3832
+ const line = (ex, ey) => {
3833
+ out.push(cx + (ex - cx) / 3, cy + (ey - cy) / 3, cx + (ex - cx) * 2 / 3, cy + (ey - cy) * 2 / 3, ex, ey);
3834
+ cx = ex;
3835
+ cy = ey;
3836
+ };
3837
+ for (let k = 0; k < count; k++) {
3838
+ const i = startIndex + k;
3839
+ const x = xs[at(i)], y = ys[at(i)];
3840
+ if (on(i)) {
3841
+ if (hasControl) {
3842
+ quad(controlX, controlY, x, y);
3843
+ hasControl = false;
3844
+ } else if (x !== cx || y !== cy) {
3845
+ line(x, y);
3846
+ }
3847
+ } else {
3848
+ if (hasControl) quad(controlX, controlY, (controlX + x) / 2, (controlY + y) / 2);
3849
+ controlX = x;
3850
+ controlY = y;
3851
+ hasControl = true;
3852
+ }
3853
+ }
3854
+ if (hasControl) quad(controlX, controlY, sx, sy);
3855
+ else if (cx !== sx || cy !== sy) line(sx, sy);
3856
+ return out;
3857
+ }
3858
+ function parseCmap(r, offset) {
3859
+ r.seek(offset + 2);
3860
+ const count = r.u16();
3861
+ let best = -1, bestScore = -1;
3862
+ for (let i = 0; i < count; i++) {
3863
+ const platform = r.u16();
3864
+ const encoding = r.u16();
3865
+ const sub = r.u32();
3866
+ const score = platform === 3 && encoding === 10 ? 4 : platform === 0 && encoding >= 4 ? 3 : platform === 3 && encoding === 1 ? 2 : platform === 0 ? 1 : 0;
3867
+ if (score > bestScore) {
3868
+ bestScore = score;
3869
+ best = offset + sub;
3870
+ }
3871
+ }
3872
+ if (best < 0) return () => 0;
3873
+ r.seek(best);
3874
+ const format = r.u16();
3875
+ if (format === 12) {
3876
+ r.seek(best + 12);
3877
+ const groups = r.u32();
3878
+ const table = [];
3879
+ for (let i = 0; i < groups; i++) table.push([r.u32(), r.u32(), r.u32()]);
3880
+ return (code) => {
3881
+ let lo = 0, hi = table.length - 1;
3882
+ while (lo <= hi) {
3883
+ const mid = lo + hi >> 1;
3884
+ const [start, end, glyph] = table[mid];
3885
+ if (code < start) hi = mid - 1;
3886
+ else if (code > end) lo = mid + 1;
3887
+ else return glyph + code - start;
3888
+ }
3889
+ return 0;
3890
+ };
3891
+ }
3892
+ if (format === 4) {
3893
+ r.seek(best + 6);
3894
+ const segX2 = r.u16();
3895
+ const segs = segX2 / 2;
3896
+ const endsAt = best + 14;
3897
+ const startsAt = endsAt + segX2 + 2;
3898
+ const deltasAt = startsAt + segX2;
3899
+ const rangesAt = deltasAt + segX2;
3900
+ const map = /* @__PURE__ */ new Map();
3901
+ for (let i = 0; i < segs; i++) {
3902
+ const end = r.seek(endsAt + i * 2).u16();
3903
+ const start = r.seek(startsAt + i * 2).u16();
3904
+ const delta = r.seek(deltasAt + i * 2).i16();
3905
+ const range = r.seek(rangesAt + i * 2).u16();
3906
+ for (let c = start; c <= end && c !== 65535; c++) {
3907
+ let glyph;
3908
+ if (range === 0) glyph = c + delta & 65535;
3909
+ else {
3910
+ const raw = r.seek(rangesAt + i * 2 + range + (c - start) * 2).u16();
3911
+ glyph = raw === 0 ? 0 : raw + delta & 65535;
3912
+ }
3913
+ if (glyph) map.set(c, glyph);
3914
+ }
3915
+ }
3916
+ return (code) => map.get(code) ?? 0;
3917
+ }
3918
+ return () => 0;
3919
+ }
3920
+ function parseKerning(r, gpos) {
3921
+ const lookups = [];
3922
+ try {
3923
+ r.seek(gpos + 6);
3924
+ const featureList = gpos + r.u16();
3925
+ const lookupList = gpos + r.u16();
3926
+ r.seek(featureList);
3927
+ const featureCount = r.u16();
3928
+ const indices = /* @__PURE__ */ new Set();
3929
+ for (let i = 0; i < featureCount; i++) {
3930
+ r.seek(featureList + 2 + i * 6);
3931
+ const tag = r.tag();
3932
+ const offset = r.u16();
3933
+ if (tag !== "kern") continue;
3934
+ r.seek(featureList + offset + 2);
3935
+ const count = r.u16();
3936
+ for (let k = 0; k < count; k++) indices.add(r.u16());
3937
+ }
3938
+ for (const index of [...indices].sort((a, b) => a - b)) {
3939
+ r.seek(lookupList + 2 + index * 2);
3940
+ const lookup = lookupList + r.u16();
3941
+ r.seek(lookup);
3942
+ const lookupType = r.u16();
3943
+ r.u16();
3944
+ const subCount = r.u16();
3945
+ const subs = [];
3946
+ for (let i = 0; i < subCount; i++) subs.push(lookup + r.u16());
3947
+ const tables = [];
3948
+ for (const first of subs) {
3949
+ let sub = first;
3950
+ let type = lookupType;
3951
+ if (type === 9) {
3952
+ r.seek(sub + 2);
3953
+ type = r.u16();
3954
+ sub += r.u32();
3955
+ }
3956
+ if (type === 2) tables.push(readPairs(r, sub));
3957
+ }
3958
+ lookups.push(tables);
3959
+ }
3960
+ } catch {
3961
+ }
3962
+ const cache2 = /* @__PURE__ */ new Map();
3963
+ return (left, right) => {
3964
+ const key = left * 65536 + right;
3965
+ const cached = cache2.get(key);
3966
+ if (cached !== void 0) return cached;
3967
+ let total = 0;
3968
+ for (const tables of lookups) {
3969
+ for (const table of tables) {
3970
+ const value = table(left, right);
3971
+ if (value !== void 0) {
3972
+ total += value;
3973
+ break;
3974
+ }
3975
+ }
3976
+ }
3977
+ cache2.set(key, total);
3978
+ return total;
3979
+ };
3980
+ }
3981
+ function readCoverage(r, offset) {
3982
+ r.seek(offset);
3983
+ const format = r.u16();
3984
+ const out = /* @__PURE__ */ new Set();
3985
+ if (format === 1) {
3986
+ const count = r.u16();
3987
+ for (let i = 0; i < count; i++) out.add(r.u16());
3988
+ } else if (format === 2) {
3989
+ const count = r.u16();
3990
+ for (let i = 0; i < count; i++) {
3991
+ const start = r.u16(), end = r.u16();
3992
+ r.u16();
3993
+ for (let glyph = start; glyph <= end; glyph++) out.add(glyph);
3994
+ }
3995
+ }
3996
+ return out;
3997
+ }
3998
+ function readClasses(r, offset) {
3999
+ r.seek(offset);
4000
+ const format = r.u16();
4001
+ const classes = /* @__PURE__ */ new Map();
4002
+ if (format === 1) {
4003
+ const start = r.u16();
4004
+ const count = r.u16();
4005
+ for (let i = 0; i < count; i++) classes.set(start + i, r.u16());
4006
+ } else if (format === 2) {
4007
+ const count = r.u16();
4008
+ for (let i = 0; i < count; i++) {
4009
+ const start = r.u16(), end = r.u16(), value = r.u16();
4010
+ for (let glyph = start; glyph <= end; glyph++) classes.set(glyph, value);
4011
+ }
4012
+ }
4013
+ return (glyph) => classes.get(glyph) ?? 0;
4014
+ }
4015
+ function valueSize(format) {
4016
+ let count = 0;
4017
+ for (let bit = 0; bit < 8; bit++) if (format & 1 << bit) count++;
4018
+ return count * 2;
4019
+ }
4020
+ function readAdvance(r, format) {
4021
+ let advance = 0;
4022
+ if (format & 1) r.i16();
4023
+ if (format & 2) r.i16();
4024
+ if (format & 4) advance = r.i16();
4025
+ if (format & 8) r.i16();
4026
+ for (let bit = 4; bit < 8; bit++) if (format & 1 << bit) r.u16();
4027
+ return advance;
4028
+ }
4029
+ function readPairs(r, sub) {
4030
+ r.seek(sub);
4031
+ const format = r.u16();
4032
+ const coverageOffset = r.u16();
4033
+ const value1 = r.u16();
4034
+ const value2 = r.u16();
4035
+ const size1 = valueSize(value1);
4036
+ const size2 = valueSize(value2);
4037
+ if (format === 1) {
4038
+ const setCount = r.u16();
4039
+ const offsets = [];
4040
+ for (let i = 0; i < setCount; i++) offsets.push(r.u16());
4041
+ r.seek(sub + coverageOffset);
4042
+ const coverageFormat = r.u16();
4043
+ const glyphs = [];
4044
+ if (coverageFormat === 1) {
4045
+ const count = r.u16();
4046
+ for (let i = 0; i < count; i++) glyphs.push(r.u16());
4047
+ } else if (coverageFormat === 2) {
4048
+ const count = r.u16();
4049
+ for (let i = 0; i < count; i++) {
4050
+ const start = r.u16(), end = r.u16();
4051
+ r.u16();
4052
+ for (let glyph = start; glyph <= end; glyph++) glyphs.push(glyph);
4053
+ }
4054
+ }
4055
+ const sets = /* @__PURE__ */ new Map();
4056
+ for (let i = 0; i < setCount; i++) {
4057
+ r.seek(sub + offsets[i]);
4058
+ const count = r.u16();
4059
+ const pairs = /* @__PURE__ */ new Map();
4060
+ for (let k = 0; k < count; k++) {
4061
+ const second = r.u16();
4062
+ const advance = readAdvance(r, value1);
4063
+ r.seek(r.position + size2);
4064
+ pairs.set(second, advance);
4065
+ }
4066
+ if (glyphs[i] !== void 0) sets.set(glyphs[i], pairs);
4067
+ }
4068
+ return (left, right) => sets.get(left)?.get(right);
4069
+ }
4070
+ if (format === 2) {
4071
+ const class1Offset = r.u16();
4072
+ const class2Offset = r.u16();
4073
+ const class1Count = r.u16();
4074
+ const class2Count = r.u16();
4075
+ const matrix = r.position;
4076
+ const coverage = readCoverage(r, sub + coverageOffset);
4077
+ const class1 = readClasses(r, sub + class1Offset);
4078
+ const class2 = readClasses(r, sub + class2Offset);
4079
+ return (left, right) => {
4080
+ if (!coverage.has(left)) return void 0;
4081
+ const c1 = class1(left), c2 = class2(right);
4082
+ if (c1 >= class1Count || c2 >= class2Count) return void 0;
4083
+ r.seek(matrix + c1 * class2Count * (size1 + size2) + c2 * (size1 + size2));
4084
+ return readAdvance(r, value1);
4085
+ };
4086
+ }
4087
+ return () => void 0;
4088
+ }
4089
+ var FILES = {
4090
+ sans: { "400": "Inter-Regular.ttf", "600": "Inter-SemiBold.ttf", "700": "Inter-Bold.ttf" },
4091
+ serif: { "400": "InstrumentSerif-Regular.ttf", "italic": "InstrumentSerif-Italic.ttf" },
4092
+ mono: { "400": "JetBrainsMono-Regular.ttf" },
4093
+ noto: { "400": "NotoSans-Regular.ttf" }
4094
+ };
4095
+ var fonts = /* @__PURE__ */ new Map();
4096
+ var pending = /* @__PURE__ */ new Map();
4097
+ function fontFor(family, weight = 400, italic = false) {
4098
+ const files = FILES[family];
4099
+ const file = (italic ? files["italic"] : void 0) ?? files[String(weight)] ?? files["400"];
4100
+ const loaded = fonts.get(file);
4101
+ if (loaded) return loaded;
4102
+ let waiting = pending.get(file);
4103
+ if (!waiting) {
4104
+ waiting = loadBinaryAsset(`fonts/${file}`).then((bytes) => {
4105
+ fonts.set(file, parseFont(bytes));
4106
+ pending.delete(file);
4107
+ });
4108
+ pending.set(file, waiting);
4109
+ }
4110
+ throw new Suspend(waiting);
4111
+ }
4112
+ var glyphPaths = /* @__PURE__ */ new WeakMap();
4113
+ function glyphPath(font, glyph, size) {
4114
+ let bySize = glyphPaths.get(font);
4115
+ if (!bySize) glyphPaths.set(font, bySize = /* @__PURE__ */ new Map());
4116
+ let byGlyph = bySize.get(size);
4117
+ if (!byGlyph) bySize.set(size, byGlyph = /* @__PURE__ */ new Map());
4118
+ const cached = byGlyph.get(glyph);
4119
+ if (cached) return cached;
4120
+ const outline = font.outline(glyph);
4121
+ const scale = size / font.unitsPerEm;
4122
+ const path = outline ? outline.contours.map((contour) => {
4123
+ const out = new Float64Array(contour.length);
4124
+ for (let i = 0; i < contour.length; i += 2) {
4125
+ out[i] = contour[i] * scale;
4126
+ out[i + 1] = -contour[i + 1] * scale;
4127
+ }
4128
+ return ring(out, true);
4129
+ }) : [];
4130
+ byGlyph.set(glyph, path);
4131
+ return path;
4132
+ }
4133
+
4134
+ // src/stage/text.ts
4135
+ var TextNode = class extends Node {
4136
+ chars = [];
4137
+ source = "";
4138
+ /** Glyph nodes whose characters match, such as every "x". */
4139
+ find(fragment) {
4140
+ const out = [];
4141
+ const keys = this.chars.map((glyph) => glyph.data["key"]).join("");
4142
+ const needle = fragment.replace(/\s/g, "");
4143
+ for (let at = keys.indexOf(needle); at >= 0; at = keys.indexOf(needle, at + 1)) {
4144
+ out.push(...this.chars.slice(at, at + needle.length));
4145
+ }
4146
+ return out;
4147
+ }
4148
+ };
4149
+ function centered(path) {
4150
+ const b = pathBounds(path);
4151
+ if (!b) return { path, x: 0, y: 0 };
4152
+ const x = b.x + b.width / 2, y = b.y + b.height / 2;
4153
+ return { path: transformPath(path, [1, 0, 0, 1, -x, -y]), x, y };
4154
+ }
4155
+ function text(content, options = {}) {
4156
+ const size = options.size ?? 40;
4157
+ const font = fontFor(options.font ?? "sans", options.weight ?? 400, options.italic ?? false);
4158
+ const scale = size / font.unitsPerEm;
4159
+ const tracking = (options.tracking ?? 0) * size;
4160
+ const leading = (options.leading ?? 1.3) * size;
4161
+ const paint = toPaint(options.color ?? "ink");
4162
+ const source = options.uppercase ? content.toUpperCase() : content;
4163
+ const measureWord = (word) => {
4164
+ const glyphs = [];
4165
+ let x = 0, previous = 0;
4166
+ for (const char of word) {
4167
+ const code = char.codePointAt(0);
4168
+ const glyph = font.glyphFor(code);
4169
+ if (previous) x += font.kern(previous, glyph) * scale;
4170
+ glyphs.push({ code, glyph, x, char });
4171
+ x += font.advance(glyph) * scale + tracking;
4172
+ previous = glyph;
4173
+ }
4174
+ return { glyphs, width: x };
4175
+ };
4176
+ const lines = [];
4177
+ const space = font.advance(font.glyphFor(32)) * scale + tracking;
4178
+ for (const paragraph of source.split("\n")) {
4179
+ let line = [];
4180
+ let width = 0;
4181
+ for (const word of paragraph.split(" ")) {
4182
+ const measured = measureWord(word);
4183
+ const gap = line.length > 0 ? space : 0;
4184
+ if (options.maxWidth !== void 0 && line.length > 0 && width + gap + measured.width > options.maxWidth) {
4185
+ lines.push({ glyphs: line, width });
4186
+ line = [];
4187
+ width = 0;
4188
+ }
4189
+ const offset = width + (line.length > 0 ? space : 0);
4190
+ for (const glyph of measured.glyphs) line.push({ ...glyph, x: glyph.x + offset });
4191
+ width = offset + measured.width;
4192
+ }
4193
+ lines.push({ glyphs: line, width });
4194
+ }
4195
+ const blockWidth = Math.max(0, ...lines.map((line) => line.width));
4196
+ const align = options.align ?? "left";
4197
+ const node = new TextNode();
4198
+ node.source = content;
4199
+ lines.forEach((line, row) => {
4200
+ const start = align === "left" ? 0 : align === "center" ? (blockWidth - line.width) / 2 : blockWidth - line.width;
4201
+ for (const placed of line.glyphs) {
4202
+ const path = glyphPath(font, placed.glyph, size);
4203
+ if (path.length === 0) continue;
4204
+ const shape = centered(path);
4205
+ const leaf = new Node(shape.path).at(start + placed.x + shape.x, row * leading + shape.y);
4206
+ leaf.base.fill = paint;
4207
+ leaf.base.trimEach = true;
4208
+ leaf.data["key"] = placed.char;
4209
+ node.chars.push(leaf);
4210
+ node.children.push(leaf);
4211
+ leaf.parent = node;
4212
+ }
4213
+ });
4214
+ const ascent = font.ascent * scale;
4215
+ const height = (lines.length - 1) * leading;
4216
+ node.base.px = blockWidth / 2;
4217
+ node.base.py = height / 2 - ascent * 0.36;
4218
+ node.data["size"] = size;
4219
+ return node;
4220
+ }
4221
+
4222
+ // src/stage/svg-import.ts
4223
+ function decode2(value) {
4224
+ return value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code))).replace(/&#x([\da-fA-F]+);/g, (_, code) => String.fromCodePoint(parseInt(code, 16))).replace(/&amp;/g, "&");
4225
+ }
4226
+ function parseXml(source) {
4227
+ const root = { name: "#root", attrs: {}, children: [], text: "" };
4228
+ const stack = [root];
4229
+ const token = /<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\?[\s\S]*?\?>|<!DOCTYPE[^>]*>|<\/([\w:.-]+)\s*>|<([\w:.-]+)((?:\s+[\w:.-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>|([^<]+)/g;
4230
+ for (let match = token.exec(source); match; match = token.exec(source)) {
4231
+ const top = stack[stack.length - 1];
4232
+ const [, cdata, closing, opening, attributes, selfClosing, content] = match;
4233
+ if (cdata !== void 0) {
4234
+ top.text += cdata;
4235
+ } else if (closing) {
4236
+ if (stack.length > 1) stack.pop();
4237
+ } else if (opening) {
4238
+ const element = { name: opening.replace(/^.*:/, ""), attrs: {}, children: [], text: "" };
4239
+ for (const attr of (attributes ?? "").matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) {
4240
+ element.attrs[attr[1]] = decode2(attr[2] ?? attr[3] ?? "");
4241
+ }
4242
+ top.children.push(element);
4243
+ if (!selfClosing) stack.push(element);
4244
+ } else if (content) {
4245
+ top.text += decode2(content);
4246
+ }
4247
+ }
4248
+ return root;
4249
+ }
4250
+ function parseTransform(value) {
4251
+ if (!value) return IDENTITY;
4252
+ let m = IDENTITY;
4253
+ for (const match of value.matchAll(/(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g)) {
4254
+ const a = match[2].trim().split(/[\s,]+/).filter(Boolean).map(Number);
4255
+ const name = match[1];
4256
+ if (name === "matrix" && a.length === 6) m = mul(m, a);
4257
+ else if (name === "translate") m = mul(m, [1, 0, 0, 1, a[0] ?? 0, a[1] ?? 0]);
4258
+ else if (name === "scale") m = mul(m, [a[0] ?? 1, 0, 0, a[1] ?? a[0] ?? 1, 0, 0]);
4259
+ else if (name === "rotate") {
4260
+ const r = (a[0] ?? 0) * Math.PI / 180;
4261
+ const c = Math.cos(r), s = Math.sin(r);
4262
+ const cx = a[1] ?? 0, cy = a[2] ?? 0;
4263
+ m = mul(m, [1, 0, 0, 1, cx, cy]);
4264
+ m = mul(m, [c, s, -s, c, 0, 0]);
4265
+ m = mul(m, [1, 0, 0, 1, -cx, -cy]);
4266
+ } else if (name === "skewX") m = mul(m, [1, 0, Math.tan((a[0] ?? 0) * Math.PI / 180), 1, 0, 0]);
4267
+ else if (name === "skewY") m = mul(m, [1, Math.tan((a[0] ?? 0) * Math.PI / 180), 0, 1, 0, 0]);
4268
+ }
4269
+ return m;
4270
+ }
4271
+ var NOT_DRAWN = /* @__PURE__ */ new Set(["defs", "clipPath", "mask", "pattern", "filter", "symbol", "marker", "linearGradient", "radialGradient", "title", "desc", "metadata", "style", "script"]);
4272
+ var SvgNode = class extends Node {
4273
+ byId = /* @__PURE__ */ new Map();
4274
+ pictureWidth = 0;
4275
+ pictureHeight = 0;
4276
+ /** Find an element by its SVG id. */
4277
+ find(id) {
4278
+ const found = this.byId.get(id);
4279
+ if (!found) throw new Error(`The SVG has no element with id ${JSON.stringify(id)}.`);
4280
+ return found;
4281
+ }
4282
+ };
4283
+ function parseCssRules(root) {
4284
+ const rules = /* @__PURE__ */ new Map();
4285
+ const visit = (element) => {
4286
+ if (element.name === "style") {
4287
+ for (const rule of element.text.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
4288
+ const body = parseStyle(rule[2]);
4289
+ for (const selector of rule[1].split(",")) {
4290
+ const key = selector.trim();
4291
+ rules.set(key, { ...rules.get(key), ...body });
4292
+ }
4293
+ }
4294
+ }
4295
+ element.children.forEach(visit);
4296
+ };
4297
+ visit(root);
4298
+ return rules;
4299
+ }
4300
+ function parseStyle(value) {
4301
+ const out = {};
4302
+ if (!value) return out;
4303
+ for (const part of value.split(";")) {
4304
+ const index = part.indexOf(":");
4305
+ if (index > 0) out[part.slice(0, index).trim()] = part.slice(index + 1).trim();
4306
+ }
4307
+ return out;
4308
+ }
4309
+ function safeColor(value) {
4310
+ if (!value || value === "none" || value === "transparent") return null;
4311
+ try {
4312
+ return parseColor(value);
4313
+ } catch {
4314
+ return null;
4315
+ }
4316
+ }
4317
+ function splitIntoGlyphs(path) {
4318
+ const items = path.map((r) => {
4319
+ const b = pathBounds([r]);
4320
+ return { ring: r, b, area: b.width * b.height, owner: -1 };
4321
+ });
4322
+ const order = items.map((_, i) => i).sort((a, b) => items[b].area - items[a].area);
4323
+ for (let k = 0; k < order.length; k++) {
4324
+ const inner = items[order[k]];
4325
+ for (let j = k - 1; j >= 0; j--) {
4326
+ const outer = items[order[j]];
4327
+ if (outer.owner !== -1) continue;
4328
+ const inside = inner.b.x >= outer.b.x - 0.01 && inner.b.y >= outer.b.y - 0.01 && inner.b.x + inner.b.width <= outer.b.x + outer.b.width + 0.01 && inner.b.y + inner.b.height <= outer.b.y + outer.b.height + 0.01;
4329
+ if (inside) {
4330
+ inner.owner = order[j];
4331
+ break;
4332
+ }
4333
+ }
4334
+ }
4335
+ const glyphs = [];
4336
+ const ownerToGlyph = /* @__PURE__ */ new Map();
4337
+ items.forEach((item, i) => {
4338
+ if (item.owner !== -1) return;
4339
+ const glyph = { x: item.b.x, rings: [item.ring] };
4340
+ ownerToGlyph.set(i, glyph);
4341
+ glyphs.push(glyph);
4342
+ });
4343
+ items.forEach((item) => {
4344
+ if (item.owner !== -1) ownerToGlyph.get(item.owner)?.rings.push(item.ring);
4345
+ });
4346
+ return glyphs.sort((a, b) => a.x - b.x).map((glyph) => glyph.rings);
4347
+ }
4348
+ function fromSvg(source, options = {}) {
4349
+ const root = parseXml(source);
4350
+ const svg = root.children.find((child) => child.name === "svg");
4351
+ if (!svg) throw new Error("fromSvg needs markup with an <svg> element.");
4352
+ const rules = parseCssRules(svg);
4353
+ const defs = /* @__PURE__ */ new Map();
4354
+ const index = (element) => {
4355
+ if (element.attrs["id"]) defs.set(element.attrs["id"], element);
4356
+ element.children.forEach(index);
4357
+ };
4358
+ index(svg);
4359
+ const box = (svg.attrs["viewBox"] ?? "").trim().split(/[\s,]+/).map(Number);
4360
+ const declaredW = parseFloat(svg.attrs["width"] ?? ""), declaredH = parseFloat(svg.attrs["height"] ?? "");
4361
+ const viewW = box.length === 4 && box[2] ? box[2] : declaredW || 300;
4362
+ const viewH = box.length === 4 && box[3] ? box[3] : declaredH || 150;
4363
+ const viewX = box.length === 4 ? box[0] : 0, viewY = box.length === 4 ? box[1] : 0;
4364
+ const naturalW = Number.isFinite(declaredW) && declaredW > 0 ? declaredW : viewW;
4365
+ const naturalH = Number.isFinite(declaredH) && declaredH > 0 ? declaredH : viewH;
4366
+ let scale = 1;
4367
+ if (options.width !== void 0 || options.height !== void 0) {
4368
+ const sx = options.width !== void 0 ? options.width / viewW : Infinity;
4369
+ const sy = options.height !== void 0 ? options.height / viewH : Infinity;
4370
+ scale = Math.min(sx, sy);
4371
+ } else {
4372
+ scale = Math.min(naturalW / viewW, naturalH / viewH);
4373
+ }
4374
+ const center = options.center ?? true;
4375
+ const offsetX = center ? -(viewX + viewW / 2) * scale : -viewX * scale;
4376
+ const offsetY = center ? -(viewY + viewH / 2) * scale : -viewY * scale;
4377
+ const base = [scale, 0, 0, scale, offsetX, offsetY];
4378
+ const out = new SvgNode();
4379
+ out.pictureWidth = viewW * scale;
4380
+ out.pictureHeight = viewH * scale;
4381
+ const splitting = options.splitGlyphs ?? true;
4382
+ const keepBackground = options.background ?? false;
4383
+ let firstShape = true;
4384
+ const gradientOf = (id, m, path) => {
4385
+ const element = defs.get(id);
4386
+ if (!element) return null;
4387
+ if (element.name === "pattern") {
4388
+ const inner = element.children.find((child) => child.name === "linearGradient");
4389
+ if (inner) return linear(inner, m, path, true);
4390
+ const fill = element.children.find((child) => child.attrs["fill"]?.startsWith("url(#"));
4391
+ const nested = fill?.attrs["fill"]?.match(/url\(#([^)]+)\)/)?.[1];
4392
+ return nested ? gradientOf(nested, m, path) : null;
4393
+ }
4394
+ if (element.name === "linearGradient") return linear(element, m, path, element.attrs["gradientUnits"] !== "userSpaceOnUse");
4395
+ if (element.name === "radialGradient") {
4396
+ const stops = stopsOf(element);
4397
+ return stops.length ? stops[stops.length - 1][1] : null;
4398
+ }
4399
+ return null;
4400
+ };
4401
+ const stopsOf = (element) => {
4402
+ const inherited = element.attrs["href"] ?? element.attrs["xlink:href"];
4403
+ const source2 = element.children.some((child) => child.name === "stop") || !inherited ? element : defs.get(inherited.replace(/^#/, "")) ?? element;
4404
+ return source2.children.filter((child) => child.name === "stop").map((stop) => {
4405
+ const style2 = parseStyle(stop.attrs["style"]);
4406
+ const offsetRaw = stop.attrs["offset"] ?? "0";
4407
+ const offset = offsetRaw.endsWith("%") ? parseFloat(offsetRaw) / 100 : parseFloat(offsetRaw);
4408
+ const color = safeColor(style2["stop-color"] ?? stop.attrs["stop-color"] ?? "#000000") ?? [0, 0, 0, 1];
4409
+ const alpha = parseFloat(style2["stop-opacity"] ?? stop.attrs["stop-opacity"] ?? "1");
4410
+ return [offset, [color[0], color[1], color[2], color[3] * alpha]];
4411
+ });
4412
+ };
4413
+ const linear = (element, m, path, objectBox) => {
4414
+ const stops = stopsOf(element);
4415
+ if (stops.length === 0) return null;
4416
+ const coordinate = (value, fallback) => {
4417
+ if (value === void 0) return fallback;
4418
+ return value.endsWith("%") ? parseFloat(value) / 100 : parseFloat(value);
4419
+ };
4420
+ const x1 = coordinate(element.attrs["x1"], 0), y1 = coordinate(element.attrs["y1"], 0);
4421
+ const x2 = coordinate(element.attrs["x2"], 1), y2 = coordinate(element.attrs["y2"], 0);
4422
+ let from, to;
4423
+ if (objectBox) {
4424
+ const b = pathBounds(path) ?? { x: 0, y: 0, width: 1, height: 1 };
4425
+ from = [b.x + x1 * b.width, b.y + y1 * b.height];
4426
+ to = [b.x + x2 * b.width, b.y + y2 * b.height];
4427
+ } else {
4428
+ from = apply(m, x1, y1);
4429
+ to = apply(m, x2, y2);
4430
+ }
4431
+ return { type: "linear", from, to, stops };
4432
+ };
4433
+ const shapePath = (element) => {
4434
+ const a = element.attrs;
4435
+ const num = (key, fallback = 0) => {
4436
+ const value = parseFloat(a[key] ?? "");
4437
+ return Number.isFinite(value) ? value : fallback;
4438
+ };
4439
+ switch (element.name) {
4440
+ case "path":
4441
+ return a["d"] ? parseSvgPath(a["d"]) : null;
4442
+ case "rect": {
4443
+ const w = num("width"), h = num("height");
4444
+ if (w <= 0 || h <= 0) return null;
4445
+ return rectPath(num("x"), num("y"), w, h, num("rx", num("ry")));
4446
+ }
4447
+ case "circle":
4448
+ return num("r") > 0 ? arcPath(num("cx"), num("cy"), num("r"), num("r"), 0, Math.PI * 2) : null;
4449
+ case "ellipse":
4450
+ return num("rx") > 0 && num("ry") > 0 ? arcPath(num("cx"), num("cy"), num("rx"), num("ry"), 0, Math.PI * 2) : null;
4451
+ case "line":
4452
+ return polyPath([[num("x1"), num("y1")], [num("x2"), num("y2")]]);
4453
+ case "polyline":
4454
+ case "polygon": {
4455
+ const values = (a["points"] ?? "").trim().split(/[\s,]+/).filter(Boolean).map(Number);
4456
+ const points = [];
4457
+ for (let i = 0; i + 1 < values.length; i += 2) points.push([values[i], values[i + 1]]);
4458
+ return points.length >= 2 ? polyPath(points, element.name === "polygon") : null;
4459
+ }
4460
+ default:
4461
+ return null;
4462
+ }
4463
+ };
4464
+ const styleOf = (element, inherited) => {
4465
+ const a = element.attrs;
4466
+ const cls = (a["class"] ?? "").split(/\s+/).filter(Boolean);
4467
+ const merged = { ...rules.get(element.name) };
4468
+ for (const name of cls) Object.assign(merged, rules.get(`.${name}`));
4469
+ if (a["id"]) Object.assign(merged, rules.get(`#${a["id"]}`));
4470
+ const pick = (key) => parseStyle(a["style"])[key] ?? a[key] ?? merged[key];
4471
+ const style2 = { ...inherited };
4472
+ const color = pick("color");
4473
+ if (color) style2.color = color;
4474
+ const fill = pick("fill");
4475
+ if (fill) style2.fill = fill === "currentColor" ? style2.color : fill;
4476
+ const stroke = pick("stroke");
4477
+ if (stroke) style2.stroke = stroke === "currentColor" ? style2.color : stroke;
4478
+ const width = pick("stroke-width");
4479
+ if (width !== void 0) style2.strokeWidth = parseFloat(width) || 0;
4480
+ const fo = pick("fill-opacity");
4481
+ if (fo !== void 0) style2.fillOpacity = parseFloat(fo);
4482
+ const so = pick("stroke-opacity");
4483
+ if (so !== void 0) style2.strokeOpacity = parseFloat(so);
4484
+ const cap = pick("stroke-linecap");
4485
+ if (cap === "round" || cap === "butt" || cap === "square") style2.cap = cap;
4486
+ const join3 = pick("stroke-linejoin");
4487
+ if (join3 === "round" || join3 === "miter" || join3 === "bevel") style2.join = join3;
4488
+ const dash = pick("stroke-dasharray");
4489
+ if (dash !== void 0) style2.dash = dash === "none" ? null : dash.trim().split(/[\s,]+/).map(Number);
4490
+ const dashOffset = pick("stroke-dashoffset");
4491
+ if (dashOffset !== void 0) style2.dashOffset = parseFloat(dashOffset) || 0;
4492
+ const size = pick("font-size");
4493
+ if (size !== void 0) style2.fontSize = parseFloat(size) || style2.fontSize;
4494
+ const anchor = pick("text-anchor");
4495
+ if (anchor) style2.anchor = anchor;
4496
+ return { style: style2, opacity: parseFloat(pick("opacity") ?? "1") };
4497
+ };
4498
+ const leafFrom = (path, m, element, style2) => {
4499
+ const world = transformPath(path, m);
4500
+ const scaleOf = matScale(m);
4501
+ const url = (value) => value?.match(/^url\(#([^)]+)\)/)?.[1];
4502
+ const fillId = url(style2.fill), strokeId = url(style2.stroke);
4503
+ const fill = fillId ? gradientOf(fillId, m, world) : safeColor(style2.fill);
4504
+ const stroke = strokeId ? gradientOf(strokeId, m, world) : safeColor(style2.stroke);
4505
+ const visibleFill = fill && style2.fillOpacity > 0 && !(Array.isArray(fill) && fill[3] === 0);
4506
+ const visibleStroke = stroke && style2.strokeOpacity > 0 && style2.strokeWidth > 0 && !(Array.isArray(stroke) && stroke[3] === 0);
4507
+ if (!visibleFill && !visibleStroke) return [];
4508
+ const clippedStroke = element.attrs["clip-path"] ? 0.5 : 1;
4509
+ const pieces = splitting && visibleFill && !visibleStroke && world.length > 1 ? splitIntoGlyphs(world) : [world];
4510
+ return pieces.map((piece) => {
4511
+ const b = pathBounds(piece) ?? { x: 0, y: 0, width: 0, height: 0 };
4512
+ const cx = b.x + b.width / 2, cy = b.y + b.height / 2;
4513
+ const leaf = new Node(transformPath(piece, [1, 0, 0, 1, -cx, -cy])).at(cx, cy);
4514
+ if (visibleFill) {
4515
+ leaf.base.fill = shiftPaint(fill, -cx, -cy);
4516
+ leaf.base.fillOpacity = style2.fillOpacity;
4517
+ }
4518
+ if (visibleStroke) {
4519
+ leaf.base.stroke = shiftPaint(stroke, -cx, -cy);
4520
+ leaf.base.strokeWidth = style2.strokeWidth * scaleOf * clippedStroke;
4521
+ leaf.base.strokeOpacity = style2.strokeOpacity;
4522
+ leaf.base.cap = style2.cap;
4523
+ leaf.base.join = style2.join;
4524
+ if (style2.dash) leaf.base.dash = style2.dash.map((value) => value * scaleOf);
4525
+ leaf.base.dashOffset = style2.dashOffset * scaleOf;
4526
+ }
4527
+ leaf.base.trimEach = true;
4528
+ return leaf;
4529
+ });
4530
+ };
4531
+ const walk = (element, parent, inherited, parentMatrix) => {
4532
+ if (NOT_DRAWN.has(element.name)) return;
4533
+ if (element.attrs["filter"]) return;
4534
+ const { style: style2, opacity } = styleOf(element, inherited);
4535
+ const m = mul(parentMatrix, parseTransform(element.attrs["transform"]));
4536
+ const register = (node) => {
4537
+ if (element.attrs["id"]) out.byId.set(element.attrs["id"], node);
4538
+ };
4539
+ if (element.name === "g" || element.name === "svg" || element.name === "a") {
4540
+ const group2 = new Node();
4541
+ if (opacity < 1) group2.base.opacity = opacity;
4542
+ register(group2);
4543
+ parent.add(group2);
4544
+ for (const child of element.children) walk(child, group2, style2, m);
4545
+ return;
4546
+ }
4547
+ if (element.name === "use") {
4548
+ const href = (element.attrs["href"] ?? element.attrs["xlink:href"] ?? "").replace(/^#/, "");
4549
+ const referenced = defs.get(href);
4550
+ if (!referenced) return;
4551
+ const placed = mul(m, [1, 0, 0, 1, parseFloat(element.attrs["x"] ?? "0") || 0, parseFloat(element.attrs["y"] ?? "0") || 0]);
4552
+ const group2 = new Node();
4553
+ if (opacity < 1) group2.base.opacity = opacity;
4554
+ parent.add(group2);
4555
+ if (referenced.name === "symbol") for (const child of referenced.children) walk(child, group2, style2, placed);
4556
+ else walk(referenced, group2, style2, placed);
4557
+ return;
4558
+ }
4559
+ if (element.name === "image") {
4560
+ const href = element.attrs["href"] ?? element.attrs["xlink:href"];
4561
+ if (!href) return;
4562
+ const width = parseFloat(element.attrs["width"] ?? "0"), height = parseFloat(element.attrs["height"] ?? "0");
4563
+ const [x, y] = apply(m, parseFloat(element.attrs["x"] ?? "0") || 0, parseFloat(element.attrs["y"] ?? "0") || 0);
4564
+ const unit = matScale(m);
4565
+ const image = { src: href, width, height };
4566
+ const node = new Node().at(x, y);
4567
+ node.base.image = image;
4568
+ node.base.sx = unit;
4569
+ node.base.sy = unit;
4570
+ if (opacity < 1) node.base.opacity = opacity;
4571
+ register(node);
4572
+ parent.add(node);
4573
+ return;
4574
+ }
4575
+ if (element.name === "text") {
4576
+ const body = (element.text + element.children.map((child) => child.text).join("")).trim();
4577
+ if (!body) return;
4578
+ const color = safeColor(style2.fill) ?? [0, 0, 0, 1];
4579
+ const size = style2.fontSize * matScale(m);
4580
+ const label = text(body, { size, color });
4581
+ const [x, y] = apply(m, parseFloat(element.attrs["x"] ?? "0") || 0, parseFloat(element.attrs["y"] ?? "0") || 0);
4582
+ const half = label.get("px");
4583
+ label.at(style2.anchor === "middle" ? x : style2.anchor === "end" ? x - half : x + half, y - size * 0.34);
4584
+ if (opacity < 1) label.base.opacity = opacity;
4585
+ register(label);
4586
+ parent.add(label);
4587
+ return;
4588
+ }
4589
+ const path = shapePath(element);
4590
+ if (!path || path.length === 0) return;
4591
+ const isBackground = firstShape && element.name === "rect" && !keepBackground && parseFloat(element.attrs["width"] ?? "0") >= viewW - 0.5 && parseFloat(element.attrs["height"] ?? "0") >= viewH - 0.5;
4592
+ firstShape = false;
4593
+ if (isBackground) return;
4594
+ const leaves = leafFrom(path, m, element, style2);
4595
+ if (leaves.length === 0) return;
4596
+ if (leaves.length === 1) {
4597
+ if (opacity < 1) leaves[0].base.opacity = opacity;
4598
+ register(leaves[0]);
4599
+ parent.add(leaves[0]);
4600
+ return;
4601
+ }
4602
+ const group = new Node();
4603
+ if (opacity < 1) group.base.opacity = opacity;
4604
+ group.add(...leaves);
4605
+ register(group);
4606
+ parent.add(group);
4607
+ };
4608
+ const initial = {
4609
+ fill: "#000000",
4610
+ stroke: null,
4611
+ strokeWidth: 1,
4612
+ fillOpacity: 1,
4613
+ strokeOpacity: 1,
4614
+ cap: "butt",
4615
+ join: "miter",
4616
+ dash: null,
4617
+ dashOffset: 0,
4618
+ color: "#000000",
4619
+ fontSize: 16,
4620
+ anchor: "start"
4621
+ };
4622
+ const { style } = styleOf(svg, initial);
4623
+ for (const child of svg.children) walk(child, out, style, base);
4624
+ return out;
4625
+ }
4626
+ function shiftPaint(paint, dx, dy) {
4627
+ if (Array.isArray(paint)) return paint;
4628
+ const gradient = paint;
4629
+ if (gradient.type === "linear") {
4630
+ return { ...gradient, from: [gradient.from[0] + dx, gradient.from[1] + dy], to: [gradient.to[0] + dx, gradient.to[1] + dy] };
4631
+ }
4632
+ if (gradient.type === "radial") return { ...gradient, center: [gradient.center[0] + dx, gradient.center[1] + dy] };
4633
+ return gradient;
4634
+ }
4635
+
4636
+ // src/stage/objects/from-component.ts
4637
+ async function fromComponent(element, options) {
4638
+ const { width, height, theme, canvas, scale, ...rest } = options;
4639
+ const svg = await renderToSvg(element, width, height, { theme: theme ?? "dark", background: canvas, watermark: false });
4640
+ return fromSvg(svg, { ...rest, width: width * (scale ?? 1), height: height * (scale ?? 1) });
4641
+ }
4642
+
4643
+ // src/stage/export.ts
4644
+ var QUALITY = {
4645
+ draft: { crf: 26, vp9Crf: 40, preset: "veryfast", motionBlur: 1 },
4646
+ standard: { crf: 18, vp9Crf: 31, preset: "medium", motionBlur: 1 },
4647
+ high: { crf: 15, vp9Crf: 24, preset: "slow", motionBlur: 4 },
4648
+ master: { crf: 11, vp9Crf: 15, preset: "slow", motionBlur: 8 }
4649
+ };
4650
+ var DEFAULT_GIF_WIDTH = 960;
4651
+ var DEFAULT_GIF_FPS = 25;
4652
+ var GIF_PALETTE_FRAMES = 12;
4653
+ var GIF_PALETTE_PIXELS = 1 << 19;
4654
+ var MAX_GIF_DELAY = 655350;
4655
+ async function resolveFilm(film, overrides) {
4656
+ return isFilm(film) ? film.compile(overrides) : film;
4657
+ }
4658
+ function frameAt(film, time) {
4659
+ try {
4660
+ return film.frame(time);
4661
+ } catch (error) {
4662
+ if (!isSuspend(error)) throw error;
4663
+ return error.promise.then(() => frameAt(film, time));
4664
+ }
4665
+ }
4666
+ function backgroundBytes(color) {
4667
+ if (!color) return [0, 0, 0];
4668
+ const rgba = parseColor(color);
4669
+ return [rgba[0], rgba[1], rgba[2]];
4670
+ }
4671
+ function outputSize(film, requested) {
4672
+ const width = requested ?? film.width;
4673
+ if (!Number.isInteger(width) || width < 2) throw new Error(`Output width must be an integer of at least 2, but received ${width}.`);
4674
+ return { width, height: Math.max(1, Math.round(width * film.height / film.width)) };
4675
+ }
4676
+ function evenSize(film, requested) {
4677
+ const { width, height } = outputSize(film, requested);
4678
+ return { width: width + width % 2, height: Math.max(2, height + height % 2) };
4679
+ }
4680
+ function timeRange(film, options) {
4681
+ const from = Math.max(0, options.from ?? 0);
4682
+ const to = Math.min(film.duration, options.to ?? film.duration);
4683
+ if (!Number.isFinite(from) || !Number.isFinite(to) || to <= from) {
4684
+ throw new Error(`The render range ${from}:${to} is empty. The film is ${film.duration.toFixed(2)} seconds long.`);
4685
+ }
4686
+ return { from, to };
4687
+ }
4688
+ function planRender(width, height, motionBlur, options = {}) {
4689
+ const frameBytes = width * height * 4;
4690
+ const budget = options.memoryBudget ?? Math.min(2 * 1024 ** 3, (0, import_node_os2.totalmem)() * 0.25);
4691
+ const requested = Math.max(1, Math.floor(options.workers ?? defaultPoolSize()));
4692
+ const perWorker = frameBytes * (motionBlur > 1 ? motionBlur + 4 : 3);
4693
+ const workers = Math.max(1, Math.min(requested, Math.floor(budget * 0.75 / perWorker)));
4694
+ const extra = Math.floor(budget * 0.25 / frameBytes);
4695
+ return { workers, readAhead: Math.max(workers + 1, Math.min(workers * 2, workers + extra)) };
4696
+ }
4697
+ function frameStream(film, pool, timeOf, size, count, readAhead, subframes = 1, shutterSpan = 0) {
4698
+ const inFlight = /* @__PURE__ */ new Map();
4699
+ const submit = async (index) => {
4700
+ const base = timeOf(index);
4701
+ const frames = [];
4702
+ for (let sub = 0; sub < subframes; sub++) {
4703
+ frames.push(await frameAt(film, base + sub / subframes * shutterSpan));
4704
+ }
4705
+ return pool.run(framesToJob(frames, size.width, backgroundBytes, size.height));
4706
+ };
4707
+ return async (index) => {
4708
+ for (let ahead = index; ahead < Math.min(count, index + readAhead); ahead++) {
4709
+ if (inFlight.has(ahead)) continue;
4710
+ const job = submit(ahead);
4711
+ job.catch(() => {
4712
+ });
4713
+ inFlight.set(ahead, job);
4714
+ }
4715
+ const pixels = await inFlight.get(index);
4716
+ inFlight.delete(index);
4717
+ return pixels;
4718
+ };
4719
+ }
4720
+ async function renderFilmVideo(film, outputPath, options = {}) {
4721
+ const compiled = await resolveFilm(film, options);
4722
+ const quality = QUALITY[options.quality ?? "standard"];
4723
+ if (!quality) throw new Error(`Unknown quality: ${options.quality}. Use draft, standard, high, or master.`);
4724
+ const size = evenSize(compiled, options.width);
4725
+ const motionBlur = Math.max(1, Math.floor(options.motionBlur ?? quality.motionBlur));
4726
+ const shutter = options.shutter ?? 0.5;
4727
+ const fps = compiled.fps;
4728
+ const codec = options.codec ?? "h264";
4729
+ const { from, to } = timeRange(compiled, options);
4730
+ const plan = planRender(size.width, size.height, motionBlur, options);
4731
+ const pool = new RasterPool(plan.workers);
4732
+ try {
4733
+ const count = Math.max(1, Math.round((to - from) * fps));
4734
+ const next = frameStream(compiled, pool, (index) => from + index / fps, size, count, plan.readAhead, motionBlur, shutter / fps);
4735
+ const output = await renderRgbaVideo((info) => next(info.index), {
4736
+ width: size.width,
4737
+ height: size.height,
4738
+ fps,
4739
+ duration: (to - from) * 1e3,
4740
+ outputPath,
4741
+ codec,
4742
+ crf: codec === "vp9" ? quality.vp9Crf : quality.crf,
4743
+ preset: quality.preset,
4744
+ // Flat color and fine lines keep their edges better with this tuning.
4745
+ tune: codec === "h264" ? "animation" : void 0,
4746
+ threads: options.threads ?? 6,
4747
+ audioPath: options.audioPath,
4748
+ audioOffset: from > 0 ? from : void 0,
4749
+ ffmpegPath: options.ffmpegPath,
4750
+ signal: options.signal,
4751
+ onProgress: options.onProgress
4752
+ });
4753
+ return { ...output, title: compiled.title, workers: pool.size, motionBlur, codec };
4754
+ } finally {
4755
+ await pool.close();
4756
+ }
4757
+ }
4758
+ var gifApi = typeof gifenc.GIFEncoder === "function" ? gifenc : gifenc.default;
4759
+ function changedRegion(previous, current, width, height) {
4760
+ let minX = width, minY = height, maxX = -1, maxY = -1;
4761
+ for (let y = 0; y < height; y++) {
4762
+ const row = y * width * 4;
4763
+ for (let x = 0; x < width; x++) {
4764
+ const o = row + x * 4;
4765
+ if (previous[o] !== current[o] || previous[o + 1] !== current[o + 1] || previous[o + 2] !== current[o + 2]) {
4766
+ if (x < minX) minX = x;
4767
+ if (x > maxX) maxX = x;
4768
+ if (y < minY) minY = y;
4769
+ maxY = y;
4770
+ }
4771
+ }
4772
+ }
4773
+ return maxX < 0 ? null : { x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1 };
4774
+ }
4775
+ function cropRegion(pixels, canvasWidth, region) {
4776
+ const out = new Uint8Array(region.width * region.height * 4);
4777
+ for (let y = 0; y < region.height; y++) {
4778
+ const start = ((region.y + y) * canvasWidth + region.x) * 4;
4779
+ out.set(pixels.subarray(start, start + region.width * 4), y * region.width * 4);
4780
+ }
4781
+ return out;
4782
+ }
4783
+ async function renderFilmGif(film, outputPath, options = {}) {
4784
+ const compiled = await resolveFilm(film, { ...options, fps: void 0 });
4785
+ const size = outputSize(compiled, options.width ?? Math.min(DEFAULT_GIF_WIDTH, compiled.width));
4786
+ const fps = Math.min(options.fps ?? DEFAULT_GIF_FPS, 50);
4787
+ const { from, to } = timeRange(compiled, options);
4788
+ const count = Math.max(1, Math.round((to - from) * fps));
4789
+ const delay = 1e3 / fps;
4790
+ const plan = planRender(size.width, size.height, 1, options);
4791
+ const pool = new RasterPool(plan.workers);
4792
+ try {
4793
+ const sampleCount = Math.min(count, GIF_PALETTE_FRAMES);
4794
+ const samples = await Promise.all(Array.from({ length: sampleCount }, async (_, i) => {
4795
+ const index = Math.floor((i + 0.5) * count / sampleCount);
4796
+ return pool.run(framesToJob([await frameAt(compiled, from + index / fps)], size.width, backgroundBytes, size.height));
4797
+ }));
4798
+ const perFrame = Math.max(1, Math.floor(GIF_PALETTE_PIXELS / sampleCount));
4799
+ const combined = new Uint8Array(perFrame * sampleCount * 4);
4800
+ samples.forEach((pixels, i) => {
4801
+ const total = pixels.length / 4;
4802
+ for (let k = 0; k < perFrame; k++) {
4803
+ const at = Math.floor((k + 0.5) * total / perFrame) * 4;
4804
+ combined.set(pixels.subarray(at, at + 4), (i * perFrame + k) * 4);
4805
+ }
4806
+ });
4807
+ const palette = gifApi.quantize(combined, 256, { format: "rgb565" });
4808
+ const gif = gifApi.GIFEncoder();
4809
+ const next = frameStream(compiled, pool, (index) => from + index / fps, size, count, plan.readAhead);
4810
+ const repeat = options.loop === false ? -1 : 0;
4811
+ let previous = null;
4812
+ let pending2 = null;
4813
+ const flush = (first) => {
4814
+ if (!pending2) return;
4815
+ let remaining = pending2.delay;
4816
+ let includePalette = first;
4817
+ do {
4818
+ const span = Math.min(MAX_GIF_DELAY, remaining);
4819
+ const start = gif.bytesView().length;
4820
+ gif.writeFrame(pending2.index, pending2.region.width, pending2.region.height, {
4821
+ ...includePalette ? { palette } : {},
4822
+ delay: Math.max(20, span),
4823
+ repeat,
4824
+ dispose: 1
4825
+ });
4826
+ if (pending2.region.x !== 0 || pending2.region.y !== 0) {
4827
+ const bytes = gif.bytesView();
4828
+ const descriptor = start + 8;
4829
+ if (bytes[descriptor] !== 44) throw new Error("The GIF encoder wrote an unexpected frame layout.");
4830
+ bytes[descriptor + 1] = pending2.region.x & 255;
4831
+ bytes[descriptor + 2] = pending2.region.x >> 8 & 255;
4832
+ bytes[descriptor + 3] = pending2.region.y & 255;
4833
+ bytes[descriptor + 4] = pending2.region.y >> 8 & 255;
4834
+ }
4835
+ includePalette = false;
4836
+ remaining -= span;
4837
+ } while (remaining > 0);
4838
+ };
4839
+ let wroteAny = false;
4840
+ for (let i = 0; i < count; i++) {
4841
+ options.signal?.throwIfAborted();
4842
+ const pixels = await next(i);
4843
+ const region = previous ? changedRegion(previous, pixels, size.width, size.height) : { x: 0, y: 0, width: size.width, height: size.height };
4844
+ if (!region) {
4845
+ if (pending2) pending2.delay += delay;
4846
+ } else {
4847
+ flush(!wroteAny);
4848
+ if (pending2) wroteAny = true;
4849
+ const cropped = region.width === size.width && region.height === size.height ? pixels : cropRegion(pixels, size.width, region);
4850
+ pending2 = { index: gifApi.applyPalette(cropped, palette, "rgb565"), region, delay };
4851
+ previous = pixels;
4852
+ }
4853
+ await options.onProgress?.({ index: i, count, time: i * delay, duration: count * delay, progress: i / count, fps });
4854
+ }
4855
+ flush(!wroteAny);
4856
+ gif.finish();
4857
+ const path = (0, import_node_path.resolve)(outputPath);
4858
+ await (0, import_promises3.mkdir)((0, import_node_path.dirname)(path), { recursive: true });
4859
+ await (0, import_promises3.writeFile)(path, gif.bytesView());
4860
+ return { width: size.width, height: size.height, frameCount: count, duration: count * delay, fps, bytes: (await (0, import_promises3.stat)(path)).size, outputPath: path, title: compiled.title };
4861
+ } finally {
4862
+ await pool.close();
4863
+ }
4864
+ }
4865
+ async function renderFilmFrame(film, time, outputPath, options = {}) {
4866
+ const compiled = await resolveFilm(film, options);
4867
+ const { width, height } = outputSize(compiled, options.width);
4868
+ const pool = new RasterPool(1);
4869
+ try {
4870
+ const frame = await frameAt(compiled, time);
4871
+ const pixels = await pool.run(framesToJob([frame], width, backgroundBytes, height));
4872
+ const path = (0, import_node_path.resolve)(outputPath);
4873
+ await (0, import_promises3.mkdir)((0, import_node_path.dirname)(path), { recursive: true });
4874
+ await (0, import_promises3.writeFile)(path, encodePng({ width, height, data: pixels, depth: 8, channels: 4 }));
4875
+ return { width, height, outputPath: path };
4876
+ } finally {
4877
+ await pool.close();
4878
+ }
4879
+ }
4880
+ async function renderFilmFrames(film, times, outputPrefix, options = {}) {
4881
+ const compiled = await resolveFilm(film, options);
4882
+ const { width, height } = outputSize(compiled, options.width);
4883
+ const plan = planRender(width, height, 1, options);
4884
+ const pool = new RasterPool(plan.workers);
4885
+ try {
4886
+ await (0, import_promises3.mkdir)((0, import_node_path.dirname)((0, import_node_path.resolve)(outputPrefix)), { recursive: true });
4887
+ const frames = [];
4888
+ for (const time of times) frames.push(await frameAt(compiled, time));
4889
+ return await Promise.all(frames.map(async (frame, index) => {
4890
+ const pixels = await pool.run(framesToJob([frame], width, backgroundBytes, height));
4891
+ const path = (0, import_node_path.resolve)(`${outputPrefix}${String(index).padStart(3, "0")}.png`);
4892
+ await (0, import_promises3.writeFile)(path, encodePng({ width, height, data: pixels, depth: 8, channels: 4 }));
4893
+ return path;
4894
+ }));
4895
+ } finally {
4896
+ await pool.close();
4897
+ }
4898
+ }
4899
+ async function renderFilmSvg(film, time, outputPath, options = {}) {
4900
+ const compiled = await resolveFilm(film, options);
4901
+ const path = (0, import_node_path.resolve)(outputPath);
4902
+ await (0, import_promises3.mkdir)((0, import_node_path.dirname)(path), { recursive: true });
4903
+ const frame = await frameAt(compiled, time);
4904
+ const scale = (options.width ?? compiled.width) / compiled.width;
4905
+ await (0, import_promises3.writeFile)(path, frameToSvg(frame, { scale }));
4906
+ return { width: Math.round(compiled.width * scale), height: Math.round(compiled.height * scale), outputPath: path };
4907
+ }
4908
+ async function posterTime(film) {
4909
+ if (film.posterTime !== void 0) return Math.max(0, Math.min(film.duration, film.posterTime));
4910
+ const active = (t) => film.clips.some((clip) => clip.t0 < t && t < clip.t1);
4911
+ const nudge = 1e-3;
4912
+ const candidates = /* @__PURE__ */ new Set();
4913
+ for (const clip of film.clips) {
4914
+ const t = clip.t1 + nudge;
4915
+ if (t < film.duration && !active(t)) candidates.add(t);
4916
+ }
4917
+ if (candidates.size === 0) for (let i = 1; i <= 10; i++) candidates.add(film.duration * i / 10 - nudge);
4918
+ const scored = [];
4919
+ for (const time of [...candidates].sort((a, b) => a - b)) {
4920
+ const frame = await frameAt(film, time);
4921
+ scored.push({ time, ink: frame.ops.length });
4922
+ }
4923
+ const fullest = Math.max(...scored.map((entry) => entry.ink));
4924
+ const rich = scored.filter((entry) => entry.ink >= fullest * 0.75);
4925
+ return rich[rich.length - 1]?.time ?? film.duration;
4926
+ }
4927
+ function captionsToVtt(film) {
4928
+ const stamp = (seconds) => {
4929
+ const m = Math.floor(seconds / 60), s = seconds - m * 60;
4930
+ return `${String(m).padStart(2, "0")}:${s.toFixed(3).padStart(6, "0")}`;
4931
+ };
4932
+ const cues = film.captions.map((cue) => `${stamp(cue.t0)} --> ${stamp(cue.t1)}
4933
+ ${cue.text}`);
4934
+ return `WEBVTT
4935
+
4936
+ ${cues.join("\n\n")}
4937
+ `;
4938
+ }
4939
+ // Annotate the CommonJS export names for ESM import in node:
4940
+ 0 && (module.exports = {
4941
+ captionsToVtt,
4942
+ fromComponent,
4943
+ planRender,
4944
+ posterTime,
4945
+ renderFilmFrame,
4946
+ renderFilmFrames,
4947
+ renderFilmGif,
4948
+ renderFilmSvg,
4949
+ renderFilmVideo
4950
+ });