vizmatic 0.3.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/PROMPT.md +75 -525
  2. package/README.md +87 -578
  3. package/ROADMAP.md +49 -67
  4. package/SCIENCE.md +250 -0
  5. package/assets/THIRD_PARTY_LICENSES.md +40 -1
  6. package/assets/fonts/InstrumentSerif-Italic.ttf +0 -0
  7. package/assets/fonts/InstrumentSerif-Regular.ttf +0 -0
  8. package/assets/licenses/raster-codecs-MIT.txt +74 -0
  9. package/dist/chunk-3F2VQ7NW.js +1 -0
  10. package/dist/chunk-4XE64I2U.js +755 -0
  11. package/dist/chunk-JHHPLALU.js +79 -0
  12. package/dist/chunk-LTX44BAE.js +112 -0
  13. package/dist/chunk-MLKGABMK.js +9 -0
  14. package/dist/chunk-PSBF4TEK.js +1 -0
  15. package/dist/chunk-RPAHMKAR.js +605 -0
  16. package/dist/chunk-RWF4VBUL.js +3617 -0
  17. package/dist/chunk-WHT6HRMX.js +4201 -0
  18. package/dist/cli.js +371 -10
  19. package/dist/index.cjs +11129 -2922
  20. package/dist/index.d.cts +1225 -369
  21. package/dist/index.d.ts +1225 -369
  22. package/dist/index.js +6220 -3015
  23. package/dist/math-LXB4FH4E.js +7 -0
  24. package/dist/math-QVCETQDQ.js +1 -0
  25. package/dist/scene-browser-assets.d.ts +38 -0
  26. package/dist/scene-browser-assets.js +53 -0
  27. package/dist/scene-browser-chunks/chunk-5MVLYGXM.js +70 -0
  28. package/dist/scene-browser-chunks/chunk-ASXKN3NU.js +1 -0
  29. package/dist/scene-browser-chunks/chunk-CM5Y5LZP.js +1 -0
  30. package/dist/scene-browser-chunks/chunk-DP7NB4EW.js +6 -0
  31. package/dist/scene-browser-chunks/emscripten-module.browser-M5AEKJGE.js +1 -0
  32. package/dist/scene-browser-chunks/ffi-FL6ORJU3.js +1 -0
  33. package/dist/scene-browser-chunks/module-ES6BEMUI-JD5S5VKR.js +1 -0
  34. package/dist/scene-browser-chunks/module-asyncify-2EFITU5U-HWPFJFJC.js +1 -0
  35. package/dist/scene-browser-chunks/scene-browser-layout-M3XSXMV4.js +27 -0
  36. package/dist/scene-browser.d.ts +117 -0
  37. package/dist/scene-browser.js +220 -0
  38. package/dist/scene-cli.d.ts +1 -0
  39. package/dist/scene-cli.js +4 -0
  40. package/dist/scene-runtime.cjs +995 -0
  41. package/dist/scene-runtime.d.cts +81 -0
  42. package/dist/scene-runtime.d.ts +81 -0
  43. package/dist/scene-runtime.js +22 -0
  44. package/dist/server-2FYHZ4UO.js +331 -0
  45. package/dist/stage-browser/browser.d.ts +2482 -0
  46. package/dist/stage-browser/chunk-SQE76S5B.js +1 -0
  47. package/dist/stage-browser/chunk-VZNL6JY2.js +59 -0
  48. package/dist/stage-browser/dagre.esm-N2NIVIAZ.js +6 -0
  49. package/dist/stage-browser/math-4WFNHVV2.js +18 -0
  50. package/dist/stage-browser/stage.js +19 -0
  51. package/dist/stage-export.cjs +4950 -0
  52. package/dist/stage-export.d.cts +112 -0
  53. package/dist/stage-export.d.ts +112 -0
  54. package/dist/stage-export.js +544 -0
  55. package/dist/stage.cjs +9745 -0
  56. package/dist/stage.d.cts +1678 -0
  57. package/dist/stage.d.ts +1678 -0
  58. package/dist/stage.js +5404 -0
  59. package/dist/svg-import-Djj2q7Pc.d.cts +742 -0
  60. package/dist/svg-import-Djj2q7Pc.d.ts +742 -0
  61. package/dist/video-CcHW1qhV.d.cts +532 -0
  62. package/dist/video-CcHW1qhV.d.ts +532 -0
  63. package/examples/README.md +18 -0
  64. package/examples/agent-pipeline.tsx +4 -4
  65. package/examples/animated-pipeline.tsx +1 -5
  66. package/examples/attention-head.tsx +12 -12
  67. package/examples/aurora-incident.tsx +4 -3
  68. package/examples/building-blocks.tsx +8 -9
  69. package/examples/catalog-charts.tsx +4 -4
  70. package/examples/catalog-content.tsx +7 -9
  71. package/examples/catalog-convolution-kernel.tsx +116 -0
  72. package/examples/catalog-data.tsx +2 -8
  73. package/examples/catalog-dataflow.tsx +5 -9
  74. package/examples/catalog-dense.tsx +80 -0
  75. package/examples/catalog-deployment.tsx +5 -11
  76. package/examples/catalog-diagrams.tsx +13 -16
  77. package/examples/catalog-drawing.tsx +7 -7
  78. package/examples/catalog-flows.tsx +4 -4
  79. package/examples/catalog-foundations.tsx +11 -11
  80. package/examples/catalog-gaussian-blur.tsx +146 -0
  81. package/examples/catalog-image-tensors.tsx +115 -0
  82. package/examples/catalog-ml.tsx +36 -31
  83. package/examples/catalog-numeric-matrices.tsx +93 -0
  84. package/examples/catalog-photo-blur.tsx +209 -0
  85. package/examples/catalog-science-ai.tsx +130 -0
  86. package/examples/catalog-science-chemistry.tsx +103 -0
  87. package/examples/catalog-science-math.tsx +93 -0
  88. package/examples/catalog-science-physics.tsx +84 -0
  89. package/examples/catalog-sequence.tsx +59 -38
  90. package/examples/data-pipeline-lineage-presentation.tsx +5 -0
  91. package/examples/data-pipeline-lineage.tsx +85 -0
  92. package/examples/daybreak-launch.tsx +1 -0
  93. package/examples/desired-quadrant.tsx +7 -8
  94. package/examples/engineering-dashboard-presentation.tsx +13 -0
  95. package/examples/engineering-dashboard.tsx +160 -0
  96. package/examples/engineering-flow.tsx +2 -4
  97. package/examples/eval-dashboard.tsx +6 -6
  98. package/examples/films/attention.ts +278 -0
  99. package/examples/films/cache-miss.ts +431 -0
  100. package/examples/films/catalog.json +132 -0
  101. package/examples/films/central-limit.ts +269 -0
  102. package/examples/films/complex-maps.ts +273 -0
  103. package/examples/films/deck-example.ts +224 -0
  104. package/examples/films/euler-circle.ts +179 -0
  105. package/examples/films/fourier-epicycles.ts +265 -0
  106. package/examples/films/gradient-descent.ts +345 -0
  107. package/examples/films/linear-maps.ts +175 -0
  108. package/examples/films/lorenz.ts +207 -0
  109. package/examples/films/pythagoras.ts +185 -0
  110. package/examples/films/taylor-series.ts +159 -0
  111. package/examples/films/vizmatic-title.ts +117 -0
  112. package/examples/llm-serving-stack-presentation.tsx +5 -0
  113. package/examples/llm-serving-stack.tsx +94 -0
  114. package/examples/model-garden.tsx +1 -0
  115. package/examples/model-router.tsx +6 -6
  116. package/examples/nccl-all-gather.tsx +3 -3
  117. package/examples/nccl-all-reduce.tsx +3 -3
  118. package/examples/nccl-all-to-all.tsx +1 -1
  119. package/examples/nccl-broadcast.tsx +1 -1
  120. package/examples/nccl-reduce-scatter.tsx +5 -5
  121. package/examples/orthogonal-routing.tsx +4 -4
  122. package/examples/pareto-frontier.tsx +9 -10
  123. package/examples/presentation-frame.tsx +6 -6
  124. package/examples/pressure-mechanism.scene.json +14 -0
  125. package/examples/production-system-map-presentation.tsx +5 -0
  126. package/examples/production-system-map.tsx +130 -0
  127. package/examples/rag-graph.tsx +7 -7
  128. package/examples/release-card.tsx +5 -5
  129. package/examples/spec-anatomy.tsx +5 -5
  130. package/examples/system-architecture.tsx +19 -32
  131. package/examples/theme-system.tsx +1 -1
  132. package/examples/token-matrix.tsx +4 -2
  133. package/examples/transparent-badge.tsx +1 -2
  134. package/examples/videos/README.md +62 -0
  135. package/examples/videos/calculus-tangent.tsx +101 -0
  136. package/examples/videos/catalyst-pathway.tsx +56 -0
  137. package/examples/videos/causal-attention.tsx +91 -0
  138. package/examples/videos/convolution-kernel.tsx +34 -0
  139. package/examples/videos/gaussian-blur.tsx +32 -0
  140. package/examples/videos/image-to-matrix.tsx +22 -0
  141. package/examples/videos/matrix-multiplication.tsx +128 -0
  142. package/examples/videos/photo-gaussian-blur.tsx +39 -0
  143. package/examples/videos/request-lifecycle.tsx +99 -0
  144. package/examples/videos/signal-to-story.tsx +126 -0
  145. package/examples/videos/wave-interference.tsx +80 -0
  146. package/examples/vizmatic-bare.d.ts +1 -0
  147. package/examples/vizmatic-hero.tsx +9 -18
  148. package/examples/website-workflow.tsx +7 -7
  149. package/examples/weekend-field-notes.tsx +3 -2
  150. package/package.json +77 -12
@@ -0,0 +1,755 @@
1
+ import {
2
+ getThemeColors
3
+ } from "./chunk-RPAHMKAR.js";
4
+
5
+ // src/scene-runtime.ts
6
+ import { getQuickJS } from "quickjs-emscripten";
7
+ import { transform } from "sucrase";
8
+
9
+ // src/bare-source.ts
10
+ function readJsxTag(source, start) {
11
+ if (source.startsWith("<>", start)) return { closing: false, end: start + 2, selfClosing: false };
12
+ if (source.startsWith("</>", start)) return { closing: true, end: start + 3, selfClosing: false };
13
+ const head = source.slice(start).match(/^<\s*(\/\s*)?[A-Za-z][\w.:$-]*/);
14
+ if (!head) return void 0;
15
+ const closing = Boolean(head[1]);
16
+ let quote;
17
+ let braces = 0;
18
+ let escaped = false;
19
+ for (let index = start + head[0].length; index < source.length; index += 1) {
20
+ const character = source[index];
21
+ if (quote) {
22
+ if (escaped) escaped = false;
23
+ else if (character === "\\") escaped = true;
24
+ else if (character === quote) quote = void 0;
25
+ continue;
26
+ }
27
+ if (character === '"' || character === "'" || character === "`") {
28
+ quote = character;
29
+ continue;
30
+ }
31
+ if (character === "{") {
32
+ braces += 1;
33
+ continue;
34
+ }
35
+ if (character === "}") {
36
+ braces = Math.max(0, braces - 1);
37
+ continue;
38
+ }
39
+ if (character !== ">" || braces > 0) continue;
40
+ const beforeClose = source.slice(start, index).trimEnd();
41
+ return {
42
+ closing,
43
+ end: index + 1,
44
+ selfClosing: !closing && beforeClose.endsWith("/")
45
+ };
46
+ }
47
+ return void 0;
48
+ }
49
+ function skipJsxExpression(source, start) {
50
+ let depth = 0;
51
+ let quote;
52
+ let escaped = false;
53
+ let blockComment = false;
54
+ let lineComment = false;
55
+ for (let index = start; index < source.length; index += 1) {
56
+ const character = source[index];
57
+ const next = source[index + 1];
58
+ if (lineComment) {
59
+ if (character === "\n") lineComment = false;
60
+ continue;
61
+ }
62
+ if (blockComment) {
63
+ if (character === "*" && next === "/") {
64
+ blockComment = false;
65
+ index += 1;
66
+ }
67
+ continue;
68
+ }
69
+ if (quote) {
70
+ if (escaped) escaped = false;
71
+ else if (character === "\\") escaped = true;
72
+ else if (character === quote) quote = void 0;
73
+ continue;
74
+ }
75
+ if (character === "/" && next === "/") {
76
+ lineComment = true;
77
+ index += 1;
78
+ continue;
79
+ }
80
+ if (character === "/" && next === "*") {
81
+ blockComment = true;
82
+ index += 1;
83
+ continue;
84
+ }
85
+ if (character === '"' || character === "'" || character === "`") {
86
+ quote = character;
87
+ continue;
88
+ }
89
+ if (character === "{") depth += 1;
90
+ else if (character === "}" && --depth === 0) return index + 1;
91
+ }
92
+ return void 0;
93
+ }
94
+ function findJsxEnd(source, start) {
95
+ let depth = 0;
96
+ for (let index = start; index < source.length; index += 1) {
97
+ if (source[index] === "{") {
98
+ const expressionEnd = skipJsxExpression(source, index);
99
+ if (expressionEnd == null) return void 0;
100
+ index = expressionEnd - 1;
101
+ continue;
102
+ }
103
+ if (source[index] !== "<") continue;
104
+ const tag = readJsxTag(source, index);
105
+ if (!tag) continue;
106
+ if (tag.closing) depth -= 1;
107
+ else if (!tag.selfClosing) depth += 1;
108
+ index = tag.end - 1;
109
+ if (depth === 0) return tag.end;
110
+ }
111
+ return void 0;
112
+ }
113
+ function hasOnlyTrailingSyntax(source) {
114
+ let index = 0;
115
+ while (index < source.length) {
116
+ const rest = source.slice(index);
117
+ const whitespace = rest.match(/^[\s;)]*/)?.[0].length ?? 0;
118
+ index += whitespace;
119
+ if (source.startsWith("//", index)) {
120
+ const newline = source.indexOf("\n", index + 2);
121
+ index = newline < 0 ? source.length : newline + 1;
122
+ continue;
123
+ }
124
+ if (source.startsWith("/*", index)) {
125
+ const end = source.indexOf("*/", index + 2);
126
+ if (end < 0) return false;
127
+ index = end + 2;
128
+ continue;
129
+ }
130
+ return index >= source.length;
131
+ }
132
+ return true;
133
+ }
134
+ function extractRootJsx(source) {
135
+ const body = source.replace(/^(?:\s*\()+\s*/, "");
136
+ const end = findJsxEnd(body, 0);
137
+ return (end == null ? body : body.slice(0, end)).trim();
138
+ }
139
+ function findBareRootJsxStart(source, allowNativeTags = false) {
140
+ const candidates = source.matchAll(allowNativeTags ? /(^|\n)([\t ]*)(?:(?:export\s+default\s+)?(?:\(\s*)*)(<(?:[A-Za-z]|>))/g : /(^|\n)([\t ]*)(?:(?:export\s+default\s+)?(?:\(\s*)*)(<(?:[A-Z]|>))/g);
141
+ for (const candidate of candidates) {
142
+ if (candidate.index == null) continue;
143
+ const lineStart = candidate.index + (candidate[1]?.length ?? 0);
144
+ const expressionStart = lineStart + (candidate[2]?.length ?? 0);
145
+ const jsxStart = candidate.index + candidate[0].lastIndexOf(candidate[3] ?? "<");
146
+ const jsxEnd = findJsxEnd(source, jsxStart);
147
+ if (jsxEnd != null && hasOnlyTrailingSyntax(source.slice(jsxEnd))) return expressionStart;
148
+ }
149
+ return -1;
150
+ }
151
+
152
+ // src/scene-components.ts
153
+ var SCENE_COMPONENT_NAMES = Object.freeze([
154
+ "Arrow",
155
+ "ArrowMarkerDef",
156
+ "AttentionMatrix",
157
+ "AxisPlot",
158
+ "Badge",
159
+ "BadgePill",
160
+ "BarChart",
161
+ "Board",
162
+ "Box",
163
+ "CalloutCard",
164
+ "Canvas",
165
+ "CanvasItem",
166
+ "Card",
167
+ "ChartFrame",
168
+ "CodeBlock",
169
+ "Column",
170
+ "Comparison",
171
+ "Connector",
172
+ "DashedLine",
173
+ "DataTable",
174
+ "DataflowDiagram",
175
+ "DeploymentDiagram",
176
+ "DetailList",
177
+ "DiagramLegend",
178
+ "DonutChart",
179
+ "DotPoint",
180
+ "EquationCard",
181
+ "FactRows",
182
+ "Flow",
183
+ "FlowArrow",
184
+ "FreeBodyDiagram",
185
+ "GeometryDiagram",
186
+ "GradientChip",
187
+ "GraphDiagram",
188
+ "Grid",
189
+ "Heatmap",
190
+ "Icon",
191
+ "InlineBar",
192
+ "IntervalPlot",
193
+ "KeyValueList",
194
+ "LayeredNetwork",
195
+ "Legend",
196
+ "LineChart",
197
+ "MathText",
198
+ "Matrix",
199
+ "MetricCard",
200
+ "MetricStrip",
201
+ "MiniBarChart",
202
+ "MoleculeDiagram",
203
+ "NumberLine",
204
+ "Panel",
205
+ "ParetoBarChart",
206
+ "ParetoChart",
207
+ "PieChart",
208
+ "Pipeline",
209
+ "PixelGrid",
210
+ "ProgressList",
211
+ "ProgressRow",
212
+ "QuadrantChart",
213
+ "ReactionEnergyDiagram",
214
+ "ReactionEquation",
215
+ "Row",
216
+ "ScatterPlot",
217
+ "Scene",
218
+ "SequenceDiagram",
219
+ "SmallMultiples",
220
+ "Sparkline",
221
+ "Stack",
222
+ "StackedBar",
223
+ "StatusDot",
224
+ "StatusList",
225
+ "StatusRow",
226
+ "StepCard",
227
+ "SvgFrame",
228
+ "SvgMathText",
229
+ "SvgPoint",
230
+ "TagList",
231
+ "TextLabel",
232
+ "Tile",
233
+ "TileGrid",
234
+ "TiledMatrix",
235
+ "Timeline",
236
+ "TitleBar",
237
+ "ToneStrip",
238
+ "TransformerTopology",
239
+ "TreeDiagram",
240
+ "ValuePill",
241
+ "VectorArrow",
242
+ "VectorSegment",
243
+ "WaveDiagram",
244
+ "WindowFrame"
245
+ ]);
246
+ var SCENE_DOM_TAGS = Object.freeze([
247
+ "div",
248
+ "span",
249
+ "p",
250
+ "strong",
251
+ "em",
252
+ "b",
253
+ "i",
254
+ "br",
255
+ "svg",
256
+ "g",
257
+ "path",
258
+ "rect",
259
+ "circle",
260
+ "ellipse",
261
+ "line",
262
+ "polyline",
263
+ "polygon",
264
+ "text",
265
+ "tspan",
266
+ "defs",
267
+ "clipPath",
268
+ "linearGradient",
269
+ "radialGradient",
270
+ "stop",
271
+ "pattern",
272
+ "marker",
273
+ "mask",
274
+ "title",
275
+ "desc",
276
+ "use"
277
+ ]);
278
+
279
+ // src/scene-contract.ts
280
+ var SCENE_RUNTIME_VERSION = "vizmatic-scene/1";
281
+ var SCENE_LIMITS = Object.freeze({
282
+ sourceBytes: 131072,
283
+ graphBytes: 2097152,
284
+ nodes: 2e3,
285
+ depth: 64,
286
+ stringLength: 65536,
287
+ canvasEdge: 1920,
288
+ canvasPixels: 2073600,
289
+ duration: 120,
290
+ frames: 3600,
291
+ memoryBytes: 64 * 1024 * 1024,
292
+ stackBytes: 256 * 1024,
293
+ evaluationMs: 250
294
+ });
295
+ var unsafeKeys = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
296
+ function isUnsafeSceneKey(key) {
297
+ return unsafeKeys.has(key);
298
+ }
299
+ function normalizeSceneRequest(request) {
300
+ if (!request || typeof request !== "object") throw new Error("A scene request is required.");
301
+ if (typeof request.source !== "string" || !request.source.trim() || new TextEncoder().encode(request.source).byteLength > SCENE_LIMITS.sourceBytes) {
302
+ throw new Error(`Scene source must contain between 1 and ${SCENE_LIMITS.sourceBytes} UTF-8 bytes.`);
303
+ }
304
+ for (const name of ["width", "height"]) {
305
+ const value = request[name];
306
+ if (!Number.isInteger(value) || value < 2 || value > SCENE_LIMITS.canvasEdge || value % 2 !== 0) {
307
+ throw new Error(`Scene ${name} must be an even integer from 2 to ${SCENE_LIMITS.canvasEdge}.`);
308
+ }
309
+ }
310
+ if (request.width * request.height > SCENE_LIMITS.canvasPixels) {
311
+ throw new Error(`Scene canvas supports at most ${SCENE_LIMITS.canvasPixels} pixels.`);
312
+ }
313
+ if (!Number.isFinite(request.duration) || request.duration <= 0 || request.duration > SCENE_LIMITS.duration) {
314
+ throw new Error(`Scene duration must be greater than 0 and at most ${SCENE_LIMITS.duration} seconds.`);
315
+ }
316
+ const fps = request.fps ?? 24;
317
+ if (!Number.isInteger(fps) || fps < 1 || fps > 60) throw new Error("Scene fps must be an integer from 1 to 60.");
318
+ const frameCount = Math.round(request.duration * fps);
319
+ if (frameCount < 1 || frameCount > SCENE_LIMITS.frames) {
320
+ throw new Error(`Scene duration must round to between 1 and ${SCENE_LIMITS.frames} frames.`);
321
+ }
322
+ const theme = request.theme ?? "dark";
323
+ if (theme !== "dark" && theme !== "light") throw new Error("Scene theme must be dark or light.");
324
+ const seed = request.seed ?? 0;
325
+ if (!Number.isInteger(seed) || seed < 0 || seed > 4294967295) throw new Error("Scene seed must be a uint32 integer.");
326
+ const cues = /* @__PURE__ */ Object.create(null);
327
+ if (request.cues !== void 0 && (!request.cues || typeof request.cues !== "object" || Array.isArray(request.cues))) {
328
+ throw new Error("Scene cues must be an object containing times in seconds.");
329
+ }
330
+ const cueEntries = Object.entries(request.cues ?? {});
331
+ if (cueEntries.length > 128) throw new Error("Scene supports at most 128 cues.");
332
+ for (const [name, time] of cueEntries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
333
+ if (!/^[A-Za-z][\w.-]{0,79}$/.test(name) || isUnsafeSceneKey(name) || !Number.isFinite(time) || time < 0 || time > request.duration) {
334
+ throw new Error(`Invalid scene cue ${JSON.stringify(name)}. Cue times must be within the requested duration.`);
335
+ }
336
+ cues[name] = time;
337
+ }
338
+ return {
339
+ source: request.source,
340
+ width: request.width,
341
+ height: request.height,
342
+ duration: request.duration,
343
+ fps,
344
+ theme,
345
+ cues,
346
+ seed,
347
+ frameCount
348
+ };
349
+ }
350
+ function normalizeSceneTime(time, duration) {
351
+ const value = time ?? 0;
352
+ if (!Number.isFinite(value) || value < 0 || value > duration) {
353
+ throw new Error("Scene time must be within its duration, in seconds.");
354
+ }
355
+ return value;
356
+ }
357
+ async function sceneSha256(value) {
358
+ const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
359
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));
360
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
361
+ }
362
+
363
+ // src/scene-prop-limits.ts
364
+ function integer(value, name, min, max) {
365
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
366
+ throw new Error(`Editable scene ${name} must be an integer from ${min} to ${max}.`);
367
+ }
368
+ return value;
369
+ }
370
+ function finite(value, name) {
371
+ if (typeof value !== "number" || !Number.isFinite(value) || Math.abs(value) > 32768) {
372
+ throw new Error(`Editable scene ${name} must be finite and within 32768 canvas units.`);
373
+ }
374
+ return value;
375
+ }
376
+ function entries(value, name, max) {
377
+ if (value === void 0) return [];
378
+ if (!Array.isArray(value) || value.length > max) throw new Error(`Editable scene ${name} supports at most ${max} entries.`);
379
+ return value;
380
+ }
381
+ function record(value, name) {
382
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Editable scene ${name} must be an object.`);
383
+ return value;
384
+ }
385
+ function validateSceneComponentProps(name, props) {
386
+ let values = 0;
387
+ const check = (value, key) => {
388
+ if (++values > 8192) throw new Error(`Editable scene ${name} props exceed their value budget.`);
389
+ if (typeof value === "number") {
390
+ if (/^(?:width|height|x|y|x1|y1|x2|y2|cx|cy|r|rx|ry|radius|length|padding|gap|nodeWidth|nodeHeight|cellSize|cellWidth|cellHeight|fontSize|nodeSize|tileWidth|minHeight)$/i.test(key)) finite(value, `${name}.${key}`);
391
+ if (/^(?:rows|cols|columns|count|repeat|gridCount|tickCount)$/i.test(key)) integer(value, `${name}.${key}`, key === "gridCount" ? 0 : 1, 2e3);
392
+ }
393
+ if (Array.isArray(value)) value.forEach((item) => check(item, ""));
394
+ else if (value && typeof value === "object") {
395
+ if (value.kind !== "vizmatic.element") Object.entries(value).forEach(([property, item]) => check(item, property));
396
+ }
397
+ };
398
+ Object.entries(props).forEach(([key, value]) => check(value, key));
399
+ if (name === "DashedLine") {
400
+ const x1 = finite(props.x1, "DashedLine.x1"), y1 = finite(props.y1, "DashedLine.y1");
401
+ const x2 = finite(props.x2, "DashedLine.x2"), y2 = finite(props.y2, "DashedLine.y2");
402
+ const spacing = props.dotSpacing ?? 8;
403
+ if (typeof spacing !== "number" || !Number.isFinite(spacing) || spacing <= 0 || Math.hypot(x2 - x1, y2 - y1) / spacing > 2e3) {
404
+ throw new Error("Editable scene DashedLine requires positive dotSpacing and at most 2000 dots.");
405
+ }
406
+ }
407
+ if (name === "TileGrid" && props.columns !== void 0) integer(props.columns, "TileGrid.columns", 1, 2e3);
408
+ if (name === "TiledMatrix") {
409
+ const rows = integer(props.rows, "TiledMatrix.rows", 1, 2e3);
410
+ const cols = integer(props.cols, "TiledMatrix.cols", 1, 2e3);
411
+ if (rows * cols > 2e3) throw new Error("Editable scene TiledMatrix supports at most 2000 cells.");
412
+ }
413
+ if (name === "AxisPlot" && props.gridCount !== void 0) integer(props.gridCount, "AxisPlot.gridCount", 0, 100);
414
+ if (["GraphDiagram", "DataflowDiagram", "DeploymentDiagram", "TransformerTopology"].includes(name)) {
415
+ for (const key of ["nodes", "groups", "boundaries", "blocks"]) entries(props[key], `${name}.${key}`, 128);
416
+ for (const key of ["edges", "connections", "routes"]) entries(props[key], `${name}.${key}`, 256);
417
+ }
418
+ if (name === "TransformerTopology" && props.expandRepeats) {
419
+ const blocks = entries(props.blocks, "TransformerTopology.blocks", 128);
420
+ const total = blocks.reduce((sum, block) => sum + integer(record(block, "Transformer block").repeat ?? 1, "Transformer block.repeat", 1, 128), 0);
421
+ if (total > 128) throw new Error("Editable scene TransformerTopology expands to at most 128 nodes.");
422
+ }
423
+ if (name === "LayeredNetwork") {
424
+ const layers = entries(props.layers, "LayeredNetwork.layers", 16);
425
+ const counts = layers.map((layer) => entries(record(layer, "Network layer").nodes, "Network layer.nodes", 32).length);
426
+ const edges = counts.reduce((sum, count, index) => sum + count * (counts[index - 1] ?? 0), 0);
427
+ if (edges > 1024) throw new Error("Editable scene LayeredNetwork supports at most 1024 connections.");
428
+ }
429
+ if (name === "TreeDiagram" && props.root !== void 0) {
430
+ let count = 0;
431
+ const tree = (node) => {
432
+ if (++count > 128) throw new Error("Editable scene TreeDiagram supports at most 128 nodes.");
433
+ entries(record(node, "Tree node").children, "Tree node.children", 128).forEach(tree);
434
+ };
435
+ tree(props.root);
436
+ }
437
+ if (name === "ParetoChart") entries(props.points, "ParetoChart.points", 512);
438
+ if (name === "NumberLine") {
439
+ entries(props.ticks, "NumberLine.ticks", 128);
440
+ entries(props.markers, "NumberLine.markers", 64);
441
+ }
442
+ if (name === "GeometryDiagram") {
443
+ entries(props.points, "GeometryDiagram.points", 128);
444
+ entries(props.segments, "GeometryDiagram.segments", 256);
445
+ entries(props.angles, "GeometryDiagram.angles", 64);
446
+ }
447
+ if (name === "FreeBodyDiagram") entries(props.forces, "FreeBodyDiagram.forces", 32);
448
+ if (name === "WaveDiagram") {
449
+ entries(props.waves, "WaveDiagram.waves", 8);
450
+ if (props.sampleCount !== void 0) integer(props.sampleCount, "WaveDiagram.sampleCount", 2, 512);
451
+ }
452
+ if (name === "MoleculeDiagram") {
453
+ entries(props.atoms, "MoleculeDiagram.atoms", 64);
454
+ entries(props.bonds, "MoleculeDiagram.bonds", 96);
455
+ }
456
+ if (name === "ReactionEquation") {
457
+ entries(props.reactants, "ReactionEquation.reactants", 16);
458
+ entries(props.products, "ReactionEquation.products", 16);
459
+ }
460
+ if (name === "AttentionMatrix") {
461
+ for (const row of entries(props.weights, "AttentionMatrix.weights", 32)) entries(row, "AttentionMatrix row", 32);
462
+ for (const row of entries(props.mask, "AttentionMatrix.mask", 32)) entries(row, "AttentionMatrix mask row", 32);
463
+ }
464
+ if (name === "PixelGrid") {
465
+ const rows = entries(props.pixels, "PixelGrid.pixels", 128);
466
+ const cells = rows.reduce((sum, row) => sum + entries(row, "PixelGrid row", 128).length, 0);
467
+ if (cells > 1024) throw new Error("Editable scene PixelGrid supports at most 1024 pixels.");
468
+ }
469
+ }
470
+
471
+ // src/scene-graph.ts
472
+ var componentNames = new Set(SCENE_COMPONENT_NAMES);
473
+ var domTags = new Set(SCENE_DOM_TAGS);
474
+ var localReference = /^#[A-Za-z_][\w:.-]*$/;
475
+ var localPaint = /^url\(\s*#[A-Za-z_][\w:.-]*\s*\)$/;
476
+ var resourceKeys = /^(?:background(?:image)?|fill|stroke|filter|clippath|mask(?:image)?|borderimage(?:source)?|liststyle(?:image)?|cursor|content)$/i;
477
+ function validateResource(value, key, inStyle) {
478
+ if (/^(?:src|href|xlinkhref|xlink:href|srcset|poster|action|formaction)$/i.test(key) && !localReference.test(value)) {
479
+ throw new Error("Scene resource references must be local SVG fragment IDs. External assets are disabled.");
480
+ }
481
+ if ((inStyle || resourceKeys.test(key) || /gradient$/i.test(key)) && (/\\|\/\*/.test(value) || /(?:https?|file|ftp|data|blob|javascript):|\/\//i.test(value) || /url\s*\(/i.test(value) && !localPaint.test(value))) {
482
+ throw new Error("Scene CSS cannot load external resources or escaped resource expressions.");
483
+ }
484
+ }
485
+ function validateResolvedSceneResources(props) {
486
+ let values = 0;
487
+ const visit = (input, key, style, depth) => {
488
+ if (++values > 32e3 || depth > SCENE_LIMITS.depth * 2) throw new Error("Resolved scene props exceed their value budget.");
489
+ if (typeof input === "string") {
490
+ validateResource(input, key, style);
491
+ return;
492
+ }
493
+ if (Array.isArray(input)) {
494
+ input.forEach((item) => visit(item, key, style, depth + 1));
495
+ return;
496
+ }
497
+ if (input && typeof input === "object") {
498
+ for (const [property, value] of Object.entries(input)) {
499
+ if (property === "children") continue;
500
+ if (property === "dangerouslySetInnerHTML" || property === "__html") throw new Error("Resolved scene cannot contain raw HTML.");
501
+ visit(value, property, style || /style$/i.test(property), depth + 1);
502
+ }
503
+ }
504
+ };
505
+ visit(props, "", false, 0);
506
+ }
507
+ function validateSceneGraph(value) {
508
+ let nodes = 0;
509
+ const visit = (input, depth, key = "", inStyle = false) => {
510
+ if (depth > SCENE_LIMITS.depth) throw new Error(`Scene graph exceeds depth ${SCENE_LIMITS.depth}.`);
511
+ if (++nodes > SCENE_LIMITS.nodes * 32) throw new Error("Scene graph contains too many values.");
512
+ if (input === null || typeof input === "boolean") return input;
513
+ if (typeof input === "number") {
514
+ if (!Number.isFinite(input) || Math.abs(input) > 1e9) throw new Error("Scene numbers must be finite and bounded.");
515
+ return input;
516
+ }
517
+ if (typeof input === "string") {
518
+ if (input.length > SCENE_LIMITS.stringLength) throw new Error("Scene string exceeds its length limit.");
519
+ validateResource(input, key, inStyle);
520
+ return input;
521
+ }
522
+ if (Array.isArray(input)) return input.map((item) => visit(item, depth + 1, key, inStyle));
523
+ if (!input || typeof input !== "object" || Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null) throw new Error("Scene props must be plain JSON values.");
524
+ const record2 = input;
525
+ const output = /* @__PURE__ */ Object.create(null);
526
+ for (const [property, item] of Object.entries(record2)) {
527
+ if (isUnsafeSceneKey(property) || /^on/i.test(property) || /^(?:xml:base|xmlBase)$/i.test(property) || property === "dangerouslySetInnerHTML" || property === "ref" || property === "__html") throw new Error(`Scene property ${JSON.stringify(property)} is not allowed.`);
528
+ output[property] = visit(item, depth + 1, property, inStyle || /style$/i.test(property));
529
+ }
530
+ if (record2.kind === "vizmatic.element") {
531
+ if (typeof record2.type !== "string" || !componentNames.has(record2.type) && !domTags.has(record2.type)) {
532
+ throw new Error(`Scene component ${JSON.stringify(record2.type)} is not supported.`);
533
+ }
534
+ if (!record2.props || typeof record2.props !== "object" || Array.isArray(record2.props) || !Array.isArray(record2.children) || Object.keys(record2).some((name) => !["kind", "type", "props", "children"].includes(name))) {
535
+ throw new Error("Invalid scene element.");
536
+ }
537
+ if (componentNames.has(record2.type)) validateSceneComponentProps(record2.type, output.props);
538
+ }
539
+ return output;
540
+ };
541
+ const graph = visit(value, 0);
542
+ let elementCount = 0;
543
+ const checkChildren = (child) => {
544
+ if (Array.isArray(child)) {
545
+ child.forEach(checkChildren);
546
+ return;
547
+ }
548
+ if (child === null || typeof child !== "object") return;
549
+ if (child.kind !== "vizmatic.element") throw new Error("Scene children must be JSX elements, text or numbers.");
550
+ if (++elementCount > SCENE_LIMITS.nodes) throw new Error(`Scene graph exceeds ${SCENE_LIMITS.nodes} elements.`);
551
+ const element = child;
552
+ element.children.forEach(checkChildren);
553
+ const checkProps = (prop) => {
554
+ if (Array.isArray(prop)) {
555
+ prop.forEach(checkProps);
556
+ return;
557
+ }
558
+ if (prop && typeof prop === "object") {
559
+ if (prop.kind === "vizmatic.element") checkChildren(prop);
560
+ else Object.values(prop).forEach(checkProps);
561
+ }
562
+ };
563
+ Object.values(element.props).forEach(checkProps);
564
+ };
565
+ checkChildren(graph);
566
+ return graph;
567
+ }
568
+
569
+ // src/scene-runtime.ts
570
+ var bootstrap = String.raw`
571
+ const __jsonStringify = JSON.stringify.bind(JSON);
572
+ const __objectEntries = Object.entries.bind(Object);
573
+ const __isArray = Array.isArray.bind(Array);
574
+ const __isFinite = Number.isFinite.bind(Number);
575
+ const __Error = Error;
576
+ const __ownDescriptor = Object.getOwnPropertyDescriptor.bind(Object);
577
+ const __freeze = (value) => {
578
+ if (value && typeof value === 'object') {
579
+ for (const child of Object.values(value)) __freeze(child);
580
+ Object.freeze(value);
581
+ }
582
+ return value;
583
+ };
584
+ const clamp = (value, min = 0, max = 1) => Math.max(min, Math.min(max, value));
585
+ const lerp = (from, to, amount) => from + (to - from) * amount;
586
+ const ease = (amount) => { const x = clamp(amount); return x * x * (3 - 2 * x); };
587
+ const easeInOut = ease;
588
+ const easeOut = (amount) => 1 - Math.pow(1 - clamp(amount), 3);
589
+ const cue = (name, span = 1) => {
590
+ if (!Object.hasOwn(cues, name)) throw new __Error('Unknown scene cue: ' + name);
591
+ if (!__isFinite(span) || span <= 0) throw new __Error('Cue span must be positive seconds.');
592
+ return clamp((time - cues[name]) / span);
593
+ };
594
+ let __randomState = seed >>> 0;
595
+ Math.random = () => {
596
+ __randomState = (__randomState + 0x6D2B79F5) >>> 0;
597
+ let v = Math.imul(__randomState ^ (__randomState >>> 15), 1 | __randomState);
598
+ v ^= v + Math.imul(v ^ (v >>> 7), 61 | v);
599
+ return ((v ^ (v >>> 14)) >>> 0) / 4294967296;
600
+ };
601
+ globalThis.Date = undefined;
602
+ globalThis.performance = undefined;
603
+ const __fragment = '__vizmatic_fragment';
604
+ const __jsx = (type, props, ...children) => {
605
+ const attributes = props == null ? {} : { ...props };
606
+ const descendants = children.length ? children : Object.hasOwn(attributes, 'children') ? [attributes.children] : [];
607
+ delete attributes.children;
608
+ if (type === __fragment) return descendants;
609
+ if (typeof type === 'function') return type({ ...attributes, children: descendants.length === 1 ? descendants[0] : descendants });
610
+ if (typeof type !== 'string') throw new __Error('Invalid scene JSX component.');
611
+ return { kind: 'vizmatic.element', type, props: attributes, children: descendants };
612
+ };
613
+ const React = __freeze({ createElement: __jsx, Fragment: __fragment });
614
+ const Fragment = __fragment;
615
+ const __primitive = (type) => (props) => {
616
+ const attributes = { ...props };
617
+ const children = Object.hasOwn(attributes, 'children') ? [attributes.children] : [];
618
+ delete attributes.children;
619
+ return { kind: 'vizmatic.element', type, props: attributes, children };
620
+ };
621
+ const __serialize = (value) => {
622
+ let values = 0;
623
+ return __jsonStringify(value, (key, item) => {
624
+ if (++values > 64000) throw new __Error('Scene graph contains too many values.');
625
+ if (typeof item === 'function' || typeof item === 'symbol' || typeof item === 'bigint') {
626
+ throw new __Error('Scene props cannot contain functions, symbols or bigint.');
627
+ }
628
+ if (typeof item === 'number' && !__isFinite(item)) throw new __Error('Scene props must be finite.');
629
+ if (item && typeof item === 'object' && typeof item.then === 'function') throw new __Error('Async scene values are not supported.');
630
+ return item;
631
+ });
632
+ };
633
+ `;
634
+ function prepareSceneSource(source) {
635
+ if (/^\s*(?:import|export)\b|\bimport\s*(?:[('"{*]|\/\*)/m.test(source)) {
636
+ throw new Error("Editable scenes use bare TSX. Imports and exports are disabled; Vizmatic components are provided automatically.");
637
+ }
638
+ const start = findBareRootJsxStart(source, true);
639
+ if (start < 0) throw new Error("Scene source needs one root JSX element after its local declarations.");
640
+ const setup = source.slice(0, start);
641
+ const jsx = extractRootJsx(source.slice(start).trim());
642
+ return transform(`(() => {
643
+ ${setup}
644
+ return (
645
+ ${jsx}
646
+ );
647
+ })()`, {
648
+ transforms: ["typescript", "jsx"],
649
+ jsxPragma: "React.createElement",
650
+ jsxFragmentPragma: "React.Fragment",
651
+ production: true,
652
+ disableESTransforms: true
653
+ }).code;
654
+ }
655
+ async function prepareScene(request) {
656
+ const normalized = Object.freeze(normalizeSceneRequest(request));
657
+ Object.freeze(normalized.cues);
658
+ const code = prepareSceneSource(normalized.source);
659
+ const sourceSha256 = await sceneSha256(normalized.source);
660
+ const inputSha256 = await sceneSha256(JSON.stringify({ runtimeVersion: SCENE_RUNTIME_VERSION, ...normalized }));
661
+ const QuickJS = await getQuickJS();
662
+ const colors = getThemeColors(normalized.theme);
663
+ const components = `const { ${SCENE_COMPONENT_NAMES.join(", ")} } = Object.fromEntries(${JSON.stringify(SCENE_COMPONENT_NAMES)}.map(name => [name, __primitive(name)]));`;
664
+ const evaluate = async (requestedTime) => {
665
+ const time = normalizeSceneTime(requestedTime, normalized.duration);
666
+ const runtime = QuickJS.newRuntime();
667
+ runtime.setMemoryLimit(SCENE_LIMITS.memoryBytes);
668
+ runtime.setMaxStackSize(SCENE_LIMITS.stackBytes);
669
+ const deadline = Date.now() + SCENE_LIMITS.evaluationMs;
670
+ runtime.setInterruptHandler(() => Date.now() > deadline);
671
+ runtime.removeModuleLoader();
672
+ const vm = runtime.newContext();
673
+ const context = {
674
+ width: normalized.width,
675
+ height: normalized.height,
676
+ duration: normalized.duration,
677
+ fps: normalized.fps,
678
+ time,
679
+ t: time,
680
+ progress: time / normalized.duration,
681
+ frame: Math.floor(time * normalized.fps + 1e-9),
682
+ theme: normalized.theme,
683
+ cues: normalized.cues,
684
+ seed: normalized.seed,
685
+ c: colors
686
+ };
687
+ const declaration = `const { ${Object.keys(context).join(", ")} } = ${JSON.stringify(context)};`;
688
+ try {
689
+ const result = vm.evalCode(`(() => { 'use strict';
690
+ ${declaration}
691
+ ${bootstrap}
692
+ __freeze(c); __freeze(cues);
693
+ ${components}
694
+ try { return __serialize(${code}); } catch (error) {
695
+ if (typeof error === 'string') throw error.slice(0, 1024);
696
+ const message = error && typeof error === 'object' ? __ownDescriptor(error, 'message')?.value : undefined;
697
+ throw typeof message === 'string' ? message.slice(0, 1024) : 'Scene evaluation failed.';
698
+ }
699
+ })()`, "scene.tsx");
700
+ if (result.error) {
701
+ const error = result.error;
702
+ try {
703
+ const message = vm.typeof(error) === "string" ? vm.getString(error) : "Scene evaluation failed or exceeded its CPU, stack or memory limit.";
704
+ throw new Error(message.slice(0, 1024));
705
+ } finally {
706
+ error.dispose();
707
+ }
708
+ }
709
+ const handle = result.value;
710
+ try {
711
+ if (vm.typeof(handle) !== "string") throw new Error("Scene source must return synchronous JSX.");
712
+ const length = vm.getProp(handle, "length");
713
+ try {
714
+ if (vm.getNumber(length) > SCENE_LIMITS.graphBytes) throw new Error("Scene graph exceeds its serialized size limit.");
715
+ } finally {
716
+ length.dispose();
717
+ }
718
+ const json = vm.getString(handle);
719
+ if (new TextEncoder().encode(json).byteLength > SCENE_LIMITS.graphBytes) throw new Error("Scene graph exceeds its serialized size limit.");
720
+ const graph = validateSceneGraph(JSON.parse(json));
721
+ return {
722
+ graph,
723
+ request: normalized,
724
+ time,
725
+ runtimeVersion: SCENE_RUNTIME_VERSION,
726
+ sourceSha256,
727
+ inputSha256: await sceneSha256(JSON.stringify({ sceneInputSha256: inputSha256, time }))
728
+ };
729
+ } finally {
730
+ handle.dispose();
731
+ }
732
+ } finally {
733
+ vm.dispose();
734
+ runtime.dispose();
735
+ }
736
+ };
737
+ return { request: normalized, sourceSha256, inputSha256, evaluate };
738
+ }
739
+ async function evaluateSceneSource(request) {
740
+ return (await prepareScene(request)).evaluate(request.time);
741
+ }
742
+
743
+ export {
744
+ SCENE_COMPONENT_NAMES,
745
+ SCENE_DOM_TAGS,
746
+ SCENE_RUNTIME_VERSION,
747
+ SCENE_LIMITS,
748
+ normalizeSceneTime,
749
+ sceneSha256,
750
+ validateResolvedSceneResources,
751
+ validateSceneGraph,
752
+ prepareSceneSource,
753
+ prepareScene,
754
+ evaluateSceneSource
755
+ };