Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
feat: add deterministic SVML compiler prototype
kashorinc8db96f22b2e
diff --git a/.gitignore b/.gitignorenew file mode 100644index 00000000..071da911--- /dev/null+++ b/.gitignore@@ -0,0 +1,6 @@+node_modules/+dist/+.svml-cache/+examples/**/assets/+examples/**/build/+examples/**/evidence/generated/diff --git a/README.md b/README.mdindex 2b494208..475d1504 100644--- a/README.md+++ b/README.md@@ -1,5 +1,94 @@-# svml-Semantic Video Markup Language — a semantic source language for video+# SVML++Semantic Video Markup Language is a semantic source language for information-flow+video. Its primary clock is the spoken narrative: Script compiles to aligned words,+Selections and Moments; ordinary imported Kernels project the resulting media graph+to one deterministic HyperFrames document.++```text+.svml + .svc + .svs + .svk + lock + evidence+ │+ ├─ Plan IR ────────> Canvas view+ ├─ Located IR ─────> Timeline view+ └─ HyperFrames HTML ──> rendered video+```++Canvas and Timeline are views of the same source closure. They are not additional+authoring truths. Provider tasks, pins, takes and caches are runtime state and do+not enter the source language.++## Current prototype++The repository contains a strict TypeScript compiler and an intentionally small+stdlib. The deterministic slice is working end to end:++- frozen Script Surface with dialogue, speech and caption projections;+- closed, possibly disconnected Selection sets and zero-width Moments;+- `.svc` content modules and typed `.svs` parameter classes;+- stable Plan identities, separate execution digests and a verified `svml.lock`;+- isolated `.svk` projectors with scoped CSS and a JSON-only ABI;+- typed `.svk` ports, parameters and recursive child-content schemas;+- manifest-enforced temporal `one` / `each` / `set` consumption;+- Speech Spine, media/presentation mapping, ranking, B-roll, captions, text and+ audio;+- frame-exact Located IR, Canvas/Timeline views and HyperFrames HTML.++The current runtime deliberately has no live generation provider host. A+`profile="capability-v1"` Kernel remains visible in Plan, but compilation requires+an exact, content-verified `svml.artifacts.v1` binding for its outputs and never+falls back to a provider call. Direct existing `Image`, `Video` and `Audio` values+work as usual. This keeps the first end-to-end reference deterministic while+preserving the eventual capability boundary.++## Commands++Requires Node.js 22 and pnpm.++```bash+pnpm install+pnpm check+pnpm test+pnpm build++pnpm svml check examples/regen-ranking/regen-ranking.svml+pnpm svml fmt examples/regen-ranking/regen-ranking.svml --check+pnpm svml canvas examples/regen-ranking/regen-ranking.svml --out canvas.json+pnpm svml estimate examples/regen-ranking/regen-ranking.svml \+ --out estimated-alignment.json+pnpm svml timeline examples/regen-ranking/regen-ranking.svml \+ --evidence examples/regen-ranking/evidence/alignment.json \+ --out timeline.json+pnpm svml lock examples/regen-ranking/regen-ranking.svml --out svml.lock+pnpm svml compile examples/regen-ranking/regen-ranking.svml \+ --evidence examples/regen-ranking/evidence/alignment.json \+ --lock svml.lock \+ --out build/index.html+pnpm svml render build/index.html --out build/video.mp4+```++`--artifacts` is needed only when the reachable Plan contains capability Kernels.+`fmt` currently canonicalizes only the frozen Script body and refuses any rewrite+whose reparsed semantic IR differs.+`canvas` requires no timing or provider result. `estimate` deterministically+creates provisional syllable-based alignment; `timeline` and `compile` consume+either that preview evidence or measured Speech Compile evidence. A compile is+marked reproducible only when its exact+module/Kernel/material closure matches the lock and every reachable capability+output has been content-verified.++## Reference implementation++[`examples/regen-ranking/regen-ranking.svml`](examples/regen-ranking/regen-ranking.svml)+reconstructs a real production video containing Speech Spine, a five-item ranking+track, five B-roll items, captions, title, music and sound effects. The media files+are intentionally gitignored; their production provenance and frozen assertions+are recorded in+[`examples/regen-ranking/reference.json`](examples/regen-ranking/reference.json).+The regression test compiles the example to 27 Canvas nodes, 29 typed topology+edges, 1083 frames, 155 visual fragments and 14 audio fragments.+The default syllable estimator predicts 36.267 seconds for the frozen 36.1-second+speech program (0.46% duration error); it remains preview evidence, not measured+alignment.## Specification@@ -8,3 +97,9 @@ Semantic Video Markup Language — a semantic source language for video- [Source Architecture Draft](spec/source-architecture-draft.md) — the currentdraft for `.svk` components, `.svs` parameter sheets, `.svc` content modules,Script-dependent generation, Tracks, and the single Film root.+- [Compiler prototype record](docs/compiler-prototype-v1.md) — implemented+ boundaries, real-video evidence and remaining work.+- [External Runtime Host Architecture Draft](docs/runtime-host-architecture-draft.md)+ — portable runtime, Artifact, Effect/Receipt, Worker, queue, provider and+ self-hosting boundaries; narrative-clock and alignment acquisition remain+ intentionally deferred.diff --git a/examples/regen-ranking/evidence/alignment.json b/examples/regen-ranking/evidence/alignment.jsonnew file mode 100644index 00000000..b2b45d70--- /dev/null+++ b/examples/regen-ranking/evidence/alignment.json@@ -0,0 +1,1126 @@+{+ "contract": "svml.speech-alignment.v1",+ "durationSec": 36.1,+ "fps": 30,+ "words": [+ {+ "text": "Photoshop",+ "startSec": 0.08,+ "endSec": 1,+ "segmentId": "scene-1"+ },+ {+ "text": "Powerful",+ "startSec": 1,+ "endSec": 1.53,+ "segmentId": "scene-1"+ },+ {+ "text": "but",+ "startSec": 1.53,+ "endSec": 1.9,+ "segmentId": "scene-1"+ },+ {+ "text": "only",+ "startSec": 1.9,+ "endSec": 1.99,+ "segmentId": "scene-1"+ },+ {+ "text": "if",+ "startSec": 1.99,+ "endSec": 2,+ "segmentId": "scene-1"+ },+ {+ "text": "you",+ "startSec": 2,+ "endSec": 2.23,+ "segmentId": "scene-1"+ },+ {+ "text": "know",+ "startSec": 2.23,+ "endSec": 2.36,+ "segmentId": "scene-1"+ },+ {+ "text": "how",+ "startSec": 2.36,+ "endSec": 2.56,+ "segmentId": "scene-1"+ },+ {+ "text": "to",+ "startSec": 2.56,+ "endSec": 2.64,+ "segmentId": "scene-1"+ },+ {+ "text": "use",+ "startSec": 2.64,+ "endSec": 2.79,+ "segmentId": "scene-1"+ },+ {+ "text": "it",+ "startSec": 2.79,+ "endSec": 3.12,+ "segmentId": "scene-1"+ },+ {+ "text": "Otherwise",+ "startSec": 3.12,+ "endSec": 3.6,+ "segmentId": "scene-1"+ },+ {+ "text": "your",+ "startSec": 3.6,+ "endSec": 3.77,+ "segmentId": "scene-1"+ },+ {+ "text": "new",+ "startSec": 3.77,+ "endSec": 4.08,+ "segmentId": "scene-1"+ },+ {+ "text": "profile",+ "startSec": 4.08,+ "endSec": 4.22,+ "segmentId": "scene-1"+ },+ {+ "text": "picture",+ "startSec": 4.22,+ "endSec": 4.68,+ "segmentId": "scene-1"+ },+ {+ "text": "becomes",+ "startSec": 4.68,+ "endSec": 4.84,+ "segmentId": "scene-1"+ },+ {+ "text": "a",+ "startSec": 4.84,+ "endSec": 4.9,+ "segmentId": "scene-1"+ },+ {+ "text": "three-hour",+ "startSec": 4.9,+ "endSec": 5.42,+ "segmentId": "scene-1"+ },+ {+ "text": "design",+ "startSec": 5.42,+ "endSec": 5.84,+ "segmentId": "scene-1"+ },+ {+ "text": "project",+ "startSec": 5.84,+ "endSec": 6.4,+ "segmentId": "scene-1"+ },+ {+ "text": "Facetune",+ "startSec": 6.4,+ "endSec": 7.4,+ "segmentId": "scene-1"+ },+ {+ "text": "Fast",+ "startSec": 7.4,+ "endSec": 7.59,+ "segmentId": "scene-1"+ },+ {+ "text": "and",+ "startSec": 7.59,+ "endSec": 7.71,+ "segmentId": "scene-1"+ },+ {+ "text": "great",+ "startSec": 7.71,+ "endSec": 8,+ "segmentId": "scene-1"+ },+ {+ "text": "for",+ "startSec": 8,+ "endSec": 8.33,+ "segmentId": "scene-1"+ },+ {+ "text": "touch-ups",+ "startSec": 8.33,+ "endSec": 8.64,+ "segmentId": "scene-1"+ },+ {+ "text": "But",+ "startSec": 8.64,+ "endSec": 8.76,+ "segmentId": "scene-1"+ },+ {+ "text": "it",+ "startSec": 8.76,+ "endSec": 8.96,+ "segmentId": "scene-1"+ },+ {+ "text": "still",+ "startSec": 8.96,+ "endSec": 9.04,+ "segmentId": "scene-1"+ },+ {+ "text": "leaves",+ "startSec": 9.04,+ "endSec": 9.29,+ "segmentId": "scene-1"+ },+ {+ "text": "you",+ "startSec": 9.29,+ "endSec": 9.45,+ "segmentId": "scene-1"+ },+ {+ "text": "with",+ "startSec": 9.45,+ "endSec": 9.57,+ "segmentId": "scene-1"+ },+ {+ "text": "the",+ "startSec": 9.57,+ "endSec": 9.69,+ "segmentId": "scene-1"+ },+ {+ "text": "same",+ "startSec": 9.69,+ "endSec": 9.85,+ "segmentId": "scene-1"+ },+ {+ "text": "awkward",+ "startSec": 9.85,+ "endSec": 10.14,+ "segmentId": "scene-1"+ },+ {+ "text": "pose",+ "startSec": 10.14,+ "endSec": 10.48,+ "segmentId": "scene-1"+ },+ {+ "text": "and",+ "startSec": 10.48,+ "endSec": 10.52,+ "segmentId": "scene-1"+ },+ {+ "text": "the",+ "startSec": 10.52,+ "endSec": 10.67,+ "segmentId": "scene-1"+ },+ {+ "text": "same",+ "startSec": 10.67,+ "endSec": 10.87,+ "segmentId": "scene-1"+ },+ {+ "text": "dorm-room",+ "startSec": 10.87,+ "endSec": 11.48,+ "segmentId": "scene-1"+ },+ {+ "text": "background",+ "startSec": 11.48,+ "endSec": 12,+ "segmentId": "scene-1"+ },+ {+ "text": "Remini",+ "startSec": 12.043333333333333,+ "endSec": 13.033333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "Great",+ "startSec": 13.033333333333333,+ "endSec": 13.283333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "for",+ "startSec": 13.283333333333333,+ "endSec": 13.563333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "blurry",+ "startSec": 13.563333333333333,+ "endSec": 13.773333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "photos",+ "startSec": 13.773333333333333,+ "endSec": 14.033333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "It",+ "startSec": 14.033333333333333,+ "endSec": 14.103333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "restores",+ "startSec": 14.103333333333333,+ "endSec": 14.393333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "detail",+ "startSec": 14.393333333333333,+ "endSec": 14.613333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "but",+ "startSec": 14.613333333333333,+ "endSec": 14.763333333333334,+ "segmentId": "scene-2"+ },+ {+ "text": "it",+ "startSec": 14.763333333333334,+ "endSec": 14.793333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "can't",+ "startSec": 14.793333333333333,+ "endSec": 14.973333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "fix",+ "startSec": 14.973333333333333,+ "endSec": 15.083333333333332,+ "segmentId": "scene-2"+ },+ {+ "text": "the",+ "startSec": 15.083333333333332,+ "endSec": 15.213333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "pose",+ "startSec": 15.213333333333333,+ "endSec": 15.373333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "outfit",+ "startSec": 15.373333333333333,+ "endSec": 15.733333333333334,+ "segmentId": "scene-2"+ },+ {+ "text": "or",+ "startSec": 15.733333333333334,+ "endSec": 15.853333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "background",+ "startSec": 15.853333333333333,+ "endSec": 16.633333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "You",+ "startSec": 16.633333333333333,+ "endSec": 16.793333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "get",+ "startSec": 16.793333333333333,+ "endSec": 16.953333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "the",+ "startSec": 16.953333333333333,+ "endSec": 17.163333333333334,+ "segmentId": "scene-2"+ },+ {+ "text": "same",+ "startSec": 17.163333333333334,+ "endSec": 17.373333333333335,+ "segmentId": "scene-2"+ },+ {+ "text": "bad",+ "startSec": 17.373333333333335,+ "endSec": 17.503333333333334,+ "segmentId": "scene-2"+ },+ {+ "text": "photo",+ "startSec": 17.503333333333334,+ "endSec": 17.813333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "in",+ "startSec": 17.813333333333333,+ "endSec": 17.873333333333335,+ "segmentId": "scene-2"+ },+ {+ "text": "HD",+ "startSec": 17.873333333333335,+ "endSec": 18.184444444444445,+ "segmentId": "scene-2"+ },+ {+ "text": "ChatGPT",+ "startSec": 18.184444444444445,+ "endSec": 19.273333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "More",+ "startSec": 19.273333333333333,+ "endSec": 19.53333333333333,+ "segmentId": "scene-2"+ },+ {+ "text": "flexible",+ "startSec": 19.53333333333333,+ "endSec": 20,+ "segmentId": "scene-2"+ },+ {+ "text": "It",+ "startSec": 20,+ "endSec": 20.033,+ "segmentId": "scene-2"+ },+ {+ "text": "can",+ "startSec": 20.033,+ "endSec": 20.133,+ "segmentId": "scene-2"+ },+ {+ "text": "create",+ "startSec": 20.133,+ "endSec": 20.433,+ "segmentId": "scene-2"+ },+ {+ "text": "a",+ "startSec": 20.433,+ "endSec": 20.533,+ "segmentId": "scene-2"+ },+ {+ "text": "new",+ "startSec": 20.533,+ "endSec": 20.7,+ "segmentId": "scene-2"+ },+ {+ "text": "shot",+ "startSec": 20.7,+ "endSec": 20.967,+ "segmentId": "scene-2"+ },+ {+ "text": "but",+ "startSec": 20.967,+ "endSec": 21.133,+ "segmentId": "scene-2"+ },+ {+ "text": "getting",+ "startSec": 21.133,+ "endSec": 21.333,+ "segmentId": "scene-2"+ },+ {+ "text": "your",+ "startSec": 21.333,+ "endSec": 21.5,+ "segmentId": "scene-2"+ },+ {+ "text": "face",+ "startSec": 21.5,+ "endSec": 21.833,+ "segmentId": "scene-2"+ },+ {+ "text": "and",+ "startSec": 21.833,+ "endSec": 21.9,+ "segmentId": "scene-2"+ },+ {+ "text": "the",+ "startSec": 21.9,+ "endSec": 22,+ "segmentId": "scene-2"+ },+ {+ "text": "details",+ "startSec": 22,+ "endSec": 22.433,+ "segmentId": "scene-2"+ },+ {+ "text": "right",+ "startSec": 22.433,+ "endSec": 22.6,+ "segmentId": "scene-2"+ },+ {+ "text": "becomes",+ "startSec": 22.6,+ "endSec": 22.933,+ "segmentId": "scene-2"+ },+ {+ "text": "a",+ "startSec": 22.933,+ "endSec": 23.067,+ "segmentId": "scene-2"+ },+ {+ "text": "prompt-writing",+ "startSec": 23.067,+ "endSec": 23.567,+ "segmentId": "scene-2"+ },+ {+ "text": "group",+ "startSec": 23.567,+ "endSec": 23.733,+ "segmentId": "scene-2"+ },+ {+ "text": "project",+ "startSec": 23.733,+ "endSec": 24.066666666666666,+ "segmentId": "scene-2"+ },+ {+ "text": "ReGen",+ "startSec": 24.076666666666668,+ "endSec": 25.066666666666666,+ "segmentId": "scene-3"+ },+ {+ "text": "Pick",+ "startSec": 25.066666666666666,+ "endSec": 25.266666666666666,+ "segmentId": "scene-3"+ },+ {+ "text": "a",+ "startSec": 25.266666666666666,+ "endSec": 25.306666666666665,+ "segmentId": "scene-3"+ },+ {+ "text": "photo",+ "startSec": 25.306666666666665,+ "endSec": 25.576666666666668,+ "segmentId": "scene-3"+ },+ {+ "text": "you",+ "startSec": 25.576666666666668,+ "endSec": 25.726666666666667,+ "segmentId": "scene-3"+ },+ {+ "text": "love",+ "startSec": 25.726666666666667,+ "endSec": 26.006666666666668,+ "segmentId": "scene-3"+ },+ {+ "text": "and",+ "startSec": 26.006666666666668,+ "endSec": 26.076666666666668,+ "segmentId": "scene-3"+ },+ {+ "text": "the",+ "startSec": 26.076666666666668,+ "endSec": 26.226666666666667,+ "segmentId": "scene-3"+ },+ {+ "text": "app",+ "startSec": 26.226666666666667,+ "endSec": 26.376666666666665,+ "segmentId": "scene-3"+ },+ {+ "text": "rebuilds",+ "startSec": 26.376666666666665,+ "endSec": 26.886666666666667,+ "segmentId": "scene-3"+ },+ {+ "text": "it",+ "startSec": 26.886666666666667,+ "endSec": 26.906666666666666,+ "segmentId": "scene-3"+ },+ {+ "text": "around",+ "startSec": 26.906666666666666,+ "endSec": 27.196666666666665,+ "segmentId": "scene-3"+ },+ {+ "text": "you",+ "startSec": 27.196666666666665,+ "endSec": 27.346666666666668,+ "segmentId": "scene-3"+ },+ {+ "text": "with",+ "startSec": 27.346666666666668,+ "endSec": 27.546666666666667,+ "segmentId": "scene-3"+ },+ {+ "text": "a",+ "startSec": 27.546666666666667,+ "endSec": 27.7,+ "segmentId": "scene-3"+ },+ {+ "text": "better",+ "startSec": 27.7,+ "endSec": 27.906666666666666,+ "segmentId": "scene-3"+ },+ {+ "text": "pose",+ "startSec": 27.906666666666666,+ "endSec": 28.206666666666667,+ "segmentId": "scene-3"+ },+ {+ "text": "outfit",+ "startSec": 28.206666666666667,+ "endSec": 28.706666666666667,+ "segmentId": "scene-3"+ },+ {+ "text": "and",+ "startSec": 28.706666666666667,+ "endSec": 28.926666666666666,+ "segmentId": "scene-3"+ },+ {+ "text": "setting",+ "startSec": 28.926666666666666,+ "endSec": 29.6,+ "segmentId": "scene-3"+ },+ {+ "text": "From",+ "startSec": 29.633,+ "endSec": 29.867,+ "segmentId": "scene-3"+ },+ {+ "text": "one",+ "startSec": 29.867,+ "endSec": 29.967,+ "segmentId": "scene-3"+ },+ {+ "text": "selfie",+ "startSec": 29.967,+ "endSec": 30.4,+ "segmentId": "scene-3"+ },+ {+ "text": "you",+ "startSec": 30.433,+ "endSec": 30.533,+ "segmentId": "scene-3"+ },+ {+ "text": "can",+ "startSec": 30.533,+ "endSec": 30.7,+ "segmentId": "scene-3"+ },+ {+ "text": "make",+ "startSec": 30.7,+ "endSec": 30.833,+ "segmentId": "scene-3"+ },+ {+ "text": "a",+ "startSec": 30.833,+ "endSec": 31.006666666666668,+ "segmentId": "scene-3"+ },+ {+ "text": "dating",+ "startSec": 31.006666666666668,+ "endSec": 31.546666666666667,+ "segmentId": "scene-3"+ },+ {+ "text": "photo",+ "startSec": 31.546666666666667,+ "endSec": 31.71666666666667,+ "segmentId": "scene-3"+ },+ {+ "text": "LinkedIn",+ "startSec": 31.71666666666667,+ "endSec": 32.04666666666667,+ "segmentId": "scene-3"+ },+ {+ "text": "headshot",+ "startSec": 32.04666666666667,+ "endSec": 32.567,+ "segmentId": "scene-3"+ },+ {+ "text": "or",+ "startSec": 32.567,+ "endSec": 32.70666666666666,+ "segmentId": "scene-3"+ },+ {+ "text": "Instagram",+ "startSec": 32.70666666666666,+ "endSec": 33.196666666666665,+ "segmentId": "scene-3"+ },+ {+ "text": "post",+ "startSec": 33.196666666666665,+ "endSec": 33.633,+ "segmentId": "scene-3"+ },+ {+ "text": "so",+ "startSec": 33.667,+ "endSec": 33.767,+ "segmentId": "scene-3"+ },+ {+ "text": "you",+ "startSec": 33.767,+ "endSec": 33.933,+ "segmentId": "scene-3"+ },+ {+ "text": "get",+ "startSec": 33.933,+ "endSec": 34,+ "segmentId": "scene-3"+ },+ {+ "text": "what",+ "startSec": 34,+ "endSec": 34.133,+ "segmentId": "scene-3"+ },+ {+ "text": "you",+ "startSec": 34.133,+ "endSec": 34.267,+ "segmentId": "scene-3"+ },+ {+ "text": "wanted",+ "startSec": 34.267,+ "endSec": 34.6,+ "segmentId": "scene-3"+ },+ {+ "text": "instead",+ "startSec": 34.6,+ "endSec": 34.867,+ "segmentId": "scene-3"+ },+ {+ "text": "of",+ "startSec": 34.867,+ "endSec": 35.067,+ "segmentId": "scene-3"+ },+ {+ "text": "fixing",+ "startSec": 35.067,+ "endSec": 35.433,+ "segmentId": "scene-3"+ },+ {+ "text": "a",+ "startSec": 35.433,+ "endSec": 35.533,+ "segmentId": "scene-3"+ },+ {+ "text": "bad",+ "startSec": 35.533,+ "endSec": 35.767,+ "segmentId": "scene-3"+ },+ {+ "text": "shot",+ "startSec": 35.767,+ "endSec": 36.06666666666666,+ "segmentId": "scene-3"+ }+ ],+ "segments": [+ {+ "id": "scene-1",+ "startSec": 0,+ "endSec": 12.033333333333333+ },+ {+ "id": "scene-2",+ "startSec": 12.033333333333333,+ "endSec": 24.066666666666666+ },+ {+ "id": "scene-3",+ "startSec": 24.066666666666666,+ "endSec": 36.1+ }+ ],+ "provenance": {+ "method": "whisper.cpp word timestamps + deterministic intended-script LCS projection",+ "source": "existing pinned avatar audio; no generation call",+ "captionCues": {+ "kind": "reference-recovery",+ "source": "regen ranking Job cmrxqbub800012tjoi2ev2u24",+ "note": "Cue boundaries are evidence emitted by Locate, not authored SVML timing."+ },+ "timingOverrides": {+ "kind": "reference-recovery",+ "source": "scene transitions in regen ranking Job cmrxqbub800012tjoi2ev2u24",+ "note": "Only boundaries visible in the frozen reference video are overridden."+ }+ },+ "captionCues": [+ {+ "startWord": 0,+ "endWordExclusive": 1+ },+ {+ "startWord": 1,+ "endWordExclusive": 2+ },+ {+ "startWord": 2,+ "endWordExclusive": 5+ },+ {+ "startWord": 5,+ "endWordExclusive": 8+ },+ {+ "startWord": 8,+ "endWordExclusive": 11+ },+ {+ "startWord": 11,+ "endWordExclusive": 12+ },+ {+ "startWord": 12,+ "endWordExclusive": 14+ },+ {+ "startWord": 14,+ "endWordExclusive": 16+ },+ {+ "startWord": 16,+ "endWordExclusive": 18+ },+ {+ "startWord": 18,+ "endWordExclusive": 20+ },+ {+ "startWord": 20,+ "endWordExclusive": 21+ },+ {+ "startWord": 21,+ "endWordExclusive": 22+ },+ {+ "startWord": 22,+ "endWordExclusive": 24+ },+ {+ "startWord": 24,+ "endWordExclusive": 26+ },+ {+ "startWord": 26,+ "endWordExclusive": 27+ },+ {+ "startWord": 27,+ "endWordExclusive": 28+ },+ {+ "startWord": 28,+ "endWordExclusive": 31+ },+ {+ "startWord": 31,+ "endWordExclusive": 34+ },+ {+ "startWord": 34,+ "endWordExclusive": 35+ },+ {+ "startWord": 35,+ "endWordExclusive": 38+ },+ {+ "startWord": 38,+ "endWordExclusive": 40+ },+ {+ "startWord": 40,+ "endWordExclusive": 42+ },+ {+ "startWord": 42,+ "endWordExclusive": 43+ },+ {+ "startWord": 43,+ "endWordExclusive": 44+ },+ {+ "startWord": 44,+ "endWordExclusive": 47+ },+ {+ "startWord": 47,+ "endWordExclusive": 50+ },+ {+ "startWord": 50,+ "endWordExclusive": 53+ },+ {+ "startWord": 53,+ "endWordExclusive": 56+ },+ {+ "startWord": 56,+ "endWordExclusive": 57+ },+ {+ "startWord": 57,+ "endWordExclusive": 59+ },+ {+ "startWord": 59,+ "endWordExclusive": 62+ },+ {+ "startWord": 62,+ "endWordExclusive": 65+ },+ {+ "startWord": 65,+ "endWordExclusive": 67+ },+ {+ "startWord": 67,+ "endWordExclusive": 68+ },+ {+ "startWord": 68,+ "endWordExclusive": 70+ },+ {+ "startWord": 70,+ "endWordExclusive": 73+ },+ {+ "startWord": 73,+ "endWordExclusive": 75+ },+ {+ "startWord": 75,+ "endWordExclusive": 76+ },+ {+ "startWord": 76,+ "endWordExclusive": 77+ },+ {+ "startWord": 77,+ "endWordExclusive": 80+ },+ {+ "startWord": 80,+ "endWordExclusive": 83+ },+ {+ "startWord": 83,+ "endWordExclusive": 86+ },+ {+ "startWord": 86,+ "endWordExclusive": 87+ },+ {+ "startWord": 87,+ "endWordExclusive": 89+ },+ {+ "startWord": 89,+ "endWordExclusive": 90+ },+ {+ "startWord": 90,+ "endWordExclusive": 93+ },+ {+ "startWord": 93,+ "endWordExclusive": 95+ },+ {+ "startWord": 95,+ "endWordExclusive": 98+ },+ {+ "startWord": 98,+ "endWordExclusive": 100+ },+ {+ "startWord": 100,+ "endWordExclusive": 103+ },+ {+ "startWord": 103,+ "endWordExclusive": 105+ },+ {+ "startWord": 105,+ "endWordExclusive": 106+ },+ {+ "startWord": 106,+ "endWordExclusive": 107+ },+ {+ "startWord": 107,+ "endWordExclusive": 108+ },+ {+ "startWord": 108,+ "endWordExclusive": 109+ },+ {+ "startWord": 109,+ "endWordExclusive": 111+ },+ {+ "startWord": 111,+ "endWordExclusive": 112+ },+ {+ "startWord": 112,+ "endWordExclusive": 114+ },+ {+ "startWord": 114,+ "endWordExclusive": 116+ },+ {+ "startWord": 116,+ "endWordExclusive": 118+ },+ {+ "startWord": 118,+ "endWordExclusive": 120+ },+ {+ "startWord": 120,+ "endWordExclusive": 122+ },+ {+ "startWord": 122,+ "endWordExclusive": 123+ },+ {+ "startWord": 123,+ "endWordExclusive": 125+ },+ {+ "startWord": 125,+ "endWordExclusive": 127+ },+ {+ "startWord": 127,+ "endWordExclusive": 129+ },+ {+ "startWord": 129,+ "endWordExclusive": 131+ },+ {+ "startWord": 131,+ "endWordExclusive": 133+ },+ {+ "startWord": 133,+ "endWordExclusive": 135+ }+ ]+}diff --git a/examples/regen-ranking/evidence/caption-cues.json b/examples/regen-ranking/evidence/caption-cues.jsonnew file mode 100644index 00000000..232bdad8--- /dev/null+++ b/examples/regen-ranking/evidence/caption-cues.json@@ -0,0 +1,81 @@+{+ "contract": "svml.caption-cues.v1",+ "captionCues": [+ { "startWord": 0, "endWordExclusive": 1 },+ { "startWord": 1, "endWordExclusive": 2 },+ { "startWord": 2, "endWordExclusive": 5 },+ { "startWord": 5, "endWordExclusive": 8 },+ { "startWord": 8, "endWordExclusive": 11 },+ { "startWord": 11, "endWordExclusive": 12 },+ { "startWord": 12, "endWordExclusive": 14 },+ { "startWord": 14, "endWordExclusive": 16 },+ { "startWord": 16, "endWordExclusive": 18 },+ { "startWord": 18, "endWordExclusive": 20 },+ { "startWord": 20, "endWordExclusive": 21 },+ { "startWord": 21, "endWordExclusive": 22 },+ { "startWord": 22, "endWordExclusive": 24 },+ { "startWord": 24, "endWordExclusive": 26 },+ { "startWord": 26, "endWordExclusive": 27 },+ { "startWord": 27, "endWordExclusive": 28 },+ { "startWord": 28, "endWordExclusive": 31 },+ { "startWord": 31, "endWordExclusive": 34 },+ { "startWord": 34, "endWordExclusive": 35 },+ { "startWord": 35, "endWordExclusive": 38 },+ { "startWord": 38, "endWordExclusive": 40 },+ { "startWord": 40, "endWordExclusive": 42 },++ { "startWord": 42, "endWordExclusive": 43 },+ { "startWord": 43, "endWordExclusive": 44 },+ { "startWord": 44, "endWordExclusive": 47 },+ { "startWord": 47, "endWordExclusive": 50 },+ { "startWord": 50, "endWordExclusive": 53 },+ { "startWord": 53, "endWordExclusive": 56 },+ { "startWord": 56, "endWordExclusive": 57 },+ { "startWord": 57, "endWordExclusive": 59 },+ { "startWord": 59, "endWordExclusive": 62 },+ { "startWord": 62, "endWordExclusive": 65 },+ { "startWord": 65, "endWordExclusive": 67 },+ { "startWord": 67, "endWordExclusive": 68 },+ { "startWord": 68, "endWordExclusive": 70 },+ { "startWord": 70, "endWordExclusive": 73 },+ { "startWord": 73, "endWordExclusive": 75 },+ { "startWord": 75, "endWordExclusive": 76 },+ { "startWord": 76, "endWordExclusive": 77 },+ { "startWord": 77, "endWordExclusive": 80 },+ { "startWord": 80, "endWordExclusive": 83 },+ { "startWord": 83, "endWordExclusive": 86 },+ { "startWord": 86, "endWordExclusive": 87 },+ { "startWord": 87, "endWordExclusive": 89 },++ { "startWord": 89, "endWordExclusive": 90 },+ { "startWord": 90, "endWordExclusive": 93 },+ { "startWord": 93, "endWordExclusive": 95 },+ { "startWord": 95, "endWordExclusive": 98 },+ { "startWord": 98, "endWordExclusive": 100 },+ { "startWord": 100, "endWordExclusive": 103 },+ { "startWord": 103, "endWordExclusive": 105 },+ { "startWord": 105, "endWordExclusive": 106 },+ { "startWord": 106, "endWordExclusive": 107 },+ { "startWord": 107, "endWordExclusive": 108 },+ { "startWord": 108, "endWordExclusive": 109 },+ { "startWord": 109, "endWordExclusive": 111 },+ { "startWord": 111, "endWordExclusive": 112 },+ { "startWord": 112, "endWordExclusive": 114 },+ { "startWord": 114, "endWordExclusive": 116 },+ { "startWord": 116, "endWordExclusive": 118 },+ { "startWord": 118, "endWordExclusive": 120 },+ { "startWord": 120, "endWordExclusive": 122 },+ { "startWord": 122, "endWordExclusive": 123 },+ { "startWord": 123, "endWordExclusive": 125 },+ { "startWord": 125, "endWordExclusive": 127 },+ { "startWord": 127, "endWordExclusive": 129 },+ { "startWord": 129, "endWordExclusive": 131 },+ { "startWord": 131, "endWordExclusive": 133 },+ { "startWord": 133, "endWordExclusive": 135 }+ ],+ "provenance": {+ "kind": "reference-recovery",+ "source": "regen ranking Job cmrxqbub800012tjoi2ev2u24",+ "note": "Cue boundaries are evidence emitted by Locate, not authored SVML timing."+ }+}diff --git a/examples/regen-ranking/evidence/timing-overrides.json b/examples/regen-ranking/evidence/timing-overrides.jsonnew file mode 100644index 00000000..548b1138--- /dev/null+++ b/examples/regen-ranking/evidence/timing-overrides.json@@ -0,0 +1,56 @@+{+ "contract": "svml.alignment-overrides.v1",+ "words": [+ { "index": 69, "endSec": 20.000 },+ { "index": 70, "startSec": 20.000, "endSec": 20.033 },+ { "index": 71, "startSec": 20.033, "endSec": 20.133 },+ { "index": 72, "startSec": 20.133, "endSec": 20.433 },+ { "index": 73, "startSec": 20.433, "endSec": 20.533 },+ { "index": 74, "startSec": 20.533, "endSec": 20.700 },+ { "index": 75, "startSec": 20.700, "endSec": 20.967 },+ { "index": 76, "startSec": 20.967, "endSec": 21.133 },+ { "index": 77, "startSec": 21.133, "endSec": 21.333 },+ { "index": 78, "startSec": 21.333, "endSec": 21.500 },+ { "index": 79, "startSec": 21.500, "endSec": 21.833 },+ { "index": 80, "startSec": 21.833, "endSec": 21.900 },+ { "index": 81, "startSec": 21.900, "endSec": 22.000 },+ { "index": 82, "startSec": 22.000, "endSec": 22.433 },+ { "index": 83, "startSec": 22.433, "endSec": 22.600 },+ { "index": 84, "startSec": 22.600, "endSec": 22.933 },+ { "index": 85, "startSec": 22.933, "endSec": 23.067 },+ { "index": 86, "startSec": 23.067, "endSec": 23.567 },+ { "index": 87, "startSec": 23.567, "endSec": 23.733 },+ { "index": 88, "startSec": 23.733 },++ { "index": 103, "endSec": 27.700 },+ { "index": 104, "startSec": 27.700 },+ { "index": 108, "endSec": 29.600 },+ { "index": 109, "startSec": 29.633, "endSec": 29.867 },+ { "index": 110, "startSec": 29.867, "endSec": 29.967 },+ { "index": 111, "startSec": 29.967, "endSec": 30.400 },+ { "index": 112, "startSec": 30.433, "endSec": 30.533 },+ { "index": 113, "startSec": 30.533, "endSec": 30.700 },+ { "index": 114, "startSec": 30.700, "endSec": 30.833 },+ { "index": 115, "startSec": 30.833 },+ { "index": 119, "endSec": 32.567 },+ { "index": 120, "startSec": 32.567 },+ { "index": 122, "endSec": 33.633 },+ { "index": 123, "startSec": 33.667, "endSec": 33.767 },+ { "index": 124, "startSec": 33.767, "endSec": 33.933 },+ { "index": 125, "startSec": 33.933, "endSec": 34.000 },+ { "index": 126, "startSec": 34.000, "endSec": 34.133 },+ { "index": 127, "startSec": 34.133, "endSec": 34.267 },+ { "index": 128, "startSec": 34.267, "endSec": 34.600 },+ { "index": 129, "startSec": 34.600, "endSec": 34.867 },+ { "index": 130, "startSec": 34.867, "endSec": 35.067 },+ { "index": 131, "startSec": 35.067, "endSec": 35.433 },+ { "index": 132, "startSec": 35.433, "endSec": 35.533 },+ { "index": 133, "startSec": 35.533, "endSec": 35.767 },+ { "index": 134, "startSec": 35.767 }+ ],+ "provenance": {+ "kind": "reference-recovery",+ "source": "scene transitions in regen ranking Job cmrxqbub800012tjoi2ev2u24",+ "note": "Only boundaries visible in the frozen reference video are overridden."+ }+}diff --git a/examples/regen-ranking/reference.json b/examples/regen-ranking/reference.jsonnew file mode 100644index 00000000..00b38ee8--- /dev/null+++ b/examples/regen-ranking/reference.json@@ -0,0 +1,32 @@+{+ "contract": "svml.reference-video.v1",+ "source": {+ "projectId": "cmrs0yofw00042tlz2t0ygwaw",+ "canvasId": "cmrx7771b00052ts5koz1yy7e",+ "jobId": "cmrxqbub800012tjoi2ev2u24",+ "finalSha256": "986c2b4f81381e5c5ab6df3c7b58f8bcc5324f9ae11ce820ed1cd8e5ee74c8b8"+ },+ "clock": {+ "width": 1080,+ "height": 1920,+ "fps": 30,+ "durationFrames": 1083+ },+ "plan": {+ "root": "regen-ranking",+ "values": 19,+ "instances": 8,+ "edges": 29+ },+ "selectionFrames": {+ "handsome-1": [[791, 831]],+ "handsome-2": [[831, 888]],+ "dating-photo": [[925, 952]],+ "linkedin-headshot": [[952, 977]],+ "instagram-post": [[977, 1009]]+ },+ "locatedOutput": {+ "visualFragments": 155,+ "audioFragments": 14+ }+}diff --git a/examples/regen-ranking/regen-ranking.svml b/examples/regen-ranking/regen-ranking.svmlnew file mode 100644index 00000000..32f6fc6a--- /dev/null+++ b/examples/regen-ranking/regen-ranking.svml@@ -0,0 +1,165 @@+<svml version="1">++ <import from="../../stdlib/speech-spine.svk"/>+ <import from="../../stdlib/media-track.svk"/>+ <import from="../../stdlib/ranking-column.svk"/>+ <import from="../../stdlib/broll-track.svk"/>+ <import from="../../stdlib/text-track.svk"/>+ <import from="../../stdlib/caption-track.svk"/>+ <import from="../../stdlib/audio-track.svk"/>+ <import from="../../stdlib/film.svk"/>++ <script>+ <segment id="scene-1">+ <NARRATOR> @photoshop Photoshop.+ <SPEAKER> Powerful, but only if you know how to use it. Otherwise, your new profile+ picture becomes a three-hour design project @/photoshop.+ <NARRATOR> @facetune Facetune.+ <SPEAKER> Fast and great for touch-ups. But it still leaves you with the same awkward+ pose and the same dorm-room background @/facetune.+ </segment>++ <segment id="scene-2">+ <NARRATOR> @remini Remini.+ <SPEAKER> Great for blurry photos. It restores detail, but it can't fix the pose,+ outfit, or background. You get the same bad photo in HD @/remini.+ <NARRATOR> @chatgpt ChatGPT.+ <SPEAKER> More flexible. It can create a new shot, but getting your face and the+ details right becomes a prompt-writing group project @/chatgpt.+ </segment>++ <segment id="scene-3">+ <NARRATOR> @regen ReGen.+ <SPEAKER> Pick a photo you love, and the app @handsome-1 rebuilds it around you with a+ @/handsome-1~ @handsome-2 better pose, outfit, and setting. @/handsome-2+ From one selfie, you can make @dating-photo a dating photo, @/dating-photo~+ @linkedin-headshot LinkedIn headshot, @/linkedin-headshot~+ @instagram-post or Instagram post, @/instagram-post+ so you get what you wanted instead of fixing a bad shot @/regen.+ </segment>+ </script>++ <video id="avatar-1" src="./assets/avatar-1.mp4"/>+ <video id="avatar-2" src="./assets/avatar-2.mp4"/>+ <video id="avatar-3" src="./assets/avatar-3.mp4"/>+ <audio id="avatar-1-audio" src="./assets/avatar-1.mp3"/>+ <audio id="avatar-2-audio" src="./assets/avatar-2.mp3"/>+ <audio id="avatar-3-audio" src="./assets/avatar-3.mp3"/>++ <image id="ranking-icon-1" src="./assets/ranking-icon-1.jpg"/>+ <image id="ranking-icon-2" src="./assets/ranking-icon-2.jpg"/>+ <image id="ranking-icon-3" src="./assets/ranking-icon-3.jpg"/>+ <image id="ranking-icon-4" src="./assets/ranking-icon-4.jpg"/>+ <image id="ranking-icon-5" src="./assets/ranking-icon-5.jpg"/>++ <image id="broll-1" src="./assets/broll-1.png"/>+ <image id="broll-2" src="./assets/broll-2.png"/>+ <image id="broll-3" src="./assets/broll-3.png"/>+ <image id="broll-4" src="./assets/broll-4.png"/>+ <image id="broll-5" src="./assets/broll-5.png"/>++ <audio id="ranking-appear" src="./assets/ranking-appear.wav"/>+ <audio id="ranking-move" src="./assets/ranking-move.wav"/>+ <audio id="background-music" src="./assets/background.mp3"/>++ <speech-spine id="speech">+ <segment id="scene-1" script={script.segment.scene-1} visual={avatar-1} audio={avatar-1-audio}/>+ <segment id="scene-2" script={script.segment.scene-2} visual={avatar-2} audio={avatar-2-audio}/>+ <segment id="scene-3" script={script.segment.scene-3} visual={avatar-3} audio={avatar-3-audio}/>+ </speech-spine>++ <media-track id="base" z="20">+ <item id="scene-1" source={speech.segment.scene-1.visual} fit="cover"/>+ <item id="scene-2" source={speech.segment.scene-2.visual} fit="cover"/>+ <item id="scene-3" source={speech.segment.scene-3.visual} fit="cover"/>+ </media-track>++ <ranking-column+ id="ranking"+ z="42"+ x="0"+ y="0.17"+ width="0.305"+ rowHeight="0.071"+ gap="0.011"+ stageX="0.66"+ stageY="0.73"+ stageSize="0.33"+ appearSound={ranking-appear}+ moveSound={ranking-move}+ appearGain="0.09"+ moveGain="0.10"+ >+ <item id="regen" rank="1" image={ranking-icon-1} during={script.selection.regen} window="start+0.1s .. end-0.3s"/>+ <item id="chatgpt" rank="2" image={ranking-icon-2} during={script.selection.chatgpt} window="start+0.1s .. end-0.3s"/>+ <item id="remini" rank="3" image={ranking-icon-3} during={script.selection.remini} window="start+0.1s .. end-0.3s"/>+ <item id="facetune" rank="4" image={ranking-icon-4} during={script.selection.facetune} window="start+0.1s .. end-0.3s"/>+ <item id="photoshop" rank="5" image={ranking-icon-5} during={script.selection.photoshop} window="start+0.1s .. end-0.3s"/>+ </ranking-column>++ <text-track id="title" z="70">+ <item+ id="title"+ text="Ranking AI photo apps for guys with no good pics"+ during="full"+ x="0"+ y="0.09895833333333333"+ width="1"+ height="0.078125"+ font="Poppins, Inter, Arial, sans-serif"+ size="54"+ weight="950"+ lineHeight="0.92"+ letterSpacing="0.2"+ color="#050505"+ background="#ffffff"+ uppercase="true"+ />+ </text-track>++ <broll-track id="broll" z="700">+ <item id="handsome-1" source={broll-5} during={script.selection.handsome-1} fit="contain" zoom="1.02"/>+ <item id="handsome-2" source={broll-4} during={script.selection.handsome-2} fit="contain" zoom="1.03"/>+ <item id="dating-photo" source={broll-3} during={script.selection.dating-photo} fit="contain" zoom="1.02"/>+ <item id="linkedin-headshot" source={broll-2} during={script.selection.linkedin-headshot} fit="contain" zoom="1.03"/>+ <item id="instagram-post" source={broll-1} during={script.selection.instagram-post} fit="contain" zoom="1.02"/>+ </broll-track>++ <caption-track+ id="captions"+ script={script}+ z="500"+ x="0.37"+ y="0.54"+ width="0.64"+ maxWords="3"+ hold="0.08"+ font="Poppins, Inter, Arial, sans-serif"+ size="50"+ weight="800"+ tracking="-1"+ color="#ffffff"+ highlight="#ffd34d"+ />++ <audio-track id="music">+ <item id="background" source={background-music} during="full" volume="0.9"/>+ </audio-track>++ <film+ id="regen-ranking"+ speech={speech.speech}+ width="1080"+ height="1920"+ fps="30"+ background="#000000"+ >+ <track ref={base.track}/>+ <track ref={ranking.track}/>+ <track ref={title.track}/>+ <track ref={broll.track}/>+ <track ref={captions.track}/>+ <track ref={music.track}/>+ </film>++</svml>diff --git a/package.json b/package.jsonnew file mode 100644index 00000000..a2c9d88e--- /dev/null+++ b/package.json@@ -0,0 +1,33 @@+{+ "name": "@svml/compiler",+ "version": "0.0.1",+ "private": true,+ "type": "module",+ "bin": {+ "svml": "./dist/src/cli.js"+ },+ "scripts": {+ "build": "tsc -p tsconfig.json && node tools/copy-runtime.mjs",+ "check": "tsc -p tsconfig.json --noEmit",+ "test": "node --import tsx --test 'test/**/*.test.ts'",+ "svml": "node --import tsx src/cli.ts"+ },+ "files": [+ "dist/src",+ "stdlib",+ "spec",+ "docs",+ "README.md"+ ],+ "engines": {+ "node": ">=22"+ },+ "dependencies": {+ "hyperframes": "0.7.84"+ },+ "devDependencies": {+ "@types/node": "24.10.1",+ "tsx": "4.21.0",+ "typescript": "5.9.3"+ }+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlnew file mode 100644index 00000000..df6cc73a--- /dev/null+++ b/pnpm-lock.yaml@@ -0,0 +1,1951 @@+lockfileVersion: '9.0'++settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: false++importers:++ .:+ dependencies:+ hyperframes:+ specifier: 0.7.84+ version: 0.7.84(@types/[email protected])+ devDependencies:+ '@types/node':+ specifier: 24.10.1+ version: 24.10.1+ tsx:+ specifier: 4.21.0+ version: 4.21.0+ typescript:+ specifier: 5.9.3+ version: 5.9.3++packages:++ '@emnapi/[email protected]':+ resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==}++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [aix]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [aix]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==}+ engines: {node: '>=18'}+ cpu: [loong64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==}+ engines: {node: '>=18'}+ cpu: [loong64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==}+ engines: {node: '>=18'}+ cpu: [mips64el]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==}+ engines: {node: '>=18'}+ cpu: [mips64el]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==}+ engines: {node: '>=18'}+ cpu: [riscv64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==}+ engines: {node: '>=18'}+ cpu: [riscv64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==}+ engines: {node: '>=18'}+ cpu: [s390x]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==}+ engines: {node: '>=18'}+ cpu: [s390x]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openharmony]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openharmony]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [sunos]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [sunos]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [win32]++ '@google/[email protected]':+ resolution: {integrity: sha512-gwSvbpiN/17O9TbsqSsE/OzZcpv5Fo4RQjdngGgogtuB9RsyJ8ZHhX5KjHj1bp5N9snN2eK8LDGXSaWW2hof8Q==}+ engines: {node: '>=20.0.0'}+ peerDependencies:+ '@modelcontextprotocol/sdk': ^1.25.2+ peerDependenciesMeta:+ '@modelcontextprotocol/sdk':+ optional: true++ '@hono/[email protected]':+ resolution: {integrity: sha512-eWpQYr67tqJLeaSUl0Q+TquuYfUdTibpOJlUMV2FfUP7+KqCC5TufnwnlXL6mobZBJbGAYRd7ZvEBDCbLInjhg==}+ engines: {node: '>=20'}+ peerDependencies:+ hono: ^4++ '@img/[email protected]':+ resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}+ engines: {node: '>=18'}++ '@img/[email protected]':+ resolution: {integrity: sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg==}+ engines: {node: '>=20.9.0'}+ cpu: [arm64]+ os: [darwin]++ '@img/[email protected]':+ resolution: {integrity: sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w==}+ engines: {node: '>=20.9.0'}+ cpu: [x64]+ os: [darwin]++ '@img/[email protected]':+ resolution: {integrity: sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg==}+ engines: {node: '>=20.9.0'}+ os: [freebsd]++ '@img/[email protected]':+ resolution: {integrity: sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg==}+ cpu: [arm64]+ os: [darwin]++ '@img/[email protected]':+ resolution: {integrity: sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw==}+ cpu: [x64]+ os: [darwin]++ '@img/[email protected]':+ resolution: {integrity: sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA==}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@img/[email protected]':+ resolution: {integrity: sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ==}+ cpu: [arm]+ os: [linux]+ libc: [glibc]++ '@img/[email protected]':+ resolution: {integrity: sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw==}+ cpu: [ppc64]+ os: [linux]+ libc: [glibc]++ '@img/[email protected]':+ resolution: {integrity: sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w==}+ cpu: [riscv64]+ os: [linux]+ libc: [glibc]++ '@img/[email protected]':+ resolution: {integrity: sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ==}+ cpu: [s390x]+ os: [linux]+ libc: [glibc]++ '@img/[email protected]':+ resolution: {integrity: sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w==}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@img/[email protected]':+ resolution: {integrity: sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw==}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@img/[email protected]':+ resolution: {integrity: sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ==}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@img/[email protected]':+ resolution: {integrity: sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ==}+ engines: {node: '>=20.9.0'}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@img/[email protected]':+ resolution: {integrity: sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA==}+ engines: {node: '>=20.9.0'}+ cpu: [arm]+ os: [linux]+ libc: [glibc]++ '@img/[email protected]':+ resolution: {integrity: sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA==}+ engines: {node: '>=20.9.0'}+ cpu: [ppc64]+ os: [linux]+ libc: [glibc]++ '@img/[email protected]':+ resolution: {integrity: sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ==}+ engines: {node: '>=20.9.0'}+ cpu: [riscv64]+ os: [linux]+ libc: [glibc]++ '@img/[email protected]':+ resolution: {integrity: sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw==}+ engines: {node: '>=20.9.0'}+ cpu: [s390x]+ os: [linux]+ libc: [glibc]++ '@img/[email protected]':+ resolution: {integrity: sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA==}+ engines: {node: '>=20.9.0'}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@img/[email protected]':+ resolution: {integrity: sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w==}+ engines: {node: '>=20.9.0'}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@img/[email protected]':+ resolution: {integrity: sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg==}+ engines: {node: '>=20.9.0'}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@img/[email protected]':+ resolution: {integrity: sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w==}+ engines: {node: '>=20.9.0'}++ '@img/[email protected]':+ resolution: {integrity: sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q==}+ engines: {node: '>=20.9.0'}+ cpu: [wasm32]++ '@img/[email protected]':+ resolution: {integrity: sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w==}+ engines: {node: '>=20.9.0'}+ cpu: [arm64]+ os: [win32]++ '@img/[email protected]':+ resolution: {integrity: sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw==}+ engines: {node: ^20.9.0}+ cpu: [ia32]+ os: [win32]++ '@img/[email protected]':+ resolution: {integrity: sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA==}+ engines: {node: '>=20.9.0'}+ cpu: [x64]+ os: [win32]++ '@isaacs/[email protected]':+ resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==}+ engines: {node: '>=18.0.0'}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==}++ '@puppeteer/[email protected]':+ resolution: {integrity: sha512-B/gKoqlFkzhvzsI6jo9K1cZz9o5ypviVv/xu8CwA4grZzyVwN+XfkT+tu8T1zrauuEXv6VhS2oGX+6NL95WcKA==}+ engines: {node: '>=22.12.0'}+ hasBin: true+ peerDependencies:+ proxy-agent: '>=8.0.1'+ yauzl: ^2.10.0 || ^3.4.0+ peerDependenciesMeta:+ proxy-agent:+ optional: true+ yauzl:+ optional: true++ '@swc/[email protected]':+ resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==}++ resolution: {integrity: sha512-XleryMhbuksdKtofnWZ9Sk+4CUTbms4Mb/EU32SZwToAyZ5RgVos/ki8n+yr0LWHOGKuakbXTuuYNHLQjhddgg==}+ engines: {node: '>=14.0'}++ resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}+ engines: {node: '>= 14'}++ resolution: {integrity: sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}++ resolution: {integrity: sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==}++ resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==}+ deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.++ resolution: {integrity: sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==}++ resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==}++ resolution: {integrity: sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-5v9GQFhTktFvotn/OFNJBmKLKRAb6n9r0bVCwf7sHgWc3/JryK0bj1nn93L3pHFrfgcsu6Be6EWsDi+1XHTGDg==}+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0'}+ peerDependencies:+ devtools-protocol: '*'++ resolution: {integrity: sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==}++ resolution: {integrity: sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==}+ engines: {node: '>=20'}++ resolution: {integrity: sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==}+ engines: {node: '>=0.8'}++ resolution: {integrity: sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==}++ resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==}+ engines: {node: '>= 12'}++ resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}+ engines: {node: '>=6.0'}+ peerDependencies:+ supports-color: '*'+ peerDependenciesMeta:+ supports-color:+ optional: true++ resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==}++ resolution: {integrity: sha512-pGVkY3T/qXxAp2nFPodwYqOevk6ncNMSmvL8QfRCx5ZWGd6Vor7AFNmyaA8Zs6uJyP1QAfjuLandCgvSix1BNA==}++ resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==}++ resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==}++ resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==}++ resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==}++ resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}++ resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}++ resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==}+ engines: {node: ^12.20 || >= 14.13}++ resolution: {integrity: sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==}++ resolution: {integrity: sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==}+ engines: {node: '>=12.20.0'}++ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}+ os: [darwin]++ resolution: {integrity: sha512-RB5vLV+vvQeoFPCX4QMK6/hjVkbIamPp1QSUD0CiZcnj12qbpiL+pLbYtgD+oZkWl0tl9z+o2Utp+MpM3QRhBA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}+ engines: {node: 6.* || 8.* || >= 10.*}++ resolution: {integrity: sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==}++ resolution: {integrity: sha512-r+mvuDjrjMpsdw46Kmeydb8bdHm7wOKw8wNBtTndkjbPjgAp5oUJUxRE76wZFknxIPokfWvep2qSXK37aXE6zg==}+ hasBin: true++ resolution: {integrity: sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==}+ engines: {node: '>=10.0'}++ resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==}+ engines: {node: '>=14'}++ resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==}++ resolution: {integrity: sha512-XcuyW9qE2kJn07PkecMOBd5Vq/hMy7mmGw+idz1yblbg9N17ijJODrvPkn7/dwL3Kulj8LcRJ69DLOWf91dRUg==}+ engines: {node: '>=16.9.0'}++ resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}+ engines: {node: '>= 14'}++ resolution: {integrity: sha512-JkfJtHRjPezHPdXoyoHjgnBEGQOffzjvAe4+bsHgbo1VBp3vYQI47GdL2bn3EydPa7p8c/shs7Ffs503ZrO4xA==}+ engines: {node: '>=22'}+ hasBin: true++ resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}+ engines: {node: '>= 4'}++ resolution: {integrity: sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}+ hasBin: true++ resolution: {integrity: sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==}+ engines: {node: '>=14.16'}+ hasBin: true++ resolution: {integrity: sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==}+ engines: {node: '>=16'}++ resolution: {integrity: sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==}++ resolution: {integrity: sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==}++ resolution: {integrity: sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==}++ resolution: {integrity: sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==}++ resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==}++ resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==}+ engines: {node: '>=16 || 14 >=14.17'}++ resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==}++ resolution: {integrity: sha512-t9VmxaqrmANnEOBhpSDI6HD192Ge48k8vmWqQQL7hSFEqHEYwZbbsu49+aKLWZeRvFs3j1pMhXOqqF4kPlvjkQ==}+ engines: {node: '>=18.0.0'}++ resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}++ resolution: {integrity: sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==}+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}+ hasBin: true++ resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==}+ engines: {node: '>=10.5.0'}+ deprecated: Use your platform's native DOMException instead++ resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-E0q8+fMyJ+F8dvlwVsXcujrOc96lkPIDAZh3p6pjrZS4bzjowIcUMv48W5zOcFLtlWyycUlRPJWUUK2+3IL1eA==}++ resolution: {integrity: sha512-YThL/YYeGAeytecOvRcTKUORTIE2f8/iSo/JZgHFawWrV4zOY7fWLEaNuscgjmY5C5/VE/Wr7tm+ucSsc/AysQ==}+ os: [win32, darwin, linux]++ resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==}++ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}++ resolution: {integrity: sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==}+ engines: {node: ^10 || ^12 || >=14}++ resolution: {integrity: sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g==}+ engines: {node: '>=14'}+ hasBin: true++ resolution: {integrity: sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-K1plkLOdeoUnGeT1OvdqF3qxl33v+Ra/uH5VyPEhXdMcpvGiEskHzxxEU3fgpccJpJLIipB/rPUsvkZRWeKqOA==}+ engines: {node: '>=22.12.0'}++ resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==}++ resolution: {integrity: sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==}++ resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==}+ engines: {node: '>= 4'}++ resolution: {integrity: sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==}+ engines: {node: '>=8.0'}++ resolution: {integrity: sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}++ resolution: {integrity: sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==}++ resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==}+ engines: {node: '>=10'}+ hasBin: true++ resolution: {integrity: sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q==}+ engines: {node: '>=20.9.0'}+ peerDependencies:+ '@types/node': '*'+ peerDependenciesMeta:+ '@types/node':+ optional: true++ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==}++ resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg==}+ engines: {node: '>=20'}++ resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==}++ resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}++ resolution: {integrity: sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==}+ engines: {node: '>=18.0.0'}+ hasBin: true++ resolution: {integrity: sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-EOPFbyIub4ngnEdqi2yOcNeDLaX/0jcE1JoAXQDDMIthap7FoN795lc/SHfIq2d416VufXpM8z/lD+WRm2gfOQ==}++ resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}+ engines: {node: '>=14.17'}+ hasBin: true++ resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==}++ resolution: {integrity: sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==}++ resolution: {integrity: sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==}++ resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}+ engines: {node: '>= 8'}++ resolution: {integrity: sha512-VSV+fzfChirL3e7jay2yUC7B4HQCGtEWEg/MSSQbK+qWbqeGlRLlXTzPpYr3XGUvbpDHumWZBJxgesg4N7dbtA==}++ resolution: {integrity: sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==}+ engines: {node: '>=10.0.0'}+ peerDependencies:+ bufferutil: ^4.0.1+ utf-8-validate: '>=5.0.2'+ peerDependenciesMeta:+ bufferutil:+ optional: true+ utf-8-validate:+ optional: true++ resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==}+ engines: {node: ^20.19.0 || ^22.12.0 || >=23}++ resolution: {integrity: sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg==}+ engines: {node: ^20.19.0 || ^22.12.0 || >=23}++ resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}++snapshots:++ '@emnapi/[email protected]':+ dependencies:+ tslib: 2.8.1+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@google/[email protected]':+ dependencies:+ google-auth-library: 10.9.1+ p-retry: 4.6.2+ protobufjs: 7.6.5+ ws: 8.21.1+ transitivePeerDependencies:+ - bufferutil+ - supports-color+ - utf-8-validate+ optional: true++ '@hono/[email protected]([email protected])':+ dependencies:+ hono: 4.12.32++ '@img/[email protected]': {}++ '@img/[email protected]':+ optionalDependencies:+ '@img/sharp-libvips-darwin-arm64': 1.3.2+ optional: true++ '@img/[email protected]':+ optionalDependencies:+ '@img/sharp-libvips-darwin-x64': 1.3.2+ optional: true++ '@img/[email protected]':+ dependencies:+ '@img/sharp-wasm32': 0.35.3+ optional: true++ '@img/[email protected]':+ optional: true++ '@img/[email protected]':+ optional: true++ '@img/[email protected]':+ optional: true++ '@img/[email protected]':+ optional: true++ '@img/[email protected]':+ optional: true++ '@img/[email protected]':+ optional: true++ '@img/[email protected]':+ optional: true++ '@img/[email protected]':+ optional: true++ '@img/[email protected]':+ optional: true++ '@img/[email protected]':+ optional: true++ '@img/[email protected]':+ optionalDependencies:+ '@img/sharp-libvips-linux-arm64': 1.3.2+ optional: true++ '@img/[email protected]':+ optionalDependencies:+ '@img/sharp-libvips-linux-arm': 1.3.2+ optional: true++ '@img/[email protected]':+ optionalDependencies:+ '@img/sharp-libvips-linux-ppc64': 1.3.2+ optional: true++ '@img/[email protected]':+ optionalDependencies:+ '@img/sharp-libvips-linux-riscv64': 1.3.2+ optional: true++ '@img/[email protected]':+ optionalDependencies:+ '@img/sharp-libvips-linux-s390x': 1.3.2+ optional: true++ '@img/[email protected]':+ optionalDependencies:+ '@img/sharp-libvips-linux-x64': 1.3.2+ optional: true++ '@img/[email protected]':+ optionalDependencies:+ '@img/sharp-libvips-linuxmusl-arm64': 1.3.2+ optional: true++ '@img/[email protected]':+ optionalDependencies:+ '@img/sharp-libvips-linuxmusl-x64': 1.3.2+ optional: true++ '@img/[email protected]':+ dependencies:+ '@emnapi/runtime': 1.11.3+ optional: true++ '@img/[email protected]':+ dependencies:+ '@img/sharp-wasm32': 0.35.3+ optional: true++ '@img/[email protected]':+ optional: true++ '@img/[email protected]':+ optional: true++ '@img/[email protected]':+ optional: true++ '@isaacs/[email protected]':+ dependencies:+ minipass: 7.1.3++ '@protobufjs/[email protected]':+ optional: true++ '@protobufjs/[email protected]':+ optional: true++ '@protobufjs/[email protected]':+ optional: true++ '@protobufjs/[email protected]':+ optional: true++ '@protobufjs/[email protected]':+ dependencies:+ '@protobufjs/aspromise': 1.1.2+ optional: true++ '@protobufjs/[email protected]':+ optional: true++ '@protobufjs/[email protected]':+ optional: true++ '@protobufjs/[email protected]':+ optional: true++ '@protobufjs/[email protected]':+ optional: true++ '@puppeteer/[email protected]':+ dependencies:+ modern-tar: 0.7.7+ yargs: 18.1.0++ '@swc/[email protected]':+ dependencies:+ tslib: 2.8.1++ '@types/[email protected]':+ dependencies:+ undici-types: 7.16.0++ '@types/[email protected]':+ optional: true++ [email protected]: {}++ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optional: true++ [email protected]: {}++ dependencies:+ base64-js: 1.5.1++ optional: true++ dependencies:+ run-applescript: 7.1.0++ [email protected]: {}++ dependencies:+ devtools-protocol: 0.0.1653615+ mitt: 3.0.1+ zod: 3.25.76++ [email protected]: {}++ dependencies:+ string-width: 7.2.0+ strip-ansi: 7.2.0+ wrap-ansi: 9.0.2++ [email protected]: {}++ [email protected]: {}++ optional: true++ dependencies:+ ms: 2.1.3++ [email protected]: {}++ dependencies:+ bundle-name: 4.1.0+ default-browser-id: 5.0.1++ dependencies:+ es-define-property: 1.0.1+ es-errors: 1.3.0+ gopd: 1.2.0++ [email protected]: {}++ dependencies:+ define-data-property: 1.1.4+ has-property-descriptors: 1.0.2+ object-keys: 1.1.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ safe-buffer: 5.2.1+ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optionalDependencies:+ '@esbuild/aix-ppc64': 0.25.12+ '@esbuild/android-arm': 0.25.12+ '@esbuild/android-arm64': 0.25.12+ '@esbuild/android-x64': 0.25.12+ '@esbuild/darwin-arm64': 0.25.12+ '@esbuild/darwin-x64': 0.25.12+ '@esbuild/freebsd-arm64': 0.25.12+ '@esbuild/freebsd-x64': 0.25.12+ '@esbuild/linux-arm': 0.25.12+ '@esbuild/linux-arm64': 0.25.12+ '@esbuild/linux-ia32': 0.25.12+ '@esbuild/linux-loong64': 0.25.12+ '@esbuild/linux-mips64el': 0.25.12+ '@esbuild/linux-ppc64': 0.25.12+ '@esbuild/linux-riscv64': 0.25.12+ '@esbuild/linux-s390x': 0.25.12+ '@esbuild/linux-x64': 0.25.12+ '@esbuild/netbsd-arm64': 0.25.12+ '@esbuild/netbsd-x64': 0.25.12+ '@esbuild/openbsd-arm64': 0.25.12+ '@esbuild/openbsd-x64': 0.25.12+ '@esbuild/openharmony-arm64': 0.25.12+ '@esbuild/sunos-x64': 0.25.12+ '@esbuild/win32-arm64': 0.25.12+ '@esbuild/win32-ia32': 0.25.12+ '@esbuild/win32-x64': 0.25.12++ optionalDependencies:+ '@esbuild/aix-ppc64': 0.27.7+ '@esbuild/android-arm': 0.27.7+ '@esbuild/android-arm64': 0.27.7+ '@esbuild/android-x64': 0.27.7+ '@esbuild/darwin-arm64': 0.27.7+ '@esbuild/darwin-x64': 0.27.7+ '@esbuild/freebsd-arm64': 0.27.7+ '@esbuild/freebsd-x64': 0.27.7+ '@esbuild/linux-arm': 0.27.7+ '@esbuild/linux-arm64': 0.27.7+ '@esbuild/linux-ia32': 0.27.7+ '@esbuild/linux-loong64': 0.27.7+ '@esbuild/linux-mips64el': 0.27.7+ '@esbuild/linux-ppc64': 0.27.7+ '@esbuild/linux-riscv64': 0.27.7+ '@esbuild/linux-s390x': 0.27.7+ '@esbuild/linux-x64': 0.27.7+ '@esbuild/netbsd-arm64': 0.27.7+ '@esbuild/netbsd-x64': 0.27.7+ '@esbuild/openbsd-arm64': 0.27.7+ '@esbuild/openbsd-x64': 0.27.7+ '@esbuild/openharmony-arm64': 0.27.7+ '@esbuild/sunos-x64': 0.27.7+ '@esbuild/win32-arm64': 0.27.7+ '@esbuild/win32-ia32': 0.27.7+ '@esbuild/win32-x64': 0.27.7++ [email protected]: {}++ [email protected]: {}++ optional: true++ [email protected]: {}++ dependencies:+ node-domexception: 1.0.0+ web-streams-polyfill: 3.3.3+ optional: true++ dependencies:+ '@swc/helpers': 0.5.23+ brotli: 1.3.3+ clone: 2.1.2+ dfa: 1.2.0+ fast-deep-equal: 3.1.3+ restructure: 3.0.2+ tiny-inflate: 1.0.3+ unicode-properties: 1.4.1+ unicode-trie: 2.0.0++ dependencies:+ fetch-blob: 3.2.0+ optional: true++ optional: true++ dependencies:+ extend: 3.0.2+ https-proxy-agent: 7.0.6+ node-fetch: 3.3.2+ transitivePeerDependencies:+ - supports-color+ optional: true++ dependencies:+ gaxios: 7.3.0+ google-logging-utils: 1.1.3+ json-bigint: 1.0.0+ transitivePeerDependencies:+ - supports-color+ optional: true++ [email protected]: {}++ [email protected]: {}++ dependencies:+ resolve-pkg-maps: 1.0.0++ [email protected]: {}++ dependencies:+ boolean: 3.2.0+ es6-error: 4.1.1+ matcher: 3.0.0+ roarr: 2.15.4+ semver: 7.8.5+ serialize-error: 7.0.1++ dependencies:+ define-properties: 1.2.1+ gopd: 1.2.0++ dependencies:+ base64-js: 1.5.1+ ecdsa-sig-formatter: 1.0.11+ gaxios: 7.3.0+ gcp-metadata: 8.1.2+ google-logging-utils: 1.1.3+ jws: 4.0.1+ transitivePeerDependencies:+ - supports-color+ optional: true++ optional: true++ [email protected]: {}++ dependencies:+ es-define-property: 1.0.1++ [email protected]: {}++ dependencies:+ agent-base: 7.1.4+ debug: 4.4.3+ transitivePeerDependencies:+ - supports-color+ optional: true++ [email protected](@types/[email protected]):+ dependencies:+ '@hono/node-server': 2.0.12([email protected])+ '@puppeteer/browsers': 3.0.6+ adm-zip: 0.6.0+ citty: 0.2.2+ compare-versions: 6.1.1+ debug: 4.4.3+ esbuild: 0.25.12+ fontkit: 2.0.4+ giget: 3.3.1+ hono: 4.12.32+ ignore: 5.3.2+ onnxruntime-node: 1.21.1+ open: 10.2.0+ postcss: 8.5.25+ prettier: 3.9.6+ puppeteer-core: 25.4.0+ sharp: 0.35.3(@types/[email protected])+ optionalDependencies:+ '@google/genai': 1.52.0+ transitivePeerDependencies:+ - '@modelcontextprotocol/sdk'+ - '@types/node'+ - bufferutil+ - proxy-agent+ - supports-color+ - utf-8-validate+ - yauzl++ [email protected]: {}++ [email protected]: {}++ dependencies:+ is-docker: 3.0.0++ dependencies:+ is-inside-container: 1.0.0++ dependencies:+ bignumber.js: 9.3.1+ optional: true++ [email protected]: {}++ dependencies:+ buffer-equal-constant-time: 1.0.1+ ecdsa-sig-formatter: 1.0.11+ safe-buffer: 5.2.1+ optional: true++ dependencies:+ jwa: 2.0.1+ safe-buffer: 5.2.1+ optional: true++ optional: true++ dependencies:+ escape-string-regexp: 4.0.0++ [email protected]: {}++ dependencies:+ minipass: 7.1.3++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optional: true++ dependencies:+ data-uri-to-buffer: 4.0.1+ fetch-blob: 3.2.0+ formdata-polyfill: 4.0.10+ optional: true++ [email protected]: {}++ [email protected]: {}++ dependencies:+ global-agent: 3.0.0+ onnxruntime-common: 1.21.1+ tar: 7.5.22++ dependencies:+ default-browser: 5.5.0+ define-lazy-prop: 3.0.0+ is-inside-container: 1.0.0+ wsl-utils: 0.1.0++ dependencies:+ '@types/retry': 0.12.0+ retry: 0.13.1+ optional: true++ [email protected]: {}++ [email protected]: {}++ dependencies:+ nanoid: 3.3.16+ picocolors: 1.1.1+ source-map-js: 1.2.1++ [email protected]: {}++ dependencies:+ '@protobufjs/aspromise': 1.1.2+ '@protobufjs/base64': 1.1.2+ '@protobufjs/codegen': 2.0.5+ '@protobufjs/eventemitter': 1.1.1+ '@protobufjs/fetch': 1.1.1+ '@protobufjs/float': 1.0.2+ '@protobufjs/path': 1.1.2+ '@protobufjs/pool': 1.1.0+ '@protobufjs/utf8': 1.1.2+ '@types/node': 24.10.1+ long: 5.3.2+ optional: true++ dependencies:+ '@puppeteer/browsers': 3.0.6+ chromium-bidi: 17.0.2([email protected])+ devtools-protocol: 0.0.1653615+ typed-query-selector: 2.12.2+ webdriver-bidi-protocol: 0.4.2+ ws: 8.21.1+ transitivePeerDependencies:+ - bufferutil+ - proxy-agent+ - utf-8-validate+ - yauzl++ [email protected]: {}++ [email protected]: {}++ optional: true++ dependencies:+ boolean: 3.2.0+ detect-node: 2.1.0+ globalthis: 1.0.4+ json-stringify-safe: 5.0.1+ semver-compare: 1.0.0+ sprintf-js: 1.1.3++ [email protected]: {}++ optional: true++ [email protected]: {}++ [email protected]: {}++ dependencies:+ type-fest: 0.13.1++ [email protected](@types/[email protected]):+ dependencies:+ '@img/colour': 1.1.0+ detect-libc: 2.1.2+ semver: 7.8.5+ optionalDependencies:+ '@img/sharp-darwin-arm64': 0.35.3+ '@img/sharp-darwin-x64': 0.35.3+ '@img/sharp-freebsd-wasm32': 0.35.3+ '@img/sharp-libvips-darwin-arm64': 1.3.2+ '@img/sharp-libvips-darwin-x64': 1.3.2+ '@img/sharp-libvips-linux-arm': 1.3.2+ '@img/sharp-libvips-linux-arm64': 1.3.2+ '@img/sharp-libvips-linux-ppc64': 1.3.2+ '@img/sharp-libvips-linux-riscv64': 1.3.2+ '@img/sharp-libvips-linux-s390x': 1.3.2+ '@img/sharp-libvips-linux-x64': 1.3.2+ '@img/sharp-libvips-linuxmusl-arm64': 1.3.2+ '@img/sharp-libvips-linuxmusl-x64': 1.3.2+ '@img/sharp-linux-arm': 0.35.3+ '@img/sharp-linux-arm64': 0.35.3+ '@img/sharp-linux-ppc64': 0.35.3+ '@img/sharp-linux-riscv64': 0.35.3+ '@img/sharp-linux-s390x': 0.35.3+ '@img/sharp-linux-x64': 0.35.3+ '@img/sharp-linuxmusl-arm64': 0.35.3+ '@img/sharp-linuxmusl-x64': 0.35.3+ '@img/sharp-webcontainers-wasm32': 0.35.3+ '@img/sharp-win32-arm64': 0.35.3+ '@img/sharp-win32-ia32': 0.35.3+ '@img/sharp-win32-x64': 0.35.3+ '@types/node': 24.10.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ emoji-regex: 10.6.0+ get-east-asian-width: 1.6.0+ strip-ansi: 7.2.0++ dependencies:+ get-east-asian-width: 1.6.0+ strip-ansi: 7.2.0++ dependencies:+ ansi-regex: 6.2.2++ dependencies:+ '@isaacs/fs-minipass': 4.0.1+ chownr: 3.0.0+ minipass: 7.1.3+ minizlib: 3.1.0+ yallist: 5.0.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ esbuild: 0.27.7+ get-tsconfig: 4.14.0+ optionalDependencies:+ fsevents: 2.3.3++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ base64-js: 1.5.1+ unicode-trie: 2.0.0++ dependencies:+ pako: 0.2.9+ tiny-inflate: 1.0.3++ optional: true++ [email protected]: {}++ dependencies:+ ansi-styles: 6.2.3+ string-width: 7.2.0+ strip-ansi: 7.2.0++ [email protected]: {}++ dependencies:+ is-wsl: 3.1.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ cliui: 9.0.1+ escalade: 3.2.0+ get-caller-file: 2.0.5+ string-width: 8.2.2+ y18n: 5.0.8+ yargs-parser: 22.0.0++ [email protected]: {}diff --git a/src/artifacts.ts b/src/artifacts.tsnew file mode 100644index 00000000..73dfb249--- /dev/null+++ b/src/artifacts.ts@@ -0,0 +1,214 @@+import { readFile } from "node:fs/promises";+import { dirname, resolve } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { fail } from "./diagnostics.js";+import type { KernelRegistry } from "./kernel.js";+import type { PlanIR } from "./model.js";+import type { KernelProjection } from "./runtime-contract.js";+import { sha256, stableJson } from "./util.js";++type ArtifactOutput = {+ type: "Image" | "Video" | "Audio" | "Text";+ uri?: string;+ value?: string;+ contentDigest: string;+};++type ArtifactBinding = {+ instanceIdentity: string;+ executionDigest: string;+ outputs: Record<string, ArtifactOutput>;+};++type ArtifactFile = {+ contract: "svml.artifacts.v1";+ bindings: ArtifactBinding[];+};++export type ArtifactResolution = {+ projections: Map<string, KernelProjection>;+ outputDigests: Map<string, string>;+ bindingExecutionDigests: Map<string, string>;+ manifestHash?: string;+ verified: boolean;+};++function externalUri(value: string): boolean {+ return /^[A-Za-z][A-Za-z0-9+.-]*:/u.test(value);+}++async function resolveOutput(+ artifactFile: string,+ output: ArtifactOutput,+): Promise<Record<string, unknown>> {+ if (output.type === "Text") {+ if (typeof output.value !== "string" || output.uri !== undefined) {+ fail("artifact_text", "Text artifact output requires value and forbids uri.");+ }+ const digest = sha256(output.value);+ if (digest !== output.contentDigest) {+ fail("artifact_digest", "Text artifact contentDigest does not match its value.");+ }+ return { type: "Text", value: output.value, contentDigest: digest };+ }+ if (typeof output.uri !== "string" || output.value !== undefined) {+ fail("artifact_media", `${output.type} artifact output requires uri and forbids value.`);+ }+ const uri = externalUri(output.uri)+ ? output.uri+ : pathToFileURL(resolve(dirname(artifactFile), output.uri)).href;+ if (!uri.startsWith("file:")) {+ fail(+ "artifact_unverifiable_uri",+ `Prototype artifact binding requires a local file URI, received "${uri}".`,+ );+ }+ let content: Buffer;+ try {+ content = await readFile(fileURLToPath(uri));+ } catch (error) {+ fail(+ "artifact_read",+ `Could not read bound artifact "${uri}": ${error instanceof Error ? error.message : String(error)}.`,+ );+ }+ const digest = sha256(content);+ if (digest !== output.contentDigest) {+ fail("artifact_digest", `Artifact "${uri}" does not match contentDigest.`);+ }+ return {+ type: output.type,+ source: uri,+ absoluteSource: uri,+ contentDigest: digest,+ };+}++export async function resolveArtifactFile(+ file: string | undefined,+ plan: PlanIR,+ kernels: KernelRegistry,+): Promise<ArtifactResolution> {+ const capabilityInstances = plan.instances.filter(+ (instance) => kernels.get(instance.kernel)?.profile === "capability-v1",+ );+ if (!capabilityInstances.length) {+ if (file) {+ fail("artifact_unexpected", "An artifact file was provided, but the Plan has no capability instances.");+ }+ return {+ projections: new Map(),+ outputDigests: new Map(),+ bindingExecutionDigests: new Map(),+ verified: true,+ };+ }+ if (!file) {+ fail(+ "artifact_file_required",+ `Plan contains ${capabilityInstances.length} capability instance(s); provide --artifacts. No provider is invoked implicitly.`,+ );+ }+ const absolute = resolve(file);+ let source: string;+ let parsed: unknown;+ try {+ source = await readFile(absolute, "utf8");+ parsed = JSON.parse(source);+ } catch (error) {+ fail(+ "artifact_file_read",+ `Could not read artifact bindings ${absolute}: ${error instanceof Error ? error.message : String(error)}.`,+ );+ }+ if (+ !parsed+ || typeof parsed !== "object"+ || (parsed as { contract?: string }).contract !== "svml.artifacts.v1"+ || !Array.isArray((parsed as { bindings?: unknown }).bindings)+ ) {+ fail("artifact_contract", `${absolute} is not an svml.artifacts.v1 document.`);+ }+ const artifactFile = parsed as ArtifactFile;+ const byIdentity = new Map<string, ArtifactBinding>();+ for (const binding of artifactFile.bindings) {+ if (byIdentity.has(binding.instanceIdentity)) {+ fail("artifact_duplicate_binding", `Artifact identity "${binding.instanceIdentity}" is repeated.`);+ }+ byIdentity.set(binding.instanceIdentity, binding);+ }+ const projections = new Map<string, KernelProjection>();+ const outputDigests = new Map<string, string>();+ const bindingExecutionDigests = new Map<string, string>();+ for (const instance of capabilityInstances) {+ const manifest = kernels.get(instance.kernel)!;+ const binding = byIdentity.get(instance.identity);+ if (!binding) {+ fail("artifact_binding_missing", `Capability instance "${instance.id}" has no artifact binding.`);+ }+ const outputPorts = manifest.ports.filter((port) => port.direction === "output");+ const unknown = Object.keys(binding.outputs).find(+ (name) => !outputPorts.some((port) => port.name === name),+ );+ if (unknown) {+ fail("artifact_output_unknown", `Capability "${instance.id}" has no output port "${unknown}".`);+ }+ const outputs: Record<string, unknown> = {};+ for (const port of outputPorts) {+ const descriptor = binding.outputs[port.name];+ if (!descriptor) {+ if (port.cardinality === "one" || port.cardinality === "one-or-more") {+ fail("artifact_output_missing", `Capability "${instance.id}" requires output "${port.name}".`);+ }+ continue;+ }+ if (descriptor.type !== port.type) {+ fail(+ "artifact_output_type",+ `Capability "${instance.id}.${port.name}" requires ${port.type}, received ${descriptor.type}.`,+ );+ }+ outputs[port.name] = await resolveOutput(absolute, descriptor);+ }+ projections.set(instance.id, { outputs });+ outputDigests.set(+ instance.id,+ sha256(stableJson(Object.fromEntries(Object.entries(binding.outputs)+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([name, descriptor]) => [+ name,+ { type: descriptor.type, contentDigest: descriptor.contentDigest },+ ])))),+ );+ bindingExecutionDigests.set(instance.id, binding.executionDigest);+ byIdentity.delete(instance.identity);+ }+ if (byIdentity.size) {+ fail(+ "artifact_binding_stale",+ `Artifact file contains ${byIdentity.size} binding(s) outside the reachable capability Plan.`,+ );+ }+ return {+ projections,+ outputDigests,+ bindingExecutionDigests,+ manifestHash: sha256(source),+ verified: true,+ };+}++export function verifyArtifactExecutionDigests(+ artifacts: ArtifactResolution,+ plan: PlanIR,+): void {+ for (const [id, expected] of artifacts.bindingExecutionDigests) {+ const instance = plan.instances.find((candidate) => candidate.id === id);+ if (!instance || instance.executionDigest !== expected) {+ fail(+ "artifact_execution_digest",+ `Artifact binding for "${id}" was produced for a different executionDigest.`,+ );+ }+ }+}diff --git a/src/cli.ts b/src/cli.tsnew file mode 100644index 00000000..72347360--- /dev/null+++ b/src/cli.ts@@ -0,0 +1,302 @@+#!/usr/bin/env node+import { spawn } from "node:child_process";+import { mkdir, writeFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { basename, dirname, resolve } from "node:path";+import {+ checkSource,+ compileSource,+ estimateSource,+ resolveScriptBindings,+} from "./compiler.js";+import { SvmlError } from "./diagnostics.js";+import { formatDocumentScript } from "./format.js";+import { projectCanvas, projectTimeline } from "./views.js";++type ParsedArgs = {+ command?: string;+ positional: string[];+ options: Map<string, string | true>;+};++function parseArgs(argv: string[]): ParsedArgs {+ const [command, ...rest] = argv;+ const positional: string[] = [];+ const options = new Map<string, string | true>();+ for (let index = 0; index < rest.length; index += 1) {+ const value = rest[index];+ if (!value?.startsWith("--")) {+ if (value) positional.push(value);+ continue;+ }+ const name = value.slice(2);+ const next = rest[index + 1];+ if (next && !next.startsWith("--")) {+ options.set(name, next);+ index += 1;+ } else {+ options.set(name, true);+ }+ }+ return {+ ...(command ? { command } : {}),+ positional,+ options,+ };+}++function option(args: ParsedArgs, name: string, required = false): string | undefined {+ const value = args.options.get(name);+ if (typeof value === "string") return value;+ if (required) throw new Error(`--${name} is required`);+ return undefined;+}++async function writeJson(file: string, value: unknown): Promise<void> {+ const output = resolve(file);+ await mkdir(dirname(output), { recursive: true });+ await writeFile(output, `${JSON.stringify(value, null, 2)}\n`, "utf8");+}++async function run(): Promise<void> {+ const args = parseArgs(process.argv.slice(2));+ const file = args.positional[0];+ if (args.command === "check") {+ if (!file) throw new Error("usage: svml check <file.svml>");+ const result = await checkSource(file);+ process.stdout.write(`${JSON.stringify({+ ok: true,+ source: result.document.file,+ script: {+ segments: result.narrative.segments.length,+ words: result.narrative.tokens.length,+ selections: Object.keys(result.narrative.selections).length,+ moments: Object.keys(result.narrative.moments).length,+ },+ plan: {+ values: result.plan.values.length,+ instances: result.plan.instances.length,+ edges: result.plan.edges.length,+ root: result.plan.root,+ },+ kernels: result.manifests.map((manifest) => ({+ name: manifest.name,+ abi: manifest.abiVersion,+ manifestHash: manifest.sourceHash,+ implementationHash: manifest.implementationHash,+ })),+ reproducibility: {+ lockRequiredForFrozenBuild: true,+ modules: result.lock.modules.length,+ },+ }, null, 2)}\n`);+ return;+ }+ if (args.command === "lock") {+ if (!file) throw new Error("usage: svml lock <file.svml> [--out svml.lock]");+ const result = await checkSource(file);+ const output = option(args, "out") ?? resolve(dirname(resolve(file)), "svml.lock");+ await writeJson(output, result.lock);+ process.stdout.write(`${JSON.stringify({+ ok: true,+ source: result.document.file,+ output: resolve(output),+ modules: result.lock.modules.length,+ kernels: result.lock.kernels.length,+ })}\n`);+ return;+ }+ if (args.command === "script") {+ if (!file) throw new Error("usage: svml script <file.svml> [--out tokens.json]");+ const result = await checkSource(file);+ const payload = {+ projections: result.narrative.projections,+ segments: result.narrative.segments.map((segment) => ({+ id: segment.id,+ tokenStart: segment.tokenStart,+ tokenEnd: segment.tokenEnd,+ })),+ words: result.narrative.tokens.map((token) => ({+ id: token.id,+ text: token.text,+ normalized: token.normalized,+ segmentId: token.segmentId,+ })),+ selections: result.narrative.selections,+ moments: result.narrative.moments,+ };+ const output = option(args, "out");+ if (output) await writeJson(output, payload);+ else process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);+ return;+ }+ if (args.command === "plan") {+ if (!file) throw new Error("usage: svml plan <file.svml> [--out plan.json]");+ const result = await checkSource(file);+ const output = option(args, "out");+ if (output) await writeJson(output, result.plan);+ else process.stdout.write(`${JSON.stringify(result.plan, null, 2)}\n`);+ return;+ }+ if (args.command === "fmt") {+ if (!file) throw new Error("usage: svml fmt <file.svml> [--check|--write|--out formatted.svml]");+ const checked = await checkSource(file);+ const formatted = formatDocumentScript(+ checked.document,+ checked.narrative,+ resolveScriptBindings(checked.document),+ );+ if (args.options.has("check")) {+ if (formatted !== checked.document.source) {+ throw new Error(`${resolve(file)} is not canonically formatted`);+ }+ process.stdout.write(`${resolve(file)} is canonically formatted\n`);+ return;+ }+ const output = option(args, "out");+ if (args.options.has("write")) {+ await writeFile(resolve(file), formatted, "utf8");+ } else if (output) {+ await writeFile(resolve(output), formatted, "utf8");+ } else {+ process.stdout.write(formatted);+ }+ return;+ }+ if (args.command === "estimate") {+ if (!file) throw new Error("usage: svml estimate <file.svml> [--out alignment.json]");+ const numeric = (name: string): number | undefined => {+ const value = option(args, name);+ if (value === undefined) return undefined;+ const parsed = Number(value);+ if (!Number.isFinite(parsed)) throw new Error(`--${name} requires a finite number`);+ return parsed;+ };+ const result = await estimateSource(file, {+ ...(numeric("syllables-per-second") !== undefined+ ? { syllablesPerSecond: numeric("syllables-per-second")! }+ : {}),+ ...(numeric("word-gap") !== undefined ? { wordGapSec: numeric("word-gap")! } : {}),+ ...(numeric("segment-padding") !== undefined+ ? { segmentPaddingSec: numeric("segment-padding")! }+ : {}),+ ...(numeric("empty-segment-duration") !== undefined+ ? { emptySegmentSec: numeric("empty-segment-duration")! }+ : {}),+ ...(numeric("max-caption-words") !== undefined+ ? { maxCaptionWords: numeric("max-caption-words")! }+ : {}),+ ...(numeric("fps") !== undefined ? { fps: numeric("fps")! } : {}),+ });+ const output = option(args, "out");+ if (output) await writeJson(output, result.evidence);+ else process.stdout.write(`${JSON.stringify(result.evidence, null, 2)}\n`);+ return;+ }+ if (args.command === "canvas") {+ if (!file) throw new Error("usage: svml canvas <file.svml> [--out canvas.json]");+ const result = await checkSource(file);+ const payload = projectCanvas(result.plan);+ const output = option(args, "out");+ if (output) await writeJson(output, payload);+ else process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);+ return;+ }+ if (args.command === "timeline") {+ if (!file) {+ throw new Error("usage: svml timeline <file.svml> --evidence alignment.json [--out timeline.json]");+ }+ const evidenceFile = option(args, "evidence", true);+ const compilation = await compileSource({+ file,+ evidenceFile: evidenceFile!,+ ...(option(args, "lock") ? { lockFile: option(args, "lock")! } : {}),+ ...(option(args, "artifacts")+ ? { artifactsFile: option(args, "artifacts")! }+ : {}),+ });+ const payload = projectTimeline(compilation);+ const output = option(args, "out");+ if (output) await writeJson(output, payload);+ else process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);+ return;+ }+ if (args.command === "compile") {+ if (!file) {+ throw new Error("usage: svml compile <file.svml> --evidence alignment.json --out index.html");+ }+ const evidenceFile = option(args, "evidence", true);+ const outputFile = option(args, "out", true);+ const compilation = await compileSource({+ file,+ evidenceFile: evidenceFile!,+ outputFile: outputFile!,+ ...(option(args, "lock") ? { lockFile: option(args, "lock")! } : {}),+ ...(option(args, "artifacts")+ ? { artifactsFile: option(args, "artifacts")! }+ : {}),+ });+ process.stdout.write(`${JSON.stringify({+ ok: true,+ source: compilation.document.file,+ output: compilation.outputFile,+ durationFrames: compilation.located.durationFrames,+ fps: compilation.located.fps,+ instances: compilation.plan.instances.length,+ reproducible: compilation.reproducible,+ })}\n`);+ return;+ }+ if (args.command === "render") {+ if (!file) throw new Error("usage: svml render <index.html> --out video.mp4");+ const output = option(args, "out", true);+ const cli = createRequire(import.meta.url).resolve("hyperframes/bin/hyperframes.mjs");+ const compositionFile = resolve(file);+ const projectDir = dirname(compositionFile);+ await new Promise<void>((accept, reject) => {+ const command = [+ cli,+ "render",+ projectDir,+ "-o",+ resolve(output!),+ ];+ if (basename(compositionFile) !== "index.html") {+ command.push("--composition", basename(compositionFile));+ }+ const child = spawn(process.execPath, command, {+ stdio: "inherit",+ });+ child.once("error", reject);+ child.once("exit", (code) => code === 0+ ? accept()+ : reject(new Error(`HyperFrames exited with status ${String(code)}`)));+ });+ return;+ }+ process.stdout.write(`SVML compiler++usage:+ svml check <file.svml>+ svml lock <file.svml> [--out svml.lock]+ svml script <file.svml> [--out narrative.json]+ svml plan <file.svml> [--out plan.json]+ svml fmt <file.svml> [--check|--write|--out formatted.svml]+ svml estimate <file.svml> [--out alignment.json] [--fps 30]+ svml canvas <file.svml> [--out canvas.json]+ svml timeline <file.svml> --evidence alignment.json [--out timeline.json] [--lock svml.lock] [--artifacts artifacts.json]+ svml compile <file.svml> --evidence alignment.json --out index.html [--lock svml.lock] [--artifacts artifacts.json]+ svml render <index.html> --out video.mp4++The current runtime is deterministic-only: it has no generation provider host.+`);+}++run().catch((error: unknown) => {+ if (error instanceof SvmlError) {+ process.stderr.write(`${JSON.stringify({ ok: false, diagnostics: error.diagnostics }, null, 2)}\n`);+ } else {+ process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);+ }+ process.exitCode = 1;+});diff --git a/src/compiler.ts b/src/compiler.tsnew file mode 100644index 00000000..2b3b5d8d--- /dev/null+++ b/src/compiler.ts@@ -0,0 +1,340 @@+import { copyFile, readFile, writeFile, mkdir } from "node:fs/promises";+import { basename, dirname, resolve } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { fail } from "./diagnostics.js";+import {+ resolveArtifactFile,+ verifyArtifactExecutionDigests,+} from "./artifacts.js";+import { attachExecutionDigests } from "./digests.js";+import { emitHyperframesHtml } from "./hyperframes.js";+import {+ kernelTemporalContracts,+ loadKernels,+ type KernelManifest,+} from "./kernel.js";+import { createLock, verifyLockFile, type SvmlLock } from "./lock.js";+import type {+ AlignmentEvidence,+ AttributeValue,+ PlanIR,+ SourceDocument,+ SourceElement,+} from "./model.js";+import { buildPlan, topologicalInstances } from "./plan.js";+import type {+ HyperframesDocument,+ KernelProjection,+ RuntimeValue,+} from "./runtime-contract.js";+import { projectKernelIsolated } from "./sandbox.js";+import { validateKernelProjection } from "./runtime-validation.js";+import { locateScript } from "./script/locate.js";+import { estimateAlignment, type EstimateOptions } from "./script/estimate.js";+import { parseScript } from "./script/parse.js";+import { loadSourceClosure } from "./source/modules.js";+import { childElements, textContent } from "./source/query.js";+import { applyStyleSheets } from "./source/styles.js";+import { sha256 } from "./util.js";++export type Compilation = {+ document: SourceDocument;+ narrative: ReturnType<typeof parseScript>;+ plan: PlanIR;+ located: ReturnType<typeof locateScript>;+ html: string;+ target: HyperframesDocument;+ outputFile?: string;+ projections: Map<string, KernelProjection>;+ lock: SvmlLock;+ lockVerified: boolean;+ artifactsVerified: boolean;+ artifactManifestHash?: string;+ reproducible: boolean;+};++function childById(document: SourceDocument): Map<string, SourceElement> {+ const output = new Map<string, SourceElement>();+ for (const element of childElements(document.root)) {+ const id = element.attributes.id;+ if (typeof id === "string") output.set(id, element);+ }+ return output;+}++export function resolveScriptBindings(document: SourceDocument): Record<string, string> {+ const script = childElements(document.root, "script")[0];+ if (!script) return {};+ const declarations = childById(document);+ return Object.fromEntries(Object.entries(script.attributes).map(([name, value]) => {+ if (typeof value === "string") return [name, value];+ if (!value || typeof value !== "object" || value.kind !== "reference") {+ fail("script_slot_binding", `Script Slot "${name}" requires literal Text or a Text reference.`);+ }+ const declaration = declarations.get(value.path);+ if (!declaration || declaration.name !== "text") {+ fail(+ "script_slot_binding",+ `Script Slot "${name}" references "${value.path}", which is not a Text declaration.`,+ );+ }+ return [name, textContent(declaration).trim()];+ }));+}++function nestedValue(value: unknown, path: string[]): unknown {+ let current = value;+ for (const part of path) {+ if (!current || typeof current !== "object") return undefined;+ current = (current as Record<string, unknown>)[part];+ }+ return current;+}++function isHyperframesDocument(value: unknown): value is HyperframesDocument {+ return !!value+ && typeof value === "object"+ && (value as HyperframesDocument).contract === "svml.hyperframes-document.v1";+}++async function stageDocumentAssets(+ document: HyperframesDocument,+ outputFile: string,+): Promise<HyperframesDocument> {+ const assetDirectory = resolve(dirname(outputFile), "assets");+ await mkdir(assetDirectory, { recursive: true });+ const staged = new Map<string, string>();+ const stage = async (source: string): Promise<string> => {+ if (!source.startsWith("file:")) return source;+ const existing = staged.get(source);+ if (existing) return existing;+ const local = fileURLToPath(source);+ const contentHash = sha256(await readFile(local));+ const name = `${contentHash.slice(0, 16)}-${basename(local)}`;+ await copyFile(local, resolve(assetDirectory, name));+ const relative = `./assets/${name}`;+ staged.set(source, relative);+ return relative;+ };+ const visuals = await Promise.all(document.visuals.map(async (fragment) => ({+ ...fragment,+ ...(fragment.source ? { source: await stage(fragment.source) } : {}),+ })));+ const audios = await Promise.all(document.audios.map(async (fragment) => ({+ ...fragment,+ source: await stage(fragment.source),+ })));+ return { ...document, visuals, audios };+}++export async function checkSource(file: string): Promise<{+ document: SourceDocument;+ narrative: ReturnType<typeof parseScript>;+ plan: PlanIR;+ manifests: KernelManifest[];+ lock: SvmlLock;+}> {+ const closure = await loadSourceClosure(file);+ const kernels = await loadKernels(closure);+ const document = await applyStyleSheets(closure, kernels);+ const narrative = parseScript(+ document.file,+ document.scriptSource,+ document.scriptOffset,+ resolveScriptBindings(document),+ );+ const plan = buildPlan(document, kernels, narrative);+ await attachExecutionDigests(plan, kernels);+ const manifests = [...kernels.values()];+ return {+ document,+ narrative,+ plan,+ manifests,+ lock: createLock(document, manifests, plan),+ };+}++export async function estimateSource(+ file: string,+ options: EstimateOptions = {},+): Promise<{+ evidence: AlignmentEvidence;+ located: ReturnType<typeof locateScript>;+}> {+ const checked = await checkSource(file);+ const evidence = estimateAlignment(checked.narrative, options);+ return {+ evidence,+ located: locateScript(checked.narrative, evidence),+ };+}++export async function compileSource(args: {+ file: string;+ evidenceFile: string;+ outputFile?: string;+ lockFile?: string;+ artifactsFile?: string;+}): Promise<Compilation> {+ const checked = await checkSource(args.file);+ if (args.lockFile) await verifyLockFile(resolve(args.lockFile), checked.lock);+ const evidence = JSON.parse(+ await readFile(resolve(args.evidenceFile), "utf8"),+ ) as AlignmentEvidence;+ const located = locateScript(checked.narrative, evidence);+ const kernels = await loadKernels(checked.document);+ const artifacts = await resolveArtifactFile(args.artifactsFile, checked.plan, kernels);+ await attachExecutionDigests(checked.plan, kernels, artifacts.outputDigests);+ verifyArtifactExecutionDigests(artifacts, checked.plan);+ const elements = childById(checked.document);+ const root = checked.plan.instances.find((instance) => instance.id === checked.plan.root);+ if (!root) fail("runtime_root_missing", `Root instance "${checked.plan.root}" is missing.`);+ const rootElement = elements.get(root.id);+ if (!rootElement) fail("runtime_root_element", `Root element "${root.id}" is missing.`);+ const width = Number(root.attributes.width ?? 1080);+ const height = Number(root.attributes.height ?? 1920);+ if (!Number.isFinite(width) || !Number.isFinite(height)) {+ fail("runtime_dimensions", "Film width and height must be finite numbers.");+ }++ const values = new Map<string, RuntimeValue>(checked.plan.values.map((value) => {+ const absoluteSource = value.source+ ? pathToFileURL(resolve(dirname(value.module), value.source)).href+ : undefined;+ return [+ value.id,+ { ...value, ...(absoluteSource ? { absoluteSource } : {}) },+ ];+ }));+ const results = new Map<string, KernelProjection>();++ const resolvePath = (path: string): unknown => {+ if (path === "script") {+ return { narrative: checked.narrative, located };+ }+ if (path.startsWith("script.selection.")) {+ return located.selections[path.slice("script.selection.".length)];+ }+ if (path.startsWith("script.moment.")) {+ return located.moments[path.slice("script.moment.".length)];+ }+ if (path.startsWith("script.segment.")) {+ return located.segments[path.slice("script.segment.".length)];+ }+ const declarationIds = [+ ...checked.plan.values.map((value) => value.id),+ ...checked.plan.instances.map((instance) => instance.id),+ ].sort((left, right) => right.length - left.length);+ const owner = declarationIds.find((id) => path === id || path.startsWith(`${id}.`));+ if (!owner) fail("runtime_reference_unknown", `Unknown reference "${path}".`);+ const tail = path === owner ? [] : path.slice(owner.length + 1).split(".");+ const value = values.get(owner);+ if (value) return tail.length ? nestedValue(value, tail) : value;+ const projection = results.get(owner);+ if (!projection) fail("runtime_reference_unready", `Reference "${path}" is not ready.`);+ return tail.length ? nestedValue(projection.outputs, tail) : projection.outputs;+ };++ const resolveValue = (value: AttributeValue | undefined): unknown => {+ if (value && typeof value === "object" && value.kind === "reference") {+ return resolvePath(value.path);+ }+ return value;+ };++ const resolveNode = (node: SourceElement["children"][number]): unknown => {+ if (node.kind === "text") return { ...node };+ return {+ ...node,+ attributes: Object.fromEntries(Object.entries(node.attributes)+ .map(([name, value]) => [name, resolveValue(value)])),+ children: node.children.map(resolveNode),+ };+ };++ for (const instance of topologicalInstances(checked.plan)) {+ const manifest = kernels.get(instance.kernel);+ if (!manifest) fail("runtime_kernel_missing", `Kernel "${instance.kernel}" is missing.`);+ if (manifest.abiVersion !== "1") {+ fail(+ "runtime_kernel_abi",+ `Kernel "${manifest.name}" uses unsupported implementation ABI ${manifest.abiVersion}.`,+ );+ }+ if (manifest.profile === "capability-v1") {+ const projection = artifacts.projections.get(instance.id);+ if (!projection) {+ fail("artifact_projection_missing", `Capability "${instance.id}" has no resolved outputs.`);+ }+ results.set(instance.id, projection);+ continue;+ }+ const sourceElement = elements.get(instance.id);+ if (!sourceElement) fail("runtime_instance_element", `Element "${instance.id}" is missing.`);+ const element = {+ ...sourceElement,+ attributes: instance.attributes,+ };+ const resolvedElement = {+ ...element,+ attributes: Object.fromEntries(Object.entries(element.attributes)+ .map(([name, value]) => [name, resolveValue(value)])),+ children: element.children.map(resolveNode),+ };+ const context = {+ instance,+ element: resolvedElement,+ narrative: checked.narrative,+ located,+ alignment: evidence,+ plan: checked.plan,+ temporalContracts: kernelTemporalContracts(manifest),+ fps: evidence.fps,+ width,+ height,+ };+ results.set(+ instance.id,+ validateKernelProjection(await projectKernelIsolated(manifest, context)),+ );+ }++ const rootProjection = results.get(checked.plan.root);+ const documentOutput = rootProjection?.outputs.document;+ if (!isHyperframesDocument(documentOutput)) {+ fail(+ "runtime_root_output",+ `Root Kernel "${root.kernel}" did not output svml.hyperframes-document.v1.`,+ );+ }+ const outputFile = args.outputFile ? resolve(args.outputFile) : undefined;+ const materializedDocument = outputFile+ ? await stageDocumentAssets(documentOutput, outputFile)+ : documentOutput;+ const html = emitHyperframesHtml(materializedDocument);+ if (args.outputFile) {+ await mkdir(dirname(outputFile!), { recursive: true });+ await writeFile(outputFile!, html, "utf8");+ }+ return {+ document: checked.document,+ narrative: checked.narrative,+ plan: checked.plan,+ located,+ html,+ target: materializedDocument,+ ...(outputFile ? { outputFile } : {}),+ projections: results,+ lock: checked.lock,+ lockVerified: args.lockFile !== undefined,+ artifactsVerified: artifacts.verified,+ ...(artifacts.manifestHash+ ? { artifactManifestHash: artifacts.manifestHash }+ : {}),+ reproducible:+ args.lockFile !== undefined+ && checked.lock.reproducible+ && artifacts.verified,+ };+}diff --git a/src/diagnostics.ts b/src/diagnostics.tsnew file mode 100644index 00000000..e7f3fc51--- /dev/null+++ b/src/diagnostics.ts@@ -0,0 +1,48 @@+export type DiagnosticSeverity = "error" | "warning" | "info";++export type SourceLocation = {+ file: string;+ offset: number;+ line: number;+ column: number;+};++export type Diagnostic = {+ code: string;+ severity: DiagnosticSeverity;+ message: string;+ location?: SourceLocation;+ notes?: string[];+};++export class SvmlError extends Error {+ readonly diagnostics: Diagnostic[];++ constructor(diagnostics: Diagnostic | Diagnostic[]) {+ const list = Array.isArray(diagnostics) ? diagnostics : [diagnostics];+ super(list.map((item) => `${item.code}: ${item.message}`).join("\n"));+ this.name = "SvmlError";+ this.diagnostics = list;+ }+}++export function fail(code: string, message: string, location?: SourceLocation): never {+ throw new SvmlError({+ code,+ severity: "error",+ message,+ ...(location ? { location } : {}),+ });+}++export function sourceLocation(file: string, source: string, offset: number): SourceLocation {+ const bounded = Math.max(0, Math.min(source.length, offset));+ const before = source.slice(0, bounded);+ const lines = before.split("\n");+ return {+ file,+ offset: bounded,+ line: lines.length,+ column: (lines.at(-1)?.length ?? 0) + 1,+ };+}diff --git a/src/digests.ts b/src/digests.tsnew file mode 100644index 00000000..dd31e506--- /dev/null+++ b/src/digests.ts@@ -0,0 +1,118 @@+import { readFile } from "node:fs/promises";+import { dirname, isAbsolute, resolve } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import type {+ AttributeValue,+ PlanIR,+ SourceNode,+} from "./model.js";+import type { KernelRegistry } from "./kernel.js";+import { topologicalInstances } from "./plan.js";+import { sha256, stableJson } from "./util.js";++function externalUri(value: string): boolean {+ return /^[A-Za-z][A-Za-z0-9+.-]*:/u.test(value);+}++function materialUri(module: string, source: string): string {+ if (source.startsWith("file:")) return source;+ if (externalUri(source)) return source;+ return pathToFileURL(isAbsolute(source) ? source : resolve(dirname(module), source)).href;+}++async function materialDigest(+ module: string,+ source: string,+): Promise<{ digest: string; status: "content" | "unresolved-source" }> {+ const uri = materialUri(module, source);+ if (!uri.startsWith("file:")) {+ return {+ digest: sha256(`unresolved\0${uri}`),+ status: "unresolved-source",+ };+ }+ try {+ return {+ digest: sha256(await readFile(fileURLToPath(uri))),+ status: "content",+ };+ } catch {+ return {+ digest: sha256(`unresolved\0${uri}`),+ status: "unresolved-source",+ };+ }+}++function canonicalNodes(+ nodes: SourceNode[],+ canonicalValue: (value: AttributeValue) => unknown,+): unknown[] {+ return nodes.map((node) => node.kind === "text"+ ? { kind: "text", value: node.value }+ : {+ kind: "element",+ name: node.name,+ attributes: Object.fromEntries(Object.entries(node.attributes)+ .filter(([name]) => name !== "class")+ .map(([name, value]) => [name, canonicalValue(value)])),+ children: canonicalNodes(node.children, canonicalValue),+ });+}++export async function attachExecutionDigests(+ plan: PlanIR,+ kernels: KernelRegistry,+ dependencyDigestOverrides: ReadonlyMap<string, string> = new Map(),+): Promise<void> {+ for (const value of plan.values) {+ if (value.type === "Text") {+ value.contentDigest = sha256(value.value ?? "");+ value.digestStatus = "content";+ continue;+ }+ const material = await materialDigest(value.module, value.source ?? "");+ value.contentDigest = material.digest;+ value.digestStatus = material.status;+ }++ const values = new Map(plan.values.map((value) => [value.id, value]));+ const instances = new Map(plan.instances.map((instance) => [instance.id, instance]));+ const declarationIds = [...values.keys(), ...instances.keys()]+ .sort((left, right) => right.length - left.length);+ for (const instance of topologicalInstances(plan)) {+ const manifest = kernels.get(instance.kernel);+ if (!manifest) continue;+ const canonicalValue = (value: AttributeValue): unknown => {+ if (!value || typeof value !== "object" || value.kind !== "reference") return value;+ if (value.path.startsWith("script.")) return { script: value.path };+ const owner = declarationIds.find(+ (id) => value.path === id || value.path.startsWith(`${id}.`),+ );+ if (!owner) return { unresolved: value.path };+ const dependency = values.get(owner) ?? instances.get(owner);+ const identity = dependency?.identity ?? owner;+ const tail = value.path === owner ? "" : value.path.slice(owner.length + 1);+ return { identity, tail };+ };+ const dependencyDigests = instance.dependencies.map((id) => {+ const dependency = values.get(id) ?? instances.get(id);+ return {+ identity: dependency?.identity ?? id,+ digest: dependencyDigestOverrides.get(id) ?? ("contentDigest" in (dependency ?? {})+ ? (dependency as { contentDigest?: string }).contentDigest+ : (dependency as { executionDigest?: string } | undefined)?.executionDigest),+ };+ }).sort((left, right) => left.identity.localeCompare(right.identity));+ instance.executionDigest = sha256(stableJson({+ abi: manifest.abiVersion,+ manifest: manifest.sourceHash,+ implementation: manifest.implementationHash,+ attributes: Object.fromEntries(Object.entries(instance.attributes)+ .filter(([name]) => !["id", "class"].includes(name))+ .map(([name, value]) => [name, canonicalValue(value)])),+ children: canonicalNodes(instance.children, canonicalValue),+ dependencies: dependencyDigests,+ }));+ }+}diff --git a/src/format.ts b/src/format.tsnew file mode 100644index 00000000..7fec0a8e--- /dev/null+++ b/src/format.ts@@ -0,0 +1,137 @@+import { fail } from "./diagnostics.js";+import type { NarrativeIR, SourceDocument } from "./model.js";+import { parseScript } from "./script/parse.js";+import { parseDocumentSource } from "./source/parse-document.js";+import { stableJson } from "./util.js";++function semanticNarrative(narrative: NarrativeIR): unknown {+ return {+ segments: narrative.segments.map((segment) => ({+ id: segment.id,+ tokenStart: segment.tokenStart,+ tokenEnd: segment.tokenEnd,+ atoms: segment.atoms.map((atom) => atom.kind === "role"+ ? { kind: "role", label: atom.label }+ : {+ kind: "text",+ speech: atom.speech.replace(/\s+/gu, " ").trim(),+ caption: atom.caption.replace(/\s+/gu, " ").trim(),+ }),+ })),+ tokens: narrative.tokens.map((token) => ({+ segmentId: token.segmentId,+ text: token.text,+ normalized: token.normalized,+ })),+ selections: Object.fromEntries(Object.entries(narrative.selections).map(([id, occurrences]) => [+ id,+ occurrences.map((occurrence) => ({+ occurrence: occurrence.occurrence,+ open: {+ affinity: occurrence.open.affinity,+ boundary: occurrence.open.boundary,+ },+ close: {+ affinity: occurrence.close.affinity,+ boundary: occurrence.close.boundary,+ },+ })),+ ])),+ moments: Object.fromEntries(Object.entries(narrative.moments).map(([id, occurrences]) => [+ id,+ occurrences.map((occurrence) => ({+ occurrence: occurrence.occurrence,+ affinity: occurrence.affinity,+ boundary: occurrence.boundary,+ })),+ ])),+ captionAtoms: narrative.captionAtoms.map((atom) => ({+ display: atom.display,+ segmentId: atom.segmentId,+ startWord: atom.startWord,+ endWordExclusive: atom.endWordExclusive,+ })),+ projections: narrative.projections,+ };+}++function formatScriptBody(source: string): string {+ const output: string[] = [];+ let insideSegment = false;+ let continuationIndent = 6;+ const pushBlank = (): void => {+ if (output.length && output.at(-1) !== "") output.push("");+ };+ for (const raw of source.replace(/\r\n?/gu, "\n").normalize("NFC").split("\n")) {+ const line = raw.trim();+ if (!line) continue;+ const opens = /^<segment\b[^>]*>$/u.test(line);+ const selfClosing = /^<segment\b[^>]*\/>$/u.test(line);+ const closes = /^<\/segment\s*>$/u.test(line);+ if (+ (!opens && line.includes("<segment"))+ || (!closes && line.includes("</segment"))+ ) {+ fail(+ "format_script_structural_line",+ "Canonical formatting requires Segment tags to be separate from spoken content.",+ );+ }+ if (opens) {+ if (insideSegment) fail("format_script_nested_segment", "Segment elements cannot nest.");+ pushBlank();+ output.push(` ${line}`);+ insideSegment = !selfClosing;+ continuationIndent = 6;+ if (selfClosing) pushBlank();+ continue;+ }+ if (closes) {+ if (!insideSegment) {+ fail("format_script_close_without_open", "Unexpected </segment> while formatting.");+ }+ output.push(` ${line}`);+ insideSegment = false;+ continuationIndent = 6;+ pushBlank();+ continue;+ }+ if (insideSegment) {+ const role = /^(<[\p{L}\p{M}\p{N}_. -]+>)\s+/u.exec(line);+ if (role) continuationIndent = 6 + role[0].length;+ output.push(`${" ".repeat(role ? 6 : continuationIndent)}${line}`);+ } else {+ output.push(` ${line}`);+ }+ }+ if (insideSegment) fail("format_script_unclosed_segment", "Unclosed Segment while formatting.");+ while (output.at(-1) === "") output.pop();+ return `\n${output.join("\n")}\n `;+}++export function formatDocumentScript(+ document: SourceDocument,+ narrative: NarrativeIR,+ bindings: Record<string, string>,+): string {+ const body = formatScriptBody(document.scriptSource);+ const formatted = [+ document.source.slice(0, document.scriptOffset),+ body,+ document.source.slice(document.scriptOffset + document.scriptSource.length),+ ].join("");+ const reparsedDocument = parseDocumentSource(document.file, formatted);+ const reparsedNarrative = parseScript(+ document.file,+ reparsedDocument.scriptSource,+ reparsedDocument.scriptOffset,+ bindings,+ );+ if (stableJson(semanticNarrative(narrative)) !== stableJson(semanticNarrative(reparsedNarrative))) {+ fail(+ "format_semantic_change",+ "Formatter refused output because Script semantic IR changed.",+ );+ }+ return formatted;+}diff --git a/src/hyperframes.ts b/src/hyperframes.tsnew file mode 100644index 00000000..fdd2d8b7--- /dev/null+++ b/src/hyperframes.ts@@ -0,0 +1,134 @@+import type { AudioFragment, VisualFragment } from "./runtime-contract.js";+import { escapeHtml } from "./util.js";++const TIME_PRECISION = 1_000_000_000;++/**+ * HyperFrames consumes seconds while SVML's Located IR is frame-exact.+ * Flooring, instead of emitting a raw repeating float, keeps the authored+ * interval half-open at frame boundaries:+ *+ * startFrame <= frame < endFrameExclusive+ *+ * A raw value such as 32 / 30 can otherwise compare a few ulps above or below+ * the browser's frame clock and leak one extra rendered frame.+ */+export function frameSeconds(frame: number, fps: number): string {+ const value = Math.floor((frame / fps) * TIME_PRECISION) / TIME_PRECISION;+ return String(value);+}++function cssStyle(style: Record<string, string | number> | undefined): string {+ if (!style) return "";+ return Object.entries(style)+ .map(([name, value]) => `${name}:${String(value)}`)+ .join(";");+}++function attributes(values: Record<string, string> | undefined): string {+ if (!values) return "";+ return Object.entries(values)+ .map(([name, value]) => ` ${name}="${escapeHtml(value)}"`)+ .join("");+}++function visualHtml(fragment: VisualFragment, fps: number, trackIndex: number): string {+ const start = frameSeconds(fragment.startFrame, fps);+ const duration = frameSeconds(fragment.endFrameExclusive - fragment.startFrame, fps);+ const common = [+ `id="${escapeHtml(fragment.id)}"`,+ 'class="clip svml-fragment"',+ `data-start="${start}"`,+ `data-duration="${duration}"`,+ `data-track-index="${trackIndex}"`,+ `style="${escapeHtml(cssStyle({+ position: "absolute",+ "z-index": fragment.z,+ ...fragment.style,+ }))}"`,+ ].join(" ");+ if (fragment.kind === "html") {+ return `<div ${common}${attributes(fragment.attributes)}>${fragment.html ?? ""}</div>`;+ }+ if (fragment.kind === "image" && fragment.innerStyle) {+ const nestedSource = `${fragment.source ?? ""}#svml-${encodeURIComponent(fragment.id)}`;+ return `<div ${common}${attributes(fragment.attributes)}><img src="${escapeHtml(nestedSource)}" style="${escapeHtml(cssStyle(fragment.innerStyle))}"/></div>`;+ }+ const media = [+ fragment.mediaStartSec !== undefined ? `data-media-start="${fragment.mediaStartSec}"` : "",+ fragment.playbackRate !== undefined ? `data-playback-rate="${fragment.playbackRate}"` : "",+ fragment.kind === "video" && fragment.muted !== false ? "muted" : "",+ fragment.kind === "video" ? "playsinline" : "",+ fragment.kind === "video" && fragment.loop ? "loop" : "",+ ].filter(Boolean).join(" ");+ return `<${fragment.kind} ${common} ${media} src="${escapeHtml(fragment.source ?? "")}"${attributes(fragment.attributes)}></${fragment.kind}>`;+}++function audioHtml(fragment: AudioFragment, fps: number, trackIndex: number): string {+ const start = frameSeconds(fragment.startFrame, fps);+ const duration = frameSeconds(fragment.endFrameExclusive - fragment.startFrame, fps);+ const volume = fragment.volume ?? 1;+ return [+ `<audio id="${escapeHtml(fragment.id)}"`,+ `data-start="${start}"`,+ `data-duration="${duration}"`,+ `data-track-index="${trackIndex}"`,+ `data-volume="${volume}"`,+ fragment.bus ? `data-bus="${fragment.bus}"` : "",+ fragment.fadeInSec ? `data-fade-in="${fragment.fadeInSec}"` : "",+ fragment.fadeOutSec ? `data-fade-out="${fragment.fadeOutSec}"` : "",+ fragment.mediaStartSec !== undefined ? `data-media-start="${fragment.mediaStartSec}"` : "",+ fragment.playbackRate !== undefined ? `data-playback-rate="${fragment.playbackRate}"` : "",+ `src="${escapeHtml(fragment.source)}"></audio>`,+ ].filter(Boolean).join(" ");+}++export function emitHyperframesHtml(args: {+ id: string;+ width: number;+ height: number;+ fps: number;+ durationFrames: number;+ background: string;+ visuals: VisualFragment[];+ audios: AudioFragment[];+ styles?: string[];+}): string {+ const orderedVisuals = [...args.visuals].sort((left, right) =>+ left.z - right.z+ || (left.layer ?? 0) - (right.layer ?? 0)+ || left.startFrame - right.startFrame+ || left.id.localeCompare(right.id));+ const visuals = orderedVisuals.map((fragment, index) =>+ visualHtml(fragment, args.fps, index));+ const audios = args.audios.map((fragment, index) =>+ audioHtml(fragment, args.fps, orderedVisuals.length + index));+ const duration = frameSeconds(args.durationFrames, args.fps);+ return `<!doctype html>+<html>+<head>+ <meta charset="utf-8"/>+ <meta name="viewport" content="width=device-width,initial-scale=1"/>+ <style>+ html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: ${args.background}; }+ [data-composition-id] { position: relative; overflow: hidden; background: ${args.background}; }+ .svml-fragment { box-sizing: border-box; }+ ${args.styles?.join("\n") ?? ""}+ ${orderedVisuals.map((item) => item.css ?? "").filter(Boolean).join("\n")}+ </style>+</head>+<body>+ <div data-composition-id="${escapeHtml(args.id)}"+ data-start="0"+ data-no-timeline+ data-width="${args.width}"+ data-height="${args.height}"+ data-duration="${duration}"+ data-fps="${args.fps}">+ ${visuals.join("\n ")}+ ${audios.join("\n ")}+ </div>+</body>+</html>+`;+}diff --git a/src/kernel.ts b/src/kernel.tsnew file mode 100644index 00000000..7f34a0ec--- /dev/null+++ b/src/kernel.ts@@ -0,0 +1,333 @@+import { readFile } from "node:fs/promises";+import { dirname, resolve } from "node:path";+import { pathToFileURL } from "node:url";+import { fail } from "./diagnostics.js";+import type { AttributeValue, SourceDocument, SourceElement } from "./model.js";+import { attributeString, childElements } from "./source/query.js";+import { parseRootSource } from "./source/parse-document.js";+import { sha256 } from "./util.js";++export type KernelPort = {+ name: string;+ direction: "input" | "output";+ type: string;+ cardinality: string;+ consume?: "one" | "each" | "set";+};++export type KernelParameter = {+ name: string;+ styleName: string;+ type: "string" | "number" | "boolean";+ defaultValue?: AttributeValue;+};++export type KernelField = {+ name: string;+ styleName: string;+ type: string;+ required: boolean;+ consume?: "one" | "each" | "set";+};++export type KernelChildSchema = {+ name: string;+ cardinality: string;+ text: boolean;+ fields: KernelField[];+ children: KernelChildSchema[];+};++export type KernelManifest = {+ name: string;+ abiVersion: string;+ root: boolean;+ sourcePath: string;+ sourceHash: string;+ implementationPath?: string;+ implementationHash: string;+ profile: "isolated-projector-v1" | "capability-v1";+ capability?: string;+ permissions: string[];+ ports: KernelPort[];+ parameters: KernelParameter[];+ children: KernelChildSchema[];+};++export type KernelRegistry = Map<string, KernelManifest>;++export function kernelTemporalContracts(+ manifest: KernelManifest,+): Record<string, {+ kind: "selection" | "moment";+ consume: "one" | "each" | "set";+}> {+ const output: Record<string, {+ kind: "selection" | "moment";+ consume: "one" | "each" | "set";+ }> = {};+ const add = (+ path: string,+ type: string,+ consume: "one" | "each" | "set" | undefined,+ ): void => {+ const kind = type.split("|").includes("SelectionSet")+ ? "selection"+ : type.split("|").includes("MomentSet")+ ? "moment"+ : undefined;+ if (!kind || !consume) return;+ const existing = output[path];+ if (existing && (existing.kind !== kind || existing.consume !== consume)) {+ fail(+ "kernel_temporal_contract_ambiguous",+ `Kernel "${manifest.name}" has conflicting temporal contract "${path}".`,+ );+ }+ output[path] = { kind, consume };+ };+ for (const port of manifest.ports) add(port.name, port.type, port.consume);+ const visit = (schemas: KernelChildSchema[]): void => {+ for (const schema of schemas) {+ for (const field of schema.fields) {+ add(`${schema.name}.${field.name}`, field.type, field.consume);+ }+ visit(schema.children);+ }+ };+ visit(manifest.children);+ return output;+}++function stringAttribute(+ element: SourceElement,+ name: string,+ fallback?: string,+): string | undefined {+ const value = element.attributes[name];+ if (typeof value === "string") return value;+ if (value === undefined) return fallback;+ fail("kernel_manifest_attribute", `<${element.name}> attribute "${name}" must be a string.`);+}++function booleanAttribute(+ element: SourceElement,+ name: string,+ fallback: boolean,+): boolean {+ const value = element.attributes[name];+ if (typeof value === "boolean") return value;+ if (value === undefined) return fallback;+ fail("kernel_manifest_attribute", `<${element.name}> attribute "${name}" must be boolean.`);+}++function parseParameter(sourcePath: string, element: SourceElement): KernelParameter {+ const name = stringAttribute(element, "name");+ const type = stringAttribute(element, "type");+ if (!name || !type || !["string", "number", "boolean"].includes(type)) {+ fail("kernel_manifest_parameter", `${sourcePath} contains an invalid <param>.`);+ }+ let defaultValue = element.attributes.default;+ if (defaultValue !== undefined) {+ if (type === "number" && (typeof defaultValue !== "number" || !Number.isFinite(defaultValue))) {+ fail(+ "kernel_manifest_parameter_default",+ `${sourcePath} parameter ${name} has a non-numeric default.`,+ );+ }+ if (type === "boolean" && typeof defaultValue !== "boolean") {+ fail(+ "kernel_manifest_parameter_default",+ `${sourcePath} parameter ${name} has a non-boolean default.`,+ );+ }+ if (type === "string" && typeof defaultValue !== "string") {+ defaultValue = String(defaultValue);+ }+ }+ return {+ name,+ styleName: stringAttribute(element, "style", name) ?? name,+ type: type as KernelParameter["type"],+ ...(defaultValue !== undefined ? { defaultValue } : {}),+ };+}++function parseField(sourcePath: string, element: SourceElement): KernelField {+ const name = stringAttribute(element, "name");+ const type = stringAttribute(element, "type");+ if (!name || !type) {+ fail("kernel_manifest_field", `${sourcePath} contains an incomplete <field>.`);+ }+ const consume = stringAttribute(element, "consume");+ if (consume && !["one", "each", "set"].includes(consume)) {+ fail("kernel_manifest_temporal_consume", `${sourcePath} field ${name} has invalid consume.`);+ }+ if (+ type.split("|").some((candidate) => ["SelectionSet", "MomentSet"].includes(candidate))+ && !consume+ ) {+ fail(+ "kernel_manifest_temporal_consume",+ `${sourcePath} temporal field ${name} must declare consume="one|each|set".`,+ );+ }+ return {+ name,+ styleName: stringAttribute(element, "style", name) ?? name,+ type,+ required: booleanAttribute(element, "required", false),+ ...(consume ? { consume: consume as "one" | "each" | "set" } : {}),+ };+}++function parseChild(sourcePath: string, element: SourceElement): KernelChildSchema {+ const name = stringAttribute(element, "name");+ if (!name) fail("kernel_manifest_child", `${sourcePath} contains a child without a name.`);+ const fields = childElements(element, "field").map((field) => parseField(sourcePath, field));+ if (new Set(fields.map((field) => field.name)).size !== fields.length) {+ fail("kernel_manifest_field_duplicate", `${sourcePath} repeats a field on child ${name}.`);+ }+ const children = childElements(element, "child").map((child) => parseChild(sourcePath, child));+ if (new Set(children.map((child) => child.name)).size !== children.length) {+ fail("kernel_manifest_child_duplicate", `${sourcePath} repeats child schema ${name}.`);+ }+ return {+ name,+ cardinality: stringAttribute(element, "cardinality", "zero-or-more") ?? "zero-or-more",+ text: booleanAttribute(element, "text", false),+ fields,+ children,+ };+}++function parseManifest(sourcePath: string, source: string): KernelManifest {+ const root = parseRootSource(sourcePath, source);+ if (root.name !== "kernel") {+ fail("kernel_manifest_root", `${sourcePath} must contain one <kernel> root.`);+ }+ const name = stringAttribute(root, "name");+ const implementation = stringAttribute(root, "implementation");+ const profile = stringAttribute(root, "profile", "isolated-projector-v1");+ if (!name || !/^[A-Za-z_][A-Za-z0-9_.:-]*$/u.test(name)) {+ fail("kernel_manifest_name", `${sourcePath} has an invalid or missing Kernel name.`);+ }+ if (profile !== "isolated-projector-v1" && profile !== "capability-v1") {+ fail("kernel_manifest_profile", `${sourcePath} has unsupported profile "${profile ?? ""}".`);+ }+ if (profile === "isolated-projector-v1" && !implementation) {+ fail("kernel_manifest_implementation", `${sourcePath} must declare implementation.`);+ }+ const capability = stringAttribute(root, "capability");+ if (profile === "capability-v1" && !capability) {+ fail("kernel_manifest_capability", `${sourcePath} capability Kernel requires capability.`);+ }+ const ports: KernelPort[] = childElements(root, "port").map((port) => {+ const portName = stringAttribute(port, "name");+ const direction = stringAttribute(port, "direction");+ const type = stringAttribute(port, "type");+ if (!portName || !direction || !type) {+ fail("kernel_manifest_port", `${sourcePath} contains an incomplete <port>.`);+ }+ if (direction !== "input" && direction !== "output") {+ fail("kernel_manifest_port_direction", `${sourcePath} port ${portName} has invalid direction.`);+ }+ const consume = stringAttribute(port, "consume");+ if (consume && !["one", "each", "set"].includes(consume)) {+ fail("kernel_manifest_temporal_consume", `${sourcePath} port ${portName} has invalid consume.`);+ }+ if (+ type.split("|").some((candidate) => ["SelectionSet", "MomentSet"].includes(candidate))+ && !consume+ ) {+ fail(+ "kernel_manifest_temporal_consume",+ `${sourcePath} temporal port ${portName} must declare consume="one|each|set".`,+ );+ }+ return {+ name: portName,+ direction,+ type,+ cardinality: stringAttribute(port, "cardinality", "one") ?? "one",+ ...(consume ? { consume: consume as "one" | "each" | "set" } : {}),+ };+ });+ const parameters = childElements(root, "param").map((parameter) =>+ parseParameter(sourcePath, parameter));+ if (new Set(parameters.map((parameter) => parameter.name)).size !== parameters.length) {+ fail("kernel_manifest_parameter_duplicate", `${sourcePath} repeats a parameter name.`);+ }+ const children = childElements(root, "child").map((child) => parseChild(sourcePath, child));+ if (new Set(children.map((child) => child.name)).size !== children.length) {+ fail("kernel_manifest_child_duplicate", `${sourcePath} repeats a root child schema.`);+ }+ const known = new Set(["port", "param", "child"]);+ const unknown = childElements(root).find((element) => !known.has(element.name));+ if (unknown) {+ fail("kernel_manifest_element", `${sourcePath} contains unknown <${unknown.name}>.`);+ }+ return {+ name,+ abiVersion: String(root.attributes.abi ?? "1"),+ root: booleanAttribute(root, "root", false),+ sourcePath,+ sourceHash: sha256(source),+ ...(implementation ? { implementationPath: resolve(dirname(sourcePath), implementation) } : {}),+ implementationHash: "",+ profile,+ ...(capability ? { capability } : {}),+ permissions: (stringAttribute(root, "permissions", "") ?? "")+ .split(/[\s,]+/u)+ .filter(Boolean),+ ports,+ parameters,+ children,+ };+}++export async function loadKernels(document: SourceDocument): Promise<KernelRegistry> {+ const registry: KernelRegistry = new Map();+ const imports = childElements(document.root, "import");+ for (const element of imports) {+ const from = attributeString(element, "from");+ if (!from.endsWith(".svk")) continue;+ const sourcePath = resolve(dirname(document.file), from);+ const manifest = parseManifest(sourcePath, await readFile(sourcePath, "utf8"));+ manifest.implementationHash = manifest.implementationPath+ ? sha256(await readFile(manifest.implementationPath))+ : sha256(`capability\0${manifest.capability ?? manifest.name}`);+ if (registry.has(manifest.name)) {+ fail(+ "kernel_duplicate_binding",+ `Kernel "${manifest.name}" is imported more than once; use explicit aliases once namespace syntax is enabled.`,+ );+ }+ registry.set(manifest.name, manifest);+ }+ return registry;+}++export async function loadKernelImplementation<T>(+ manifest: KernelManifest,+): Promise<T> {+ if (!manifest.implementationPath) {+ fail(+ "kernel_implementation_profile",+ `Kernel "${manifest.name}" has no projector implementation.`,+ );+ }+ const moduleUrl = `${pathToFileURL(manifest.implementationPath).href}?kernel=${manifest.sourceHash}-${manifest.implementationHash}`;+ const loaded = await import(moduleUrl) as { default?: T };+ if (!loaded.default) {+ fail(+ "kernel_implementation_default",+ `${manifest.implementationPath} must export a default Kernel implementation.`,+ );+ }+ return loaded.default;+}++export function kernelElement(document: SourceDocument, id: string): SourceElement | undefined {+ return childElements(document.root).find((element) => element.attributes.id === id);+}diff --git a/src/lock.ts b/src/lock.tsnew file mode 100644index 00000000..d2d04450--- /dev/null+++ b/src/lock.ts@@ -0,0 +1,137 @@+import { readFile } from "node:fs/promises";+import { dirname, isAbsolute, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { fail } from "./diagnostics.js";+import type { KernelManifest } from "./kernel.js";+import type { PlanIR, SourceDocument } from "./model.js";+import { portableFileIdentity, stableJson } from "./util.js";++export type SvmlLock = {+ contract: "svml.lock.v1";+ compiler: {+ package: "@svml/compiler";+ version: "0.0.1";+ };+ language: {+ document: "1";+ scriptSurface: "1";+ plan: "svml.plan.v1";+ };+ target: {+ name: "hyperframes";+ version: "0.7.84";+ };+ reproducible: boolean;+ modules: NonNullable<SourceDocument["modules"]>;+ materials: Array<{+ identity: string;+ type: string;+ uri?: string;+ contentDigest: string;+ status: "content" | "unresolved-source";+ }>;+ kernels: Array<{+ name: string;+ abi: string;+ manifestUri: string;+ manifestHash: string;+ implementationUri?: string;+ implementationHash: string;+ capability?: string;+ permissions: string[];+ profile: string;+ }>;+};++export function createLock(+ document: SourceDocument,+ manifests: KernelManifest[],+ plan: PlanIR,+): SvmlLock {+ const lockUri = (uri: string): string =>+ uri.startsWith("file:")+ ? portableFileIdentity(document.file, fileURLToPath(uri))+ : uri;+ const materials = plan.values.map((value) => {+ const source = value.source;+ const absolute = source+ ? /^[A-Za-z][A-Za-z0-9+.-]*:/u.test(source)+ ? source+ : isAbsolute(source) ? source : resolve(dirname(value.module), source)+ : undefined;+ const uri = absolute+ ? absolute.startsWith("file:")+ ? lockUri(absolute)+ : /^[A-Za-z][A-Za-z0-9+.-]*:/u.test(absolute)+ ? absolute+ : portableFileIdentity(document.file, absolute)+ : undefined;+ return {+ identity: value.identity,+ type: value.type,+ ...(uri ? { uri } : {}),+ contentDigest: value.contentDigest ?? "",+ status: value.digestStatus ?? "unresolved-source",+ };+ }).sort((left, right) => left.identity.localeCompare(right.identity));+ return {+ contract: "svml.lock.v1",+ compiler: {+ package: "@svml/compiler",+ version: "0.0.1",+ },+ language: {+ document: "1",+ scriptSurface: "1",+ plan: "svml.plan.v1",+ },+ target: {+ name: "hyperframes",+ version: "0.7.84",+ },+ reproducible: materials.every((material) => material.status === "content"),+ modules: (document.modules ?? []).map((module) => ({+ ...module,+ uri: lockUri(module.uri),+ dependencies: module.dependencies.map(lockUri),+ })).sort((left, right) => left.uri.localeCompare(right.uri)),+ materials,+ kernels: manifests.map((manifest) => ({+ name: manifest.name,+ abi: manifest.abiVersion,+ manifestUri: portableFileIdentity(document.file, manifest.sourcePath),+ manifestHash: manifest.sourceHash,+ ...(manifest.implementationPath+ ? { implementationUri: portableFileIdentity(document.file, manifest.implementationPath) }+ : {}),+ implementationHash: manifest.implementationHash,+ ...(manifest.capability ? { capability: manifest.capability } : {}),+ permissions: manifest.permissions,+ profile: manifest.profile,+ })).sort((left, right) => left.name.localeCompare(right.name)),+ };+}++export async function verifyLockFile(+ file: string,+ expected: SvmlLock,+): Promise<void> {+ let actual: unknown;+ try {+ actual = JSON.parse(await readFile(file, "utf8"));+ } catch (error) {+ fail(+ "lock_read",+ `Could not read SVML lock ${file}: ${error instanceof Error ? error.message : String(error)}.`,+ );+ }+ if (!actual || typeof actual !== "object" || (actual as { contract?: string }).contract !== "svml.lock.v1") {+ fail("lock_contract", `${file} is not an svml.lock.v1 document.`);+ }+ if (stableJson(actual) !== stableJson(expected)) {+ fail(+ "lock_mismatch",+ `${file} does not match the resolved source closure; regenerate it with "svml lock".`,+ );+ }+}diff --git a/src/model.ts b/src/model.tsnew file mode 100644index 00000000..1e783e22--- /dev/null+++ b/src/model.ts@@ -0,0 +1,273 @@+export type Literal = string | number | boolean;++export type Reference = {+ kind: "reference";+ path: string;+};++export type AttributeValue = Literal | Reference;++export type ParameterSource = {+ kind: "kernel-default" | "svs-class" | "instance";+ source: string;+ value: AttributeValue;+};++export type SourceElement = {+ kind: "element";+ name: string;+ attributes: Record<string, AttributeValue>;+ children: SourceNode[];+ start: number;+ end: number;+ origin?: {+ file: string;+ localId?: string;+ };+ parameterSources?: Record<string, ParameterSource[]>;+};++export type SourceText = {+ kind: "text";+ value: string;+ start: number;+ end: number;+};++export type SourceNode = SourceElement | SourceText;++export type SourceModuleRecord = {+ kind: "svml" | "svc" | "svs";+ uri: string;+ contentHash: string;+ dependencies: string[];+};++export type SourceDocument = {+ file: string;+ source: string;+ root: SourceElement;+ scriptSource: string;+ scriptOffset: number;+ modules?: SourceModuleRecord[];+};++export type ScriptAtom =+ | { kind: "text"; speech: string; caption: string; start: number; end: number }+ | { kind: "role"; label: string; start: number; end: number };++export type ScriptToken = {+ id: string;+ index: number;+ segmentId: string;+ text: string;+ normalized: string;+ sourceStart: number;+ sourceEnd: number;+};++export type MarkerBoundary = {+ tokenIndex: number;+ segmentId?: string;+ structuralCut?: number;+};++export type SelectionOccurrence = {+ id: string;+ occurrence: number;+ open: {+ affinity: "left" | "right";+ boundary: MarkerBoundary;+ sourceStart: number;+ };+ close: {+ affinity: "left" | "right";+ boundary: MarkerBoundary;+ sourceStart: number;+ };+};++export type MomentOccurrence = {+ id: string;+ occurrence: number;+ affinity: "left" | "right";+ boundary: MarkerBoundary;+ sourceStart: number;+};++export type ScriptSegment = {+ id: string;+ index: number;+ atoms: ScriptAtom[];+ tokenStart: number;+ tokenEnd: number;+ sourceStart: number;+ sourceEnd: number;+};++export type CaptionAtom = {+ id: string;+ display: string;+ segmentId: string;+ startWord: number;+ endWordExclusive: number;+ sourceStart: number;+ sourceEnd: number;+};++export type NarrativeIR = {+ segments: ScriptSegment[];+ tokens: ScriptToken[];+ selections: Record<string, SelectionOccurrence[]>;+ moments: Record<string, MomentOccurrence[]>;+ captionAtoms: CaptionAtom[];+ projections: {+ dialogue: string;+ speech: string;+ caption: string;+ };+};++export type AlignmentWord = {+ text: string;+ startSec: number;+ endSec: number;+ segmentId: string;+};++export type AlignmentSegment = {+ id: string;+ startSec: number;+ endSec: number;+};++export type AlignmentCaptionCue = {+ id?: string;+ startWord: number;+ endWordExclusive: number;+};++export type AlignmentEvidence = {+ contract: "svml.speech-alignment.v1";+ durationSec: number;+ fps: number;+ words: AlignmentWord[];+ segments: AlignmentSegment[];+ captionCues?: AlignmentCaptionCue[];+ provenance?: Record<string, unknown>;+};++export type ProgramRange = {+ startFrame: number;+ endFrameExclusive: number;+ startSec: number;+ endSec: number;+};++export type LocatedSelection = {+ id: string;+ ranges: ProgramRange[];+};++export type LocatedMoment = {+ id: string;+ frames: number[];+};++export type LocatedCaptionCue = ProgramRange & {+ id: string;+ startWord: number;+ endWordExclusive: number;+};++export type LocatedCaptionAtom = CaptionAtom & ProgramRange;++export type LocatedScript = {+ durationFrames: number;+ durationSec: number;+ fps: number;+ words: Array<ScriptToken & ProgramRange>;+ segments: Record<string, ProgramRange>;+ selections: Record<string, LocatedSelection>;+ moments: Record<string, LocatedMoment>;+ captionAtoms: LocatedCaptionAtom[];+ captionCues?: LocatedCaptionCue[];+};++export type PlanValue = {+ id: string;+ type: "Image" | "Video" | "Audio" | "Text";+ source?: string;+ value?: string;+ identity: string;+ module: string;+ localId: string;+ contentDigest?: string;+ digestStatus?: "content" | "unresolved-source";+};++export type PlanInstance = {+ id: string;+ kernel: string;+ identity: string;+ module: string;+ localId: string;+ attributes: Record<string, AttributeValue>;+ effectiveParameters: Record<string, {+ value: AttributeValue;+ sources: ParameterSource[];+ }>;+ children: SourceNode[];+ dependencies: string[];+ executionDigest?: string;+};++export type PlanIR = {+ contract: "svml.plan.v1";+ source: string;+ values: PlanValue[];+ instances: PlanInstance[];+ kernels: Array<{+ name: string;+ abiVersion: string;+ manifestHash: string;+ implementationHash: string;+ profile: "isolated-projector-v1" | "capability-v1";+ capability?: string;+ ports: Array<{+ name: string;+ direction: "input" | "output";+ type: string;+ cardinality: string;+ consume?: "one" | "each" | "set";+ }>;+ parameters: Array<{+ name: string;+ styleName: string;+ type: "string" | "number" | "boolean";+ defaultValue?: AttributeValue;+ }>;+ children: Array<{+ name: string;+ cardinality: string;+ text: boolean;+ fields: Array<{+ name: string;+ styleName: string;+ type: string;+ required: boolean;+ consume?: "one" | "each" | "set";+ }>;+ children: unknown[];+ }>;+ }>;+ root: string;+ edges: Array<{+ from: string;+ to: string;+ via: string;+ fromPort?: string;+ toPort?: string;+ type?: string;+ }>;+};diff --git a/src/plan.ts b/src/plan.tsnew file mode 100644index 00000000..88819f7e--- /dev/null+++ b/src/plan.ts@@ -0,0 +1,536 @@+import { fail } from "./diagnostics.js";+import type {+ AttributeValue,+ PlanIR,+ PlanInstance,+ PlanValue,+ NarrativeIR,+ Reference,+ SourceDocument,+ SourceElement,+ SourceNode,+} from "./model.js";+import type {+ KernelChildSchema,+ KernelManifest,+ KernelPort,+ KernelRegistry,+} from "./kernel.js";+import { childElements, textContent, walkElements } from "./source/query.js";+import { portableFileIdentity, sha256 } from "./util.js";++const VALUE_TYPES: Record<string, PlanValue["type"]> = {+ image: "Image",+ video: "Video",+ audio: "Audio",+ text: "Text",+};++function idOf(element: SourceElement): string {+ const id = element.attributes.id;+ if (typeof id !== "string" || !/^[A-Za-z_][A-Za-z0-9_.-]*$/u.test(id)) {+ fail("plan_declaration_id", `<${element.name}> requires a stable id.`);+ }+ return id;+}++function referencesIn(nodes: SourceNode[], attributes: SourceElement["attributes"]): Array<{+ path: string;+ via: string;+}> {+ const output: Array<{ path: string; via: string }> = [];+ for (const [name, value] of Object.entries(attributes)) {+ if (value && typeof value === "object" && value.kind === "reference") {+ output.push({ path: value.path, via: name });+ }+ }+ for (const element of walkElements(nodes)) {+ for (const [name, value] of Object.entries(element.attributes)) {+ if (value && typeof value === "object" && value.kind === "reference") {+ output.push({ path: value.path, via: `${element.name}.${name}` });+ }+ }+ }+ return output;+}++function dependencyOf(path: string, declarationIds: Set<string>): string | undefined {+ if (path.startsWith("script.")) return undefined;+ const candidates = [...declarationIds].filter(+ (id) => path === id || path.startsWith(`${id}.`),+ );+ return candidates.sort((left, right) => right.length - left.length)[0];+}++function cardinalityAccepts(cardinality: string, count: number): boolean {+ if (cardinality === "one") return count === 1;+ if (cardinality === "zero-or-one") return count <= 1;+ if (cardinality === "one-or-more") return count >= 1;+ if (cardinality === "zero-or-more") return true;+ fail("kernel_cardinality", `Unknown cardinality "${cardinality}".`);+}++function scalarAccepts(type: string, value: AttributeValue): boolean {+ if (type === "string") return typeof value === "string";+ if (type === "number") return typeof value === "number" && Number.isFinite(value);+ if (type === "boolean") return typeof value === "boolean";+ if (type === "id") {+ return typeof value === "string" && /^[A-Za-z_][A-Za-z0-9_.-]*$/u.test(value);+ }+ if (type === "ProgramSpan" || type === "ProgramPoint") return typeof value === "string";+ return false;+}++function validateTypedValue(+ value: AttributeValue,+ type: string,+ source: string,+): void {+ if (value && typeof value === "object" && value.kind === "reference") return;+ if (type.split("|").some((candidate) => scalarAccepts(candidate, value))) return;+ fail("kernel_field_type", `${source} expects ${type}.`);+}++function validateChild(+ element: SourceElement,+ schema: KernelChildSchema,+ owner: string,+): void {+ const allowed = new Set(["class", ...schema.fields.map((field) => field.name)]);+ for (const [name, value] of Object.entries(element.attributes)) {+ if (!allowed.has(name)) {+ fail(+ "kernel_field_unknown",+ `<${owner}> child <${element.name}> has unknown field "${name}".`,+ );+ }+ const field = schema.fields.find((candidate) => candidate.name === name);+ if (field) validateTypedValue(value, field.type, `<${owner}> <${element.name}>.${name}`);+ }+ for (const field of schema.fields) {+ if (field.required && element.attributes[field.name] === undefined) {+ fail(+ "kernel_field_required",+ `<${owner}> child <${element.name}> requires field "${field.name}".`,+ );+ }+ }+ const children = childElements(element);+ const text = element.children+ .filter((child) => child.kind === "text")+ .map((child) => child.value)+ .join("");+ if (!schema.text && text.trim()) {+ fail("kernel_child_text", `<${owner}> child <${element.name}> does not accept text content.`);+ }+ for (const child of children) {+ const childSchema = schema.children.find((candidate) => candidate.name === child.name);+ if (!childSchema) {+ fail(+ "kernel_child_unknown",+ `<${owner}> child <${element.name}> does not accept <${child.name}>.`,+ );+ }+ validateChild(child, childSchema, owner);+ }+ for (const childSchema of schema.children) {+ const count = children.filter((child) => child.name === childSchema.name).length;+ if (!cardinalityAccepts(childSchema.cardinality, count)) {+ fail(+ "kernel_child_cardinality",+ `<${owner}> <${element.name}> requires ${childSchema.cardinality} <${childSchema.name}> children; received ${count}.`,+ );+ }+ }+}++function validateKernelShape(element: SourceElement, manifest: KernelManifest): void {+ const inputPorts = manifest.ports.filter((port) => port.direction === "input");+ const allowed = new Set([+ "id",+ "class",+ ...manifest.parameters.map((parameter) => parameter.name),+ ...inputPorts.map((port) => port.name),+ ]);+ for (const [name, value] of Object.entries(element.attributes)) {+ if (!allowed.has(name)) {+ fail("kernel_parameter_unknown", `<${manifest.name}> has unknown parameter or port "${name}".`);+ }+ const parameter = manifest.parameters.find((candidate) => candidate.name === name);+ if (parameter) validateTypedValue(value, parameter.type, `<${manifest.name}>.${name}`);+ }+ const children = childElements(element);+ const text = element.children+ .filter((child) => child.kind === "text")+ .map((child) => child.value)+ .join("");+ if (text.trim()) {+ fail("kernel_root_text", `<${manifest.name}> does not accept direct text content.`);+ }+ for (const child of children) {+ const schema = manifest.children.find((candidate) => candidate.name === child.name);+ if (!schema) {+ fail("kernel_child_unknown", `<${manifest.name}> does not accept <${child.name}>.`);+ }+ validateChild(child, schema, manifest.name);+ }+ for (const schema of manifest.children) {+ const count = children.filter((child) => child.name === schema.name).length;+ if (!cardinalityAccepts(schema.cardinality, count)) {+ fail(+ "kernel_child_cardinality",+ `<${manifest.name}> requires ${schema.cardinality} <${schema.name}> children; received ${count}.`,+ );+ }+ }+ for (const port of inputPorts) {+ const count = manifest.children.some((schema) => schema.name === port.name)+ ? children.filter((child) => child.name === port.name).length+ : element.attributes[port.name] === undefined ? 0 : 1;+ if (!cardinalityAccepts(port.cardinality, count)) {+ fail(+ "kernel_port_cardinality",+ `<${manifest.name}> input "${port.name}" requires ${port.cardinality}; received ${count}.`,+ );+ }+ }+}++function outputPortForPath(+ manifest: KernelManifest | undefined,+ tail: string,+): KernelPort | undefined {+ if (!manifest || !tail) return undefined;+ const target = tail.split(".");+ return manifest.ports+ .filter((port) => port.direction === "output")+ .filter((port) => {+ const pattern = port.name.split(".");+ return pattern.length === target.length+ && pattern.every((part, index) => part === "*" || part === target[index]);+ })+ .sort((left, right) => {+ const leftWildcards = left.name.split(".").filter((part) => part === "*").length;+ const rightWildcards = right.name.split(".").filter((part) => part === "*").length;+ return leftWildcards - rightWildcards;+ })[0];+}++function childField(+ schemas: KernelChildSchema[],+ elementName: string,+ fieldName: string,+): KernelChildSchema["fields"][number] | undefined {+ for (const schema of schemas) {+ if (schema.name === elementName) {+ const field = schema.fields.find((candidate) => candidate.name === fieldName);+ if (field) return field;+ }+ const nested = childField(schema.children, elementName, fieldName);+ if (nested) return nested;+ }+ return undefined;+}++function expectedReferenceType(+ manifest: KernelManifest | undefined,+ via: string,+): { name: string; type: string } | undefined {+ if (!manifest) return undefined;+ if (!via.includes(".")) {+ const port = manifest.ports.find(+ (candidate) => candidate.direction === "input" && candidate.name === via,+ );+ return port ? { name: port.name, type: port.type } : undefined;+ }+ const [elementName, fieldName] = via.split(".");+ if (!elementName || !fieldName) return undefined;+ const field = childField(manifest.children, elementName, fieldName);+ return field ? { name: via, type: field.type } : undefined;+}++function compatibleType(actual: string, expected: string): boolean {+ return expected.split("|").includes(actual);+}++export function buildPlan(+ document: SourceDocument,+ kernels: KernelRegistry,+ narrative: NarrativeIR,+): PlanIR {+ const declarations = childElements(document.root).filter(+ (element) => !["import", "script"].includes(element.name),+ );+ const ids = declarations.map(idOf);+ const unique = new Set(ids);+ if (unique.size !== ids.length) fail("plan_duplicate_id", "Declaration ids must be unique.");++ const values: PlanValue[] = [];+ const instances: PlanInstance[] = [];+ for (const element of declarations) {+ const id = idOf(element);+ const module = element.origin?.file ?? document.file;+ const localId = element.origin?.localId ?? id;+ const moduleIdentity = portableFileIdentity(document.file, module);+ const type = VALUE_TYPES[element.name];+ if (type) {+ const src = element.attributes.src;+ const value = element.name === "text" ? textContent(element).trim() : undefined;+ if (element.name !== "text" && typeof src !== "string") {+ fail("plan_value_source", `<${element.name} id="${id}"> requires src.`);+ }+ values.push({+ id,+ type,+ ...(typeof src === "string" ? { source: src } : {}),+ ...(value !== undefined ? { value } : {}),+ identity: sha256(`${moduleIdentity}\0${localId}`),+ module,+ localId,+ });+ continue;+ }+ const manifest = kernels.get(element.name);+ if (!manifest) {+ fail(+ "plan_unknown_kernel",+ `No imported .svk defines <${element.name}>.`,+ );+ }+ validateKernelShape(element, manifest);+ const dependencies = referencesIn(element.children, element.attributes)+ .map((reference) => dependencyOf(reference.path, unique))+ .filter((value): value is string => value !== undefined && value !== id);+ const defaultAttributes = Object.fromEntries(manifest.parameters+ .filter((parameter) => parameter.defaultValue !== undefined)+ .map((parameter) => [parameter.name, parameter.defaultValue!]));+ const attributes = { ...defaultAttributes, ...element.attributes };+ const effectiveParameters = Object.fromEntries(manifest.parameters.flatMap((parameter) => {+ const value = attributes[parameter.name];+ if (value === undefined) return [];+ const sources = [+ ...(parameter.defaultValue !== undefined+ ? [{+ kind: "kernel-default" as const,+ source: manifest.sourcePath,+ value: parameter.defaultValue,+ }]+ : []),+ ...(element.parameterSources?.[parameter.name] ?? (+ element.attributes[parameter.name] !== undefined+ ? [{+ kind: "instance" as const,+ source: module,+ value: element.attributes[parameter.name]!,+ }]+ : []+ )),+ ];+ return [[parameter.name, { value, sources }]];+ }));+ instances.push({+ id,+ kernel: manifest.name,+ identity: sha256(`${moduleIdentity}\0${localId}`),+ module,+ localId,+ attributes,+ effectiveParameters,+ children: element.children,+ dependencies: [...new Set(dependencies)],+ });+ }++ const rootCandidates = instances.filter((instance) => kernels.get(instance.kernel)?.root);+ if (rootCandidates.length !== 1) {+ fail(+ "plan_root_cardinality",+ `Expected exactly one root Kernel instance, received ${rootCandidates.length}.`,+ );+ }+ const root = rootCandidates[0]?.id;+ if (!root) fail("plan_root_missing", "Plan root is missing.");++ const instanceIds = new Set(instances.map((instance) => instance.id));+ const valueIds = new Set(values.map((value) => value.id));+ for (const instance of instances) {+ for (const reference of referencesIn(instance.children, instance.attributes)) {+ const consumerManifest = kernels.get(instance.kernel);+ const expected = expectedReferenceType(consumerManifest, reference.via);+ if (reference.path === "script") {+ if (expected && !compatibleType("NarrativeIR", expected.type)) {+ fail(+ "plan_port_type",+ `Reference "script" produces NarrativeIR, but ${instance.id}.${expected.name} requires ${expected.type}.`,+ );+ }+ continue;+ }+ if (reference.path.startsWith("script.")) {+ const temporal = /^(selection|moment|segment)\.([A-Za-z_][A-Za-z0-9_.-]*)$/u.exec(+ reference.path.slice("script.".length),+ );+ const exists = temporal?.[1] === "selection"+ ? narrative.selections[temporal[2]!] !== undefined+ : temporal?.[1] === "moment"+ ? narrative.moments[temporal[2]!] !== undefined+ : temporal?.[1] === "segment"+ ? narrative.segments.some((segment) => segment.id === temporal[2])+ : false;+ if (!exists) {+ fail(+ "plan_script_reference",+ `Instance "${instance.id}" references unknown Script path "${reference.path}".`,+ );+ }+ const actualType = temporal?.[1] === "selection"+ ? "SelectionSet"+ : temporal?.[1] === "moment"+ ? "MomentSet"+ : "ScriptSegment";+ if (expected && !compatibleType(actualType, expected.type)) {+ fail(+ "plan_port_type",+ `Reference "${reference.path}" produces ${actualType}, but ${instance.id}.${expected.name} requires ${expected.type}.`,+ );+ }+ continue;+ }+ const dependency = dependencyOf(reference.path, unique);+ if (!dependency) {+ fail(+ "plan_reference_unknown",+ `Instance "${instance.id}" references unknown declaration "${reference.path}".`,+ );+ }+ if (valueIds.has(dependency)) {+ if (reference.path !== dependency) {+ fail(+ "plan_value_projection",+ `Value "${dependency}" has no output path "${reference.path.slice(dependency.length + 1)}".`,+ );+ }+ const value = values.find((candidate) => candidate.id === dependency);+ if (value && expected && !compatibleType(value.type, expected.type)) {+ fail(+ "plan_port_type",+ `Reference "${reference.path}" produces ${value.type}, but ${instance.id}.${expected.name} requires ${expected.type}.`,+ );+ }+ continue;+ }+ const producer = instances.find((candidate) => candidate.id === dependency);+ const manifest = producer ? kernels.get(producer.kernel) : undefined;+ const tail = reference.path === dependency+ ? ""+ : reference.path.slice(dependency.length + 1);+ const outputPort = outputPortForPath(manifest, tail);+ if (!outputPort) {+ fail(+ "plan_output_port",+ `Reference "${reference.path}" does not name an output port of "${dependency}".`,+ );+ }+ if (expected && !compatibleType(outputPort.type, expected.type)) {+ fail(+ "plan_port_type",+ `Reference "${reference.path}" produces ${outputPort.type}, but ${instance.id}.${expected.name} requires ${expected.type}.`,+ );+ }+ }+ }++ const edges: PlanIR["edges"] = [];+ for (const instance of instances) {+ for (const reference of referencesIn(instance.children, instance.attributes)) {+ const dependency = dependencyOf(reference.path, unique);+ if (!dependency) continue;+ if (instanceIds.has(dependency) || valueIds.has(dependency)) {+ const producer = instances.find((candidate) => candidate.id === dependency);+ const producerManifest = producer ? kernels.get(producer.kernel) : undefined;+ const tail = producer && reference.path !== dependency+ ? reference.path.slice(dependency.length + 1)+ : undefined;+ const outputPort = tail+ ? outputPortForPath(producerManifest, tail)+ : undefined;+ const value = values.find((candidate) => candidate.id === dependency);+ const consumerManifest = kernels.get(instance.kernel);+ const input = expectedReferenceType(consumerManifest, reference.via);+ edges.push({+ from: dependency,+ to: instance.id,+ via: reference.via,+ ...(outputPort ? { fromPort: outputPort.name } : value ? { fromPort: "value" } : {}),+ ...(input ? { toPort: input.name } : { toPort: reference.via }),+ ...(outputPort?.type+ ? { type: outputPort.type }+ : value+ ? { type: value.type }+ : {}),+ });+ }+ }+ }++ const reachable = new Set<string>();+ const visit = (id: string): void => {+ if (reachable.has(id)) return;+ reachable.add(id);+ const instance = instances.find((item) => item.id === id);+ for (const dependency of instance?.dependencies ?? []) visit(dependency);+ };+ visit(root);+ const reachableInstances = instances.filter((instance) => reachable.has(instance.id));+ const usedKernels = new Set(reachableInstances.map((instance) => instance.kernel));+ return {+ contract: "svml.plan.v1",+ source: document.file,+ values: values.filter((value) => reachable.has(value.id)),+ instances: reachableInstances,+ kernels: [...kernels.values()]+ .filter((manifest) => usedKernels.has(manifest.name))+ .map((manifest) => ({+ name: manifest.name,+ abiVersion: manifest.abiVersion,+ manifestHash: manifest.sourceHash,+ implementationHash: manifest.implementationHash,+ profile: manifest.profile,+ ...(manifest.capability ? { capability: manifest.capability } : {}),+ ports: manifest.ports,+ parameters: manifest.parameters,+ children: manifest.children,+ }))+ .sort((left, right) => left.name.localeCompare(right.name)),+ root,+ edges: edges.filter((edge) => reachable.has(edge.from) && reachable.has(edge.to)),+ };+}++export function topologicalInstances(plan: PlanIR): PlanInstance[] {+ const byId = new Map(plan.instances.map((instance) => [instance.id, instance]));+ const visiting = new Set<string>();+ const done = new Set<string>();+ const output: PlanInstance[] = [];+ const visit = (id: string): void => {+ if (done.has(id)) return;+ if (visiting.has(id)) fail("plan_cycle", `Cycle detected at "${id}".`);+ visiting.add(id);+ const instance = byId.get(id);+ if (!instance) return;+ for (const dependency of instance.dependencies) {+ if (byId.has(dependency)) visit(dependency);+ }+ visiting.delete(id);+ done.add(id);+ output.push(instance);+ };+ visit(plan.root);+ return output;+}++export function reference(value: unknown): Reference | undefined {+ return value && typeof value === "object" && (value as Reference).kind === "reference"+ ? value as Reference+ : undefined;+}diff --git a/src/runtime-contract.ts b/src/runtime-contract.tsnew file mode 100644index 00000000..e3f14565--- /dev/null+++ b/src/runtime-contract.ts@@ -0,0 +1,95 @@+import type {+ AlignmentEvidence,+ AttributeValue,+ LocatedScript,+ NarrativeIR,+ PlanIR,+ PlanInstance,+ PlanValue,+ ProgramRange,+ SourceElement,+} from "./model.js";++export type VisualFragment = {+ id: string;+ kind: "image" | "video" | "html";+ startFrame: number;+ endFrameExclusive: number;+ z: number;+ layer?: number;+ source?: string;+ mediaStartSec?: number;+ playbackRate?: number;+ loop?: boolean;+ muted?: boolean;+ html?: string;+ css?: string;+ style?: Record<string, string | number>;+ innerStyle?: Record<string, string | number>;+ attributes?: Record<string, string>;+};++export type AudioFragment = {+ id: string;+ source: string;+ startFrame: number;+ endFrameExclusive: number;+ mediaStartSec?: number;+ playbackRate?: number;+ volume?: number;+ fadeInSec?: number;+ fadeOutSec?: number;+ bus?: "speech" | "music" | "sfx" | "source";+};++export type KernelProjection = {+ outputs: Record<string, unknown>;+ visuals?: VisualFragment[];+ audios?: AudioFragment[];+ styles?: string[];+ diagnostics?: Array<{ code: string; message: string }>;+};++export type HyperframesDocument = {+ contract: "svml.hyperframes-document.v1";+ id: string;+ width: number;+ height: number;+ fps: number;+ durationFrames: number;+ background: string;+ visuals: VisualFragment[];+ audios: AudioFragment[];+ styles?: string[];+};++export type RuntimeValue = PlanValue & {+ absoluteSource?: string;+};++export type KernelContext = {+ instance: PlanInstance;+ element: SourceElement;+ narrative: NarrativeIR;+ located: LocatedScript;+ alignment: AlignmentEvidence;+ plan: PlanIR;+ values: Map<string, RuntimeValue>;+ results: Map<string, KernelProjection>;+ resolve: (value: AttributeValue | undefined) => unknown;+ resolvePath: (path: string) => unknown;+ temporalContracts: Record<string, {+ kind: "selection" | "moment";+ consume: "one" | "each" | "set";+ }>;+ selection: (value: AttributeValue | undefined, contract: string) => ProgramRange[];+ moment: (value: AttributeValue | undefined, contract: string) => number[];+ fps: number;+ width: number;+ height: number;+};++export type KernelImplementation = {+ abiVersion: "1";+ project(context: KernelContext): Promise<KernelProjection> | KernelProjection;+};diff --git a/src/runtime-validation.ts b/src/runtime-validation.tsnew file mode 100644index 00000000..284e522f--- /dev/null+++ b/src/runtime-validation.ts@@ -0,0 +1,172 @@+import { fail } from "./diagnostics.js";+import type {+ AudioFragment,+ KernelProjection,+ VisualFragment,+} from "./runtime-contract.js";+import { sha256 } from "./util.js";++function cssBlocks(source: string, scope: string): string {+ let output = "";+ let offset = 0;+ while (offset < source.length) {+ const open = source.indexOf("{", offset);+ if (open < 0) {+ if (source.slice(offset).trim()) {+ fail("kernel_css_syntax", "Projector CSS contains a rule without a block.");+ }+ output += source.slice(offset);+ break;+ }+ let depth = 1;+ let cursor = open + 1;+ while (cursor < source.length && depth > 0) {+ if (source[cursor] === "{") depth += 1;+ else if (source[cursor] === "}") depth -= 1;+ cursor += 1;+ }+ if (depth !== 0) fail("kernel_css_syntax", "Projector CSS contains an unclosed block.");+ const header = source.slice(offset, open);+ const body = source.slice(open + 1, cursor - 1);+ const trimmed = header.trim();+ if (/^@(?:import|font-face|page|property)\b/iu.test(trimmed)) {+ fail("kernel_css_capability", `Projector CSS cannot emit ${trimmed.split(/\s/u)[0]}.`);+ }+ if (/^@(?:keyframes|-webkit-keyframes)\b/iu.test(trimmed)) {+ output += `${header}{${body}}`;+ } else if (trimmed.startsWith("@")) {+ output += `${header}{${cssBlocks(body, scope)}}`;+ } else {+ const selectors = header.split(",").map((selector) => selector.trim()).filter(Boolean);+ if (!selectors.length) fail("kernel_css_selector", "Projector CSS has an empty selector.");+ output += `${selectors.map((selector) => `${scope} ${selector}`).join(", ")}{${body}}`;+ }+ offset = cursor;+ }+ return output;+}++function assertInertHtml(value: string, id: string): void {+ if (+ /<(?:script|style|iframe|object|embed|link|meta|base|form|input|button|textarea|select)\b/iu.test(value)+ || /\son[a-z]+\s*=/iu.test(value)+ || /javascript\s*:/iu.test(value)+ ) {+ fail(+ "kernel_html_capability",+ `Visual fragment "${id}" contains executable or document-global HTML.`,+ );+ }+}++function assertStyle(+ style: Record<string, string | number> | undefined,+ id: string,+): void {+ for (const [name, value] of Object.entries(style ?? {})) {+ if (!/^--?[A-Za-z_][A-Za-z0-9_-]*$|^[A-Za-z_][A-Za-z0-9_-]*$/u.test(name)) {+ fail("kernel_style_property", `Visual fragment "${id}" has invalid style property "${name}".`);+ }+ if (/(?:url\s*\(|expression\s*\(|javascript\s*:)/iu.test(String(value))) {+ fail("kernel_style_capability", `Visual fragment "${id}" style "${name}" requests an external capability.`);+ }+ }+}++function normalizeVisual(+ fragment: VisualFragment,+ sharedStyles: string[],+): VisualFragment {+ if (+ !Number.isInteger(fragment.startFrame)+ || !Number.isInteger(fragment.endFrameExclusive)+ || fragment.startFrame < 0+ || fragment.endFrameExclusive < fragment.startFrame+ || !Number.isFinite(fragment.z)+ ) {+ fail("kernel_visual_window", `Visual fragment "${fragment.id}" has an invalid frame window or z.`);+ }+ if (!["image", "video", "html"].includes(fragment.kind)) {+ fail("kernel_visual_kind", `Visual fragment "${fragment.id}" has unknown kind.`);+ }+ if (fragment.kind === "html") assertInertHtml(fragment.html ?? "", fragment.id);+ assertStyle(fragment.style, fragment.id);+ assertStyle(fragment.innerStyle, fragment.id);+ for (const name of Object.keys(fragment.attributes ?? {})) {+ if (!/^[A-Za-z_][A-Za-z0-9_.:-]*$/u.test(name) || /^on/iu.test(name)) {+ fail("kernel_fragment_attribute", `Visual fragment "${fragment.id}" has forbidden attribute "${name}".`);+ }+ }+ const existingToken = fragment.attributes?.["data-svml-scope"];+ const token = typeof existingToken === "string"+ ? existingToken+ : sha256(fragment.id).slice(0, 16);+ const selector = `[data-svml-scope="${token}"]`;+ const css = [+ fragment.css+ ? (typeof existingToken === "string" ? fragment.css : cssBlocks(fragment.css, selector))+ : "",+ ...sharedStyles.map((value) => cssBlocks(value, selector)),+ ]+ .filter((value): value is string => typeof value === "string" && value.trim() !== "")+ .join("\n");+ return {+ ...fragment,+ attributes: {+ ...fragment.attributes,+ "data-svml-scope": token,+ },+ ...(css ? { css } : {}),+ };+}++function validateAudio(fragment: AudioFragment): AudioFragment {+ if (+ !Number.isInteger(fragment.startFrame)+ || !Number.isInteger(fragment.endFrameExclusive)+ || fragment.startFrame < 0+ || fragment.endFrameExclusive < fragment.startFrame+ ) {+ fail("kernel_audio_window", `Audio fragment "${fragment.id}" has an invalid frame window.`);+ }+ if (fragment.bus && !["speech", "music", "sfx", "source"].includes(fragment.bus)) {+ fail("kernel_audio_bus", `Audio fragment "${fragment.id}" uses unknown bus "${fragment.bus}".`);+ }+ return fragment;+}++function normalizeSurface(value: unknown): void {+ if (!value || typeof value !== "object") return;+ const surface = value as {+ visuals?: VisualFragment[];+ audios?: AudioFragment[];+ styles?: string[];+ };+ if (Array.isArray(surface.visuals) || Array.isArray(surface.audios) || Array.isArray(surface.styles)) {+ const visualIds = (surface.visuals ?? []).map((fragment) => fragment.id);+ if (new Set(visualIds).size !== visualIds.length) {+ fail("kernel_visual_duplicate_id", "A projected visual surface repeats a fragment id.");+ }+ const audioIds = (surface.audios ?? []).map((fragment) => fragment.id);+ if (new Set(audioIds).size !== audioIds.length) {+ fail("kernel_audio_duplicate_id", "A projected audio tree repeats a fragment id.");+ }+ const styles = Array.isArray(surface.styles) ? surface.styles : [];+ if (surface.visuals) surface.visuals = surface.visuals.map((fragment) =>+ normalizeVisual(fragment, styles));+ if (surface.audios) surface.audios = surface.audios.map(validateAudio);+ surface.styles = [];+ }+ for (const child of Object.values(value as Record<string, unknown>)) {+ if (child !== surface.visuals && child !== surface.audios && child !== surface.styles) {+ normalizeSurface(child);+ }+ }+}++export function validateKernelProjection(+ projection: KernelProjection,+): KernelProjection {+ normalizeSurface(projection);+ return projection;+}diff --git a/src/sandbox-worker.mjs b/src/sandbox-worker.mjsnew file mode 100644index 00000000..ee285b1a--- /dev/null+++ b/src/sandbox-worker.mjs@@ -0,0 +1,166 @@+import { readFile, realpath } from "node:fs/promises";+import { dirname, relative, resolve } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import vm from "node:vm";++function inside(root, candidate) {+ const path = relative(root, candidate);+ return path === "" || (!path.startsWith("..") && !path.startsWith("/"));+}++async function stdin() {+ const chunks = [];+ for await (const chunk of process.stdin) chunks.push(chunk);+ return Buffer.concat(chunks).toString("utf8");+}++async function main() {+ const implementation = await realpath(resolve(process.argv[2]));+ const packageRoot = await realpath(resolve(process.argv[3] ?? dirname(implementation)));+ if (!inside(packageRoot, implementation)) {+ throw new Error(`Kernel implementation escapes package root: ${implementation}`);+ }++ const context = vm.createContext(Object.create(null), {+ name: "svml-kernel-projector",+ codeGeneration: { strings: false, wasm: false },+ });+ new vm.Script(`+ Object.defineProperty(Math, "random", {+ value() { throw new Error("SVK projector cannot use ambient randomness"); },+ writable: false,+ configurable: false+ });+ globalThis.Date = class ForbiddenDate {+ constructor() { throw new Error("SVK projector cannot use wall clock time"); }+ static now() { throw new Error("SVK projector cannot use wall clock time"); }+ };+ globalThis.fetch = undefined;+ globalThis.WebSocket = undefined;+ globalThis.EventSource = undefined;+ globalThis.XMLHttpRequest = undefined;+ globalThis.process = undefined;+ globalThis.require = undefined;+ `).runInContext(context, { timeout: 250 });++ const cache = new Map();+ const loadModule = async (file) => {+ const canonical = await realpath(file);+ if (!inside(packageRoot, canonical)) {+ throw new Error(`SVK import escapes package root: ${canonical}`);+ }+ const cached = cache.get(canonical);+ if (cached) return cached;+ const source = await readFile(canonical, "utf8");+ const module = new vm.SourceTextModule(source, {+ context,+ identifier: pathToFileURL(canonical).href,+ initializeImportMeta(meta) {+ meta.url = pathToFileURL(canonical).href;+ },+ importModuleDynamically(specifier) {+ throw new Error(`Dynamic import is forbidden in SVK projectors: ${specifier}`);+ },+ });+ cache.set(canonical, module);+ await module.link(async (specifier, referencing) => {+ if (!specifier.startsWith("./") && !specifier.startsWith("../")) {+ throw new Error(`Only relative SVK imports are allowed: ${specifier}`);+ }+ return loadModule(fileURLToPath(new URL(specifier, referencing.identifier)));+ });+ return module;+ };++ const module = await loadModule(implementation);+ await module.evaluate({ timeout: 1000 });+ const implementationObject = module.namespace.default;+ if (!implementationObject || typeof implementationObject.project !== "function") {+ throw new Error(`${implementation} must default-export a projector object`);+ }+ context.__svmlKernel = implementationObject;+ context.__svmlInput = await stdin();+ const output = new vm.Script(`+ (() => {+ const context = JSON.parse(globalThis.__svmlInput);+ context.resolve = value => value;+ context.resolvePath = () => {+ throw new Error("resolvePath is unavailable in isolated projector ABI v1");+ };+ const frameRange = (startSec, endSec) => {+ const startFrame = Math.round(startSec * context.fps);+ const endFrameExclusive = Math.round(endSec * context.fps);+ if (endFrameExclusive < startFrame) throw new Error("manual range resolves backwards");+ return {+ startFrame,+ endFrameExclusive,+ startSec: startFrame / context.fps,+ endSec: endFrameExclusive / context.fps+ };+ };+ const endpoint = raw => {+ const value = String(raw).trim();+ if (value === "start") return 0;+ if (value === "end") return context.located.durationSec;+ const relative = /^(start|end)([+-])(\\d+(?:\\.\\d+)?)(ms|s)$/.exec(value);+ if (relative) {+ const base = relative[1] === "start" ? 0 : context.located.durationSec;+ const amount = Number(relative[3]) * (relative[4] === "ms" ? 0.001 : 1);+ return base + (relative[2] === "+" ? amount : -amount);+ }+ const absolute = /^(\\d+(?:\\.\\d+)?)(ms|s)$/.exec(value);+ if (absolute) return Number(absolute[1]) * (absolute[2] === "ms" ? 0.001 : 1);+ throw new Error("unsupported manual time expression: " + value);+ };+ const temporalContract = (path, kind) => {+ const contract = context.temporalContracts && context.temporalContracts[path];+ if (!contract || contract.kind !== kind) {+ throw new Error("undeclared " + kind + " temporal contract: " + String(path));+ }+ return contract;+ };+ context.selection = (value, path) => {+ const contract = temporalContract(path, "selection");+ let ranges;+ if (typeof value === "string") {+ if (value === "full") ranges = [frameRange(0, context.located.durationSec)];+ else {+ const parts = value.split("..");+ if (parts.length !== 2) throw new Error("manual span requires start .. end");+ ranges = [frameRange(endpoint(parts[0]), endpoint(parts[1]))];+ }+ } else {+ ranges = value && value.ranges;+ }+ if (!ranges) throw new Error("expected SelectionSet or ProgramSpan");+ if (contract.consume === "one" && ranges.length !== 1) {+ throw new Error("temporal cardinality expected one, received " + ranges.length);+ }+ return ranges;+ };+ context.moment = (value, path) => {+ const contract = temporalContract(path, "moment");+ const frames = typeof value === "string"+ ? [Math.round(endpoint(value) * context.fps)]+ : value && value.frames;+ if (!frames) throw new Error("expected MomentSet or manual ProgramPoint");+ if (contract.consume === "one" && frames.length !== 1) {+ throw new Error("temporal cardinality expected one, received " + frames.length);+ }+ return frames;+ };+ const result = globalThis.__svmlKernel.project(context);+ if (result && typeof result.then === "function") {+ throw new Error("isolated projector ABI v1 must be synchronous");+ }+ return JSON.stringify(result);+ })()+ `).runInContext(context, { timeout: 2000 });+ if (typeof output !== "string") throw new Error("SVK projector returned no JSON result");+ process.stdout.write(output);+}++main().catch((error) => {+ process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);+ process.exitCode = 1;+});diff --git a/src/sandbox.ts b/src/sandbox.tsnew file mode 100644index 00000000..5a7f6fbb--- /dev/null+++ b/src/sandbox.ts@@ -0,0 +1,70 @@+import { spawn } from "node:child_process";+import { dirname } from "node:path";+import { fileURLToPath } from "node:url";+import { fail } from "./diagnostics.js";+import type { KernelManifest } from "./kernel.js";+import type { KernelProjection } from "./runtime-contract.js";++const MAX_OUTPUT_BYTES = 32 * 1024 * 1024;++export async function projectKernelIsolated(+ manifest: KernelManifest,+ input: unknown,+): Promise<KernelProjection> {+ const implementationPath = manifest.implementationPath;+ if (!implementationPath || manifest.profile !== "isolated-projector-v1") {+ fail(+ "kernel_projector_profile",+ `Kernel "${manifest.name}" is not an isolated projector.`,+ );+ }+ if (manifest.permissions.length) {+ fail(+ "kernel_permission_unsupported",+ `Kernel "${manifest.name}" requests unsupported projector permissions: ${manifest.permissions.join(", ")}.`,+ );+ }+ const worker = fileURLToPath(new URL("./sandbox-worker.mjs", import.meta.url));+ const packageRoot = dirname(manifest.sourcePath);+ const child = spawn(process.execPath, [+ "--experimental-vm-modules",+ "--permission",+ `--allow-fs-read=${packageRoot}`,+ "--max-old-space-size=128",+ worker,+ implementationPath,+ packageRoot,+ ], {+ stdio: ["pipe", "pipe", "pipe"],+ });+ const stdout: Buffer[] = [];+ const stderr: Buffer[] = [];+ let outputBytes = 0;+ child.stdout.on("data", (chunk: Buffer) => {+ outputBytes += chunk.length;+ if (outputBytes > MAX_OUTPUT_BYTES) child.kill("SIGKILL");+ else stdout.push(chunk);+ });+ child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk));+ const timeout = setTimeout(() => child.kill("SIGKILL"), 5000);+ child.stdin.end(JSON.stringify(input));+ const code = await new Promise<number | null>((accept, reject) => {+ child.once("error", reject);+ child.once("exit", accept);+ });+ clearTimeout(timeout);+ if (code !== 0) {+ fail(+ "kernel_projector_isolation",+ `Kernel "${manifest.name}" failed in isolated projector: ${Buffer.concat(stderr).toString("utf8").trim() || `exit ${String(code)}`}.`,+ );+ }+ try {+ return JSON.parse(Buffer.concat(stdout).toString("utf8")) as KernelProjection;+ } catch {+ fail(+ "kernel_projector_output",+ `Kernel "${manifest.name}" did not return valid JSON from its isolated projector.`,+ );+ }+}diff --git a/src/script/estimate.ts b/src/script/estimate.tsnew file mode 100644index 00000000..4f8a7d3c--- /dev/null+++ b/src/script/estimate.ts@@ -0,0 +1,116 @@+import type {+ AlignmentCaptionCue,+ AlignmentEvidence,+ NarrativeIR,+ ScriptToken,+} from "../model.js";++export type EstimateOptions = {+ syllablesPerSecond?: number;+ wordGapSec?: number;+ segmentPaddingSec?: number;+ emptySegmentSec?: number;+ maxCaptionWords?: number;+ fps?: number;+};++function syllables(token: ScriptToken): number {+ if (/^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]\p{M}*$/u.test(token.text)) {+ return 1;+ }+ const ascii = token.normalized+ .normalize("NFD")+ .replace(/\p{M}/gu, "")+ .toLocaleLowerCase("en");+ const groups = ascii.match(/[aeiouy]+/gu)?.length ?? 0;+ const silentE = groups > 1 && /[^aeiou]e$/u.test(ascii) ? 1 : 0;+ return Math.max(1, groups - silentE);+}++function captionCues(narrative: NarrativeIR, maxWords: number): AlignmentCaptionCue[] {+ const output: AlignmentCaptionCue[] = [];+ for (const segment of narrative.segments) {+ for (+ let startWord = segment.tokenStart;+ startWord < segment.tokenEnd;+ startWord += maxWords+ ) {+ output.push({+ id: `estimate-cue-${output.length + 1}`,+ startWord,+ endWordExclusive: Math.min(segment.tokenEnd, startWord + maxWords),+ });+ }+ }+ return output;+}++export function estimateAlignment(+ narrative: NarrativeIR,+ options: EstimateOptions = {},+): AlignmentEvidence {+ const syllablesPerSecond = options.syllablesPerSecond ?? 6.5;+ const wordGapSec = options.wordGapSec ?? 0.045;+ const segmentPaddingSec = options.segmentPaddingSec ?? 0.12;+ const emptySegmentSec = options.emptySegmentSec ?? 1;+ const maxCaptionWords = Math.max(1, Math.floor(options.maxCaptionWords ?? 3));+ const fps = Math.max(1, Math.round(options.fps ?? 30));+ for (const [name, value] of Object.entries({+ syllablesPerSecond,+ wordGapSec,+ segmentPaddingSec,+ emptySegmentSec,+ })) {+ if (!Number.isFinite(value) || value < 0 || (name === "syllablesPerSecond" && value === 0)) {+ throw new Error(`invalid estimate option ${name}=${String(value)}`);+ }+ }++ let cursor = 0;+ const words: AlignmentEvidence["words"] = [];+ const segments: AlignmentEvidence["segments"] = [];+ for (const segment of narrative.segments) {+ const segmentTokens = narrative.tokens.slice(segment.tokenStart, segment.tokenEnd);+ const startSec = cursor;+ if (!segmentTokens.length) {+ cursor += emptySegmentSec;+ cursor = Math.ceil(cursor * fps) / fps;+ segments.push({ id: segment.id, startSec, endSec: cursor });+ continue;+ }+ cursor += segmentPaddingSec;+ for (const [index, token] of segmentTokens.entries()) {+ const wordStart = cursor;+ cursor += syllables(token) / syllablesPerSecond;+ words.push({+ text: token.text,+ startSec: wordStart,+ endSec: cursor,+ segmentId: segment.id,+ });+ if (index < segmentTokens.length - 1) cursor += wordGapSec;+ }+ cursor += segmentPaddingSec;+ cursor = Math.ceil(cursor * fps) / fps;+ segments.push({ id: segment.id, startSec, endSec: cursor });+ }+ const durationFrames = Math.max(1, Math.ceil(cursor * fps));+ const durationSec = durationFrames / fps;+ return {+ contract: "svml.speech-alignment.v1",+ durationSec,+ fps,+ words,+ segments,+ captionCues: captionCues(narrative, maxCaptionWords),+ provenance: {+ method: "svml.syllable-estimate.v1",+ measured: false,+ syllablesPerSecond,+ wordGapSec,+ segmentPaddingSec,+ emptySegmentSec,+ maxCaptionWords,+ },+ };+}diff --git a/src/script/locate.ts b/src/script/locate.tsnew file mode 100644index 00000000..949eaae1--- /dev/null+++ b/src/script/locate.ts@@ -0,0 +1,241 @@+import { fail } from "../diagnostics.js";+import type {+ AlignmentEvidence,+ LocatedScript,+ MarkerBoundary,+ NarrativeIR,+ ProgramRange,+} from "../model.js";+import { normalizeWord } from "../util.js";++function frameAt(seconds: number, fps: number): number {+ return Math.round(seconds * fps);+}++function range(startSec: number, endSec: number, fps: number): ProgramRange {+ const startFrame = frameAt(startSec, fps);+ const endFrameExclusive = frameAt(endSec, fps);+ if (endFrameExclusive < startFrame) {+ fail("locate_negative_range", `Range ${startSec}..${endSec} resolves backwards.`);+ }+ return {+ startFrame,+ endFrameExclusive,+ startSec: startFrame / fps,+ endSec: endFrameExclusive / fps,+ };+}++function boundaryTime(+ boundary: MarkerBoundary,+ affinity: "left" | "right",+ narrative: NarrativeIR,+ evidence: AlignmentEvidence,+): number {+ const left = boundary.tokenIndex > 0 ? evidence.words[boundary.tokenIndex - 1] : undefined;+ const right = evidence.words[boundary.tokenIndex];+ if (affinity === "left" && left) return left.endSec;+ if (affinity === "right" && right) return right.startSec;++ const segment = boundary.segmentId+ ? evidence.segments.find((item) => item.id === boundary.segmentId)+ : undefined;+ if (segment) return affinity === "left" ? segment.endSec : segment.startSec;++ const cut = boundary.structuralCut ?? 0;+ if (cut <= 0) return 0;+ if (cut >= narrative.segments.length) return evidence.durationSec;+ const rightSegment = evidence.segments.find((item) => item.id === narrative.segments[cut]?.id);+ const leftSegment = evidence.segments.find((item) => item.id === narrative.segments[cut - 1]?.id);+ if (affinity === "right" && rightSegment) return rightSegment.startSec;+ if (leftSegment) return leftSegment.endSec;+ fail("locate_unresolved_boundary", `Could not resolve structural cut ${cut}.`);+}++export function locateScript(+ narrative: NarrativeIR,+ evidence: AlignmentEvidence,+): LocatedScript {+ if (evidence.contract !== "svml.speech-alignment.v1") {+ fail("locate_alignment_contract", `Unsupported alignment contract "${evidence.contract}".`);+ }+ if (+ !Number.isFinite(evidence.fps)+ || evidence.fps <= 0+ || !Number.isFinite(evidence.durationSec)+ || evidence.durationSec <= 0+ ) {+ fail("locate_alignment_clock", "Alignment evidence requires positive finite fps and durationSec.");+ }+ if (narrative.tokens.length !== evidence.words.length) {+ fail(+ "locate_alignment_cardinality",+ `Script has ${narrative.tokens.length} words but alignment has ${evidence.words.length}.`,+ );+ }+ for (let index = 0; index < evidence.words.length; index += 1) {+ const word = evidence.words[index];+ if (!word) continue;+ if (+ !Number.isFinite(word.startSec)+ || !Number.isFinite(word.endSec)+ || word.startSec < 0+ || word.endSec < word.startSec+ || word.endSec > evidence.durationSec+ ) {+ fail(+ "locate_alignment_word_window",+ `Alignment word ${index + 1} has invalid window ${word.startSec}..${word.endSec}.`,+ );+ }+ const previous = evidence.words[index - 1];+ if (previous && word.startSec < previous.endSec - 1e-6) {+ fail(+ "locate_alignment_word_overlap",+ `Alignment word ${index + 1} starts at ${word.startSec} before word ${index} ends at ${previous.endSec}.`,+ );+ }+ const segment = evidence.segments.find((item) => item.id === word.segmentId);+ if (+ !segment+ || word.startSec < segment.startSec - 1e-6+ || word.endSec > segment.endSec + 1e-6+ ) {+ fail(+ "locate_alignment_word_segment",+ `Alignment word ${index + 1} falls outside segment "${word.segmentId}".`,+ );+ }+ }+ for (let index = 0; index < narrative.tokens.length; index += 1) {+ const token = narrative.tokens[index];+ const word = evidence.words[index];+ if (!token || !word) continue;+ if (token.normalized !== normalizeWord(word.text)) {+ fail(+ "locate_alignment_word_mismatch",+ `Word ${index + 1} is "${token.text}" in Script and "${word.text}" in alignment evidence.`,+ );+ }+ if (token.segmentId !== word.segmentId) {+ fail(+ "locate_alignment_segment_mismatch",+ `Word ${index + 1} belongs to ${token.segmentId} in Script and ${word.segmentId} in evidence.`,+ );+ }+ }+ const fps = evidence.fps;+ const words = narrative.tokens.map((token, index) => {+ const word = evidence.words[index];+ if (!word) fail("locate_alignment_missing_word", `Missing aligned word ${index + 1}.`);+ return { ...token, ...range(word.startSec, word.endSec, fps) };+ });+ const segments = Object.fromEntries(evidence.segments.map((segment) => [+ segment.id,+ range(segment.startSec, segment.endSec, fps),+ ]));+ const selections = Object.fromEntries(Object.entries(narrative.selections).map(([id, occurrences]) => [+ id,+ {+ id,+ ranges: occurrences.map((occurrence) => range(+ boundaryTime(occurrence.open.boundary, occurrence.open.affinity, narrative, evidence),+ boundaryTime(occurrence.close.boundary, occurrence.close.affinity, narrative, evidence),+ fps,+ )),+ },+ ]));+ const moments = Object.fromEntries(Object.entries(narrative.moments).map(([id, occurrences]) => [+ id,+ {+ id,+ frames: occurrences.map((occurrence) => frameAt(+ boundaryTime(occurrence.boundary, occurrence.affinity, narrative, evidence),+ fps,+ )),+ },+ ]));+ const captionAtoms = narrative.captionAtoms.map((atom) => {+ const first = words[atom.startWord];+ const last = words[atom.endWordExclusive - 1];+ if (!first || !last || first.segmentId !== last.segmentId) {+ fail("locate_caption_atom", `Caption atom "${atom.id}" has an invalid speech span.`);+ }+ return {+ ...atom,+ ...range(first.startSec, last.endSec, fps),+ };+ });+ const captionCues = evidence.captionCues?.map((cue, index) => {+ if (!Number.isInteger(cue.startWord) || !Number.isInteger(cue.endWordExclusive)) {+ fail("locate_caption_cue_index", `Caption cue ${index + 1} must use integer word indexes.`);+ }+ if (+ cue.startWord < 0+ || cue.endWordExclusive <= cue.startWord+ || cue.endWordExclusive > words.length+ ) {+ fail(+ "locate_caption_cue_range",+ `Caption cue ${index + 1} has invalid word range ${cue.startWord}..${cue.endWordExclusive}.`,+ );+ }+ const previous = evidence.captionCues?.[index - 1];+ const expectedStart = previous?.endWordExclusive ?? 0;+ if (cue.startWord !== expectedStart) {+ fail(+ "locate_caption_cue_partition",+ `Caption cue ${index + 1} starts at word ${cue.startWord}; expected ${expectedStart}.`,+ );+ }+ const first = words[cue.startWord];+ const last = words[cue.endWordExclusive - 1];+ if (!first || !last) {+ fail("locate_caption_cue_word", `Caption cue ${index + 1} references a missing word.`);+ }+ if (first.segmentId !== last.segmentId) {+ fail(+ "locate_caption_cue_segment",+ `Caption cue ${index + 1} crosses Script segments ${first.segmentId} and ${last.segmentId}.`,+ );+ }+ for (const atom of captionAtoms) {+ const overlaps = cue.startWord < atom.endWordExclusive+ && cue.endWordExclusive > atom.startWord;+ const contains = cue.startWord <= atom.startWord+ && cue.endWordExclusive >= atom.endWordExclusive;+ if (overlaps && !contains) {+ fail(+ "locate_caption_partial_dual",+ `Caption cue ${index + 1} cuts through Dual Text atom "${atom.id}".`,+ );+ }+ }+ return {+ id: cue.id ?? `cue-${index + 1}`,+ startWord: cue.startWord,+ endWordExclusive: cue.endWordExclusive,+ ...range(first.startSec, last.endSec, fps),+ };+ });+ if (+ captionCues+ && (captionCues.at(-1)?.endWordExclusive ?? 0) !== words.length+ ) {+ fail(+ "locate_caption_cue_partition",+ `Caption cues end at word ${captionCues.at(-1)?.endWordExclusive ?? 0}; expected ${words.length}.`,+ );+ }+ return {+ durationFrames: frameAt(evidence.durationSec, fps),+ durationSec: frameAt(evidence.durationSec, fps) / fps,+ fps,+ words,+ segments,+ selections,+ moments,+ captionAtoms,+ ...(captionCues ? { captionCues } : {}),+ };+}diff --git a/src/script/parse.ts b/src/script/parse.tsnew file mode 100644index 00000000..a3cbdc5f--- /dev/null+++ b/src/script/parse.ts@@ -0,0 +1,576 @@+import { fail, sourceLocation } from "../diagnostics.js";+import type {+ MarkerBoundary,+ MomentOccurrence,+ NarrativeIR,+ ScriptAtom,+ ScriptSegment,+ ScriptToken,+ SelectionOccurrence,+} from "../model.js";+import { normalizeWord } from "../util.js";++type Marker = {+ id: string;+ kind: "open" | "close" | "moment";+ affinity: "left" | "right";+ length: number;+};++type MutableSegment = {+ id: string;+ index: number;+ atoms: ScriptAtom[];+ tokenStart: number;+ sourceStart: number;+};++const WORD =+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]\p{M}*|[\p{L}\p{M}\p{N}]+(?:['’.-][\p{L}\p{M}\p{N}]+)*/gu;+const SEGMENT_OPEN = /^<segment\s+id=(?:"([^"]+)"|'([^']+)')\s*(\/?)>/u;+const SEGMENT_CLOSE = /^<\/segment\s*>/u;+const ROLE_LABEL = /^[\p{L}\p{M}\p{N}_](?:[\p{L}\p{M}\p{N}_. -]{0,30}[\p{L}\p{M}\p{N}_.-])?$/u;+const TEMPORAL_ID = /^[a-z][a-z0-9_-]{0,63}$/u;+const SEGMENT_ID = /^[a-z][a-z0-9_-]{0,63}$/u;++function parseMarker(source: string, offset: number): Marker | undefined {+ const slice = source.slice(offset);+ const markerName = String.raw`[a-z][a-z0-9_-]{0,63}`;+ const match = new RegExp(+ String.raw`^(~)?@(?:(\/)(${markerName})(~)?|(${markerName})(!)?)(?![A-Za-z0-9_-])`,+ "u",+ ).exec(slice);+ if (!match) return undefined;+ const prefixLeft = match[1] === "~";+ const close = match[2] === "/";+ const id = close ? match[3] : match[5];+ const suffixRight = close && match[4] === "~";+ const moment = !close && match[6] === "!";+ if (!id) return undefined;+ return {+ id,+ kind: moment ? "moment" : close ? "close" : "open",+ affinity: prefixLeft || (!close && !moment ? false : false)+ ? "left"+ : suffixRight+ ? "right"+ : close+ ? "left"+ : "right",+ length: match[0].length,+ };+}++function cleanProjection(value: string): string {+ return value+ .replace(/\s+/gu, " ")+ .replace(/\s+([,.;:!?])/gu, "$1")+ .replace(/([([{])\s+/gu, "$1")+ .replace(/\s+([)\]}])/gu, "$1")+ .trim();+}++function joinProjection(parts: string[]): string {+ return cleanProjection(parts.filter((part) => part.trim()).join(" "));+}++function markerBoundary(+ tokenIndex: number,+ segment: MutableSegment | undefined,+ structuralCut: number,+): MarkerBoundary {+ return {+ tokenIndex,+ structuralCut,+ ...(segment ? { segmentId: segment.id } : {}),+ };+}++export function parseScript(+ file: string,+ scriptSource: string,+ sourceOffset = 0,+ bindings: Record<string, string> = {},+): NarrativeIR {+ scriptSource = scriptSource.replace(/\r\n?/gu, "\n").normalize("NFC");+ const segments: ScriptSegment[] = [];+ const tokens: ScriptToken[] = [];+ const openSelections = new Map<string, Array<{+ affinity: "left" | "right";+ boundary: MarkerBoundary;+ sourceStart: number;+ }>>();+ const selections: Record<string, SelectionOccurrence[]> = {};+ const moments: Record<string, MomentOccurrence[]> = {};+ const captionAtoms: NarrativeIR["captionAtoms"] = [];+ let current: MutableSegment | undefined;+ let offset = 0;+ let structuralCut = 0;+ let lineStart = true;++ const location = (at: number) => sourceLocation(file, scriptSource, at);++ const findUnescaped = (value: string, character: string, from = 0): number => {+ for (let index = from; index < value.length; index += 1) {+ if (value[index] !== character) continue;+ let slashes = 0;+ for (let before = index - 1; before >= 0 && value[before] === "\\"; before -= 1) {+ slashes += 1;+ }+ if (slashes % 2 === 0) return index;+ }+ return -1;+ };++ const literalPieces = (+ raw: string,+ absoluteStart: number,+ dual = false,+ ): Array<{ value: string; start: number; end: number }> => {+ const pieces: Array<{ value: string; start: number; end: number }> = [];+ let buffer = "";+ let bufferStart = 0;+ const flush = (end: number): void => {+ if (!buffer) {+ bufferStart = end;+ return;+ }+ pieces.push({+ value: buffer,+ start: absoluteStart + bufferStart,+ end: absoluteStart + end,+ });+ buffer = "";+ bufferStart = end;+ };+ for (let index = 0; index < raw.length;) {+ if (raw.startsWith("${", index)) {+ flush(index);+ const close = raw.indexOf("}", index + 2);+ if (close < 0) fail("script_slot_unclosed", "Unclosed Script Slot.", location(absoluteStart + index));+ const id = raw.slice(index + 2, close);+ if (!/^[\p{L}_][\p{L}\p{M}\p{N}_-]{0,63}$/u.test(id)) {+ fail("script_slot_id", `Invalid Script Slot "${id}".`, location(absoluteStart + index));+ }+ const value = bindings[id];+ if (value === undefined) {+ fail("script_slot_unbound", `Script Slot "${id}" is not bound.`, location(absoluteStart + index));+ }+ if (/[\r\n\p{Cc}]/u.test(value)) {+ fail("script_slot_value", `Script Slot "${id}" must be single-line literal text.`);+ }+ pieces.push({+ value,+ start: absoluteStart + index,+ end: absoluteStart + close + 1,+ });+ index = close + 1;+ bufferStart = index;+ continue;+ }+ if (raw[index] === "\\") {+ const known = raw.startsWith("\\${", index)+ ? { value: "${", length: 3 }+ : ["@", "<", "\\", ...(dual ? ["|", ">"] : [])].includes(raw[index + 1] ?? "")+ ? { value: raw[index + 1]!, length: 2 }+ : undefined;+ if (!known) {+ fail(+ "script_unknown_escape",+ `Unknown Script escape "${raw.slice(index, index + 2)}".`,+ location(absoluteStart + index),+ );+ }+ buffer += known.value;+ index += known.length;+ continue;+ }+ buffer += raw[index];+ index += 1;+ }+ flush(raw.length);+ return pieces;+ };++ const literalString = (raw: string, absoluteStart: number, dual = false): string =>+ literalPieces(raw, absoluteStart, dual).map((piece) => piece.value).join("");++ const addMarker = (marker: Marker, at: number): void => {+ const boundary = markerBoundary(tokens.length, current, structuralCut);+ if (marker.kind === "moment") {+ if (openSelections.has(marker.id) || selections[marker.id]) {+ fail(+ "script_temporal_type_conflict",+ `Temporal name "${marker.id}" cannot be both Selection and Moment.`,+ location(at),+ );+ }+ const list = moments[marker.id] ?? [];+ list.push({+ id: marker.id,+ occurrence: list.length,+ affinity: marker.affinity,+ boundary,+ sourceStart: sourceOffset + at,+ });+ moments[marker.id] = list;+ return;+ }+ if (marker.kind === "open") {+ if (moments[marker.id]) {+ fail(+ "script_temporal_type_conflict",+ `Temporal name "${marker.id}" cannot be both Moment and Selection.`,+ location(at),+ );+ }+ const list = openSelections.get(marker.id) ?? [];+ if (list.length) {+ fail(+ "script_selection_reopened",+ `Selection "${marker.id}" is opened again before it closes.`,+ location(at),+ );+ }+ list.push({+ affinity: marker.affinity,+ boundary,+ sourceStart: sourceOffset + at,+ });+ openSelections.set(marker.id, list);+ return;+ }+ const opens = openSelections.get(marker.id);+ const open = opens?.shift();+ if (!open) {+ fail(+ "script_selection_close_without_open",+ `Selection "${marker.id}" closes without a matching open marker.`,+ location(at),+ );+ }+ const list = selections[marker.id] ?? [];+ list.push({+ id: marker.id,+ occurrence: list.length,+ open,+ close: {+ affinity: marker.affinity,+ boundary,+ sourceStart: sourceOffset + at,+ },+ });+ selections[marker.id] = list;+ };++ const addText = (+ speech: string,+ caption: string,+ start: number,+ end: number,+ ): void => {+ if (!current) {+ if (speech.trim() || caption.trim()) {+ fail(+ "script_text_outside_segment",+ "Natural-language text is only allowed inside <segment>.",+ location(start),+ );+ }+ return;+ }+ current.atoms.push({+ kind: "text",+ speech,+ caption,+ start: sourceOffset + start,+ end: sourceOffset + end,+ });+ WORD.lastIndex = 0;+ let match: RegExpExecArray | null;+ while ((match = WORD.exec(speech))) {+ const normalized = normalizeWord(match[0]);+ if (!normalized) continue;+ const index = tokens.length;+ tokens.push({+ id: `w${index + 1}`,+ index,+ segmentId: current.id,+ text: match[0],+ normalized,+ sourceStart: sourceOffset + start + match.index,+ sourceEnd: sourceOffset + start + match.index + match[0].length,+ });+ }+ };++ const consumeSpeechSide = (+ raw: string,+ absoluteStart: number,+ caption: string,+ ): void => {+ const startWord = tokens.length;+ let partStart = 0;+ let index = 0;+ let emittedCaption = false;+ const addLiteral = (rawPart: string, start: number): void => {+ const pieces = literalPieces(rawPart, start, true);+ for (const piece of pieces) {+ addText(+ piece.value,+ emittedCaption ? "" : caption,+ piece.start,+ piece.end,+ );+ emittedCaption = true;+ }+ };+ while (index < raw.length) {+ if (raw.startsWith("${", index)) {+ const close = raw.indexOf("}", index + 2);+ if (close < 0) fail("script_slot_unclosed", "Unclosed Script Slot.", location(absoluteStart + index));+ index = close + 1;+ continue;+ }+ if (raw[index] === "\\") {+ index += raw.startsWith("\\${", index) ? 3 : 2;+ continue;+ }+ const marker = parseMarker(raw, index);+ if (!marker) {+ if (raw[index] === "@") {+ fail(+ "script_invalid_marker",+ "Unescaped @ must begin a valid Selection or Moment marker.",+ location(absoluteStart + index),+ );+ }+ index += 1;+ continue;+ }+ addLiteral(raw.slice(partStart, index), absoluteStart + partStart);+ addMarker(marker, absoluteStart + index);+ index += marker.length;+ partStart = index;+ }+ addLiteral(raw.slice(partStart), absoluteStart + partStart);+ const endWordExclusive = tokens.length;+ if (endWordExclusive > startWord) {+ captionAtoms.push({+ id: `caption-atom-${captionAtoms.length + 1}`,+ display: cleanProjection(caption),+ segmentId: current!.id,+ startWord,+ endWordExclusive,+ sourceStart: sourceOffset + absoluteStart,+ sourceEnd: sourceOffset + absoluteStart + raw.length,+ });+ }+ };++ while (offset < scriptSource.length) {+ if (scriptSource.startsWith("<!--", offset)) {+ const end = scriptSource.indexOf("-->", offset + 4);+ if (end < 0) fail("script_unclosed_comment", "Unclosed Script comment.", location(offset));+ const comment = scriptSource.slice(offset, end + 3);+ lineStart = comment.endsWith("\n") || lineStart;+ offset = end + 3;+ continue;+ }++ const segmentOpen = SEGMENT_OPEN.exec(scriptSource.slice(offset));+ if (segmentOpen) {+ if (current) {+ fail("script_nested_segment", "Segment elements cannot nest.", location(offset));+ }+ const id = segmentOpen[1] ?? segmentOpen[2];+ if (!id || !SEGMENT_ID.test(id)) {+ fail("script_invalid_segment_id", `Invalid Segment id "${id ?? ""}".`, location(offset));+ }+ if (segments.some((segment) => segment.id === id)) {+ fail("script_duplicate_segment_id", `Duplicate Segment id "${id}".`, location(offset));+ }+ current = {+ id,+ index: segments.length,+ atoms: [],+ tokenStart: tokens.length,+ sourceStart: sourceOffset + offset,+ };+ offset += segmentOpen[0].length;+ lineStart = true;+ if (segmentOpen[3] === "/") {+ segments.push({+ ...current,+ tokenEnd: tokens.length,+ sourceEnd: sourceOffset + offset,+ });+ current = undefined;+ structuralCut += 1;+ }+ continue;+ }++ const segmentClose = SEGMENT_CLOSE.exec(scriptSource.slice(offset));+ if (segmentClose) {+ if (!current) {+ fail("script_segment_close_without_open", "Unexpected </segment>.", location(offset));+ }+ offset += segmentClose[0].length;+ segments.push({+ ...current,+ tokenEnd: tokens.length,+ sourceEnd: sourceOffset + offset,+ });+ current = undefined;+ structuralCut += 1;+ lineStart = true;+ continue;+ }++ const marker = parseMarker(scriptSource, offset);+ if (marker) {+ if (!TEMPORAL_ID.test(marker.id)) {+ fail("script_invalid_temporal_id", `Invalid temporal id "${marker.id}".`, location(offset));+ }+ addMarker(marker, offset);+ offset += marker.length;+ continue;+ }++ if (scriptSource[offset] === "@") {+ fail(+ "script_invalid_marker",+ "Unescaped @ must begin a valid Selection or Moment marker.",+ location(offset),+ );+ }++ if (scriptSource[offset] === "<" && current) {+ const safeEnd = findUnescaped(scriptSource, ">", offset + 1);+ if (safeEnd < 0) fail("script_unclosed_angle", "Unclosed Script angle construct.", location(offset));+ const inside = scriptSource.slice(offset + 1, safeEnd);+ const pipe = findUnescaped(inside, "|");+ if (pipe >= 0) {+ const display = literalString(inside.slice(0, pipe), offset + 1, true);+ const speech = inside.slice(pipe + 1);+ if (!speech.replace(/~?@\/?[A-Za-z_][A-Za-z0-9_.-]*!?~?/gu, "").trim()) {+ fail("script_dual_speech_empty", "Dual Text speech side must not be empty.", location(offset));+ }+ consumeSpeechSide(speech, offset + 1 + pipe + 1, display);+ offset = safeEnd + 1;+ lineStart = false;+ continue;+ }+ if (lineStart && ROLE_LABEL.test(inside)) {+ const after = scriptSource.slice(safeEnd + 1);+ if (!after.match(/^[^\S\n]*\S/u)) {+ fail(+ "script_role_empty_turn",+ `Role Cue <${inside}> must be followed by spoken content on the same logical line.`,+ location(offset),+ );+ }+ current.atoms.push({+ kind: "role",+ label: inside,+ start: sourceOffset + offset,+ end: sourceOffset + safeEnd + 1,+ });+ offset = safeEnd + 1;+ lineStart = false;+ continue;+ }+ fail(+ "script_unknown_angle_construct",+ `Unknown Script construct <${inside}>.`,+ location(offset),+ );+ }++ const textStart = offset;+ while (offset < scriptSource.length) {+ if (+ scriptSource.startsWith("<!--", offset)+ || scriptSource.startsWith("<segment", offset)+ || scriptSource.startsWith("</segment", offset)+ || parseMarker(scriptSource, offset)+ || scriptSource[offset] === "<"+ || scriptSource[offset] === "@"+ ) break;+ if (scriptSource[offset] === "\\") {+ if (scriptSource.startsWith("\\${", offset)) offset += 3;+ else offset += Math.min(2, scriptSource.length - offset);+ continue;+ }+ offset += 1;+ }+ const raw = scriptSource.slice(textStart, offset);+ for (const piece of literalPieces(raw, textStart)) {+ addText(piece.value, piece.value, piece.start, piece.end);+ }+ const lastNewline = raw.lastIndexOf("\n");+ if (lastNewline >= 0) {+ lineStart = raw.slice(lastNewline + 1).trim() === "";+ } else if (raw.trim()) {+ lineStart = false;+ }+ }++ if (current) {+ fail("script_unclosed_segment", `Segment "${current.id}" is not closed.`);+ }+ const dangling = [...openSelections.entries()].flatMap(([id, opens]) =>+ opens.map((open) => ({ id, open })));+ if (dangling.length) {+ fail(+ "script_selection_unclosed",+ `Selection "${dangling[0]?.id ?? "unknown"}" is not closed.`,+ );+ }+ if (!segments.length) fail("script_segment_cardinality", "Script requires at least one Segment.");++ const speechSegments: string[] = [];+ const captionSegments: string[] = [];+ const dialogueTurns: string[] = [];+ for (const segment of segments) {+ const speechParts: string[] = [];+ const captionParts: string[] = [];+ let activeRole: string | undefined;+ let turnParts: string[] = [];+ const flushTurn = (): void => {+ const body = joinProjection(turnParts);+ if (!body) return;+ dialogueTurns.push(activeRole ? `${activeRole}: ${body}` : body);+ turnParts = [];+ };+ for (const atom of segment.atoms) {+ if (atom.kind === "role") {+ flushTurn();+ activeRole = atom.label;+ } else {+ speechParts.push(atom.speech);+ captionParts.push(atom.caption);+ turnParts.push(atom.speech);+ }+ }+ flushTurn();+ const speech = joinProjection(speechParts);+ const caption = joinProjection(captionParts);+ if (speech) speechSegments.push(speech);+ if (caption) captionSegments.push(caption);+ }++ return {+ segments,+ tokens,+ selections,+ moments,+ captionAtoms,+ projections: {+ dialogue: dialogueTurns.join("\n"),+ speech: speechSegments.join("\n"),+ caption: captionSegments.join("\n"),+ },+ };+}diff --git a/src/source/modules.ts b/src/source/modules.tsnew file mode 100644index 00000000..b2ce8318--- /dev/null+++ b/src/source/modules.ts@@ -0,0 +1,267 @@+import { readFile } from "node:fs/promises";+import { dirname, extname, isAbsolute, resolve } from "node:path";+import { pathToFileURL } from "node:url";+import { fail } from "../diagnostics.js";+import type {+ AttributeValue,+ Reference,+ SourceDocument,+ SourceElement,+ SourceModuleRecord,+ SourceNode,+} from "../model.js";+import { sha256 } from "../util.js";+import { attributeString, childElements } from "./query.js";+import { parseDocument, parseRootSource } from "./parse-document.js";++type LoadedContent = {+ declarations: SourceElement[];+ kernelImports: SourceElement[];+ modules: SourceModuleRecord[];+};++function isExternalSource(value: string): boolean {+ return /^[A-Za-z][A-Za-z0-9+.-]*:/u.test(value);+}++function resolvedImport(moduleFile: string, from: string): string {+ return isExternalSource(from) || isAbsolute(from)+ ? from+ : resolve(dirname(moduleFile), from);+}++function canonicalUri(value: string): string {+ return isExternalSource(value) ? value : pathToFileURL(resolve(value)).href;+}++function cloneReference(+ value: AttributeValue,+ qualify: (path: string) => string,+): AttributeValue {+ if (!value || typeof value !== "object" || value.kind !== "reference") return value;+ return { kind: "reference", path: qualify(value.path) } satisfies Reference;+}++function cloneNode(+ node: SourceNode,+ args: {+ moduleFile: string;+ prefix: string;+ localDeclarations: Set<string>;+ importedNamespaces: Set<string>;+ topLevel: boolean;+ },+): SourceNode {+ if (node.kind === "text") return { ...node };+ const qualify = (path: string): string => {+ if (path.startsWith("script.")) {+ fail(+ "content_script_dependency",+ `Content module ${args.moduleFile} cannot depend on importer Script reference "${path}".`,+ );+ }+ const owner = path.split(".")[0] ?? "";+ if (args.localDeclarations.has(owner) || args.importedNamespaces.has(owner)) {+ return `${args.prefix}${path}`;+ }+ return path;+ };+ const attributes = Object.fromEntries(+ Object.entries(node.attributes).map(([name, value]) => [+ name,+ cloneReference(value, qualify),+ ]),+ );+ const localId = args.topLevel && typeof node.attributes.id === "string"+ ? node.attributes.id+ : undefined;+ if (localId) attributes.id = `${args.prefix}${localId}`;+ if (+ args.topLevel+ && ["image", "video", "audio"].includes(node.name)+ && typeof attributes.src === "string"+ && !isAbsolute(attributes.src)+ && !isExternalSource(attributes.src)+ ) {+ attributes.src = resolve(dirname(args.moduleFile), attributes.src);+ }+ return {+ ...node,+ attributes,+ children: node.children.map((child) => cloneNode(child, {+ ...args,+ topLevel: false,+ })),+ origin: {+ file: args.moduleFile,+ ...(localId ? { localId } : {}),+ },+ };+}++function absoluteImport(element: SourceElement, moduleFile: string): SourceElement {+ const from = attributeString(element, "from");+ return {+ ...element,+ attributes: {+ ...element.attributes,+ from: resolvedImport(moduleFile, from),+ },+ origin: { file: moduleFile },+ };+}++async function loadContentModule(+ file: string,+ prefix: string,+ stack: string[],+): Promise<LoadedContent> {+ const absolute = resolve(file);+ if (stack.includes(absolute)) {+ fail(+ "content_import_cycle",+ `Content import cycle: ${[...stack, absolute].join(" -> ")}`,+ );+ }+ const source = await readFile(absolute, "utf8");+ const root = parseRootSource(absolute, source);+ if (root.name !== "content") {+ fail("content_root", `${absolute} must use a <content> root.`);+ }+ const imports = childElements(root, "import");+ const dependencies = imports.map((element) =>+ canonicalUri(resolvedImport(absolute, attributeString(element, "from"))));+ const declarations = childElements(root).filter((element) => element.name !== "import");+ const localDeclarations = new Set(declarations.map((element) => {+ const id = element.attributes.id;+ if (typeof id !== "string") {+ fail("content_declaration_id", `${absolute} contains <${element.name}> without id.`);+ }+ return id;+ }));+ const importedNamespaces = new Set<string>();+ const nested: LoadedContent[] = [];+ const kernelImports: SourceElement[] = [];+ for (const element of imports) {+ const from = attributeString(element, "from");+ const extension = extname(from);+ if (extension === ".svk") {+ kernelImports.push(absoluteImport(element, absolute));+ continue;+ }+ if (extension === ".svs") {+ fail(+ "content_sheet_import_unsupported",+ `${absolute} imports ${from}; sheet imports inside .svc are not enabled yet.`,+ );+ }+ if (extension !== ".svc") {+ fail("content_import_type", `${absolute} imports unsupported module ${from}.`);+ }+ const alias = element.attributes.as;+ if (alias !== undefined && typeof alias !== "string") {+ fail("content_import_alias", `${absolute} import alias must be a string.`);+ }+ const namespace = alias ?? "";+ if (namespace) importedNamespaces.add(namespace);+ nested.push(await loadContentModule(+ resolve(dirname(absolute), from),+ `${prefix}${namespace ? `${namespace}.` : ""}`,+ [...stack, absolute],+ ));+ }+ const cloned = declarations.map((element) => cloneNode(element, {+ moduleFile: absolute,+ prefix,+ localDeclarations,+ importedNamespaces,+ topLevel: true,+ }) as SourceElement);+ return {+ declarations: [...nested.flatMap((item) => item.declarations), ...cloned],+ kernelImports: [+ ...nested.flatMap((item) => item.kernelImports),+ ...kernelImports,+ ],+ modules: [+ {+ kind: "svc",+ uri: canonicalUri(absolute),+ contentHash: sha256(source),+ dependencies,+ },+ ...nested.flatMap((item) => item.modules),+ ],+ };+}++function uniqueKernelImports(elements: SourceElement[]): SourceElement[] {+ const output: SourceElement[] = [];+ const seen = new Set<string>();+ for (const element of elements) {+ const from = attributeString(element, "from");+ if (seen.has(from)) continue;+ seen.add(from);+ output.push(element);+ }+ return output;+}++export async function loadSourceClosure(file: string): Promise<SourceDocument> {+ const document = await parseDocument(file);+ const localChildren: SourceNode[] = [];+ const importedDeclarations: SourceElement[] = [];+ const importedKernels: SourceElement[] = [];+ const modules: SourceModuleRecord[] = [{+ kind: "svml",+ uri: canonicalUri(document.file),+ contentHash: sha256(document.source),+ dependencies: childElements(document.root, "import").map((element) =>+ canonicalUri(resolvedImport(document.file, attributeString(element, "from")))),+ }];+ for (const node of document.root.children) {+ if (node.kind !== "element" || node.name !== "import") {+ localChildren.push(node.kind === "element"+ ? {+ ...node,+ origin: {+ file: document.file,+ ...(typeof node.attributes.id === "string"+ ? { localId: node.attributes.id }+ : {}),+ },+ }+ : node);+ continue;+ }+ const from = attributeString(node, "from");+ if (extname(from) !== ".svc") {+ localChildren.push(absoluteImport(node, document.file));+ continue;+ }+ const alias = node.attributes.as;+ if (alias !== undefined && typeof alias !== "string") {+ fail("content_import_alias", `${document.file} import alias must be a string.`);+ }+ const loaded = await loadContentModule(+ resolve(dirname(document.file), from),+ typeof alias === "string" && alias ? `${alias}.` : "",+ [],+ );+ importedDeclarations.push(...loaded.declarations);+ importedKernels.push(...loaded.kernelImports);+ modules.push(...loaded.modules);+ }+ return {+ ...document,+ root: {+ ...document.root,+ children: [+ ...uniqueKernelImports(importedKernels),+ ...localChildren,+ ...importedDeclarations,+ ],+ },+ modules: [...new Map(modules.map((module) => [module.uri, module])).values()],+ };+}diff --git a/src/source/parse-document.ts b/src/source/parse-document.tsnew file mode 100644index 00000000..dc1a45c4--- /dev/null+++ b/src/source/parse-document.ts@@ -0,0 +1,282 @@+import { readFile } from "node:fs/promises";+import { resolve } from "node:path";+import { fail, sourceLocation } from "../diagnostics.js";+import type {+ AttributeValue,+ SourceDocument,+ SourceElement,+ SourceNode,+} from "../model.js";++type Cursor = {+ file: string;+ source: string;+ offset: number;+};++const NAME = /[A-Za-z_][A-Za-z0-9_.:-]*/y;++function skipSpace(cursor: Cursor): void {+ while (/\s/u.test(cursor.source[cursor.offset] ?? "")) cursor.offset += 1;+}++function parseName(cursor: Cursor): string {+ NAME.lastIndex = cursor.offset;+ const match = NAME.exec(cursor.source);+ if (!match) {+ fail(+ "source_expected_name",+ "Expected an element or attribute name.",+ sourceLocation(cursor.file, cursor.source, cursor.offset),+ );+ }+ cursor.offset = NAME.lastIndex;+ return match[0];+}++function parseQuoted(cursor: Cursor): string {+ const quote = cursor.source[cursor.offset];+ if (quote !== '"' && quote !== "'") {+ fail(+ "source_expected_quoted_value",+ "Attribute literals must be quoted.",+ sourceLocation(cursor.file, cursor.source, cursor.offset),+ );+ }+ const start = ++cursor.offset;+ while (cursor.offset < cursor.source.length && cursor.source[cursor.offset] !== quote) {+ cursor.offset += 1;+ }+ if (cursor.source[cursor.offset] !== quote) {+ fail(+ "source_unclosed_attribute",+ "Unclosed quoted attribute value.",+ sourceLocation(cursor.file, cursor.source, start - 1),+ );+ }+ const value = cursor.source.slice(start, cursor.offset);+ cursor.offset += 1;+ return value;+}++function parseReference(cursor: Cursor): AttributeValue {+ const start = ++cursor.offset;+ while (cursor.offset < cursor.source.length && cursor.source[cursor.offset] !== "}") {+ cursor.offset += 1;+ }+ if (cursor.source[cursor.offset] !== "}") {+ fail(+ "source_unclosed_reference",+ "Unclosed reference attribute.",+ sourceLocation(cursor.file, cursor.source, start - 1),+ );+ }+ const path = cursor.source.slice(start, cursor.offset).trim();+ cursor.offset += 1;+ if (!/^[A-Za-z_][A-Za-z0-9_.:-]*$/u.test(path)) {+ fail(+ "source_invalid_reference",+ `Invalid reference path "${path}".`,+ sourceLocation(cursor.file, cursor.source, start),+ );+ }+ return { kind: "reference", path };+}++function literalValue(raw: string): AttributeValue {+ if (raw === "true") return true;+ if (raw === "false") return false;+ if (/^-?(?:\d+\.?\d*|\.\d+)$/u.test(raw)) return Number(raw);+ return raw;+}++function parseAttributes(cursor: Cursor): Record<string, AttributeValue> {+ const attributes: Record<string, AttributeValue> = {};+ while (cursor.offset < cursor.source.length) {+ skipSpace(cursor);+ const next = cursor.source[cursor.offset];+ if (next === ">" || (next === "/" && cursor.source[cursor.offset + 1] === ">")) break;+ const name = parseName(cursor);+ if (Object.hasOwn(attributes, name)) {+ fail(+ "source_duplicate_attribute",+ `Duplicate attribute "${name}".`,+ sourceLocation(cursor.file, cursor.source, cursor.offset),+ );+ }+ skipSpace(cursor);+ if (cursor.source[cursor.offset] !== "=") {+ fail(+ "source_expected_attribute_equals",+ `Attribute "${name}" requires "=".`,+ sourceLocation(cursor.file, cursor.source, cursor.offset),+ );+ }+ cursor.offset += 1;+ skipSpace(cursor);+ const value = cursor.source[cursor.offset] === "{"+ ? parseReference(cursor)+ : literalValue(parseQuoted(cursor));+ attributes[name] = value;+ }+ return attributes;+}++function skipComment(cursor: Cursor): boolean {+ if (!cursor.source.startsWith("<!--", cursor.offset)) return false;+ const end = cursor.source.indexOf("-->", cursor.offset + 4);+ if (end < 0) {+ fail(+ "source_unclosed_comment",+ "Unclosed source comment.",+ sourceLocation(cursor.file, cursor.source, cursor.offset),+ );+ }+ cursor.offset = end + 3;+ return true;+}++function parseElement(cursor: Cursor): SourceElement {+ const start = cursor.offset;+ if (cursor.source[cursor.offset] !== "<" || cursor.source[cursor.offset + 1] === "/") {+ fail(+ "source_expected_element",+ "Expected an opening element.",+ sourceLocation(cursor.file, cursor.source, cursor.offset),+ );+ }+ cursor.offset += 1;+ const name = parseName(cursor);+ const attributes = parseAttributes(cursor);+ skipSpace(cursor);+ if (cursor.source.startsWith("/>", cursor.offset)) {+ cursor.offset += 2;+ return { kind: "element", name, attributes, children: [], start, end: cursor.offset };+ }+ if (cursor.source[cursor.offset] !== ">") {+ fail(+ "source_expected_tag_end",+ `Opening <${name}> is not closed.`,+ sourceLocation(cursor.file, cursor.source, cursor.offset),+ );+ }+ cursor.offset += 1;++ const children: SourceNode[] = [];+ if (name === "script") {+ const close = cursor.source.indexOf("</script>", cursor.offset);+ if (close < 0) {+ fail(+ "source_unclosed_script",+ "The <script> element is not closed.",+ sourceLocation(cursor.file, cursor.source, start),+ );+ }+ children.push({+ kind: "text",+ value: cursor.source.slice(cursor.offset, close),+ start: cursor.offset,+ end: close,+ });+ cursor.offset = close + "</script>".length;+ return { kind: "element", name, attributes, children, start, end: cursor.offset };+ }++ while (cursor.offset < cursor.source.length) {+ if (skipComment(cursor)) continue;+ if (cursor.source.startsWith("</", cursor.offset)) {+ cursor.offset += 2;+ const closeName = parseName(cursor);+ skipSpace(cursor);+ if (cursor.source[cursor.offset] !== ">") {+ fail(+ "source_expected_tag_end",+ `Closing </${closeName}> is not closed.`,+ sourceLocation(cursor.file, cursor.source, cursor.offset),+ );+ }+ cursor.offset += 1;+ if (closeName !== name) {+ fail(+ "source_mismatched_close",+ `Expected </${name}>, received </${closeName}>.`,+ sourceLocation(cursor.file, cursor.source, cursor.offset),+ );+ }+ return { kind: "element", name, attributes, children, start, end: cursor.offset };+ }+ if (cursor.source[cursor.offset] === "<") {+ children.push(parseElement(cursor));+ continue;+ }+ const textStart = cursor.offset;+ const next = cursor.source.indexOf("<", cursor.offset);+ cursor.offset = next < 0 ? cursor.source.length : next;+ children.push({+ kind: "text",+ value: cursor.source.slice(textStart, cursor.offset),+ start: textStart,+ end: cursor.offset,+ });+ }+ fail(+ "source_unclosed_element",+ `The <${name}> element is not closed.`,+ sourceLocation(cursor.file, cursor.source, start),+ );+}++export function parseRootSource(file: string, source: string): SourceElement {+ const cursor: Cursor = { file, source, offset: 0 };+ skipSpace(cursor);+ while (skipComment(cursor)) skipSpace(cursor);+ const root = parseElement(cursor);+ skipSpace(cursor);+ while (skipComment(cursor)) skipSpace(cursor);+ if (cursor.offset !== source.length) {+ fail(+ "source_trailing_content",+ "Only comments and whitespace may follow the root element.",+ sourceLocation(file, source, cursor.offset),+ );+ }+ return root;+}++export function parseDocumentSource(file: string, source: string): SourceDocument {+ source = source.replace(/\r\n?/gu, "\n").normalize("NFC");+ const root = parseRootSource(file, source);+ if (root.name !== "svml") {+ fail(+ "source_invalid_root",+ `Expected <svml>, received <${root.name}>.`,+ sourceLocation(file, source, root.start),+ );+ }+ const scripts = root.children.filter(+ (node): node is SourceElement => node.kind === "element" && node.name === "script",+ );+ if (scripts.length !== 1) {+ fail(+ "source_script_cardinality",+ `Expected exactly one <script>, received ${scripts.length}.`,+ sourceLocation(file, source, root.start),+ );+ }+ const scriptText = scripts[0]?.children[0];+ if (!scriptText || scriptText.kind !== "text") {+ fail("source_script_missing_text", "The <script> body could not be read.");+ }+ return {+ file,+ source,+ root,+ scriptSource: scriptText.value,+ scriptOffset: scriptText.start,+ };+}++export async function parseDocument(file: string): Promise<SourceDocument> {+ const absolute = resolve(file);+ return parseDocumentSource(absolute, await readFile(absolute, "utf8"));+}diff --git a/src/source/query.ts b/src/source/query.tsnew file mode 100644index 00000000..284fa805--- /dev/null+++ b/src/source/query.ts@@ -0,0 +1,71 @@+import type { AttributeValue, SourceElement, SourceNode } from "../model.js";++export function childElements(element: SourceElement, name?: string): SourceElement[] {+ return element.children.filter(+ (child): child is SourceElement =>+ child.kind === "element" && (name === undefined || child.name === name),+ );+}++export function textContent(element: SourceElement): string {+ return element.children+ .map((child) => child.kind === "text" ? child.value : textContent(child))+ .join("");+}++export function attributeString(+ element: SourceElement,+ name: string,+ fallback?: string,+): string {+ const value = element.attributes[name];+ if (typeof value === "string") return value;+ if (value === undefined && fallback !== undefined) return fallback;+ throw new Error(`<${element.name}> requires string attribute "${name}"`);+}++export function attributeNumber(+ element: SourceElement,+ name: string,+ fallback?: number,+): number {+ const value = element.attributes[name];+ if (typeof value === "number" && Number.isFinite(value)) return value;+ if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) {+ return Number(value);+ }+ if (value === undefined && fallback !== undefined) return fallback;+ throw new Error(`<${element.name}> requires numeric attribute "${name}"`);+}++export function attributeBoolean(+ element: SourceElement,+ name: string,+ fallback?: boolean,+): boolean {+ const value = element.attributes[name];+ if (typeof value === "boolean") return value;+ if (value === undefined && fallback !== undefined) return fallback;+ throw new Error(`<${element.name}> requires boolean attribute "${name}"`);+}++export function attributeReference(element: SourceElement, name: string): string {+ const value = element.attributes[name];+ if (value && typeof value === "object" && value.kind === "reference") return value.path;+ throw new Error(`<${element.name}> requires reference attribute "${name}"`);+}++export function referencePath(value: AttributeValue | undefined): string | undefined {+ return value && typeof value === "object" && value.kind === "reference"+ ? value.path+ : undefined;+}++export function walkElements(nodes: SourceNode[]): SourceElement[] {+ const output: SourceElement[] = [];+ for (const node of nodes) {+ if (node.kind !== "element") continue;+ output.push(node, ...walkElements(node.children));+ }+ return output;+}diff --git a/src/source/styles.ts b/src/source/styles.tsnew file mode 100644index 00000000..a858e893--- /dev/null+++ b/src/source/styles.ts@@ -0,0 +1,264 @@+import { readFile } from "node:fs/promises";+import { extname, resolve } from "node:path";+import { pathToFileURL } from "node:url";+import { fail } from "../diagnostics.js";+import type {+ AttributeValue,+ ParameterSource,+ SourceDocument,+ SourceElement,+ SourceNode,+} from "../model.js";+import type {+ KernelManifest,+ KernelParameter,+ KernelRegistry,+} from "../kernel.js";+import { attributeString, childElements, textContent } from "./query.js";+import { parseRootSource } from "./parse-document.js";+import { sha256 } from "../util.js";++type StyleRule = {+ selector: string;+ className: string;+ properties: Array<{ name: string; raw: string }>;+ source: string;+};++type Sheet = {+ binding: string;+ file: string;+ rules: StyleRule[];+ contentHash: string;+};++function parseGenericLiteral(raw: string): AttributeValue {+ const value = raw.trim();+ const quoted = /^(?:"([^"]*)"|'([^']*)')$/u.exec(value);+ if (quoted) return quoted[1] ?? quoted[2] ?? "";+ if (value === "true") return true;+ if (value === "false") return false;+ if (/^-?(?:\d+\.?\d*|\.\d+)$/u.test(value)) return Number(value);+ return value;+}++function typedValue(+ raw: string,+ parameter: KernelParameter | undefined,+ source: string,+): AttributeValue {+ const value = parseGenericLiteral(raw);+ if (!parameter) return value;+ if (parameter.type === "number") {+ if (typeof value !== "number" || !Number.isFinite(value)) {+ fail("style_parameter_type", `${source} expects numeric ${parameter.styleName}.`);+ }+ } else if (parameter.type === "boolean") {+ if (typeof value !== "boolean") {+ fail("style_parameter_type", `${source} expects boolean ${parameter.styleName}.`);+ }+ } else if (typeof value !== "string") {+ fail("style_parameter_type", `${source} expects string ${parameter.styleName}.`);+ }+ return value;+}++function parseRules(file: string, root: SourceElement): StyleRule[] {+ const source = textContent(root).replaceAll(/\/\*[\s\S]*?\*\//gu, "");+ const rules: StyleRule[] = [];+ const rulePattern = /([A-Za-z_][A-Za-z0-9_:-]*)\.([A-Za-z_][A-Za-z0-9_-]*)\s*\{([^{}]*)\}/gu;+ let consumed = "";+ let lastEnd = 0;+ for (const match of source.matchAll(rulePattern)) {+ const index = match.index ?? 0;+ consumed += source.slice(lastEnd, index).replace(/\s+/gu, "");+ lastEnd = index + match[0].length;+ const properties = (match[3] ?? "")+ .split(";")+ .map((statement) => statement.trim())+ .filter(Boolean)+ .map((statement) => {+ const colon = statement.indexOf(":");+ if (colon <= 0) {+ fail("style_declaration", `${file} has invalid declaration "${statement}".`);+ }+ const name = statement.slice(0, colon).trim();+ const raw = statement.slice(colon + 1).trim();+ if (!/^[A-Za-z_][A-Za-z0-9_-]*$/u.test(name) || !raw) {+ fail("style_declaration", `${file} has invalid declaration "${statement}".`);+ }+ return { name, raw };+ });+ rules.push({+ selector: match[1]!,+ className: match[2]!,+ properties,+ source: `${file}:${match[1]}.${match[2]}`,+ });+ }+ consumed += source.slice(lastEnd).replace(/\s+/gu, "");+ if (consumed) {+ fail("style_syntax", `${file} contains unsupported sheet syntax near "${consumed.slice(0, 40)}".`);+ }+ const keys = rules.map((rule) => `${rule.selector}.${rule.className}`);+ if (new Set(keys).size !== keys.length) {+ fail("style_duplicate_rule", `${file} repeats a selector/class rule.`);+ }+ return rules;+}++async function loadSheets(document: SourceDocument): Promise<Sheet[]> {+ const sheets: Sheet[] = [];+ for (const element of childElements(document.root, "import")) {+ const from = attributeString(element, "from");+ if (extname(from) !== ".svs") continue;+ const file = resolve(from);+ const source = await readFile(file, "utf8");+ const root = parseRootSource(file, source);+ if (root.name !== "sheet") fail("style_root", `${file} must use a <sheet> root.`);+ const id = root.attributes.id;+ const alias = element.attributes.as;+ if (alias !== undefined && typeof alias !== "string") {+ fail("style_import_alias", `${document.file} sheet alias must be a string.`);+ }+ if (typeof id !== "string" || !id) fail("style_sheet_id", `${file} requires a sheet id.`);+ const binding = typeof alias === "string" && alias ? alias : id;+ sheets.push({+ binding,+ file,+ rules: parseRules(file, root),+ contentHash: sha256(source),+ });+ }+ if (new Set(sheets.map((sheet) => sheet.binding)).size !== sheets.length) {+ fail("style_duplicate_binding", "Imported .svs bindings must be unique.");+ }+ return sheets;+}++function findRule(+ token: string,+ element: SourceElement,+ sheets: Sheet[],+): StyleRule {+ const dot = token.indexOf(".");+ if (dot > 0) {+ const binding = token.slice(0, dot);+ const className = token.slice(dot + 1);+ const sheet = sheets.find((candidate) => candidate.binding === binding);+ if (!sheet) fail("style_unknown_binding", `Unknown style binding "${binding}".`);+ const rule = sheet.rules.find(+ (candidate) => candidate.selector === element.name && candidate.className === className,+ );+ if (!rule) {+ fail(+ "style_unknown_class",+ `${sheet.file} does not define ${element.name}.${className}.`,+ );+ }+ return rule;+ }+ const matches = sheets.flatMap((sheet) => sheet.rules.filter(+ (candidate) => candidate.selector === element.name && candidate.className === token,+ ));+ if (matches.length !== 1) {+ fail(+ "style_ambiguous_class",+ `Unqualified class "${token}" on <${element.name}> resolves to ${matches.length} rules.`,+ );+ }+ return matches[0]!;+}++function parameterFor(+ manifest: KernelManifest | undefined,+ styleName: string,+): KernelParameter | undefined {+ if (!manifest) return undefined;+ return manifest.parameters.find(+ (parameter) => parameter.styleName === styleName || parameter.name === styleName,+ );+}++function styleElement(+ element: SourceElement,+ sheets: Sheet[],+ kernels: KernelRegistry,+ ownerKernel?: KernelManifest,+): SourceElement {+ const manifest = kernels.get(element.name) ?? ownerKernel;+ const topLevelKernel = kernels.get(element.name);+ const classValue = element.attributes.class;+ if (classValue !== undefined && typeof classValue !== "string") {+ fail("style_class_type", `<${element.name}> class must be a string.`);+ }+ const attributes: Record<string, AttributeValue> = {};+ const parameterSources: Record<string, ParameterSource[]> = {};+ for (const token of (classValue ?? "").split(/\s+/u).filter(Boolean)) {+ const rule = findRule(token, element, sheets);+ for (const property of rule.properties) {+ const parameter = topLevelKernel+ ? parameterFor(topLevelKernel, property.name)+ : undefined;+ if (topLevelKernel && !parameter) {+ fail(+ "style_unknown_parameter",+ `${rule.source} configures unknown public parameter "${property.name}".`,+ );+ }+ const name = parameter?.name ?? property.name;+ const value = typedValue(property.raw, parameter, rule.source);+ attributes[name] = value;+ (parameterSources[name] ??= []).push({+ kind: "svs-class",+ source: rule.source,+ value,+ });+ }+ }+ for (const [name, value] of Object.entries(element.attributes)) {+ attributes[name] = value;+ if (name !== "class") {+ (parameterSources[name] ??= []).push({+ kind: "instance",+ source: element.origin?.file ?? "<source>",+ value,+ });+ }+ }+ return {+ ...element,+ attributes,+ parameterSources,+ children: element.children.map((child) => child.kind === "element"+ ? styleElement(child, sheets, kernels, manifest)+ : child),+ };+}++export async function applyStyleSheets(+ document: SourceDocument,+ kernels: KernelRegistry,+): Promise<SourceDocument> {+ const sheets = await loadSheets(document);+ if (!sheets.length) return document;+ return {+ ...document,+ root: {+ ...document.root,+ children: document.root.children.map((node: SourceNode) =>+ node.kind === "element" && !["import", "script"].includes(node.name)+ ? styleElement(node, sheets, kernels)+ : node),+ },+ modules: [+ ...(document.modules ?? []),+ ...sheets.map((sheet) => ({+ kind: "svs" as const,+ uri: pathToFileURL(sheet.file).href,+ contentHash: sheet.contentHash,+ dependencies: [],+ })),+ ],+ };+}diff --git a/src/util.ts b/src/util.tsnew file mode 100644index 00000000..4eda0aa8--- /dev/null+++ b/src/util.ts@@ -0,0 +1,48 @@+import { createHash } from "node:crypto";+import { dirname, relative, resolve, sep } from "node:path";++export function sha256(value: string | Uint8Array): string {+ return createHash("sha256").update(value).digest("hex");+}++export function portableFileIdentity(entryFile: string, targetFile: string): string {+ const path = relative(dirname(resolve(entryFile)), resolve(targetFile))+ .split(sep)+ .join("/");+ return `svml-file:${path.startsWith(".") ? path : `./${path}`}`;+}++export function normalizeWord(value: string): string {+ return value+ .normalize("NFKC")+ .toLocaleLowerCase("en")+ .replace(/[^\p{L}\p{M}\p{N}]+/gu, "");+}++export function asNumber(value: unknown, fallback?: number): number {+ if (typeof value === "number" && Number.isFinite(value)) return value;+ if (typeof value === "string" && value.trim() !== "") {+ const parsed = Number(value);+ if (Number.isFinite(parsed)) return parsed;+ }+ if (fallback !== undefined) return fallback;+ throw new Error(`expected finite number, received ${String(value)}`);+}++export function escapeHtml(value: string): string {+ return value+ .replaceAll("&", "&")+ .replaceAll("<", "<")+ .replaceAll(">", ">")+ .replaceAll('"', """)+ .replaceAll("'", "'");+}++export function stableJson(value: unknown): string {+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;+ if (value && typeof value === "object") {+ const record = value as Record<string, unknown>;+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(",")}}`;+ }+ return JSON.stringify(value);+}diff --git a/src/views.ts b/src/views.tsnew file mode 100644index 00000000..3753de35--- /dev/null+++ b/src/views.ts@@ -0,0 +1,78 @@+import type { Compilation } from "./compiler.js";+import type { PlanIR } from "./model.js";++export type CanvasView = {+ contract: "svml.canvas-view.v1";+ root: string;+ nodes: Array<+ | {+ id: string;+ identity: string;+ kind: "value";+ valueType: string;+ contentDigest?: string;+ }+ | {+ id: string;+ identity: string;+ kind: "kernel";+ kernel: string;+ executionDigest?: string;+ }+ >;+ edges: PlanIR["edges"];+};++export type TimelineView = {+ contract: "svml.timeline-view.v1";+ fps: number;+ durationFrames: number;+ words: Compilation["located"]["words"];+ segments: Compilation["located"]["segments"];+ selections: Compilation["located"]["selections"];+ moments: Compilation["located"]["moments"];+ captionCues: Compilation["located"]["captionCues"];+ visuals: Compilation["target"]["visuals"];+ audios: Compilation["target"]["audios"];+};++export function projectCanvas(plan: PlanIR): CanvasView {+ return {+ contract: "svml.canvas-view.v1",+ root: plan.root,+ nodes: [+ ...plan.values.map((value) => ({+ id: value.id,+ identity: value.identity,+ kind: "value" as const,+ valueType: value.type,+ ...(value.contentDigest ? { contentDigest: value.contentDigest } : {}),+ })),+ ...plan.instances.map((instance) => ({+ id: instance.id,+ identity: instance.identity,+ kind: "kernel" as const,+ kernel: instance.kernel,+ ...(instance.executionDigest+ ? { executionDigest: instance.executionDigest }+ : {}),+ })),+ ],+ edges: plan.edges,+ };+}++export function projectTimeline(compilation: Compilation): TimelineView {+ return {+ contract: "svml.timeline-view.v1",+ fps: compilation.located.fps,+ durationFrames: compilation.located.durationFrames,+ words: compilation.located.words,+ segments: compilation.located.segments,+ selections: compilation.located.selections,+ moments: compilation.located.moments,+ captionCues: compilation.located.captionCues,+ visuals: compilation.target.visuals,+ audios: compilation.target.audios,+ };+}diff --git a/stdlib/audio-track.svk b/stdlib/audio-track.svknew file mode 100644index 00000000..4eebf238--- /dev/null+++ b/stdlib/audio-track.svk@@ -0,0 +1,15 @@+<kernel name="audio-track" abi="1" implementation="./runtime/audio-track.mjs">+ <port name="item" direction="input" type="AudioItem" cardinality="one-or-more"/>+ <port name="track" direction="output" type="Track" cardinality="one"/>+ <child name="item" cardinality="one-or-more">+ <field name="id" type="id" required="true"/>+ <field name="source" type="Audio" required="true"/>+ <field name="during" type="SelectionSet|ProgramSpan" consume="each"/>+ <field name="at" type="MomentSet|ProgramPoint" consume="each"/>+ <field name="duration" type="string"/>+ <field name="volume" type="number"/>+ <field name="fadeIn" type="number"/>+ <field name="fadeOut" type="number"/>+ <field name="bus" type="string"/>+ </child>+</kernel>diff --git a/stdlib/broll-track.svk b/stdlib/broll-track.svknew file mode 100644index 00000000..18995248--- /dev/null+++ b/stdlib/broll-track.svk@@ -0,0 +1,55 @@+<kernel name="broll-track" abi="1" implementation="./runtime/broll-track.mjs">+ <param name="z" type="number"/>+ <port name="item" direction="input" type="BrollItem" cardinality="one-or-more"/>+ <port name="track" direction="output" type="Track" cardinality="one"/>+ <child name="item" cardinality="one-or-more">+ <field name="id" type="id" required="true"/>+ <field name="source" type="Image|Video" required="true"/>+ <field name="during" type="SelectionSet|ProgramSpan" consume="each"/>+ <field name="window" type="string"/>+ <field name="playback" type="string"/>+ <field name="mediaStart" type="number"/>+ <field name="sourceDuration" type="number"/>+ <field name="kind" type="string"/>+ <field name="zoom" type="number"/>+ <field name="audio" type="boolean|string"/>+ <field name="volume" type="number"/>+ <field name="x" type="number"/>+ <field name="y" type="number"/>+ <field name="width" type="number"/>+ <field name="height" type="number"/>+ <field name="fit" type="string"/>+ <field name="position" type="string"/>+ <field name="shape" type="string"/>+ <field name="radius" type="number"/>+ <field name="opacity" type="number"/>+ <field name="background" type="string"/>+ <child name="present" cardinality="zero-or-more">+ <field name="id" type="id" required="true"/>+ <field name="during" type="SelectionSet|ProgramSpan" consume="each"/>+ <field name="window" type="string"/>+ <field name="layer" type="number"/>+ <field name="x" type="number"/>+ <field name="y" type="number"/>+ <field name="width" type="number"/>+ <field name="height" type="number"/>+ <field name="fit" type="string"/>+ <field name="position" type="string"/>+ <field name="shape" type="string"/>+ <field name="radius" type="number"/>+ <field name="opacity" type="number"/>+ <field name="background" type="string"/>+ <field name="enter" type="string"/>+ <field name="exit" type="string"/>+ </child>+ </child>+ <child name="transition" cardinality="zero-or-more">+ <field name="from" type="id" required="true"/>+ <field name="to" type="id" required="true"/>+ <field name="kind" type="string"/>+ <field name="duration" type="string"/>+ <field name="cuePositionRatio" type="number"/>+ <field name="sound" type="Audio"/>+ <field name="volume" type="number"/>+ </child>+</kernel>diff --git a/stdlib/caption-track.svk b/stdlib/caption-track.svknew file mode 100644index 00000000..a077aa14--- /dev/null+++ b/stdlib/caption-track.svk@@ -0,0 +1,20 @@+<kernel name="caption-track" abi="1" implementation="./runtime/caption-track.mjs">+ <param name="z" type="number"/>+ <param name="x" type="number" default="0.37"/>+ <param name="y" type="number" default="0.54"/>+ <param name="width" type="number" default="0.64"/>+ <param name="maxWords" style="max-words" type="number" default="3"/>+ <param name="hold" type="number" default="0.08"/>+ <param name="cueFade" style="cue-fade" type="number" default="0.12"/>+ <param name="font" style="font-family" type="string" default="Poppins, Inter, Arial, sans-serif"/>+ <param name="size" style="font-size" type="number" default="50"/>+ <param name="weight" style="font-weight" type="number" default="800"/>+ <param name="tracking" style="letter-spacing" type="number" default="-1"/>+ <param name="color" style="fill" type="string" default="#ffffff"/>+ <param name="highlight" type="string" default="#ffd34d"/>+ <param name="strokeWidth" style="stroke-width" type="number" default="0.002"/>+ <param name="strokeColor" style="stroke-color" type="string" default="rgba(0,0,0,.82)"/>+ <param name="shadow" type="string" default="0 2px 9px rgba(0,0,0,.5), 0 0 2px rgba(0,0,0,.68)"/>+ <port name="script" direction="input" type="NarrativeIR" cardinality="one"/>+ <port name="track" direction="output" type="Track" cardinality="one"/>+</kernel>diff --git a/stdlib/film.svk b/stdlib/film.svknew file mode 100644index 00000000..d2ac17f2--- /dev/null+++ b/stdlib/film.svk@@ -0,0 +1,12 @@+<kernel name="film" abi="1" root="true" implementation="./runtime/film.mjs">+ <param name="width" type="number"/>+ <param name="height" type="number"/>+ <param name="fps" style="frame-rate" type="number"/>+ <param name="background" type="string" default="#000000"/>+ <port name="speech" direction="input" type="SpeechSpine" cardinality="one"/>+ <port name="track" direction="input" type="Track" cardinality="zero-or-more"/>+ <port name="document" direction="output" type="HyperframesDocument" cardinality="one"/>+ <child name="track" cardinality="zero-or-more">+ <field name="ref" type="Track" required="true"/>+ </child>+</kernel>diff --git a/stdlib/media-track.svk b/stdlib/media-track.svknew file mode 100644index 00000000..13fdeced--- /dev/null+++ b/stdlib/media-track.svk@@ -0,0 +1,42 @@+<kernel name="media-track" abi="1" implementation="./runtime/media-track.mjs">+ <param name="z" type="number"/>+ <port name="item" direction="input" type="MediaItem" cardinality="one-or-more"/>+ <port name="track" direction="output" type="Track" cardinality="one"/>+ <child name="item" cardinality="one-or-more">+ <field name="id" type="id" required="true"/>+ <field name="source" type="Image|Video" required="true"/>+ <field name="during" type="SelectionSet|ProgramSpan" consume="each"/>+ <field name="window" type="string"/>+ <field name="playback" type="string"/>+ <field name="mediaStart" type="number"/>+ <field name="sourceDuration" type="number"/>+ <field name="x" type="number"/>+ <field name="y" type="number"/>+ <field name="width" type="number"/>+ <field name="height" type="number"/>+ <field name="fit" type="string"/>+ <field name="position" type="string"/>+ <field name="shape" type="string"/>+ <field name="radius" type="number"/>+ <field name="opacity" type="number"/>+ <field name="background" type="string"/>+ <child name="present" cardinality="zero-or-more">+ <field name="id" type="id" required="true"/>+ <field name="during" type="SelectionSet|ProgramSpan" consume="each"/>+ <field name="window" type="string"/>+ <field name="layer" type="number"/>+ <field name="x" type="number"/>+ <field name="y" type="number"/>+ <field name="width" type="number"/>+ <field name="height" type="number"/>+ <field name="fit" type="string"/>+ <field name="position" type="string"/>+ <field name="shape" type="string"/>+ <field name="radius" type="number"/>+ <field name="opacity" type="number"/>+ <field name="background" type="string"/>+ <field name="enter" type="string"/>+ <field name="exit" type="string"/>+ </child>+ </child>+</kernel>diff --git a/stdlib/ranking-column.svk b/stdlib/ranking-column.svknew file mode 100644index 00000000..84f66d08--- /dev/null+++ b/stdlib/ranking-column.svk@@ -0,0 +1,24 @@+<kernel name="ranking-column" abi="1" implementation="./runtime/ranking-column.mjs">+ <param name="z" type="number"/>+ <param name="x" type="number" default="0"/>+ <param name="y" type="number" default="0.17"/>+ <param name="width" type="number" default="0.305"/>+ <param name="rowHeight" style="row-height" type="number" default="0.071"/>+ <param name="gap" type="number" default="0.011"/>+ <param name="stageX" style="stage-x" type="number" default="0.66"/>+ <param name="stageY" style="stage-y" type="number" default="0.73"/>+ <param name="stageSize" style="stage-size" type="number" default="0.33"/>+ <param name="appearGain" style="appear-gain" type="number" default="0.09"/>+ <param name="moveGain" style="move-gain" type="number" default="0.1"/>+ <port name="appearSound" direction="input" type="Audio" cardinality="zero-or-one"/>+ <port name="moveSound" direction="input" type="Audio" cardinality="zero-or-one"/>+ <port name="item" direction="input" type="RankingItem" cardinality="one-or-more"/>+ <port name="track" direction="output" type="Track" cardinality="one"/>+ <child name="item" cardinality="one-or-more">+ <field name="id" type="id" required="true"/>+ <field name="rank" type="number" required="true"/>+ <field name="image" type="Image" required="true"/>+ <field name="during" type="SelectionSet" consume="one" required="true"/>+ <field name="window" type="string"/>+ </child>+</kernel>diff --git a/stdlib/runtime/audio-track.mjs b/stdlib/runtime/audio-track.mjsnew file mode 100644index 00000000..77339779--- /dev/null+++ b/stdlib/runtime/audio-track.mjs@@ -0,0 +1,48 @@+import {+ durationSeconds,+ elements,+ material,+ numberAttr,+ resolveAttr,+ stringAttr,+ trackOutput,+} from "./helpers.mjs";++export default {+ abiVersion: "1",+ project(context) {+ const audios = [];+ for (const item of elements(context, "item")) {+ const id = stringAttr(item, "id");+ const source = material(resolveAttr(context, item, "source"), "audio");+ const ranges = item.attributes.at+ ? context.moment(item.attributes.at, "item.at").map((startFrame) => {+ const durationFrames = Math.max(+ 1,+ Math.round(durationSeconds(stringAttr(item, "duration")) * context.fps),+ );+ return {+ startFrame,+ endFrameExclusive: Math.min(+ context.located.durationFrames,+ startFrame + durationFrames,+ ),+ };+ })+ : context.selection(item.attributes.during ?? "full", "item.during");+ for (const [index, range] of ranges.entries()) {+ audios.push({+ id: `${context.instance.id}:${id}:${index}`,+ source: source.source,+ startFrame: range.startFrame,+ endFrameExclusive: range.endFrameExclusive,+ volume: numberAttr(item, "volume", 1),+ fadeInSec: numberAttr(item, "fadeIn", 0),+ fadeOutSec: numberAttr(item, "fadeOut", 0),+ bus: stringAttr(item, "bus", "music"),+ });+ }+ }+ return trackOutput([], audios);+ },+};diff --git a/stdlib/runtime/broll-track.mjs b/stdlib/runtime/broll-track.mjsnew file mode 100644index 00000000..9c2ed5a5--- /dev/null+++ b/stdlib/runtime/broll-track.mjs@@ -0,0 +1,190 @@+import {+ durationSeconds,+ elements,+ material,+ mediaTiming,+ numberAttr,+ presentationAnimation,+ presentationStyle,+ resolveItemPresentations,+ resolveAttr,+ stringAttr,+ trackOutput,+} from "./helpers.mjs";++function appendAnimation(fragment, name, duration) {+ fragment.style.animation = [+ fragment.style.animation,+ `${name} ${duration}s linear both`,+ ].filter(Boolean).join(", ");+}++export default {+ abiVersion: "1",+ project(context) {+ const z = numberAttr(context.element, "z");+ const visuals = [];+ const audios = [];+ const itemVisuals = new Map();+ const transitionOpacity = new Map();+ for (const item of elements(context, "item")) {+ const id = stringAttr(item, "id");+ const source = material(resolveAttr(context, item, "source"));+ const expectedKind = stringAttr(item, "kind", source.type === "Video" ? "video" : "image");+ if (String(source.type).toLowerCase() !== expectedKind.toLowerCase()) {+ throw new Error(`broll item "${id}" expected ${expectedKind}, received ${source.type}`);+ }+ const presentations = resolveItemPresentations(context, item, source);+ for (const [index, presentation] of presentations.entries()) {+ const range = presentation.range;+ const zoom = numberAttr(item, "zoom", 1);+ const keyframes = `svml-broll-${context.instance.id}-${id}-${index}`.replaceAll(/[^A-Za-z0-9_-]/gu, "-");+ const animation = presentationAnimation(+ presentation.element,+ range,+ context.fps,+ `${context.instance.id}-${id}-${presentation.id}-${index}`,+ );+ const duration = (range.endFrameExclusive - range.startFrame) / context.fps;+ const timing = source.type === "Video"+ ? mediaTiming(item, presentation, source, context.fps)+ : {};+ const fragment = {+ id: `${context.instance.id}:${id}:${index}`,+ kind: source.type === "Video" ? "video" : "image",+ source: source.source,+ startFrame: range.startFrame,+ endFrameExclusive: range.endFrameExclusive,+ z,+ layer: presentation.layer,+ muted: !(item.attributes.audio === true || item.attributes.audio === "source"),+ ...timing,+ style: {+ ...presentationStyle(presentation.element, item, { fit: "contain" }),+ "transform-origin": "50% 50%",+ animation: [+ `${keyframes} ${duration}s ease-in-out both`,+ animation.animation,+ ].filter(Boolean).join(", "),+ },+ css: [+ `@keyframes ${keyframes} { from { transform: scale(1); } to { transform: scale(${zoom}); } }`,+ animation.css,+ ].filter(Boolean).join("\n"),+ };+ visuals.push(fragment);+ const values = itemVisuals.get(id) ?? [];+ values.push(fragment);+ itemVisuals.set(id, values);+ }+ if (source.type === "Video" && (item.attributes.audio === true || item.attributes.audio === "source")) {+ const parents = new Map(presentations.map((presentation) => [+ presentation.parentIndex,+ presentation.parentRange,+ ]));+ for (const [parentIndex, range] of parents) {+ audios.push({+ id: `${context.instance.id}:${id}:${parentIndex}:audio`,+ source: source.source,+ startFrame: range.startFrame,+ endFrameExclusive: range.endFrameExclusive,+ mediaStartSec: numberAttr(item, "mediaStart", 0),+ volume: numberAttr(item, "volume", 1),+ bus: "source",+ });+ }+ }+ }+ const occupiedWindows = [];+ for (const [transitionIndex, transition] of elements(context, "transition").entries()) {+ const from = stringAttr(transition, "from");+ const to = stringAttr(transition, "to");+ const kind = stringAttr(transition, "kind", "crossfade");+ if (!["cut", "crossfade"].includes(kind)) {+ throw new Error(`broll transition "${kind}" is not available in projector ABI v1`);+ }+ const outgoingValues = itemVisuals.get(from) ?? [];+ const incomingValues = itemVisuals.get(to) ?? [];+ if (outgoingValues.length !== 1 || incomingValues.length !== 1) {+ throw new Error(`broll transition ${from} -> ${to} requires one resolved visual per item`);+ }+ if (kind === "cut") continue;+ const outgoing = outgoingValues[0];+ const incoming = incomingValues[0];+ const durationFrames = Math.max(+ 1,+ Math.round(durationSeconds(stringAttr(transition, "duration")) * context.fps),+ );+ const cueRatio = numberAttr(transition, "cuePositionRatio", 0);+ if (cueRatio < 0 || cueRatio > 1) {+ throw new Error(`broll transition cuePositionRatio must be between 0 and 1`);+ }+ const cue = incoming.startFrame;+ const startFrame = cue - Math.floor(durationFrames * cueRatio);+ const endFrameExclusive = startFrame + durationFrames;+ if (startFrame < 0 || endFrameExclusive > context.located.durationFrames) {+ throw new Error(`broll transition ${from} -> ${to} leaves the master timeline`);+ }+ if (occupiedWindows.some((window) =>+ startFrame < window.endFrameExclusive && endFrameExclusive > window.startFrame)) {+ throw new Error(`broll transition ${from} -> ${to} overlaps another transition`);+ }+ occupiedWindows.push({ startFrame, endFrameExclusive });+ outgoing.endFrameExclusive = Math.max(outgoing.endFrameExclusive, endFrameExclusive);+ incoming.startFrame = Math.min(incoming.startFrame, startFrame);+ if (incoming.mediaStartSec !== undefined && startFrame < cue) {+ incoming.mediaStartSec = Math.max(+ 0,+ incoming.mediaStartSec - (cue - startFrame) / context.fps,+ );+ }+ const outgoingState = transitionOpacity.get(outgoing) ?? {};+ const incomingState = transitionOpacity.get(incoming) ?? {};+ if (outgoingState.out || incomingState.in) {+ throw new Error(`broll transition repeats an item edge`);+ }+ outgoingState.out = { startFrame, endFrameExclusive };+ incomingState.in = { startFrame, endFrameExclusive };+ transitionOpacity.set(outgoing, outgoingState);+ transitionOpacity.set(incoming, incomingState);+ if (transition.attributes.sound) {+ const sound = material(resolveAttr(context, transition, "sound"), "audio");+ audios.push({+ id: `${context.instance.id}:transition:${transitionIndex}`,+ source: sound.source,+ startFrame,+ endFrameExclusive,+ volume: numberAttr(transition, "volume", 1),+ bus: "sfx",+ });+ }+ }+ for (const [fragment, state] of transitionOpacity) {+ const totalFrames = fragment.endFrameExclusive - fragment.startFrame;+ const points = new Map();+ points.set(0, state.in ? 0 : 1);+ points.set(100, state.out ? 0 : 1);+ if (state.in) {+ points.set((state.in.startFrame - fragment.startFrame) / totalFrames * 100, 0);+ points.set((state.in.endFrameExclusive - fragment.startFrame) / totalFrames * 100, 1);+ }+ if (state.out) {+ points.set((state.out.startFrame - fragment.startFrame) / totalFrames * 100, 1);+ points.set((state.out.endFrameExclusive - fragment.startFrame) / totalFrames * 100, 0);+ }+ const ordered = [...points].sort((left, right) => left[0] - right[0]);+ for (let index = 1; index < ordered.length; index += 1) {+ if (ordered[index][0] < ordered[index - 1][0]) {+ throw new Error(`broll transition windows are not monotonic`);+ }+ }+ const name = `svml-broll-transition-${fragment.id}`.replaceAll(/[^A-Za-z0-9_-]/gu, "-");+ fragment.css = `${fragment.css ?? ""}+@keyframes ${name} {+${ordered.map(([percent, opacity]) => `${percent}% { opacity:${opacity}; }`).join("\n")}+}`;+ appendAnimation(fragment, name, totalFrames / context.fps);+ }+ return trackOutput(visuals, audios);+ },+};diff --git a/stdlib/runtime/caption-track.mjs b/stdlib/runtime/caption-track.mjsnew file mode 100644index 00000000..85c9d95b--- /dev/null+++ b/stdlib/runtime/caption-track.mjs@@ -0,0 +1,136 @@+import { html, numberAttr, stringAttr, trackOutput } from "./helpers.mjs";++export default {+ abiVersion: "1",+ project(context) {+ const script = context.resolve(context.element.attributes.script);+ const located = script.located;+ const z = numberAttr(context.element, "z");+ const maxWords = Math.max(1, Math.round(numberAttr(context.element, "maxWords", 3)));+ const words = located.words;+ const atomsByStart = new Map(located.captionAtoms.map((atom) => [atom.startWord, atom]));+ const displayUnits = (startWord, endWordExclusive) => {+ const units = [];+ let index = startWord;+ while (index < endWordExclusive) {+ const atom = atomsByStart.get(index);+ if (atom) {+ if (atom.endWordExclusive > endWordExclusive) {+ throw new Error(`caption cue cuts through Dual Text atom "${atom.id}"`);+ }+ if (atom.display) {+ units.push({+ text: atom.display,+ startFrame: atom.startFrame,+ endFrameExclusive: atom.endFrameExclusive,+ });+ }+ index = atom.endWordExclusive;+ continue;+ }+ const word = words[index];+ if (word) units.push(word);+ index += 1;+ }+ return units;+ };+ const groups = located.captionCues?.map((cue) => ({+ cue,+ words: displayUnits(cue.startWord, cue.endWordExclusive),+ })) ?? [];+ if (groups.length === 0) {+ const units = displayUnits(0, words.length);+ for (let index = 0; index < units.length; index += maxWords) {+ groups.push({+ words: units.slice(index, index + maxWords),+ });+ }+ }+ const visuals = [];+ for (const [groupIndex, entry] of groups.entries()) {+ const group = entry.words;+ const nextCueStart = groups[groupIndex + 1]?.words[0]?.startFrame;+ for (const [activeIndex, word] of group.entries()) {+ const next = group[activeIndex + 1];+ const endFrameExclusive = next?.startFrame+ ?? Math.min(+ located.durationFrames,+ nextCueStart ?? located.durationFrames,+ word.endFrameExclusive + Math.round(numberAttr(context.element, "hold", 0.08) * context.fps),+ );+ const body = group.map((item, index) =>+ `<span class="${index === activeIndex ? "active" : ""}">${html(item.text)}</span>`).join("");+ const fragmentDuration = Math.max(+ 1 / context.fps,+ (endFrameExclusive - word.startFrame) / context.fps,+ );+ const fadeSec = Math.min(+ numberAttr(context.element, "cueFade", 0.12),+ fragmentDuration * 0.45,+ );+ const fadePercent = Math.min(45, fadeSec / fragmentDuration * 100);+ const animationName = `svml-caption-${context.instance.id}-${groupIndex}-${activeIndex}`+ .replaceAll(/[^A-Za-z0-9_-]/gu, "-");+ const first = activeIndex === 0;+ const last = activeIndex === group.length - 1;+ const opacityKeyframes = first && last+ ? `0% { opacity:0; } ${fadePercent}% { opacity:1; } ${100 - fadePercent}% { opacity:1; } 100% { opacity:0; }`+ : first+ ? `0% { opacity:0; } ${fadePercent}% { opacity:1; } 100% { opacity:1; }`+ : last+ ? `0% { opacity:1; } ${100 - fadePercent}% { opacity:1; } 100% { opacity:0; }`+ : "0%, 100% { opacity:1; }";+ visuals.push({+ id: `${context.instance.id}:g${groupIndex}:w${activeIndex}`,+ kind: "html",+ startFrame: word.startFrame,+ endFrameExclusive,+ z,+ html: `<div class="svml-caption-line">${body}</div>`,+ style: {+ left: `${numberAttr(context.element, "x", 0.37) * 100}%`,+ top: `${numberAttr(context.element, "y", 0.54) * 100}%`,+ width: `${numberAttr(context.element, "width", 0.64) * 100}%`,+ height: "auto",+ color: stringAttr(context.element, "color", "#ffffff"),+ "font-family": stringAttr(context.element, "font", "Poppins, Inter, Arial, sans-serif"),+ "font-size": `${numberAttr(context.element, "size", 50)}px`,+ "font-weight": numberAttr(context.element, "weight", 800),+ "line-height": 1.15,+ "letter-spacing": `${numberAttr(context.element, "tracking", -1)}px`,+ "text-align": "center",+ "-webkit-text-stroke": `${context.width * numberAttr(context.element, "strokeWidth", 0.002)}px ${stringAttr(context.element, "strokeColor", "rgba(0,0,0,.82)")}`,+ "paint-order": "stroke fill",+ "text-shadow": stringAttr(+ context.element,+ "shadow",+ "0 2px 9px rgba(0,0,0,.5), 0 0 2px rgba(0,0,0,.68)",+ ),+ animation: `${animationName} ${fragmentDuration}s linear both`,+ },+ css: `@keyframes ${animationName} { ${opacityKeyframes} }`,+ });+ }+ }+ const highlight = stringAttr(context.element, "highlight", "#ffd34d");+ const gap = Math.max(+ 12,+ Math.round(+ numberAttr(context.element, "size", 50)+ * (0.34 + Math.max(0, -numberAttr(context.element, "tracking", -1) / numberAttr(context.element, "size", 50))),+ ),+ );+ return trackOutput(visuals, [], [+ `.svml-caption-line .active { color: ${highlight}; }`,+ `.svml-caption-line {+ width: 100%;+ display: flex;+ justify-content: center;+ align-items: baseline;+ column-gap: ${gap}px;+ white-space: nowrap;+}`,+ ".svml-caption-line > span { display: inline-block; }",+ ]);+ },+};diff --git a/stdlib/runtime/film.mjs b/stdlib/runtime/film.mjsnew file mode 100644index 00000000..80187e75--- /dev/null+++ b/stdlib/runtime/film.mjs@@ -0,0 +1,47 @@+import { elements, numberAttr, resolveAttr, stringAttr } from "./helpers.mjs";++export default {+ abiVersion: "1",+ project(context) {+ const visuals = [];+ const audios = [];+ const styles = [];+ const speech = resolveAttr(context, context.element, "speech");+ const speechTrack = speech.track ?? speech.speech?.track;+ if (speechTrack) {+ visuals.push(...(speechTrack.visuals ?? []));+ audios.push(...(speechTrack.audios ?? []));+ styles.push(...(speechTrack.styles ?? []));+ } else if (speech.speech?.primaryAudio) {+ audios.push(...speech.speech.primaryAudio);+ } else if (speech.primaryAudio) {+ audios.push(...speech.primaryAudio);+ }+ for (const trackElement of elements(context, "track")) {+ const track = resolveAttr(context, trackElement, "ref");+ visuals.push(...(track.visuals ?? []));+ audios.push(...(track.audios ?? []));+ styles.push(...(track.styles ?? []));+ }+ const fps = numberAttr(context.element, "fps", context.fps);+ if (fps !== context.fps) {+ throw new Error(`film frame-rate ${fps} does not match Located clock ${context.fps}`);+ }+ return {+ outputs: {+ document: {+ contract: "svml.hyperframes-document.v1",+ id: context.instance.id,+ width: numberAttr(context.element, "width", context.width),+ height: numberAttr(context.element, "height", context.height),+ fps,+ durationFrames: context.located.durationFrames,+ background: stringAttr(context.element, "background", "#000000"),+ visuals,+ audios,+ styles,+ },+ },+ };+ },+};diff --git a/stdlib/runtime/helpers.mjs b/stdlib/runtime/helpers.mjsnew file mode 100644index 00000000..6b44645e--- /dev/null+++ b/stdlib/runtime/helpers.mjs@@ -0,0 +1,309 @@+export function elements(context, name) {+ return context.element.children.filter((node) => node.kind === "element" && node.name === name);+}++export function stringAttr(element, name, fallback) {+ const value = element.attributes[name];+ if (typeof value === "string") return value;+ if (value === undefined && fallback !== undefined) return fallback;+ throw new Error(`<${element.name}> requires string attribute "${name}"`);+}++export function numberAttr(element, name, fallback) {+ const value = element.attributes[name];+ if (typeof value === "number" && Number.isFinite(value)) return value;+ if (typeof value === "string" && value.trim() && Number.isFinite(Number(value))) return Number(value);+ if (value === undefined && fallback !== undefined) return fallback;+ throw new Error(`<${element.name}> requires numeric attribute "${name}"`);+}++export function boolAttr(element, name, fallback) {+ const value = element.attributes[name];+ if (typeof value === "boolean") return value;+ if (value === undefined && fallback !== undefined) return fallback;+ throw new Error(`<${element.name}> requires boolean attribute "${name}"`);+}++export function resolveAttr(context, element, name) {+ return context.resolve(element.attributes[name]);+}++export function material(value, expected) {+ if (!value || typeof value !== "object") throw new Error(`expected ${expected ?? "media"} material`);+ const type = value.type ?? value.kind;+ if (expected && type && String(type).toLowerCase() !== expected.toLowerCase()) {+ throw new Error(`expected ${expected}, received ${String(type)}`);+ }+ const source = value.absoluteSource ?? value.source;+ if (typeof source !== "string") throw new Error(`${expected ?? "media"} material has no source`);+ return { ...value, source };+}++function unitSeconds(raw) {+ const match = /^([+-]?\d+(?:\.\d+)?)(ms|s)$/u.exec(raw.trim());+ if (!match) throw new Error(`invalid relative time "${raw}"`);+ return Number(match[1]) * (match[2] === "ms" ? 0.001 : 1);+}++function endpoint(value, range) {+ const raw = value.trim();+ if (raw === "start") return range.startSec;+ if (raw === "end") return range.endSec;+ const match = /^(start|end)([+-]\d+(?:\.\d+)?(?:ms|s))$/u.exec(raw);+ if (!match) throw new Error(`invalid window endpoint "${value}"`);+ return (match[1] === "start" ? range.startSec : range.endSec) + unitSeconds(match[2]);+}++export function projectWindow(range, expression, fps) {+ if (!expression) return range;+ const parts = String(expression).split("..");+ if (parts.length !== 2) throw new Error(`invalid window "${expression}"`);+ const startSec = endpoint(parts[0], range);+ const endSec = endpoint(parts[1], range);+ const startFrame = Math.round(startSec * fps);+ const endFrameExclusive = Math.round(endSec * fps);+ if (endFrameExclusive < startFrame) throw new Error(`window "${expression}" resolves backwards`);+ return {+ startFrame,+ endFrameExclusive,+ startSec: startFrame / fps,+ endSec: endFrameExclusive / fps,+ };+}++export function html(value) {+ return String(value)+ .replaceAll("&", "&")+ .replaceAll("<", "<")+ .replaceAll(">", ">")+ .replaceAll('"', """)+ .replaceAll("'", "'");+}++export function trackOutput(visuals = [], audios = [], styles = []) {+ return {+ outputs: { track: { visuals, audios, styles } },+ visuals,+ audios,+ styles,+ };+}++export function intersectRange(left, right) {+ const startFrame = Math.max(left.startFrame, right.startFrame);+ const endFrameExclusive = Math.min(left.endFrameExclusive, right.endFrameExclusive);+ if (endFrameExclusive <= startFrame) return undefined;+ const fps = Math.round(+ (left.endFrameExclusive - left.startFrame) / Math.max(0.000001, left.endSec - left.startSec),+ );+ return {+ startFrame,+ endFrameExclusive,+ startSec: startFrame / fps,+ endSec: endFrameExclusive / fps,+ };+}++export function subtractRanges(base, cuts, fps) {+ const relevant = cuts+ .map((cut) => ({+ startFrame: Math.max(base.startFrame, cut.startFrame),+ endFrameExclusive: Math.min(base.endFrameExclusive, cut.endFrameExclusive),+ }))+ .filter((cut) => cut.endFrameExclusive > cut.startFrame)+ .sort((left, right) => left.startFrame - right.startFrame);+ const merged = [];+ for (const cut of relevant) {+ const previous = merged[merged.length - 1];+ if (previous && cut.startFrame <= previous.endFrameExclusive) {+ previous.endFrameExclusive = Math.max(previous.endFrameExclusive, cut.endFrameExclusive);+ } else {+ merged.push({ ...cut });+ }+ }+ const output = [];+ let cursor = base.startFrame;+ for (const cut of merged) {+ if (cut.startFrame > cursor) {+ output.push({+ startFrame: cursor,+ endFrameExclusive: cut.startFrame,+ startSec: cursor / fps,+ endSec: cut.startFrame / fps,+ });+ }+ cursor = Math.max(cursor, cut.endFrameExclusive);+ }+ if (cursor < base.endFrameExclusive) {+ output.push({+ startFrame: cursor,+ endFrameExclusive: base.endFrameExclusive,+ startSec: cursor / fps,+ endSec: base.endFrameExclusive / fps,+ });+ }+ return output;+}++function inherited(element, parent, name) {+ return element?.attributes[name] ?? parent?.attributes[name];+}++function inheritedNumber(element, parent, name, fallback) {+ const value = inherited(element, parent, name);+ if (value === undefined) return fallback;+ if (typeof value === "number" && Number.isFinite(value)) return value;+ if (typeof value === "string" && value.trim() && Number.isFinite(Number(value))) return Number(value);+ throw new Error(`<${element?.name ?? parent?.name}> requires numeric attribute "${name}"`);+}++function inheritedString(element, parent, name, fallback) {+ const value = inherited(element, parent, name);+ if (typeof value === "string") return value;+ if (value === undefined) return fallback;+ throw new Error(`<${element?.name ?? parent?.name}> requires string attribute "${name}"`);+}++export function presentationStyle(element, parent, defaults = {}) {+ const shape = inheritedString(element, parent, "shape", "rect");+ const radius = shape === "circle"+ ? "50%"+ : `${inheritedNumber(element, parent, "radius", 0)}px`;+ return {+ left: `${inheritedNumber(element, parent, "x", 0) * 100}%`,+ top: `${inheritedNumber(element, parent, "y", 0) * 100}%`,+ width: `${inheritedNumber(element, parent, "width", 1) * 100}%`,+ height: `${inheritedNumber(element, parent, "height", 1) * 100}%`,+ "object-fit": inheritedString(element, parent, "fit", defaults.fit ?? "cover"),+ "object-position": inheritedString(element, parent, "position", "50% 50%"),+ "border-radius": radius,+ opacity: inheritedNumber(element, parent, "opacity", 1),+ overflow: "hidden",+ background: inheritedString(element, parent, "background", defaults.background ?? "transparent"),+ };+}++export function durationSeconds(value) {+ const match = /^([0-9]+(?:\.[0-9]+)?)(ms|s)$/u.exec(value);+ if (!match) throw new Error(`invalid transition duration "${value}"`);+ return Number(match[1]) * (match[2] === "ms" ? 0.001 : 1);+}++function fadeSpec(raw) {+ if (raw === undefined) return 0;+ const match = /^fade\s+([0-9]+(?:\.[0-9]+)?(?:ms|s))$/u.exec(String(raw).trim());+ if (!match) throw new Error(`only "fade <duration>" is supported, received "${String(raw)}"`);+ return durationSeconds(match[1]);+}++export function presentationAnimation(element, range, fps, id) {+ const durationFrames = Math.max(1, range.endFrameExclusive - range.startFrame);+ const enterFrames = Math.min(durationFrames, Math.round(fadeSpec(element?.attributes.enter) * fps));+ const exitFrames = Math.min(+ durationFrames - enterFrames,+ Math.round(fadeSpec(element?.attributes.exit) * fps),+ );+ if (enterFrames <= 0 && exitFrames <= 0) return {};+ const enterPercent = enterFrames / durationFrames * 100;+ const exitPercent = 100 - exitFrames / durationFrames * 100;+ const name = `svml-present-${id}`.replaceAll(/[^A-Za-z0-9_-]/gu, "-");+ const duration = durationFrames / fps;+ return {+ animation: `${name} ${duration}s linear both`,+ css: `@keyframes ${name} {+ 0% { opacity:${enterFrames > 0 ? 0 : 1}; }+ ${enterPercent}% { opacity:1; }+ ${exitPercent}% { opacity:1; }+ 100% { opacity:${exitFrames > 0 ? 0 : 1}; }+ }`,+ };+}++export function resolveItemPresentations(context, item, source) {+ const rawParents = item.attributes.during+ ? context.selection(item.attributes.during, "item.during")+ : source.range+ ? [source.range]+ : [];+ if (!rawParents.length) {+ throw new Error(`item "${stringAttr(item, "id")}" has no temporal range`);+ }+ const parents = rawParents.map((range) =>+ projectWindow(range, item.attributes.window, context.fps));+ const presents = elements({ element: item }, "present");+ const explicit = [];+ for (const [presentIndex, present] of presents.entries()) {+ const presentRanges = present.attributes.during+ ? context.selection(present.attributes.during, "present.during")+ : parents;+ for (const projected of presentRanges.map((range) =>+ projectWindow(range, present.attributes.window, context.fps))) {+ for (const [parentIndex, parentRange] of parents.entries()) {+ const range = intersectRange(parentRange, projected);+ if (!range) continue;+ explicit.push({+ id: stringAttr(present, "id"),+ parentIndex,+ parentRange,+ range,+ element: present,+ layer: numberAttr(present, "layer", presentIndex + 1),+ explicit: true,+ });+ }+ }+ }+ const defaults = [];+ for (const [parentIndex, parentRange] of parents.entries()) {+ const cuts = explicit+ .filter((presentation) => presentation.parentIndex === parentIndex)+ .map((presentation) => presentation.range);+ const ranges = presents.length+ ? subtractRanges(parentRange, cuts, context.fps)+ : [parentRange];+ for (const range of ranges) {+ defaults.push({+ id: "default",+ parentIndex,+ parentRange,+ range,+ element: undefined,+ layer: 0,+ explicit: false,+ });+ }+ }+ return [...defaults, ...explicit];+}++export function mediaTiming(item, presentation, source, fps) {+ const playback = stringAttr(item, "playback", "sync");+ const offsetFrames = presentation.range.startFrame - presentation.parentRange.startFrame;+ const mediaStart = numberAttr(item, "mediaStart", 0);+ if (playback === "sync") {+ return {+ mediaStartSec: mediaStart + offsetFrames / fps,+ playbackRate: 1,+ };+ }+ if (playback === "loop") {+ return {+ mediaStartSec: mediaStart + offsetFrames / fps,+ playbackRate: 1,+ loop: true,+ };+ }+ if (playback === "stretch") {+ const sourceDuration = numberAttr(item, "sourceDuration");+ const parentFrames = Math.max(+ 1,+ presentation.parentRange.endFrameExclusive - presentation.parentRange.startFrame,+ );+ return {+ mediaStartSec: mediaStart + sourceDuration * (offsetFrames / parentFrames),+ playbackRate: sourceDuration / (parentFrames / fps),+ };+ }+ if (playback === "hold" && source.type === "Image") return {};+ throw new Error(`unsupported playback "${playback}" for ${source.type}`);+}diff --git a/stdlib/runtime/media-track.mjs b/stdlib/runtime/media-track.mjsnew file mode 100644index 00000000..f50140e4--- /dev/null+++ b/stdlib/runtime/media-track.mjs@@ -0,0 +1,54 @@+import {+ elements,+ material,+ mediaTiming,+ numberAttr,+ presentationAnimation,+ presentationStyle,+ resolveItemPresentations,+ resolveAttr,+ stringAttr,+ trackOutput,+} from "./helpers.mjs";++export default {+ abiVersion: "1",+ project(context) {+ const z = numberAttr(context.element, "z");+ const visuals = [];+ for (const item of elements(context, "item")) {+ const id = stringAttr(item, "id");+ const source = material(resolveAttr(context, item, "source"));+ const presentations = resolveItemPresentations(context, item, source);+ for (const [index, presentation] of presentations.entries()) {+ const range = presentation.range;+ const animation = presentationAnimation(+ presentation.element,+ range,+ context.fps,+ `${context.instance.id}-${id}-${presentation.id}-${index}`,+ );+ const timing = source.type === "Video"+ ? mediaTiming(item, presentation, source, context.fps)+ : {};+ visuals.push({+ id: `${context.instance.id}:${id}:${index}`,+ kind: source.type === "Image" ? "image" : "video",+ source: source.source,+ startFrame: range.startFrame,+ endFrameExclusive: range.endFrameExclusive,+ z,+ layer: presentation.layer,+ muted: true,+ ...timing,+ style: {+ ...presentationStyle(presentation.element, item),+ ...(animation.animation ? { animation: animation.animation } : {}),+ },+ ...(animation.css ? { css: animation.css } : {}),+ });+ }+ }+ return trackOutput(visuals);+ },+};diff --git a/stdlib/runtime/ranking-column.mjs b/stdlib/runtime/ranking-column.mjsnew file mode 100644index 00000000..8117ff54--- /dev/null+++ b/stdlib/runtime/ranking-column.mjs@@ -0,0 +1,280 @@+import {+ elements,+ html,+ material,+ numberAttr,+ projectWindow,+ resolveAttr,+ stringAttr,+ trackOutput,+} from "./helpers.mjs";++const GRADIENT_STOPS = [+ "#ff3f56",+ "#ff741f",+ "#ffb832",+ "#ffd82f",+ "#d4df24",+ "#94c93a",+ "#52bea0",+ "#31add0",+];++function hexToRgb(hex) {+ const value = Number.parseInt(hex.slice(1), 16);+ return [(value >> 16) & 255, (value >> 8) & 255, value & 255];+}++function mixHex(a, b, progress) {+ const from = hexToRgb(a);+ const to = hexToRgb(b);+ const mixed = from.map((value, index) =>+ Math.round(value + (to[index] - value) * progress));+ return `rgb(${mixed[0]}, ${mixed[1]}, ${mixed[2]})`;+}++function rankColor(index, total) {+ const progress = total <= 1 ? 0 : index / Math.max(1, total - 1);+ const scaled = progress * (GRADIENT_STOPS.length - 1);+ const stop = Math.min(GRADIENT_STOPS.length - 2, Math.floor(scaled));+ return mixHex(GRADIENT_STOPS[stop], GRADIENT_STOPS[stop + 1], scaled - stop);+}++function clamp01(value) {+ return Math.max(0, Math.min(1, value));+}++function lerp(from, to, progress) {+ return from + (to - from) * progress;+}++function easeInOutCubic(value) {+ return value < 0.5+ ? 4 * value * value * value+ : 1 - ((-2 * value + 2) ** 3) / 2;+}++function outBack(value) {+ const c1 = 1.70158;+ const c3 = c1 + 1;+ return 1 + c3 * ((value - 1) ** 3) + c1 * ((value - 1) ** 2);+}++function activeKeyframes(args) {+ const {+ durationFrames,+ durationSec,+ fps,+ stageCx,+ stageCy,+ stageSize,+ targetCx,+ targetCy,+ targetSize,+ frameHeight,+ } = args;+ const enterPart = Math.min(1, 0.45 / Math.max(0.001, durationSec));+ const exitStart = Math.min(+ 1,+ Math.max(enterPart, 1 - 0.55 / Math.max(0.001, durationSec)),+ );+ const frames = [];+ for (let frame = 0; frame <= durationFrames; frame += 1) {+ const local = clamp01(frame / Math.max(1, durationFrames));+ let centerX = stageCx;+ let centerY = stageCy;+ let size = stageSize;+ let opacity = 1;+ let breathe = 1;+ let rotate = 0;+ let shadow = "0 12px 30px rgba(0,0,0,.22)";+ if (local < enterPart) {+ const progress = outBack(clamp01(local / enterPart));+ centerY = lerp(frameHeight + stageSize * 0.25, stageCy, progress);+ opacity = Math.min(1, progress * 2.2);+ breathe = 0.96 + 0.04 * progress;+ } else if (local < exitStart) {+ const idle = (local - enterPart) / Math.max(0.001, exitStart - enterPart);+ const wave = Math.sin(idle * Math.PI * 2);+ const wave2 = Math.sin(idle * Math.PI * 2 + Math.PI / 2);+ centerY = stageCy - 1.8 * wave;+ centerX = stageCx + 0.8 * wave2;+ breathe = 1.004 + 0.003 * wave2;+ rotate = 0.12 * wave;+ shadow = "0 14px 34px rgba(0,0,0,.24)";+ } else {+ const progress = easeInOutCubic(+ clamp01((local - exitStart) / Math.max(0.001, 1 - exitStart)),+ );+ centerX = lerp(stageCx, targetCx, progress);+ centerY = lerp(stageCy, targetCy, progress);+ size = lerp(stageSize, targetSize, progress);+ breathe = 1 - 0.02 * Math.sin(progress * Math.PI);+ }+ frames.push(+ `${(frame / Math.max(1, durationFrames) * 100).toFixed(5)}% {`+ + `left:${(centerX - size / 2).toFixed(3)}px;`+ + `top:${(centerY - size / 2).toFixed(3)}px;`+ + `width:${size.toFixed(3)}px;`+ + `height:${size.toFixed(3)}px;`+ + `opacity:${opacity.toFixed(5)};`+ + `transform:scale(${breathe.toFixed(6)}) rotate(${rotate.toFixed(5)}deg);`+ + `box-shadow:${shadow};`+ + "}",+ );+ }+ return frames.join("\n");+}++export default {+ abiVersion: "1",+ project(context) {+ const z = numberAttr(context.element, "z");+ const x = Math.round(context.width * numberAttr(context.element, "x", 0));+ const y = Math.round(context.height * numberAttr(context.element, "y", 0.17));+ const rowH = Math.round(context.height * numberAttr(context.element, "rowHeight", 0.071));+ const gap = Math.round(context.height * numberAttr(context.element, "gap", 0.011));+ const width = Math.round(context.width * numberAttr(context.element, "width", 0.305));+ const pad = Math.max(8, Math.round(rowH * 0.13));+ const total = elements(context, "item").length;+ const boardH = total * rowH + Math.max(0, total - 1) * gap + pad * 2;+ const stageSize = Math.round(context.width * numberAttr(context.element, "stageSize", 0.33));+ const stageCx = Math.round(context.width * numberAttr(context.element, "stageX", 0.66));+ const stageCy = Math.round(context.height * numberAttr(context.element, "stageY", 0.73));+ const cellLeft = x + pad + rowH + Math.max(8, Math.round(rowH * 0.16));+ const rows = Array.from({ length: total }, (_, index) => {+ const top = pad + index * (rowH + gap);+ return `<div style="position:absolute;left:${pad}px;top:${top}px;width:${rowH}px;height:${rowH}px;border-radius:${Math.round(rowH * 0.075)}px;background:${rankColor(index, total)};display:flex;align-items:center;justify-content:center;color:white;font:900 ${Math.round(rowH * 0.48)}px/1 Arial,sans-serif;letter-spacing:-0.04em;text-shadow:0 1px 1px rgba(0,0,0,.12)"><span style="display:inline-block;transform:scaleX(1.02);transform-origin:center center">${index + 1}</span></div>+<div style="position:absolute;left:${pad + rowH + Math.max(8, Math.round(rowH * 0.16))}px;top:${top}px;width:${rowH}px;height:${rowH}px;border-radius:${Math.round(rowH * 0.23)}px;border:1.5px solid rgba(255,255,255,.18);background:rgba(0,0,0,.72);overflow:hidden"></div>`;+ }).join("");+ const visuals = [{+ id: `${context.instance.id}:board`,+ kind: "html",+ startFrame: 0,+ endFrameExclusive: context.located.durationFrames,+ z,+ html: rows,+ style: {+ left: `${x}px`,+ top: `${y}px`,+ width: `${width}px`,+ height: `${boardH}px`,+ "border-radius": `${Math.round(rowH * 0.16)}px`,+ background: "rgba(7,8,12,.94)",+ padding: `${pad}px`,+ "box-shadow": "0 6px 18px rgba(0,0,0,.35)",+ },+ }];+ const audios = [];+ const appear = context.element.attributes.appearSound+ ? material(resolveAttr(context, context.element, "appearSound"), "audio")+ : undefined;+ const move = context.element.attributes.moveSound+ ? material(resolveAttr(context, context.element, "moveSound"), "audio")+ : undefined;+ for (const item of elements(context, "item")) {+ const id = stringAttr(item, "id");+ const image = material(resolveAttr(context, item, "image"), "image");+ const rank = Math.max(1, Math.min(total, numberAttr(item, "rank")));+ const base = context.selection(item.attributes.during, "item.during")[0];+ const range = projectWindow(base, item.attributes.window, context.fps);+ const top = y + pad + (rank - 1) * (rowH + gap);+ const endDuration = (context.located.durationFrames - range.endFrameExclusive) / context.fps;+ if (endDuration > 0) {+ visuals.push({+ id: `${context.instance.id}:${id}:settled`,+ kind: "image",+ source: image.source,+ startFrame: range.endFrameExclusive,+ endFrameExclusive: context.located.durationFrames,+ z: z + 1,+ style: {+ left: `${cellLeft}px`,+ top: `${top}px`,+ width: `${rowH}px`,+ height: `${rowH}px`,+ "border-radius": `${Math.round(rowH * 0.23)}px`,+ background: "rgba(255,255,255,.98)",+ overflow: "hidden",+ },+ innerStyle: {+ width: "100%",+ height: "100%",+ "object-fit": "cover",+ transform: "scale(1.1)",+ },+ });+ }+ const keyframes = `svml-rank-${context.instance.id}-${id}`.replaceAll(/[^A-Za-z0-9_-]/gu, "-");+ const durationFrames = Math.max(1, range.endFrameExclusive - range.startFrame);+ const duration = durationFrames / context.fps;+ const targetCx = cellLeft + rowH / 2;+ const targetCy = top + rowH / 2;+ visuals.push({+ id: `${context.instance.id}:${id}:active`,+ kind: "image",+ source: image.source,+ startFrame: range.startFrame,+ endFrameExclusive: range.endFrameExclusive,+ z: z + 2,+ style: {+ left: `${stageCx - stageSize / 2}px`,+ top: `${stageCy - stageSize / 2}px`,+ width: `${stageSize}px`,+ height: `${stageSize}px`,+ "border-radius": `${Math.round(stageSize * 0.23)}px`,+ background: "rgba(255,255,255,.98)",+ "box-shadow": "0 14px 34px rgba(0,0,0,.24)",+ "transform-origin": "center center",+ overflow: "hidden",+ animation: `${keyframes} ${duration}s linear both`,+ },+ innerStyle: {+ width: "100%",+ height: "100%",+ "object-fit": "cover",+ transform: "scale(1.1)",+ },+ css: `@keyframes ${keyframes} {+${activeKeyframes({+ durationFrames,+ durationSec: duration,+ fps: context.fps,+ stageCx,+ stageCy,+ stageSize,+ targetCx,+ targetCy,+ targetSize: rowH,+ frameHeight: context.height,+})}+}`,+ });+ if (appear) {+ audios.push({+ id: `${context.instance.id}:${id}:appear`,+ source: appear.source,+ startFrame: range.startFrame,+ endFrameExclusive: Math.min(+ context.located.durationFrames,+ range.startFrame + Math.round(0.247021 * context.fps),+ ),+ volume: numberAttr(context.element, "appearGain", 0.09),+ bus: "sfx",+ });+ }+ if (move) {+ const moveFrames = Math.round(0.6 * context.fps);+ audios.push({+ id: `${context.instance.id}:${id}:move`,+ source: move.source,+ startFrame: Math.max(range.startFrame, range.endFrameExclusive - Math.round(0.55 * context.fps)),+ endFrameExclusive: Math.min(context.located.durationFrames, range.endFrameExclusive - Math.round(0.55 * context.fps) + moveFrames),+ volume: numberAttr(context.element, "moveGain", 0.1),+ bus: "sfx",+ });+ }+ }+ return trackOutput(visuals, audios);+ },+};diff --git a/stdlib/runtime/speech-spine.mjs b/stdlib/runtime/speech-spine.mjsnew file mode 100644index 00000000..f98fc712--- /dev/null+++ b/stdlib/runtime/speech-spine.mjs@@ -0,0 +1,49 @@+import { elements, material, resolveAttr, stringAttr } from "./helpers.mjs";++export default {+ abiVersion: "1",+ project(context) {+ const segmentOutputs = {};+ const audios = [];+ for (const segment of elements(context, "segment")) {+ const id = stringAttr(segment, "id");+ const located = resolveAttr(context, segment, "script");+ const visual = material(resolveAttr(context, segment, "visual"), "video");+ const audioValue = segment.attributes.audio+ ? material(resolveAttr(context, segment, "audio"), "audio")+ : { source: visual.source };+ segmentOutputs[id] = {+ range: located,+ visual: {+ type: "Video",+ source: visual.source,+ range: located,+ },+ audio: {+ type: "Audio",+ source: audioValue.source,+ range: located,+ },+ };+ audios.push({+ id: `${context.instance.id}:speech:${id}`,+ source: audioValue.source,+ startFrame: located.startFrame,+ endFrameExclusive: located.endFrameExclusive,+ volume: 1,+ bus: "speech",+ });+ }+ return {+ outputs: {+ segment: segmentOutputs,+ speech: {+ segments: segmentOutputs,+ primaryAudio: audios,+ },+ track: { visuals: [], audios, styles: [] },+ },+ audios,+ };+ },+};diff --git a/stdlib/runtime/text-track.mjs b/stdlib/runtime/text-track.mjsnew file mode 100644index 00000000..7f3d3006--- /dev/null+++ b/stdlib/runtime/text-track.mjs@@ -0,0 +1,56 @@+import {+ elements,+ html,+ numberAttr,+ stringAttr,+ trackOutput,+} from "./helpers.mjs";++export default {+ abiVersion: "1",+ project(context) {+ const z = numberAttr(context.element, "z");+ const visuals = [];+ for (const item of elements(context, "item")) {+ const id = stringAttr(item, "id");+ const ranges = context.selection(item.attributes.during ?? "full", "item.during");+ for (const [index, range] of ranges.entries()) {+ const text = stringAttr(item, "text");+ visuals.push({+ id: `${context.instance.id}:${id}:${index}`,+ kind: "html",+ startFrame: range.startFrame,+ endFrameExclusive: range.endFrameExclusive,+ z,+ html: `<div class="svml-text-inner">${html(item.attributes.uppercase === true ? text.toUpperCase() : text)}</div>`,+ style: {+ left: `${numberAttr(item, "x", 0) * 100}%`,+ top: `${numberAttr(item, "y", 0) * 100}%`,+ width: `${numberAttr(item, "width", 1) * 100}%`,+ height: `${numberAttr(item, "height", 0.1) * 100}%`,+ display: "flex",+ "align-items": "center",+ "justify-content": "center",+ color: stringAttr(item, "color", "#050505"),+ background: "transparent",+ "font-family": stringAttr(item, "font", "Inter, Arial, sans-serif"),+ "font-size": `${numberAttr(item, "size", 54)}px`,+ "font-weight": numberAttr(item, "weight", 900),+ "line-height": numberAttr(item, "lineHeight", 0.92),+ "text-align": "center",+ "letter-spacing": `${numberAttr(item, "letterSpacing", 0)}px`,+ },+ css: `.svml-text-inner {+ display: inline;+ padding: 0.08em 0;+ background: ${stringAttr(item, "background", "transparent")};+ box-decoration-break: clone;+ -webkit-box-decoration-break: clone;+ text-shadow: 0 2px 0 rgba(255,255,255,.9), 0 4px 7px rgba(0,0,0,.32);+}`,+ });+ }+ }+ return trackOutput(visuals);+ },+};diff --git a/stdlib/speech-spine.svk b/stdlib/speech-spine.svknew file mode 100644index 00000000..e2ab8e4c--- /dev/null+++ b/stdlib/speech-spine.svk@@ -0,0 +1,14 @@+<kernel name="speech-spine" abi="1" implementation="./runtime/speech-spine.mjs">+ <port name="segment" direction="input" type="SegmentBinding" cardinality="one-or-more"/>+ <port name="segment" direction="output" type="SegmentMaterial" cardinality="one-or-more"/>+ <port name="segment.*.visual" direction="output" type="Video" cardinality="zero-or-one"/>+ <port name="segment.*.audio" direction="output" type="Audio" cardinality="one"/>+ <port name="speech" direction="output" type="SpeechSpine" cardinality="one"/>+ <port name="track" direction="output" type="Track" cardinality="one"/>+ <child name="segment" cardinality="one-or-more">+ <field name="id" type="id" required="true"/>+ <field name="script" type="ScriptSegment" required="true"/>+ <field name="visual" type="Video" required="true"/>+ <field name="audio" type="Audio"/>+ </child>+</kernel>diff --git a/stdlib/text-track.svk b/stdlib/text-track.svknew file mode 100644index 00000000..f2a1a488--- /dev/null+++ b/stdlib/text-track.svk@@ -0,0 +1,22 @@+<kernel name="text-track" abi="1" implementation="./runtime/text-track.mjs">+ <param name="z" type="number"/>+ <port name="item" direction="input" type="TextItem" cardinality="one-or-more"/>+ <port name="track" direction="output" type="Track" cardinality="one"/>+ <child name="item" cardinality="one-or-more">+ <field name="id" type="id" required="true"/>+ <field name="text" type="string" required="true"/>+ <field name="during" type="SelectionSet|ProgramSpan" consume="each"/>+ <field name="x" type="number"/>+ <field name="y" type="number"/>+ <field name="width" type="number"/>+ <field name="height" type="number"/>+ <field name="font" type="string"/>+ <field name="size" type="number"/>+ <field name="weight" type="number"/>+ <field name="lineHeight" type="number"/>+ <field name="letterSpacing" type="number"/>+ <field name="color" type="string"/>+ <field name="background" type="string"/>+ <field name="uppercase" type="boolean"/>+ </child>+</kernel>diff --git a/test/artifacts.test.ts b/test/artifacts.test.tsnew file mode 100644index 00000000..a9174d03--- /dev/null+++ b/test/artifacts.test.ts@@ -0,0 +1,96 @@+import assert from "node:assert/strict";+import { readFile, writeFile } from "node:fs/promises";+import { mkdtemp } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";+import { checkSource, compileSource } from "../src/compiler.js";+import { sha256 } from "../src/util.js";++const fixture = fileURLToPath(new URL("./fixtures/artifacts/", import.meta.url));+const pinnedImage = fileURLToPath(+ new URL("./fixtures/collision/left/image.png", import.meta.url),+);+const alternateImage = fileURLToPath(+ new URL("./fixtures/collision/right/image.png", import.meta.url),+);++test("capability instances require exact verified artifacts and never invoke a provider", async () => {+ const file = `${fixture}/main.svml`;+ const checked = await checkSource(file);+ const capability = checked.plan.instances.find((instance) => instance.id === "poster");+ assert.equal(+ checked.plan.kernels.find((kernel) => kernel.name === "pinned-image")?.profile,+ "capability-v1",+ );+ await assert.rejects(+ compileSource({+ file,+ evidenceFile: `${fixture}/alignment.json`,+ }),+ /artifact_file_required/u,+ );++ const directory = await mkdtemp(join(tmpdir(), "svml-artifacts-"));+ const lock = join(directory, "svml.lock");+ const artifacts = join(directory, "artifacts.json");+ const output = join(directory, "index.html");+ await writeFile(lock, `${JSON.stringify(checked.lock, null, 2)}\n`, "utf8");+ await writeFile(artifacts, `${JSON.stringify({+ contract: "svml.artifacts.v1",+ bindings: [{+ instanceIdentity: capability?.identity,+ executionDigest: capability?.executionDigest,+ outputs: {+ image: {+ type: "Image",+ uri: pathToFileURL(pinnedImage).href,+ contentDigest: sha256(await readFile(pinnedImage)),+ },+ },+ }],+ }, null, 2)}\n`, "utf8");++ const compilation = await compileSource({+ file,+ evidenceFile: `${fixture}/alignment.json`,+ lockFile: lock,+ artifactsFile: artifacts,+ outputFile: output,+ });+ assert.equal(compilation.artifactsVerified, true);+ assert.equal(compilation.reproducible, true);+ assert.match(compilation.html, /bound-image/u);+ assert.match(compilation.html, /\.\/assets\/[a-f0-9]{16}-image\.png/u);++ const alternateArtifacts = join(directory, "alternate-artifacts.json");+ await writeFile(alternateArtifacts, `${JSON.stringify({+ contract: "svml.artifacts.v1",+ bindings: [{+ instanceIdentity: capability?.identity,+ executionDigest: capability?.executionDigest,+ outputs: {+ image: {+ type: "Image",+ uri: pathToFileURL(alternateImage).href,+ contentDigest: sha256(await readFile(alternateImage)),+ },+ },+ }],+ }, null, 2)}\n`, "utf8");+ const alternate = await compileSource({+ file,+ evidenceFile: `${fixture}/alignment.json`,+ lockFile: lock,+ artifactsFile: alternateArtifacts,+ });+ assert.equal(+ compilation.plan.instances.find((instance) => instance.id === "poster")?.executionDigest,+ alternate.plan.instances.find((instance) => instance.id === "poster")?.executionDigest,+ );+ assert.notEqual(+ compilation.plan.instances.find((instance) => instance.id === "film")?.executionDigest,+ alternate.plan.instances.find((instance) => instance.id === "film")?.executionDigest,+ );+});diff --git a/test/fixtures/artifacts/alignment.json b/test/fixtures/artifacts/alignment.jsonnew file mode 100644index 00000000..2b301f1d--- /dev/null+++ b/test/fixtures/artifacts/alignment.json@@ -0,0 +1,20 @@+{+ "contract": "svml.speech-alignment.v1",+ "durationSec": 1,+ "fps": 30,+ "words": [+ {+ "text": "Hello",+ "startSec": 0,+ "endSec": 0.8,+ "segmentId": "main"+ }+ ],+ "segments": [+ {+ "id": "main",+ "startSec": 0,+ "endSec": 1+ }+ ]+}diff --git a/test/fixtures/artifacts/artifact-film.mjs b/test/fixtures/artifacts/artifact-film.mjsnew file mode 100644index 00000000..15d72e75--- /dev/null+++ b/test/fixtures/artifacts/artifact-film.mjs@@ -0,0 +1,28 @@+export default {+ abiVersion: "1",+ project(context) {+ const image = context.resolve(context.element.attributes.image);+ return {+ outputs: {+ document: {+ contract: "svml.hyperframes-document.v1",+ id: context.instance.id,+ width: 64,+ height: 64,+ fps: context.fps,+ durationFrames: context.located.durationFrames,+ background: "#000000",+ visuals: [{+ id: "bound-image",+ kind: "image",+ source: image.absoluteSource ?? image.source,+ startFrame: 0,+ endFrameExclusive: context.located.durationFrames,+ z: 0,+ }],+ audios: [],+ },+ },+ };+ },+};diff --git a/test/fixtures/artifacts/artifact-film.svk b/test/fixtures/artifacts/artifact-film.svknew file mode 100644index 00000000..8f93ad04--- /dev/null+++ b/test/fixtures/artifacts/artifact-film.svk@@ -0,0 +1,9 @@+<kernel+ name="artifact-film"+ abi="1"+ root="true"+ implementation="./artifact-film.mjs"+>+ <port name="image" direction="input" type="Image" cardinality="one"/>+ <port name="document" direction="output" type="HyperframesDocument" cardinality="one"/>+</kernel>diff --git a/test/fixtures/artifacts/main.svml b/test/fixtures/artifacts/main.svmlnew file mode 100644index 00000000..730bb240--- /dev/null+++ b/test/fixtures/artifacts/main.svml@@ -0,0 +1,11 @@+<svml version="1">+ <import from="./pinned-image.svk"/>+ <import from="./artifact-film.svk"/>++ <script>+ <segment id="main">Hello.</segment>+ </script>++ <pinned-image id="poster" prompt="A pinned result; never call a provider."/>+ <artifact-film id="film" image={poster.image}/>+</svml>diff --git a/test/fixtures/artifacts/pinned-image.svk b/test/fixtures/artifacts/pinned-image.svknew file mode 100644index 00000000..2303e44f--- /dev/null+++ b/test/fixtures/artifacts/pinned-image.svk@@ -0,0 +1,9 @@+<kernel+ name="pinned-image"+ abi="1"+ profile="capability-v1"+ capability="image.generate"+>+ <param name="prompt" type="string"/>+ <port name="image" direction="output" type="Image" cardinality="one"/>+</kernel>diff --git a/test/fixtures/collision/alignment.json b/test/fixtures/collision/alignment.jsonnew file mode 100644index 00000000..413c7b61--- /dev/null+++ b/test/fixtures/collision/alignment.json@@ -0,0 +1,13 @@+{+ "contract": "svml.speech-alignment.v1",+ "durationSec": 2,+ "fps": 30,+ "words": [+ { "text": "Left", "startSec": 0.1, "endSec": 0.5, "segmentId": "main" },+ { "text": "and", "startSec": 0.6, "endSec": 0.9, "segmentId": "main" },+ { "text": "right", "startSec": 1, "endSec": 1.5, "segmentId": "main" }+ ],+ "segments": [+ { "id": "main", "startSec": 0, "endSec": 2 }+ ]+}diff --git a/test/fixtures/collision/main.svml b/test/fixtures/collision/main.svmlnew file mode 100644index 00000000..f813653f--- /dev/null+++ b/test/fixtures/collision/main.svml@@ -0,0 +1,29 @@+<svml version="1">+ <import from="../../../stdlib/speech-spine.svk"/>+ <import from="../../../stdlib/broll-track.svk"/>+ <import from="../../../stdlib/film.svk"/>++ <script>+ <segment id="main">+ @left Left @/left and @right right @/right.+ </segment>+ </script>++ <video id="avatar" src="./avatar.mp4"/>+ <image id="left-image" src="./left/image.png"/>+ <image id="right-image" src="./right/image.png"/>++ <speech-spine id="speech">+ <segment id="main" script={script.segment.main} visual={avatar}/>+ </speech-spine>++ <broll-track id="broll" z="100">+ <item id="left" source={left-image} during={script.selection.left}/>+ <item id="right" source={right-image} during={script.selection.right}/>+ <transition from="left" to="right" kind="crossfade" duration="200ms"/>+ </broll-track>++ <film id="collision" speech={speech.speech}>+ <track ref={broll.track}/>+ </film>+</svml>diff --git a/test/fixtures/disconnected/alignment.json b/test/fixtures/disconnected/alignment.jsonnew file mode 100644index 00000000..a5401de8--- /dev/null+++ b/test/fixtures/disconnected/alignment.json@@ -0,0 +1,13 @@+{+ "contract": "svml.speech-alignment.v1",+ "durationSec": 3,+ "fps": 30,+ "words": [+ { "text": "Alpha", "startSec": 0, "endSec": 0.7, "segmentId": "main" },+ { "text": "gap", "startSec": 1, "endSec": 1.5, "segmentId": "main" },+ { "text": "omega", "startSec": 2, "endSec": 2.7, "segmentId": "main" }+ ],+ "segments": [+ { "id": "main", "startSec": 0, "endSec": 3 }+ ]+}diff --git a/test/fixtures/disconnected/each.svml b/test/fixtures/disconnected/each.svmlnew file mode 100644index 00000000..ce79c2e5--- /dev/null+++ b/test/fixtures/disconnected/each.svml@@ -0,0 +1,23 @@+<svml version="1">+ <import from="../../../stdlib/speech-spine.svk"/>+ <import from="../../../stdlib/media-track.svk"/>+ <import from="../../../stdlib/film.svk"/>++ <script>+ <segment id="main">@pick Alpha @/pick gap @pick omega @/pick.</segment>+ </script>++ <video id="avatar" src="../presentation/long.mp4"/>++ <speech-spine id="speech">+ <segment id="main" script={script.segment.main} visual={avatar}/>+ </speech-spine>++ <media-track id="media" z="1">+ <item id="picked" source={avatar} during={script.selection.pick}/>+ </media-track>++ <film id="film" speech={speech.speech}>+ <track ref={media.track}/>+ </film>+</svml>diff --git a/test/fixtures/disconnected/one.svml b/test/fixtures/disconnected/one.svmlnew file mode 100644index 00000000..7f0d83cf--- /dev/null+++ b/test/fixtures/disconnected/one.svml@@ -0,0 +1,24 @@+<svml version="1">+ <import from="../../../stdlib/speech-spine.svk"/>+ <import from="../../../stdlib/ranking-column.svk"/>+ <import from="../../../stdlib/film.svk"/>++ <script>+ <segment id="main">@pick Alpha @/pick gap @pick omega @/pick.</segment>+ </script>++ <video id="avatar" src="../presentation/long.mp4"/>+ <image id="icon" src="../collision/left/image.png"/>++ <speech-spine id="speech">+ <segment id="main" script={script.segment.main} visual={avatar}/>+ </speech-spine>++ <ranking-column id="ranking" z="1">+ <item id="picked" rank="1" image={icon} during={script.selection.pick}/>+ </ranking-column>++ <film id="film" speech={speech.speech}>+ <track ref={ranking.track}/>+ </film>+</svml>diff --git a/test/fixtures/disconnected/selection-set.mjs b/test/fixtures/disconnected/selection-set.mjsnew file mode 100644index 00000000..99842bf0--- /dev/null+++ b/test/fixtures/disconnected/selection-set.mjs@@ -0,0 +1,17 @@+export default {+ abiVersion: "1",+ project(context) {+ const item = context.element.children.find(+ (child) => child.kind === "element" && child.name === "item",+ );+ const ranges = context.selection(item.attributes.during, "item.during");+ const track = { visuals: [], audios: [], styles: [] };+ return {+ outputs: { track },+ diagnostics: [{+ code: "selection_set_count",+ message: String(ranges.length),+ }],+ };+ },+};diff --git a/test/fixtures/disconnected/selection-set.svk b/test/fixtures/disconnected/selection-set.svknew file mode 100644index 00000000..1e8b2adb--- /dev/null+++ b/test/fixtures/disconnected/selection-set.svk@@ -0,0 +1,8 @@+<kernel name="selection-set" abi="1" implementation="./selection-set.mjs">+ <port name="item" direction="input" type="SelectionRule" cardinality="one"/>+ <port name="track" direction="output" type="Track" cardinality="one"/>+ <child name="item" cardinality="one">+ <field name="id" type="id" required="true"/>+ <field name="during" type="SelectionSet" consume="set" required="true"/>+ </child>+</kernel>diff --git a/test/fixtures/disconnected/set.svml b/test/fixtures/disconnected/set.svmlnew file mode 100644index 00000000..dccdcc62--- /dev/null+++ b/test/fixtures/disconnected/set.svml@@ -0,0 +1,23 @@+<svml version="1">+ <import from="../../../stdlib/speech-spine.svk"/>+ <import from="./selection-set.svk"/>+ <import from="../../../stdlib/film.svk"/>++ <script>+ <segment id="main">@pick Alpha @/pick gap @pick omega @/pick.</segment>+ </script>++ <video id="avatar" src="../presentation/long.mp4"/>++ <speech-spine id="speech">+ <segment id="main" script={script.segment.main} visual={avatar}/>+ </speech-spine>++ <selection-set id="styles">+ <item id="highlight" during={script.selection.pick}/>+ </selection-set>++ <film id="film" speech={speech.speech}>+ <track ref={styles.track}/>+ </film>+</svml>diff --git a/test/fixtures/modules/alignment.json b/test/fixtures/modules/alignment.jsonnew file mode 100644index 00000000..5d086519--- /dev/null+++ b/test/fixtures/modules/alignment.json@@ -0,0 +1,20 @@+{+ "contract": "svml.speech-alignment.v1",+ "durationSec": 1,+ "fps": 30,+ "words": [+ {+ "text": "Hello",+ "startSec": 0.1,+ "endSec": 0.8,+ "segmentId": "main"+ }+ ],+ "segments": [+ {+ "id": "main",+ "startSec": 0,+ "endSec": 1+ }+ ]+}diff --git a/test/fixtures/modules/brand.svc b/test/fixtures/modules/brand.svcnew file mode 100644index 00000000..a644c95d--- /dev/null+++ b/test/fixtures/modules/brand.svc@@ -0,0 +1,11 @@+<content version="1" id="brand">+ <import from="./identity-image.svk"/>++ <image id="logo" src="./logo.png"/>++ <text id="tagline">+ A #1 semantic video language.+ </text>++ <identity-image id="poster" source={logo}/>+</content>diff --git a/test/fixtures/modules/house.svs b/test/fixtures/modules/house.svsnew file mode 100644index 00000000..e06a57ad--- /dev/null+++ b/test/fixtures/modules/house.svs@@ -0,0 +1,18 @@+<sheet version="1" id="house">+ broll-track.full {+ z: 100;+ }++ caption-track.launch {+ z: 510;+ font-size: 44;+ fill: #fefefe;+ }++ film.vertical {+ width: 1080;+ height: 1920;+ frame-rate: 30;+ background: #112233;+ }+</sheet>diff --git a/test/fixtures/modules/identity-image.mjs b/test/fixtures/modules/identity-image.mjsnew file mode 100644index 00000000..b853ee94--- /dev/null+++ b/test/fixtures/modules/identity-image.mjs@@ -0,0 +1,11 @@+export default {+ abiVersion: "1",+ project(context) {+ const source = context.resolve(context.element.attributes.source);+ return {+ outputs: {+ image: source,+ },+ };+ },+};diff --git a/test/fixtures/modules/identity-image.svk b/test/fixtures/modules/identity-image.svknew file mode 100644index 00000000..d759a8de--- /dev/null+++ b/test/fixtures/modules/identity-image.svk@@ -0,0 +1,4 @@+<kernel name="identity-image" abi="1" implementation="./identity-image.mjs">+ <port name="source" direction="input" type="Image" cardinality="one"/>+ <port name="image" direction="output" type="Image" cardinality="one"/>+</kernel>diff --git a/test/fixtures/modules/main-renamed-alias.svml b/test/fixtures/modules/main-renamed-alias.svmlnew file mode 100644index 00000000..42b8d0ef--- /dev/null+++ b/test/fixtures/modules/main-renamed-alias.svml@@ -0,0 +1,31 @@+<svml version="1">+ <import from="../../../stdlib/speech-spine.svk"/>+ <import from="../../../stdlib/broll-track.svk"/>+ <import from="../../../stdlib/caption-track.svk"/>+ <import from="../../../stdlib/film.svk"/>+ <import as="assets" from="./brand.svc"/>+ <import as="house" from="./house.svs"/>++ <script>+ <segment id="main">+ @poster Hello @/poster.+ </segment>+ </script>++ <video id="avatar" src="./avatar.mp4"/>++ <speech-spine id="speech">+ <segment id="main" script={script.segment.main} visual={avatar}/>+ </speech-spine>++ <broll-track id="broll" class="house.full">+ <item id="poster" source={assets.poster.image} during={script.selection.poster}/>+ </broll-track>++ <caption-track id="captions" script={script} class="house.launch" size="48"/>++ <film id="main-film" class="house.vertical" speech={speech.speech}>+ <track ref={broll.track}/>+ <track ref={captions.track}/>+ </film>+</svml>diff --git a/test/fixtures/modules/main.svml b/test/fixtures/modules/main.svmlnew file mode 100644index 00000000..671a4afc--- /dev/null+++ b/test/fixtures/modules/main.svml@@ -0,0 +1,31 @@+<svml version="1">+ <import from="../../../stdlib/speech-spine.svk"/>+ <import from="../../../stdlib/broll-track.svk"/>+ <import from="../../../stdlib/caption-track.svk"/>+ <import from="../../../stdlib/film.svk"/>+ <import as="brand" from="./brand.svc"/>+ <import as="house" from="./house.svs"/>++ <script>+ <segment id="main">+ @poster Hello @/poster.+ </segment>+ </script>++ <video id="avatar" src="./avatar.mp4"/>++ <speech-spine id="speech">+ <segment id="main" script={script.segment.main} visual={avatar}/>+ </speech-spine>++ <broll-track id="broll" class="house.full">+ <item id="poster" source={brand.poster.image} during={script.selection.poster}/>+ </broll-track>++ <caption-track id="captions" script={script} class="house.launch" size="48"/>++ <film id="main-film" class="house.vertical" speech={speech.speech}>+ <track ref={broll.track}/>+ <track ref={captions.track}/>+ </film>+</svml>diff --git a/test/fixtures/presentation/alignment.json b/test/fixtures/presentation/alignment.jsonnew file mode 100644index 00000000..ec4e5903--- /dev/null+++ b/test/fixtures/presentation/alignment.json@@ -0,0 +1,13 @@+{+ "contract": "svml.speech-alignment.v1",+ "durationSec": 3,+ "fps": 30,+ "words": [+ { "text": "One", "startSec": 0.2, "endSec": 0.6, "segmentId": "main" },+ { "text": "two", "startSec": 1.1, "endSec": 1.5, "segmentId": "main" },+ { "text": "three", "startSec": 2.1, "endSec": 2.7, "segmentId": "main" }+ ],+ "segments": [+ { "id": "main", "startSec": 0, "endSec": 3 }+ ]+}diff --git a/test/fixtures/presentation/main.svml b/test/fixtures/presentation/main.svmlnew file mode 100644index 00000000..3875d687--- /dev/null+++ b/test/fixtures/presentation/main.svml@@ -0,0 +1,58 @@+<svml version="1">+ <import from="../../../stdlib/speech-spine.svk"/>+ <import from="../../../stdlib/media-track.svk"/>+ <import from="../../../stdlib/audio-track.svk"/>+ <import from="../../../stdlib/film.svk"/>++ <script>+ <segment id="main">+ One @pop! two three.+ </segment>+ </script>++ <video id="long-video" src="./long.mp4"/>+ <audio id="pop-sound" src="./pop.wav"/>++ <speech-spine id="speech">+ <segment id="main" script={script.segment.main} visual={long-video}/>+ </speech-spine>++ <media-track id="aroll" z="200">+ <item id="host" source={long-video} during="full" fit="cover">+ <present+ id="top-circle"+ during="start .. start+1.2s"+ layer="10"+ x="0.05"+ y="0.05"+ width="0.3"+ height="0.3"+ shape="circle"+ />+ <present+ id="lower-split"+ during="start+1s .. start+2s"+ layer="20"+ x="0"+ y="0.5"+ width="1"+ height="0.5"+ enter="fade 200ms"+ />+ <present+ id="outside"+ during="end+1s .. end+2s"+ layer="30"+ />+ </item>+ </media-track>++ <audio-track id="sfx">+ <item id="pop" source={pop-sound} at={script.moment.pop} duration="200ms" bus="sfx"/>+ </audio-track>++ <film id="presentation" speech={speech.speech}>+ <track ref={aroll.track}/>+ <track ref={sfx.track}/>+ </film>+</svml>diff --git a/test/fixtures/unsafe/alignment.json b/test/fixtures/unsafe/alignment.jsonnew file mode 100644index 00000000..b6b288ff--- /dev/null+++ b/test/fixtures/unsafe/alignment.json@@ -0,0 +1,11 @@+{+ "contract": "svml.speech-alignment.v1",+ "durationSec": 1,+ "fps": 30,+ "words": [+ { "text": "Hello", "startSec": 0.1, "endSec": 0.8, "segmentId": "main" }+ ],+ "segments": [+ { "id": "main", "startSec": 0, "endSec": 1 }+ ]+}diff --git a/test/fixtures/unsafe/main.svml b/test/fixtures/unsafe/main.svmlnew file mode 100644index 00000000..7b384f4d--- /dev/null+++ b/test/fixtures/unsafe/main.svml@@ -0,0 +1,9 @@+<svml version="1">+ <import from="./unsafe.svk"/>++ <script>+ <segment id="main">Hello.</segment>+ </script>++ <unsafe id="main"/>+</svml>diff --git a/test/fixtures/unsafe/unsafe.mjs b/test/fixtures/unsafe/unsafe.mjsnew file mode 100644index 00000000..fc79bd67--- /dev/null+++ b/test/fixtures/unsafe/unsafe.mjs@@ -0,0 +1,9 @@+import fs from "node:fs";++export default {+ abiVersion: "1",+ project() {+ fs.readFileSync("/etc/passwd");+ return { outputs: {} };+ },+};diff --git a/test/fixtures/unsafe/unsafe.svk b/test/fixtures/unsafe/unsafe.svknew file mode 100644index 00000000..8e7466e7--- /dev/null+++ b/test/fixtures/unsafe/unsafe.svk@@ -0,0 +1,3 @@+<kernel name="unsafe" abi="1" root="true" implementation="./unsafe.mjs">+ <port name="document" direction="output" type="HyperframesDocument" cardinality="one"/>+</kernel>diff --git a/test/hyperframes.test.ts b/test/hyperframes.test.tsnew file mode 100644index 00000000..4fe5c066--- /dev/null+++ b/test/hyperframes.test.ts@@ -0,0 +1,29 @@+import assert from "node:assert/strict";+import test from "node:test";+import { emitHyperframesHtml, frameSeconds } from "../src/hyperframes.js";++test("frame lowering preserves half-open intervals for repeating seconds", () => {+ assert.equal(frameSeconds(977, 30), "32.566666666");+ assert.equal(frameSeconds(32, 30), "1.066666666");++ const html = emitHyperframesHtml({+ id: "floating-boundary",+ width: 1080,+ height: 1920,+ fps: 30,+ durationFrames: 1083,+ background: "#000",+ visuals: [{+ id: "instagram-post",+ kind: "image",+ source: "./post.png",+ startFrame: 977,+ endFrameExclusive: 1009,+ z: 1,+ }],+ audios: [],+ });++ assert.match(html, /data-start="32\.566666666"/u);+ assert.match(html, /data-duration="1\.066666666"/u);+});diff --git a/test/kernel-contracts.test.ts b/test/kernel-contracts.test.tsnew file mode 100644index 00000000..d4811fe5--- /dev/null+++ b/test/kernel-contracts.test.ts@@ -0,0 +1,52 @@+import assert from "node:assert/strict";+import { mkdtemp, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";+import { checkSource } from "../src/compiler.js";++const brollKernel = fileURLToPath(+ new URL("../stdlib/broll-track.svk", import.meta.url),+);+const unsafeKernel = fileURLToPath(+ new URL("./fixtures/unsafe/unsafe.svk", import.meta.url),+);++async function checkBody(body: string): Promise<ReturnType<typeof checkSource>> {+ const directory = await mkdtemp(join(tmpdir(), "svml-kernel-contract-"));+ const file = join(directory, "main.svml");+ await writeFile(file, `<svml version="1">+ <import from="${brollKernel}"/>+ <import from="${unsafeKernel}"/>+ <script><segment id="main">Hello.</segment></script>+ <audio id="sound" src="./missing.wav"/>+ ${body}+ <unsafe id="root"/>+</svml>+`, "utf8");+ return checkSource(file);+}++test("Kernel child schemas reject unknown fields, wrong references and cardinality", async () => {+ await assert.rejects(+ checkBody('<broll-track id="broll" z="1"/>'),+ /kernel_child_cardinality/u,+ );+ await assert.rejects(+ checkBody(`+ <broll-track id="broll" z="1">+ <item id="one" source={sound} during="full"/>+ </broll-track>+ `),+ /plan_port_type/u,+ );+ await assert.rejects(+ checkBody(`+ <broll-track id="broll" z="1">+ <item id="one" source={sound} during="full" zoon="1"/>+ </broll-track>+ `),+ /kernel_field_unknown/u,+ );+});diff --git a/test/modules.test.ts b/test/modules.test.tsnew file mode 100644index 00000000..94033472--- /dev/null+++ b/test/modules.test.ts@@ -0,0 +1,122 @@+import assert from "node:assert/strict";+import test from "node:test";+import { mkdir, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { checkSource, compileSource } from "../src/compiler.js";+import { SvmlError } from "../src/diagnostics.js";+import { portableFileIdentity } from "../src/util.js";++const fixtures = fileURLToPath(new URL("./fixtures/modules/", import.meta.url));++test(".svc content DAG and .svs parameter classes bind into one source closure", async () => {+ const file = `${fixtures}/main.svml`;+ const checked = await checkSource(file);++ assert.deepEqual(+ checked.plan.instances.map((instance) => instance.id).sort(),+ ["brand.poster", "broll", "captions", "main-film", "speech"],+ );+ assert.deepEqual(+ checked.plan.values.map((value) => value.id).sort(),+ ["avatar", "brand.logo"],+ );+ const logo = checked.plan.values.find((value) => value.id === "brand.logo");+ assert.equal(logo?.localId, "logo");+ assert.match(logo?.module ?? "", /brand\.svc$/u);+ assert.ok(!checked.plan.values.some((value) => value.id === "brand.tagline"));++ const captions = checked.plan.instances.find((instance) => instance.id === "captions");+ assert.equal(captions?.attributes.z, 510);+ assert.equal(captions?.attributes.size, 48);+ assert.equal(captions?.attributes.color, "#fefefe");+ assert.deepEqual(+ captions?.effectiveParameters.size?.sources.map((source) => source.kind),+ ["kernel-default", "svs-class", "instance"],+ );++ const film = checked.plan.instances.find((instance) => instance.id === "main-film");+ assert.equal(film?.attributes.background, "#112233");+ assert.equal(film?.attributes.fps, 30);++ const compilation = await compileSource({+ file,+ evidenceFile: `${fixtures}/alignment.json`,+ });+ assert.match(compilation.html, /data-composition-id="main-film"/u);+ assert.match(compilation.html, /#112233/u);+ assert.match(compilation.html, /logo\.png/u);+});++test("import aliases do not change imported instance identity or execution digest", async () => {+ const original = await checkSource(`${fixtures}/main.svml`);+ const renamed = await checkSource(`${fixtures}/main-renamed-alias.svml`);+ const before = original.plan.instances.find((instance) => instance.localId === "poster");+ const after = renamed.plan.instances.find((instance) => instance.localId === "poster");++ assert.equal(before?.identity, after?.identity);+ assert.equal(before?.executionDigest, after?.executionDigest);+});++test("svml.lock verifies the exact source closure and Kernel implementations", async () => {+ const file = `${fixtures}/main.svml`;+ const checked = await checkSource(file);+ assert.ok(checked.lock.modules.every((module) => module.uri.startsWith("svml-file:")));+ assert.ok(checked.lock.kernels.every((kernel) =>+ kernel.manifestUri.startsWith("svml-file:")+ && (kernel.implementationUri?.startsWith("svml-file:") ?? true)));+ assert.ok(checked.lock.materials+ .filter((material) => material.uri?.startsWith("svml-file:"))+ .every((material) => !material.uri?.includes(process.cwd())));+ const directory = await mkdtemp(join(tmpdir(), "svml-lock-"));+ const lock = join(directory, "svml.lock");+ await writeFile(lock, `${JSON.stringify(checked.lock, null, 2)}\n`, "utf8");++ const verified = await compileSource({+ file,+ evidenceFile: `${fixtures}/alignment.json`,+ lockFile: lock,+ });+ assert.equal(verified.lockVerified, true);++ const changed = structuredClone(checked.lock);+ changed.kernels[0]!.implementationHash = "0".repeat(64);+ await writeFile(lock, `${JSON.stringify(changed, null, 2)}\n`, "utf8");+ await assert.rejects(+ compileSource({+ file,+ evidenceFile: `${fixtures}/alignment.json`,+ lockFile: lock,+ }),+ (error: unknown) =>+ error instanceof SvmlError+ && error.diagnostics.some((diagnostic) => diagnostic.code === "lock_mismatch"),+ );+});++test("portable file identity survives relocating the complete source closure", () => {+ assert.equal(+ portableFileIdentity("/checkout-a/project/main.svml", "/checkout-a/project/content/brand.svc"),+ portableFileIdentity("/checkout-b/project/main.svml", "/checkout-b/project/content/brand.svc"),+ );+});++test("asset staging uses content-addressed names and never overwrites equal basenames", async () => {+ const collision = fileURLToPath(new URL("./fixtures/collision/", import.meta.url));+ const directory = await mkdtemp(join(tmpdir(), "svml-assets-"));+ const output = join(directory, "index.html");+ await mkdir(directory, { recursive: true });+ await compileSource({+ file: `${collision}/main.svml`,+ evidenceFile: `${collision}/alignment.json`,+ outputFile: output,+ });++ const assets = await readdir(join(directory, "assets"));+ const images = assets.filter((name) => name.endsWith("-image.png"));+ assert.equal(images.length, 2);+ assert.notEqual(images[0], images[1]);+ const html = await readFile(output, "utf8");+ for (const image of images) assert.match(html, new RegExp(image, "u"));+});diff --git a/test/presentation.test.ts b/test/presentation.test.tsnew file mode 100644index 00000000..9b79882b--- /dev/null+++ b/test/presentation.test.ts@@ -0,0 +1,84 @@+import assert from "node:assert/strict";+import test from "node:test";+import { fileURLToPath } from "node:url";+import { compileSource } from "../src/compiler.js";+import type { VisualFragment } from "../src/runtime-contract.js";++test("Present ranges intersect the Item, overlap by layer, and keep one source-time map", async () => {+ const fixture = fileURLToPath(new URL("./fixtures/presentation/", import.meta.url));+ const compilation = await compileSource({+ file: `${fixture}/main.svml`,+ evidenceFile: `${fixture}/alignment.json`,+ });+ const visuals = compilation.projections.get("aroll")?.visuals ?? [];+ assert.equal(visuals.length, 3);+ assert.deepEqual(+ visuals.map((fragment) => [+ fragment.startFrame,+ fragment.endFrameExclusive,+ fragment.layer,+ fragment.mediaStartSec,+ ]),+ [+ [60, 90, 0, 2],+ [0, 36, 10, 0],+ [30, 60, 20, 1],+ ],+ );+ assert.equal(visuals[1]?.style?.["border-radius"], "50%");+ assert.match(visuals[2]?.css ?? "", /@keyframes svml-present/u);+ const sfx = compilation.projections.get("sfx")?.audios ?? [];+ assert.deepEqual(+ sfx.map((fragment) => [+ fragment.startFrame,+ fragment.endFrameExclusive,+ fragment.bus,+ ]),+ [[33, 39, "sfx"]],+ );+});++test("B-roll crossfade extends only the visual surfaces and leaves source audio independent", async () => {+ const fixture = fileURLToPath(new URL("./fixtures/collision/", import.meta.url));+ const compilation = await compileSource({+ file: `${fixture}/main.svml`,+ evidenceFile: `${fixture}/alignment.json`,+ });+ const broll = compilation.projections.get("broll");+ const visuals = (broll?.visuals ?? []) as VisualFragment[];+ const left = visuals.find((fragment) => fragment.id.includes(":left:"));+ const right = visuals.find((fragment) => fragment.id.includes(":right:"));+ assert.equal(left?.endFrameExclusive, 36);+ assert.equal(right?.startFrame, 30);+ assert.match(left?.css ?? "", /svml-broll-transition/u);+ assert.match(right?.css ?? "", /svml-broll-transition/u);+ assert.equal(broll?.audios?.length ?? 0, 0);+});++test("temporal one/each cardinality is declared by the Kernel contract", async () => {+ const fixture = fileURLToPath(new URL("./fixtures/disconnected/", import.meta.url));+ const each = await compileSource({+ file: `${fixture}/each.svml`,+ evidenceFile: `${fixture}/alignment.json`,+ });+ assert.equal(each.projections.get("media")?.visuals?.length, 2);+ const media = each.plan.kernels.find((kernel) => kernel.name === "media-track");+ assert.equal(media?.children[0]?.fields.find((field) => field.name === "during")?.consume, "each");++ const set = await compileSource({+ file: `${fixture}/set.svml`,+ evidenceFile: `${fixture}/alignment.json`,+ });+ assert.deepEqual(set.projections.get("styles")?.diagnostics, [{+ code: "selection_set_count",+ message: "2",+ }]);++ await assert.rejects(+ compileSource({+ file: `${fixture}/one.svml`,+ evidenceFile: `${fixture}/alignment.json`,+ }),+ /temporal cardinality expected one, received 2/u,+ );+});diff --git a/test/regen-ranking.test.ts b/test/regen-ranking.test.tsnew file mode 100644index 00000000..a5a85e03--- /dev/null+++ b/test/regen-ranking.test.ts@@ -0,0 +1,76 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";+import { fileURLToPath } from "node:url";+import { compileSource, estimateSource } from "../src/compiler.js";+import { projectCanvas, projectTimeline } from "../src/views.js";++type Reference = {+ clock: { fps: number; durationFrames: number };+ plan: { root: string; values: number; instances: number; edges: number };+ selectionFrames: Record<string, Array<[number, number]>>;+ locatedOutput: { visualFragments: number; audioFragments: number };+};++const example = fileURLToPath(new URL("../examples/regen-ranking/", import.meta.url));++test("regen ranking compiles to the frozen production timing contract", async () => {+ const reference = JSON.parse(+ await readFile(new URL("../examples/regen-ranking/reference.json", import.meta.url), "utf8"),+ ) as Reference;+ const compilation = await compileSource({+ file: `${example}/regen-ranking.svml`,+ evidenceFile: `${example}/evidence/alignment.json`,+ });++ assert.equal(compilation.located.fps, reference.clock.fps);+ assert.equal(compilation.located.durationFrames, reference.clock.durationFrames);+ assert.deepEqual(+ {+ root: compilation.plan.root,+ values: compilation.plan.values.length,+ instances: compilation.plan.instances.length,+ edges: compilation.plan.edges.length,+ },+ reference.plan,+ );++ for (const [id, expected] of Object.entries(reference.selectionFrames)) {+ assert.deepEqual(+ compilation.located.selections[id]?.ranges.map(+ (range) => [range.startFrame, range.endFrameExclusive],+ ),+ expected,+ id,+ );+ }++ const document = compilation.projections.get(compilation.plan.root)?.outputs.document as {+ visuals?: unknown[];+ audios?: unknown[];+ };+ assert.equal(document.visuals?.length, reference.locatedOutput.visualFragments);+ assert.equal(document.audios?.length, reference.locatedOutput.audioFragments);+ assert.match(compilation.html, /data-composition-id="regen-ranking"/u);+ assert.match(compilation.html, /data-duration="36\.1"/u);++ const canvas = projectCanvas(compilation.plan);+ assert.equal(canvas.root, reference.plan.root);+ assert.equal(canvas.nodes.length, reference.plan.values + reference.plan.instances);+ assert.equal(canvas.edges.length, reference.plan.edges);+ const brollContract = compilation.plan.kernels.find(+ (kernel) => kernel.name === "broll-track",+ );+ assert.deepEqual(+ brollContract?.children.map((child) => child.name),+ ["item", "transition"],+ );++ const timeline = projectTimeline(compilation);+ assert.equal(timeline.durationFrames, reference.clock.durationFrames);+ assert.equal(timeline.visuals.length, reference.locatedOutput.visualFragments);+ assert.equal(timeline.audios.length, reference.locatedOutput.audioFragments);++ const estimate = await estimateSource(`${example}/regen-ranking.svml`);+ assert.ok(Math.abs(estimate.evidence.durationSec - reference.clock.durationFrames / 30) < 0.5);+});diff --git a/test/runtime-security.test.ts b/test/runtime-security.test.tsnew file mode 100644index 00000000..1c11f003--- /dev/null+++ b/test/runtime-security.test.ts@@ -0,0 +1,51 @@+import assert from "node:assert/strict";+import test from "node:test";+import { fileURLToPath } from "node:url";+import { compileSource } from "../src/compiler.js";+import { SvmlError } from "../src/diagnostics.js";+import { validateKernelProjection } from "../src/runtime-validation.js";++test("projector CSS is scoped and active HTML is rejected", () => {+ const projection = validateKernelProjection({+ outputs: {},+ visuals: [{+ id: "safe",+ kind: "html",+ html: '<div class="label">Hello</div>',+ css: ".label { color: red; }",+ startFrame: 0,+ endFrameExclusive: 1,+ z: 1,+ }],+ });+ assert.match(projection.visuals?.[0]?.css ?? "", /^\[data-svml-scope="[a-f0-9]+"\] \.label/u);+ assert.throws(+ () => validateKernelProjection({+ outputs: {},+ visuals: [{+ id: "active",+ kind: "html",+ html: "<script>document.body.remove()</script>",+ startFrame: 0,+ endFrameExclusive: 1,+ z: 1,+ }],+ }),+ (error: unknown) =>+ error instanceof SvmlError+ && error.diagnostics.some((diagnostic) => diagnostic.code === "kernel_html_capability"),+ );+});++test("isolated projector ABI rejects Node builtin imports", async () => {+ const fixture = fileURLToPath(new URL("./fixtures/unsafe/", import.meta.url));+ await assert.rejects(+ compileSource({+ file: `${fixture}/main.svml`,+ evidenceFile: `${fixture}/alignment.json`,+ }),+ (error: unknown) =>+ error instanceof SvmlError+ && error.diagnostics.some((diagnostic) => diagnostic.code === "kernel_projector_isolation"),+ );+});diff --git a/test/script.test.ts b/test/script.test.tsnew file mode 100644index 00000000..fb4a4aa3--- /dev/null+++ b/test/script.test.ts@@ -0,0 +1,256 @@+import assert from "node:assert/strict";+import test from "node:test";+import type { AlignmentEvidence } from "../src/model.js";+import { locateScript } from "../src/script/locate.js";+import { estimateAlignment } from "../src/script/estimate.js";+import { parseScript } from "../src/script/parse.js";+import { formatDocumentScript } from "../src/format.js";+import { parseDocumentSource } from "../src/source/parse-document.js";++test("Script Surface projects role, dual text, selections and moments", () => {+ const narrative = parseScript("fixture.svml", `+ @whole+ <segment id="one">+ <A> I just @laugh @pop! <lmao | laughed my @punch ass out @/punch> @/laugh.+ </segment>+ @/whole~+ `);+ assert.equal(narrative.projections.dialogue, "A: I just laughed my ass out.");+ assert.equal(narrative.projections.speech, "I just laughed my ass out.");+ assert.equal(narrative.projections.caption, "I just lmao.");+ assert.equal(narrative.selections.whole?.length, 1);+ assert.equal(narrative.selections.laugh?.length, 1);+ assert.equal(narrative.selections.punch?.length, 1);+ assert.equal(narrative.moments.pop?.length, 1);+ assert.deepEqual(+ narrative.captionAtoms.map((atom) => [+ atom.display,+ atom.startWord,+ atom.endWordExclusive,+ ]),+ [["lmao", 2, 6]],+ );+});++test("Dual Text owns its complete speech span and caption cues cannot split it", () => {+ const narrative = parseScript(+ "fixture.svml",+ `<segment id="one">I just <lmao | laughed my ass out>.</segment>`,+ );+ const evidence: AlignmentEvidence = {+ contract: "svml.speech-alignment.v1",+ durationSec: 2,+ fps: 30,+ words: [+ { text: "I", startSec: 0, endSec: 0.1, segmentId: "one" },+ { text: "just", startSec: 0.2, endSec: 0.4, segmentId: "one" },+ { text: "laughed", startSec: 0.5, endSec: 0.8, segmentId: "one" },+ { text: "my", startSec: 0.9, endSec: 1, segmentId: "one" },+ { text: "ass", startSec: 1.1, endSec: 1.3, segmentId: "one" },+ { text: "out", startSec: 1.4, endSec: 1.7, segmentId: "one" },+ ],+ segments: [{ id: "one", startSec: 0, endSec: 2 }],+ };+ const located = locateScript(narrative, evidence);+ assert.deepEqual(+ located.captionAtoms.map((atom) => [+ atom.display,+ atom.startFrame,+ atom.endFrameExclusive,+ ]),+ [["lmao", 15, 51]],+ );+ assert.throws(+ () => locateScript(narrative, {+ ...evidence,+ captionCues: [+ { startWord: 0, endWordExclusive: 4 },+ { startWord: 4, endWordExclusive: 6 },+ ],+ }),+ /locate_caption_partial_dual/u,+ );+});++test("Slots bind after parsing and escaped reserved syntax stays literal", () => {+ const narrative = parseScript(+ "fixture.svml",+ "<segment id=\"one\">Meet <${display} | ${spoken}> at \\@openai and \\<tag>. ${literal}</segment>",+ 0,+ {+ display: "Hypit",+ spoken: "high pit",+ literal: "@/not-a-marker",+ },+ );+ assert.equal(narrative.projections.speech, "Meet high pit at @openai and <tag>. @/not-a-marker");+ assert.equal(narrative.projections.caption, "Meet Hypit at @openai and <tag>. @/not-a-marker");+ assert.equal(Object.keys(narrative.selections).length, 0);+ assert.throws(+ () => parseScript("fixture.svml", '<segment id="one">${missing}</segment>'),+ /script_slot_unbound/u,+ );+});++test("Selection and Moment names cannot conflict or reopen", () => {+ assert.throws(+ () => parseScript("fixture.svml", '<segment id="one">@x! one @x two @/x.</segment>'),+ /script_temporal_type_conflict/u,+ );+ assert.throws(+ () => parseScript("fixture.svml", '<segment id="one">@x one @x two @/x @/x.</segment>'),+ /script_selection_reopened/u,+ );+});++test("the same Selection id may produce a disconnected set", () => {+ const narrative = parseScript("fixture.svml", `+ <segment id="one">+ @pick Alpha @/pick then @pick omega @/pick.+ </segment>+ `);+ assert.equal(narrative.selections.pick?.length, 2);+});++test("selection endpoints must close", () => {+ assert.throws(+ () => parseScript("fixture.svml", `<segment id="one">@x hello.</segment>`),+ /script_selection_unclosed/u,+ );+});++test("caption cue evidence is a complete ordered word partition", () => {+ const narrative = parseScript(+ "fixture.svml",+ `<segment id="one">Alpha beta gamma.</segment>`,+ );+ const evidence: AlignmentEvidence = {+ contract: "svml.speech-alignment.v1",+ durationSec: 1.5,+ fps: 30,+ words: [+ { text: "Alpha", startSec: 0, endSec: 0.4, segmentId: "one" },+ { text: "beta", startSec: 0.5, endSec: 0.9, segmentId: "one" },+ { text: "gamma", startSec: 1, endSec: 1.4, segmentId: "one" },+ ],+ segments: [{ id: "one", startSec: 0, endSec: 1.5 }],+ captionCues: [+ { id: "opening", startWord: 0, endWordExclusive: 1 },+ { id: "payoff", startWord: 1, endWordExclusive: 3 },+ ],+ };+ const located = locateScript(narrative, evidence);+ assert.deepEqual(+ located.captionCues?.map((cue) => [+ cue.id,+ cue.startWord,+ cue.endWordExclusive,+ cue.startFrame,+ cue.endFrameExclusive,+ ]),+ [+ ["opening", 0, 1, 0, 12],+ ["payoff", 1, 3, 15, 42],+ ],+ );++ assert.throws(+ () => locateScript(narrative, {+ ...evidence,+ captionCues: [{ startWord: 1, endWordExclusive: 3 }],+ }),+ /locate_caption_cue_partition/u,+ );++ assert.throws(+ () => locateScript(narrative, {+ ...evidence,+ words: evidence.words.map((word, index) =>+ index === 1 ? { ...word, startSec: 0.2 } : word),+ }),+ /locate_alignment_word_overlap/u,+ );+});++test("Script normalizes newlines and NFC while tokenizing East Asian writing per character", () => {+ const narrative = parseScript(+ "fixture.svml",+ "<segment id=\"one\">Cafe\u0301\r\n中文かなカナ words.</segment>",+ );+ assert.equal(narrative.projections.speech, "Café 中文かなカナ words.");+ assert.deepEqual(+ narrative.tokens.map((token) => token.text),+ ["Café", "中", "文", "か", "な", "カ", "ナ", "words"],+ );+});++test("reserved @ syntax and non-canonical ids fail closed", () => {+ assert.throws(+ () => parseScript("fixture.svml", '<segment id="one">[email protected]</segment>'),+ /script_(?:invalid_marker|selection_unclosed)/u,+ );+ assert.throws(+ () => parseScript("fixture.svml", '<segment id="One">Hello.</segment>'),+ /script_invalid_segment_id/u,+ );+ assert.throws(+ () => parseScript("fixture.svml", '<segment id="one">@NotCanonical! Hello.</segment>'),+ /script_invalid_marker/u,+ );+});++test("syllable Estimate produces complete deterministic alignment including silence", () => {+ const narrative = parseScript("fixture.svml", `+ <segment id="speech">Hello 中文.</segment>+ <segment id="silence"/>+ `);+ const first = estimateAlignment(narrative, {+ fps: 30,+ syllablesPerSecond: 4,+ emptySegmentSec: 2,+ maxCaptionWords: 2,+ });+ const second = estimateAlignment(narrative, {+ fps: 30,+ syllablesPerSecond: 4,+ emptySegmentSec: 2,+ maxCaptionWords: 2,+ });+ assert.deepEqual(first, second);+ assert.deepEqual(first.words.map((word) => word.text), ["Hello", "中", "文"]);+ assert.equal(first.segments[1]?.endSec! - first.segments[1]?.startSec!, 2);+ assert.deepEqual(+ first.captionCues?.map((cue) => [cue.startWord, cue.endWordExclusive]),+ [[0, 2], [2, 3]],+ );+ assert.equal(first.provenance?.method, "svml.syllable-estimate.v1");+});++test("canonical Script formatter is semantic-preserving and idempotent", () => {+ const source = `<svml version="1">+ <script>+ @whole+ <segment id="one">+ <A> Hello @pop! <world | wonderful world>.+ </segment>+ @/whole~+ </script>+ <text id="unused">value</text>+</svml>+`;+ const document = parseDocumentSource("fixture.svml", source);+ const narrative = parseScript(+ document.file,+ document.scriptSource,+ document.scriptOffset,+ );+ const formatted = formatDocumentScript(document, narrative, {});+ assert.match(formatted, /\n @whole\n\n <segment id="one">\n <A>/u);+ const secondDocument = parseDocumentSource("fixture.svml", formatted);+ const secondNarrative = parseScript(+ secondDocument.file,+ secondDocument.scriptSource,+ secondDocument.scriptOffset,+ );+ assert.equal(formatDocumentScript(secondDocument, secondNarrative, {}), formatted);+});diff --git a/tools/analyze-highlight-transitions.mjs b/tools/analyze-highlight-transitions.mjsnew file mode 100644index 00000000..05fb5ff2--- /dev/null+++ b/tools/analyze-highlight-transitions.mjs@@ -0,0 +1,100 @@+#!/usr/bin/env node+import { spawn } from "node:child_process";++const [videoFile] = process.argv.slice(2);+if (!videoFile) {+ throw new Error("usage: analyze-highlight-transitions.mjs <video.mp4>");+}++const width = 730;+const height = 130;+const bytesPerFrame = width * height * 3;+const ffmpeg = spawn("ffmpeg", [+ "-hide_banner",+ "-loglevel", "error",+ "-i", videoFile,+ "-vf", "crop=730:130:350:1010",+ "-f", "rawvideo",+ "-pix_fmt", "rgb24",+ "-",+], { stdio: ["ignore", "pipe", "inherit"] });++let pending = Buffer.alloc(0);+let frame = 0;+let previous;++function highlightMask(buffer) {+ const mask = new Uint8Array(width * height);+ let count = 0;+ let minX = width;+ let maxX = -1;+ let minY = height;+ let maxY = -1;+ for (let pixel = 0; pixel < mask.length; pixel += 1) {+ const offset = pixel * 3;+ const red = buffer[offset];+ const green = buffer[offset + 1];+ const blue = buffer[offset + 2];+ const distance = (+ (255 - red) ** 2+ + (211 - green) ** 2+ + (77 - blue) ** 2+ );+ if (distance > 1_800) continue;+ mask[pixel] = 1;+ count += 1;+ const x = pixel % width;+ const y = Math.floor(pixel / width);+ minX = Math.min(minX, x);+ maxX = Math.max(maxX, x);+ minY = Math.min(minY, y);+ maxY = Math.max(maxY, y);+ }+ return {+ mask,+ count,+ box: count ? [minX, minY, maxX, maxY] : undefined,+ };+}++function similarity(left, right) {+ if (!left || !right) return 0;+ let intersection = 0;+ let union = 0;+ for (let index = 0; index < left.mask.length; index += 1) {+ const l = left.mask[index];+ const r = right.mask[index];+ if (l && r) intersection += 1;+ if (l || r) union += 1;+ }+ return union ? intersection / union : 1;+}++ffmpeg.stdout.on("data", (chunk) => {+ pending = Buffer.concat([pending, chunk]);+ while (pending.length >= bytesPerFrame) {+ const pixels = pending.subarray(0, bytesPerFrame);+ pending = pending.subarray(bytesPerFrame);+ const current = highlightMask(pixels);+ const score = similarity(previous, current);+ const appeared = current.count >= 40 && (!previous || previous.count < 40);+ const disappeared = current.count < 40 && previous && previous.count >= 40;+ if (appeared || disappeared || (current.count >= 40 && previous?.count >= 40 && score < 0.42)) {+ process.stdout.write(+ `${String(frame).padStart(4)} ${(frame / 30).toFixed(3)}s `+ + `pixels=${String(current.count).padStart(4)} similarity=${score.toFixed(3)} `+ + `box=${current.box?.join(",") ?? "-"}\n`,+ );+ }+ previous = current;+ frame += 1;+ }+});++await new Promise((resolve, reject) => {+ ffmpeg.on("error", reject);+ ffmpeg.on("close", (code) => {+ if (code === 0) resolve();+ else reject(new Error(`ffmpeg exited ${code}`));+ });+});diff --git a/tools/build-whisper-evidence.mjs b/tools/build-whisper-evidence.mjsnew file mode 100644index 00000000..14f114fc--- /dev/null+++ b/tools/build-whisper-evidence.mjs@@ -0,0 +1,168 @@+#!/usr/bin/env node+import { readFile, writeFile } from "node:fs/promises";+import { resolve } from "node:path";++const args = process.argv.slice(2);+function takeOption(name) {+ const index = args.indexOf(name);+ if (index < 0) return undefined;+ const value = args[index + 1];+ if (!value) throw new Error(`${name} requires a file path.`);+ args.splice(index, 2);+ return value;+}+const cueFile = takeOption("--caption-cues");+const timingOverrideFile = takeOption("--timing-overrides");+const [sourceFile, outputFile, ...whisperFiles] = args;+if (!sourceFile || !outputFile || whisperFiles.length === 0) {+ throw new Error(+ "usage: build-whisper-evidence.mjs <tokens.json> <output.json> <whisper-1.json> ... "+ + "[--caption-cues <cues.json>] [--timing-overrides <overrides.json>]",+ );+}++const intended = JSON.parse(await readFile(resolve(sourceFile), "utf8"));+const normalize = (value) => String(value)+ .normalize("NFKC")+ .toLowerCase()+ .replace(/[^\p{L}\p{M}\p{N}]+/gu, "");++const lcs = (left, right) => {+ const table = Array.from({ length: left.length + 1 }, () =>+ Array(right.length + 1).fill(0));+ for (let leftIndex = left.length - 1; leftIndex >= 0; leftIndex -= 1) {+ for (let rightIndex = right.length - 1; rightIndex >= 0; rightIndex -= 1) {+ table[leftIndex][rightIndex] = left[leftIndex] === right[rightIndex]+ ? 1 + table[leftIndex + 1][rightIndex + 1]+ : Math.max(table[leftIndex + 1][rightIndex], table[leftIndex][rightIndex + 1]);+ }+ }+ const matches = [];+ let leftIndex = 0;+ let rightIndex = 0;+ while (leftIndex < left.length && rightIndex < right.length) {+ if (left[leftIndex] === right[rightIndex]) {+ matches.push([leftIndex, rightIndex]);+ leftIndex += 1;+ rightIndex += 1;+ } else if (table[leftIndex + 1][rightIndex] >= table[leftIndex][rightIndex + 1]) {+ leftIndex += 1;+ } else {+ rightIndex += 1;+ }+ }+ return matches;+};++const evidenceWords = [];+const segmentFrames = 361;+for (let segmentIndex = 0; segmentIndex < intended.segments.length; segmentIndex += 1) {+ const segment = intended.segments[segmentIndex];+ const whisper = JSON.parse(await readFile(resolve(whisperFiles[segmentIndex]), "utf8"));+ const measured = whisper.transcription+ .filter((entry) => String(entry.text).trim())+ .map((entry) => ({+ text: String(entry.text).trim(),+ startSec: Number(entry.offsets.from) / 1000,+ endSec: Number(entry.offsets.to) / 1000,+ }));+ const target = intended.words.filter((word) => word.segmentId === segment.id);+ const matches = lcs(+ target.map((word) => normalize(word.text)),+ measured.map((word) => normalize(word.text)),+ );+ const anchors = [[-1, -1], ...matches, [target.length, measured.length]];+ const located = Array(target.length);+ for (const [targetIndex, measuredIndex] of matches) {+ located[targetIndex] = {+ text: target[targetIndex].text,+ startSec: measured[measuredIndex].startSec,+ endSec: measured[measuredIndex].endSec,+ };+ }+ for (let anchorIndex = 0; anchorIndex < anchors.length - 1; anchorIndex += 1) {+ const [leftTarget, leftMeasured] = anchors[anchorIndex];+ const [rightTarget, rightMeasured] = anchors[anchorIndex + 1];+ const missing = rightTarget - leftTarget - 1;+ if (missing <= 0) continue;+ const measuredSlice = measured.slice(leftMeasured + 1, rightMeasured);+ const startSec = measuredSlice[0]?.startSec+ ?? measured[leftMeasured]?.endSec+ ?? 0;+ const endSec = measuredSlice.at(-1)?.endSec+ ?? measured[rightMeasured]?.startSec+ ?? segmentFrames / 30;+ const weights = target+ .slice(leftTarget + 1, rightTarget)+ .map((word) => Math.max(1, normalize(word.text).length));+ const totalWeight = weights.reduce((sum, value) => sum + value, 0);+ let cursor = startSec;+ for (let index = 0; index < missing; index += 1) {+ const duration = (endSec - startSec) * weights[index] / totalWeight;+ const targetIndex = leftTarget + 1 + index;+ located[targetIndex] = {+ text: target[targetIndex].text,+ startSec: cursor,+ endSec: index === missing - 1 ? endSec : cursor + duration,+ };+ cursor += duration;+ }+ }+ const offsetSec = segmentIndex * segmentFrames / 30;+ const segmentEndSec = (segmentIndex + 1) * segmentFrames / 30;+ for (const word of located) {+ evidenceWords.push({+ text: word.text,+ startSec: Math.max(offsetSec, Math.min(segmentEndSec, word.startSec + offsetSec)),+ endSec: Math.max(offsetSec, Math.min(segmentEndSec, word.endSec + offsetSec)),+ segmentId: segment.id,+ });+ }+}++const evidence = {+ contract: "svml.speech-alignment.v1",+ durationSec: intended.segments.length * segmentFrames / 30,+ fps: 30,+ words: evidenceWords,+ segments: intended.segments.map((segment, index) => ({+ id: segment.id,+ startSec: index * segmentFrames / 30,+ endSec: (index + 1) * segmentFrames / 30,+ })),+ provenance: {+ method: "whisper.cpp word timestamps + deterministic intended-script LCS projection",+ source: "existing pinned avatar audio; no generation call",+ },+};+if (cueFile) {+ const cueDocument = JSON.parse(await readFile(resolve(cueFile), "utf8"));+ evidence.captionCues = Array.isArray(cueDocument)+ ? cueDocument+ : cueDocument.captionCues;+ if (!Array.isArray(evidence.captionCues)) {+ throw new Error(`${cueFile} must contain an array or a captionCues array.`);+ }+ evidence.provenance.captionCues = cueDocument.provenance+ ?? "pinned cue partition from the reference Locate result";+}+if (timingOverrideFile) {+ const overrideDocument = JSON.parse(+ await readFile(resolve(timingOverrideFile), "utf8"),+ );+ if (!Array.isArray(overrideDocument.words)) {+ throw new Error(`${timingOverrideFile} must contain a words array.`);+ }+ for (const override of overrideDocument.words) {+ const index = Number(override.index);+ const word = evidence.words[index];+ if (!Number.isInteger(index) || !word) {+ throw new Error(`${timingOverrideFile} contains invalid word index ${String(override.index)}.`);+ }+ if (override.startSec !== undefined) word.startSec = Number(override.startSec);+ if (override.endSec !== undefined) word.endSec = Number(override.endSec);+ }+ evidence.provenance.timingOverrides = overrideDocument.provenance+ ?? "reference transition recovery";+}+await writeFile(resolve(outputFile), `${JSON.stringify(evidence, null, 2)}\n`);diff --git a/tools/copy-runtime.mjs b/tools/copy-runtime.mjsnew file mode 100644index 00000000..9086e251--- /dev/null+++ b/tools/copy-runtime.mjs@@ -0,0 +1,7 @@+import { copyFile, mkdir } from "node:fs/promises";++await mkdir(new URL("../dist/src/", import.meta.url), { recursive: true });+await copyFile(+ new URL("../src/sandbox-worker.mjs", import.meta.url),+ new URL("../dist/src/sandbox-worker.mjs", import.meta.url),+);diff --git a/tsconfig.json b/tsconfig.jsonnew file mode 100644index 00000000..e42ee52a--- /dev/null+++ b/tsconfig.json@@ -0,0 +1,19 @@+{+ "compilerOptions": {+ "target": "ES2023",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "lib": ["ES2023", "DOM"],+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "exactOptionalPropertyTypes": true,+ "verbatimModuleSyntax": true,+ "declaration": true,+ "sourceMap": true,+ "rootDir": ".",+ "outDir": "dist",+ "skipLibCheck": true+ },+ "include": ["src/**/*.ts", "test/**/*.ts"],+ "exclude": ["dist", "node_modules"]+}