vizmatic 0.3.1 → 0.4.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.
package/dist/index.js CHANGED
@@ -1,445 +1,33 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // src/theme.ts
8
- import parseCssColor from "parse-css-color";
9
- var darkColors = {
10
- // Canvas backgrounds
11
- bg: "#151620",
12
- bgCard: "#1a1b26",
13
- bgCardAlt: "#1e2030",
14
- bgHover: "#24253a",
15
- bgSubtle: "#151620",
16
- // Brand / semantic colors (matches Mermaid palette)
17
- primary: "#7c3aed",
18
- // Purple — key/highlighted components
19
- primaryLight: "#a78bfa",
20
- primaryDark: "#6d28d9",
21
- secondary: "#2563eb",
22
- // Blue — supporting elements
23
- secondaryLight: "#60a5fa",
24
- secondaryDark: "#1d4ed8",
25
- positive: "#059669",
26
- // Green — output/success
27
- positiveLight: "#34d399",
28
- positiveDark: "#047857",
29
- warning: "#d97706",
30
- // Amber — warnings
31
- warningLight: "#fbbf24",
32
- warningDark: "#b45309",
33
- critical: "#dc2626",
34
- // Red — errors/bottlenecks
35
- criticalLight: "#f87171",
36
- criticalDark: "#b91c1c",
37
- info: "#06b6d4",
38
- // Cyan — informational
39
- infoLight: "#22d3ee",
40
- infoDark: "#0891b2",
41
- accent: "#f472b6",
42
- // Pink — accents
43
- accentLight: "#f9a8d4",
44
- neutral: "#334155",
45
- // Slate — infrastructure/background
46
- neutralLight: "#475569",
47
- neutralDark: "#1e293b",
48
- // Text
49
- textPrimary: "#f1f5f9",
50
- textSecondary: "#94a3b8",
51
- textMuted: "#8493a8",
52
- textOnColor: "#ffffff",
53
- // Borders
54
- border: "#334155",
55
- borderSubtle: "#1e293b",
56
- borderLight: "#475569",
57
- shadow: "rgba(0, 0, 0, 0.24)"
58
- };
59
- var lightColors = {
60
- // Canvas backgrounds
61
- bg: "#f5f7fa",
62
- bgCard: "#f8fafc",
63
- bgCardAlt: "#f1f5f9",
64
- bgHover: "#e2e8f0",
65
- bgSubtle: "#f5f7fa",
66
- // Brand / semantic colors (same hues, adjusted for light bg)
67
- primary: "#7c3aed",
68
- primaryLight: "#8b5cf6",
69
- primaryDark: "#6d28d9",
70
- secondary: "#2563eb",
71
- secondaryLight: "#3b82f6",
72
- secondaryDark: "#1d4ed8",
73
- positive: "#059669",
74
- positiveLight: "#10b981",
75
- positiveDark: "#047857",
76
- warning: "#d97706",
77
- warningLight: "#f59e0b",
78
- warningDark: "#b45309",
79
- critical: "#dc2626",
80
- criticalLight: "#ef4444",
81
- criticalDark: "#b91c1c",
82
- info: "#0891b2",
83
- infoLight: "#06b6d4",
84
- infoDark: "#0e7490",
85
- accent: "#ec4899",
86
- accentLight: "#f472b6",
87
- neutral: "#cbd5e1",
88
- neutralLight: "#94a3b8",
89
- neutralDark: "#e2e8f0",
90
- // Text
91
- textPrimary: "#0f172a",
92
- textSecondary: "#475569",
93
- textMuted: "#5b677a",
94
- textOnColor: "#ffffff",
95
- // Borders
96
- border: "#e2e8f0",
97
- borderSubtle: "#e2e8f0",
98
- borderLight: "#cbd5e1",
99
- shadow: "rgba(15, 23, 42, 0.12)"
100
- };
101
- var defaultStyleTokens = {
102
- preset: "default",
103
- fontSans: "Inter",
104
- fontMono: "JetBrains Mono"
105
- };
106
- var engineeringColors = {
107
- ...lightColors,
108
- bg: "#f4f4f5",
109
- bgCard: "#ffffff",
110
- bgCardAlt: "#ececee",
111
- bgHover: "#e4e4e7",
112
- bgSubtle: "#eeeeef",
113
- primary: "#632ca6",
114
- primaryLight: "#6d28d9",
115
- primaryDark: "#4c1d95",
116
- secondary: "#124fc7",
117
- secondaryLight: "#1556d1",
118
- secondaryDark: "#123d96",
119
- positive: "#087a55",
120
- positiveLight: "#0a8060",
121
- positiveDark: "#05543c",
122
- warning: "#c96c00",
123
- warningLight: "#d97800",
124
- warningDark: "#9a4f00",
125
- critical: "#b83232",
126
- criticalLight: "#c43d3d",
127
- criticalDark: "#8f2626",
128
- info: "#0b7185",
129
- infoLight: "#0d7d92",
130
- infoDark: "#075565",
131
- accent: "#a83c76",
132
- accentLight: "#b74583",
133
- neutral: "#52525b",
134
- neutralLight: "#71717a",
135
- neutralDark: "#3f3f46",
136
- textPrimary: "#101012",
137
- textSecondary: "#3f3f46",
138
- textMuted: "#68686f",
139
- textOnColor: "#ffffff",
140
- border: "#3f3f46",
141
- borderSubtle: "#d4d4d8",
142
- borderLight: "#a1a1aa",
143
- shadow: "rgba(0, 0, 0, 0)"
144
- };
145
- function getThemeColors(mode, preset = "default") {
146
- if (preset === "engineering") {
147
- return {
148
- ...engineeringColors,
149
- preset,
150
- fontSans: "Inter",
151
- fontMono: "JetBrains Mono"
152
- };
153
- }
154
- return {
155
- ...mode === "light" ? lightColors : darkColors,
156
- ...defaultStyleTokens
157
- };
158
- }
159
- var colors = {
160
- ...darkColors,
161
- ...defaultStyleTokens
162
- };
163
- var gradients = {
164
- purple: "linear-gradient(135deg, #7c3aed, #a855f7)",
165
- blue: "linear-gradient(135deg, #2563eb, #60a5fa)",
166
- green: "linear-gradient(135deg, #059669, #34d399)",
167
- warm: "linear-gradient(135deg, #f59e0b, #ef4444)",
168
- cyan: "linear-gradient(135deg, #06b6d4, #22d3ee)",
169
- pink: "linear-gradient(135deg, #ec4899, #f472b6)",
170
- sunset: "linear-gradient(135deg, #f97316, #db2777)",
171
- ocean: "linear-gradient(135deg, #0284c7, #7c3aed)",
172
- dark: "linear-gradient(180deg, #0f1117, #1a1b26)"
173
- };
174
- var toneGradients = {
175
- blue: gradients.blue,
176
- purple: gradients.purple,
177
- green: gradients.green,
178
- warm: gradients.warm,
179
- cyan: gradients.cyan,
180
- pink: gradients.pink,
181
- red: gradients.warm,
182
- critical: gradients.warm,
183
- neutral: gradients.dark,
184
- sunset: gradients.sunset,
185
- ocean: gradients.ocean,
186
- dark: gradients.dark
187
- };
188
- function getToneGradient(tone) {
189
- return toneGradients[tone];
190
- }
191
- function getToneColor(tone, c) {
192
- return {
193
- blue: c.secondaryLight,
194
- purple: c.primaryLight,
195
- green: c.positiveLight,
196
- warm: c.warningLight,
197
- cyan: c.infoLight,
198
- pink: c.accentLight,
199
- red: c.criticalLight,
200
- critical: c.criticalLight,
201
- neutral: c.textSecondary,
202
- sunset: c.warningLight,
203
- ocean: c.infoLight,
204
- dark: c.textSecondary
205
- }[tone];
206
- }
207
- function getReadableToneColor(tone, c, background = c.bgCard, backdrop = c.bgCard) {
208
- const semanticColor = {
209
- blue: "secondary",
210
- purple: "primary",
211
- green: "positive",
212
- warm: "warning",
213
- cyan: "info",
214
- pink: "accent",
215
- red: "critical",
216
- critical: "critical",
217
- neutral: "neutral",
218
- sunset: "warning",
219
- ocean: "info",
220
- dark: "neutral"
221
- };
222
- const color = getReadableColor(semanticColor[tone], c);
223
- return colorContrast(color, background, backdrop) >= 4.5 ? color : getReadableTextColor(background, c, backdrop);
224
- }
225
- function getToneFill(tone, c) {
226
- if (c.preset !== "engineering") return withColorAlpha(getToneColor(tone, c), 22 / 255);
227
- return {
228
- blue: "#cddcfa",
229
- purple: "#dfcff8",
230
- green: "#d5ede4",
231
- warm: "#fde7ce",
232
- cyan: "#d7edf1",
233
- pink: "#f3d9e7",
234
- red: "#f4d7d7",
235
- critical: "#f4d7d7",
236
- neutral: "#e4e4e7",
237
- sunset: "#fde1d6",
238
- ocean: "#d8e2f6",
239
- dark: "#dedee2"
240
- }[tone];
241
- }
242
- var typography = {
243
- title: { fontSize: 28, fontWeight: 700, fontFamily: "Inter" },
244
- subtitle: { fontSize: 20, fontWeight: 600, fontFamily: "Inter" },
245
- label: { fontSize: 16, fontWeight: 600, fontFamily: "Inter" },
246
- body: { fontSize: 14, fontWeight: 400, fontFamily: "Inter" },
247
- small: { fontSize: 12, fontWeight: 500, fontFamily: "Inter" },
248
- tiny: { fontSize: 11, fontWeight: 500, fontFamily: "Inter" },
249
- code: { fontSize: 13, fontWeight: 400, fontFamily: "JetBrains Mono" },
250
- annotation: { fontSize: 12, fontWeight: 500, fontFamily: "Inter", fontStyle: "italic" }
251
- };
252
- var canvas = {
253
- standard: { width: 800, height: 500 },
254
- wide: { width: 1e3, height: 400 },
255
- square: { width: 600, height: 600 },
256
- tall: { width: 600, height: 800 }
257
- };
258
- function getStyles(c) {
259
- return {
260
- canvas: {
261
- width: "100%",
262
- height: "100%",
263
- display: "flex",
264
- flexDirection: "column",
265
- backgroundColor: c.bg,
266
- fontFamily: c.fontSans,
267
- padding: 40
268
- },
269
- card: {
270
- display: "flex",
271
- flexDirection: "column",
272
- backgroundColor: c.bgCard,
273
- borderRadius: 8,
274
- border: `1px solid ${c.borderSubtle}`,
275
- padding: 20
276
- },
277
- pill: {
278
- display: "flex",
279
- alignItems: "center",
280
- justifyContent: "center",
281
- borderRadius: 999,
282
- padding: "6px 16px",
283
- fontSize: 13,
284
- fontWeight: 600,
285
- fontFamily: "Inter"
286
- }
287
- };
288
- }
289
- var styles = {
290
- canvas: {
291
- width: "100%",
292
- height: "100%",
293
- display: "flex",
294
- flexDirection: "column",
295
- backgroundColor: colors.bg,
296
- fontFamily: "Inter",
297
- padding: 40
298
- },
299
- card: {
300
- display: "flex",
301
- flexDirection: "column",
302
- backgroundColor: colors.bgCard,
303
- borderRadius: 8,
304
- border: `1px solid ${colors.borderSubtle}`,
305
- padding: 20
306
- },
307
- pill: {
308
- display: "flex",
309
- alignItems: "center",
310
- justifyContent: "center",
311
- borderRadius: 999,
312
- padding: "6px 16px",
313
- fontSize: 13,
314
- fontWeight: 600,
315
- fontFamily: "Inter"
316
- }
317
- };
318
- function getColor(name, c) {
319
- if (c) return c[name];
320
- return colors[name];
321
- }
322
- function getReadableColor(name, c) {
323
- const variants = {
324
- primary: [c.primaryLight, c.primary, c.primaryDark],
325
- secondary: [c.secondaryLight, c.secondary, c.secondaryDark],
326
- positive: [c.positiveLight, c.positive, c.positiveDark],
327
- warning: [c.warningLight, c.warning, c.warningDark],
328
- critical: [c.criticalLight, c.critical, c.criticalDark],
329
- info: [c.infoLight, c.info, c.infoDark],
330
- accent: [c.accentLight, c.accent, "#be185d"],
331
- neutral: [c.textSecondary, c.neutralLight, c.neutral, c.neutralDark]
332
- };
333
- return variants[name].reduce((best, candidate) => colorContrast(candidate, c.bgCard) > colorContrast(best, c.bgCard) ? candidate : best);
334
- }
335
- function parseColor(color) {
336
- const parsed = parseCssColor(color);
337
- if (!parsed || parsed.values.length < 3) return void 0;
338
- if (parsed.type !== "hsl") {
339
- return {
340
- channels: [parsed.values[0] ?? 0, parsed.values[1] ?? 0, parsed.values[2] ?? 0],
341
- alpha: parsed.alpha
342
- };
343
- }
344
- const hue = ((parsed.values[0] ?? 0) % 360 + 360) % 360;
345
- const saturation = (parsed.values[1] ?? 0) / 100;
346
- const lightness = (parsed.values[2] ?? 0) / 100;
347
- const chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;
348
- const segment = hue / 60;
349
- const intermediate = chroma * (1 - Math.abs(segment % 2 - 1));
350
- let channels;
351
- if (segment < 1) channels = [chroma, intermediate, 0];
352
- else if (segment < 2) channels = [intermediate, chroma, 0];
353
- else if (segment < 3) channels = [0, chroma, intermediate];
354
- else if (segment < 4) channels = [0, intermediate, chroma];
355
- else if (segment < 5) channels = [intermediate, 0, chroma];
356
- else channels = [chroma, 0, intermediate];
357
- const offset = lightness - chroma / 2;
358
- return {
359
- channels: channels.map((channel) => Math.round((channel + offset) * 255)),
360
- alpha: parsed.alpha
361
- };
362
- }
363
- function withColorAlpha(color, opacity) {
364
- if (typeof color !== "string" || !Number.isFinite(opacity)) return "transparent";
365
- const parsed = parseColor(color);
366
- if (!parsed) return "transparent";
367
- const alpha = Math.min(1, Math.max(0, parsed.alpha * Math.min(1, Math.max(0, opacity))));
368
- const hex = color.trim();
369
- if (/^#[\da-f]{6}$/i.test(hex)) {
370
- return `${hex}${Math.round(alpha * 255).toString(16).padStart(2, "0")}`;
371
- }
372
- return `rgba(${parsed.channels.join(", ")}, ${Number(alpha.toFixed(6))})`;
373
- }
374
- function colorLuminance(color, backdrop) {
375
- const parsed = parseColor(color);
376
- if (!parsed) return void 0;
377
- let channels = parsed.channels;
378
- if (parsed.alpha < 1) {
379
- const backdropColor = backdrop ? parseColor(backdrop) : void 0;
380
- if (!backdropColor) return void 0;
381
- channels = channels.map((channel, index) => Math.round(
382
- channel * parsed.alpha + backdropColor.channels[index] * (1 - parsed.alpha)
383
- ));
384
- }
385
- const [r, g, b] = channels.map((channel) => {
386
- const normalized = channel / 255;
387
- return normalized <= 0.04045 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
388
- });
389
- return 0.2126 * r + 0.7152 * g + 0.0722 * b;
390
- }
391
- function colorContrast(left, right, rightBackdrop) {
392
- const leftLuminance = colorLuminance(left);
393
- const rightLuminance = colorLuminance(right, rightBackdrop);
394
- if (leftLuminance == null || rightLuminance == null) return 0;
395
- return (Math.max(leftLuminance, rightLuminance) + 0.05) / (Math.min(leftLuminance, rightLuminance) + 0.05);
396
- }
397
- function getReadableTextColor(background, c, backdrop = c.bgCard) {
398
- if (colorLuminance(background, backdrop) == null) return c.textPrimary;
399
- const candidates = [c.textPrimary, c.textOnColor, c.bg, "#000000"];
400
- const readable = candidates.find((candidate) => colorContrast(candidate, background, backdrop) >= 4.5);
401
- if (readable) return readable;
402
- return candidates.reduce((best, candidate) => colorContrast(candidate, background, backdrop) > colorContrast(best, background, backdrop) ? candidate : best);
403
- }
404
- function getGradient(name) {
405
- const map = {
406
- primary: gradients.purple,
407
- secondary: gradients.blue,
408
- positive: gradients.green,
409
- warning: gradients.warm,
410
- critical: gradients.warm,
411
- info: gradients.cyan,
412
- accent: gradients.pink,
413
- neutral: gradients.dark
414
- };
415
- return map[name];
416
- }
417
- function heatColor(value) {
418
- const v = Math.max(0, Math.min(1, value));
419
- if (v < 0.25) {
420
- const t = v / 0.25;
421
- return lerpColor("#1e293b", "#0891b2", t);
422
- } else if (v < 0.5) {
423
- const t = (v - 0.25) / 0.25;
424
- return lerpColor("#0891b2", "#059669", t);
425
- } else if (v < 0.75) {
426
- const t = (v - 0.5) / 0.25;
427
- return lerpColor("#059669", "#d97706", t);
428
- } else {
429
- const t = (v - 0.75) / 0.25;
430
- return lerpColor("#d97706", "#dc2626", t);
431
- }
432
- }
433
- function lerpColor(a, b, t) {
434
- const ah = parseInt(a.slice(1), 16);
435
- const bh = parseInt(b.slice(1), 16);
436
- const ar = ah >> 16 & 255, ag = ah >> 8 & 255, ab = ah & 255;
437
- const br = bh >> 16 & 255, bg = bh >> 8 & 255, bb = bh & 255;
438
- const rr = Math.round(ar + (br - ar) * t);
439
- const rg = Math.round(ag + (bg - ag) * t);
440
- const rb = Math.round(ab + (bb - ab) * t);
441
- return `#${(rr << 16 | rg << 8 | rb).toString(16).padStart(6, "0")}`;
442
- }
1
+ import {
2
+ SCENE_COMPONENT_NAMES,
3
+ SCENE_DOM_TAGS,
4
+ SCENE_LIMITS,
5
+ SCENE_RUNTIME_VERSION,
6
+ __export,
7
+ canvas,
8
+ colors,
9
+ evaluateSceneSource,
10
+ getColor,
11
+ getGradient,
12
+ getReadableColor,
13
+ getReadableTextColor,
14
+ getReadableToneColor,
15
+ getStyles,
16
+ getThemeColors,
17
+ getToneColor,
18
+ getToneFill,
19
+ getToneGradient,
20
+ gradients,
21
+ heatColor,
22
+ normalizeSceneTime,
23
+ prepareScene,
24
+ sceneSha256,
25
+ styles,
26
+ toneGradients,
27
+ typography,
28
+ validateResolvedSceneResources,
29
+ withColorAlpha
30
+ } from "./chunk-FEIPTPBZ.js";
443
31
 
444
32
  // src/primitives.ts
445
33
  var primitives_exports = {};
@@ -3534,9 +3122,9 @@ function preferredSide(from, to) {
3534
3122
  return to.cy >= from.cy ? "bottom" : "top";
3535
3123
  }
3536
3124
  function routingAnchor(node, side, offset = 0.5) {
3537
- const bounds = box(node);
3538
- if (side === "left" || side === "right") return { x: bounds[side], y: bounds.top + node.height * offset };
3539
- return { x: bounds.left + node.width * offset, y: bounds[side] };
3125
+ const bounds2 = box(node);
3126
+ if (side === "left" || side === "right") return { x: bounds2[side], y: bounds2.top + node.height * offset };
3127
+ return { x: bounds2.left + node.width * offset, y: bounds2[side] };
3540
3128
  }
3541
3129
  function outward(point, side, distance) {
3542
3130
  return {
@@ -3750,7 +3338,7 @@ function routeOrthogonalGraph(nodes, edges, width, height, clearance = 12, gap =
3750
3338
  }
3751
3339
  const points = simplify([start, ...result.points, end]);
3752
3340
  if (points.length < 2) continue;
3753
- const repeated = (previous.get(key) ?? []).some((route) => route.length === points.length && (route.every((point, position) => point.x === points[position].x && point.y === points[position].y) || route.every((point, position) => point.x === points[points.length - 1 - position].x && point.y === points[points.length - 1 - position].y)));
3341
+ const repeated = (previous.get(key) ?? []).some((route) => route.length === points.length && (route.every((point, position2) => point.x === points[position2].x && point.y === points[position2].y) || route.every((point, position2) => point.x === points[points.length - 1 - position2].x && point.y === points[points.length - 1 - position2].y)));
3754
3342
  if (repeated) {
3755
3343
  failure = "parallel connectors have no separate lane at the requested clearance";
3756
3344
  continue;
@@ -3766,17 +3354,17 @@ function routeOrthogonalGraph(nodes, edges, width, height, clearance = 12, gap =
3766
3354
  }
3767
3355
  function routingLabelPosition(points) {
3768
3356
  let longest = 0;
3769
- let position = points[0];
3357
+ let position2 = points[0];
3770
3358
  for (let i = 1; i < points.length; i++) {
3771
3359
  const a = points[i - 1];
3772
3360
  const b = points[i];
3773
3361
  const length = Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
3774
3362
  if (length > longest) {
3775
3363
  longest = length;
3776
- position = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
3364
+ position2 = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
3777
3365
  }
3778
3366
  }
3779
- return position;
3367
+ return position2;
3780
3368
  }
3781
3369
 
3782
3370
  // src/primitives/diagrams.ts
@@ -4067,13 +3655,13 @@ function connectorLabelCollisions(edges, nodes, groups = []) {
4067
3655
  if (rectanglesOverlap(labels[index].bounds, labels[otherIndex].bounds, 4)) collisions += 1;
4068
3656
  }
4069
3657
  for (const node of nodes.values()) {
4070
- const bounds = {
3658
+ const bounds2 = {
4071
3659
  left: node.cx - node.width / 2,
4072
3660
  right: node.cx + node.width / 2,
4073
3661
  top: node.cy - node.height / 2,
4074
3662
  bottom: node.cy + node.height / 2
4075
3663
  };
4076
- if (rectanglesOverlap(labels[index].bounds, bounds)) collisions += 1;
3664
+ if (rectanglesOverlap(labels[index].bounds, bounds2)) collisions += 1;
4077
3665
  }
4078
3666
  for (const group of groups) {
4079
3667
  const headerBounds = {
@@ -4334,24 +3922,24 @@ function GraphDiagram({
4334
3922
  const offsetX = (resolvedWidth - (graphSize.width ?? resolvedWidth)) / 2;
4335
3923
  const offsetY = (resolvedHeight - (graphSize.height ?? resolvedHeight)) / 2;
4336
3924
  layout = new Map(nodes.map((node) => {
4337
- const position = graph.node(node.id);
3925
+ const position2 = graph.node(node.id);
4338
3926
  return [node.id, {
4339
3927
  ...node,
4340
3928
  width: node.width ?? nodeWidth,
4341
3929
  height: node.height ?? nodeHeight,
4342
- cx: (position?.x ?? resolvedWidth / 2) + offsetX,
4343
- cy: (position?.y ?? resolvedHeight / 2) + offsetY
3930
+ cx: (position2?.x ?? resolvedWidth / 2) + offsetX,
3931
+ cy: (position2?.y ?? resolvedHeight / 2) + offsetY
4344
3932
  }];
4345
3933
  }));
4346
3934
  const groupsById = new Map(groups.map((group) => [group.id, group]));
4347
3935
  groupLayout = groups.map((group) => {
4348
- const position = graph.node(group.id);
3936
+ const position2 = graph.node(group.id);
4349
3937
  return {
4350
3938
  ...group,
4351
- width: position?.width ?? 0,
4352
- height: position?.height ?? 0,
4353
- cx: (position?.x ?? resolvedWidth / 2) + offsetX,
4354
- cy: (position?.y ?? resolvedHeight / 2) + offsetY,
3939
+ width: position2?.width ?? 0,
3940
+ height: position2?.height ?? 0,
3941
+ cx: (position2?.x ?? resolvedWidth / 2) + offsetX,
3942
+ cy: (position2?.y ?? resolvedHeight / 2) + offsetY,
4355
3943
  depth: graphGroupDepth(group, groupsById)
4356
3944
  };
4357
3945
  }).sort((left, right) => left.depth - right.depth);
@@ -4645,7 +4233,8 @@ function GraphDiagram({
4645
4233
  flexDirection: "column",
4646
4234
  alignItems: icon ? "flex-start" : "center",
4647
4235
  gap: node.detail ? 5 : 0,
4648
- minWidth: 0
4236
+ minWidth: 0,
4237
+ flexShrink: 1
4649
4238
  }
4650
4239
  },
4651
4240
  React6.createElement("div", {
@@ -5391,7 +4980,7 @@ function SequenceDiagram({
5391
4980
  const noteElements = rows.map((row, rowIndex) => {
5392
4981
  if (!row.item || !isNote(row.item)) return null;
5393
4982
  const note = row.item;
5394
- const bounds = sequenceNoteBounds(note, participantXs, resolvedWidth, noteWidth, padding);
4983
+ const bounds2 = sequenceNoteBounds(note, participantXs, resolvedWidth, noteWidth, padding);
5395
4984
  const tone = note.tone ?? "warm";
5396
4985
  const accent = note.muted ? c.textMuted : getToneColor(tone, c);
5397
4986
  return React7.createElement("div", {
@@ -5399,9 +4988,9 @@ function SequenceDiagram({
5399
4988
  "data-vizmatic-sequence-note": note.id ?? row.key,
5400
4989
  style: {
5401
4990
  position: "absolute",
5402
- left: bounds.left,
4991
+ left: bounds2.left,
5403
4992
  top: rowCenter(rowIndex) - 17,
5404
- width: bounds.width,
4993
+ width: bounds2.width,
5405
4994
  minHeight: 34,
5406
4995
  boxSizing: "border-box",
5407
4996
  display: "flex",
@@ -7061,25 +6650,44 @@ function CanvasChartFit({ children, width, height }) {
7061
6650
  }
7062
6651
  function prepareChartFits(element) {
7063
6652
  const sizes = /* @__PURE__ */ new Map();
6653
+ const hasText = (node) => {
6654
+ if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") return true;
6655
+ if (Array.isArray(node)) return node.some(hasText);
6656
+ return isValidElement2(node) && node.type === React10.Fragment && hasText(node.props.children);
6657
+ };
7064
6658
  const visit = (node, scope) => {
7065
6659
  if (Array.isArray(node)) return node.map((child) => visit(child, scope));
7066
6660
  if (!isValidElement2(node)) return node;
7067
- if (typeof node.type === "function") {
7068
- const resolved = visit(node.type(node.props), scope);
6661
+ const forwarded = node.type;
6662
+ const render = typeof node.type === "function" ? node.type : forwarded?.$$typeof === /* @__PURE__ */ Symbol.for("react.forward_ref") ? forwarded.render : void 0;
6663
+ if (render) {
6664
+ const resolved = visit(render(node.props), scope);
7069
6665
  return node.key != null && isValidElement2(resolved) ? React10.cloneElement(resolved, { key: node.key }) : resolved;
7070
6666
  }
7071
6667
  const size = node.props[FIT_PROP];
7072
6668
  const props = { ...node.props };
7073
6669
  delete props[FIT_PROP];
6670
+ let childScope = scope;
7074
6671
  if (size) {
7075
6672
  const id = String(sizes.size);
7076
6673
  sizes.set(id, size);
7077
6674
  props[VIEWPORT_PROP] = id;
7078
- return React10.cloneElement(node, props, visit(node.props.children, id));
6675
+ childScope = id;
6676
+ } else if (scope !== void 0 && typeof node.type === "string") {
6677
+ props[SCOPE_PROP] = scope;
7079
6678
  }
7080
- if (scope !== void 0 && typeof node.type === "string") props[SCOPE_PROP] = scope;
7081
6679
  const children = node.props.children;
7082
- return children === void 0 ? React10.cloneElement(node, props) : React10.cloneElement(node, props, visit(children, scope));
6680
+ const preparedChildren = children === void 0 ? void 0 : visit(children, childScope);
6681
+ if (typeof node.type === "string") {
6682
+ const style = node.props.style;
6683
+ props.style = {
6684
+ minWidth: 0,
6685
+ minHeight: 0,
6686
+ ...style?.flex === void 0 ? { flexShrink: hasText(preparedChildren) ? 1 : 0 } : {},
6687
+ ...style
6688
+ };
6689
+ }
6690
+ return children === void 0 ? React10.cloneElement(node, props) : React10.cloneElement(node, props, preparedChildren);
7083
6691
  };
7084
6692
  return { element: visit(element), sizes };
7085
6693
  }
@@ -7105,14 +6713,14 @@ async function renderWithCanvasChartFit(render, element, options) {
7105
6713
  const prepared = prepareChartFits(element);
7106
6714
  if (!prepared.sizes.size) return render(prepared.element, options);
7107
6715
  const viewports = /* @__PURE__ */ new Map();
7108
- const bounds = /* @__PURE__ */ new Map();
6716
+ const bounds2 = /* @__PURE__ */ new Map();
7109
6717
  await render(prepared.element, { ...options, onNodeDetected(node) {
7110
6718
  const viewport = node.props[VIEWPORT_PROP];
7111
6719
  if (typeof viewport === "string") viewports.set(viewport, node);
7112
6720
  const id = node.props[SCOPE_PROP];
7113
- if (typeof id !== "string" || node.width <= 0 || node.height <= 0) return;
7114
- const prior = bounds.get(id);
7115
- bounds.set(id, {
6721
+ if (typeof id !== "string" || node.width < 0 || node.height < 0) return;
6722
+ const prior = bounds2.get(id);
6723
+ bounds2.set(id, {
7116
6724
  left: Math.min(prior?.left ?? Infinity, node.left),
7117
6725
  top: Math.min(prior?.top ?? Infinity, node.top),
7118
6726
  right: Math.max(prior?.right ?? -Infinity, node.left + node.width),
@@ -7122,7 +6730,7 @@ async function renderWithCanvasChartFit(render, element, options) {
7122
6730
  const geometry = /* @__PURE__ */ new Map();
7123
6731
  for (const [id, size] of prepared.sizes) {
7124
6732
  const viewport = viewports.get(id);
7125
- const measured = bounds.get(id);
6733
+ const measured = bounds2.get(id);
7126
6734
  if (!viewport || !measured) throw new Error("Could not measure the chart inside CanvasItem.");
7127
6735
  const width = measured.right - measured.left, height = measured.bottom - measured.top;
7128
6736
  const scale = Math.min(size.width / width, size.height / height);
@@ -9069,8 +8677,11 @@ function CanvasItem({ children, x, y, width, height }) {
9069
8677
  if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error("CanvasItem x and y must be finite numbers.");
9070
8678
  const sizedChildren = React13.Children.map(children, (child) => {
9071
8679
  if (!React13.isValidElement(child)) return child;
9072
- const sized = React13.cloneElement(child, { ...width !== void 0 ? { width } : {}, ...height !== void 0 ? { height } : {} });
9073
- return width !== void 0 && height !== void 0 && isCanvasChart(child.type) ? React13.createElement(CanvasChartFit, { width, height, __vizmaticTextScope: child.props.__vizmaticTextScope }, sized) : sized;
8680
+ if (width !== void 0 && height !== void 0 && isCanvasChart(child.type)) {
8681
+ const chart = React13.cloneElement(child, { width: child.props.width ?? width, height: child.props.height ?? height });
8682
+ return React13.createElement(CanvasChartFit, { width, height, __vizmaticTextScope: child.props.__vizmaticTextScope }, chart);
8683
+ }
8684
+ return React13.cloneElement(child, { ...width !== void 0 ? { width } : {}, ...height !== void 0 ? { height } : {} });
9074
8685
  });
9075
8686
  return React13.createElement("div", { style: {
9076
8687
  display: "flex",
@@ -9133,8 +8744,8 @@ function normalizeWatermark(watermark) {
9133
8744
  function Watermark(_props) {
9134
8745
  return null;
9135
8746
  }
9136
- function positionStyle(position) {
9137
- switch (position) {
8747
+ function positionStyle(position2) {
8748
+ switch (position2) {
9138
8749
  case "top-left":
9139
8750
  return { top: 8, left: 10 };
9140
8751
  case "bottom-left":
@@ -9185,7 +8796,7 @@ function wrapWithWatermark(element, width, height, theme = "dark", watermark = t
9185
8796
  const isDark = theme === "dark";
9186
8797
  const options = normalizeWatermark(watermark);
9187
8798
  const color = options?.color ?? (isDark ? WATERMARK_COLOR_DARK : WATERMARK_COLOR_LIGHT);
9188
- const position = options?.position ?? "top-right";
8799
+ const position2 = options?.position ?? "top-right";
9189
8800
  const opacity = options?.opacity ?? (isDark ? 0.55 : 0.4);
9190
8801
  const icon = options ? imageNode(options.image) ?? iconNode(options.icon, color) : void 0;
9191
8802
  const text = options?.text ?? DEFAULT_WATERMARK_TEXT;
@@ -9218,7 +8829,7 @@ function wrapWithWatermark(element, width, height, theme = "dark", watermark = t
9218
8829
  {
9219
8830
  style: {
9220
8831
  position: "absolute",
9221
- ...positionStyle(position),
8832
+ ...positionStyle(position2),
9222
8833
  display: "flex",
9223
8834
  alignItems: "center",
9224
8835
  gap: 5,
@@ -9582,23 +9193,19 @@ function cropLayoutNodes(nodes, region) {
9582
9193
  }];
9583
9194
  });
9584
9195
  }
9585
- function cropSavesEnough(source, target) {
9586
- if (source <= 0 || target >= source) return false;
9587
- return (source - target) / source * 100 >= CROP_THRESHOLD_PERCENT;
9588
- }
9589
9196
  var CanvasOverflowError = class extends Error {
9590
9197
  width;
9591
9198
  height;
9592
9199
  overflow;
9593
9200
  animation;
9594
9201
  constructor(width, height, overflow, animation) {
9595
- const position = animation ? [
9202
+ const position2 = animation ? [
9596
9203
  animation.sceneIndex != null ? `scene ${animation.sceneIndex + 1}` : void 0,
9597
9204
  animation.frameIndex != null ? `frame ${animation.frameIndex + 1}${animation.frameCount ? `/${animation.frameCount}` : ""}` : void 0,
9598
9205
  animation.time != null ? `${Math.round(animation.time)}ms` : void 0,
9599
9206
  animation.label ? JSON.stringify(animation.label) : void 0
9600
9207
  ].filter(Boolean).join(", ") : "";
9601
- super(`Canvas overflow detected (${width}\xD7${height})${position ? ` at ${position}` : ""}: ${overflow.message}`);
9208
+ super(`Canvas overflow detected (${width}\xD7${height})${position2 ? ` at ${position2}` : ""}: ${overflow.message}`);
9602
9209
  this.name = "CanvasOverflowError";
9603
9210
  this.width = width;
9604
9211
  this.height = height;
@@ -9642,7 +9249,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
9642
9249
  const detectPixels = detectResult.pixels;
9643
9250
  const pixelData = new Uint8Array(detectPixels.buffer);
9644
9251
  const detectedBg = detectBackgroundColor(pixelData);
9645
- const bounds = detectContentBounds(
9252
+ const bounds2 = detectContentBounds(
9646
9253
  pixelData,
9647
9254
  options.width,
9648
9255
  detectResult.height,
@@ -9661,7 +9268,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
9661
9268
  let finalWidth = options.width;
9662
9269
  let finalHeight = options.height;
9663
9270
  let finalElement = element;
9664
- const croppedHeight = bounds.y + bounds.height;
9271
+ const croppedHeight = bounds2.y + bounds2.height;
9665
9272
  const heightSaved = options.height - croppedHeight;
9666
9273
  const heightSavedPercent = heightSaved / options.height * 100;
9667
9274
  if (shouldCropHeight(options.crop) && heightSavedPercent >= CROP_THRESHOLD_PERCENT) {
@@ -9720,7 +9327,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
9720
9327
  viewportBg,
9721
9328
  AUTOCROP_PADDING
9722
9329
  );
9723
- if (cropSavesEnough(finalWidth, viewportBounds.width) || cropSavesEnough(viewportCheck.height, viewportBounds.height)) {
9330
+ if (viewportBounds.width < finalWidth || viewportBounds.height < viewportCheck.height) {
9724
9331
  finalSvg = cropSvgViewport(finalSvg, viewportBounds);
9725
9332
  finalRender.layoutNodes = cropLayoutNodes(finalRender.layoutNodes, viewportBounds);
9726
9333
  finalWidth = viewportBounds.width;
@@ -9832,7 +9439,7 @@ import { Resvg as Resvg2 } from "@resvg/resvg-js";
9832
9439
  import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
9833
9440
  import { dirname as dirname2 } from "path";
9834
9441
  import * as gifenc from "gifenc";
9835
- import parseCssColor2 from "parse-css-color";
9442
+ import parseCssColor from "parse-css-color";
9836
9443
 
9837
9444
  // src/timeline.ts
9838
9445
  var MIN_FPS = 1;
@@ -9852,18 +9459,18 @@ function clampProgress(progress) {
9852
9459
  return Math.max(0, Math.min(1, progress));
9853
9460
  }
9854
9461
  function easingValue(easing = "linear", progress) {
9855
- const amount = clampProgress(progress);
9462
+ const amount2 = clampProgress(progress);
9856
9463
  let result;
9857
9464
  if (typeof easing === "function") {
9858
- result = easing(amount);
9465
+ result = easing(amount2);
9859
9466
  } else if (easing === "ease-in") {
9860
- result = amount * amount * amount;
9467
+ result = amount2 * amount2 * amount2;
9861
9468
  } else if (easing === "ease-out") {
9862
- result = 1 - (1 - amount) ** 3;
9469
+ result = 1 - (1 - amount2) ** 3;
9863
9470
  } else if (easing === "ease-in-out") {
9864
- result = amount < 0.5 ? 4 * amount * amount * amount : 1 - (-2 * amount + 2) ** 3 / 2;
9471
+ result = amount2 < 0.5 ? 4 * amount2 * amount2 * amount2 : 1 - (-2 * amount2 + 2) ** 3 / 2;
9865
9472
  } else if (easing === "linear") {
9866
- result = amount;
9473
+ result = amount2;
9867
9474
  } else {
9868
9475
  throw new Error(`Unknown animation easing: ${String(easing)}`);
9869
9476
  }
@@ -9935,8 +9542,8 @@ function defineAnimation(definition) {
9935
9542
  fps
9936
9543
  };
9937
9544
  }
9938
- function interpolateValue(from, to, progress, interpolate) {
9939
- if (interpolate) return interpolate(from, to, progress);
9545
+ function interpolateValue(from, to, progress, interpolate2) {
9546
+ if (interpolate2) return interpolate2(from, to, progress);
9940
9547
  if (typeof from === "number" && typeof to === "number" && Number.isFinite(from) && Number.isFinite(to)) {
9941
9548
  return from + (to - from) * progress;
9942
9549
  }
@@ -10072,6 +9679,23 @@ function sampleAnimation(animation, time) {
10072
9679
  if (!Number.isFinite(time)) throw new Error("Animation sample time must be finite");
10073
9680
  return evaluateAnimation(animation, time).state;
10074
9681
  }
9682
+ function sampleAnimationFrame(animation, requestedTime, timing) {
9683
+ if (!Number.isFinite(requestedTime)) throw new Error("Animation sample time must be finite");
9684
+ const time = Math.max(0, Math.min(animation.duration, requestedTime));
9685
+ const evaluated = evaluateAnimation(animation, time);
9686
+ return {
9687
+ state: evaluated.state,
9688
+ frame: {
9689
+ ...timing,
9690
+ time,
9691
+ duration: animation.duration,
9692
+ progress: time / animation.duration,
9693
+ step: evaluated.step,
9694
+ stepProgress: evaluated.stepProgress,
9695
+ label: evaluated.label
9696
+ }
9697
+ };
9698
+ }
10075
9699
  function animationCadence(duration, fps) {
10076
9700
  const interval = 1e3 / fps;
10077
9701
  const times = [0];
@@ -10110,24 +9734,12 @@ function sampleAnimationFrames(animation, options = {}) {
10110
9734
  assertFps(fps);
10111
9735
  const cadence = animationCadence(animation.duration, fps);
10112
9736
  const count = cadence.times.length;
10113
- return cadence.times.map((time, index) => {
10114
- const evaluated = evaluateAnimation(animation, time);
10115
- return {
10116
- state: evaluated.state,
10117
- frame: {
10118
- index,
10119
- count,
10120
- time,
10121
- duration: animation.duration,
10122
- delay: cadence.delays[index],
10123
- progress: time / animation.duration,
10124
- step: evaluated.step,
10125
- stepProgress: evaluated.stepProgress,
10126
- label: evaluated.label,
10127
- fps
10128
- }
10129
- };
10130
- });
9737
+ return cadence.times.map((time, index) => sampleAnimationFrame(animation, time, {
9738
+ index,
9739
+ count,
9740
+ delay: cadence.delays[index],
9741
+ fps
9742
+ }));
10131
9743
  }
10132
9744
 
10133
9745
  // src/animate.ts
@@ -10223,7 +9835,7 @@ function hslToRgb(hue, saturation, lightness) {
10223
9835
  }
10224
9836
  function colorForBackground(background, theme) {
10225
9837
  const value = background === "theme" ? getThemeColors(theme).bg : background;
10226
- const parsed = parseCssColor2(value);
9838
+ const parsed = parseCssColor(value);
10227
9839
  if (!parsed) throw new Error(`Invalid animation background color: ${value}`);
10228
9840
  const [r, g, b] = parsed.type === "hsl" ? hslToRgb(parsed.values[0], parsed.values[1], parsed.values[2]) : [parsed.values[0], parsed.values[1], parsed.values[2]];
10229
9841
  return { r, g, b, a: Math.round(parsed.alpha * 255) };
@@ -10298,16 +9910,16 @@ function cropFramePixels(pixels, canvasWidth, region) {
10298
9910
  }
10299
9911
  function deltaPixelFrame(frame, previous, enabled) {
10300
9912
  if (!enabled || !previous) return frame;
10301
- const bounds = changedBounds(previous, frame.pixels, frame.width, frame.height);
10302
- if (!bounds || bounds.width === frame.width && bounds.height === frame.height) return frame;
9913
+ const bounds2 = changedBounds(previous, frame.pixels, frame.width, frame.height);
9914
+ if (!bounds2 || bounds2.width === frame.width && bounds2.height === frame.height) return frame;
10303
9915
  return {
10304
9916
  ...frame,
10305
- x: bounds.x,
10306
- y: bounds.y,
9917
+ x: bounds2.x,
9918
+ y: bounds2.y,
10307
9919
  delta: true,
10308
- width: bounds.width,
10309
- height: bounds.height,
10310
- pixels: cropFramePixels(frame.pixels, frame.width, bounds)
9920
+ width: bounds2.width,
9921
+ height: bounds2.height,
9922
+ pixels: cropFramePixels(frame.pixels, frame.width, bounds2)
10311
9923
  };
10312
9924
  }
10313
9925
  function encodeGif(frames, loop, deltaFrames) {
@@ -10413,8 +10025,8 @@ async function scenesToFrames(scenes, options) {
10413
10025
  );
10414
10026
  const frameDelays = transitionFrameDelays(transitionDuration, transitionFrames);
10415
10027
  for (let frameIndex = 0; frameIndex < transitionFrames; frameIndex += 1) {
10416
- const amount = (frameIndex + 1) / transitionFrames;
10417
- const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels, amount) : blendPixels(backgroundPixels(scaledWidth, scaledHeight, options.theme, options.background), current.pixels, amount);
10028
+ const amount2 = (frameIndex + 1) / transitionFrames;
10029
+ const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels, amount2) : blendPixels(backgroundPixels(scaledWidth, scaledHeight, options.theme, options.background), current.pixels, amount2);
10418
10030
  frames.push({ pixels, delay: frameDelays[frameIndex], width: scaledWidth, height: scaledHeight });
10419
10031
  }
10420
10032
  }
@@ -10606,6 +10218,1825 @@ async function renderAnimationGifWithOutput(animation, options) {
10606
10218
  };
10607
10219
  }
10608
10220
 
10221
+ // src/math.ts
10222
+ import parseCssColor2 from "parse-css-color";
10223
+ import { liteAdaptor } from "mathjax-full/js/adaptors/liteAdaptor.js";
10224
+ import { RegisterHTMLHandler } from "mathjax-full/js/handlers/html.js";
10225
+ import { TeX } from "mathjax-full/js/input/tex.js";
10226
+ import "mathjax-full/js/input/tex/ams/AmsConfiguration.js";
10227
+ import "mathjax-full/js/input/tex/newcommand/NewcommandConfiguration.js";
10228
+ import { mathjax } from "mathjax-full/js/mathjax.js";
10229
+ import { SVG } from "mathjax-full/js/output/svg.js";
10230
+ var DEFAULT_FONT_SIZE = 16;
10231
+ var EX_FACTOR = 0.5;
10232
+ var adaptor = liteAdaptor({ fontSize: DEFAULT_FONT_SIZE });
10233
+ RegisterHTMLHandler(adaptor);
10234
+ var outputJax = new SVG({ fontCache: "none", exFactor: EX_FACTOR });
10235
+ var renderCache = /* @__PURE__ */ new Map();
10236
+ var RENDER_CACHE_LIMIT = 128;
10237
+ function createDocument() {
10238
+ const inputJax = new TeX({
10239
+ packages: ["base", "ams", "newcommand"],
10240
+ formatError(_jax, error) {
10241
+ throw new Error(`Invalid TeX: ${error.message}`, { cause: error });
10242
+ }
10243
+ });
10244
+ return mathjax.document("", { InputJax: inputJax, OutputJax: outputJax });
10245
+ }
10246
+ function parseEx(value, name) {
10247
+ if (typeof value !== "string" || !value.endsWith("ex")) {
10248
+ throw new Error(`MathJax returned an unsupported ${name} dimension`);
10249
+ }
10250
+ const amount2 = Number(value.slice(0, -2));
10251
+ if (!Number.isFinite(amount2) || amount2 <= 0) {
10252
+ throw new Error(`MathJax returned an invalid ${name} dimension`);
10253
+ }
10254
+ return amount2;
10255
+ }
10256
+ function parseViewBox(value) {
10257
+ if (typeof value !== "string") throw new Error("MathJax returned an SVG without a viewBox");
10258
+ const values = value.trim().split(/[ ,]+/).map(Number);
10259
+ if (values.length !== 4 || values.some((part) => !Number.isFinite(part)) || values[2] <= 0 || values[3] <= 0) {
10260
+ throw new Error("MathJax returned an invalid SVG viewBox");
10261
+ }
10262
+ return [values[0], values[1], values[2], values[3]];
10263
+ }
10264
+ function renderMathSvg(tex, options = {}) {
10265
+ if (typeof tex !== "string" || tex.trim().length === 0) {
10266
+ throw new Error("TeX input must be a non-empty string");
10267
+ }
10268
+ const fontSize = options.fontSize ?? DEFAULT_FONT_SIZE;
10269
+ if (!Number.isFinite(fontSize) || fontSize <= 0) {
10270
+ throw new Error("Math SVG fontSize must be a positive finite number");
10271
+ }
10272
+ const color = options.color ?? "#000000";
10273
+ if (typeof color !== "string" || !parseCssColor2(color.trim())) {
10274
+ throw new Error("Math SVG color must be a valid CSS color");
10275
+ }
10276
+ const normalizedColor = color.trim();
10277
+ const display = options.display ?? false;
10278
+ const key = JSON.stringify([tex, fontSize, normalizedColor, display]);
10279
+ const cached = renderCache.get(key);
10280
+ if (cached) {
10281
+ renderCache.delete(key);
10282
+ renderCache.set(key, cached);
10283
+ return { ...cached };
10284
+ }
10285
+ let container;
10286
+ try {
10287
+ container = createDocument().convert(tex, {
10288
+ display,
10289
+ em: fontSize,
10290
+ ex: fontSize * EX_FACTOR,
10291
+ containerWidth: fontSize * 80
10292
+ });
10293
+ } catch (cause) {
10294
+ if (cause instanceof Error && cause.message.startsWith("Invalid TeX:")) throw cause;
10295
+ const detail = cause instanceof Error ? cause.message : String(cause);
10296
+ throw new Error(`Unable to render TeX: ${detail}`, { cause });
10297
+ }
10298
+ const svgElement = adaptor.tags(container, "svg")[0];
10299
+ if (!svgElement) throw new Error("MathJax did not produce an SVG image");
10300
+ const width = parseEx(adaptor.getAttribute(svgElement, "width"), "width") * fontSize * EX_FACTOR;
10301
+ const height = parseEx(adaptor.getAttribute(svgElement, "height"), "height") * fontSize * EX_FACTOR;
10302
+ if (!Number.isFinite(width) || !Number.isFinite(height)) {
10303
+ throw new Error("MathJax returned non-finite SVG dimensions");
10304
+ }
10305
+ const [, viewBoxY, , viewBoxHeight] = parseViewBox(adaptor.getAttribute(svgElement, "viewBox"));
10306
+ const baseline = -viewBoxY * height / viewBoxHeight;
10307
+ if (!Number.isFinite(baseline)) {
10308
+ throw new Error("MathJax returned an invalid SVG baseline");
10309
+ }
10310
+ const drawing = adaptor.tags(svgElement, "g")[0];
10311
+ if (!drawing) throw new Error("MathJax returned an SVG without a drawing group");
10312
+ adaptor.removeAttribute(svgElement, "style");
10313
+ adaptor.setAttribute(svgElement, "width", `${width}px`);
10314
+ adaptor.setAttribute(svgElement, "height", `${height}px`);
10315
+ adaptor.setAttribute(drawing, "fill", normalizedColor);
10316
+ adaptor.setAttribute(drawing, "stroke", normalizedColor);
10317
+ const result = {
10318
+ svg: adaptor.serializeXML(svgElement),
10319
+ width,
10320
+ height,
10321
+ baseline
10322
+ };
10323
+ renderCache.set(key, result);
10324
+ if (renderCache.size > RENDER_CACHE_LIMIT) {
10325
+ renderCache.delete(renderCache.keys().next().value);
10326
+ }
10327
+ return { ...result };
10328
+ }
10329
+
10330
+ // src/motion.ts
10331
+ var DEFAULT_ARC_LIFT = 80;
10332
+ function assertFiniteProgress(progress) {
10333
+ if (!Number.isFinite(progress)) throw new Error("Motion progress must be finite");
10334
+ }
10335
+ function clampProgress2(progress) {
10336
+ assertFiniteProgress(progress);
10337
+ return Math.max(0, Math.min(1, progress));
10338
+ }
10339
+ function assertPoint(point, context) {
10340
+ if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {
10341
+ throw new Error(`${context} coordinates must be finite`);
10342
+ }
10343
+ }
10344
+ function interpolate(from, to, progress) {
10345
+ return {
10346
+ x: from.x * (1 - progress) + to.x * progress,
10347
+ y: from.y * (1 - progress) + to.y * progress
10348
+ };
10349
+ }
10350
+ function smoothstep(progress) {
10351
+ const amount2 = clampProgress2(progress);
10352
+ return amount2 * amount2 * (3 - 2 * amount2);
10353
+ }
10354
+ function arcSwap(from, to, progress, options = {}) {
10355
+ assertPoint(from, "Arc swap start");
10356
+ assertPoint(to, "Arc swap end");
10357
+ const amount2 = clampProgress2(progress);
10358
+ const lift = options.lift ?? DEFAULT_ARC_LIFT;
10359
+ if (!Number.isFinite(lift)) throw new Error("Arc swap lift must be finite");
10360
+ if (amount2 === 0) return [{ x: from.x, y: from.y }, { x: to.x, y: to.y }];
10361
+ if (amount2 === 1) return [{ x: to.x, y: to.y }, { x: from.x, y: from.y }];
10362
+ const eased = (options.easing ?? smoothstep)(amount2);
10363
+ if (!Number.isFinite(eased)) throw new Error("Motion easing must return a finite number");
10364
+ const t = Math.max(0, Math.min(1, eased));
10365
+ if (t === 0) return [{ x: from.x, y: from.y }, { x: to.x, y: to.y }];
10366
+ if (t === 1) return [{ x: to.x, y: to.y }, { x: from.x, y: from.y }];
10367
+ const dx = to.x - from.x;
10368
+ const dy = to.y - from.y;
10369
+ const length = Math.hypot(dx, dy);
10370
+ if (!Number.isFinite(length)) throw new Error("Arc swap distance must be finite");
10371
+ if (length === 0) return [{ x: from.x, y: from.y }, { x: to.x, y: to.y }];
10372
+ const normalX = -dy / length;
10373
+ const normalY = dx / length;
10374
+ const arcHeight = 4 * (1 - t) * t * lift;
10375
+ const firstBase = interpolate(from, to, t);
10376
+ const secondBase = interpolate(to, from, t);
10377
+ const first = {
10378
+ x: firstBase.x + normalX * arcHeight,
10379
+ y: firstBase.y + normalY * arcHeight
10380
+ };
10381
+ const second = {
10382
+ x: secondBase.x - normalX * arcHeight,
10383
+ y: secondBase.y - normalY * arcHeight
10384
+ };
10385
+ assertPoint(first, "Arc swap result");
10386
+ assertPoint(second, "Arc swap result");
10387
+ return [first, second];
10388
+ }
10389
+ function pathLengths(points) {
10390
+ const lengths = [];
10391
+ let total = 0;
10392
+ for (let index = 0; index < points.length; index += 1) {
10393
+ const point = points[index];
10394
+ assertPoint(point, `Path point ${index}`);
10395
+ if (index === 0) continue;
10396
+ const previous = points[index - 1];
10397
+ const length = Math.hypot(point.x - previous.x, point.y - previous.y);
10398
+ if (!Number.isFinite(length)) throw new Error("Path segment length must be finite");
10399
+ total += length;
10400
+ if (!Number.isFinite(total)) throw new Error("Path length must be finite");
10401
+ lengths.push(length);
10402
+ }
10403
+ return lengths;
10404
+ }
10405
+ function tracePolyline(points, progress) {
10406
+ const amount2 = clampProgress2(progress);
10407
+ if (points.length === 0) return [];
10408
+ const lengths = pathLengths(points);
10409
+ if (amount2 === 1) return points.map(({ x, y }) => ({ x, y }));
10410
+ const traced = [{ x: points[0].x, y: points[0].y }];
10411
+ if (amount2 === 0 || lengths.length === 0) return traced;
10412
+ const total = lengths.reduce((sum, length) => sum + length, 0);
10413
+ if (total === 0) return traced;
10414
+ const target = total * amount2;
10415
+ let travelled = 0;
10416
+ for (let index = 0; index < lengths.length; index += 1) {
10417
+ const segmentLength = lengths[index];
10418
+ const next = points[index + 1];
10419
+ if (segmentLength === 0) continue;
10420
+ const segmentEnd = travelled + segmentLength;
10421
+ if (target >= segmentEnd) {
10422
+ traced.push({ x: next.x, y: next.y });
10423
+ travelled = segmentEnd;
10424
+ continue;
10425
+ }
10426
+ const segmentProgress = (target - travelled) / segmentLength;
10427
+ const point = interpolate(points[index], next, segmentProgress);
10428
+ assertPoint(point, "Polyline trace result");
10429
+ const previous = traced[traced.length - 1];
10430
+ if (point.x !== previous.x || point.y !== previous.y) traced.push(point);
10431
+ return traced;
10432
+ }
10433
+ return traced;
10434
+ }
10435
+ function pointAlongPath(points, progress) {
10436
+ if (points.length === 0) throw new Error("Cannot find a point along an empty path");
10437
+ const traced = tracePolyline(points, progress);
10438
+ return { ...traced[traced.length - 1] };
10439
+ }
10440
+
10441
+ // src/canvas-components.ts
10442
+ function finite(value, name) {
10443
+ if (!Number.isFinite(value)) throw new Error(`${name} must be finite`);
10444
+ }
10445
+ function nonnegative(value, name) {
10446
+ finite(value, name);
10447
+ if (value < 0) throw new Error(`${name} must be nonnegative`);
10448
+ }
10449
+ function positive(value, name) {
10450
+ finite(value, name);
10451
+ if (value <= 0) throw new Error(`${name} must be positive`);
10452
+ }
10453
+ function normalizedOpacity(value, name = "Canvas opacity") {
10454
+ finite(value, name);
10455
+ return Math.max(0, Math.min(1, value));
10456
+ }
10457
+ function validateBounds(bounds2) {
10458
+ finite(bounds2.x, "Canvas x");
10459
+ finite(bounds2.y, "Canvas y");
10460
+ positive(bounds2.width, "Canvas width");
10461
+ positive(bounds2.height, "Canvas height");
10462
+ nonnegative(bounds2.radius ?? 14, "Canvas radius");
10463
+ }
10464
+ function layoutTokenRow(values, options = {}) {
10465
+ const { advance = 24, gap = 16, minWidth = 64, paddingX = 17, width } = options;
10466
+ nonnegative(advance, "Token advance");
10467
+ nonnegative(gap, "Token gap");
10468
+ positive(minWidth, "Token minimum width");
10469
+ nonnegative(paddingX, "Token horizontal padding");
10470
+ if (width !== void 0) positive(width, "Token width");
10471
+ if (options.x !== void 0) finite(options.x, "Token x");
10472
+ if (options.centerX !== void 0) finite(options.centerX, "Token center x");
10473
+ const items = values.map((value) => {
10474
+ const text = String(value);
10475
+ return { text, x: 0, width: width ?? Math.max(minWidth, text.length * advance + 2 * paddingX) };
10476
+ });
10477
+ const totalWidth = items.reduce((total, item) => total + item.width, 0) + Math.max(0, items.length - 1) * gap;
10478
+ let x = options.x ?? (options.centerX ?? 0) - totalWidth / 2;
10479
+ finite(x, "Token row origin");
10480
+ for (const item of items) {
10481
+ item.x = x;
10482
+ x += item.width + gap;
10483
+ finite(x, "Token row extent");
10484
+ }
10485
+ return items;
10486
+ }
10487
+ function createCanvasComponents(painter) {
10488
+ function fade(alpha2, draw) {
10489
+ const amount2 = normalizedOpacity(alpha2);
10490
+ if (amount2 > 0) painter.opacity(amount2, draw);
10491
+ }
10492
+ function panel(options, draw) {
10493
+ validateBounds(options);
10494
+ const { x, y, width, height, fill, stroke, radius = 14, padding = 10, id, scope = "container", opacity = 1 } = options;
10495
+ nonnegative(padding, "Canvas padding");
10496
+ const alpha2 = normalizedOpacity(opacity);
10497
+ if (scope !== "container" && scope !== "label") throw new Error("Canvas scope must be container or label");
10498
+ let shape;
10499
+ painter.opacity(alpha2, () => {
10500
+ shape = painter.rect(x, y, width, height, fill, stroke, radius);
10501
+ if (draw) {
10502
+ const bounds2 = { x, y, width, height, radius };
10503
+ const scopeOptions = { padding, id };
10504
+ if (scope === "label") painter.labelScope(bounds2, draw, scopeOptions);
10505
+ else painter.container(bounds2, draw, scopeOptions);
10506
+ }
10507
+ });
10508
+ return shape;
10509
+ }
10510
+ function card(options) {
10511
+ const { label, x, y, width, height, fontSize = 32, font = "sans", textColor, baselineOffset = fontSize * 0.34, labelOpacity = 1 } = options;
10512
+ positive(fontSize, "Canvas font size");
10513
+ finite(baselineOffset, "Canvas text baseline offset");
10514
+ const labelAlpha = normalizedOpacity(labelOpacity, "Canvas label opacity");
10515
+ return panel(options, () => {
10516
+ fade(labelAlpha, () => {
10517
+ painter.text(String(label), x + width / 2, y + height / 2 + baselineOffset, fontSize, textColor, "center", font);
10518
+ });
10519
+ });
10520
+ }
10521
+ function matrix(options) {
10522
+ const { values, x, y, cellSize = 112, gap = 8, inset = 0, format = String, style = {}, cellStyle } = options;
10523
+ finite(x, "Matrix x");
10524
+ finite(y, "Matrix y");
10525
+ positive(cellSize, "Matrix cell size");
10526
+ nonnegative(gap, "Matrix gap");
10527
+ finite(inset, "Matrix inset");
10528
+ if (gap >= cellSize) throw new Error("Matrix gap must be smaller than cell size");
10529
+ const columns = values[0]?.length ?? 0;
10530
+ for (const row of values) {
10531
+ if (!Array.isArray(row) || row.length !== columns) throw new Error("Canvas matrix rows must be rectangular");
10532
+ }
10533
+ const shapes = [];
10534
+ for (let row = 0; row < values.length; row += 1) {
10535
+ for (let column = 0; column < columns; column += 1) {
10536
+ const value = values[row][column];
10537
+ const cell = { ...style, ...cellStyle?.(value, row, column) };
10538
+ finite(cell.opacity ?? 1, "Canvas opacity");
10539
+ if ((cell.opacity ?? 1) <= 0) continue;
10540
+ const shape = card({
10541
+ ...cell,
10542
+ x: x + column * cellSize + inset,
10543
+ y: y + row * cellSize + inset,
10544
+ width: cellSize - gap,
10545
+ height: cellSize - gap,
10546
+ label: format(value, row, column)
10547
+ });
10548
+ shapes.push(shape);
10549
+ }
10550
+ }
10551
+ return shapes;
10552
+ }
10553
+ function tokenRow(options) {
10554
+ const { values, y, height = 68, reveal = 1, opacity = 1, ...style } = options;
10555
+ finite(y, "Token row y");
10556
+ positive(height, "Token height");
10557
+ finite(reveal, "Token reveal");
10558
+ const alpha2 = normalizedOpacity(opacity);
10559
+ const items = layoutTokenRow(values, options);
10560
+ const shapes = [];
10561
+ for (let index = 0; index < items.length; index += 1) {
10562
+ const amount2 = Math.max(0, Math.min(1, reveal * items.length - index)) * alpha2;
10563
+ if (amount2 <= 0) continue;
10564
+ const { text: label, x, width } = items[index];
10565
+ const shape = card({ ...style, label, x, y, width, height, opacity: amount2 });
10566
+ shapes.push(shape);
10567
+ }
10568
+ return shapes;
10569
+ }
10570
+ function particle(options) {
10571
+ const { points, progress, radius = 9, fill, stroke, strokeWidth = 3 } = options;
10572
+ finite(progress, "Particle progress");
10573
+ positive(radius, "Particle radius");
10574
+ nonnegative(strokeWidth, "Particle stroke width");
10575
+ if (progress <= 0 || progress >= 1) return null;
10576
+ const point = pointAlongPath(points, progress);
10577
+ painter.circle(point.x, point.y, radius, fill, stroke, strokeWidth);
10578
+ return point;
10579
+ }
10580
+ return { panel, card, matrix, tokenRow, particle, fade };
10581
+ }
10582
+
10583
+ // src/teaching-transfer.ts
10584
+ function nonnegative2(value, name) {
10585
+ if (!Number.isFinite(value) || value < 0) throw new Error(`${name} must be finite and nonnegative`);
10586
+ }
10587
+ function alpha(value) {
10588
+ if (!Number.isFinite(value)) throw new Error("Transfer opacity must be finite");
10589
+ return Math.max(0, Math.min(1, value));
10590
+ }
10591
+ function bounds(shape) {
10592
+ if (![shape.x, shape.y, shape.width, shape.height].every(Number.isFinite) || shape.width <= 0 || shape.height <= 0) {
10593
+ throw new Error("Transfer endpoints require finite positive rectangular bounds");
10594
+ }
10595
+ nonnegative2(shape.radius ?? 0, "Transfer corner radius");
10596
+ }
10597
+ function center(shape) {
10598
+ return { x: shape.x + shape.width / 2, y: shape.y + shape.height / 2 };
10599
+ }
10600
+ function edgeDistance(shape, ux, uy) {
10601
+ const halfWidth = shape.width / 2, halfHeight = shape.height / 2;
10602
+ const limit = Math.min(ux === 0 ? Infinity : halfWidth / Math.abs(ux), uy === 0 ? Infinity : halfHeight / Math.abs(uy));
10603
+ const radius = Math.min(shape.radius ?? 0, halfWidth, halfHeight);
10604
+ if (radius === 0) return limit;
10605
+ const outside = (distance) => Math.hypot(
10606
+ Math.max(0, Math.abs(ux * distance) - (halfWidth - radius)),
10607
+ Math.max(0, Math.abs(uy * distance) - (halfHeight - radius))
10608
+ ) > radius;
10609
+ if (!outside(limit)) return limit;
10610
+ let low = 0, high = limit;
10611
+ for (let index = 0; index < 32; index += 1) {
10612
+ const middle = (low + high) / 2;
10613
+ if (outside(middle)) high = middle;
10614
+ else low = middle;
10615
+ }
10616
+ return low;
10617
+ }
10618
+ function safeGap(shape, ux, uy, clearance, edge) {
10619
+ const expanded = Math.min(
10620
+ ux === 0 ? Infinity : (shape.width / 2 + clearance) / Math.abs(ux),
10621
+ uy === 0 ? Infinity : (shape.height / 2 + clearance) / Math.abs(uy)
10622
+ );
10623
+ return expanded - edge;
10624
+ }
10625
+ function createTeachingTransfer(painter) {
10626
+ return (options) => {
10627
+ const { source, target, color = "#63DEEC", width = 3, margin = 2, progress, particle } = options;
10628
+ bounds(source.shape);
10629
+ bounds(target.shape);
10630
+ nonnegative2(width, "Transfer stroke width");
10631
+ if (width === 0) throw new Error("Transfer stroke width must be positive");
10632
+ nonnegative2(margin, "Transfer margin");
10633
+ const opacity = Math.min(alpha(source.opacity), alpha(target.opacity), alpha(options.opacity ?? 1));
10634
+ for (const gap of [options.gap, options.fromGap, options.toGap]) {
10635
+ if (gap !== void 0) nonnegative2(gap, "Transfer gap");
10636
+ }
10637
+ if (progress !== void 0 && !Number.isFinite(progress)) throw new Error("Transfer progress must be finite");
10638
+ if (particle && progress === void 0) throw new Error("Transfer particle requires progress");
10639
+ const radius = particle?.radius ?? 7, strokeWidth = particle?.strokeWidth ?? 3;
10640
+ nonnegative2(radius, "Transfer particle radius");
10641
+ if (radius === 0) throw new Error("Transfer particle radius must be positive");
10642
+ nonnegative2(strokeWidth, "Transfer particle stroke width");
10643
+ if (opacity === 0) return null;
10644
+ const a = center(source.shape), z = center(target.shape);
10645
+ const distance = Math.hypot(z.x - a.x, z.y - a.y);
10646
+ if (!Number.isFinite(distance) || distance === 0) throw new Error("Transfer endpoints must have distinct finite centers");
10647
+ const ux = (z.x - a.x) / distance, uy = (z.y - a.y) / distance;
10648
+ const sourceEdge = edgeDistance(source.shape, ux, uy), targetEdge = edgeDistance(target.shape, ux, uy);
10649
+ const markerRadius = progress === void 0 ? 0 : radius + (particle?.stroke ? strokeWidth / 2 : 0);
10650
+ const clearance = Math.max(width / 2, markerRadius) + margin;
10651
+ const fromGap = Math.max(options.fromGap ?? options.gap ?? 0, safeGap(source.shape, ux, uy, clearance, sourceEdge));
10652
+ const toGap = Math.max(options.toGap ?? options.gap ?? 0, safeGap(target.shape, ux, uy, clearance, targetEdge));
10653
+ if (distance <= sourceEdge + targetEdge + fromGap + toGap) throw new Error("Transfer endpoints leave no room for the requested clearance");
10654
+ let route;
10655
+ painter.opacity(opacity, () => {
10656
+ route = painter.connect(source.shape, target.shape, { color, width, fromGap, toGap });
10657
+ if (progress !== void 0 && progress > 0 && progress < 1) {
10658
+ const x = route.from.x * (1 - progress) + route.to.x * progress;
10659
+ const y = route.from.y * (1 - progress) + route.to.y * progress;
10660
+ painter.circle(x, y, radius, particle?.fill ?? color, particle?.stroke, strokeWidth);
10661
+ }
10662
+ });
10663
+ return route;
10664
+ };
10665
+ }
10666
+
10667
+ // src/teaching-grid.ts
10668
+ function positive2(value, name) {
10669
+ if (!Number.isFinite(value) || value <= 0) throw new Error(`${name} must be finite and positive`);
10670
+ }
10671
+ function layoutCellGrid(options) {
10672
+ const { x, y, width, height, rows, columns } = options;
10673
+ if (![x, y, x + width, y + height].every(Number.isFinite)) throw new Error("Grid bounds must be finite");
10674
+ positive2(width, "Grid width");
10675
+ positive2(height, "Grid height");
10676
+ if (![rows, columns, rows * columns].every(Number.isSafeInteger) || rows <= 0 || columns <= 0) {
10677
+ throw new Error("Grid rows and columns must be positive safe integers");
10678
+ }
10679
+ const bounds2 = { x, y, width, height };
10680
+ const cells = Array.from({ length: rows }, (_, row) => Array.from({ length: columns }, (_2, column) => ({
10681
+ x: x + column * width / columns,
10682
+ y: y + row * height / rows,
10683
+ width: width / columns,
10684
+ height: height / rows
10685
+ })));
10686
+ return {
10687
+ bounds: bounds2,
10688
+ cells,
10689
+ cell(row, column) {
10690
+ if (!Number.isSafeInteger(row) || !Number.isSafeInteger(column) || row < 0 || row >= rows || column < 0 || column >= columns) {
10691
+ throw new Error("Grid cell index is outside the grid");
10692
+ }
10693
+ return cells[row][column];
10694
+ }
10695
+ };
10696
+ }
10697
+ function createTeachingGrid(painter) {
10698
+ const components = createCanvasComponents(painter);
10699
+ return (options) => {
10700
+ const layout = layoutCellGrid(options);
10701
+ const {
10702
+ x,
10703
+ y,
10704
+ width,
10705
+ height,
10706
+ rows,
10707
+ columns,
10708
+ fill = "#18283B",
10709
+ stroke = "#63DEEC",
10710
+ lineWidth = 1,
10711
+ labels,
10712
+ highlights = [],
10713
+ fontSize = 28,
10714
+ textColor = "#FFFFFF",
10715
+ padding = 4
10716
+ } = options;
10717
+ positive2(lineWidth, "Grid line width");
10718
+ if (lineWidth >= Math.min(width / columns, height / rows)) throw new Error("Grid line width must be smaller than a cell");
10719
+ positive2(fontSize, "Grid font size");
10720
+ if (!Number.isFinite(padding) || padding < 0) throw new Error("Grid padding must be finite and nonnegative");
10721
+ if (labels && (labels.length !== rows || labels.some((row) => row.length !== columns))) {
10722
+ throw new Error("Grid labels must match rows and columns");
10723
+ }
10724
+ for (const highlight of highlights) {
10725
+ layout.cell(highlight.row, highlight.column);
10726
+ if (!Number.isFinite(highlight.opacity ?? 1)) throw new Error("Grid highlight opacity must be finite");
10727
+ }
10728
+ const shape = components.panel({ ...layout.bounds, fill, stroke, radius: 0, padding: 0 }, () => {
10729
+ for (const highlight of highlights) {
10730
+ const cell = layout.cell(highlight.row, highlight.column);
10731
+ const inset2 = Math.min(2, cell.width / 4, cell.height / 4);
10732
+ components.fade(highlight.opacity ?? 1, () => {
10733
+ painter.rect(cell.x + inset2, cell.y + inset2, cell.width - 2 * inset2, cell.height - 2 * inset2, highlight.fill, highlight.stroke, 0);
10734
+ });
10735
+ }
10736
+ const inset = lineWidth / 2;
10737
+ for (let column = 1; column < columns; column += 1) {
10738
+ const left = x + column * width / columns;
10739
+ painter.path([{ x: left, y: y + inset }, { x: left, y: y + height - inset }], { color: stroke, width: lineWidth });
10740
+ }
10741
+ for (let row = 1; row < rows; row += 1) {
10742
+ const top = y + row * height / rows;
10743
+ painter.path([{ x: x + inset, y: top }, { x: x + width - inset, y: top }], { color: stroke, width: lineWidth });
10744
+ }
10745
+ labels?.forEach((row, r) => row.forEach((label, column) => {
10746
+ const cell = layout.cell(r, column), value = String(label);
10747
+ const baseline = cell.y + cell.height / 2 + fontSize * 0.34 - (value.split("\n").length - 1) * fontSize * 0.7;
10748
+ painter.labelScope(cell, () => painter.text(value, cell.x + cell.width / 2, baseline, fontSize, textColor, "center"), { padding });
10749
+ }));
10750
+ });
10751
+ return { ...layout, shape };
10752
+ };
10753
+ }
10754
+
10755
+ // src/teaching-timeline.ts
10756
+ function createTeachingTimeline(painter) {
10757
+ return (options) => {
10758
+ const {
10759
+ x,
10760
+ y,
10761
+ width,
10762
+ height,
10763
+ domain: [lo, hi],
10764
+ lanes,
10765
+ intervals,
10766
+ time = hi,
10767
+ ticks = [lo, hi],
10768
+ formatTime = String,
10769
+ labelWidth = 180,
10770
+ laneGap = 18,
10771
+ fontSize = 28,
10772
+ color = "#8D9CB9",
10773
+ trackColor = "#18283B",
10774
+ cursorColor = "#FFCE73"
10775
+ } = options;
10776
+ if (![x, y, x + width, y + height, lo, hi, hi - lo, time, labelWidth, laneGap, fontSize].every(Number.isFinite)) throw new Error("Timeline values must be finite");
10777
+ if (width <= 0 || height <= 0 || hi <= lo || time < lo || time > hi) throw new Error("Timeline needs positive bounds and a current time inside its increasing domain");
10778
+ if (fontSize <= 0 || labelWidth <= 12 || labelWidth >= width - 6 || laneGap < 0 || !lanes.length) throw new Error("Timeline needs positive label space, font size, and at least one lane");
10779
+ const ids = new Set(lanes.map((lane) => lane.id));
10780
+ if (ids.size !== lanes.length || lanes.some((lane) => !lane.id)) throw new Error("Timeline lane IDs must be nonempty and unique");
10781
+ const intervalIds = /* @__PURE__ */ new Set();
10782
+ for (const interval of intervals) {
10783
+ if (!interval.id || intervalIds.has(interval.id) || !ids.has(interval.lane)) throw new Error("Timeline intervals need unique IDs and an existing lane");
10784
+ intervalIds.add(interval.id);
10785
+ if (![interval.start, interval.end, interval.opacity ?? 1].every(Number.isFinite) || interval.start < lo || interval.end > hi || interval.end <= interval.start) throw new Error("Timeline intervals must have finite positive durations inside the domain");
10786
+ }
10787
+ for (const lane of lanes) {
10788
+ const ordered = intervals.filter((interval) => interval.lane === lane.id).sort((a, b) => a.start - b.start);
10789
+ if (ordered.some((interval, i) => i > 0 && interval.start < ordered[i - 1].end)) throw new Error(`Timeline intervals overlap in lane ${lane.id}; use separate lanes for concurrent work`);
10790
+ }
10791
+ if (ticks.some((tick) => !Number.isFinite(tick) || tick < lo || tick > hi)) throw new Error("Timeline ticks must lie inside the domain");
10792
+ const axisHeight = Math.max(36, fontSize * 2 + 18);
10793
+ const laneHeight = (height - axisHeight - (lanes.length - 1) * laneGap) / lanes.length;
10794
+ const labelHeight = fontSize * 1.5, barHeight = laneHeight - labelHeight;
10795
+ if (barHeight < 12) throw new Error("Timeline height cannot fit lane labels and interval bars");
10796
+ const left = x + labelWidth + 3, plotWidth = width - labelWidth - 6;
10797
+ const point = (value) => {
10798
+ if (!Number.isFinite(value) || value < lo || value > hi) throw new Error("Timeline point must lie inside the domain");
10799
+ return left + (value - lo) / (hi - lo) * plotWidth;
10800
+ };
10801
+ const bounds2 = { x, y, width, height };
10802
+ const result = { bounds: bounds2, time, point, lanes: /* @__PURE__ */ Object.create(null), intervals: /* @__PURE__ */ Object.create(null) };
10803
+ painter.container(bounds2, () => {
10804
+ lanes.forEach((lane, index) => {
10805
+ const top = y + index * (laneHeight + laneGap);
10806
+ const track = { x: left - 2, y: top + labelHeight, width: plotWidth + 4, height: barHeight };
10807
+ const shape = painter.rect(track.x, track.y, track.width, track.height, trackColor, color, 0);
10808
+ result.lanes[lane.id] = { shape, bounds: track };
10809
+ painter.labelScope({ x, y: top, width: labelWidth - 12, height: laneHeight }, () => {
10810
+ painter.text(lane.label, x, top + laneHeight / 2 + fontSize * 0.34, fontSize, color, "left");
10811
+ }, { padding: 0 });
10812
+ for (const interval of intervals.filter((item) => item.lane === lane.id)) {
10813
+ const visibleEnd = Math.max(interval.start, Math.min(time, interval.end));
10814
+ const elapsed = visibleEnd - interval.start;
10815
+ const bar = { x: point(interval.start), y: track.y + 2, width: point(visibleEnd) - point(interval.start), height: barHeight - 4 };
10816
+ const opacity = Math.max(0, Math.min(1, interval.opacity ?? 1));
10817
+ const item = { id: interval.id, shape: null, bounds: bar, elapsed, opacity, complete: time >= interval.end };
10818
+ result.intervals[interval.id] = item;
10819
+ if (elapsed === 0 || opacity === 0) continue;
10820
+ painter.opacity(opacity, () => {
10821
+ painter.container(track, () => {
10822
+ item.shape = painter.rect(bar.x, bar.y, bar.width, bar.height, interval.color ?? "#63DEEC", void 0, 0);
10823
+ }, { padding: 0 });
10824
+ if (interval.label) {
10825
+ const labelBounds = { x: point(interval.start), y: top, width: point(interval.end) - point(interval.start), height: labelHeight };
10826
+ painter.labelScope(labelBounds, () => painter.text(interval.label, labelBounds.x + labelBounds.width / 2, top + fontSize, fontSize, interval.color ?? "#63DEEC", "center"), { padding: 2 });
10827
+ }
10828
+ });
10829
+ }
10830
+ });
10831
+ const axisY = y + height - axisHeight + Math.max(10, fontSize * 0.5);
10832
+ painter.line(left, axisY, left + plotWidth, axisY, color, 2);
10833
+ for (const tick of ticks) {
10834
+ const px = point(tick);
10835
+ painter.line(px, axisY, px, axisY + 6, color, 2);
10836
+ painter.labelScope({ x: left - labelWidth, y: axisY + 8, width: plotWidth + labelWidth, height: fontSize * 1.5 }, () => {
10837
+ painter.text(formatTime(tick), px, axisY + fontSize * 1.4, fontSize, color, tick === hi ? "right" : tick === lo ? "left" : "center");
10838
+ }, { padding: 0 });
10839
+ }
10840
+ painter.line(point(time), axisY - 8, point(time), axisY + 8, cursorColor, 3);
10841
+ }, { padding: 0 });
10842
+ return result;
10843
+ };
10844
+ }
10845
+
10846
+ // src/teaching-allocation.ts
10847
+ var COLORS = ["#63DEEC", "#79A6FF", "#D6A0FF", "#FFCE73"];
10848
+ function layoutAllocation(options) {
10849
+ const { x, y, width, height, capacity, parts } = options;
10850
+ if (![x, y, x + width, y + height, capacity].every(Number.isFinite) || width <= 0 || height <= 0 || capacity <= 0) throw new Error("Allocation needs finite positive bounds and capacity");
10851
+ const ids = /* @__PURE__ */ new Set();
10852
+ let used = 0;
10853
+ for (const part of parts) {
10854
+ if (!part.id || ids.has(part.id)) throw new Error("Allocation part IDs must be nonempty and unique");
10855
+ ids.add(part.id);
10856
+ if (!Number.isFinite(part.value) || part.value < 0) throw new Error("Allocation values must be finite and nonnegative");
10857
+ used += part.value;
10858
+ }
10859
+ if (!Number.isFinite(used) || used - capacity > Number.EPSILON * Math.max(used, capacity) * 8) throw new Error("Allocation exceeds capacity");
10860
+ used = Math.min(used, capacity);
10861
+ let offset = 0;
10862
+ const segments = parts.map((part) => {
10863
+ const start = Math.min(offset, capacity);
10864
+ offset += part.value;
10865
+ return { id: part.id, value: part.value, bounds: { x: x + width * (start / capacity), y, width: width * ((Math.min(offset, capacity) - start) / capacity), height } };
10866
+ });
10867
+ const remaining = Math.max(0, capacity - used);
10868
+ return { bounds: { x, y, width, height }, used, remaining, parts: segments, freeBounds: { x: x + width * (used / capacity), y, width: width * (remaining / capacity), height } };
10869
+ }
10870
+ function createTeachingAllocation(painter) {
10871
+ return (options) => {
10872
+ const { x, y, width, height, fontSize = 28, unit = "", format = String, color = "#8D9CB9", trackColor = "#18283B" } = options;
10873
+ if (!Number.isFinite(fontSize) || fontSize <= 0) throw new Error("Allocation font size must be finite and positive");
10874
+ const header = fontSize * 1.7, barHeight = fontSize * 2, rowHeight = fontSize * 1.65, gap = fontSize * 0.6;
10875
+ if (height < header + barHeight + gap + (options.parts.length + 1) * rowHeight || width <= 6 || width * 0.67 <= fontSize) throw new Error("Allocation bounds cannot fit the strip and ledger");
10876
+ const layout = layoutAllocation({ ...options, x: x + 3, y: y + header + 3, width: width - 6, height: barHeight - 6 });
10877
+ const suffix = unit ? ` ${unit}` : "", shapes = [];
10878
+ let shape;
10879
+ painter.container({ x, y, width, height }, () => {
10880
+ painter.labelScope({ x, y, width, height: header }, () => painter.text(`Used ${format(layout.used)} / ${format(options.capacity)}${suffix}`, x, y + fontSize, fontSize, color, "left"), { padding: 0 });
10881
+ const strip = { x: x + 1, y: y + header + 1, width: width - 2, height: barHeight - 2 };
10882
+ shape = painter.rect(strip.x, strip.y, strip.width, strip.height, trackColor, color, 0);
10883
+ painter.container(strip, () => {
10884
+ layout.parts.forEach((part, index) => shapes.push(part.bounds.width === 0 ? null : painter.rect(part.bounds.x, part.bounds.y, part.bounds.width, part.bounds.height, options.parts[index].color ?? COLORS[index % COLORS.length], void 0, 0)));
10885
+ }, { padding: 0 });
10886
+ const rows = [...options.parts, { id: "free", label: "Free", value: layout.remaining, color }];
10887
+ rows.forEach((part, index) => {
10888
+ const top = y + header + barHeight + gap + index * rowHeight, baseline = top + rowHeight / 2 + fontSize * 0.34;
10889
+ painter.rect(x, top + (rowHeight - fontSize * 0.6) / 2, fontSize * 0.6, fontSize * 0.6, part.color ?? COLORS[index % COLORS.length], void 0, 0);
10890
+ painter.labelScope({ x: x + fontSize, y: top, width: width * 0.67 - fontSize, height: rowHeight }, () => painter.text(part.label, x + fontSize, baseline, fontSize, color, "left"), { padding: 0 });
10891
+ painter.labelScope({ x: x + width * 0.7, y: top, width: width * 0.3, height: rowHeight }, () => painter.text(`${format(part.value)}${suffix}`, x + width, baseline, fontSize, color, "right"), { padding: 0 });
10892
+ });
10893
+ }, { padding: 0 });
10894
+ return { ...layout, shapes, shape };
10895
+ };
10896
+ }
10897
+
10898
+ // src/teaching-canvas.ts
10899
+ var INK = "#8D9CB9";
10900
+ var ACCENT = "#63DEEC";
10901
+ var PANEL = "#18283B";
10902
+ function finite2(value, name) {
10903
+ if (!Number.isFinite(value)) throw new Error(`${name} must be finite`);
10904
+ }
10905
+ function positive3(value, name) {
10906
+ finite2(value, name);
10907
+ if (value <= 0) throw new Error(`${name} must be positive`);
10908
+ }
10909
+ function boundsOf(options) {
10910
+ finite2(options.x, "Teaching x");
10911
+ finite2(options.y, "Teaching y");
10912
+ positive3(options.width, "Teaching width");
10913
+ positive3(options.height, "Teaching height");
10914
+ return { x: options.x, y: options.y, width: options.width, height: options.height };
10915
+ }
10916
+ function amount(value, name = "Teaching progress") {
10917
+ finite2(value, name);
10918
+ return Math.max(0, Math.min(1, value));
10919
+ }
10920
+ function domainOf(domain, name) {
10921
+ finite2(domain[0], `${name} start`);
10922
+ finite2(domain[1], `${name} end`);
10923
+ if (domain[1] <= domain[0] || !Number.isFinite(domain[1] - domain[0])) {
10924
+ throw new Error(`${name} must have a finite positive span`);
10925
+ }
10926
+ return [domain[0], domain[1]];
10927
+ }
10928
+ function createTeachingCanvas(painter) {
10929
+ const components = createCanvasComponents(painter);
10930
+ function axes(options) {
10931
+ let bounds2 = boundsOf(options);
10932
+ const xDomain = domainOf(options.xDomain, "Plot x domain");
10933
+ const yDomain = domainOf(options.yDomain, "Plot y domain");
10934
+ if (options.equalUnits) {
10935
+ const xSpan = xDomain[1] - xDomain[0];
10936
+ const ySpan = yDomain[1] - yDomain[0];
10937
+ const pixelsPerUnit = Math.min(bounds2.width / xSpan, bounds2.height / ySpan);
10938
+ const width2 = xSpan * pixelsPerUnit;
10939
+ const height2 = ySpan * pixelsPerUnit;
10940
+ bounds2 = boundsOf({
10941
+ x: bounds2.x + (bounds2.width - width2) / 2,
10942
+ y: bounds2.y + (bounds2.height - height2) / 2,
10943
+ width: width2,
10944
+ height: height2
10945
+ });
10946
+ }
10947
+ const { x, y, width, height } = bounds2;
10948
+ const { color = INK, gridColor, fontSize = 28, xTicks = [], yTicks = [], formatX = String, formatY = String } = options;
10949
+ positive3(fontSize, "Axis font size");
10950
+ xTicks.forEach((tick) => finite2(tick, "Axis x tick"));
10951
+ yTicks.forEach((tick) => finite2(tick, "Axis y tick"));
10952
+ const plot = {
10953
+ bounds: bounds2,
10954
+ xDomain,
10955
+ yDomain,
10956
+ point(px, py) {
10957
+ finite2(px, "Plot point x");
10958
+ finite2(py, "Plot point y");
10959
+ const point = {
10960
+ x: x + (px - xDomain[0]) / (xDomain[1] - xDomain[0]) * width,
10961
+ y: y + height - (py - yDomain[0]) / (yDomain[1] - yDomain[0]) * height
10962
+ };
10963
+ finite2(point.x, "Mapped point x");
10964
+ finite2(point.y, "Mapped point y");
10965
+ return point;
10966
+ }
10967
+ };
10968
+ for (const tick of xTicks) {
10969
+ if (tick < xDomain[0] || tick > xDomain[1]) continue;
10970
+ const point = plot.point(tick, yDomain[0]);
10971
+ if (gridColor) painter.path([{ x: point.x, y }, { x: point.x, y: y + height }], { color: gridColor, width: 1, clip: bounds2 });
10972
+ painter.line(point.x, y + height, point.x, y + height + 7, color, 2);
10973
+ painter.text(formatX(tick), point.x, y + height + 36, fontSize, color, "center");
10974
+ }
10975
+ for (const tick of yTicks) {
10976
+ if (tick < yDomain[0] || tick > yDomain[1]) continue;
10977
+ const point = plot.point(xDomain[0], tick);
10978
+ if (gridColor) painter.path([{ x, y: point.y }, { x: x + width, y: point.y }], { color: gridColor, width: 1, clip: bounds2 });
10979
+ painter.line(x - 7, point.y, x, point.y, color, 2);
10980
+ painter.text(formatY(tick), x - 18, point.y + 9, fontSize, color, "right");
10981
+ }
10982
+ painter.line(x, y + height, x + width, y + height, color, 2);
10983
+ painter.line(x, y, x, y + height, color, 2);
10984
+ if (options.xLabel) painter.text(options.xLabel, x + width / 2, y + height + 72, 30, color, "center");
10985
+ if (options.yLabel) painter.text(options.yLabel, x, y - 26, 30, color, "left");
10986
+ return plot;
10987
+ }
10988
+ function curve(options) {
10989
+ const { plot, points, color, width = 4, progress = 1 } = options;
10990
+ positive3(width, "Curve width");
10991
+ const mapped = points.map((point) => plot.point(point.x, point.y));
10992
+ const visible = tracePolyline(mapped, progress);
10993
+ if (visible.length > 1) painter.path(visible, { color, width, clip: plot.bounds });
10994
+ return visible;
10995
+ }
10996
+ function scatter(options) {
10997
+ const { plot, points, color = ACCENT, radius = 7, opacity = 1 } = options;
10998
+ positive3(radius, "Scatter radius");
10999
+ const alpha2 = amount(opacity, "Scatter opacity");
11000
+ const projected = points.map((point) => {
11001
+ positive3(point.radius ?? radius, "Scatter point radius");
11002
+ return {
11003
+ ...plot.point(point.x, point.y),
11004
+ radius: point.radius ?? radius,
11005
+ color: point.color ?? color,
11006
+ inDomain: point.x >= plot.xDomain[0] && point.x <= plot.xDomain[1] && point.y >= plot.yDomain[0] && point.y <= plot.yDomain[1]
11007
+ };
11008
+ });
11009
+ const shapes = [];
11010
+ if (alpha2 === 0) return shapes;
11011
+ painter.opacity(alpha2, () => {
11012
+ for (const point of projected) {
11013
+ if (!point.inDomain) continue;
11014
+ shapes.push(painter.circle(point.x, point.y, point.radius, point.color));
11015
+ }
11016
+ });
11017
+ return shapes;
11018
+ }
11019
+ function bars(options) {
11020
+ const bounds2 = boundsOf(options);
11021
+ const { x, y, width, height } = bounds2;
11022
+ const { values, labels, colors: colors2, color = ACCENT, progress = 1, showValues = false, format = String, fontSize = 28, gap = 20 } = options;
11023
+ positive3(fontSize, "Bar font size");
11024
+ finite2(gap, "Bar gap");
11025
+ if (gap < 0) throw new Error("Bar gap must be nonnegative");
11026
+ values.forEach((value) => {
11027
+ finite2(value, "Bar value");
11028
+ if (value < 0) throw new Error("Bar values must be nonnegative");
11029
+ });
11030
+ if (labels && labels.length !== values.length) throw new Error("Bar labels must match values");
11031
+ if (colors2 && colors2.length !== values.length) throw new Error("Bar colors must match values");
11032
+ const maximumValue = values.reduce((maximum2, value) => Math.max(maximum2, value), 0);
11033
+ const maximum = options.max ?? (maximumValue || 1);
11034
+ positive3(maximum, "Bar maximum");
11035
+ if (maximum < maximumValue) throw new Error("Bar maximum must contain every value");
11036
+ const reveal = amount(progress);
11037
+ if (!values.length) return { bars: [], slots: [], bounds: bounds2 };
11038
+ const barWidth = (width - gap * (values.length - 1)) / values.length;
11039
+ positive3(barWidth, "Bar width after gaps");
11040
+ const shapes = [];
11041
+ const slots = [];
11042
+ values.forEach((value, index) => {
11043
+ const left = x + index * (barWidth + gap);
11044
+ const barHeight = value / maximum * height * reveal;
11045
+ slots.push({ x: left, y, width: barWidth, height });
11046
+ shapes.push(barHeight > 0 ? painter.rect(left, y + height - barHeight, barWidth, barHeight, colors2?.[index] ?? color, void 0, Math.min(8, barWidth / 2, barHeight / 2)) : null);
11047
+ if (labels) painter.text(labels[index], left + barWidth / 2, y + height + 38, fontSize, INK, "center");
11048
+ if (showValues && reveal > 0) painter.text(format(value), left + barWidth / 2, y + height - barHeight - 14, fontSize, colors2?.[index] ?? color, "center");
11049
+ });
11050
+ return { bars: shapes, slots, bounds: bounds2 };
11051
+ }
11052
+ function flowGraph(options) {
11053
+ const { nodes, edges, stroke = ACCENT, fill = PANEL, textColor = "#FFFFFF", padding = 12 } = options;
11054
+ finite2(padding, "Flow node padding");
11055
+ if (padding < 0) throw new Error("Flow node padding must be nonnegative");
11056
+ const descriptors = /* @__PURE__ */ Object.create(null);
11057
+ for (const node of nodes) {
11058
+ if (!node.id || Object.hasOwn(descriptors, node.id)) throw new Error("Flow node IDs must be nonempty and unique");
11059
+ const bounds2 = boundsOf(node);
11060
+ positive3(node.fontSize ?? 30, "Flow node font size");
11061
+ finite2(node.radius ?? 14, "Flow node radius");
11062
+ if ((node.radius ?? 14) < 0) throw new Error("Flow node radius must be nonnegative");
11063
+ descriptors[node.id] = { ...bounds2, radius: node.radius ?? 14 };
11064
+ }
11065
+ for (const edge of edges) {
11066
+ if (!Object.hasOwn(descriptors, edge.from) || !Object.hasOwn(descriptors, edge.to)) throw new Error("Flow edge must reference existing nodes");
11067
+ if (edge.from === edge.to) throw new Error("Flow edges must connect distinct nodes");
11068
+ if (edge.progress !== void 0) amount(edge.progress);
11069
+ if (edge.width !== void 0) positive3(edge.width, "Flow edge width");
11070
+ for (const gap of [edge.gap, edge.fromGap, edge.toGap]) {
11071
+ if (gap !== void 0) finite2(gap, "Flow edge gap");
11072
+ }
11073
+ }
11074
+ const routes = edges.map((edge) => {
11075
+ const { from, to, progress, ...style } = edge;
11076
+ const route = painter.connect(descriptors[from], descriptors[to], { color: stroke, ...style });
11077
+ if (progress !== void 0) components.particle({ points: [route.from, route.to], progress, radius: 7, fill: style.color ?? stroke });
11078
+ return route;
11079
+ });
11080
+ for (const node of nodes) {
11081
+ const shape = components.card({
11082
+ ...descriptors[node.id],
11083
+ label: node.label,
11084
+ id: node.id,
11085
+ fill: node.fill ?? fill,
11086
+ stroke: node.color ?? stroke,
11087
+ textColor,
11088
+ fontSize: node.fontSize ?? 30,
11089
+ padding
11090
+ });
11091
+ Object.assign(descriptors[node.id], shape);
11092
+ }
11093
+ return { nodes: descriptors, routes };
11094
+ }
11095
+ return { axes, curve, scatter, bars, flowGraph, transfer: createTeachingTransfer(painter), grid: createTeachingGrid(painter), timeline: createTeachingTimeline(painter), allocation: createTeachingAllocation(painter) };
11096
+ }
11097
+
11098
+ // src/teaching-math.ts
11099
+ function finite3(value, name) {
11100
+ if (!Number.isFinite(value)) throw new Error(`${name} must be finite`);
11101
+ }
11102
+ function finiteValues(values, name) {
11103
+ values.forEach((value) => finite3(value, name));
11104
+ }
11105
+ function seededRandom(seed) {
11106
+ if (!Number.isSafeInteger(seed)) throw new Error("Random seed must be a safe integer");
11107
+ let state = seed >>> 0;
11108
+ return () => {
11109
+ state = state + 1831565813 >>> 0;
11110
+ let value = Math.imul(state ^ state >>> 15, 1 | state);
11111
+ value ^= value + Math.imul(value ^ value >>> 7, 61 | value);
11112
+ return ((value ^ value >>> 14) >>> 0) / 4294967296;
11113
+ };
11114
+ }
11115
+ function lerpArray(from, to, progress) {
11116
+ if (from.length !== to.length) throw new Error("Interpolation vectors must have equal lengths");
11117
+ finite3(progress, "Interpolation progress");
11118
+ finiteValues(from, "Interpolation value");
11119
+ finiteValues(to, "Interpolation value");
11120
+ const result = from.map((value, index) => {
11121
+ const end = to[index];
11122
+ const blended = value * (1 - progress) + end * progress;
11123
+ if (Number.isFinite(blended)) return blended;
11124
+ const scale = Math.max(Math.abs(value), Math.abs(end));
11125
+ return (value / scale + (end / scale - value / scale) * progress) * scale;
11126
+ });
11127
+ finiteValues(result, "Interpolation result");
11128
+ return result;
11129
+ }
11130
+ function dotProduct(left, right) {
11131
+ if (left.length !== right.length) throw new Error("Dot product vectors must have equal lengths");
11132
+ finiteValues(left, "Dot product value");
11133
+ finiteValues(right, "Dot product value");
11134
+ const result = left.reduce((sum, value, index) => sum + value * right[index], 0);
11135
+ finite3(result, "Dot product result");
11136
+ return result;
11137
+ }
11138
+ function matrixWidth(matrix, name) {
11139
+ const width = matrix[0]?.length ?? 0;
11140
+ for (const row of matrix) {
11141
+ if (row.length !== width) throw new Error(`${name} rows must be rectangular`);
11142
+ finiteValues(row, `${name} value`);
11143
+ }
11144
+ return width;
11145
+ }
11146
+ function multiplyMatrices(left, right) {
11147
+ const inner = matrixWidth(left, "Left matrix");
11148
+ const columns = matrixWidth(right, "Right matrix");
11149
+ if (inner !== right.length) throw new Error("Matrix inner dimensions must match");
11150
+ return left.map((row) => Array.from({ length: columns }, (_, column) => {
11151
+ const result = row.reduce((sum, value, index) => sum + value * right[index][column], 0);
11152
+ finite3(result, "Matrix product value");
11153
+ return result;
11154
+ }));
11155
+ }
11156
+ function stableSoftmax(values, temperature = 1) {
11157
+ finite3(temperature, "Softmax temperature");
11158
+ if (temperature <= 0) throw new Error("Softmax temperature must be positive");
11159
+ finiteValues(values, "Softmax logit");
11160
+ if (!values.length) return [];
11161
+ const maximum = values.reduce((largest, value) => Math.max(largest, value), -Infinity);
11162
+ const weights = values.map((value) => Math.exp((value - maximum) / temperature));
11163
+ const total = weights.reduce((sum, value) => sum + value, 0);
11164
+ return weights.map((value) => value / total);
11165
+ }
11166
+ function entropy(probabilities, base = 2) {
11167
+ finite3(base, "Entropy base");
11168
+ if (base <= 0 || base === 1) throw new Error("Entropy base must be positive and different from one");
11169
+ finiteValues(probabilities, "Entropy probability");
11170
+ if (!probabilities.length) return 0;
11171
+ if (probabilities.some((value) => value < 0 || value > 1)) {
11172
+ throw new Error("Entropy probabilities must lie between zero and one");
11173
+ }
11174
+ const total = probabilities.reduce((sum, value) => sum + value, 0);
11175
+ if (Math.abs(total - 1) > 1e-9) throw new Error("Entropy probabilities must sum to one");
11176
+ return -probabilities.reduce((sum, value) => value === 0 ? sum : sum + value * Math.log(value), 0) / Math.log(base);
11177
+ }
11178
+ function normalizeVector(values) {
11179
+ finiteValues(values, "Vector value");
11180
+ const scale = values.reduce((largest, value) => Math.max(largest, Math.abs(value)), 0);
11181
+ if (scale === 0) return values.map(() => 0);
11182
+ const scaled = values.map((value) => value / scale);
11183
+ const length = Math.sqrt(scaled.reduce((sum, value) => sum + value * value, 0));
11184
+ return scaled.map((value) => value / length);
11185
+ }
11186
+ function sampleFunction(fn, low, high, count = 100) {
11187
+ finite3(low, "Sample domain start");
11188
+ finite3(high, "Sample domain end");
11189
+ if (high <= low) throw new Error("Sample domain must increase");
11190
+ if (!Number.isSafeInteger(count) || count < 2) throw new Error("Sample count must be an integer of at least two");
11191
+ return Array.from({ length: count }, (_, index) => {
11192
+ const amount2 = index / (count - 1);
11193
+ const x = low * (1 - amount2) + high * amount2;
11194
+ const y = fn(x);
11195
+ finite3(y, "Sampled function value");
11196
+ return { x, y };
11197
+ });
11198
+ }
11199
+ function gaussian(mean, sigma, x) {
11200
+ finite3(mean, "Gaussian mean");
11201
+ finite3(sigma, "Gaussian standard deviation");
11202
+ finite3(x, "Gaussian x");
11203
+ if (sigma <= 0) throw new Error("Gaussian standard deviation must be positive");
11204
+ const z = (x - mean) / sigma;
11205
+ const density = Math.exp(-0.5 * z * z) / sigma / Math.sqrt(2 * Math.PI);
11206
+ finite3(density, "Gaussian density");
11207
+ return density;
11208
+ }
11209
+ function sampleGaussian(random) {
11210
+ const first = random();
11211
+ const second = random();
11212
+ if (!Number.isFinite(first) || !Number.isFinite(second) || first < 0 || first >= 1 || second < 0 || second >= 1) {
11213
+ throw new Error("Gaussian random draws must lie in [0, 1)");
11214
+ }
11215
+ return Math.sqrt(-2 * Math.log(1 - first)) * Math.cos(2 * Math.PI * second);
11216
+ }
11217
+
11218
+ // src/teaching-cues.ts
11219
+ function position(beat, progress) {
11220
+ if (!Number.isSafeInteger(beat) || beat < 0) throw new Error("Cue beat must be a nonnegative safe integer");
11221
+ if (!Number.isFinite(progress) || progress < 0 || progress > 1) throw new Error("Cue progress must be between zero and one");
11222
+ if (progress === 1) {
11223
+ if (!Number.isSafeInteger(beat + 1)) throw new Error("Cue position exceeds the safe integer range");
11224
+ return { beat: beat + 1, beatP: 0 };
11225
+ }
11226
+ return { beat, beatP: progress };
11227
+ }
11228
+ function compare(left, right) {
11229
+ return left.beat === right.beat ? left.beatP - right.beatP : left.beat - right.beat;
11230
+ }
11231
+ function createCueTrack(options) {
11232
+ const ids = /* @__PURE__ */ new Set();
11233
+ const entry = ({ id, snapshot }) => {
11234
+ if (typeof id !== "string" || !id.trim() || ids.has(id)) throw new Error("Cue IDs must be nonempty and unique");
11235
+ ids.add(id);
11236
+ return Object.freeze({ id, snapshot });
11237
+ };
11238
+ const initial = entry(options.initial);
11239
+ const cues = options.cues.map((cue) => ({ position: position(cue.beat, cue.at), value: entry(cue) }));
11240
+ for (let index = 1; index < cues.length; index += 1) {
11241
+ if (compare(cues[index - 1].position, cues[index].position) >= 0) {
11242
+ throw new Error("Cue positions must be strictly increasing");
11243
+ }
11244
+ }
11245
+ return Object.freeze({
11246
+ sample(current) {
11247
+ const at = position(current.beat, current.beatP);
11248
+ let low = 0, high = cues.length;
11249
+ while (low < high) {
11250
+ const middle = Math.floor((low + high) / 2);
11251
+ if (compare(cues[middle].position, at) <= 0) low = middle + 1;
11252
+ else high = middle;
11253
+ }
11254
+ return low === 0 ? initial : cues[low - 1].value;
11255
+ }
11256
+ });
11257
+ }
11258
+
11259
+ // src/camera-motion.ts
11260
+ function clampProgress3(progress) {
11261
+ if (!Number.isFinite(progress)) throw new Error("Camera progress must be finite");
11262
+ return Math.max(0, Math.min(1, progress));
11263
+ }
11264
+ function assertCamera(camera, context) {
11265
+ if (!Number.isFinite(camera.x) || !Number.isFinite(camera.y)) {
11266
+ throw new Error(`${context} coordinates must be finite`);
11267
+ }
11268
+ if (!Number.isFinite(camera.zoom) || camera.zoom <= 0) {
11269
+ throw new Error(`${context} zoom must be finite and greater than zero`);
11270
+ }
11271
+ }
11272
+ function assertViewport(viewport) {
11273
+ if (!Number.isFinite(viewport.width) || viewport.width <= 0) {
11274
+ throw new Error("Camera viewport width must be finite and greater than zero");
11275
+ }
11276
+ if (!Number.isFinite(viewport.height) || viewport.height <= 0) {
11277
+ throw new Error("Camera viewport height must be finite and greater than zero");
11278
+ }
11279
+ }
11280
+ function assertZoomConstraints(options) {
11281
+ const { minZoom, maxZoom } = options;
11282
+ if (minZoom !== void 0 && (!Number.isFinite(minZoom) || minZoom <= 0)) {
11283
+ throw new Error("Camera minZoom must be finite and greater than zero");
11284
+ }
11285
+ if (maxZoom !== void 0 && (!Number.isFinite(maxZoom) || maxZoom <= 0)) {
11286
+ throw new Error("Camera maxZoom must be finite and greater than zero");
11287
+ }
11288
+ if (minZoom !== void 0 && maxZoom !== void 0 && minZoom > maxZoom) {
11289
+ throw new Error("Camera minZoom cannot exceed maxZoom");
11290
+ }
11291
+ }
11292
+ function assertZoomInRange(camera, options) {
11293
+ if (options.minZoom !== void 0 && camera.zoom < options.minZoom || options.maxZoom !== void 0 && camera.zoom > options.maxZoom) {
11294
+ throw new Error("Camera zoom is outside the configured range");
11295
+ }
11296
+ }
11297
+ function interpolateLinear(from, to, progress) {
11298
+ return from * (1 - progress) + to * progress;
11299
+ }
11300
+ function interpolateCamera(from, to, progress, options = {}) {
11301
+ assertCamera(from, "Camera start");
11302
+ assertCamera(to, "Camera end");
11303
+ assertZoomConstraints(options);
11304
+ assertZoomInRange(from, options);
11305
+ assertZoomInRange(to, options);
11306
+ const amount2 = clampProgress3(progress);
11307
+ if (amount2 === 0) return { ...from };
11308
+ if (amount2 === 1) return { ...to };
11309
+ const eased = (options.easing ?? smoothstep)(amount2);
11310
+ if (!Number.isFinite(eased)) throw new Error("Camera easing must return a finite number");
11311
+ const t = Math.max(0, Math.min(1, eased));
11312
+ if (t === 0) return { ...from };
11313
+ if (t === 1) return { ...to };
11314
+ const camera = {
11315
+ x: interpolateLinear(from.x, to.x, t),
11316
+ y: interpolateLinear(from.y, to.y, t),
11317
+ zoom: Math.exp(Math.log(from.zoom) * (1 - t) + Math.log(to.zoom) * t)
11318
+ };
11319
+ assertCamera(camera, "Camera result");
11320
+ assertZoomInRange(camera, options);
11321
+ return camera;
11322
+ }
11323
+ function cameraSvgTransform(camera, viewport) {
11324
+ assertCamera(camera, "Camera");
11325
+ assertViewport(viewport);
11326
+ return `translate(${viewport.width / 2} ${viewport.height / 2}) scale(${camera.zoom}) translate(${-camera.x} ${-camera.y})`;
11327
+ }
11328
+ function projectWorldPoint(point, camera, viewport) {
11329
+ if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {
11330
+ throw new Error("World point coordinates must be finite");
11331
+ }
11332
+ assertCamera(camera, "Camera");
11333
+ assertViewport(viewport);
11334
+ const projected = {
11335
+ x: viewport.width / 2 + (point.x - camera.x) * camera.zoom,
11336
+ y: viewport.height / 2 + (point.y - camera.y) * camera.zoom
11337
+ };
11338
+ if (!Number.isFinite(projected.x) || !Number.isFinite(projected.y)) {
11339
+ throw new Error("Projected world point coordinates must be finite");
11340
+ }
11341
+ return projected;
11342
+ }
11343
+
11344
+ // src/path-morph.ts
11345
+ var DEFAULT_MORPH_SAMPLES = 64;
11346
+ var MAX_MORPH_SAMPLES = 4096;
11347
+ function clampProgress4(progress) {
11348
+ if (!Number.isFinite(progress)) throw new Error("Polyline morph progress must be finite");
11349
+ return Math.max(0, Math.min(1, progress));
11350
+ }
11351
+ function validatePolyline(points, context) {
11352
+ if (!Array.isArray(points) || points.length === 0) {
11353
+ throw new Error(`${context} polyline must be a non-empty array`);
11354
+ }
11355
+ for (let index = 0; index < points.length; index += 1) {
11356
+ const point = points[index];
11357
+ if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y)) {
11358
+ throw new Error(`${context} point ${index} coordinates must be finite`);
11359
+ }
11360
+ }
11361
+ }
11362
+ function validateSamples(samples) {
11363
+ if (!Number.isInteger(samples) || samples < 2) {
11364
+ throw new Error("Polyline morph samples must be an integer of at least 2");
11365
+ }
11366
+ if (samples > MAX_MORPH_SAMPLES) {
11367
+ throw new Error(`Polyline morph samples cannot exceed ${MAX_MORPH_SAMPLES}`);
11368
+ }
11369
+ }
11370
+ function resamplePolyline(points, samples) {
11371
+ const lengths = points.slice(1).map((point, index) => Math.hypot(point.x - points[index].x, point.y - points[index].y));
11372
+ const total = lengths.reduce((sum, length) => sum + length, 0);
11373
+ if (!Number.isFinite(total)) throw new Error("Polyline morph arc length must be finite");
11374
+ if (total === 0) return Array.from({ length: samples }, () => ({ ...points[0] }));
11375
+ let segment = 0;
11376
+ let offset = 0;
11377
+ return Array.from({ length: samples }, (_, index) => {
11378
+ if (index === samples - 1) return { ...points[points.length - 1] };
11379
+ const distance = total * (index / (samples - 1));
11380
+ while (segment < lengths.length - 1 && (lengths[segment] === 0 || distance > offset + lengths[segment])) {
11381
+ offset += lengths[segment++];
11382
+ }
11383
+ const t = (distance - offset) / lengths[segment];
11384
+ const from = points[segment], to = points[segment + 1];
11385
+ return { x: from.x * (1 - t) + to.x * t, y: from.y * (1 - t) + to.y * t };
11386
+ });
11387
+ }
11388
+ function createPolylineMorph(from, to, options = {}) {
11389
+ validatePolyline(from, "Start");
11390
+ validatePolyline(to, "End");
11391
+ const samples = options.samples ?? DEFAULT_MORPH_SAMPLES;
11392
+ validateSamples(samples);
11393
+ const startSamples = resamplePolyline(from, samples);
11394
+ const endSamples = resamplePolyline(to, samples);
11395
+ const easing = options.easing ?? smoothstep;
11396
+ return (progress) => {
11397
+ const amount2 = clampProgress4(progress);
11398
+ const eased = amount2 === 0 || amount2 === 1 ? amount2 : easing(amount2);
11399
+ if (!Number.isFinite(eased)) throw new Error("Polyline morph easing must return a finite number");
11400
+ const t = Math.max(0, Math.min(1, eased));
11401
+ return startSamples.map((start, index) => {
11402
+ const end = endSamples[index];
11403
+ return { x: start.x * (1 - t) + end.x * t, y: start.y * (1 - t) + end.y * t };
11404
+ });
11405
+ };
11406
+ }
11407
+ function morphPolyline(from, to, progress, options = {}) {
11408
+ return createPolylineMorph(from, to, options)(progress);
11409
+ }
11410
+
11411
+ // src/video.ts
11412
+ import { spawn } from "child_process";
11413
+ import { randomUUID } from "crypto";
11414
+ import { mkdir as mkdir3, open, rename, rm, stat } from "fs/promises";
11415
+ import { basename, dirname as dirname3, join as join2, resolve } from "path";
11416
+ import { Resvg as Resvg3 } from "@resvg/resvg-js";
11417
+ import parseCssColor3 from "parse-css-color";
11418
+ var MAX_STDERR_CHARS = 8192;
11419
+ function validateTiming(duration, fps) {
11420
+ if (!Number.isFinite(duration) || duration <= 0) {
11421
+ throw new Error("duration must be a positive finite number");
11422
+ }
11423
+ if (!Number.isInteger(fps) || fps < 1 || fps > 120) {
11424
+ throw new Error("fps must be an integer between 1 and 120");
11425
+ }
11426
+ const count = Math.round(duration * fps / 1e3);
11427
+ if (!Number.isSafeInteger(count) || count < 1) {
11428
+ throw new Error("duration must round to at least one frame and no more than Number.MAX_SAFE_INTEGER frames");
11429
+ }
11430
+ return { count, duration: count * 1e3 / fps };
11431
+ }
11432
+ function frameInfo(index, schedule, fps) {
11433
+ return {
11434
+ index,
11435
+ count: schedule.count,
11436
+ time: index * 1e3 / fps,
11437
+ duration: schedule.duration,
11438
+ progress: index / schedule.count,
11439
+ fps
11440
+ };
11441
+ }
11442
+ function* videoFrameSchedule(duration, fps = 30) {
11443
+ const schedule = validateTiming(duration, fps);
11444
+ for (let index = 0; index < schedule.count; index++) {
11445
+ yield frameInfo(index, schedule, fps);
11446
+ }
11447
+ }
11448
+ async function renderAnimationVideo(animation, options) {
11449
+ const scale = options.scale ?? 1;
11450
+ if (!Number.isFinite(options.width) || options.width <= 0 || !Number.isFinite(options.height) || options.height <= 0) {
11451
+ throw new Error("Animation width and height must be positive finite numbers");
11452
+ }
11453
+ if (!Number.isFinite(scale) || scale <= 0) throw new Error("scale must be a positive finite number");
11454
+ const theme = options.theme ?? "dark";
11455
+ const background = options.background ?? "theme";
11456
+ const backgroundColor = background === "theme" ? getThemeColors(theme).bg : background;
11457
+ const parsedBackground = parseCssColor3(backgroundColor);
11458
+ if (!parsedBackground || parsedBackground.alpha !== 1) {
11459
+ throw new Error('MP4 requires an opaque background; use "theme" or an opaque CSS color');
11460
+ }
11461
+ return renderRgbaVideo(async (info) => {
11462
+ const sampled = sampleAnimationFrame(animation, info.time, {
11463
+ index: info.index,
11464
+ count: info.count,
11465
+ delay: 1e3 / info.fps,
11466
+ fps: info.fps
11467
+ });
11468
+ const edges = { top: false, right: false, bottom: false, left: false };
11469
+ const svg = await renderToSvg(animation.render(sampled.state, sampled.frame), options.width, options.height, {
11470
+ theme,
11471
+ background,
11472
+ watermark: options.watermark ?? options.brand,
11473
+ onNodeDetected: (node) => {
11474
+ edges.top ||= node.top < -0.5;
11475
+ edges.right ||= node.left + node.width > options.width + 0.5;
11476
+ edges.bottom ||= node.top + node.height > options.height + 0.5;
11477
+ edges.left ||= node.left < -0.5;
11478
+ }
11479
+ });
11480
+ const names = Object.keys(edges).filter((edge) => edges[edge]);
11481
+ if (names.length) {
11482
+ const overflow = {
11483
+ overflows: true,
11484
+ edges,
11485
+ message: `Content overflows canvas at: ${names.join(", ")}. Increase the illustration dimensions.`
11486
+ };
11487
+ throw new CanvasOverflowError(options.width, options.height, overflow, {
11488
+ frameIndex: info.index,
11489
+ frameCount: info.count,
11490
+ time: info.time,
11491
+ label: sampled.frame.label
11492
+ });
11493
+ }
11494
+ const rendered = new Resvg3(svg, {
11495
+ fitTo: { mode: "width", value: options.width * scale },
11496
+ background: backgroundColor
11497
+ }).render();
11498
+ if (rendered.width !== options.width * scale || rendered.height !== options.height * scale) {
11499
+ throw new Error("All video frames must match the scaled canvas dimensions");
11500
+ }
11501
+ return rendered.pixels;
11502
+ }, {
11503
+ ...options,
11504
+ width: options.width * scale,
11505
+ height: options.height * scale,
11506
+ duration: animation.duration
11507
+ });
11508
+ }
11509
+ function abortError() {
11510
+ const error = new Error("Video export was aborted.");
11511
+ error.name = "AbortError";
11512
+ return error;
11513
+ }
11514
+ function withAbort(promise, signal) {
11515
+ if (!signal) return promise;
11516
+ if (signal.aborted) return Promise.reject(abortError());
11517
+ return new Promise((resolvePromise, rejectPromise) => {
11518
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
11519
+ const onAbort = () => {
11520
+ cleanup();
11521
+ rejectPromise(abortError());
11522
+ };
11523
+ signal.addEventListener("abort", onAbort, { once: true });
11524
+ promise.then(
11525
+ (value) => {
11526
+ cleanup();
11527
+ resolvePromise(value);
11528
+ },
11529
+ (error) => {
11530
+ cleanup();
11531
+ rejectPromise(error);
11532
+ }
11533
+ );
11534
+ });
11535
+ }
11536
+ function formatSeconds(durationMs) {
11537
+ return (durationMs / 1e3).toFixed(12).replace(/0+$/, "").replace(/\.$/, "");
11538
+ }
11539
+ function describeExit(code, signal, stderr) {
11540
+ const status = signal ? `signal ${signal}` : `exit code ${code}`;
11541
+ const detail = stderr.trim();
11542
+ return new Error(`FFmpeg failed (${status})${detail ? `: ${detail}` : ""}`);
11543
+ }
11544
+ async function stopEncoder(child, exited) {
11545
+ if (child.exitCode !== null || child.signalCode !== null) return;
11546
+ child.kill("SIGTERM");
11547
+ let timer;
11548
+ const terminated = await Promise.race([
11549
+ exited.then(() => true),
11550
+ new Promise((resolvePromise) => {
11551
+ timer = setTimeout(() => resolvePromise(false), 1e3);
11552
+ })
11553
+ ]);
11554
+ if (timer) clearTimeout(timer);
11555
+ if (!terminated) {
11556
+ child.kill("SIGKILL");
11557
+ await exited;
11558
+ }
11559
+ }
11560
+ async function renderRgbaVideo(renderFrame2, options) {
11561
+ const fps = options.fps ?? 30;
11562
+ const schedule = validateTiming(options.duration, fps);
11563
+ const { width, height } = options;
11564
+ if (!Number.isSafeInteger(width) || width <= 0 || width % 2 !== 0) {
11565
+ throw new Error("width must be a positive even integer");
11566
+ }
11567
+ if (!Number.isSafeInteger(height) || height <= 0 || height % 2 !== 0) {
11568
+ throw new Error("height must be a positive even integer");
11569
+ }
11570
+ const expectedBytes = width * height * 4;
11571
+ if (!Number.isSafeInteger(expectedBytes)) {
11572
+ throw new Error("frame dimensions are too large");
11573
+ }
11574
+ if (typeof renderFrame2 !== "function") throw new Error("renderFrame must be a function");
11575
+ if (typeof options.outputPath !== "string" || options.outputPath.length === 0) {
11576
+ throw new Error("outputPath must be a non-empty path");
11577
+ }
11578
+ const ffmpegPath = options.ffmpegPath ?? "ffmpeg";
11579
+ const preset = options.preset ?? "fast";
11580
+ const crf = options.crf ?? 18;
11581
+ const threads = options.threads ?? 4;
11582
+ if (typeof ffmpegPath !== "string" || ffmpegPath.length === 0) throw new Error("ffmpegPath must be a non-empty path");
11583
+ if (typeof preset !== "string" || preset.length === 0) throw new Error("preset must be a non-empty string");
11584
+ if (!Number.isInteger(crf) || crf < 0 || crf > 51) throw new Error("crf must be an integer between 0 and 51");
11585
+ if (!Number.isSafeInteger(threads) || threads < 1) throw new Error("threads must be a positive safe integer");
11586
+ if (options.audioPath !== void 0 && (typeof options.audioPath !== "string" || options.audioPath.length === 0)) {
11587
+ throw new Error("audioPath must be a non-empty path when provided");
11588
+ }
11589
+ if (options.signal?.aborted) throw abortError();
11590
+ const outputPath = resolve(options.outputPath);
11591
+ const outputDirectory = dirname3(outputPath);
11592
+ await mkdir3(outputDirectory, { recursive: true });
11593
+ const tempPath = join2(outputDirectory, `.${basename(outputPath)}.${randomUUID()}.tmp.mp4`);
11594
+ const tempFile = await open(tempPath, "wx", 384);
11595
+ try {
11596
+ await tempFile.close();
11597
+ } catch (error) {
11598
+ await rm(tempPath, { force: true });
11599
+ throw error;
11600
+ }
11601
+ const seconds = formatSeconds(schedule.duration);
11602
+ const args = [
11603
+ "-hide_banner",
11604
+ "-loglevel",
11605
+ "error",
11606
+ "-nostdin",
11607
+ "-y",
11608
+ "-f",
11609
+ "rawvideo",
11610
+ "-pixel_format",
11611
+ "rgba",
11612
+ "-video_size",
11613
+ `${width}x${height}`,
11614
+ "-framerate",
11615
+ String(fps),
11616
+ "-i",
11617
+ "pipe:0"
11618
+ ];
11619
+ if (options.audioPath) args.push("-i", resolve(options.audioPath));
11620
+ args.push("-map", "0:v:0");
11621
+ if (options.audioPath) args.push("-map", "1:a:0", "-af", `asetpts=PTS-STARTPTS,apad,atrim=duration=${seconds}`);
11622
+ args.push(
11623
+ "-frames:v",
11624
+ String(schedule.count),
11625
+ "-t",
11626
+ seconds,
11627
+ "-c:v",
11628
+ "libx264",
11629
+ "-preset",
11630
+ preset,
11631
+ "-crf",
11632
+ String(crf),
11633
+ "-threads:v",
11634
+ String(threads),
11635
+ "-pix_fmt",
11636
+ "yuv420p"
11637
+ );
11638
+ if (options.audioPath) args.push("-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2");
11639
+ args.push("-movflags", "+faststart", tempPath);
11640
+ let stderr = "";
11641
+ let inputError;
11642
+ let child;
11643
+ try {
11644
+ child = spawn(ffmpegPath, args, { stdio: ["pipe", "ignore", "pipe"] });
11645
+ } catch (error) {
11646
+ await rm(tempPath, { force: true });
11647
+ throw error;
11648
+ }
11649
+ child.stderr?.on("data", (chunk) => {
11650
+ stderr += chunk.toString();
11651
+ if (stderr.length > MAX_STDERR_CHARS) stderr = stderr.slice(-MAX_STDERR_CHARS);
11652
+ });
11653
+ child.stdin?.on("error", (error) => {
11654
+ inputError = error;
11655
+ });
11656
+ let exitResult;
11657
+ const exited = new Promise((resolvePromise) => {
11658
+ child.once("error", (error) => {
11659
+ exitResult = { code: null, signal: null, error };
11660
+ resolvePromise(exitResult);
11661
+ });
11662
+ child.once("close", (code, signal) => {
11663
+ exitResult = { code, signal };
11664
+ resolvePromise(exitResult);
11665
+ });
11666
+ });
11667
+ function observeEncoder(operation, index, finishAfterSuccess) {
11668
+ const lastFrame = index === schedule.count - 1;
11669
+ const completed = (exit) => {
11670
+ if (!exit.error && exit.code === 0 && lastFrame) {
11671
+ return finishAfterSuccess ? Promise.resolve(void 0) : operation;
11672
+ }
11673
+ if (exit.error) return Promise.reject(new Error(`Unable to start FFmpeg: ${exit.error.message}`, { cause: exit.error }));
11674
+ return Promise.reject(describeExit(exit.code, exit.signal, stderr));
11675
+ };
11676
+ if (exitResult) return completed(exitResult);
11677
+ return new Promise((resolvePromise, rejectPromise) => {
11678
+ const cleanup = () => {
11679
+ child.removeListener("error", onError);
11680
+ child.removeListener("close", onClose);
11681
+ };
11682
+ const onError = (error) => {
11683
+ cleanup();
11684
+ rejectPromise(new Error(`Unable to start FFmpeg: ${error.message}`, { cause: error }));
11685
+ };
11686
+ const onClose = (code, signal) => {
11687
+ cleanup();
11688
+ void completed({ code, signal }).then(resolvePromise, rejectPromise);
11689
+ };
11690
+ child.once("error", onError);
11691
+ child.once("close", onClose);
11692
+ operation.then(
11693
+ (value) => {
11694
+ cleanup();
11695
+ resolvePromise(value);
11696
+ },
11697
+ (error) => {
11698
+ cleanup();
11699
+ rejectPromise(error);
11700
+ }
11701
+ );
11702
+ });
11703
+ }
11704
+ try {
11705
+ const input = child.stdin;
11706
+ if (!input) throw new Error("FFmpeg did not provide a frame input stream");
11707
+ for (let index = 0; index < schedule.count; index++) {
11708
+ const info = frameInfo(index, schedule, fps);
11709
+ const rendered = await withAbort(observeEncoder(Promise.resolve(renderFrame2(info)), index, false), options.signal);
11710
+ if (!(rendered instanceof Uint8Array) || rendered.byteLength !== expectedBytes) {
11711
+ throw new Error(`Frame ${index} must contain exactly ${expectedBytes} RGBA bytes`);
11712
+ }
11713
+ if (inputError) throw describeExit(null, null, inputError.message || stderr);
11714
+ const pixels = Buffer.from(rendered.buffer, rendered.byteOffset, rendered.byteLength);
11715
+ const write = new Promise((resolvePromise, rejectPromise) => {
11716
+ input.write(pixels, (error) => error ? rejectPromise(error) : resolvePromise());
11717
+ });
11718
+ await withAbort(observeEncoder(write, index, true), options.signal);
11719
+ if (options.onProgress) {
11720
+ await withAbort(observeEncoder(Promise.resolve(options.onProgress(info)), index, false), options.signal);
11721
+ }
11722
+ }
11723
+ input.end();
11724
+ const exit = await withAbort(exited, options.signal);
11725
+ if (exit.error) throw new Error(`Unable to start FFmpeg: ${exit.error.message}`, { cause: exit.error });
11726
+ if (exit.code !== 0) throw describeExit(exit.code, exit.signal, stderr);
11727
+ const outputStat = await stat(tempPath);
11728
+ await rename(tempPath, outputPath);
11729
+ return {
11730
+ width,
11731
+ height,
11732
+ frameCount: schedule.count,
11733
+ duration: schedule.duration,
11734
+ fps,
11735
+ bytes: outputStat.size,
11736
+ outputPath,
11737
+ audioIncluded: options.audioPath !== void 0
11738
+ };
11739
+ } catch (error) {
11740
+ await stopEncoder(child, exited);
11741
+ if (inputError && error instanceof Error && (error.message === "write EPIPE" || error.code === "EPIPE")) {
11742
+ throw describeExit(null, null, stderr || inputError.message);
11743
+ }
11744
+ throw error;
11745
+ } finally {
11746
+ await rm(tempPath, { force: true });
11747
+ }
11748
+ }
11749
+
11750
+ // src/scene-renderer.ts
11751
+ import React15 from "react";
11752
+ import { readFile as readFile2, mkdir as mkdir4, open as open2, rename as rename2, rm as rm2 } from "fs/promises";
11753
+ import { createReadStream } from "fs";
11754
+ import { dirname as dirname4, join as join3, resolve as resolve2 } from "path";
11755
+ import { fileURLToPath as fileURLToPath2 } from "url";
11756
+ import { createHash, randomUUID as randomUUID2 } from "crypto";
11757
+ import { brotliDecompressSync as brotliDecompressSync2 } from "zlib";
11758
+ import { Resvg as Resvg4 } from "@resvg/resvg-js";
11759
+ function outputSettings(prepared, outputScale = 1, previewFps) {
11760
+ if (!Number.isFinite(outputScale) || outputScale < 0.25 || outputScale > 1) {
11761
+ throw new Error("Scene outputScale must be from 0.25 to 1.");
11762
+ }
11763
+ const { width: logicalWidth, height: logicalHeight, fps: logicalFps, duration } = prepared.request;
11764
+ const width = logicalWidth * outputScale, height = logicalHeight * outputScale;
11765
+ if (![width, height].every((value) => Number.isInteger(value) && value >= 2 && value % 2 === 0)) {
11766
+ throw new Error("Scaled scene width and height must be positive even integers.");
11767
+ }
11768
+ const fps = previewFps === void 0 ? logicalFps : previewFps;
11769
+ if (!Number.isInteger(fps) || fps < 1 || fps > logicalFps) {
11770
+ throw new Error("Scene previewFps must be an integer from 1 to the logical scene fps.");
11771
+ }
11772
+ const frameCount = Math.round(duration * fps);
11773
+ if (frameCount < 1) throw new Error("Scene preview duration must round to at least one output frame.");
11774
+ return { width, height, fps, frameCount, outputScale, preview: outputScale !== 1 || fps !== logicalFps };
11775
+ }
11776
+ var assetPins = {
11777
+ "fonts/Inter-Regular.ttf": "1b08e7fc267a5c7e1d614100f604b83e7e8a0be241f0f288faa2b3ac93a683ba",
11778
+ "fonts/Inter-SemiBold.ttf": "e7a1aaf7eda9f2fad4131725fa556265ec75ca7b2d756260173a040363e8d4f7",
11779
+ "fonts/Inter-Bold.ttf": "b37284b5701b6b168dfc770aa1a4ac492106422fd3ba76bc7641e37434e8019c",
11780
+ "fonts/JetBrainsMono-Regular.ttf": "44ce4a84f20d60f24539bd0cef11f79c29e38609e0f8adf18551c9794a5d9dc3",
11781
+ "fonts/NotoSans-Regular.ttf": "5be701a9511117e73603bdab95947feef4f18bd1851dbddc30659370b26c69f1",
11782
+ "fonts/NotoSansMath-Regular.ttf": "3cbaf44af13f592bc7f7172a50edab4c73ac2f3d19af2d697a01ebd3288e322d",
11783
+ "emoji.json.br": "4911e822be2ed684fe811cadf036139e3efe353ffe2990311e1763f38ae7daab"
11784
+ };
11785
+ var assetsPromise;
11786
+ async function sceneAssets() {
11787
+ assetsPromise ??= loadSceneAssets().catch((error) => {
11788
+ assetsPromise = void 0;
11789
+ throw error;
11790
+ });
11791
+ return assetsPromise;
11792
+ }
11793
+ async function loadSceneAssets() {
11794
+ const moduleDir = typeof __dirname !== "undefined" ? __dirname : dirname4(fileURLToPath2(import.meta.url));
11795
+ const assetDir = join3(moduleDir, "..", "assets");
11796
+ const files = /* @__PURE__ */ new Map();
11797
+ for (const [name, expected] of Object.entries(assetPins)) {
11798
+ const bytes = await readFile2(join3(assetDir, name));
11799
+ if (await sceneSha256(bytes) !== expected) throw new Error(`Pinned scene asset does not match: ${name}`);
11800
+ files.set(name, bytes);
11801
+ }
11802
+ const fontDefinitions = [
11803
+ ["Inter", "Inter-Regular.ttf", 400],
11804
+ ["Inter", "Inter-SemiBold.ttf", 600],
11805
+ ["Inter", "Inter-Bold.ttf", 700],
11806
+ ["JetBrains Mono", "JetBrainsMono-Regular.ttf", 400],
11807
+ ["Noto Sans", "NotoSans-Regular.ttf", 400],
11808
+ ["Noto Sans Math", "NotoSansMath-Regular.ttf", 400]
11809
+ ];
11810
+ return {
11811
+ fonts: fontDefinitions.map(([name, filename, weight]) => ({
11812
+ name,
11813
+ weight,
11814
+ style: "normal",
11815
+ data: Uint8Array.from(files.get(`fonts/${filename}`)).buffer
11816
+ })),
11817
+ fontFiles: fontDefinitions.map(([, filename]) => join3(assetDir, "fonts", filename)),
11818
+ emoji: JSON.parse(brotliDecompressSync2(files.get("emoji.json.br")).toString("utf8")),
11819
+ sha256: await sceneSha256(JSON.stringify(assetPins))
11820
+ };
11821
+ }
11822
+ var trustedComponents = Object.fromEntries(SCENE_COMPONENT_NAMES.map((name) => [name, primitives_exports[name]]));
11823
+ var svgTags = new Set(SCENE_DOM_TAGS.filter((name) => !["div", "span", "p", "strong", "em", "b", "i", "br"].includes(name)));
11824
+ function isElement(value) {
11825
+ return Boolean(value && !Array.isArray(value) && typeof value === "object" && value.kind === "vizmatic.element");
11826
+ }
11827
+ var xml = (value) => String(value).replace(/[&<>"']/g, (character) => ({
11828
+ "&": "&amp;",
11829
+ "<": "&lt;",
11830
+ ">": "&gt;",
11831
+ '"': "&quot;",
11832
+ "'": "&apos;"
11833
+ })[character]);
11834
+ function svgAttribute(name) {
11835
+ if (name === "className") return "class";
11836
+ if (name === "xlinkHref") return "href";
11837
+ if (/^(?:viewBox|preserveAspectRatio|gradientUnits|gradientTransform|patternUnits|patternContentUnits|patternTransform|markerWidth|markerHeight|markerUnits|refX|refY|textLength|lengthAdjust|clipPathUnits)$/.test(name)) return name;
11838
+ return name.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);
11839
+ }
11840
+ function serializeSvg(node, budget, depth = 0) {
11841
+ if (++budget.nodes > SCENE_LIMITS.nodes * 16) throw new Error("Resolved scene exceeds its host element budget.");
11842
+ if (depth > SCENE_LIMITS.depth * 2) throw new Error("Resolved SVG exceeds its depth limit.");
11843
+ const emit = (chunk) => {
11844
+ budget.svgBytes += Buffer.byteLength(chunk);
11845
+ if (budget.svgBytes > SCENE_LIMITS.graphBytes * 4) throw new Error("Resolved SVG exceeds its serialized byte budget.");
11846
+ return chunk;
11847
+ };
11848
+ if (node === null || node === void 0 || typeof node === "boolean") return "";
11849
+ if (typeof node === "string" || typeof node === "number") return emit(xml(node));
11850
+ if (Array.isArray(node)) return node.map((child) => serializeSvg(child, budget, depth + 1)).join("");
11851
+ if (!React15.isValidElement(node)) throw new Error("Invalid resolved SVG child.");
11852
+ if (node.type === React15.Fragment) return serializeSvg(node.props.children, budget, depth + 1);
11853
+ if (node.type === SvgMathText) {
11854
+ const { text, x, y, fill, fontSize = 13, fontFamily = "JetBrains Mono", fontWeight = 700, textAnchor = "middle", dominantBaseline = "middle", opacity = 1 } = node.props;
11855
+ return serializeSvg(React15.createElement("text", { x, y, fill, fontSize, fontFamily, fontWeight, textAnchor, dominantBaseline, opacity }, String(text)), budget, depth + 1);
11856
+ }
11857
+ if (typeof node.type === "function") {
11858
+ return serializeSvg(node.type(node.props), budget, depth + 1);
11859
+ }
11860
+ if (typeof node.type !== "string" || !svgTags.has(node.type)) throw new Error("Only SVG components may be placed inside an SVG scene.");
11861
+ validateResolvedSceneResources(node.props);
11862
+ const attributes = Object.entries(node.props).filter(([key, value]) => key !== "children" && key !== "key" && value !== void 0 && value !== null).map(([key, value]) => {
11863
+ if (key === "style" && typeof value === "object") {
11864
+ const style = Object.entries(value).map(([property, item]) => `${svgAttribute(property)}:${String(item)}`).join(";");
11865
+ return ` style="${xml(style)}"`;
11866
+ }
11867
+ if (!/^[A-Za-z_][\w:.-]*$/.test(key) || typeof value === "object" || typeof value === "function") throw new Error("Unsupported SVG attribute.");
11868
+ return ` ${svgAttribute(key)}="${xml(String(value))}"`;
11869
+ }).join("");
11870
+ return emit(`<${node.type}${attributes}>`) + serializeSvg(node.props.children, budget, depth + 1) + emit(`</${node.type}>`);
11871
+ }
11872
+ function graphToReact(value, theme) {
11873
+ if (Array.isArray(value)) return value.map((child) => graphToReact(child, theme));
11874
+ if (!isElement(value)) return value;
11875
+ const convertProp = (prop) => {
11876
+ if (isElement(prop)) return graphToReact(prop, theme);
11877
+ if (Array.isArray(prop)) return prop.map(convertProp);
11878
+ if (prop && typeof prop === "object") return Object.fromEntries(Object.entries(prop).map(([key, item]) => [key, convertProp(item)]));
11879
+ return prop;
11880
+ };
11881
+ const props = Object.fromEntries(Object.entries(value.props).map(([name, prop]) => [name, convertProp(prop)]));
11882
+ const component = trustedComponents[value.type];
11883
+ if (component) props.c ??= theme;
11884
+ return React15.createElement(component ?? value.type, props, ...value.children.map((child) => graphToReact(child, theme)));
11885
+ }
11886
+ function renderSvgImage(element, assets, width, height, budget, outputScale = 1, includePng = true) {
11887
+ const root = React15.cloneElement(element, { xmlns: "http://www.w3.org/2000/svg", width, height });
11888
+ const svg = serializeSvg(root, budget);
11889
+ const image = new Resvg4(svg, {
11890
+ font: { loadSystemFonts: false, fontFiles: assets.fontFiles, defaultFontFamily: "Inter" },
11891
+ background: "rgba(0,0,0,0)",
11892
+ ...outputScale !== 1 ? { fitTo: { mode: "width", value: width * outputScale } } : {}
11893
+ }).render();
11894
+ if (image.width !== width * outputScale || image.height !== height * outputScale) throw new Error("SVG frame does not match scaled scene dimensions.");
11895
+ return { pixels: image.pixels, ...includePng ? { png: image.asPng() } : {} };
11896
+ }
11897
+ function rasterizeNestedSvg(node, assets, defaultWidth, defaultHeight, budget) {
11898
+ if (++budget.nodes > SCENE_LIMITS.nodes * 16) throw new Error("Resolved scene exceeds its host element budget.");
11899
+ if (Array.isArray(node)) return node.map((child) => rasterizeNestedSvg(child, assets, defaultWidth, defaultHeight, budget));
11900
+ if (!React15.isValidElement(node)) return node;
11901
+ if (node.type === "svg") {
11902
+ const width = typeof node.props.width === "number" ? node.props.width : defaultWidth;
11903
+ const height = typeof node.props.height === "number" ? node.props.height : defaultHeight;
11904
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > SCENE_LIMITS.canvasEdge || height > SCENE_LIMITS.canvasEdge || width * height > SCENE_LIMITS.canvasPixels) {
11905
+ throw new Error("Nested SVG dimensions exceed the scene canvas limits.");
11906
+ }
11907
+ budget.pixels += width * height;
11908
+ budget.count += 1;
11909
+ if (budget.pixels > defaultWidth * defaultHeight * 4 || budget.count > 16) {
11910
+ throw new Error("Nested SVG rasterization exceeds the per-frame pixel or image budget.");
11911
+ }
11912
+ const { png } = renderSvgImage(node, assets, width, height, budget);
11913
+ return React15.createElement("img", {
11914
+ width,
11915
+ height,
11916
+ src: `data:image/png;base64,${Buffer.from(png).toString("base64")}`,
11917
+ style: { display: "flex", flexShrink: 0, ...node.props.style }
11918
+ });
11919
+ }
11920
+ if (typeof node.type === "function") return rasterizeNestedSvg(node.type(node.props), assets, defaultWidth, defaultHeight, budget);
11921
+ validateResolvedSceneResources(node.props);
11922
+ return React15.cloneElement(node, {}, rasterizeNestedSvg(node.props.children, assets, defaultWidth, defaultHeight, budget));
11923
+ }
11924
+ async function renderPreparedFrame(prepared, assets, time, outputScale, includePng) {
11925
+ const evaluated = await prepared.evaluate(time);
11926
+ const { width, height, theme } = prepared.request;
11927
+ const c = getThemeColors(theme);
11928
+ let element = graphToReact(evaluated.graph, c);
11929
+ if (React15.isValidElement(element) && element.type === "svg") {
11930
+ const image = renderSvgImage(React15.cloneElement(element, {
11931
+ children: [React15.createElement("rect", { key: "__scene_background", width, height, fill: c.bg }), element.props.children]
11932
+ }), assets, width, height, { pixels: 0, count: 0, nodes: 0, svgBytes: 0 }, outputScale, includePng);
11933
+ return image;
11934
+ }
11935
+ element = React15.createElement("div", { style: { display: "flex", position: "relative", width, height, backgroundColor: c.bg, fontFamily: "Inter", color: c.textPrimary } }, element);
11936
+ return withRenderContext({ background: "theme" }, async () => {
11937
+ element = rasterizeNestedSvg(element, assets, width, height, { pixels: 0, count: 0, nodes: 0, svgBytes: 0 });
11938
+ const accessible = prepareAccessibleSvg(element);
11939
+ const layoutNodes = [];
11940
+ const rendered = await satori(accessible.element, {
11941
+ width,
11942
+ height,
11943
+ fonts: assets.fonts,
11944
+ loadAdditionalAsset: async (code, segment) => {
11945
+ if (code !== "emoji") return [];
11946
+ const points = [...segment].map((character) => character.codePointAt(0).toString(16));
11947
+ const candidates = [points.join("-"), points.filter((point) => point !== "fe0f").join("-")];
11948
+ const svg2 = candidates.map((name) => assets.emoji[`${name}.svg`]).find(Boolean);
11949
+ if (!svg2) throw new Error("A scene glyph is not available in the pinned offline font and emoji assets.");
11950
+ return `data:image/svg+xml;base64,${Buffer.from(svg2).toString("base64")}`;
11951
+ },
11952
+ onNodeDetected: (node) => layoutNodes.push(node)
11953
+ });
11954
+ const svg = addSvgAccessibility(rendered, accessible.graphs, layoutNodes);
11955
+ const image = new Resvg4(svg, {
11956
+ background: c.bg,
11957
+ font: { loadSystemFonts: false, fontFiles: assets.fontFiles },
11958
+ ...outputScale !== 1 ? { fitTo: { mode: "width", value: width * outputScale } } : {}
11959
+ }).render();
11960
+ if (image.width !== width * outputScale || image.height !== height * outputScale) throw new Error("Layout frame does not match scaled scene dimensions.");
11961
+ return { pixels: image.pixels, ...includePng ? { png: image.asPng() } : {} };
11962
+ });
11963
+ }
11964
+ async function outputMetadata(prepared, assets, settings, outputPath, bytes, kind, time) {
11965
+ const { width, height, duration, fps, frameCount } = prepared.request;
11966
+ const digest = createHash("sha256");
11967
+ for await (const chunk of createReadStream(outputPath)) digest.update(chunk);
11968
+ return {
11969
+ runtimeVersion: SCENE_RUNTIME_VERSION,
11970
+ sourceSha256: prepared.sourceSha256,
11971
+ inputSha256: await sceneSha256(JSON.stringify({
11972
+ requestSha256: prepared.inputSha256,
11973
+ fontAssetsSha256: assets.sha256,
11974
+ kind,
11975
+ ...time !== void 0 ? { time } : {},
11976
+ ...settings.preview ? { outputScale: settings.outputScale, width: settings.width, height: settings.height, fps: settings.fps, frameCount: settings.frameCount } : {}
11977
+ })),
11978
+ assetSha256: digest.digest("hex"),
11979
+ fontAssetsSha256: assets.sha256,
11980
+ width: settings.width,
11981
+ height: settings.height,
11982
+ duration,
11983
+ fps: settings.fps,
11984
+ frameCount: settings.frameCount,
11985
+ bytes,
11986
+ outputPath: resolve2(outputPath),
11987
+ ...settings.preview ? {
11988
+ outputScale: settings.outputScale,
11989
+ ...kind === "mp4" ? { previewFps: settings.fps } : {},
11990
+ logicalWidth: width,
11991
+ logicalHeight: height,
11992
+ logicalFps: fps,
11993
+ logicalFrameCount: frameCount
11994
+ } : {}
11995
+ };
11996
+ }
11997
+ async function atomicWrite(outputPath, bytes) {
11998
+ const target = resolve2(outputPath);
11999
+ await mkdir4(dirname4(target), { recursive: true });
12000
+ const temporary = join3(dirname4(target), `.vizmatic-scene-${randomUUID2()}.tmp`);
12001
+ const file = await open2(temporary, "wx", 384);
12002
+ try {
12003
+ await file.writeFile(bytes);
12004
+ await file.close();
12005
+ await rename2(temporary, target);
12006
+ } catch (error) {
12007
+ await file.close().catch(() => {
12008
+ });
12009
+ await rm2(temporary, { force: true });
12010
+ throw error;
12011
+ }
12012
+ }
12013
+ async function renderSceneFrame(options) {
12014
+ if (typeof options.outputPath !== "string" || !options.outputPath) throw new Error("Scene outputPath is required.");
12015
+ const prepared = await prepareScene(options);
12016
+ const settings = outputSettings(prepared, options.outputScale);
12017
+ const time = normalizeSceneTime(options.time, prepared.request.duration);
12018
+ const assets = await sceneAssets();
12019
+ const image = await renderPreparedFrame(prepared, assets, time, settings.outputScale, true);
12020
+ await atomicWrite(options.outputPath, image.png);
12021
+ return { ...await outputMetadata(prepared, assets, settings, options.outputPath, image.png.byteLength, "png", time), time };
12022
+ }
12023
+ async function renderSceneVideo(options) {
12024
+ if (typeof options.outputPath !== "string" || !options.outputPath) throw new Error("Scene outputPath is required.");
12025
+ const prepared = await prepareScene(options);
12026
+ const settings = outputSettings(prepared, options.outputScale, options.previewFps);
12027
+ const assets = await sceneAssets();
12028
+ const { duration } = prepared.request;
12029
+ const output = await renderRgbaVideo(async (frame) => (await renderPreparedFrame(prepared, assets, frame.time / 1e3, settings.outputScale, false)).pixels, {
12030
+ width: settings.width,
12031
+ height: settings.height,
12032
+ duration: duration * 1e3,
12033
+ fps: settings.fps,
12034
+ outputPath: options.outputPath,
12035
+ signal: options.signal
12036
+ });
12037
+ return { ...await outputMetadata(prepared, assets, settings, options.outputPath, output.bytes, "mp4"), encodedDuration: output.duration / 1e3 };
12038
+ }
12039
+
10609
12040
  // src/import-types.ts
10610
12041
  function graphImportResult(source, graph, diagnostics) {
10611
12042
  if (graph.nodes.length === 0 && diagnostics.every(({ severity }) => severity !== "error")) {
@@ -10691,7 +12122,7 @@ function readEndpoint(line, from) {
10691
12122
  { open: "(", close: ")", lossy: true },
10692
12123
  { open: "{", close: "}", lossy: true }
10693
12124
  ];
10694
- const delimiter = delimiters.find(({ open }) => rest.startsWith(open));
12125
+ const delimiter = delimiters.find(({ open: open3 }) => rest.startsWith(open3));
10695
12126
  if (!delimiter) return { id, label: id, shape: "rectangle", next: index };
10696
12127
  const content = readDelimited(line, afterId + delimiter.open.length, delimiter.close);
10697
12128
  if (!content) return void 0;
@@ -11162,13 +12593,13 @@ function importD2Graph(source) {
11162
12593
  }
11163
12594
 
11164
12595
  // src/check.ts
11165
- import { mkdtemp, rm } from "fs/promises";
12596
+ import { mkdtemp, rm as rm3 } from "fs/promises";
11166
12597
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
11167
12598
  import { tmpdir } from "os";
11168
- import { join as join2 } from "path";
12599
+ import { join as join4 } from "path";
11169
12600
 
11170
12601
  // src/diagnostics.ts
11171
- import parseCssColor3 from "parse-css-color";
12602
+ import parseCssColor4 from "parse-css-color";
11172
12603
  import { Children, isValidElement as isValidElement3 } from "react";
11173
12604
  var CHECK_DIAGNOSTIC_CODES = [
11174
12605
  "accessibility.low_contrast",
@@ -11209,7 +12640,7 @@ function hslToRgb2(hue, saturation, lightness) {
11209
12640
  }
11210
12641
  function colorFromCss(value) {
11211
12642
  if (typeof value !== "string") return void 0;
11212
- const parsed = parseCssColor3(value);
12643
+ const parsed = parseCssColor4(value);
11213
12644
  if (!parsed || parsed.values.length < 3) return void 0;
11214
12645
  const [r, g, b] = parsed.type === "hsl" ? hslToRgb2(parsed.values[0] ?? 0, parsed.values[1] ?? 0, parsed.values[2] ?? 0) : [parsed.values[0] ?? 0, parsed.values[1] ?? 0, parsed.values[2] ?? 0];
11215
12646
  return {
@@ -11221,13 +12652,13 @@ function colorFromCss(value) {
11221
12652
  }
11222
12653
  function compositeOver(foreground, background) {
11223
12654
  if (foreground.alpha >= 1 || !background) return foreground;
11224
- const alpha = foreground.alpha + background.alpha * (1 - foreground.alpha);
11225
- if (alpha <= 0) return { r: 0, g: 0, b: 0, alpha: 0 };
12655
+ const alpha2 = foreground.alpha + background.alpha * (1 - foreground.alpha);
12656
+ if (alpha2 <= 0) return { r: 0, g: 0, b: 0, alpha: 0 };
11226
12657
  return {
11227
- r: (foreground.r * foreground.alpha + background.r * background.alpha * (1 - foreground.alpha)) / alpha,
11228
- g: (foreground.g * foreground.alpha + background.g * background.alpha * (1 - foreground.alpha)) / alpha,
11229
- b: (foreground.b * foreground.alpha + background.b * background.alpha * (1 - foreground.alpha)) / alpha,
11230
- alpha
12658
+ r: (foreground.r * foreground.alpha + background.r * background.alpha * (1 - foreground.alpha)) / alpha2,
12659
+ g: (foreground.g * foreground.alpha + background.g * background.alpha * (1 - foreground.alpha)) / alpha2,
12660
+ b: (foreground.b * foreground.alpha + background.b * background.alpha * (1 - foreground.alpha)) / alpha2,
12661
+ alpha: alpha2
11231
12662
  };
11232
12663
  }
11233
12664
  function isUnresolvedColor(value) {
@@ -11257,13 +12688,13 @@ function fontSizePixels(value, inherited) {
11257
12688
  if (typeof value !== "string") return inherited;
11258
12689
  const match = value.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(px|pt|rem|em|%)?$/);
11259
12690
  if (!match?.[1]) return inherited;
11260
- const amount = Number(match[1]);
12691
+ const amount2 = Number(match[1]);
11261
12692
  const unit = match[2] ?? "px";
11262
- if (unit === "pt") return amount * 4 / 3;
11263
- if (unit === "rem") return amount * 16;
11264
- if (unit === "em") return amount * (inherited ?? 16);
11265
- if (unit === "%") return amount / 100 * (inherited ?? 16);
11266
- return amount;
12693
+ if (unit === "pt") return amount2 * 4 / 3;
12694
+ if (unit === "rem") return amount2 * 16;
12695
+ if (unit === "em") return amount2 * (inherited ?? 16);
12696
+ if (unit === "%") return amount2 / 100 * (inherited ?? 16);
12697
+ return amount2;
11267
12698
  }
11268
12699
  function requiredContrast(context) {
11269
12700
  const large = (context.fontSize ?? 16) >= 24 || (context.fontSize ?? 16) >= 18.66 && (context.fontWeight ?? 400) >= 700;
@@ -11280,8 +12711,8 @@ function elementId(props) {
11280
12711
  const value = props.id ?? props["data-vizmatic-id"];
11281
12712
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
11282
12713
  }
11283
- function resolveFunctionComponent(node, trustedComponents) {
11284
- if (!isValidElement3(node) || typeof node.type !== "function" || trustedComponents.has(node.type)) return void 0;
12714
+ function resolveFunctionComponent(node, trustedComponents2) {
12715
+ if (!isValidElement3(node) || typeof node.type !== "function" || trustedComponents2.has(node.type)) return void 0;
11285
12716
  const component = node.type;
11286
12717
  if (component.__vizmaticPrimitive) return void 0;
11287
12718
  if (component.prototype?.isReactComponent) return void 0;
@@ -11291,13 +12722,13 @@ function resolveFunctionComponent(node, trustedComponents) {
11291
12722
  return void 0;
11292
12723
  }
11293
12724
  }
11294
- function analyzeContrast(element, theme, trustedComponents = /* @__PURE__ */ new Set(), rootBackground2) {
12725
+ function analyzeContrast(element, theme, trustedComponents2 = /* @__PURE__ */ new Set(), rootBackground2) {
11295
12726
  const diagnostics = [];
11296
12727
  const seen = /* @__PURE__ */ new Set();
11297
12728
  let visited = 0;
11298
12729
  function visit(node, inherited, path) {
11299
12730
  if (visited++ >= MAX_CONTRAST_NODES || !isValidElement3(node)) return;
11300
- const resolved = resolveFunctionComponent(node, trustedComponents);
12731
+ const resolved = resolveFunctionComponent(node, trustedComponents2);
11301
12732
  if (resolved !== void 0) {
11302
12733
  visit(resolved, inherited, path);
11303
12734
  return;
@@ -11306,7 +12737,7 @@ function analyzeContrast(element, theme, trustedComponents = /* @__PURE__ */ new
11306
12737
  const style = typeof node.type === "string" ? styleRecord(props.style) : {};
11307
12738
  const backgroundImage = typeof style.backgroundImage === "string" ? style.backgroundImage.trim().toLowerCase() : "";
11308
12739
  const backgroundShorthand = typeof style.background === "string" ? style.background.trim() : "";
11309
- const isBackgroundWrapper = typeof node.type === "function" && (trustedComponents.has(node.type) || Boolean(node.type.__vizmaticPrimitive));
12740
+ const isBackgroundWrapper = typeof node.type === "function" && (trustedComponents2.has(node.type) || Boolean(node.type.__vizmaticPrimitive));
11310
12741
  const wrapperBackground = isBackgroundWrapper ? props.background : void 0;
11311
12742
  const hasUnresolvedBackground = backgroundImage !== "" && backgroundImage !== "none" || isUnresolvedColor(style.backgroundColor) || backgroundShorthand !== "" && backgroundShorthand.toLowerCase() !== "none" && !colorFromCss(backgroundShorthand) || isUnresolvedColor(wrapperBackground);
11312
12743
  const ownBackground = colorFromCss(style.backgroundColor) ?? colorFromCss(style.background) ?? colorFromCss(wrapperBackground);
@@ -11360,7 +12791,7 @@ function renderedTextNodes(nodes) {
11360
12791
  const style = styleRecord(node.props.style);
11361
12792
  const fontSize = fontSizePixels(style.fontSize, inherited?.fontSize) ?? 16;
11362
12793
  const textAlign = typeof style.textAlign === "string" ? style.textAlign : inherited?.textAlign ?? "left";
11363
- const text = node.textContent?.trim();
12794
+ const text = String(node.textContent ?? "").trim();
11364
12795
  if (text && node.width > 0 && node.height > 0) {
11365
12796
  const estimatedLines = Math.max(1, Math.round(node.height / Math.max(fontSize * 1.5, 1)));
11366
12797
  const paintHeight = Math.min(
@@ -11565,12 +12996,12 @@ function analyzeRenderedLayout(nodes, theme) {
11565
12996
  }
11566
12997
  return diagnostics;
11567
12998
  }
11568
- function analyzeWhitespaceBalance(bounds, width, height, theme) {
12999
+ function analyzeWhitespaceBalance(bounds2, width, height, theme) {
11569
13000
  const gutters = {
11570
- left: bounds.x,
11571
- right: width - bounds.x - bounds.width,
11572
- top: bounds.y,
11573
- bottom: height - bounds.y - bounds.height
13001
+ left: bounds2.x,
13002
+ right: width - bounds2.x - bounds2.width,
13003
+ top: bounds2.y,
13004
+ bottom: height - bounds2.y - bounds2.height
11574
13005
  };
11575
13006
  const diagnostics = [];
11576
13007
  const horizontalDifference = Math.abs(gutters.left - gutters.right);
@@ -11582,7 +13013,7 @@ function analyzeWhitespaceBalance(bounds, width, height, theme) {
11582
13013
  theme,
11583
13014
  message: `Horizontal gutters differ by ${Math.round(horizontalDifference)}px (${Math.round(gutters.left)}px left, ${Math.round(gutters.right)}px right).`,
11584
13015
  suggestion: "Recenter the composition, crop the canvas, or use the open space intentionally.",
11585
- location: { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height }
13016
+ location: { x: bounds2.x, y: bounds2.y, width: bounds2.width, height: bounds2.height }
11586
13017
  });
11587
13018
  }
11588
13019
  if (verticalDifference > 48 && verticalDifference / height > 0.12) {
@@ -11592,7 +13023,7 @@ function analyzeWhitespaceBalance(bounds, width, height, theme) {
11592
13023
  theme,
11593
13024
  message: `Vertical gutters differ by ${Math.round(verticalDifference)}px (${Math.round(gutters.top)}px top, ${Math.round(gutters.bottom)}px bottom).`,
11594
13025
  suggestion: "Recenter the composition, crop the canvas, or use the open space intentionally.",
11595
- location: { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height }
13026
+ location: { x: bounds2.x, y: bounds2.y, width: bounds2.width, height: bounds2.height }
11596
13027
  });
11597
13028
  }
11598
13029
  return diagnostics;
@@ -11816,7 +13247,7 @@ async function checkFrame(input, options = {}) {
11816
13247
  });
11817
13248
  const create = input.create ?? (() => input.scene);
11818
13249
  const failOn = options.failOn ?? "error";
11819
- const tempDir = await mkdtemp(join2(tmpdir(), "vizmatic-check-"));
13250
+ const tempDir = await mkdtemp(join4(tmpdir(), "vizmatic-check-"));
11820
13251
  const reports = [];
11821
13252
  try {
11822
13253
  for (const [themeIndex, theme] of themes.entries()) {
@@ -11848,7 +13279,7 @@ async function checkFrame(input, options = {}) {
11848
13279
  height,
11849
13280
  autoSize,
11850
13281
  background: options.background,
11851
- outputPath: join2(tempDir, `${themeIndex}.png`)
13282
+ outputPath: join4(tempDir, `${themeIndex}.png`)
11852
13283
  }));
11853
13284
  diagnostics2.push(...messageDiagnostics(rendered.messages, theme));
11854
13285
  if (rendered.value) {
@@ -11889,7 +13320,7 @@ async function checkFrame(input, options = {}) {
11889
13320
  height,
11890
13321
  autoSize: { width: true, height: true },
11891
13322
  background: options.background,
11892
- outputPath: join2(tempDir, `${themeIndex}-suggestion.png`)
13323
+ outputPath: join4(tempDir, `${themeIndex}-suggestion.png`)
11893
13324
  }));
11894
13325
  const suggestedDimensions = suggestion.value ? { width: suggestion.value.width, height: suggestion.value.height } : void 0;
11895
13326
  diagnostics2.push({
@@ -11916,7 +13347,7 @@ async function checkFrame(input, options = {}) {
11916
13347
  });
11917
13348
  }
11918
13349
  } finally {
11919
- await rm(tempDir, { recursive: true, force: true });
13350
+ await rm3(tempDir, { recursive: true, force: true });
11920
13351
  }
11921
13352
  const summary = counts(reports);
11922
13353
  const diagnostics = reports.flatMap(({ diagnostics: themeDiagnostics }) => themeDiagnostics);
@@ -11984,6 +13415,8 @@ export {
11984
13415
  ProgressRow,
11985
13416
  QuadrantChart,
11986
13417
  Row,
13418
+ SCENE_LIMITS,
13419
+ SCENE_RUNTIME_VERSION,
11987
13420
  ScatterPlot,
11988
13421
  Scene,
11989
13422
  SequenceDiagram,
@@ -12010,10 +13443,16 @@ export {
12010
13443
  Watermark,
12011
13444
  WindowFrame,
12012
13445
  analyzeAnimationCadence,
13446
+ arcSwap,
13447
+ cameraSvgTransform,
12013
13448
  canvas,
12014
13449
  checkFrame,
12015
13450
  colors,
13451
+ createCanvasComponents,
13452
+ createCueTrack,
12016
13453
  createPlotArea,
13454
+ createPolylineMorph,
13455
+ createTeachingCanvas,
12017
13456
  cropPixels,
12018
13457
  defineAnimation,
12019
13458
  defineDiagramIcon,
@@ -12022,8 +13461,12 @@ export {
12022
13461
  detectBackgroundColor,
12023
13462
  detectContentBounds,
12024
13463
  detectOverflow,
13464
+ dotProduct,
13465
+ entropy,
13466
+ evaluateSceneSource,
12025
13467
  formatMathText,
12026
13468
  formatTensorShape,
13469
+ gaussian,
12027
13470
  getColor,
12028
13471
  getFonts,
12029
13472
  getGradient,
@@ -12040,24 +13483,48 @@ export {
12040
13483
  hold,
12041
13484
  importD2Graph,
12042
13485
  importMermaidGraph,
13486
+ interpolateCamera,
12043
13487
  keyframe,
13488
+ layoutAllocation,
13489
+ layoutCellGrid,
13490
+ layoutTokenRow,
13491
+ lerpArray,
12044
13492
  loadAdditionalAsset,
13493
+ morphPolyline,
13494
+ multiplyMatrices,
13495
+ normalizeVector,
12045
13496
  normalizeWatermark,
12046
13497
  parallel,
13498
+ pointAlongPath,
13499
+ prepareScene,
13500
+ projectWorldPoint,
12047
13501
  renderAnimatedGif,
12048
13502
  renderAnimatedGifWithOutput,
12049
13503
  renderAnimationGif,
12050
13504
  renderAnimationGifWithOutput,
13505
+ renderAnimationVideo,
13506
+ renderMathSvg,
13507
+ renderRgbaVideo,
13508
+ renderSceneFrame,
13509
+ renderSceneVideo,
12051
13510
  renderToBuffer,
12052
13511
  renderToPng,
12053
13512
  renderToPngWithOutput,
12054
13513
  renderToSvg,
12055
13514
  sampleAnimation,
13515
+ sampleAnimationFrame,
12056
13516
  sampleAnimationFrames,
13517
+ sampleFunction,
13518
+ sampleGaussian,
13519
+ seededRandom,
13520
+ smoothstep,
13521
+ stableSoftmax,
12057
13522
  styles,
12058
13523
  toneGradients,
13524
+ tracePolyline,
12059
13525
  tween,
12060
13526
  typography,
13527
+ videoFrameSchedule,
12061
13528
  withColorAlpha,
12062
13529
  wrapWithBrand,
12063
13530
  wrapWithWatermark