Skip to content

armgit / hypit

Public Imported from GitHub
0

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.

feat: isolate caption authoring and close package dependencies

kashorin80bcd3d8e170
diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts
index 9fab9aa9..55d6af18 100644
--- a/docs/.vitepress/config.ts
+++ b/docs/.vitepress/config.ts
@@ -155,7 +155,7 @@ const enTheme = {
{ text: "Adding an Author Package", link: "/guide/author-packages" },
{ text: "Adding a Provider", link: "/guide/providers" },
{ text: "Runtime Profile", link: "/guide/runtime-profile" },
- { text: "Component Playground", link: "/guide/playground" },
+ { text: "Caption Playground", link: "/guide/caption-playground" },
{ text: "Local Services", link: "/guide/services" },
{ text: "Testing", link: "/guide/testing" },
{ text: "Conventions", link: "/guide/conventions" },
@@ -198,7 +198,7 @@ const zhTheme = {
{ text: "添加 Author 包", link: "/zh/guide/author-packages" },
{ text: "添加 Provider", link: "/zh/guide/providers" },
{ text: "Runtime Profile", link: "/zh/guide/runtime-profile" },
- { text: "组件 Playground", link: "/zh/guide/playground" },
+ { text: "字幕 Playground", link: "/zh/guide/caption-playground" },
{ text: "本地服务", link: "/zh/guide/services" },
{ text: "测试", link: "/zh/guide/testing" },
{ text: "代码规范", link: "/zh/guide/conventions" },
diff --git a/docs/guide/author-packages.md b/docs/guide/author-packages.md
index e4765102..1ca4ae6e 100644
--- a/docs/guide/author-packages.md
+++ b/docs/guide/author-packages.md
@@ -133,10 +133,14 @@ pnpm install --frozen-lockfile
pnpm narratage lock-packages <lock-file> \
--package @narratage/my-component \
- [--package @narratage/other-dep ...] \
- --root .
+ [--package @narratage/other-direct-package ...] \
+ --package-root .
```
+Only name direct packages you chose. Exact logical Module dependencies declared by their Manifests
+are added from the installed physical dependency closure automatically; missing or ambiguous
+providers make lock creation fail.
+
## 8. Use in Author Source
```xml
diff --git a/docs/guide/caption-playground.md b/docs/guide/caption-playground.md
new file mode 100644
index 00000000..5a5a1308
--- /dev/null
+++ b/docs/guide/caption-playground.md
@@ -0,0 +1,53 @@
+---
+title: Caption Playground
+description: Edit a real Fine Caption SVS Recipe and exact font stack with live feedback.
+---
+
+# Caption Playground
+
+Caption styling benefits from a visual editor, but the editor must not become a
+second authoring system. Caption Playground reads and writes the same `.svml`
+and `.svs` files that an ordinary Build compiles.
+
+```bash
+pnpm caption:playground -- \
+ --source examples/talking-film-graph-check/main.svml \
+ --package-lock examples/talking-film-graph-check/svml.packages.lock \
+ --style base-caption \
+ --display story.caption \
+ --recipe examples/talking-film-graph-check/studio.svs#caption.base \
+ --font examples/talking-film-graph-check/main.svml#caption-font \
+ --canvas 1080x1920 \
+ --fps 30
+```
+
+Open `http://localhost:5178`.
+
+All selections are explicit:
+
+| Argument | Selected fact |
+|---|---|
+| `--source` | self-described author source |
+| `--package-lock` | trusted author compiler closure |
+| `--style` | authored Fine Caption Style export |
+| `--display` | authored Caption Display export |
+| `--recipe` | real SVS file and Recipe path to edit |
+| `--font` | real SVML file and `fonts:Stack` id to edit |
+| `--canvas`, `--fps` | local preview context, not author semantics |
+
+Recipe fields use author vocabulary: `size`, `padding`, `fill`, and so on. The
+form never exposes compiled DTO names such as `fontSizePx` or
+`paddingXPx`. Font family, weight and style have one source of truth: the
+selected `<fonts:Stack>` in SVML, while the SVS Recipe owns size, placement,
+paint, boxes, karaoke and motion.
+
+The font gallery renders each choice in its own pinned redistributable font.
+Clicking one atomically edits the selected stack and recompiles the source.
+External editor or Agent changes use the same files and trigger the same
+refresh. Stale browser writes are rejected by source digest instead of silently
+overwriting newer work.
+
+Caption Playground creates no component registry, preview package metadata,
+private project file, hidden default Style or production-package dependency.
+Its showcase Cue timing exists only in the browser so animation can be scrubbed;
+it never enters the Graph or BuildState.
diff --git a/docs/guide/develop.md b/docs/guide/develop.md
index 9fe649c8..e1354d70 100644
--- a/docs/guide/develop.md
+++ b/docs/guide/develop.md
@@ -57,7 +57,7 @@ narratage/
| [Adding an author package](./author-packages.md) | Step-by-step: new component, Surface, activation |
| [Adding a Provider](./providers.md) | Step-by-step: new Endpoint adapter |
| [Runtime Profile](./runtime-profile.md) | JSON and TypeScript configuration, diagnostics, Build archive |
-| [Component playground](./playground.md) | Previewing one visual component without a Build |
+| [Caption Playground](./caption-playground.md) | Edit real Caption SVML/SVS with live feedback |
| [Local services](./services.md) | WhisperX and OpenCV setup |
| [Testing](./testing.md) | Test runner, patterns, examples, boundary tests |
| [Conventions](./conventions.md) | Naming, module boundaries, wire data, TypeScript config |
diff --git a/docs/guide/playground.md b/docs/guide/playground.md
deleted file mode 100644
index 0905640a..00000000
--- a/docs/guide/playground.md
+++ /dev/null
@@ -1,76 +0,0 @@
----
-title: Component Playground
-description: Previewing a visual component without running a Build.
----
-
-# Component Playground
-
-Seeing what a caption or an overlay looks like normally costs a whole Build:
-Author Source, Run Source, a Runtime Profile, generation, alignment, render. The
-playground renders one component on its own, in a browser, in milliseconds.
-
-```bash
-pnpm playground
-```
-
-Then open `http://localhost:5178`. Nothing else is needed — no Runtime Profile,
-no credentials, no local services.
-
-## What you see
-
-| Control | What it does |
-|---|---|
-| Component list | Every module that can put pixels on a frame |
-| W / H / fps / sec / bg | The canvas, the frame domain and the clear colour |
-| Input forms | One per input the component takes |
-| Scrubber | Frame-exact; the counter shows `frame / last` |
-
-The preview runs the installed modules' real Producer handlers and compiles the
-same document a Build would render.
-
-The list and the structural forms are read from public manifests, so a module
-that declares a Producer emitting a `VisualTrack` appears on its own.
-
-## Hard boundary
-
-Two rules are permanent:
-
-1. The Playground is a consumer of the system, never an author of system
- semantics. Production Protocol, Core and domain packages contain no
- Playground defaults, UI hints, fixtures, facets or preview helpers.
-2. The Playground maintains no component, Recipe, Story, Scenario or example
- registry and defines no parallel source format. A startup command may select
- packages and ordinary SVML/SVS/Run sources for that session; selection is not
- a central catalog.
-
-The generic form uses only facts the production contract already needs:
-schema kinds, enums and numeric bounds. Canvas size, duration, frame rate,
-background and blank form values are local session state owned by this tool.
-If the Playground later needs richer controls or fixtures, they must be added
-inside `tools/playground`; a production package must not change for that reason.
-Likewise, examples remain normal project sources rather than entries in a
-Playground-owned registry.
-
-## Media
-
-Content-addressed media is currently entered as an existing digest. The generic
-form deliberately does not reinterpret an arbitrary production string as a file
-picker.
-
-## When something is wrong
-
-A rejected value shows the compiler's own message under the canvas and leaves
-the last good frame on screen, so you can read the error and the picture
-together.
-
-## Known divergences from a real render
-
-- Fonts lower to a plain CSS `font-family` string. The production
- `FontArtifactRef` path with hashed `@font-face` families is not exercised.
-- Audio tracks are not played.
-- A `ProgramSpace` input is filled from the canvas controls rather than offered
- in a form.
-
-See [`tools/playground/README.md`](https://github.com/cashdiffusion/svml/blob/main/tools/playground/README.md)
-for how the timeline shim works and what a module must declare to be
-previewable.
diff --git a/docs/guide/providers.md b/docs/guide/providers.md
index a81578f9..bec821e2 100644
--- a/docs/guide/providers.md
+++ b/docs/guide/providers.md
@@ -172,7 +172,7 @@ Lock into a Runtime package lock:
```bash
pnpm narratage lock-packages <runtime-lock> \
--package @narratage/provider-my-service \
- --root .
+ --package-root .
```
## 7. Reference from svml.runtime.json
diff --git a/docs/guide/runtime-profile.md b/docs/guide/runtime-profile.md
index 10268e13..3b9daaf7 100644
--- a/docs/guide/runtime-profile.md
+++ b/docs/guide/runtime-profile.md
@@ -94,6 +94,19 @@ Two forms are supported:
Credentials are referenced by environment variable name, never stored in the Profile.
+### Filesystem fields
+
+| Field | Meaning |
+|---|---|
+| `root` | Runtime data root. State databases, Artifact storage and relative lock paths are based here. Defaults to the Profile directory. |
+| `packageRoot` | Optional Host override for the `node_modules` supplying both locks. The official CLI defaults to its own installation; the direct local API defaults to `root`. |
+| `packageLock` | Locked deterministic implementation packages, resolved relative to `root`. |
+| `runtimePackageLock` | Locked privileged Runtime adapters, resolved relative to `root`. |
+
+`root` and `packageRoot` are deliberately separate. An external video project can retain all data
+in its own directory while loading verified executable packages from one Narratage installation.
+Neither value enters Author or Run graph identity.
+
### Scheduling
`maxConcurrency` caps total concurrent Operations across all lanes. Each named `lane` has its own
diff --git a/docs/quickstart/composition.md b/docs/quickstart/composition.md
index 0a75c40b..bbd514b6 100644
--- a/docs/quickstart/composition.md
+++ b/docs/quickstart/composition.md
@@ -215,7 +215,7 @@ The complete data flow from Script to rendered video. This example is based on
caption.base {
cue-min-words: 1; cue-max-words: 5;
stack-order: 70; x: 0.08; y: 0.76; width: 0.84;
- font: Inter; weight: 600; size: 58; line-height: 1; align: center;
+ size: 58; line-height: 1; align: center;
fill: #FFFFFF; background: #09090BCC; padding: 16 24; radius: 18;
}
text.title {
diff --git a/docs/quickstart/run.md b/docs/quickstart/run.md
index f0534499..d0ddceb8 100644
--- a/docs/quickstart/run.md
+++ b/docs/quickstart/run.md
@@ -258,6 +258,47 @@ Builds need. When `uv` is not on your PATH the Python step is skipped with a war
`narratage build` will start the required services automatically; you do not need to launch them
yourself.
+#### Keep production projects outside the Narratage checkout
+
+Author files do not have to live under this repository. For example, keep a project at
+`/work/my-film` while using packages installed in `/opt/narratage`:
+
+```bash
+cd /opt/narratage
+
+pnpm narratage lock-packages /work/my-film/svml.packages.lock \
+ --package @narratage/script \
+ --package @narratage/estimate
+
+pnpm narratage plan /work/my-film/build.svrun \
+ --package-lock /work/my-film/svml.packages.lock
+```
+
+The Source Workspace defaults to the directory containing `build.svrun`; its relative Author
+Sources and assets stay inside that boundary. `--package-root` has one unrelated Host purpose: it
+overrides where the CLI locates the installed `node_modules` whose bytes are verified against the
+lock. The official CLI normally supplies its own installation location, so no package path is
+needed above. Use `--root` only when deliberately widening the Source Workspace above the Run
+Source directory. Do not symlink a project into this repository: canonical-path containment
+intentionally rejects that escape.
+
+The official CLI supplies the same installation location while reading the external project's
+Runtime Profile, so the Profile remains portable:
+
+```json
+{
+ "format": "svml.runtime-config@1",
+ "packageLock": "./svml.packages.lock",
+ "runtimePackageLock": "./svml.runtime-packages.lock",
+ "endpoints": [],
+ "permissions": []
+}
+```
+
+Runtime state, archived Artifacts and the lock files remain under `/work/my-film`. Set
+`--package-root` or the Profile's `packageRoot` only when the packages intentionally live somewhere
+other than the CLI installation.
+
### 1. Diagnose the environment
```bash
@@ -292,7 +333,8 @@ pnpm narratage build examples/talking-head-aroll/build.svrun \
|---|---|
| `--runtime` | Path to the Runtime Profile |
| `--package-lock` | Path to the package lock file |
-| `--root` | Workspace root directory |
+| `--package-root` | Host directory containing the installed packages named by the lock |
+| `--root` | Optional Source Workspace boundary; defaults to the entry Source directory |
| `--build-id` | User-chosen identifier for this Build (used for retrieval and reuse) |
| `--follow` | Stream Build progress to the terminal |
diff --git a/docs/quickstart/styles.md b/docs/quickstart/styles.md
index 0ab95276..f3754405 100644
--- a/docs/quickstart/styles.md
+++ b/docs/quickstart/styles.md
@@ -78,8 +78,6 @@ caption.dialogue {
x: 0.08;
y: 0.76;
width: 0.84;
- font: Inter;
- weight: 600;
size: 58;
line-height: 0.96;
align: center;
@@ -96,8 +94,6 @@ caption.dialogue {
| `stack-order` | Z-stacking order among all Tracks (higher = on top) |
| `x`, `y` | Position as fraction of canvas (0–1) |
| `width` | Width as fraction of canvas |
-| `font` | Readable Recipe label; exact bytes come from the required `font=` graph edge |
-| `weight` | Requested font weight (1–1000) |
| `size` | Font size in pixels |
| `line-height` | Line height multiplier |
| `align` | Text alignment: `left`, `center`, `right` |
@@ -107,7 +103,7 @@ caption.dialogue {
| `radius` | Container border radius in pixels |
For reproducible rendering, select an exact installed face in the `.svml` source and pass that
-Record to the Fine Style. The primary face's `weight` and `style` must match the Recipe:
+Record to the Fine Style. Family, weight and style have one source of truth on this exact font edge:
```svml
<fonts:Face id="caption-font" family="inter" weight="600" style="normal"/>
@@ -124,7 +120,7 @@ caption.alice {
cue-min-words: 2; cue-max-words: 5;
stack-order: 70;
x: 0.08; y: 0.76; width: 0.84;
- font: Inter; weight: 600; size: 58;
+ size: 58;
fill: #73FBD3;
background: #09090BCC;
padding: 16 24; radius: 18;
@@ -134,7 +130,7 @@ caption.bob {
cue-min-words: 2; cue-max-words: 5;
stack-order: 70;
x: 0.08; y: 0.76; width: 0.84;
- font: Inter; weight: 600; size: 58;
+ size: 58;
fill: #FFD166;
background: #09090BCC;
padding: 16 24; radius: 18;
@@ -364,8 +360,8 @@ never guesses a font:
font={caption-fonts}/>
```
-`fonts:Stack` emits one generic `FontStackRef`: its primary must match the Recipe's weight/style and
-its fallbacks preserve their own honest metadata. CJK and Emoji can be split into several
+`fonts:Stack` emits one generic `FontStackRef`; its primary and fallbacks preserve their own honest
+metadata. The Caption Recipe does not repeat family, weight or style. CJK and Emoji can be split into several
Unicode-range files while remaining one logical graph edge. Terminal Text and Fine Caption reject
an omitted stack; machine-font fallback is not part of Visual IR.
For a symbol with both text and Emoji presentation, write the authored Unicode Emoji sequence
@@ -414,8 +410,6 @@ A complete `studio.svs` file for a four-take talking-head project:
x: 0.08;
y: 0.74;
width: 0.84;
- font: Inter;
- weight: 800;
size: 44;
line-height: 1;
align: center;
diff --git a/docs/quickstart/tracks.md b/docs/quickstart/tracks.md
index a5157865..cc6ad348 100644
--- a/docs/quickstart/tracks.md
+++ b/docs/quickstart/tracks.md
@@ -44,7 +44,7 @@ caption.primary {
cue-max-words: 7;
stack-order: 70; x: 0.5; y: 0.88; width: 0.84;
anchor-x: center; anchor-y: bottom;
- font: Inter; weight: 700; size: 58; font-style: normal;
+ size: 58;
line-height: 0.96; letter-spacing: -0.5; word-gap: 14;
align: center; direction: ltr;
fill: #FFFFFF; opacity: 1;
@@ -77,8 +77,8 @@ caption.primary {
font={caption-fonts}/>
```
-The required `font=` edge carries one byte-reproducible `FontStackRef`. The primary face must match
-the Recipe's weight/style; each fallback retains its own exact face metadata. Fine rejects a Style
+The required `font=` edge carries one byte-reproducible `FontStackRef`. Family, weight and style
+exist only on that edge; each fallback retains its own exact face metadata. Fine rejects a Style
without that stack instead of falling back to machine fonts.
Another Caption package may define completely different planning fields and visual parameters
diff --git a/docs/zh/guide/author-packages.md b/docs/zh/guide/author-packages.md
index 0ca760ef..b549ce6c 100644
--- a/docs/zh/guide/author-packages.md
+++ b/docs/zh/guide/author-packages.md
@@ -128,10 +128,13 @@ pnpm install --frozen-lockfile
pnpm narratage lock-packages <lock-file> \
--package @narratage/my-component \
- [--package @narratage/other-dep ...] \
- --root .
+ [--package @narratage/other-direct-package ...] \
+ --package-root .
```
+这里只列出你直接选择的包。它们的 Manifest 声明的精确逻辑 Module 依赖,会从已安装的
+物理依赖闭包中自动加入;缺失、摘要不匹配或存在多个候选时,建锁会直接失败。
+
## 8. 在 Author Source 中使用
```xml
diff --git a/docs/zh/guide/caption-playground.md b/docs/zh/guide/caption-playground.md
new file mode 100644
index 00000000..de3105af
--- /dev/null
+++ b/docs/zh/guide/caption-playground.md
@@ -0,0 +1,39 @@
+---
+title: 字幕 Playground
+description: 直接编辑真实 Fine Caption SVS 配方与精确字体栈,并实时查看结果。
+---
+
+# 字幕 Playground
+
+字幕样式确实需要可视化编辑,但编辑器不能变成第二套作者系统。字幕
+Playground 直接读写普通 Build 使用的同一份 `.svml` 与 `.svs`。
+
+```bash
+pnpm caption:playground -- \
+ --source examples/talking-film-graph-check/main.svml \
+ --package-lock examples/talking-film-graph-check/svml.packages.lock \
+ --style base-caption \
+ --display story.caption \
+ --recipe examples/talking-film-graph-check/studio.svs#caption.base \
+ --font examples/talking-film-graph-check/main.svml#caption-font \
+ --canvas 1080x1920 \
+ --fps 30
+```
+
+打开 `http://localhost:5178`。
+
+启动命令显式选择源码、包锁、Style 导出、Display 导出、SVS Recipe、
+字体栈以及本地预览画布。系统没有中央组件注册表、隐藏默认样式或
+Playground 私有工程文件。
+
+表单编辑的是作者语汇,例如 `size`、`padding`、`fill`,不会暴露
+`fontSizePx`、`paddingXPx` 之类编译 DTO。字体家族、字重、字形只在
+SVML 的 `<fonts:Stack>` 中声明;SVS 负责字号、位置、绘制、文字盒、
+卡拉 OK 与动画。
+
+字体画廊使用每种开源字体自己的固定字节直接展示。选择字体会原子地
+修改真实字体栈并重新编译。编辑器或 Agent 修改同一文件也会触发刷新;
+浏览器提交时带有旧文件摘要,过期写入不会覆盖更新内容。
+
+为了拖动查看动画,浏览器会临时安排一条展示时间线。这条时间线不写入
+Record、SemanticMap、BuildState 或源文件,不会把猜测时间传播进图中。
diff --git a/docs/zh/guide/develop.md b/docs/zh/guide/develop.md
index 15d3e2f0..b8b629f1 100644
--- a/docs/zh/guide/develop.md
+++ b/docs/zh/guide/develop.md
@@ -57,7 +57,7 @@ narratage/
| [添加 Author 包](./author-packages.md) | 分步说明:新增组件、Surface、activation |
| [添加 Provider](./providers.md) | 分步说明:新增 Endpoint 适配器 |
| [Runtime Profile](./runtime-profile.md) | JSON 与 TypeScript 配置、诊断、Build 归档 |
-| [组件 Playground](./playground.md) | 不跑 Build 预览单个视觉组件 |
+| [字幕 Playground](./caption-playground.md) | 直接编辑真实字幕 SVML/SVS 并实时预览 |
| [本地服务](./services.md) | WhisperX 与 OpenCV 的搭建 |
| [测试](./testing.md) | 测试运行器、写法、示例、boundary tests |
| [代码规范](./conventions.md) | 命名、模块边界、wire 数据、TypeScript 配置 |
diff --git a/docs/zh/guide/playground.md b/docs/zh/guide/playground.md
deleted file mode 100644
index 27953d8e..00000000
--- a/docs/zh/guide/playground.md
+++ /dev/null
@@ -1,60 +0,0 @@
----
-title: 组件 Playground
-description: 不跑 Build 也能预览视觉组件。
----
-
-# 组件 Playground
-
-想看一条字幕或一个文字层长什么样,通常要付出一整次 Build 的代价:Author Source、Run Source、
-Runtime Profile、生成、对齐、渲染。Playground 在浏览器里单独渲染一个组件,耗时以毫秒计。
-
-```bash
-pnpm playground
-```
-
-然后打开 `http://localhost:5178`。不需要别的——没有 Runtime Profile,没有凭据,也不需要本地服务。
-
-## 界面
-
-| 控件 | 作用 |
-|---|---|
-| 组件下拉 | 所有能在画面上产生像素的模块 |
-| W / H / fps / sec / bg | 画布、帧域与清除颜色 |
-| 输入表单 | 组件每个输入各一份 |
-| 刻度条 | 帧精确,计数显示为 `当前帧 / 末帧` |
-
-预览运行的是已安装模块真正的 Producer handler,编译出的文档与 Build 渲染的是同一份。
-
-下拉与结构化表单都读自公开 manifest,所以只要模块声明了「输出 `VisualTrack` 的 Producer」,它自己就会出现。
-
-## 硬边界
-
-两条规则永久成立:
-
-1. Playground 只能消费系统,不能定义系统语义。生产 Protocol、Core 与领域包中不得出现任何
- Playground 默认值、UI 提示、fixture、facet 或预览辅助函数。
-2. Playground 不维护组件、Recipe、Story、Scenario 或示例注册表,也不定义一套平行的源码格式。
- 启动命令可以为本次会话选择包和普通 SVML/SVS/Run 源码;这种局部选择不是中央目录。
-
-通用表单只消费生产合同本来就需要的事实:schema 类型、枚举和数值边界。画布大小、时长、
-帧率、背景色和空白表单值都只是本工具内部的会话状态。如果以后需要更丰富的控件或 fixture,
-必须在 `tools/playground` 内部实现,不能要求生产包为预览便利而改变。
-示例同样必须是普通项目源码,不能成为 Playground 自有注册表中的条目。
-
-## 媒体
-
-内容寻址媒体目前需要填写已有 digest。通用表单不会把生产合同中的任意字符串擅自解释成文件选择器。
-
-## 出错时
-
-被拒绝的值会把编译器原本的报错显示在画布下方,并保留上一帧正确画面,让你能同时看到错误和图像。
-
-## 与真实渲染的已知偏差
-
-- 字体降级为普通 CSS `font-family` 字符串,不会走生产环境中带哈希 `@font-face` 的
- `FontArtifactRef` 路径。
-- 不播放音频轨。
-- `ProgramSpace` 输入由画布控件填充,不出现在表单里。
-
-时间线 shim 的原理、以及一个模块需要声明什么才能被预览,见
-[`tools/playground/README.md`](https://github.com/cashdiffusion/svml/blob/main/tools/playground/README.md)。
diff --git a/docs/zh/guide/providers.md b/docs/zh/guide/providers.md
index 97d9dcef..d93ab2c5 100644
--- a/docs/zh/guide/providers.md
+++ b/docs/zh/guide/providers.md
@@ -165,7 +165,7 @@ const adapter = createRuntimeEndpointAdapterFacet({
```bash
pnpm narratage lock-packages <runtime-lock> \
--package @narratage/provider-my-service \
- --root .
+ --package-root .
```
## 7. 在 svml.runtime.json 中引用
diff --git a/docs/zh/guide/runtime-profile.md b/docs/zh/guide/runtime-profile.md
index e55a0c5f..c2c600b8 100644
--- a/docs/zh/guide/runtime-profile.md
+++ b/docs/zh/guide/runtime-profile.md
@@ -92,6 +92,18 @@ Runtime Profile 声明冻结后的 Build *在哪里*执行:Endpoint、凭据
凭据通过环境变量名引用,绝不存放在 Profile 里。
+### 文件系统字段
+
+| 字段 | 含义 |
+|---|---|
+| `root` | Runtime 数据根目录;状态数据库、Artifact 存储和相对 lock 路径都以此为基准。默认是 Profile 所在目录。 |
+| `packageRoot` | 为两份 lock 提供 `node_modules` 的可选 Host 覆盖项。官方 CLI 默认使用自身安装位置;直接调用本地 API 时默认等于 `root`。 |
+| `packageLock` | 确定性实现包的 lock;相对 `root` 解析。 |
+| `runtimePackageLock` | 有权限的 Runtime Adapter lock;相对 `root` 解析。 |
+
+`root` 与 `packageRoot` 有意分离。外部视频项目可以把全部数据留在自己的目录,同时从一个
+Narratage 安装目录加载经过校验的可执行包。两者都不进入 Author Graph 或 Run Graph 身份。
+
### 调度
`maxConcurrency` 限制所有 lane 上并发 Operation 的总量。每个具名 lane 还有自己的子上限。lane 由 Endpoint 声明,并由 Scheduler 强制执行。
diff --git a/docs/zh/quickstart/composition.md b/docs/zh/quickstart/composition.md
index 3f3c7ae3..1821ab46 100644
--- a/docs/zh/quickstart/composition.md
+++ b/docs/zh/quickstart/composition.md
@@ -211,7 +211,7 @@ Build Target,也可以直接接到媒体裁切、音频/帧提取或模型参
caption.base {
cue-min-words: 1; cue-max-words: 5;
stack-order: 70; x: 0.08; y: 0.76; width: 0.84;
- font: Inter; weight: 600; size: 58; line-height: 1; align: center;
+ size: 58; line-height: 1; align: center;
fill: #FFFFFF; background: #09090BCC; padding: 16 24; radius: 18;
}
text.title {
diff --git a/docs/zh/quickstart/run.md b/docs/zh/quickstart/run.md
index bf9d20f5..c0cb1df7 100644
--- a/docs/zh/quickstart/run.md
+++ b/docs/zh/quickstart/run.md
@@ -245,6 +245,43 @@ pnpm install
`narratage build` 会自动启动所需的服务,无需手动启动。
+#### 把正式视频项目放在 Narratage 仓库之外
+
+作者文件不必位于本仓库之下。例如,项目放在 `/work/my-film`,同时复用
+`/opt/narratage` 中已安装的包:
+
+```bash
+cd /opt/narratage
+
+pnpm narratage lock-packages /work/my-film/svml.packages.lock \
+ --package @narratage/script \
+ --package @narratage/estimate
+
+pnpm narratage plan /work/my-film/build.svrun \
+ --package-lock /work/my-film/svml.packages.lock
+```
+
+Source Workspace 默认是 `build.svrun` 所在目录;相对引用的 Author Source 与素材都必须留在
+这个边界内。`--package-root` 是另一项无关的 Host 覆盖项:它只负责指定已安装的
+`node_modules`,然后按照 lock 校验包字节。官方 CLI 通常会自动提供自身的安装位置,所以
+上面的命令无需填写包路径。只有需要主动扩大源码边界时才传 `--root`。不要把外部项目软
+链接进仓库;canonical path 的边界检查会有意拒绝这种逃逸。
+
+官方 CLI 读取外部项目的 Runtime Profile 时也会提供同一个安装位置,因此 Profile 仍可移植:
+
+```json
+{
+ "format": "svml.runtime-config@1",
+ "packageLock": "./svml.packages.lock",
+ "runtimePackageLock": "./svml.runtime-packages.lock",
+ "endpoints": [],
+ "permissions": []
+}
+```
+
+Runtime 状态、归档 Artifact 和 lock 仍全部留在 `/work/my-film`。只有包被有意安装在 CLI
+之外时,才使用 `--package-root` 或 Profile 的 `packageRoot` 覆盖位置。
+
### 1. 诊断环境
```bash
@@ -277,7 +314,8 @@ pnpm narratage build examples/talking-head-aroll/build.svrun \
|---|---|
| `--runtime` | Runtime Profile 的路径 |
| `--package-lock` | 包锁定文件的路径 |
-| `--root` | 工作区根目录 |
+| `--package-root` | 存放 lock 所列已安装包的 Host 目录 |
+| `--root` | 可选的 Source Workspace 边界;默认是入口 Source 所在目录 |
| `--build-id` | 用户为此 Build 选择的标识符(用于检索和复用) |
| `--follow` | 将 Build 进度流式输出到终端 |
diff --git a/docs/zh/quickstart/styles.md b/docs/zh/quickstart/styles.md
index 1e3c407c..a68a595c 100644
--- a/docs/zh/quickstart/styles.md
+++ b/docs/zh/quickstart/styles.md
@@ -74,8 +74,6 @@ caption.dialogue {
x: 0.08;
y: 0.76;
width: 0.84;
- font: Inter;
- weight: 600;
size: 58;
line-height: 0.96;
align: center;
@@ -92,8 +90,6 @@ caption.dialogue {
| `stack-order` | 所有 Track 之间的 Z 轴层叠顺序(值越大越靠前) |
| `x`、`y` | 位置,以画布比例表示(0–1) |
| `width` | 宽度,以画布比例表示 |
-| `font` | Recipe 中便于阅读的字体标签;精确字节来自必填的 `font=` 图边 |
-| `weight` | 请求的字体粗细(1–1000) |
| `size` | 字体大小(像素) |
| `line-height` | 行高倍数 |
| `align` | 文本对齐方式:`left`、`center`、`right` |
@@ -103,7 +99,7 @@ caption.dialogue {
| `radius` | 容器圆角半径(像素) |
若要可复现渲染,应在 `.svml` 源码中显式选择已安装的精确字体,并把该 Record 传给 Fine
-Style。主字体的 `weight` 与 `style` 必须和 Recipe 一致:
+Style。字体家族、字重和字形只在这条精确字体边上声明一次:
```svml
<fonts:Face id="caption-font" family="inter" weight="600" style="normal"/>
@@ -120,7 +116,7 @@ caption.alice {
cue-min-words: 2; cue-max-words: 5;
stack-order: 70;
x: 0.08; y: 0.76; width: 0.84;
- font: Inter; weight: 600; size: 58;
+ size: 58;
fill: #73FBD3;
background: #09090BCC;
padding: 16 24; radius: 18;
@@ -130,7 +126,7 @@ caption.bob {
cue-min-words: 2; cue-max-words: 5;
stack-order: 70;
x: 0.08; y: 0.76; width: 0.84;
- font: Inter; weight: 600; size: 58;
+ size: 58;
fill: #FFD166;
background: #09090BCC;
padding: 16 24; radius: 18;
@@ -354,8 +350,8 @@ SVS 描述字体策略,但不选择或打开字体字节。常用开源字体
font={caption-fonts}/>
```
-`fonts:Stack` 产出通用 `FontStackRef`:主字体必须和 Recipe 的 weight/style 一致,Fallback
-保留自己的真实元数据。CJK 与 Emoji 即使由多个 Unicode-range 文件组成,在作者图中仍是
+`fonts:Stack` 产出通用 `FontStackRef`,主字体与 Fallback 都保留自己的真实元数据;
+Caption Recipe 不再重复家族、字重或字形。CJK 与 Emoji 即使由多个 Unicode-range 文件组成,在作者图中仍是
一条逻辑边。终端 Text 与 Fine Caption 都拒绝省略字体栈;Visual IR 不接受机器字体兜底。
对于同时具有文本与 Emoji 两种呈现的符号,作者应写真实的 Unicode Emoji 序列(例如
包含 VS16 的 `☎️`);任何包都不会为了强制彩色而改写显示稿。
@@ -403,8 +399,6 @@ SVS 描述字体策略,但不选择或打开字体字节。常用开源字体
x: 0.08;
y: 0.74;
width: 0.84;
- font: Inter;
- weight: 800;
size: 44;
line-height: 1;
align: center;
diff --git a/docs/zh/quickstart/tracks.md b/docs/zh/quickstart/tracks.md
index f7c3196b..d771ea06 100644
--- a/docs/zh/quickstart/tracks.md
+++ b/docs/zh/quickstart/tracks.md
@@ -40,7 +40,7 @@ caption.primary {
cue-min-words: 2; cue-max-words: 7;
stack-order: 70; x: 0.5; y: 0.88; width: 0.84;
anchor-x: center; anchor-y: bottom;
- font: Inter; weight: 700; size: 58; line-height: 1; align: center;
+ size: 58; line-height: 1; align: center;
fill: #FFFFFF; stroke-color: #09090B; stroke-width: 2;
background: #00000000; padding: 0; radius: 0;
karaoke: trail; karaoke-transition: wipe; active-fill: #FFD54A;
@@ -60,11 +60,11 @@ caption.primary {
font={caption-fonts}/>
```
-必填的 `font=` 边携带一个按字节复现的 `FontStackRef`。主字体必须与 Recipe
-的 weight/style 一致;每个 Fallback 保留自己的真实字体信息。省略字体栈会在编译时
+必填的 `font=` 边携带一个按字节复现的 `FontStackRef`。字体家族、字重和字形只在这条
+边上声明一次;每个 Fallback 保留自己的真实字体信息。省略字体栈会在编译时
失败,不会退回当前机器上的同名字体。
-Recipe 同时包含 `cue-min-words`、`cue-max-words` 和完整字体/框参数。Fine 不声明任何
+Recipe 同时包含 `cue-min-words`、`cue-max-words` 和完整字号/外观/框参数。Fine 不声明任何
逐词字段;其他字幕包可以定义完全不同的字段和渲染方式,无需修改公共 Caption。
Fine 不是一组互斥预设。基础/激活渐变、描边、阴影、长阴影、外发光、下划线、Pill
diff --git a/examples/talking-film-golden/studio.svs b/examples/talking-film-golden/studio.svs
index 1fa0257e..44279403 100644
--- a/examples/talking-film-golden/studio.svs
+++ b/examples/talking-film-golden/studio.svs
@@ -60,8 +60,6 @@
x: 0.08;
y: 0.76;
width: 0.84;
- font: inter-semibold;
- weight: 600;
size: 58;
line-height: 0.96;
align: center;
@@ -78,8 +76,6 @@
x: 0.08;
y: 0.76;
width: 0.84;
- font: inter-semibold;
- weight: 600;
size: 58;
line-height: 0.96;
align: center;
@@ -96,8 +92,6 @@
x: 0.08;
y: 0.76;
width: 0.84;
- font: inter-semibold;
- weight: 600;
size: 58;
line-height: 0.96;
align: center;
diff --git a/examples/talking-film-graph-check/studio.svs b/examples/talking-film-graph-check/studio.svs
index 2b5813be..99821095 100644
--- a/examples/talking-film-graph-check/studio.svs
+++ b/examples/talking-film-graph-check/studio.svs
@@ -13,7 +13,7 @@
caption.base {
cue-min-words: 1; cue-max-words: 5;
stack-order: 70; x: 0.5; y: 0.88; width: 0.84; anchor-x: center; anchor-y: bottom;
- font: Inter; weight: 700; size: 58; line-height: 1; align: center;
+ size: 58; line-height: 1; align: center;
fill: #FFFFFF; stroke-color: #09090B; stroke-width: 2;
shadow-color: #000000; shadow-opacity: 0.72; shadow-x: 0; shadow-y: 3; shadow-blur: 8;
glow-color: #FFFFFF; glow-opacity: 0.12; glow-blur: 8;
diff --git a/examples/talking-film-graph-check/svml.packages.lock b/examples/talking-film-graph-check/svml.packages.lock
index 21acba5c..4da609b9 100644
--- a/examples/talking-film-graph-check/svml.packages.lock
+++ b/examples/talking-film-graph-check/svml.packages.lock
@@ -1,5 +1,38 @@
{
"format": "svml.node-package-lock@1",
+ "selected": [
+ "@narratage/artifact",
+ "@narratage/caption",
+ "@narratage/caption-fine",
+ "@narratage/caption-gemini",
+ "@narratage/composition",
+ "@narratage/film",
+ "@narratage/fonts-open",
+ "@narratage/generation",
+ "@narratage/hyperframes",
+ "@narratage/media",
+ "@narratage/media-pipeline",
+ "@narratage/media-track",
+ "@narratage/narrative",
+ "@narratage/program-space",
+ "@narratage/render-hyperframes",
+ "@narratage/run-markup",
+ "@narratage/script",
+ "@narratage/seedance",
+ "@narratage/semantic-map",
+ "@narratage/spatial",
+ "@narratage/speech",
+ "@narratage/speech-alignment",
+ "@narratage/speech-basis",
+ "@narratage/speech-evidence",
+ "@narratage/speech-spine",
+ "@narratage/svs",
+ "@narratage/temporal",
+ "@narratage/text",
+ "@narratage/typography-track",
+ "@narratage/visual-ir",
+ "@narratage/whisperx"
+ ],
"artifacts": [
{
"name": "@fontsource-variable/archivo",
@@ -554,7 +587,7 @@
{
"name": "@narratage/caption-fine",
"version": "0.0.0-dev",
- "digest": "sha256:8094384ca1980ee72e0a5621a7ee9d62aec167521fdb536eb068eeeecee2ec9c"
+ "digest": "sha256:b66c7ab8ce58cad4c6254f1d18b4be3fbdd353b6910fc7a2657cb09781a6ecc7"
},
{
"name": "@narratage/caption-gemini",
@@ -719,7 +752,7 @@
{
"name": "@narratage/svs",
"version": "0.0.0-dev",
- "digest": "sha256:e44ae945c23e041602eb2f029a4c72b96fc2525e6c767e117e2bf0f11a830e0e"
+ "digest": "sha256:2658027814f0be50cfea761cf5a7ee42004dc30d7b9e252750940a7a8fcddca5"
},
{
"name": "@narratage/temporal",
@@ -778,7 +811,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:c5616408dd56ce9c903523319b2a697ff6b8af5bfe1dc66fe793a11e4629f3cf",
- "closureDigest": "sha256:79c0da36f1526e8fab9682b3255667599d9dcd67b584602b7b60713fee841f97"
+ "closureDigest": "sha256:3ba4088d7e8703f27748b52ba9e4964d799d474c22d9da17afb2c0d7625a8a80"
},
{
"specifier": "@narratage/caption-gemini",
@@ -805,7 +838,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:8e58b5630b9a68a8ce7314620f5f1c7cda973a05c179c18d61e10d68002964f0",
- "closureDigest": "sha256:defb86a53cf0e6683fe54592ac168e307a5e32b1e76ce851d5d9804fd0ef7095"
+ "closureDigest": "sha256:f78c843e6e47e0571f922caecb294c60dd5b423658a0b98fc7377db3cbdafbd0"
},
{
"specifier": "@narratage/fonts-open",
@@ -823,7 +856,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:d74a57a3210267e665366513324db5c313b3ca0f770da66e74cc38aee5048efb",
- "closureDigest": "sha256:f0999a26b4590b0110e25256f892ad580540618c07c436e916672c3cb371eca2"
+ "closureDigest": "sha256:0a3093f555ce7e80832dd1fec8a5d575fcf2b3b86a0ecf4e840babd7d9080120"
},
{
"specifier": "@narratage/hyperframes",
@@ -859,7 +892,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:bb26c54c0ad8802ee8c7cd6f13314c90dd7de7e937ded1c501367e19693fe3b1",
- "closureDigest": "sha256:887a248210fe92c66575cd8f4943d353a7007f4ce51e81411aa446a17d6d5f63"
+ "closureDigest": "sha256:feab5487260d97a8ed806c0b18aa78c6898a230f3045e462900d69ee7e4c9e92"
},
{
"specifier": "@narratage/narrative",
@@ -904,7 +937,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:69e1c08a5f07c73a506ca8286426a0386485738649e86463cca0b291f319ee4e",
- "closureDigest": "sha256:dfded35adc0aa0d163fba58d375fccc9a69b4ad1168744dc9c2826b9f914cd78"
+ "closureDigest": "sha256:5031128c71900c50b7ca9527bbbfabc85b0f310a9fc84034959df8b4b35c65d2"
},
{
"specifier": "@narratage/seedance",
@@ -913,7 +946,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:e889ca3808a19f544e7aa5e27453beb5a09464c645633b0b1b1d9a4b7ce6591a",
- "closureDigest": "sha256:dfba58117095497c73bd830149da98ce3e560d4ef9201a3e793286c059ade869"
+ "closureDigest": "sha256:193c1f9937adbd21bc0dbac47cbfb18a0f5cc15d7748de3d7717fb1683739004"
},
{
"specifier": "@narratage/semantic-map",
@@ -958,7 +991,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:f01f21badb0ccdd5cc62b131be05f46030bffee96042c7323a0c572786d012ef",
- "closureDigest": "sha256:992c1bda3746087ee746b03eee75fe8309d0b5f351f9ebb1da7e6b5793d37e54"
+ "closureDigest": "sha256:725bd1a8411596f0ad284260e7f3c189eaa9d20bd46706ee824b0848eadc019e"
},
{
"specifier": "@narratage/speech-evidence",
@@ -976,7 +1009,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:a27dd4349d6bb1aaa7f382ad09f883e9894157579e48285b00e8fa24456190f7",
- "closureDigest": "sha256:8f52117330a8c3c08e2346ba08e8c61fe05a92d776a142e405e1b397ee778584"
+ "closureDigest": "sha256:af643b38d811656e465a06d24eaebe7d0de7c184f86a13db56b244a4463373b8"
},
{
"specifier": "@narratage/svs",
@@ -985,7 +1018,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:9cc7c397d2cd97b5a3e814886b6553b6d236fd8825df0d056e328b7f0cf20163",
- "closureDigest": "sha256:6ee450114180d7f6f515b834a9cf1000795007b3ec8e57ba6860b30320fb2eba"
+ "closureDigest": "sha256:4c93cdef1bbace70ff11792777622049b5262a593a2b4d7b890afc9543955ba2"
},
{
"specifier": "@narratage/temporal",
@@ -1003,7 +1036,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:4435dd4bd38e5e017013f775e28e379e3e235211649ee8f3913378f7f9e60b58",
- "closureDigest": "sha256:888a51aafa5225bee3cd589318f12e2974735ddea62e96d2bf8a098ad39b1389"
+ "closureDigest": "sha256:9d50fa2a214341b4af403dbf3e89332ac4b35aefc234ff35e0b066b32ee20243"
},
{
"specifier": "@narratage/typography-track",
@@ -1012,7 +1045,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:cc8349fec027f43e01a8832ba8a7050490e924851cee3325d3568cb5bc5fd57f",
- "closureDigest": "sha256:dd59ced7a21d5aba3b6e3aa1e6e83e4b32325409bbbe91afc616cd1ebf2047ca"
+ "closureDigest": "sha256:cb8f564bad8252f0e369e9ecc0e0255b1086edd229b93be0ef3b0b54bb234526"
},
{
"specifier": "@narratage/visual-ir",
@@ -1033,5 +1066,5 @@
"closureDigest": "sha256:100c9aef680d5cba8ebf6abe9e51bf1c6cdf7ae092144fbed3e35857ad8d88b9"
}
],
- "digest": "sha256:de6e20272897d7a75f97edaa0f7de4ab9d2082fbb42fa6e9c08f9361fe8ad9df"
+ "digest": "sha256:2dfa17718e21be3060ff4a39c7c612b2f28de6c595f0667a23188adf78a478a7"
}
diff --git a/examples/talking-film-live/studio.svs b/examples/talking-film-live/studio.svs
index b726225c..92261acb 100644
--- a/examples/talking-film-live/studio.svs
+++ b/examples/talking-film-live/studio.svs
@@ -12,8 +12,6 @@
x: 0.08;
y: 0.74;
width: 0.84;
- font: Inter;
- weight: 700;
size: 30;
line-height: 1;
align: center;
diff --git a/examples/talking-film-live/svml.packages.lock b/examples/talking-film-live/svml.packages.lock
index a4deec31..03be73dd 100644
--- a/examples/talking-film-live/svml.packages.lock
+++ b/examples/talking-film-live/svml.packages.lock
@@ -1,5 +1,39 @@
{
"format": "svml.node-package-lock@1",
+ "selected": [
+ "@narratage/artifact",
+ "@narratage/caption",
+ "@narratage/caption-fine",
+ "@narratage/caption-gemini",
+ "@narratage/composition",
+ "@narratage/estimate",
+ "@narratage/film",
+ "@narratage/fonts-open",
+ "@narratage/generation",
+ "@narratage/hyperframes",
+ "@narratage/media",
+ "@narratage/media-pipeline",
+ "@narratage/media-track",
+ "@narratage/narrative",
+ "@narratage/program-space",
+ "@narratage/render-hyperframes",
+ "@narratage/run-markup",
+ "@narratage/script",
+ "@narratage/seedance",
+ "@narratage/semantic-map",
+ "@narratage/spatial",
+ "@narratage/speech",
+ "@narratage/speech-alignment",
+ "@narratage/speech-basis",
+ "@narratage/speech-evidence",
+ "@narratage/speech-spine",
+ "@narratage/svs",
+ "@narratage/temporal",
+ "@narratage/text",
+ "@narratage/typography-track",
+ "@narratage/visual-ir",
+ "@narratage/whisperx"
+ ],
"artifacts": [
{
"name": "@fontsource-variable/archivo",
@@ -554,7 +588,7 @@
{
"name": "@narratage/caption-fine",
"version": "0.0.0-dev",
- "digest": "sha256:8094384ca1980ee72e0a5621a7ee9d62aec167521fdb536eb068eeeecee2ec9c"
+ "digest": "sha256:b66c7ab8ce58cad4c6254f1d18b4be3fbdd353b6910fc7a2657cb09781a6ecc7"
},
{
"name": "@narratage/caption-gemini",
@@ -724,7 +758,7 @@
{
"name": "@narratage/svs",
"version": "0.0.0-dev",
- "digest": "sha256:e44ae945c23e041602eb2f029a4c72b96fc2525e6c767e117e2bf0f11a830e0e"
+ "digest": "sha256:2658027814f0be50cfea761cf5a7ee42004dc30d7b9e252750940a7a8fcddca5"
},
{
"name": "@narratage/temporal",
@@ -788,7 +822,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:c5616408dd56ce9c903523319b2a697ff6b8af5bfe1dc66fe793a11e4629f3cf",
- "closureDigest": "sha256:79c0da36f1526e8fab9682b3255667599d9dcd67b584602b7b60713fee841f97"
+ "closureDigest": "sha256:3ba4088d7e8703f27748b52ba9e4964d799d474c22d9da17afb2c0d7625a8a80"
},
{
"specifier": "@narratage/caption-gemini",
@@ -815,7 +849,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:9975815b3109520eb6bba276554a90767a9aebff6498c2768d9faf4763219bef",
- "closureDigest": "sha256:8c7022b670c9ba8bb33c58540775a65f0da7e5f8d149ca2494bba34fbd3df8a2"
+ "closureDigest": "sha256:811be87579f5934cdcf1289253cc31e835b3fc9f97a4911ad88fc01a387f7d65"
},
{
"specifier": "@narratage/film",
@@ -824,7 +858,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:8e58b5630b9a68a8ce7314620f5f1c7cda973a05c179c18d61e10d68002964f0",
- "closureDigest": "sha256:defb86a53cf0e6683fe54592ac168e307a5e32b1e76ce851d5d9804fd0ef7095"
+ "closureDigest": "sha256:f78c843e6e47e0571f922caecb294c60dd5b423658a0b98fc7377db3cbdafbd0"
},
{
"specifier": "@narratage/fonts-open",
@@ -842,7 +876,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:d74a57a3210267e665366513324db5c313b3ca0f770da66e74cc38aee5048efb",
- "closureDigest": "sha256:f0999a26b4590b0110e25256f892ad580540618c07c436e916672c3cb371eca2"
+ "closureDigest": "sha256:0a3093f555ce7e80832dd1fec8a5d575fcf2b3b86a0ecf4e840babd7d9080120"
},
{
"specifier": "@narratage/hyperframes",
@@ -878,7 +912,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:bb26c54c0ad8802ee8c7cd6f13314c90dd7de7e937ded1c501367e19693fe3b1",
- "closureDigest": "sha256:887a248210fe92c66575cd8f4943d353a7007f4ce51e81411aa446a17d6d5f63"
+ "closureDigest": "sha256:feab5487260d97a8ed806c0b18aa78c6898a230f3045e462900d69ee7e4c9e92"
},
{
"specifier": "@narratage/narrative",
@@ -923,7 +957,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:69e1c08a5f07c73a506ca8286426a0386485738649e86463cca0b291f319ee4e",
- "closureDigest": "sha256:dfded35adc0aa0d163fba58d375fccc9a69b4ad1168744dc9c2826b9f914cd78"
+ "closureDigest": "sha256:5031128c71900c50b7ca9527bbbfabc85b0f310a9fc84034959df8b4b35c65d2"
},
{
"specifier": "@narratage/seedance",
@@ -932,7 +966,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:e889ca3808a19f544e7aa5e27453beb5a09464c645633b0b1b1d9a4b7ce6591a",
- "closureDigest": "sha256:dfba58117095497c73bd830149da98ce3e560d4ef9201a3e793286c059ade869"
+ "closureDigest": "sha256:193c1f9937adbd21bc0dbac47cbfb18a0f5cc15d7748de3d7717fb1683739004"
},
{
"specifier": "@narratage/semantic-map",
@@ -977,7 +1011,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:f01f21badb0ccdd5cc62b131be05f46030bffee96042c7323a0c572786d012ef",
- "closureDigest": "sha256:992c1bda3746087ee746b03eee75fe8309d0b5f351f9ebb1da7e6b5793d37e54"
+ "closureDigest": "sha256:725bd1a8411596f0ad284260e7f3c189eaa9d20bd46706ee824b0848eadc019e"
},
{
"specifier": "@narratage/speech-evidence",
@@ -995,7 +1029,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:a27dd4349d6bb1aaa7f382ad09f883e9894157579e48285b00e8fa24456190f7",
- "closureDigest": "sha256:8f52117330a8c3c08e2346ba08e8c61fe05a92d776a142e405e1b397ee778584"
+ "closureDigest": "sha256:af643b38d811656e465a06d24eaebe7d0de7c184f86a13db56b244a4463373b8"
},
{
"specifier": "@narratage/svs",
@@ -1004,7 +1038,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:9cc7c397d2cd97b5a3e814886b6553b6d236fd8825df0d056e328b7f0cf20163",
- "closureDigest": "sha256:6ee450114180d7f6f515b834a9cf1000795007b3ec8e57ba6860b30320fb2eba"
+ "closureDigest": "sha256:4c93cdef1bbace70ff11792777622049b5262a593a2b4d7b890afc9543955ba2"
},
{
"specifier": "@narratage/temporal",
@@ -1022,7 +1056,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:4435dd4bd38e5e017013f775e28e379e3e235211649ee8f3913378f7f9e60b58",
- "closureDigest": "sha256:888a51aafa5225bee3cd589318f12e2974735ddea62e96d2bf8a098ad39b1389"
+ "closureDigest": "sha256:9d50fa2a214341b4af403dbf3e89332ac4b35aefc234ff35e0b066b32ee20243"
},
{
"specifier": "@narratage/typography-track",
@@ -1031,7 +1065,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:cc8349fec027f43e01a8832ba8a7050490e924851cee3325d3568cb5bc5fd57f",
- "closureDigest": "sha256:dd59ced7a21d5aba3b6e3aa1e6e83e4b32325409bbbe91afc616cd1ebf2047ca"
+ "closureDigest": "sha256:cb8f564bad8252f0e369e9ecc0e0255b1086edd229b93be0ef3b0b54bb234526"
},
{
"specifier": "@narratage/visual-ir",
@@ -1052,5 +1086,5 @@
"closureDigest": "sha256:100c9aef680d5cba8ebf6abe9e51bf1c6cdf7ae092144fbed3e35857ad8d88b9"
}
],
- "digest": "sha256:c31ecd0c8525a1bac674dd4637194965a9018146727bd7546ead8c44f32aad6e"
+ "digest": "sha256:3174f8a8c8590dbdbdd0352c34b46133ee53d5217cc5212d0a8ad917736401a2"
}
diff --git a/examples/talking-film-live/svml.runtime-packages.lock b/examples/talking-film-live/svml.runtime-packages.lock
index c54cf422..5f6f9306 100644
--- a/examples/talking-film-live/svml.runtime-packages.lock
+++ b/examples/talking-film-live/svml.runtime-packages.lock
@@ -1,5 +1,12 @@
{
"format": "svml.node-package-lock@1",
+ "selected": [
+ "@narratage/provider-google-vertex",
+ "@narratage/provider-hyperframes-local",
+ "@narratage/provider-kie",
+ "@narratage/provider-media-local",
+ "@narratage/provider-whisperx-local"
+ ],
"artifacts": [
{
"name": "@esbuild/darwin-arm64",
@@ -199,7 +206,7 @@
{
"name": "@narratage/svs",
"version": "0.0.0-dev",
- "digest": "sha256:e44ae945c23e041602eb2f029a4c72b96fc2525e6c767e117e2bf0f11a830e0e"
+ "digest": "sha256:2658027814f0be50cfea761cf5a7ee42004dc30d7b9e252750940a7a8fcddca5"
},
{
"name": "@narratage/text",
@@ -888,7 +895,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:e61ebb911a33d4c5d0e4e4ee4fb69cdb790f4ced050ef35f7472bfbd72013d9b",
- "closureDigest": "sha256:d9fe3a4539facd6ddbc8119096e6abc26f1d6c130963f0a548b02ede667c83fd"
+ "closureDigest": "sha256:c7526eb040617e45080b72a4f50f8f32ae6dc33fcc08ebaefecccd478b23d8c7"
},
{
"specifier": "@narratage/provider-media-local",
@@ -909,5 +916,5 @@
"closureDigest": "sha256:1f4387ca08d77d88c2a02faa0a40ba0d5c76f676f6128a94215ab39010112266"
}
],
- "digest": "sha256:e18633dbebec6ba3bc44490c83e5218f2b46578f00e09eed098ae8289ccab0fe"
+ "digest": "sha256:e635b2789745d90ddb8e32b30dd3261f738d44d62a508f33ceaca97629d0a898"
}
diff --git a/examples/talking-head-aroll/README.md b/examples/talking-head-aroll/README.md
index 41f4e4ef..9f9dbf9d 100644
--- a/examples/talking-head-aroll/README.md
+++ b/examples/talking-head-aroll/README.md
@@ -56,7 +56,7 @@ pnpm narratage lock-packages examples/talking-head-aroll/svml.packages.lock \
--package @narratage/media-pipeline \
--package @narratage/render-hyperframes \
--package @narratage/run-markup \
- --root .
+ --package-root .
pnpm narratage lock-packages examples/talking-head-aroll/svml.runtime-packages.lock \
--package @narratage/provider-kie \
@@ -64,7 +64,7 @@ pnpm narratage lock-packages examples/talking-head-aroll/svml.runtime-packages.l
--package @narratage/provider-whisperx-local \
--package @narratage/provider-google-vertex \
--package @narratage/provider-hyperframes-local \
- --root .
+ --package-root .
```
Inspect the authored graph—including the visible `*.prompt` Text output and `*.program`—without a paid call:
diff --git a/examples/talking-head-aroll/studio.svs b/examples/talking-head-aroll/studio.svs
index f990ba95..c10c3e58 100644
--- a/examples/talking-head-aroll/studio.svs
+++ b/examples/talking-head-aroll/studio.svs
@@ -28,8 +28,6 @@
x: 0.08;
y: 0.74;
width: 0.84;
- font: Inter;
- weight: 800;
size: 44;
line-height: 1;
align: center;
diff --git a/examples/talking-head-aroll/svml.packages.lock b/examples/talking-head-aroll/svml.packages.lock
index 295975b1..cc62dfb0 100644
--- a/examples/talking-head-aroll/svml.packages.lock
+++ b/examples/talking-head-aroll/svml.packages.lock
@@ -1,5 +1,36 @@
{
"format": "svml.node-package-lock@1",
+ "selected": [
+ "@narratage/artifact",
+ "@narratage/caption",
+ "@narratage/caption-fine",
+ "@narratage/caption-gemini",
+ "@narratage/composition",
+ "@narratage/estimate",
+ "@narratage/film",
+ "@narratage/fonts-open",
+ "@narratage/generation",
+ "@narratage/hyperframes",
+ "@narratage/media",
+ "@narratage/media-pipeline",
+ "@narratage/narrative",
+ "@narratage/program-space",
+ "@narratage/render-hyperframes",
+ "@narratage/run-markup",
+ "@narratage/script",
+ "@narratage/seedance",
+ "@narratage/semantic-map",
+ "@narratage/spatial",
+ "@narratage/speech",
+ "@narratage/speech-alignment",
+ "@narratage/speech-basis",
+ "@narratage/speech-evidence",
+ "@narratage/speech-spine",
+ "@narratage/svs",
+ "@narratage/text",
+ "@narratage/visual-ir",
+ "@narratage/whisperx"
+ ],
"artifacts": [
{
"name": "@fontsource-variable/archivo",
@@ -554,7 +585,7 @@
{
"name": "@narratage/caption-fine",
"version": "0.0.0-dev",
- "digest": "sha256:8094384ca1980ee72e0a5621a7ee9d62aec167521fdb536eb068eeeecee2ec9c"
+ "digest": "sha256:b66c7ab8ce58cad4c6254f1d18b4be3fbdd353b6910fc7a2657cb09781a6ecc7"
},
{
"name": "@narratage/caption-gemini",
@@ -724,7 +755,7 @@
{
"name": "@narratage/svs",
"version": "0.0.0-dev",
- "digest": "sha256:e44ae945c23e041602eb2f029a4c72b96fc2525e6c767e117e2bf0f11a830e0e"
+ "digest": "sha256:2658027814f0be50cfea761cf5a7ee42004dc30d7b9e252750940a7a8fcddca5"
},
{
"name": "@narratage/temporal",
@@ -783,7 +814,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:c5616408dd56ce9c903523319b2a697ff6b8af5bfe1dc66fe793a11e4629f3cf",
- "closureDigest": "sha256:79c0da36f1526e8fab9682b3255667599d9dcd67b584602b7b60713fee841f97"
+ "closureDigest": "sha256:3ba4088d7e8703f27748b52ba9e4964d799d474c22d9da17afb2c0d7625a8a80"
},
{
"specifier": "@narratage/caption-gemini",
@@ -810,7 +841,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:9975815b3109520eb6bba276554a90767a9aebff6498c2768d9faf4763219bef",
- "closureDigest": "sha256:8c7022b670c9ba8bb33c58540775a65f0da7e5f8d149ca2494bba34fbd3df8a2"
+ "closureDigest": "sha256:811be87579f5934cdcf1289253cc31e835b3fc9f97a4911ad88fc01a387f7d65"
},
{
"specifier": "@narratage/film",
@@ -819,7 +850,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:8e58b5630b9a68a8ce7314620f5f1c7cda973a05c179c18d61e10d68002964f0",
- "closureDigest": "sha256:defb86a53cf0e6683fe54592ac168e307a5e32b1e76ce851d5d9804fd0ef7095"
+ "closureDigest": "sha256:f78c843e6e47e0571f922caecb294c60dd5b423658a0b98fc7377db3cbdafbd0"
},
{
"specifier": "@narratage/fonts-open",
@@ -837,7 +868,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:d74a57a3210267e665366513324db5c313b3ca0f770da66e74cc38aee5048efb",
- "closureDigest": "sha256:f0999a26b4590b0110e25256f892ad580540618c07c436e916672c3cb371eca2"
+ "closureDigest": "sha256:0a3093f555ce7e80832dd1fec8a5d575fcf2b3b86a0ecf4e840babd7d9080120"
},
{
"specifier": "@narratage/hyperframes",
@@ -909,7 +940,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:69e1c08a5f07c73a506ca8286426a0386485738649e86463cca0b291f319ee4e",
- "closureDigest": "sha256:dfded35adc0aa0d163fba58d375fccc9a69b4ad1168744dc9c2826b9f914cd78"
+ "closureDigest": "sha256:5031128c71900c50b7ca9527bbbfabc85b0f310a9fc84034959df8b4b35c65d2"
},
{
"specifier": "@narratage/seedance",
@@ -918,7 +949,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:e889ca3808a19f544e7aa5e27453beb5a09464c645633b0b1b1d9a4b7ce6591a",
- "closureDigest": "sha256:dfba58117095497c73bd830149da98ce3e560d4ef9201a3e793286c059ade869"
+ "closureDigest": "sha256:193c1f9937adbd21bc0dbac47cbfb18a0f5cc15d7748de3d7717fb1683739004"
},
{
"specifier": "@narratage/semantic-map",
@@ -963,7 +994,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:f01f21badb0ccdd5cc62b131be05f46030bffee96042c7323a0c572786d012ef",
- "closureDigest": "sha256:992c1bda3746087ee746b03eee75fe8309d0b5f351f9ebb1da7e6b5793d37e54"
+ "closureDigest": "sha256:725bd1a8411596f0ad284260e7f3c189eaa9d20bd46706ee824b0848eadc019e"
},
{
"specifier": "@narratage/speech-evidence",
@@ -981,7 +1012,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:a27dd4349d6bb1aaa7f382ad09f883e9894157579e48285b00e8fa24456190f7",
- "closureDigest": "sha256:8f52117330a8c3c08e2346ba08e8c61fe05a92d776a142e405e1b397ee778584"
+ "closureDigest": "sha256:af643b38d811656e465a06d24eaebe7d0de7c184f86a13db56b244a4463373b8"
},
{
"specifier": "@narratage/svs",
@@ -990,7 +1021,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:9cc7c397d2cd97b5a3e814886b6553b6d236fd8825df0d056e328b7f0cf20163",
- "closureDigest": "sha256:6ee450114180d7f6f515b834a9cf1000795007b3ec8e57ba6860b30320fb2eba"
+ "closureDigest": "sha256:4c93cdef1bbace70ff11792777622049b5262a593a2b4d7b890afc9543955ba2"
},
{
"specifier": "@narratage/text",
@@ -999,7 +1030,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:4435dd4bd38e5e017013f775e28e379e3e235211649ee8f3913378f7f9e60b58",
- "closureDigest": "sha256:888a51aafa5225bee3cd589318f12e2974735ddea62e96d2bf8a098ad39b1389"
+ "closureDigest": "sha256:9d50fa2a214341b4af403dbf3e89332ac4b35aefc234ff35e0b066b32ee20243"
},
{
"specifier": "@narratage/visual-ir",
@@ -1020,5 +1051,5 @@
"closureDigest": "sha256:100c9aef680d5cba8ebf6abe9e51bf1c6cdf7ae092144fbed3e35857ad8d88b9"
}
],
- "digest": "sha256:0bf37c5517d23404c45c279eabe0d91465ab42045ca3d0826fcc9bac79e5cce4"
+ "digest": "sha256:ea6a07f8606486b61fc6422b8104a3047f9039ed7a99107d8734299f9ea60509"
}
diff --git a/examples/talking-head-aroll/svml.runtime-packages.lock b/examples/talking-head-aroll/svml.runtime-packages.lock
index c54cf422..5f6f9306 100644
--- a/examples/talking-head-aroll/svml.runtime-packages.lock
+++ b/examples/talking-head-aroll/svml.runtime-packages.lock
@@ -1,5 +1,12 @@
{
"format": "svml.node-package-lock@1",
+ "selected": [
+ "@narratage/provider-google-vertex",
+ "@narratage/provider-hyperframes-local",
+ "@narratage/provider-kie",
+ "@narratage/provider-media-local",
+ "@narratage/provider-whisperx-local"
+ ],
"artifacts": [
{
"name": "@esbuild/darwin-arm64",
@@ -199,7 +206,7 @@
{
"name": "@narratage/svs",
"version": "0.0.0-dev",
- "digest": "sha256:e44ae945c23e041602eb2f029a4c72b96fc2525e6c767e117e2bf0f11a830e0e"
+ "digest": "sha256:2658027814f0be50cfea761cf5a7ee42004dc30d7b9e252750940a7a8fcddca5"
},
{
"name": "@narratage/text",
@@ -888,7 +895,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:e61ebb911a33d4c5d0e4e4ee4fb69cdb790f4ced050ef35f7472bfbd72013d9b",
- "closureDigest": "sha256:d9fe3a4539facd6ddbc8119096e6abc26f1d6c130963f0a548b02ede667c83fd"
+ "closureDigest": "sha256:c7526eb040617e45080b72a4f50f8f32ae6dc33fcc08ebaefecccd478b23d8c7"
},
{
"specifier": "@narratage/provider-media-local",
@@ -909,5 +916,5 @@
"closureDigest": "sha256:1f4387ca08d77d88c2a02faa0a40ba0d5c76f676f6128a94215ab39010112266"
}
],
- "digest": "sha256:e18633dbebec6ba3bc44490c83e5218f2b46578f00e09eed098ae8289ccab0fe"
+ "digest": "sha256:e635b2789745d90ddb8e32b30dd3261f738d44d62a508f33ceaca97629d0a898"
}
diff --git a/package.json b/package.json
index e5d79649..2a968dc9 100644
--- a/package.json
+++ b/package.json
@@ -16,7 +16,7 @@
"smoke:kie": "node --import tsx packages/provider-kie/test/live-smoke.ts",
"narratage": "node --import tsx packages/video-cli/src/cli.ts",
"svml": "node --import tsx packages/video-cli/src/cli.ts",
- "playground": "vite --config tools/playground/vite.config.ts",
+ "caption:playground": "node --import tsx tools/caption-playground/start.ts",
"build:media-lambda": "pnpm --filter @narratage/media-lambda build",
"build:media-lambda-layer": "pnpm --filter @narratage/media-lambda build:layer"
},
diff --git a/packages/caption-fine/README.md b/packages/caption-fine/README.md
index ebcdedbd..8e55cd0d 100644
--- a/packages/caption-fine/README.md
+++ b/packages/caption-fine/README.md
@@ -35,7 +35,7 @@ caption.primary {
cue-min-words: 2; cue-max-words: 6;
stack-order: 70; x: 0.5; y: 0.88; width: 0.84;
anchor-x: center; anchor-y: bottom; align: center; direction: ltr;
- font: Inter; weight: 800; size: 58; line-height: 1.05;
+ size: 58; line-height: 1.05;
fill: #FFFFFF; gradient-from: #FFFFFF; gradient-to: #93C5FD; gradient-angle: 120;
stroke-color: #09090B; stroke-width: 2;
shadow-color: #000000; shadow-opacity: 0.7; shadow-x: 0; shadow-y: 3; shadow-blur: 8;
@@ -59,8 +59,8 @@ already-read Pill rather than one capsule per Atom. Text may remain `trail` whil
One Track handles the default and ordered Style replacements. `font=` accepts either one exact
`FontArtifactRef` plus ordered Style `Fallback` children, or a reusable Media `FontStackRef` such as
-the compact `fonts:Stack` above. The primary must match the Recipe's weight/style; fallbacks keep
-their own honest face metadata. Omitting the stack is invalid rather than an environment-font
+the compact `fonts:Stack` above. Family, weight and style exist only on those exact font values;
+the Recipe owns size and appearance. Fallbacks keep their own honest face metadata. Omitting the stack is invalid rather than an environment-font
prototype path. Fine never clips author text and intentionally has no `max-lines`.
Common Caption, Composition and Core know none of Fine's Recipe fields or layout policy. See
`spec/caption-fine.md` for the full parameter surface, defaults and non-goals.
diff --git a/packages/caption-fine/src/index.ts b/packages/caption-fine/src/index.ts
index 431ef825..24c29776 100644
--- a/packages/caption-fine/src/index.ts
+++ b/packages/caption-fine/src/index.ts
@@ -8,6 +8,12 @@ export {
captionFineTrackSurfaceImplementationDigest,
} from "./manifest.js";
export { renderFineCaption, renderFineCaptionImplementationDigest } from "./render.js";
+export {
+ fineCaptionOneShotMotions,
+ fineCaptionOptionalRecipeProperties,
+ fineCaptionRecipeSchema,
+ fineCaptionRequiredRecipeProperties,
+} from "./recipe.js";
export {
assertFineCaptionParameters,
FINE_CAPTION_FAMILY,
diff --git a/packages/caption-fine/src/recipe.ts b/packages/caption-fine/src/recipe.ts
new file mode 100644
index 00000000..e7957e2f
--- /dev/null
+++ b/packages/caption-fine/src/recipe.ts
@@ -0,0 +1,108 @@
+import type { ValueSchema } from "@narratage/protocol";
+
+export const fineCaptionOneShotMotions = [
+ "none", "fade", "pop", "scale", "spring", "bounce", "elastic", "stamp", "tilt", "zoom-blur",
+ "flip-x", "flip-y", "spin", "squash", "stretch", "slide-left", "slide-right", "slide-up", "slide-down",
+ "blur-in", "wipe-left", "wipe-right", "wipe-up", "wipe-down",
+] as const;
+
+const paired = (...names: readonly string[]): readonly string[] =>
+ names.flatMap((name) => [name, `active-${name}`]);
+
+const colors = new Set([
+ ...paired("fill", "glow-color", "gradient-from", "gradient-to", "long-shadow-color", "shadow-color", "stroke-color"),
+ "background", "border-color", "underline-color",
+ "active-box-background", "active-box-border-color", "active-underline-color",
+]);
+
+const unitFractions = new Set([
+ "x", "y", "width",
+ ...paired("opacity", "glow-opacity", "long-shadow-opacity", "shadow-opacity"),
+]);
+
+const integers = new Set([
+ "cue-min-words", "cue-max-words", "stack-order",
+ "active-box-transition-frames", "active-response-frames",
+ "atom-enter-frames", "atom-exit-frames", "cue-enter-frames", "cue-exit-frames",
+ "loop-period-frames",
+]);
+
+const numbers = new Set([
+ "size", "radius", "line-height", "border-width", "letter-spacing", "loop-intensity",
+ "slide-distance", "word-gap", "active-box-border-width", "active-box-radius", "active-scale",
+ "underline-offset", "underline-thickness", "active-underline-offset", "active-underline-thickness",
+ ...paired("glow-blur", "gradient-angle", "long-shadow-angle", "long-shadow-distance",
+ "shadow-blur", "shadow-x", "shadow-y", "stroke-width"),
+]);
+
+const strings = new Set(["padding", "active-box-padding"]);
+
+const enums: Readonly<Record<string, readonly string[]>> = {
+ "align": ["left", "center", "right"],
+ "anchor-x": ["left", "center", "right"],
+ "anchor-y": ["top", "center", "bottom"],
+ "direction": ["ltr", "rtl"],
+ "text-transform": ["none", "uppercase", "lowercase"],
+ "atom-reveal": ["all", "on-start", "typewriter"],
+ "karaoke": ["off", "current", "trail"],
+ "karaoke-transition": ["step", "wipe"],
+ "underline": ["off", "always"],
+ "active-underline": ["off", "current", "trail"],
+ "active-box": ["off", "current", "trail"],
+ "active-box-continuity": ["isolated", "joined"],
+ "loop": ["none", "shake", "wobble", "glow-pulse", "breathe", "float", "pulse", "flicker"],
+ "loop-target": ["cue", "active-atom"],
+ "cue-enter": fineCaptionOneShotMotions,
+ "cue-exit": fineCaptionOneShotMotions,
+ "atom-enter": fineCaptionOneShotMotions,
+ "atom-exit": fineCaptionOneShotMotions,
+ "active-box-enter": fineCaptionOneShotMotions,
+ "active-box-exit": fineCaptionOneShotMotions,
+ "active-response": fineCaptionOneShotMotions,
+};
+
+export const fineCaptionRequiredRecipeProperties = [
+ "align", "background", "cue-max-words", "cue-min-words", "fill",
+ "line-height", "padding", "radius", "size", "stack-order", "width", "x", "y",
+] as const;
+
+export const fineCaptionOptionalRecipeProperties = [
+ "active-box", "active-box-background", "active-box-border-color", "active-box-border-width",
+ "active-box-continuity", "active-box-enter", "active-box-exit", "active-box-padding", "active-box-radius",
+ "active-box-transition-frames", "active-fill", "active-glow-blur", "active-glow-color", "active-glow-opacity",
+ "active-gradient-angle", "active-gradient-from", "active-gradient-to", "active-long-shadow-angle",
+ "active-long-shadow-color", "active-long-shadow-distance", "active-long-shadow-opacity", "active-opacity",
+ "active-response", "active-response-frames", "active-scale", "active-shadow-blur", "active-shadow-color", "active-shadow-opacity",
+ "active-shadow-x", "active-shadow-y", "active-stroke-color", "active-stroke-width", "active-underline",
+ "active-underline-color", "active-underline-offset", "active-underline-thickness", "anchor-x", "anchor-y",
+ "atom-enter", "atom-enter-frames", "atom-exit", "atom-exit-frames", "atom-reveal", "border-color", "border-width", "cue-enter",
+ "cue-enter-frames", "cue-exit", "cue-exit-frames", "direction", "glow-blur", "glow-color",
+ "glow-opacity", "gradient-angle", "gradient-from", "gradient-to", "karaoke", "karaoke-transition",
+ "letter-spacing", "long-shadow-angle", "long-shadow-color", "long-shadow-distance", "long-shadow-opacity",
+ "loop", "loop-intensity", "loop-period-frames", "loop-target", "opacity", "shadow-blur", "shadow-color",
+ "shadow-opacity", "shadow-x", "shadow-y", "slide-distance", "stroke-color", "stroke-width", "text-transform",
+ "underline", "underline-color", "underline-offset", "underline-thickness", "word-gap",
+] as const;
+
+function schemaFor(name: string): ValueSchema {
+ if (colors.has(name)) return { kind: "string" };
+ if (unitFractions.has(name)) return { kind: "number", minimum: 0, maximum: 1 };
+ if (integers.has(name)) return { kind: "number", integer: true };
+ if (numbers.has(name)) return { kind: "number" };
+ if (strings.has(name)) return { kind: "string" };
+ const values = enums[name];
+ if (values !== undefined) return { kind: "string", enum: values };
+ throw new Error(`Fine Caption Recipe property ${name} has no declared value shape`);
+}
+
+const required = new Set<string>(fineCaptionRequiredRecipeProperties);
+const properties = [...fineCaptionRequiredRecipeProperties, ...fineCaptionOptionalRecipeProperties];
+
+/** Public author contract for the exact properties accepted by a Fine Caption SVS Recipe. */
+export const fineCaptionRecipeSchema: ValueSchema = {
+ kind: "object",
+ fields: Object.fromEntries(properties.map((name) => [
+ name,
+ required.has(name) ? { schema: schemaFor(name) } : { schema: schemaFor(name), optional: true },
+ ])),
+};
diff --git a/packages/caption-fine/src/render.ts b/packages/caption-fine/src/render.ts
index 3749744c..4be7cea4 100644
--- a/packages/caption-fine/src/render.ts
+++ b/packages/caption-fine/src/render.ts
@@ -49,11 +49,6 @@ function alphaColor(hex: string, opacity: number): string {
function typographyStyle(parameters: FineCaptionParameters): VisualStyleDeclaration[] {
return [
{ name: "font-size", value: `${compactNumber(parameters.typography.fontSizePx)}px` },
- ...(parameters.typography.exactFonts === undefined ? [
- { name: "font-family", value: parameters.typography.fontFamily },
- { name: "font-style", value: parameters.typography.fontStyle },
- { name: "font-weight", value: parameters.typography.fontWeight },
- ] as const : []),
{ name: "letter-spacing", value: `${compactNumber(parameters.layout.letterSpacingPx)}px` },
{ name: "line-height", value: parameters.layout.lineHeight },
{ name: "text-transform", value: parameters.typography.textTransform },
diff --git a/packages/caption-fine/src/style.ts b/packages/caption-fine/src/style.ts
index e72c4d20..4f8a3749 100644
--- a/packages/caption-fine/src/style.ts
+++ b/packages/caption-fine/src/style.ts
@@ -6,33 +6,18 @@ import { digestOf } from "@narratage/protocol";
import type { SvsRecipe } from "@narratage/svs";
import type { FineCaptionGlyphPaint, FineCaptionParameters } from "./types.js";
+import {
+ fineCaptionOneShotMotions,
+ fineCaptionOptionalRecipeProperties,
+ fineCaptionRequiredRecipeProperties,
+} from "./recipe.js";
export const FINE_CAPTION_FAMILY = "@narratage/caption-fine@1";
-const REQUIRED_PROPERTIES = [
- "align", "background", "cue-max-words", "cue-min-words", "fill", "font",
- "line-height", "padding", "radius", "size", "stack-order", "weight", "width", "x", "y",
-] as const;
-
-const OPTIONAL_PROPERTIES = [
- "active-box", "active-box-background", "active-box-border-color", "active-box-border-width",
- "active-box-continuity", "active-box-enter", "active-box-exit", "active-box-padding", "active-box-radius",
- "active-box-transition-frames", "active-fill", "active-glow-blur", "active-glow-color", "active-glow-opacity",
- "active-gradient-angle", "active-gradient-from", "active-gradient-to", "active-long-shadow-angle",
- "active-long-shadow-color", "active-long-shadow-distance", "active-long-shadow-opacity", "active-opacity",
- "active-response", "active-response-frames", "active-scale", "active-shadow-blur", "active-shadow-color", "active-shadow-opacity",
- "active-shadow-x", "active-shadow-y", "active-stroke-color", "active-stroke-width", "active-underline",
- "active-underline-color", "active-underline-offset", "active-underline-thickness", "anchor-x", "anchor-y",
- "atom-enter", "atom-enter-frames", "atom-exit", "atom-exit-frames", "atom-reveal", "border-color", "border-width", "cue-enter",
- "cue-enter-frames", "cue-exit", "cue-exit-frames", "direction", "font-style", "glow-blur", "glow-color",
- "glow-opacity", "gradient-angle", "gradient-from", "gradient-to", "karaoke", "karaoke-transition",
- "letter-spacing", "long-shadow-angle", "long-shadow-color", "long-shadow-distance", "long-shadow-opacity",
- "loop", "loop-intensity", "loop-period-frames", "loop-target", "opacity", "shadow-blur", "shadow-color",
- "shadow-opacity", "shadow-x", "shadow-y", "slide-distance", "stroke-color", "stroke-width", "text-transform",
- "underline", "underline-color", "underline-offset", "underline-thickness", "word-gap",
-] as const;
-
-const ALLOWED_PROPERTIES = new Set<string>([...REQUIRED_PROPERTIES, ...OPTIONAL_PROPERTIES]);
+const ALLOWED_PROPERTIES = new Set<string>([
+ ...fineCaptionRequiredRecipeProperties,
+ ...fineCaptionOptionalRecipeProperties,
+]);
function required(value: SvsRecipe, name: string): unknown {
if (!Object.hasOwn(value.properties, name)) throw new Error(`Fine Caption Recipe requires ${name}`);
@@ -184,7 +169,7 @@ export function fineCaptionParameters(
recipe: SvsRecipe,
exactFonts: readonly FontArtifactRef[],
): FineCaptionParameters {
- for (const name of REQUIRED_PROPERTIES) required(recipe, name);
+ for (const name of fineCaptionRequiredRecipeProperties) required(recipe, name);
const unknown = Object.keys(recipe.properties).filter((name) => !ALLOWED_PROPERTIES.has(name));
if (unknown.length > 0) throw new Error(`Fine Caption Recipe contains unknown property ${unknown[0]}`);
@@ -192,11 +177,6 @@ export function fineCaptionParameters(
const activeBoxPadding = padding(string(recipe, "active-box-padding", "0"));
const fontSizePx = number(recipe, "size");
const basePaint = glyphPaint(recipe, "");
- const oneShotMotions = [
- "none", "fade", "pop", "scale", "spring", "bounce", "elastic", "stamp", "tilt", "zoom-blur",
- "flip-x", "flip-y", "spin", "squash", "stretch", "slide-left", "slide-right", "slide-up", "slide-down",
- "blur-in", "wipe-left", "wipe-right", "wipe-up", "wipe-down",
- ] as const;
const parameters: FineCaptionParameters = {
contract: "svml.caption-fine-parameters@1",
stackingOrder: integer(recipe, "stack-order"),
@@ -215,10 +195,7 @@ export function fineCaptionParameters(
wordGapPx: number(recipe, "word-gap", fontSizePx * 0.25),
},
typography: {
- fontFamily: string(recipe, "font"),
fontSizePx,
- fontWeight: integer(recipe, "weight"),
- fontStyle: choice(recipe, "font-style", ["normal", "italic", "oblique"] as const, "normal"),
textTransform: choice(recipe, "text-transform", ["none", "uppercase", "lowercase"] as const, "none"),
exactFonts: [...exactFonts],
},
@@ -257,21 +234,21 @@ export function fineCaptionParameters(
paddingXPx: activeBoxPadding.x,
paddingYPx: activeBoxPadding.y,
radiusPx: number(recipe, "active-box-radius", 8),
- enter: choice(recipe, "active-box-enter", oneShotMotions, "none"),
- exit: choice(recipe, "active-box-exit", oneShotMotions, "none"),
+ enter: choice(recipe, "active-box-enter", fineCaptionOneShotMotions, "none"),
+ exit: choice(recipe, "active-box-exit", fineCaptionOneShotMotions, "none"),
transitionFrames: integer(recipe, "active-box-transition-frames", 0),
},
motion: {
- cueEnter: choice(recipe, "cue-enter", oneShotMotions, "none"),
- cueExit: choice(recipe, "cue-exit", oneShotMotions, "none"),
+ cueEnter: choice(recipe, "cue-enter", fineCaptionOneShotMotions, "none"),
+ cueExit: choice(recipe, "cue-exit", fineCaptionOneShotMotions, "none"),
cueEnterFrames: integer(recipe, "cue-enter-frames", 0),
cueExitFrames: integer(recipe, "cue-exit-frames", 0),
- atomEnter: choice(recipe, "atom-enter", oneShotMotions, "none"),
+ atomEnter: choice(recipe, "atom-enter", fineCaptionOneShotMotions, "none"),
atomEnterFrames: integer(recipe, "atom-enter-frames", 0),
- atomExit: choice(recipe, "atom-exit", oneShotMotions, "none"),
+ atomExit: choice(recipe, "atom-exit", fineCaptionOneShotMotions, "none"),
atomExitFrames: integer(recipe, "atom-exit-frames", 0),
atomReveal: choice(recipe, "atom-reveal", ["all", "on-start", "typewriter"] as const, "all"),
- activeResponse: choice(recipe, "active-response", oneShotMotions, "none"),
+ activeResponse: choice(recipe, "active-response", fineCaptionOneShotMotions, "none"),
activeResponseFrames: integer(recipe, "active-response-frames", 6),
activeScale: number(recipe, "active-scale", 1.08),
slideDistancePx: number(recipe, "slide-distance", 24),
@@ -292,7 +269,7 @@ export function assertFineCaptionParameters(value: FineCaptionParameters): void
}
const nonNegative = [
value.placement.x, value.placement.y, value.placement.width, value.typography.fontSizePx,
- value.typography.fontWeight, value.layout.lineHeight, value.layout.wordGapPx, value.cueBox.paddingXPx,
+ value.layout.lineHeight, value.layout.wordGapPx, value.cueBox.paddingXPx,
value.cueBox.paddingYPx, value.cueBox.radiusPx, value.cueBox.borderWidthPx,
value.underline.thicknessPx, value.underline.offsetPx, value.activeUnderline.thicknessPx,
value.activeUnderline.offsetPx, value.activeBox.borderWidthPx, value.activeBox.paddingXPx,
@@ -313,16 +290,10 @@ export function assertFineCaptionParameters(value: FineCaptionParameters): void
|| !Number.isFinite(value.motion.activeScale) || !Number.isFinite(value.layout.letterSpacingPx)) {
throw new Error("Fine Caption parameters contain invalid numeric bounds");
}
- if (!value.typography.fontFamily.trim() || value.typography.fontWeight < 1 || value.typography.fontWeight > 1000) {
- throw new Error("Fine Caption typography is invalid");
- }
if (value.typography.exactFonts.length === 0) throw new Error("Fine Caption exact Font stack is empty");
const faces = new Set<string>();
for (const [index, font] of value.typography.exactFonts.entries()) {
assertFontArtifactRef(font, `Fine Caption exact Font ${index + 1}`);
- if (index === 0 && (font.weight !== value.typography.fontWeight || font.style !== value.typography.fontStyle)) {
- throw new Error("Fine Caption primary exact Font face must match Recipe weight and font-style");
- }
const identity = digestOf(font);
if (faces.has(identity)) throw new Error("Fine Caption exact Font stack contains a duplicate face");
faces.add(identity);
diff --git a/packages/caption-fine/src/surface.ts b/packages/caption-fine/src/surface.ts
index 2e02bdcf..4a68a138 100644
--- a/packages/caption-fine/src/surface.ts
+++ b/packages/caption-fine/src/surface.ts
@@ -102,7 +102,7 @@ function exactFonts(
}
export const decodeFineCaptionStyleSurface: StructuredSurfaceHandler = ({ element, resolveReference }) => {
- attributes(element, ["id", "recipe"], ["font"]);
+ attributes(element, ["id", "recipe", "font"]);
const id = stringAttribute(element, "id");
const recipe = inline<SvsRecipe>(reference(element, "recipe", svsRecipeType, resolveReference), `${element.name}.recipe`);
const style = fineCaptionStyle(id, recipe, exactFonts(element, resolveReference));
diff --git a/packages/caption-fine/src/types.ts b/packages/caption-fine/src/types.ts
index 8453f987..e1745bb1 100644
--- a/packages/caption-fine/src/types.ts
+++ b/packages/caption-fine/src/types.ts
@@ -101,10 +101,7 @@ export type FineCaptionParameters = {
readonly wordGapPx: number;
};
readonly typography: {
- readonly fontFamily: string;
readonly fontSizePx: number;
- readonly fontWeight: number;
- readonly fontStyle: "normal" | "italic" | "oblique";
readonly textTransform: "none" | "uppercase" | "lowercase";
readonly exactFonts: readonly FontArtifactRef[];
};
diff --git a/packages/caption-fine/test/caption-fine.test.ts b/packages/caption-fine/test/caption-fine.test.ts
index 0bba0342..dcf3c970 100644
--- a/packages/caption-fine/test/caption-fine.test.ts
+++ b/packages/caption-fine/test/caption-fine.test.ts
@@ -20,8 +20,6 @@ const recipe: SvsRecipe = {
x: 0.08,
y: 0.76,
width: 0.84,
- font: "Inter",
- weight: 800,
size: 58,
"line-height": 1,
align: "center",
@@ -169,7 +167,6 @@ test("Fine resolves the complete orthogonal Paint, anchor, karaoke and motion su
direction: "rtl",
"letter-spacing": -1.5,
"word-gap": 11,
- "font-style": "italic",
"text-transform": "uppercase",
opacity: 0.9,
"gradient-from": "#FFFFFF",
@@ -252,7 +249,7 @@ test("Fine resolves the complete orthogonal Paint, anchor, karaoke and motion su
x: 0.08, y: 0.76, width: 0.84, anchorX: "center", anchorY: "bottom",
});
assert.equal(parameters.layout.direction, "rtl");
- assert.equal(parameters.typography.fontStyle, "italic");
+ assert.equal(parameters.typography.exactFonts[0]?.style, "italic");
assert.equal(parameters.typography.textTransform, "uppercase");
assert.deepEqual(parameters.basePaint.gradient, { from: "#FFFFFF", to: "#55CCFF", angleDeg: 120 });
assert.equal(parameters.basePaint.stroke.widthPx, 3);
@@ -371,7 +368,7 @@ test("an exact Font is explicit Style input and reaches every base and active gl
for (const glyph of glyphs) {
if (glyph.kind === "text") assert.deepEqual(glyph.fonts, [exactFont]);
}
- assert.throws(() => fineCaptionStyle("mismatch", recipe, [{ ...exactFont, weight: 700 }]), /must match/u);
+ assert.doesNotThrow(() => fineCaptionStyle("another-exact-face", recipe, [{ ...exactFont, weight: 700 }]));
});
test("an ordered exact Font stack preserves honest fallback faces and rejects duplicates", () => {
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 1fc9e456..5e2a926f 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -9,6 +9,7 @@ must pass one explicit `CliDistribution`:
```ts
type CliDistribution = {
name: string;
+ packageRoot?: string;
builtInPackageContributions: readonly NodePackageContribution[];
runFrontends: readonly RunFrontend[];
createCompiler(options): NodeCompiler;
diff --git a/packages/cli/src/distribution.ts b/packages/cli/src/distribution.ts
index 3bbfb712..28be0afc 100644
--- a/packages/cli/src/distribution.ts
+++ b/packages/cli/src/distribution.ts
@@ -5,7 +5,8 @@ import type { NodePackageContribution } from "@narratage/package-loader-node";
import type { RunFrontend } from "@narratage/run";
export type CliCompilerOptions = {
- readonly root?: string;
+ /** Canonical containment boundary for Author and Run Sources plus source assets. */
+ readonly workspaceRoot?: string;
readonly packageContributions: readonly NodePackageContribution[];
};
@@ -17,6 +18,8 @@ export type CliCompilerOptions = {
*/
export type CliDistribution = {
readonly name: string;
+ /** Host location from which installed locked packages resolve. A caller may explicitly override it. */
+ readonly packageRoot?: string;
readonly builtInPackageContributions: readonly NodePackageContribution[];
/** Explicitly trusted Run Frontends; source Headers select among them without suffix defaults. */
readonly runFrontends: readonly RunFrontend[];
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index 76913201..1abed1d7 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -32,7 +32,10 @@ type ParsedArgs = {
/** Second command word. Only `services` takes one. */
readonly action: string | undefined;
readonly file: string | undefined;
- readonly root: string | undefined;
+ /** Canonical containment boundary for Author and Run Sources plus source assets. */
+ readonly workspaceRoot: string | undefined;
+ /** Host directory whose node_modules contains the packages named by a package lock. */
+ readonly packageRoot: string | undefined;
readonly targets: readonly string[];
readonly substitute: boolean;
readonly runtime: string | undefined;
@@ -59,7 +62,8 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
const file = command === "builds" ? undefined : positional[0];
const rest = command === "builds" ? positional : positional.slice(1);
const targets: string[] = [];
- let root: string | undefined;
+ let workspaceRoot: string | undefined;
+ let packageRoot: string | undefined;
let runtime: string | undefined;
let buildId: string | undefined;
let follow = false;
@@ -87,7 +91,14 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
if (item === "--root") {
const value = rest[index + 1];
if (value === undefined || value.startsWith("--")) throw new Error("--root requires a directory");
- root = resolve(value);
+ workspaceRoot = resolve(value);
+ index += 1;
+ continue;
+ }
+ if (item === "--package-root") {
+ const value = rest[index + 1];
+ if (value === undefined || value.startsWith("--")) throw new Error("--package-root requires a directory");
+ packageRoot = resolve(value);
index += 1;
continue;
}
@@ -198,7 +209,8 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
command,
action,
file,
- root,
+ workspaceRoot,
+ packageRoot,
targets,
substitute,
runtime,
@@ -221,13 +233,13 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
function usage(): string {
return [
"usage:",
- " narratage lock-packages <svml.packages.lock> --package installed-name [--package installed-name] [--root directory]",
+ " narratage lock-packages <svml.packages.lock> --package installed-name [--package installed-name] [--package-root directory]",
" narratage doctor <runtime-profile.json>",
" narratage services up|down|status <runtime-profile.json> [--max-wait-ms milliseconds]",
" narratage gc <runtime-profile.json> [--apply]",
- " narratage check <self-described-source> [--runtime profile.json] [--package-lock file] [--root directory]",
- " narratage plan <run-source> [--runtime profile.json] [--package-lock file]",
- " narratage build <run-source> --runtime profile.json|./svml.runtime.ts [--follow] [--no-services]",
+ " narratage check <self-described-source> [--runtime profile.json] [--package-lock file] [--package-root directory] [--root workspace]",
+ " narratage plan <run-source> [--runtime profile.json] [--package-lock file] [--package-root directory] [--root workspace]",
+ " narratage build <run-source> --runtime profile.json|./svml.runtime.ts [--package-lock file] [--package-root directory] [--root workspace] [--follow] [--no-services]",
" narratage status <build-id> --runtime profile.json|./svml.runtime.ts",
" narratage builds --runtime profile.json|./svml.runtime.ts",
" narratage inspect <build-id> --runtime profile.json|./svml.runtime.ts",
@@ -344,15 +356,19 @@ export async function runCli(
if (args.command === "lock-packages") {
if (args.packages.length === 0) throw new Error("lock-packages requires at least one --package");
if (args.packageLock !== undefined) throw new Error("lock-packages does not accept --package-lock");
+ if (args.workspaceRoot !== undefined) {
+ throw new Error("lock-packages does not compile a Workspace; use --package-root to locate installed packages");
+ }
const output = resolve(args.file!);
- const root = args.root ?? dirname(output);
- const lock = await createNodePackageLock(args.packages, root);
+ const packageRoot = args.packageRoot ?? distribution.packageRoot ?? dirname(output);
+ const lock = await createNodePackageLock(args.packages, packageRoot);
await writeNodePackageLock(output, lock);
io.write(`${JSON.stringify({ ok: true, packageLock: output, digest: lock.digest, packages: lock.packages }, null, 2)}\n`);
return;
}
if (args.command === "doctor") {
- if (args.runtime !== undefined || args.packageLock !== undefined || args.packages.length > 0 || args.apply) {
+ if (args.runtime !== undefined || args.packageLock !== undefined || args.packageRoot !== undefined
+ || args.packages.length > 0 || args.apply) {
throw new Error("doctor reads all deployment selection from the Runtime Profile itself");
}
const result = await distribution.doctorRuntimeConfig(resolve(args.file!));
@@ -364,7 +380,8 @@ export async function runCli(
return;
}
if (args.command === "services") {
- if (args.runtime !== undefined || args.packageLock !== undefined || args.packages.length > 0 || args.apply) {
+ if (args.runtime !== undefined || args.packageLock !== undefined || args.packageRoot !== undefined
+ || args.packages.length > 0 || args.apply) {
throw new Error("services reads all deployment selection from the Runtime Profile itself");
}
if (args.action !== "up" && args.action !== "down" && args.action !== "status") {
@@ -389,7 +406,8 @@ export async function runCli(
return;
}
if (args.command === "gc") {
- if (args.runtime !== undefined || args.packageLock !== undefined || args.packages.length > 0) {
+ if (args.runtime !== undefined || args.packageLock !== undefined || args.packageRoot !== undefined
+ || args.packages.length > 0) {
throw new Error("gc reads all deployment selection from the Runtime Profile itself");
}
const runtime = await loadLocalRuntime(resolve(args.file!), distribution);
@@ -540,13 +558,19 @@ export async function runCli(
return;
}
if (args.packages.length > 0) throw new Error("--package is only valid for lock-packages");
+ if (args.packageRoot !== undefined && args.packageLock === undefined) {
+ throw new Error("--package-root locates the installed packages named by --package-lock; provide both options");
+ }
const loadedPackageSet = args.packageLock === undefined
? undefined
- : await loadNodePackageSet(args.packageLock, args.root ?? dirname(args.packageLock));
+ : await loadNodePackageSet(
+ args.packageLock,
+ args.packageRoot ?? distribution.packageRoot ?? dirname(args.packageLock),
+ );
const packageContributions = loadedPackageSet?.contributions ?? distribution.builtInPackageContributions;
const runFrontends = collectRunFrontends(distribution.runFrontends, packageContributions);
const compiler = distribution.createCompiler({
- ...(args.root === undefined ? {} : { root: args.root }),
+ ...(args.workspaceRoot === undefined ? {} : { workspaceRoot: args.workspaceRoot }),
packageContributions,
});
const workspace = await compiler.openFile(args.file!);
diff --git a/packages/local/README.md b/packages/local/README.md
index 1983a9ac..799add2f 100644
--- a/packages/local/README.md
+++ b/packages/local/README.md
@@ -62,6 +62,8 @@ services.
```ts
export default await createProjectLocalRuntime({
root: import.meta.dirname,
+ // May point at a separate Narratage installation when this project owns no node_modules.
+ packageRoot: "/opt/narratage",
packageLock: "./svml.packages.lock",
runtimeServices: [createS3ArtifactStorePackage({
bucket: "team-svml-artifacts",
diff --git a/packages/local/src/config.ts b/packages/local/src/config.ts
index c6639e03..4729692e 100644
--- a/packages/local/src/config.ts
+++ b/packages/local/src/config.ts
@@ -29,6 +29,8 @@ export type RuntimeConfigDocument = {
readonly format: "svml.runtime-config@1";
/** Resolved relative to the configuration file. Defaults to its directory. */
readonly root?: string;
+ /** Resolved relative to the configuration file. Locates installed Node packages, not Runtime data. */
+ readonly packageRoot?: string;
readonly statePath?: string;
readonly catalogPath?: string;
readonly artifactPath?: string;
@@ -118,7 +120,7 @@ function scheduling(value: unknown): RuntimeConfigDocument["scheduling"] {
export function parseRuntimeConfig(value: unknown): RuntimeConfigDocument {
const item = object(value, "$runtime");
exactKeys(item, [
- "format", "root", "statePath", "catalogPath", "artifactPath", "packageLock", "runtimePackageLock",
+ "format", "root", "packageRoot", "statePath", "catalogPath", "artifactPath", "packageLock", "runtimePackageLock",
"runtimeServices", "endpoints",
"permissions", "scheduling",
], "$runtime");
@@ -137,6 +139,9 @@ export function parseRuntimeConfig(value: unknown): RuntimeConfigDocument {
return {
format: "svml.runtime-config@1",
...(optionalString(item.root, "$runtime.root") === undefined ? {} : { root: item.root as string }),
+ ...(optionalString(item.packageRoot, "$runtime.packageRoot") === undefined
+ ? {}
+ : { packageRoot: item.packageRoot as string }),
...(optionalString(item.statePath, "$runtime.statePath") === undefined ? {} : { statePath: item.statePath as string }),
...(optionalString(item.catalogPath, "$runtime.catalogPath") === undefined ? {} : { catalogPath: item.catalogPath as string }),
...(optionalString(item.artifactPath, "$runtime.artifactPath") === undefined ? {} : { artifactPath: item.artifactPath as string }),
@@ -155,6 +160,8 @@ export type LoadRuntimeConfigOptions = {
/** Trusted embedding adapters. Locked installed adapters are normally selected by runtimePackageLock. */
readonly registry?: RuntimeAdapterRegistry;
readonly components?: readonly ComponentPackage[];
+ /** Host package installation used when the Profile does not explicitly select packageRoot. */
+ readonly packageRoot?: string;
};
export type RuntimeConfigDoctorResult = {
@@ -165,10 +172,11 @@ export type RuntimeConfigDoctorResult = {
async function installLockedRuntimeAdapters(
registry: RuntimeAdapterRegistry,
path: string | undefined,
- root: string,
+ lockRoot: string,
+ packageRoot: string,
): Promise<void> {
if (path === undefined) return;
- const loaded = await loadNodePackageSet(resolve(root, path), root);
+ const loaded = await loadNodePackageSet(resolve(lockRoot, path), packageRoot);
const lockedPackages = new Map(loaded.lock.packages.map((item) => [item.package.name, item]));
const artifacts = new Map(loaded.lock.artifacts.map((item) => [`${item.name}@${item.version}`, item]));
for (const contribution of loaded.contributions) {
@@ -206,8 +214,9 @@ export async function declaredExternalServices(
const absolute = resolve(path);
const document = parseRuntimeConfig(JSON.parse(await readFile(absolute, "utf8")));
const root = resolve(dirname(absolute), document.root ?? ".");
+ const packageRoot = resolve(dirname(absolute), document.packageRoot ?? options.packageRoot ?? document.root ?? ".");
const registry = options.registry ?? new RuntimeAdapterRegistry();
- await installLockedRuntimeAdapters(registry, document.runtimePackageLock, root);
+ await installLockedRuntimeAdapters(registry, document.runtimePackageLock, root, packageRoot);
const services: DeclaredExternalService[] = [];
for (const item of document.endpoints) {
if (!registry.has(item.use, "endpoint")) {
@@ -241,6 +250,7 @@ export async function doctorRuntimeConfig(
const absolute = resolve(path);
const document = parseRuntimeConfig(JSON.parse(await readFile(absolute, "utf8")));
const root = resolve(dirname(absolute), document.root ?? ".");
+ const packageRoot = resolve(dirname(absolute), document.packageRoot ?? options.packageRoot ?? document.root ?? ".");
const diagnostics: RuntimeDoctorDiagnostic[] = [];
try {
if (!(await stat(root)).isDirectory()) throw new Error(`Runtime root ${root} is not a directory`);
@@ -250,14 +260,14 @@ export async function doctorRuntimeConfig(
}
const registry = options.registry ?? new RuntimeAdapterRegistry();
try {
- await installLockedRuntimeAdapters(registry, document.runtimePackageLock, root);
+ await installLockedRuntimeAdapters(registry, document.runtimePackageLock, root, packageRoot);
} catch (error) {
diagnostics.push(diagnostic(error, "RUNTIME_PACKAGE_LOCK_INVALID", document.runtimePackageLock));
return { root, diagnostics };
}
if (document.packageLock !== undefined) {
try {
- await loadNodePackageSet(resolve(root, document.packageLock), root);
+ await loadNodePackageSet(resolve(root, document.packageLock), packageRoot);
} catch (error) {
diagnostics.push(diagnostic(error, "IMPLEMENTATION_PACKAGE_LOCK_INVALID", document.packageLock));
}
@@ -350,8 +360,9 @@ export async function createRuntimeFromConfig(
const absolute = resolve(path);
const document = parseRuntimeConfig(JSON.parse(await readFile(absolute, "utf8")));
const root = resolve(dirname(absolute), document.root ?? ".");
+ const packageRoot = resolve(dirname(absolute), document.packageRoot ?? options.packageRoot ?? document.root ?? ".");
const registry = options.registry ?? new RuntimeAdapterRegistry();
- await installLockedRuntimeAdapters(registry, document.runtimePackageLock, root);
+ await installLockedRuntimeAdapters(registry, document.runtimePackageLock, root, packageRoot);
const runtimeServices = await Promise.all(document.runtimeServices.map(async (item) => {
return await registry.createService(item.use, {
root,
@@ -369,6 +380,7 @@ export async function createRuntimeFromConfig(
}));
return await createProjectLocalRuntime({
root,
+ packageRoot,
...(document.statePath === undefined ? {} : { statePath: document.statePath }),
...(document.catalogPath === undefined ? {} : { catalogPath: document.catalogPath }),
...(document.artifactPath === undefined ? {} : { artifactPath: document.artifactPath }),
diff --git a/packages/local/src/runtime.ts b/packages/local/src/runtime.ts
index cc23db20..f4b8de07 100644
--- a/packages/local/src/runtime.ts
+++ b/packages/local/src/runtime.ts
@@ -311,9 +311,10 @@ export async function createProjectLocalRuntime(
options: ProjectLocalRuntimeOptions = {},
): Promise<LocalRuntime> {
const root = resolve(options.root ?? process.cwd());
+ const packageRoot = resolve(options.packageRoot ?? root);
const lockedPackageSet = options.packageLock === undefined
? undefined
- : await loadNodePackageSet(resolve(root, options.packageLock), root);
+ : await loadNodePackageSet(resolve(root, options.packageLock), packageRoot);
const lockedComponents = lockedPackageSet === undefined
? []
: collectNodePackageComponents(lockedPackageSet.contributions);
diff --git a/packages/local/src/types.ts b/packages/local/src/types.ts
index 5c03b510..94e23156 100644
--- a/packages/local/src/types.ts
+++ b/packages/local/src/types.ts
@@ -54,6 +54,8 @@ export type CreateLocalRuntimeOptions = {
export type ProjectLocalRuntimeOptions = {
/** Project directory containing the private .svml Runtime directory. Defaults to cwd. */
readonly root?: string;
+ /** Host directory whose node_modules contains the packages named by packageLock. Defaults to root. */
+ readonly packageRoot?: string;
readonly statePath?: string;
/** Optional separate Host catalog database. Defaults to statePath when using local SQLite state. */
readonly catalogPath?: string;
diff --git a/packages/local/test/config.test.ts b/packages/local/test/config.test.ts
index cc198dc3..284bf2f3 100644
--- a/packages/local/test/config.test.ts
+++ b/packages/local/test/config.test.ts
@@ -34,12 +34,15 @@ test("declarative Runtime config starts the domain-neutral local defaults", asyn
});
test("Runtime config is closed data and rejects unknown environment authority", () => {
- assert.equal(parseRuntimeConfig({
+ const parsed = parseRuntimeConfig({
format: "svml.runtime-config@1",
+ packageRoot: "/opt/narratage",
catalogPath: ".svml/catalog.sqlite",
endpoints: [],
permissions: [],
- }).catalogPath, ".svml/catalog.sqlite");
+ });
+ assert.equal(parsed.catalogPath, ".svml/catalog.sqlite");
+ assert.equal(parsed.packageRoot, "/opt/narratage");
assert.throws(() => parseRuntimeConfig({
format: "svml.runtime-config@1",
endpoints: [],
diff --git a/packages/local/test/local.test.ts b/packages/local/test/local.test.ts
index 41ebe18a..be3406b9 100644
--- a/packages/local/test/local.test.ts
+++ b/packages/local/test/local.test.ts
@@ -231,8 +231,11 @@ test("project local runtime resumes durable work while component and endpoint pa
test("project local runtime activates locked compute facets without deployment source registration", async () => {
const directory = await mkdtemp(join(tmpdir(), "svml-local-locked-components-"));
- const packageRoot = join(directory, "node_modules", "example-greeting-components");
+ const runtimeRoot = join(directory, "external-project");
+ const installedRoot = join(directory, "narratage-install");
+ const packageRoot = join(installedRoot, "node_modules", "example-greeting-components");
const lockPath = join(directory, "svml.packages.lock");
+ await mkdir(runtimeRoot, { recursive: true });
await mkdir(packageRoot, { recursive: true });
await writeFile(join(packageRoot, "package.json"), JSON.stringify({
name: "example-greeting-components",
@@ -280,11 +283,12 @@ test("project local runtime activates locked compute facets without deployment s
`, "utf8");
try {
- const lock = await createNodePackageLock(["example-greeting-components"], directory);
+ const lock = await createNodePackageLock(["example-greeting-components"], installedRoot);
await writeNodePackageLock(lockPath, lock);
const runtime = await createProjectLocalRuntime({
- root: directory,
- packageLock: "svml.packages.lock",
+ root: runtimeRoot,
+ packageRoot: installedRoot,
+ packageLock: "../svml.packages.lock",
});
await assert.rejects(
async () => await runtime.build({
diff --git a/packages/package-loader-node/README.md b/packages/package-loader-node/README.md
index 3894d3d8..33fa144f 100644
--- a/packages/package-loader-node/README.md
+++ b/packages/package-loader-node/README.md
@@ -1,10 +1,14 @@
# `@narratage/package-loader-node`
-Trusted installed-package locking and loading for Node Hosts. One package lock binds every selected
+Trusted installed-package locking and loading for Node Hosts. One package lock binds every directly selected
physical package and declared dependency byte plus Module, Author/Run Frontend, Host-facet, Producer and Type
Validator identities. Loading verifies all artifacts and checks deterministic compute facets
against their static Manifests before returning verified `NodePackageContribution` values.
+The caller selects only package roots. During the explicit lock action, the Loader follows exact
+Module Manifest dependencies (`ModuleRef + digest`) and adds the unique installed contribution that
+provides each one. This is a local dependency closure, not a built-in package map or registry.
+
This package does not select an author syntax. Syntax-specific executable facets remain inert until
an exact Host ABI installs them. `@narratage/compiler-markup-node` selects the official Markup Surface ABI;
`@narratage/local` can load the same package's deterministic compute facets without depending on Markup.
@@ -17,9 +21,13 @@ deployment configuration independently chooses whether to grant author or determ
Executable plans bind the package-lock digest as `BuildRequest.implementationClosure`.
```bash
-narratage lock-packages ./svml.packages.lock --package @example/cards --root .
+narratage lock-packages ./svml.packages.lock --package @example/cards --package-root .
narratage check ./main.svml --package-lock ./svml.packages.lock --root .
```
+If `@example/cards` requires a Module exported by an installed dependency, that dependency does not
+need another `--package`. Missing, digest-mismatched or ambiguous providers fail while creating the
+lock, before compilation.
+
See [`../../docs/node-package-activation.md`](../../docs/node-package-activation.md)
for the lock, trust and restart laws.
diff --git a/packages/package-loader-node/src/lock.ts b/packages/package-loader-node/src/lock.ts
index 41181a1f..933df226 100644
--- a/packages/package-loader-node/src/lock.ts
+++ b/packages/package-loader-node/src/lock.ts
@@ -142,6 +142,14 @@ function optionalDependency(json: PackageJson, name: string): boolean {
}
async function packageClosure(entries: readonly string[], root: string): Promise<readonly ResolvedPhysicalPackage[]> {
+ return await packageClosureFromPhysical(
+ await Promise.all(entries.map(async (entry) => await resolvePhysicalPackage(entry, root))),
+ );
+}
+
+async function packageClosureFromPhysical(
+ entries: readonly ResolvedPhysicalPackage[],
+): Promise<readonly ResolvedPhysicalPackage[]> {
const resolved = new Map<string, ResolvedPhysicalPackage>();
const visit = async (item: ResolvedPhysicalPackage): Promise<void> => {
const key = `${item.json.name}@${item.json.version}`;
@@ -160,7 +168,7 @@ async function packageClosure(entries: readonly string[], root: string): Promise
}
}
};
- for (const entry of entries) await visit(await resolvePhysicalPackage(entry, root));
+ for (const entry of entries) await visit(entry);
return [...resolved.values()].sort((left, right) =>
`${left.json.name}@${left.json.version}`.localeCompare(`${right.json.name}@${right.json.version}`),
);
@@ -265,6 +273,7 @@ async function importContribution(item: ResolvedPhysicalPackage): Promise<NodePa
function lockContent(lock: Omit<NodePackageLock, "digest">): Omit<NodePackageLock, "digest"> {
return {
format: lock.format,
+ selected: [...lock.selected].sort(),
artifacts: [...lock.artifacts].sort((left, right) =>
`${left.name}@${left.version}`.localeCompare(`${right.name}@${right.version}`),
),
@@ -280,8 +289,11 @@ function sealLock(content: Omit<NodePackageLock, "digest">): NodePackageLock {
function parseLock(value: unknown): NodePackageLock {
const parsed = object(value, "$lock");
assert(parsed.format === "svml.node-package-lock@1", "$lock.format must be svml.node-package-lock@1");
+ assert(Array.isArray(parsed.selected), "$lock.selected must be an array");
assert(Array.isArray(parsed.artifacts), "$lock.artifacts must be an array");
assert(Array.isArray(parsed.packages), "$lock.packages must be an array");
+ const selected = parsed.selected.map((raw, index) => string(raw, `$lock.selected[${index}]`));
+ assert(new Set(selected).size === selected.length, "$lock.selected repeats a package");
const artifacts = parsed.artifacts.map((raw, index) => {
const item = object(raw, `$lock.artifacts[${index}]`);
const digest = string(item.digest, `$lock.artifacts[${index}].digest`);
@@ -311,7 +323,7 @@ function parseLock(value: unknown): NodePackageLock {
});
const digest = string(parsed.digest, "$lock.digest");
assert(isDigest(digest), "$lock.digest is invalid");
- const lock = sealLock({ format: "svml.node-package-lock@1", artifacts, packages });
+ const lock = sealLock({ format: "svml.node-package-lock@1", selected, artifacts, packages });
assert(lock.digest === digest, "Node package lock digest is invalid");
return lock;
}
@@ -329,21 +341,99 @@ function sameArtifacts(left: readonly LockedPackageArtifact[], right: readonly L
=== JSON.stringify([...right].sort((a, b) => `${a.name}@${a.version}`.localeCompare(`${b.name}@${b.version}`)));
}
-/** Lock creation is the explicit trust action and therefore may inspect the selected package exports. */
+/** The explicit trust action may inspect activation metadata inside the selected physical closure. */
export async function createNodePackageLock(
specifiers: readonly string[],
root: string,
): Promise<NodePackageLock> {
const unique = [...new Set(specifiers)].sort();
assert(unique.length > 0, "at least one Node package is required");
- const closure = await packageClosure(unique, root);
+ const selectedPhysical = await Promise.all(unique.map(async (specifier) =>
+ await resolvePhysicalPackage(specifier, root)));
+ const closure = await packageClosureFromPhysical(selectedPhysical);
+ const candidates = new Map<string, {
+ readonly physical: ResolvedPhysicalPackage;
+ readonly contribution: NodePackageContribution;
+ }>();
+ for (const physical of closure) {
+ if (physical.json.svml?.activation === undefined) continue;
+ candidates.set(`${physical.json.name}@${physical.json.version}`, {
+ physical,
+ contribution: await importContribution(physical),
+ });
+ }
+
+ const selectedKeys = new Set(selectedPhysical.map((item) => `${item.json.name}@${item.json.version}`));
+ const activated = new Map<string, {
+ readonly physical: ResolvedPhysicalPackage;
+ readonly contribution: NodePackageContribution;
+ }>();
+ for (const key of selectedKeys) {
+ const candidate = candidates.get(key);
+ assert(candidate !== undefined, `${key} does not declare svml.activation`);
+ activated.set(key, candidate);
+ }
+
+ const moduleKey = (name: string, version: string): string => `${name}@${version}`;
+ const required = new Map<string, string>();
+ const visitContribution = (candidate: {
+ readonly physical: ResolvedPhysicalPackage;
+ readonly contribution: NodePackageContribution;
+ }): void => {
+ for (const module of candidate.contribution.modules ?? []) {
+ for (const dependency of module.manifest.dependencies) {
+ const key = moduleKey(dependency.module.name, dependency.module.version);
+ const existing = required.get(key);
+ assert(existing === undefined || existing === dependency.digest,
+ `Module dependency ${key} is required with two different digests`);
+ required.set(key, dependency.digest);
+ }
+ }
+ };
+ for (const candidate of activated.values()) visitContribution(candidate);
+
+ const satisfied = (): Map<string, string> => {
+ const modules = new Map<string, string>();
+ for (const candidate of activated.values()) {
+ for (const module of candidate.contribution.modules ?? []) {
+ const key = moduleKey(module.manifest.name, module.manifest.version);
+ const digest = digestOf(module.manifest);
+ const existing = modules.get(key);
+ assert(existing === undefined || existing === digest,
+ `activated packages repeat Module ${key} with different digests`);
+ modules.set(key, digest);
+ }
+ }
+ return modules;
+ };
+
+ while (true) {
+ const modules = satisfied();
+ const unresolved = [...required.entries()].find(([key, digest]) => modules.get(key) !== digest);
+ if (unresolved === undefined) break;
+ const [key, digest] = unresolved;
+ const providers = [...candidates.values()].filter((candidate) =>
+ (candidate.contribution.modules ?? []).some((module) =>
+ moduleKey(module.manifest.name, module.manifest.version) === key
+ && digestOf(module.manifest) === digest),
+ );
+ assert(providers.length > 0,
+ `no installed package in the selected physical closure provides required Module ${key} (${digest})`);
+ assert(providers.length === 1,
+ `multiple installed packages in the selected physical closure provide required Module ${key} (${digest})`);
+ const provider = providers[0]!;
+ const providerKey = `${provider.physical.json.name}@${provider.physical.json.version}`;
+ assert(!activated.has(providerKey), `Module dependency ${key} cannot be resolved`);
+ activated.set(providerKey, provider);
+ visitContribution(provider);
+ }
+ collectNodePackageComponents([...activated.values()].map((item) => item.contribution));
+
const packages: LockedNodePackage[] = [];
- for (const specifier of unique) {
- const physical = await resolvePhysicalPackage(specifier, root);
- const contribution = await importContribution(physical);
- const ownArtifacts = await resolvedArtifacts(await packageClosure([specifier], root));
+ for (const { physical, contribution } of activated.values()) {
+ const ownArtifacts = await resolvedArtifacts(await packageClosureFromPhysical([physical]));
packages.push({
- specifier,
+ specifier: physical.json.name,
package: { name: physical.json.name, version: physical.json.version },
facetsDigest: digestOf(contributionMetadata(contribution)),
closureDigest: digestOf({ format: "svml.package-closure@1", artifacts: ownArtifacts }),
@@ -351,6 +441,7 @@ export async function createNodePackageLock(
}
return sealLock({
format: "svml.node-package-lock@1",
+ selected: unique,
artifacts: await resolvedArtifacts(closure),
packages,
});
@@ -366,8 +457,7 @@ export async function loadNodePackageSet(
root = dirname(resolve(path)),
): Promise<LoadedNodePackageSet> {
const lock = parseLock(JSON.parse(await readFile(path, "utf8")));
- const specifiers = lock.packages.map((item) => item.specifier);
- const closure = await packageClosure(specifiers, root);
+ const closure = await packageClosure(lock.selected, root);
const artifacts = await resolvedArtifacts(closure);
assert(sameArtifacts(artifacts, lock.artifacts), "installed Node package bytes do not match the lock");
const byName = new Map(closure.map((item) => [`${item.json.name}@${item.json.version}`, item]));
@@ -375,15 +465,16 @@ export async function loadNodePackageSet(
for (const expected of lock.packages) {
const physical = byName.get(`${expected.package.name}@${expected.package.version}`);
assert(physical !== undefined, `${expected.package.name}@${expected.package.version} is not installed`);
- assert(physical.json.name === expected.specifier, `${expected.specifier} resolved to another package`);
+ assert(physical.json.name === expected.specifier, `${expected.specifier} identifies another package`);
const contribution = await importContribution(physical);
assert(digestOf(contributionMetadata(contribution)) === expected.facetsDigest,
`${expected.specifier} facets do not match the lock`);
- const ownArtifacts = await resolvedArtifacts(await packageClosure([expected.specifier], root));
+ const ownArtifacts = await resolvedArtifacts(await packageClosureFromPhysical([physical]));
assert(digestOf({ format: "svml.package-closure@1", artifacts: ownArtifacts }) === expected.closureDigest,
`${expected.specifier} dependency closure does not match the lock`);
values.push(contribution);
}
+ collectNodePackageComponents(values);
return { lock, contributions: values };
}
diff --git a/packages/package-loader-node/src/types.ts b/packages/package-loader-node/src/types.ts
index 35aab4a3..7fd8d378 100644
--- a/packages/package-loader-node/src/types.ts
+++ b/packages/package-loader-node/src/types.ts
@@ -43,7 +43,10 @@ export type LockedNodePackage = {
export type NodePackageLock = {
readonly format: "svml.node-package-lock@1";
readonly digest: Digest;
+ /** Physical packages selected explicitly by the lock author. */
+ readonly selected: readonly string[];
readonly artifacts: readonly LockedPackageArtifact[];
+ /** Selected contributions plus the exact Module providers required by their Manifests. */
readonly packages: readonly LockedNodePackage[];
};
diff --git a/packages/package-loader-node/test/loader.test.ts b/packages/package-loader-node/test/loader.test.ts
index 312bc8f7..74555bd2 100644
--- a/packages/package-loader-node/test/loader.test.ts
+++ b/packages/package-loader-node/test/loader.test.ts
@@ -18,6 +18,7 @@ import {
} from "@narratage/package-loader-node";
import { RuntimeAdapterRegistry } from "@narratage/runtime-adapter";
import { TypeValidatorRegistry } from "@narratage/validation";
+import { digestOf } from "@narratage/protocol";
import type { ProducerRef } from "@narratage/protocol";
const implementationDigest = `sha256:${"1".repeat(64)}`;
@@ -27,12 +28,15 @@ async function fixture(): Promise<{
readonly root: string;
readonly activation: string;
readonly dependency: string;
+ readonly helperDigest: string;
readonly source: string;
readonly lock: string;
}> {
const root = await mkdtemp(join(tmpdir(), "svml-package-loader-"));
const packageRoot = join(root, "node_modules", "example-card");
- const dependencyRoot = join(root, "node_modules", "example-helper");
+ // Keep the logical Module provider nested: normal loading must rediscover it from the selected
+ // root's physical closure, not assume every activated dependency is resolvable from Workspace root.
+ const dependencyRoot = join(packageRoot, "node_modules", "example-helper");
const typesRoot = join(root, "node_modules", "example-types");
const extraRoot = join(root, "node_modules", "example-extra");
await mkdir(packageRoot, { recursive: true });
@@ -41,13 +45,28 @@ async function fixture(): Promise<{
await mkdir(extraRoot, { recursive: true });
const activation = join(packageRoot, "activation.mjs");
const dependency = join(dependencyRoot, "index.mjs");
+ const helperManifest = {
+ format: "svml.module@1" as const,
+ name: "example.helper",
+ version: "1",
+ dependencies: [],
+ types: [],
+ capabilities: [],
+ surfaces: [],
+ producers: [],
+ };
await writeFile(join(dependencyRoot, "package.json"), JSON.stringify({
name: "example-helper",
version: "1.0.0",
type: "module",
exports: "./index.mjs",
+ svml: { activation: "./index.mjs" },
}, null, 2), "utf8");
- await writeFile(dependency, "export const helper = true;\n", "utf8");
+ await writeFile(dependency, `export default {
+ format: "svml.node-package@1",
+ name: "example-helper",
+ modules: [{ manifest: ${JSON.stringify(helperManifest)} }],
+ };\n`, "utf8");
await writeFile(join(typesRoot, "package.json"), JSON.stringify({
name: "example-types",
version: "1.0.0",
@@ -90,7 +109,10 @@ async function fixture(): Promise<{
format: "svml.module@1",
name: module.name,
version: module.version,
- dependencies: [],
+ dependencies: [{
+ module: { name: "example.helper", version: "1" },
+ digest: ${JSON.stringify(digestOf(helperManifest))},
+ }],
types: [{
name: resultType.name,
schema: { kind: "string", minLength: 1 },
@@ -183,17 +205,27 @@ async function fixture(): Promise<{
<import as="example" from="example.card@1"/>
<example:Card/>
</svml>`, "utf8");
- return { root, activation, dependency, source, lock: join(root, "svml.packages.lock") };
+ return {
+ root,
+ activation,
+ dependency,
+ helperDigest: digestOf(helperManifest),
+ source,
+ lock: join(root, "svml.packages.lock"),
+ };
}
test("an installed locked package carries inert Host facets and activatable compute", async () => {
const item = await fixture();
const lock = await createNodePackageLock(["example-card"], item.root);
assert.deepEqual(lock.artifacts.map((artifact) => artifact.name), ["example-card", "example-helper", "example-types"]);
+ assert.deepEqual(lock.selected, ["example-card"]);
+ assert.deepEqual(lock.packages.map((value) => value.specifier), ["example-card", "example-helper"]);
await writeNodePackageLock(item.lock, lock);
const packages = await loadNodePackageContributions(item.lock, item.root);
assert.equal(packages[0]?.name, "example-card");
+ assert.equal(packages[1]?.name, "example-helper");
assert.equal(packages[0]?.hostFacets?.[0]?.abi, "svml.markup-surface-host@1");
const registered: Array<{ readonly producer: ProducerRef; readonly digest: string }> = [];
@@ -220,6 +252,49 @@ test("dependency bytes are rejected before a locked contribution entry is reused
);
});
+test("a missing exact Module provider is rejected while the lock is created", async () => {
+ const item = await fixture();
+ await writeFile(
+ item.activation,
+ (await readFile(item.activation, "utf8")).replace(item.helperDigest, `sha256:${"9".repeat(64)}`),
+ "utf8",
+ );
+
+ await assert.rejects(
+ async () => await createNodePackageLock(["example-card"], item.root),
+ /no installed package .* provides required Module example\.helper@1/u,
+ );
+});
+
+test("two physical packages cannot ambiguously provide one required Module", async () => {
+ const item = await fixture();
+ const copyRoot = join(item.root, "node_modules", "example-helper-copy");
+ await mkdir(copyRoot, { recursive: true });
+ await writeFile(join(copyRoot, "package.json"), JSON.stringify({
+ name: "example-helper-copy",
+ version: "1.0.0",
+ type: "module",
+ exports: "./index.mjs",
+ svml: { activation: "./index.mjs" },
+ }, null, 2), "utf8");
+ await writeFile(
+ join(copyRoot, "index.mjs"),
+ (await readFile(item.dependency, "utf8")).replace('name: "example-helper"', 'name: "example-helper-copy"'),
+ "utf8",
+ );
+ const cardPackagePath = join(item.root, "node_modules", "example-card", "package.json");
+ const cardPackage = JSON.parse(await readFile(cardPackagePath, "utf8")) as {
+ dependencies: Record<string, string>;
+ };
+ cardPackage.dependencies["example-helper-copy"] = "1.0.0";
+ await writeFile(cardPackagePath, JSON.stringify(cardPackage, null, 2), "utf8");
+
+ await assert.rejects(
+ async () => await createNodePackageLock(["example-card"], item.root),
+ /multiple installed packages .* provide required Module example\.helper@1/u,
+ );
+});
+
test("an unrelated selected package does not contaminate another package's implementation closure", async () => {
const item = await fixture();
const alone = await createNodePackageLock(["example-card"], item.root);
diff --git a/packages/seedance-kits/README.md b/packages/seedance-kits/README.md
index 03a72719..f021457c 100644
--- a/packages/seedance-kits/README.md
+++ b/packages/seedance-kits/README.md
@@ -3,6 +3,10 @@
Data-only authoring Kits for recurring Seedance semantics. They are `TextTemplate` source modules,
not model wrappers, Providers or new execution nodes.
+Vendor the selected `.svs` file into the video project (for example `./kits/speaker-v1.svs`). This
+keeps its bytes inside the project's Source Closure and Workspace boundary; a project must not
+reach back into a Narratage checkout through `../../packages/...`.
+
Each Kit is rendered by the domain-neutral `text:Render` Surface. Its Text output then feeds one of
the three low-level `@narratage/seedance` invocation modes. Reference media and duration remain
ordinary explicit graph edges:
@@ -10,7 +14,7 @@ ordinary explicit graph edges:
```svml
<import as="text" from="@narratage/text@1"/>
<import as="seedance" from="@narratage/seedance@1"/>
-<import as="broll-kit" source="../../packages/seedance-kits/kits/broll-v1.svs"/>
+<import as="broll-kit" source="./kits/broll-v1.svs"/>
<text:Render id="broll-prompt" template={broll-kit.broll-v1} recipe={studio.broll}>
<text:Set name="story" text={copy.broll}/>
@@ -27,7 +31,7 @@ Speaker uses the same graph vocabulary. The Kit assumes `@image1` is the visible
`@audio1` is the voice-timbre reference; it owns no media counting or generation wrapper:
```svml
-<import as="speaker-kit" source="../../packages/seedance-kits/kits/speaker-v1.svs"/>
+<import as="speaker-kit" source="./kits/speaker-v1.svs"/>
<text:Render id="hook-prompt"
template={speaker-kit.speaker-v1}
diff --git a/packages/svs/src/parser.ts b/packages/svs/src/parser.ts
index 8ce9ea06..0285fb32 100644
--- a/packages/svs/src/parser.ts
+++ b/packages/svs/src/parser.ts
@@ -1,6 +1,11 @@
import type { CanonicalValue } from "@narratage/protocol";
-import type { ParsedSvsRecipe, ParsedSvsSheet, SvsRecipe } from "./types.js";
+import type {
+ ParsedSvsProperty,
+ ParsedSvsRecipe,
+ ParsedSvsSheet,
+ SvsRecipe,
+} from "./types.js";
const RULE = /^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)+/u;
const PROPERTY = /^[a-z][a-z0-9-]*/u;
@@ -174,12 +179,17 @@ function parseProperties(
sourceName: string,
text: string,
offset: number,
-): Readonly<Record<string, CanonicalValue>> {
+): {
+ readonly values: Readonly<Record<string, CanonicalValue>>;
+ readonly parsed: readonly ParsedSvsProperty[];
+} {
const properties: Record<string, CanonicalValue> = {};
+ const parsed: ParsedSvsProperty[] = [];
let cursor = 0;
while (cursor < text.length) {
cursor = skipSpace(text, cursor);
if (cursor >= text.length) break;
+ const propertyStart = cursor;
const match = PROPERTY.exec(text.slice(cursor));
if (!match) fail(sourceName, "SVS_PROPERTY", "Expected a recipe property.", offset + cursor);
const name = match[0];
@@ -193,9 +203,18 @@ function parseProperties(
const semicolon = valueSemicolon(text, valueStart);
if (semicolon < 0) fail(sourceName, "SVS_PROPERTY_SEMICOLON", `Property ${name} requires ';'.`, offset + valueStart);
properties[name] = parseValue(sourceName, text.slice(valueStart, semicolon), offset + valueStart);
+ let trimmedStart = valueStart;
+ let trimmedEnd = semicolon;
+ while (/\s/u.test(text[trimmedStart] ?? "")) trimmedStart += 1;
+ while (trimmedEnd > trimmedStart && /\s/u.test(text[trimmedEnd - 1] ?? "")) trimmedEnd -= 1;
+ parsed.push({
+ name,
+ range: { start: offset + propertyStart, end: offset + semicolon + 1 },
+ valueRange: { start: offset + trimmedStart, end: offset + trimmedEnd },
+ });
cursor = semicolon + 1;
}
- return properties;
+ return { values: properties, parsed };
}
export function parseSvs(sourceName: string, source: string): ParsedSvsSheet {
@@ -228,12 +247,13 @@ export function parseSvs(sourceName: string, source: string): ParsedSvsSheet {
const blockStart = cursor + 1;
const blockEnd = closingBrace(text, blockStart, close);
if (blockEnd < 0 || blockEnd > close) fail(sourceName, "SVS_RULE_UNCLOSED", `Recipe ${path} is not closed.`, start);
+ const parsedProperties = parseProperties(sourceName, text.slice(blockStart, blockEnd), blockStart);
const value: SvsRecipe = {
contract: "svml.svs-recipe@1",
path,
- properties: parseProperties(sourceName, text.slice(blockStart, blockEnd), blockStart),
+ properties: parsedProperties.values,
};
- recipes.push({ value, range: { start, end: blockEnd + 1 } });
+ recipes.push({ value, range: { start, end: blockEnd + 1 }, properties: parsedProperties.parsed });
cursor = blockEnd + 1;
}
return {
diff --git a/packages/svs/src/types.ts b/packages/svs/src/types.ts
index a51da8ee..b20fae64 100644
--- a/packages/svs/src/types.ts
+++ b/packages/svs/src/types.ts
@@ -9,6 +9,16 @@ export type SvsRecipe = {
export type ParsedSvsRecipe = {
readonly value: SvsRecipe;
readonly range: SourceRange;
+ /** Exact author-source spans, for editors that must preserve surrounding trivia. */
+ readonly properties: readonly ParsedSvsProperty[];
+};
+
+export type ParsedSvsProperty = {
+ readonly name: string;
+ /** From the property name through its terminating semicolon. */
+ readonly range: SourceRange;
+ /** The trimmed value only; replacing this span preserves author formatting. */
+ readonly valueRange: SourceRange;
};
export type ParsedSvsSheet = {
diff --git a/packages/svs/test/source-closure.test.ts b/packages/svs/test/source-closure.test.ts
index 20d91c19..8605f7f6 100644
--- a/packages/svs/test/source-closure.test.ts
+++ b/packages/svs/test/source-closure.test.ts
@@ -412,3 +412,18 @@ test("quoted Recipe values may contain Prompt punctuation without changing SVS s
);
assert.equal(sheet.recipes[0]?.value.properties.text, "first; second } /* literal */");
});
+
+test("SVS exposes exact property and value spans without inventing editor metadata", () => {
+ const source = `<sheet version="1">
+ caption.primary {
+ size : 58 ; /* preserve me */
+ padding: 16 24;
+ }
+</sheet>`;
+ const recipe = parseSvs("editable.svs", source).recipes[0]!;
+ const size = recipe.properties.find((property) => property.name === "size")!;
+ assert.equal(source.slice(size.range.start, size.range.end), "size : 58 ;");
+ assert.equal(source.slice(size.valueRange.start, size.valueRange.end), "58");
+ const padding = recipe.properties.find((property) => property.name === "padding")!;
+ assert.equal(source.slice(padding.valueRange.start, padding.valueRange.end), "16 24");
+});
diff --git a/packages/video-cli/README.md b/packages/video-cli/README.md
index 7ddc1d6f..46917738 100644
--- a/packages/video-cli/README.md
+++ b/packages/video-cli/README.md
@@ -12,9 +12,9 @@ From the repository:
```bash
pnpm narratage lock-packages ./svml.packages.lock \
- --package @narratage/run-markup --package @narratage/script --package @example/cards --root .
+ --package @narratage/run-markup --package @narratage/script --package @example/cards --package-root .
pnpm narratage lock-packages ./svml.runtime-packages.lock \
- --package @narratage/provider-kie --package @narratage/provider-media-local --root .
+ --package @narratage/provider-kie --package @narratage/provider-media-local --package-root .
pnpm narratage check path/to/main.svml --package-lock ./svml.packages.lock --root .
pnpm narratage check path/to/build.svrun --package-lock ./svml.packages.lock --root .
pnpm narratage plan path/to/build.svrun --package-lock ./svml.packages.lock --root .
@@ -29,6 +29,13 @@ pnpm narratage doctor ./svml.runtime.json
pnpm narratage gc ./svml.runtime.json
```
+`--root` is only the Source Workspace containment boundary. `--package-root` is only the Host
+override used to resolve the installed packages named by a lock; by default this Distribution uses
+its own installation location. Keeping the two concepts separate lets a video project live outside
+this checkout without weakening canonical-path source and asset containment. A JSON Runtime Profile
+has the same optional `packageRoot` override while retaining state and Artifacts under its own
+`root`.
+
`check` is usable for an Author Source or a complete Run Source. `plan` and `build` require a Run
Source because an Author Graph without execution intent is not a Build. The live example executes
the explicit Vertex Gemini Caption package and real local/remote Endpoints; the CLI never
diff --git a/packages/video-cli/src/compiler.ts b/packages/video-cli/src/compiler.ts
index 0cf1e701..5fa53de5 100644
--- a/packages/video-cli/src/compiler.ts
+++ b/packages/video-cli/src/compiler.ts
@@ -7,6 +7,6 @@ export const videoBuiltInPackageContributions = [] as const;
/** Assemble the Markup compiler Host from only the packages selected for this invocation. */
export function createVideoCompiler(options: CliCompilerOptions) {
return createMarkupNodeCompiler(options.packageContributions, {
- ...(options.root === undefined ? {} : { root: options.root }),
+ ...(options.workspaceRoot === undefined ? {} : { root: options.workspaceRoot }),
});
}
diff --git a/packages/video-cli/src/distribution.ts b/packages/video-cli/src/distribution.ts
index 3279b8c1..bb2acf8c 100644
--- a/packages/video-cli/src/distribution.ts
+++ b/packages/video-cli/src/distribution.ts
@@ -11,17 +11,20 @@ import {
} from "@narratage/local";
import { createVideoRuntimeFromConfig } from "./runtime-config.js";
+const packageRoot = import.meta.dirname;
+
/** Official video authoring and local Runtime-adapter assembly for the generic CLI engine. */
export const videoCliDistribution: CliDistribution = {
name: "@narratage/video-cli",
+ packageRoot,
builtInPackageContributions: videoBuiltInPackageContributions,
runFrontends: [],
createCompiler: createVideoCompiler,
createRuntimeFromConfig: createVideoRuntimeFromConfig,
- doctorRuntimeConfig,
+ doctorRuntimeConfig: async (path) => await doctorRuntimeConfig(path, { packageRoot }),
externalServices: {
- up: bringExternalServicesUp,
- down: takeExternalServicesDown,
- report: reportExternalServices,
+ up: async (path, options) => await bringExternalServicesUp(path, { ...options, packageRoot }),
+ down: async (path) => await takeExternalServicesDown(path, { packageRoot }),
+ report: async (path) => await reportExternalServices(path, { packageRoot }),
},
};
diff --git a/packages/video-cli/src/runtime-config.ts b/packages/video-cli/src/runtime-config.ts
index 981114d3..e331840f 100644
--- a/packages/video-cli/src/runtime-config.ts
+++ b/packages/video-cli/src/runtime-config.ts
@@ -4,6 +4,6 @@ import { createRuntimeFromConfig } from "@narratage/local";
* Video CLI assembly adds no privileged Provider registry. The Runtime Profile selects
* locked Runtime Adapter packages, so installing a new adapter never changes this CLI.
*/
-export async function createVideoRuntimeFromConfig(path: string) {
- return await createRuntimeFromConfig(path);
+export async function createVideoRuntimeFromConfig(path: string, packageRoot = import.meta.dirname) {
+ return await createRuntimeFromConfig(path, { packageRoot });
}
diff --git a/packages/video-cli/test/cli.test.ts b/packages/video-cli/test/cli.test.ts
index d8c0ccf2..d5114c98 100644
--- a/packages/video-cli/test/cli.test.ts
+++ b/packages/video-cli/test/cli.test.ts
@@ -121,7 +121,7 @@ test("author source binds an ordered exact Font stack to a Fine Caption Style",
caption.primary {
cue-min-words: 1; cue-max-words: 4;
stack-order: 20; x: 0.5; y: 0.9; width: 0.8;
- align: center; font: Studio Sans; weight: 600; size: 48; line-height: 1.1;
+ align: center; size: 48; line-height: 1.1;
fill: #ffffff; background: #00000000; padding: 0 0; radius: 0;
}
</sheet>`, "utf8");
@@ -158,7 +158,7 @@ test("an installed open-font package supplies a multilingual exact stack without
caption.primary {
cue-min-words: 1; cue-max-words: 4;
stack-order: 20; x: 0.5; y: 0.9; width: 0.8;
- align: center; font: Installed Open Stack; weight: 700; size: 48; line-height: 1.1;
+ align: center; size: 48; line-height: 1.1;
fill: #ffffff; background: #00000000; padding: 0 0; radius: 0;
}
</sheet>`, "utf8");
@@ -271,7 +271,7 @@ test("CLI accepts a declarative Runtime Profile without an executable config mod
);
await writeFile(profile, JSON.stringify({
format: "svml.runtime-config@1",
- root: process.cwd(),
+ root,
statePath: join(root, "state.sqlite"),
catalogPath: join(root, "catalog.sqlite"),
artifactPath: join(root, "artifacts"),
@@ -344,18 +344,21 @@ test("one checked-in fixture closes the complete provider-free video plan", asyn
});
test("CLI package lock activates an installed package without changing the official host", async () => {
- const root = await mkdtemp(join(tmpdir(), "svml-cli-package-lock-"));
- const packageRoot = join(root, "node_modules", "example-empty");
- await mkdir(packageRoot, { recursive: true });
+ const directory = await mkdtemp(join(tmpdir(), "svml-cli-package-lock-"));
+ const projectRoot = join(directory, "external-video-project");
+ const installedPackage = join(directory, "narratage-install", "node_modules", "example-empty");
+ const packageRoot = join(directory, "narratage-install");
+ await mkdir(projectRoot, { recursive: true });
+ await mkdir(installedPackage, { recursive: true });
const implementationDigest = `sha256:${"2".repeat(64)}`;
- await writeFile(join(packageRoot, "package.json"), JSON.stringify({
+ await writeFile(join(installedPackage, "package.json"), JSON.stringify({
name: "example-empty",
version: "1.0.0",
type: "module",
exports: "./activation.mjs",
svml: { activation: "./activation.mjs" },
}), "utf8");
- await writeFile(join(packageRoot, "activation.mjs"), `
+ await writeFile(join(installedPackage, "activation.mjs"), `
const module = { name: "example.empty", version: "1" };
const digest = ${JSON.stringify(implementationDigest)};
export default {
@@ -375,8 +378,8 @@ test("CLI package lock activates an installed package without changing the offic
}],
};
`, "utf8");
- const file = join(root, "main.svml");
- const lockPath = join(root, "svml.packages.lock");
+ const file = join(projectRoot, "main.svml");
+ const lockPath = join(projectRoot, "svml.packages.lock");
await writeFile(file, `<?svml using="@narratage/markup@1"?>
<svml>
<import as="example" from="example.empty@1"/>
@@ -384,18 +387,18 @@ test("CLI package lock activates an installed package without changing the offic
</svml>`, "utf8");
await assert.rejects(
- async () => await runCli(["check", file, "--root", root], { write() {} }),
+ async () => await runCli(["check", file], { write() {} }),
/No registered module satisfies example\.empty@1/,
);
let lockOutput = "";
- await runCli(["lock-packages", lockPath, "--package", "example-empty", "--root", root], {
+ await runCli(["lock-packages", lockPath, "--package", "example-empty", "--package-root", packageRoot], {
write: (text) => { lockOutput += text; },
});
assert.equal(JSON.parse(lockOutput).ok, true);
let checkOutput = "";
- await runCli(["check", file, "--package-lock", lockPath, "--root", root], {
+ await runCli(["check", file, "--package-lock", lockPath, "--package-root", packageRoot], {
write: (text) => { checkOutput += text; },
});
const checked = JSON.parse(checkOutput) as { readonly ok: boolean; readonly modules: readonly string[] };
diff --git a/spec/caption-fine.md b/spec/caption-fine.md
index 37cfcb7e..f5df0748 100644
--- a/spec/caption-fine.md
+++ b/spec/caption-fine.md
@@ -62,14 +62,14 @@ must be a separately connected component whose failure is explicit in the graph.
### 3. Typography
-- `font`, `weight`, `size`, `font-style: normal | italic | oblique`
+- Recipe: `size`
- `text-transform: none | uppercase | lowercase`
Text transform is terminal presentation only. It never changes `CaptionDisplaySequence`, planner
input, Word/Atom identity, speech correspondence or timing.
-The Recipe's `font` property is a readable family label, not a source of bytes. Every Style must
-import exact installed faces from `@narratage/fonts-open`, or declare custom/brand bytes with
+Family, weight and style are deliberately absent from the Recipe. Every Style must import exact
+installed faces from `@narratage/fonts-open`, or declare custom/brand bytes with
`<media:Font>`. `font=` accepts one exact face with ordered Style-owned
Fallback children, or one reusable generic `FontStackRef`. The compact open-font path is:
@@ -80,8 +80,8 @@ Fallback children, or one reusable generic `FontStackRef`. The compact open-font
<caption-fine:Style id="primary" recipe={studio.caption.primary} font={caption-fonts}/>
```
-The primary face must declare the Recipe's exact weight/style. A fallback preserves its own honest
-face metadata—for example a 700-weight Latin primary may use a 400-weight symbol fallback. Exact
+The font edge is the single source of truth for family, weight and style. A fallback preserves its
+own honest face metadata—for example a 700-weight Latin primary may use a 400-weight symbol fallback. Exact
duplicate faces are rejected. One logical face may contain several content-addressed Unicode-range
sources, as the installed CJK and Emoji fonts do. Fine expands `FontStackRef` into the same ordered
exact faces and puts them only
diff --git a/test/caption-playground-runtime-shim.test.ts b/test/caption-playground-runtime-shim.test.ts
new file mode 100644
index 00000000..5b5f852a
--- /dev/null
+++ b/test/caption-playground-runtime-shim.test.ts
@@ -0,0 +1,49 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { sealComposition, sealVisualTrack } from "@narratage/composition";
+import { compileHyperframesDocument } from "@narratage/hyperframes";
+import { sealProgramSpace } from "@narratage/program-space";
+
+import { injectRuntimeShim } from "../tools/caption-playground/src/preview/runtime-shim.js";
+
+const space = sealProgramSpace({
+ contract: "svml.program-space@1",
+ durationSec: 2,
+ frameRate: { numerator: 30, denominator: 1 },
+});
+
+function document_() {
+ return compileHyperframesDocument(sealComposition({
+ contract: "svml.composition@1",
+ id: "caption-preview",
+ canvas: { width: 1080, height: 1920, clearColor: "#09090b" },
+ tracks: [sealVisualTrack({
+ contract: "svml.visual-track@1",
+ visualIr: "svml.visual-ir@1",
+ id: "caption",
+ presents: [{
+ id: "one", span: { startFrame: 0, endFrameExclusive: 30 },
+ stacking: { order: 10, tieBreak: "caption" },
+ elements: [{ id: "root", order: 0, kind: "box", style: [{ name: "position", value: "absolute" }] }],
+ }],
+ })],
+ }), space);
+}
+
+test("Caption preview shim sizes the Hyperframes root and supplies a seekable timeline", () => {
+ const { html } = document_();
+ const rootRule = /\[data-composition-id\]\{([^}]*)\}/u.exec(html);
+ assert.notEqual(rootRule, null);
+ assert.doesNotMatch(rootRule![1]!, /(^|;)\s*(width|height)\s*:/u);
+ assert.doesNotMatch(html, /visibility\s*:/u);
+ const output = injectRuntimeShim(html);
+ assert.match(output, /root\.style\.height/u);
+ assert.match(output, /__svmlSeekFrame/u);
+ assert.match(output, /visibility/u);
+ assert.ok(output.lastIndexOf("<script>") < output.lastIndexOf("</body>"));
+});
+
+test("Caption preview shim is still injected when body close is absent", () => {
+ assert.match(injectRuntimeShim("<!doctype html><html></html>"), /__svmlSeekFrame/u);
+});
diff --git a/test/playground-discovery.test.ts b/test/playground-discovery.test.ts
deleted file mode 100644
index 0b8ece7d..00000000
--- a/test/playground-discovery.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import assert from "node:assert/strict";
-import { readdirSync } from "node:fs";
-import test from "node:test";
-import { fileURLToPath } from "node:url";
-
-import { discoverPreviewProducers } from "../tools/playground/src/discovery/producers.js";
-import type { PreviewSources } from "../tools/playground/src/discovery/producers.js";
-
-/**
- * The playground lists no components. It finds them, by asking the manifests
- * which modules declare a Producer that outputs a VisualTrack.
- *
- * These tests run that discovery over the real workspace, so a module that
- * gains or loses a visual Producer changes the result here without anybody
- * editing a list — which is the property the whole arrangement exists for.
- */
-
-const packages = fileURLToPath(new URL("../packages", import.meta.url));
-
-function workspace(): PreviewSources {
- const entries: Record<string, () => Promise<unknown>> = {};
- const components: Record<string, () => Promise<unknown>> = {};
- for (const dir of readdirSync(packages, { withFileTypes: true })) {
- if (!dir.isDirectory()) continue;
- // The browser follows this same dedicated metadata boundary. Importing
- // package indexes would pull Node-only Providers and Drivers into Vite.
- entries[`${dir.name}/manifest`] = async () => await import(`${packages}/${dir.name}/src/manifest.ts`);
- components[dir.name] = async () => await import(`${packages}/${dir.name}/src/component.ts`);
- }
- return { manifests: entries, components };
-}
-
-test("an arbitrary supplied visual module is discovered without registration", async () => {
- const module = { name: "@example/visual", version: "1" } as const;
- const input = { module, name: "Input" } as const;
- const track = {
- module: { name: "@narratage/composition", version: "1" },
- name: "VisualTrack",
- } as const;
- const implementation = {
- kind: "registered", locator: "@example/visual/render",
- digest: `sha256:${"0".repeat(64)}`,
- } as const;
-
- const found = await discoverPreviewProducers({
- manifests: {
- arbitrary: async () => ({ manifest: {
- format: "svml.module@1", name: module.name, version: module.version,
- dependencies: [], capabilities: [], surfaces: [],
- types: [{ name: input.name, schema: { kind: "string" } }],
- producers: [{
- name: "render", inputs: [{ name: "input", type: input }],
- outputs: [{ name: "track", type: track }], needs: [], implementation,
- }],
- } }),
- },
- components: {
- arbitrary: async () => ({ component: {
- name: module.name,
- producers: [{
- producer: { module, name: "render" },
- handler: () => ({ outputs: { track: { value: "arbitrary-output" } } }),
- }],
- } }),
- },
- });
-
- assert.equal(found.length, 1);
- assert.equal(found[0]?.id, "@example/visual#render");
- assert.deepEqual(found[0]?.inputs.map((entry) => entry.name), ["input"]);
-});
-
-test("each producer carries its inputs' declared schemas", async () => {
- for (const producer of await discoverPreviewProducers(workspace())) {
- assert.ok(producer.inputs.length > 0, `${producer.id} declares no inputs`);
- for (const input of producer.inputs) {
- assert.notEqual(input.schema, undefined,
- `${producer.id} input ${input.name} has no schema, so no form can be built for it`);
- }
- }
-});
-
-test("discovery never obtains authored values from production type declarations", async () => {
- const found = await discoverPreviewProducers(workspace());
- for (const producer of found) {
- for (const input of producer.inputs) {
- assert.deepEqual(Object.keys(input).sort(), ["name", "schema", "type"]);
- }
- }
-});
-
-test("each producer is discovered exactly once", async () => {
- const found = await discoverPreviewProducers(workspace());
- assert.equal(new Set(found.map((producer) => producer.id)).size, found.length);
-});
diff --git a/test/playground-runtime-shim.test.ts b/test/playground-runtime-shim.test.ts
deleted file mode 100644
index 3747f881..00000000
--- a/test/playground-runtime-shim.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import { sealComposition, sealVisualTrack } from "@narratage/composition";
-import { compileHyperframesDocument } from "@narratage/hyperframes";
-import { sealProgramSpace } from "@narratage/program-space";
-
-import { injectRuntimeShim } from "../tools/playground/src/preview/runtime-shim.js";
-
-/**
- * The playground shows the compiled document directly in an iframe, so it must
- * supply the two things a real render gets from the HyperFrames producer: a
- * sized composition root, and a timeline. Both are absences in the document
- * rather than statements in it, which makes them easy to regress silently —
- * these tests pin the absences so the shim's reason for existing stays visible.
- */
-
-const programSpace = sealProgramSpace({
- contract: "svml.program-space@1",
- durationSec: 2,
- frameRate: { numerator: 30, denominator: 1 },
-});
-
-function document_() {
- const track = sealVisualTrack({
- contract: "svml.visual-track@1",
- visualIr: "svml.visual-ir@1",
- id: "shot",
- presents: [{
- id: "one",
- span: { startFrame: 0, endFrameExclusive: 30 },
- stacking: { order: 10, tieBreak: "shot" },
- elements: [{
- id: "root",
- order: 0,
- kind: "box",
- style: [{ name: "position", value: "absolute" }, { name: "inset", value: 0 }],
- }],
- }],
- });
- return compileHyperframesDocument(sealComposition({
- contract: "svml.composition@1",
- id: "shim-fixture",
- canvas: { width: 1080, height: 1920, clearColor: "#09090b" },
- tracks: [track],
- }), programSpace);
-}
-
-test("the compiled document states its frame size only as data, never as layout", () => {
- const { html } = document_();
- // The size is present to read...
- assert.match(html, /data-width="1080"/u);
- assert.match(html, /data-height="1920"/u);
- // ...but the root's own rule carries no width or height, so the element
- // computes to zero height and clips every Present away. If this assertion
- // ever fails the upstream compiler started sizing the root and the shim can
- // stop doing it.
- const rootRule = /\[data-composition-id\]\{([^}]*)\}/u.exec(html);
- assert.notEqual(rootRule, null, "the compiled stylesheet must scope a rule to the composition root");
- assert.doesNotMatch(rootRule![1]!, /(^|;)\s*(width|height)\s*:/u);
-});
-
-test("the compiled document gates no Present and delays no animation", () => {
- const { html } = document_();
- assert.match(html, /class="clip svml-visual-present"/u);
- // data-start is metadata, not a rule: nothing hides a Present outside its span.
- assert.doesNotMatch(html, /visibility\s*:/u);
- assert.doesNotMatch(html, /animation-delay/u);
-});
-
-test("the shim supplies the size and the timeline, immediately before body close", () => {
- const shimmed = injectRuntimeShim(document_().html);
- assert.match(shimmed, /root\.style\.height/u);
- assert.match(shimmed, /__svmlSeekFrame/u);
- assert.match(shimmed, /visibility/u);
- const script = shimmed.lastIndexOf("<script>");
- assert.ok(script !== -1 && script < shimmed.lastIndexOf("</body>"),
- "the shim must run after the elements it seeks exist");
-});
-
-test("a document without a body close still receives the shim", () => {
- assert.match(injectRuntimeShim("<!doctype html><html></html>"), /__svmlSeek/u);
-});
diff --git a/tools/caption-playground-sha256.test.mjs b/tools/caption-playground-sha256.test.mjs
new file mode 100644
index 00000000..d772c740
--- /dev/null
+++ b/tools/caption-playground-sha256.test.mjs
@@ -0,0 +1,17 @@
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import test from "node:test";
+
+import { createHash as shimCreateHash } from "./caption-playground/src/shims/node-crypto.ts";
+
+const cases = ["", "abc", "x".repeat(55), "x".repeat(56), "x".repeat(64), "字幕轨道与画布"];
+test("Caption Playground browser sha256 agrees with Node", () => {
+ for (const value of cases) {
+ assert.equal(shimCreateHash("sha256").update(value).digest("hex"), createHash("sha256").update(value).digest("hex"));
+ }
+});
+
+test("Caption Playground browser sha256 rejects unsupported operations", () => {
+ assert.throws(() => shimCreateHash("sha512"), /sha256/u);
+ assert.throws(() => shimCreateHash("sha256").update("a").digest("base64"), /hex/u);
+});
diff --git a/tools/caption-playground-source-bytes.test.mjs b/tools/caption-playground-source-bytes.test.mjs
new file mode 100644
index 00000000..2809f841
--- /dev/null
+++ b/tools/caption-playground-source-bytes.test.mjs
@@ -0,0 +1,25 @@
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const root = fileURLToPath(new URL("..", import.meta.url));
+const paths = execFileSync("git", ["ls-files", "-c", "-o", "--exclude-standard", "tools/caption-playground", "test"], {
+ cwd: root, encoding: "utf8",
+}).trim().split("\n").filter((path) => /\.(?:ts|mjs|js|html|css|json)$/u.test(path));
+
+test("Caption Playground source carries no raw control byte", () => {
+ const offenders = [];
+ for (const path of paths) {
+ const file = new URL(path, new URL("..", import.meta.url));
+ if (!existsSync(file)) continue;
+ for (const [index, byte] of readFileSync(file).entries()) {
+ if (byte < 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d) {
+ offenders.push(`${path}: 0x${byte.toString(16)} at ${index}`);
+ break;
+ }
+ }
+ }
+ assert.deepEqual(offenders, []);
+});
diff --git a/tools/caption-playground/README.md b/tools/caption-playground/README.md
new file mode 100644
index 00000000..b698ecfa
--- /dev/null
+++ b/tools/caption-playground/README.md
@@ -0,0 +1,54 @@
+# Caption Playground
+
+A filesystem-backed editor for one real Fine Caption Style. It is deliberately
+not a generic component inspector.
+
+```bash
+pnpm caption:playground -- \
+ --source examples/talking-film-graph-check/main.svml \
+ --package-lock examples/talking-film-graph-check/svml.packages.lock \
+ --style base-caption \
+ --display story.caption \
+ --recipe examples/talking-film-graph-check/studio.svs#caption.base \
+ --font examples/talking-film-graph-check/main.svml#caption-font \
+ --canvas 1080x1920 \
+ --fps 30
+```
+
+Every semantic input is selected at startup. There is no central package list,
+component registry, preview default or private Playground document.
+
+The author Source, SVS and font-source files may live outside this repository. Installed packages
+resolve from this tool's own installation by default; pass `--package-root <directory>` only when
+the lock names packages installed somewhere else. Source containment and package resolution remain
+separate boundaries, just as they are in the CLI.
+
+## Source of truth
+
+- Recipe controls write the named properties in the selected `.svs` Recipe.
+- Font controls write `family`, `weight` and `style` on the selected
+ `<fonts:Stack>` in the `.svml` source.
+- Script and other external edits are watched and recompiled.
+- Each browser write carries the digest it read. If an editor or Agent changed
+ the file first, the stale browser write is rejected and the newest source is
+ shown.
+
+Writes are atomic. The browser keeps only the playhead, search text and open UI
+sections in memory.
+
+## What is real and what is preview-only
+
+The Node side loads the selected package lock and runs the ordinary author
+compiler. The browser receives the real `CaptionStyleIntent`,
+`CaptionDisplaySequence` and exact font attachments, then calls the real Fine
+Caption renderer and Hyperframes document compiler.
+
+The only synthetic fact is a local showcase timeline used to scrub karaoke and
+motion before WhisperX evidence exists. It never becomes a Record, SemanticMap,
+BuildState or source file. It therefore cannot claim estimated timing in the
+author or run graph.
+
+The font gallery is the catalog already owned by `@narratage/fonts-open`; font
+cards lazy-load and render their own pinned font bytes. Selecting a card still
+changes the real `fonts:Stack`, so the next frame is compiled from the same font
+Artifact path as a Build.
diff --git a/tools/caption-playground/index.html b/tools/caption-playground/index.html
new file mode 100644
index 00000000..ffcc0678
--- /dev/null
+++ b/tools/caption-playground/index.html
@@ -0,0 +1,10 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <link rel="icon" href="data:," />
+ <title>Caption Playground · Narratage</title>
+ </head>
+ <body><div id="app"></div><script type="module" src="/src/main.ts"></script></body>
+</html>
diff --git a/tools/caption-playground/src/main.ts b/tools/caption-playground/src/main.ts
new file mode 100644
index 00000000..4bbfef71
--- /dev/null
+++ b/tools/caption-playground/src/main.ts
@@ -0,0 +1,329 @@
+import type { CaptionProgram, TimedCaptionProjection } from "@narratage/caption";
+import { resolveCaptionProgram } from "@narratage/caption";
+import { renderFineCaption } from "@narratage/caption-fine";
+import type { CaptionDisplayAtom, CaptionDisplaySequence } from "@narratage/narrative";
+import type { CanonicalValue, ValueSchema } from "@narratage/protocol";
+import { sealProgramSpace } from "@narratage/program-space";
+
+import type {
+ CaptionPlaygroundFailure,
+ CaptionPlaygroundFont,
+ CaptionPlaygroundSnapshot,
+ FontPatch,
+ RecipePatch,
+} from "./shared.js";
+import { renderPreview } from "./preview/render.js";
+import { createStage } from "./ui/stage.js";
+import "./style.css";
+
+const app = document.querySelector<HTMLElement>("#app")!;
+app.innerHTML = `
+ <header class="topbar">
+ <div><strong>Caption Playground</strong><span>real SVML · real SVS · exact fonts</span></div>
+ <div class="status" data-status>Compiling…</div>
+ </header>
+ <main><div data-stage></div><aside data-controls></aside></main>`;
+const stage = createStage();
+app.querySelector<HTMLElement>("[data-stage]")!.append(stage.element);
+const controls = app.querySelector<HTMLElement>("[data-controls]")!;
+const status = app.querySelector<HTMLElement>("[data-status]")!;
+
+let snapshot: CaptionPlaygroundSnapshot | undefined;
+let requestInFlight = false;
+const loadedFontCss = new Set<string>();
+
+function cueProjection(display: CaptionDisplaySequence, program: CaptionProgram): TimedCaptionProjection {
+ const atomByWord = new Map(display.atoms.flatMap((atom) => atom.wordIds.map((wordId) => [wordId, atom] as const)));
+ const cues: TimedCaptionProjection["cues"][number][] = [];
+ let cursor = 0;
+ for (const run of program.runs) {
+ const style = program.styles.find((item) => item.id === run.styleId)!;
+ const atoms: CaptionDisplayAtom[] = [];
+ for (const wordId of run.wordIds) {
+ const atom = atomByWord.get(wordId)!;
+ if (atoms.at(-1)?.id !== atom.id) atoms.push(atom);
+ }
+ const groups: CaptionDisplayAtom[][] = [];
+ for (const atom of atoms) {
+ const group = groups.at(-1);
+ const count = group?.reduce((sum, item) => sum + item.wordIds.length, 0) ?? 0;
+ if (group === undefined || (count > 0 && count + atom.wordIds.length > style.planning.cue.maximumWords)) {
+ groups.push([atom]);
+ } else {
+ group.push(atom);
+ }
+ }
+ for (const group of groups) {
+ const words = group.reduce((sum, atom) => sum + atom.wordIds.length, 0);
+ const duration = Math.max(1, words * 0.42);
+ const start = cursor;
+ const end = cursor + duration;
+ let atomCursor = start;
+ const timedAtoms = group.map((atom, index) => {
+ const atomEnd = index === group.length - 1
+ ? end
+ : atomCursor + duration * atom.wordIds.length / words;
+ const value = { atomId: atom.id, startSec: atomCursor, endSec: atomEnd };
+ atomCursor = atomEnd;
+ return value;
+ });
+ cues.push({
+ id: `caption-playground:cue:${cues.length + 1}`,
+ runId: run.id,
+ styleId: run.styleId,
+ segmentId: group[0]!.segmentId,
+ startSec: start,
+ endSec: end,
+ atoms: timedAtoms,
+ fields: [],
+ });
+ cursor = end;
+ }
+ }
+ return { contract: "svml.timed-caption-projection@1", displaySequenceId: display.id, cues };
+}
+
+function showPreview(value: CaptionPlaygroundSnapshot): void {
+ const program = resolveCaptionProgram(value.display, "caption-playground", value.style, []);
+ const projection = cueProjection(value.display, program);
+ const rawDuration = projection.cues.at(-1)?.endSec ?? 1;
+ const frameCount = Math.max(1, Math.ceil(rawDuration * value.preview.fps));
+ const space = sealProgramSpace({
+ contract: "svml.program-space@1",
+ durationSec: frameCount / value.preview.fps,
+ frameRate: { numerator: value.preview.fps, denominator: 1 },
+ });
+ stage.show(renderPreview({
+ id: "caption-playground",
+ canvas: { width: value.preview.width, height: value.preview.height, clearColor: "#121216" },
+ programSpace: space,
+ tracks: [renderFineCaption(projection, program, value.display, space)],
+ }));
+}
+
+function groupFor(name: string): string {
+ if (name.startsWith("cue-") || name === "cue-min-words" || name === "cue-max-words") return "Cue planning & motion";
+ if (["x", "y", "width", "anchor-x", "anchor-y", "stack-order", "align", "direction"].includes(name)) return "Placement & layout";
+ if (["size", "line-height", "letter-spacing", "word-gap", "text-transform"].includes(name)) return "Typography";
+ if (name.startsWith("active-box")) return "Active word box";
+ if (name.startsWith("active-underline") || name === "underline" || name.startsWith("underline-")) return "Underline";
+ if (name.startsWith("active-")) return "Active word paint & response";
+ if (name.startsWith("karaoke")) return "Karaoke";
+ if (name.startsWith("atom-")) return "Atom reveal & motion";
+ if (name.startsWith("loop")) return "Loop motion";
+ if (["background", "border-color", "border-width", "padding", "radius"].includes(name)) return "Cue box";
+ return "Base glyph paint";
+}
+
+function fieldSchema(schema: ValueSchema, name: string): { readonly schema: ValueSchema; readonly optional: boolean } {
+ if (schema.kind !== "object") throw new Error("Fine Caption Recipe schema is not an object");
+ const field = schema.fields[name];
+ if (field === undefined) throw new Error(`No schema for ${name}`);
+ return { schema: field.schema, optional: field.optional === true };
+}
+
+function editor(name: string, value: CanonicalValue | undefined, schema: ValueSchema, optional: boolean): HTMLElement {
+ const row = document.createElement("label");
+ row.className = "property";
+ row.innerHTML = `<span>${name}</span>`;
+ const enabled = document.createElement("input");
+ enabled.type = "checkbox";
+ enabled.className = "property-toggle";
+ enabled.checked = value !== undefined;
+ if (optional) row.prepend(enabled);
+ const control = schema.kind === "string" && schema.enum !== undefined
+ ? document.createElement("select")
+ : document.createElement("input");
+ if (control instanceof HTMLSelectElement && schema.kind === "string") {
+ for (const item of schema.enum ?? []) control.add(new Option(item, item));
+ control.value = typeof value === "string" ? value : schema.enum?.[0] ?? "";
+ } else if (control instanceof HTMLInputElement) {
+ control.type = schema.kind === "number" ? "number" : "text";
+ if (schema.kind === "number") {
+ control.step = schema.integer === true ? "1" : "any";
+ if (schema.minimum !== undefined) control.min = String(schema.minimum);
+ if (schema.maximum !== undefined) control.max = String(schema.maximum);
+ }
+ control.value = value === undefined ? "" : String(value);
+ }
+ control.disabled = optional && value === undefined;
+ row.append(control);
+ const save = async (): Promise<void> => {
+ if (snapshot === undefined || requestInFlight) return;
+ const parsed: CanonicalValue = schema.kind === "number" ? Number(control.value) : control.value;
+ if (schema.kind === "number" && !Number.isFinite(parsed)) return;
+ await patch("/__caption/recipe", {
+ expectedDigest: snapshot.recipe.digest,
+ name,
+ value: parsed,
+ } satisfies RecipePatch);
+ };
+ control.addEventListener("change", () => void save());
+ enabled.addEventListener("change", () => {
+ if (snapshot === undefined) return;
+ control.disabled = !enabled.checked;
+ if (!enabled.checked) {
+ void patch("/__caption/recipe", {
+ expectedDigest: snapshot.recipe.digest,
+ name,
+ remove: true,
+ } satisfies RecipePatch);
+ } else {
+ if (!control.value) {
+ if (schema.kind === "number") control.value = "0";
+ else if (schema.kind === "string" && schema.enum !== undefined) control.value = schema.enum[0] ?? "";
+ else control.value = "none";
+ }
+ void save();
+ }
+ });
+ return row;
+}
+
+function loadFontCss(font: CaptionPlaygroundFont): void {
+ if (loadedFontCss.has(font.id)) return;
+ loadedFontCss.add(font.id);
+ const link = document.createElement("link");
+ link.rel = "stylesheet";
+ link.href = `/__caption/font-css/${font.id}`;
+ document.head.append(link);
+}
+
+function fontPanel(value: CaptionPlaygroundSnapshot): HTMLElement {
+ const section = document.createElement("section");
+ section.className = "font-panel";
+ section.innerHTML = `
+ <div class="section-heading"><div><h2>Exact font</h2><p>${value.font.file} · ${value.font.id}</p></div></div>
+ <div class="font-current"><select data-weight></select><select data-style></select></div>
+ <input class="font-search" type="search" placeholder="Search 109 redistributable font families…" />
+ <div class="font-grid"></div>`;
+ const grid = section.querySelector<HTMLElement>(".font-grid")!;
+ const search = section.querySelector<HTMLInputElement>(".font-search")!;
+ const weight = section.querySelector<HTMLSelectElement>("[data-weight]")!;
+ const style = section.querySelector<HTMLSelectElement>("[data-style]")!;
+ const selected = value.fonts.find((font) => font.id === value.font.family);
+ for (const item of selected?.weights ?? [value.font.weight]) weight.add(new Option(String(item), String(item)));
+ weight.value = String(value.font.weight);
+ for (const item of selected?.styles ?? [value.font.style]) style.add(new Option(item, item));
+ style.value = value.font.style;
+
+ const choose = (family: CaptionPlaygroundFont, selectedWeight = family.previewWeight, selectedStyle = family.previewStyle): void => {
+ void patch("/__caption/font", {
+ expectedDigest: snapshot!.font.digest,
+ family: family.id,
+ weight: selectedWeight,
+ style: selectedStyle,
+ } satisfies FontPatch);
+ };
+ weight.addEventListener("change", () => selected && choose(selected, Number(weight.value), style.value as "normal" | "italic"));
+ style.addEventListener("change", () => selected && choose(selected, Number(weight.value), style.value as "normal" | "italic"));
+
+ const cards = value.fonts.map((font) => {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = `font-card${font.id === value.font.family ? " selected" : ""}`;
+ button.dataset.search = `${font.label} ${font.id} ${font.category}`.toLowerCase();
+ button.innerHTML = `<strong>${font.label}</strong><span>Aa 45% — Caption ✨</span><small>${font.category}</small>`;
+ const sample = button.querySelector<HTMLElement>("span")!;
+ sample.style.fontFamily = `caption-gallery-${font.id}, sans-serif`;
+ sample.style.fontWeight = String(font.previewWeight);
+ sample.style.fontStyle = font.previewStyle;
+ button.addEventListener("click", () => choose(font));
+ grid.append(button);
+ return { font, button };
+ });
+ const observer = new IntersectionObserver((entries) => {
+ for (const entry of entries) {
+ if (!entry.isIntersecting) continue;
+ const found = cards.find((item) => item.button === entry.target);
+ if (found !== undefined) loadFontCss(found.font);
+ observer.unobserve(entry.target);
+ }
+ }, { root: grid, rootMargin: "180px" });
+ cards.forEach(({ button }) => observer.observe(button));
+ search.addEventListener("input", () => {
+ const query = search.value.trim().toLowerCase();
+ cards.forEach(({ button }) => { button.hidden = query.length > 0 && !button.dataset.search!.includes(query); });
+ });
+ return section;
+}
+
+function renderControls(value: CaptionPlaygroundSnapshot): void {
+ controls.replaceChildren(fontPanel(value));
+ const byGroup = new Map<string, string[]>();
+ if (value.recipe.schema.kind !== "object") return;
+ for (const name of Object.keys(value.recipe.schema.fields)) {
+ const group = groupFor(name);
+ const values = byGroup.get(group) ?? [];
+ values.push(name);
+ byGroup.set(group, values);
+ }
+ for (const [group, names] of byGroup) {
+ const details = document.createElement("details");
+ details.open = ["Cue planning & motion", "Placement & layout", "Typography", "Base glyph paint", "Cue box"].includes(group);
+ const summary = document.createElement("summary");
+ summary.textContent = group;
+ details.append(summary);
+ const body = document.createElement("div");
+ body.className = "property-grid";
+ for (const name of names) {
+ const declared = fieldSchema(value.recipe.schema, name);
+ body.append(editor(name, value.recipe.values[name], declared.schema, declared.optional));
+ }
+ details.append(body);
+ controls.append(details);
+ }
+}
+
+function applySnapshot(value: CaptionPlaygroundSnapshot): void {
+ snapshot = value;
+ status.className = "status ok";
+ status.textContent = `Watching ${value.recipe.file} · revision ${value.revision}`;
+ try { showPreview(value); } catch (error) { stage.showError(error instanceof Error ? error.message : String(error)); }
+ renderControls(value);
+}
+
+async function patch(path: string, value: RecipePatch | FontPatch): Promise<void> {
+ requestInFlight = true;
+ status.className = "status";
+ status.textContent = "Writing source…";
+ try {
+ const response = await fetch(path, {
+ method: "PATCH",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(value),
+ });
+ const result = await response.json() as CaptionPlaygroundSnapshot | { readonly error: string; readonly snapshot?: CaptionPlaygroundSnapshot };
+ if (!response.ok) {
+ if ("snapshot" in result && result.snapshot !== undefined) applySnapshot(result.snapshot);
+ throw new Error("error" in result ? result.error : `HTTP ${response.status}`);
+ }
+ applySnapshot(result as CaptionPlaygroundSnapshot);
+ } catch (error) {
+ stage.showError(error instanceof Error ? error.message : String(error));
+ status.className = "status error";
+ status.textContent = "Source update failed";
+ } finally {
+ requestInFlight = false;
+ }
+}
+
+const response = await fetch("/__caption/session");
+const initial = await response.json() as CaptionPlaygroundSnapshot | CaptionPlaygroundFailure;
+if (response.ok && "style" in initial) applySnapshot(initial);
+else {
+ const message = "error" in initial ? initial.error : "Caption compiler failed";
+ stage.showError(message);
+ status.className = "status error";
+ status.textContent = "Compile failed";
+}
+
+type Hot = { on(event: string, listener: (value: unknown) => void): void };
+const hot = (import.meta as ImportMeta & { hot?: Hot }).hot;
+hot?.on("caption:snapshot", (value) => applySnapshot(value as CaptionPlaygroundSnapshot));
+hot?.on("caption:error", (value) => {
+ const failure = value as CaptionPlaygroundFailure;
+ stage.showError(failure.error);
+ status.className = "status error";
+ status.textContent = `Compile failed · revision ${failure.revision}`;
+});
diff --git a/tools/caption-playground/src/preview/render.ts b/tools/caption-playground/src/preview/render.ts
new file mode 100644
index 00000000..c5d6bc66
--- /dev/null
+++ b/tools/caption-playground/src/preview/render.ts
@@ -0,0 +1,37 @@
+import {
+ compileHyperframesDocument,
+ materializeHyperframesHtml,
+ programSpaceFrameCount,
+ sealComposition,
+} from "../svml.js";
+import type { Composition, ProgramSpace, Track } from "../svml.js";
+import { injectRuntimeShim } from "./runtime-shim.js";
+
+export type PreviewOutput = {
+ readonly srcdoc: string;
+ readonly frameCount: number;
+ readonly fps: number;
+ readonly canvas: { readonly width: number; readonly height: number };
+};
+
+export function renderPreview(input: {
+ readonly id: string;
+ readonly canvas: Composition["canvas"];
+ readonly programSpace: ProgramSpace;
+ readonly tracks: readonly Track[];
+}): PreviewOutput {
+ const document = compileHyperframesDocument(sealComposition({
+ contract: "svml.composition@1",
+ id: input.id,
+ canvas: input.canvas,
+ tracks: input.tracks,
+ }), input.programSpace);
+ const html = materializeHyperframesHtml(document, (artifact) =>
+ `/__caption/artifact/${artifact.digest}`);
+ return {
+ srcdoc: injectRuntimeShim(html),
+ frameCount: programSpaceFrameCount(input.programSpace),
+ fps: input.programSpace.frameRate.numerator / input.programSpace.frameRate.denominator,
+ canvas: document.canvas,
+ };
+}
diff --git a/tools/caption-playground/src/preview/runtime-shim.ts b/tools/caption-playground/src/preview/runtime-shim.ts
new file mode 100644
index 00000000..bf30f068
--- /dev/null
+++ b/tools/caption-playground/src/preview/runtime-shim.ts
@@ -0,0 +1,39 @@
+export const RUNTIME_SHIM = String.raw`
+<script>
+(function () {
+ var root = document.querySelector('[data-composition-id]');
+ var fpsAttr = (root && root.getAttribute('data-fps')) || '30';
+ var slash = fpsAttr.indexOf('/');
+ var fps = slash === -1 ? parseFloat(fpsAttr) : parseFloat(fpsAttr.slice(0, slash)) / parseFloat(fpsAttr.slice(slash + 1));
+ if (root) {
+ root.style.width = (root.getAttribute('data-width') || '0') + 'px';
+ root.style.height = (root.getAttribute('data-height') || '0') + 'px';
+ }
+ function seek(seconds) {
+ var clips = document.querySelectorAll('.svml-visual-present');
+ for (var i = 0; i < clips.length; i++) {
+ var clip = clips[i];
+ var start = parseFloat(clip.getAttribute('data-start') || '0') || 0;
+ var duration = parseFloat(clip.getAttribute('data-duration') || '0') || 0;
+ var local = seconds - start;
+ var inside = local >= 0 && local < duration;
+ clip.style.visibility = inside ? 'visible' : 'hidden';
+ var animations = clip.getAnimations({ subtree: true });
+ for (var a = 0; a < animations.length; a++) {
+ try {
+ animations[a].pause();
+ animations[a].currentTime = Math.max(0, Math.min(duration, local)) * 1000;
+ } catch (error) { /* animation will be sought again */ }
+ }
+ }
+ }
+ window.__svmlSeekFrame = function (frame) { seek(frame / fps); };
+ seek(0);
+ window.addEventListener('load', function () { seek(0); });
+})();
+</script>`;
+
+export function injectRuntimeShim(html: string): string {
+ const at = html.lastIndexOf("</body>");
+ return at < 0 ? html + RUNTIME_SHIM : html.slice(0, at) + RUNTIME_SHIM + html.slice(at);
+}
diff --git a/tools/caption-playground/src/server.ts b/tools/caption-playground/src/server.ts
new file mode 100644
index 00000000..12fa746e
--- /dev/null
+++ b/tools/caption-playground/src/server.ts
@@ -0,0 +1,390 @@
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+import { readFile, rename, writeFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { dirname, relative, resolve } from "node:path";
+
+import { fineCaptionRecipeSchema, FINE_CAPTION_FAMILY } from "@narratage/caption-fine";
+import { openFontFamilies } from "@narratage/fonts-open";
+import type { OpenFontFamily, OpenFontStyle } from "@narratage/fonts-open";
+import { loadNodePackageSet } from "@narratage/package-loader-node";
+import type { ArtifactAttachment } from "@narratage/host";
+import type { CanonicalValue, TypedRecord } from "@narratage/protocol";
+import { parseSvs } from "@narratage/svs";
+import { createVideoCompiler } from "@narratage/video-cli";
+import type { Plugin, ViteDevServer } from "vite";
+
+import type {
+ CaptionPlaygroundFailure,
+ CaptionPlaygroundFont,
+ CaptionPlaygroundSnapshot,
+ FontPatch,
+ RecipePatch,
+} from "./shared.js";
+
+// Resolve font packages from the package that owns that catalog. They are its
+// dependencies, not hidden root dependencies of this developer tool.
+const require = createRequire(new URL("../../../packages/fonts-open/src/surface.ts", import.meta.url));
+
+export type CaptionPlaygroundOptions = {
+ readonly source: string;
+ readonly packageLock: string;
+ /** Host directory whose installed packages are named by packageLock. */
+ readonly packageRoot: string;
+ readonly styleExport: string;
+ readonly displayExport: string;
+ readonly recipeFile: string;
+ readonly recipePath: string;
+ readonly fontFile: string;
+ readonly fontId: string;
+ readonly width: number;
+ readonly height: number;
+ readonly fps: number;
+};
+
+type CurrentState = {
+ readonly snapshot: CaptionPlaygroundSnapshot;
+ readonly attachments: ReadonlyMap<string, ArtifactAttachment>;
+};
+
+function sha256(value: string): string {
+ return `sha256:${createHash("sha256").update(value).digest("hex")}`;
+}
+
+function maskedSourceHeader(source: string): string {
+ return source.replace(/^\s*<\?svml\s+using=(['"])[^'"]+\1\s*\?>/u, (header) =>
+ header.replace(/[^\r\n]/gu, " "));
+}
+
+function json(response: import("node:http").ServerResponse, status: number, value: unknown): void {
+ response.statusCode = status;
+ response.setHeader("content-type", "application/json; charset=utf-8");
+ response.end(`${JSON.stringify(value)}\n`);
+}
+
+async function body<T>(request: import("node:http").IncomingMessage): Promise<T> {
+ const chunks: Uint8Array[] = [];
+ for await (const chunk of request) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
+ return JSON.parse(Buffer.concat(chunks).toString("utf8")) as T;
+}
+
+function inlineExport(
+ result: Awaited<ReturnType<ReturnType<typeof createVideoCompiler>["compileFile"]>>,
+ name: string,
+): unknown {
+ const item = result.exports.find((candidate) => candidate.name === name);
+ if (item === undefined) throw new Error(`Source exports no ${name}`);
+ if (item.ref.kind !== "record") throw new Error(`${name} is computed at run time; Caption Playground needs an authored value`);
+ const recordId = item.ref.id;
+ const record: TypedRecord | undefined = result.program.records.find((candidate) => candidate.id === recordId);
+ if (record?.value.kind !== "inline") throw new Error(`${name} is not an authored inline value`);
+ return record.value.value;
+}
+
+function assertRecord(value: unknown, contract: string, subject: string): asserts value is Record<string, unknown> {
+ if (value === null || typeof value !== "object" || Array.isArray(value)
+ || (value as Record<string, unknown>).contract !== contract) {
+ throw new Error(`${subject} is not ${contract}`);
+ }
+}
+
+function fontWeights(family: OpenFontFamily): readonly number[] {
+ if (family.kind === "static" || family.kind === "static-split" || family.kind === "external-split") {
+ return family.weights;
+ }
+ const common = [100, 200, 300, 400, 500, 600, 700, 800, 900]
+ .filter((weight) => weight >= family.minimumWeight && weight <= family.maximumWeight);
+ return common.length > 0 ? common : [family.minimumWeight, family.maximumWeight];
+}
+
+function catalog(): readonly CaptionPlaygroundFont[] {
+ return Object.entries(openFontFamilies).map(([id, family]) => {
+ const weights = fontWeights(family);
+ return {
+ id,
+ label: family.label,
+ category: family.category,
+ intendedUse: family.intendedUse,
+ license: family.license,
+ weights,
+ styles: family.styles,
+ previewWeight: weights.includes(700) ? 700 : weights.includes(400) ? 400 : weights[0]!,
+ previewStyle: family.styles.includes("normal") ? "normal" : family.styles[0]!,
+ };
+ }).sort((left, right) => left.label.localeCompare(right.label));
+}
+
+function quotePattern(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
+}
+
+function fontTag(source: string, id: string): {
+ readonly start: number;
+ readonly end: number;
+ readonly text: string;
+ readonly family: string;
+ readonly weight: number;
+ readonly style: OpenFontStyle;
+} {
+ const tag = new RegExp(`<[A-Za-z][A-Za-z0-9_-]*:Stack\\b[^>]*\\bid=(['"])${quotePattern(id)}\\1[^>]*>`, "u").exec(source);
+ if (tag?.index === undefined) throw new Error(`Source contains no fonts:Stack with id=${id}`);
+ const text = tag[0];
+ const attribute = (name: string): string | undefined =>
+ new RegExp(`\\b${name}=(['"])(.*?)\\1`, "u").exec(text)?.[2];
+ const family = attribute("family");
+ const weight = Number(attribute("weight"));
+ const style = attribute("style") as OpenFontStyle | undefined;
+ if (family === undefined || !Number.isSafeInteger(weight) || (style !== "normal" && style !== "italic")) {
+ throw new Error(`fonts:Stack ${id} must declare family, weight and style`);
+ }
+ return { start: tag.index, end: tag.index + text.length, text, family, weight, style };
+}
+
+function replaceAttribute(tag: string, name: string, value: string): string {
+ const pattern = new RegExp(`(\\b${name}=)(['"])(.*?)\\2`, "u");
+ if (!pattern.test(tag)) throw new Error(`fonts:Stack is missing ${name}`);
+ return tag.replace(pattern, `$1"${value}"`);
+}
+
+function canonicalSource(value: CanonicalValue): string {
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
+ if (typeof value === "string" && /^[^;{}\r\n]+$/u.test(value) && value.trim() === value) return value;
+ if (typeof value === "string") return JSON.stringify(value);
+ return JSON.stringify(value);
+}
+
+async function atomicWrite(path: string, contents: string): Promise<void> {
+ const temporary = `${path}.caption-playground-${process.pid}-${Date.now()}`;
+ await writeFile(temporary, contents, "utf8");
+ await rename(temporary, path);
+}
+
+function defaultFontFile(
+ family: OpenFontFamily & { readonly fileStem: string },
+ weight: number,
+ style: OpenFontStyle,
+): string {
+ const filename = family.kind === "static"
+ ? `${family.fileStem}-${weight}-${style}.woff2`
+ : `${family.fileStem}-${style}.woff2`;
+ return require.resolve(`${family.packageName}/files/${filename}`);
+}
+
+function splitFontFiles(
+ family: OpenFontFamily & { readonly kind: "variable-split" | "static-split" | "external-split" },
+ weight: number,
+ style: OpenFontStyle,
+): readonly { readonly file: string; readonly unicodeRange: string }[] {
+ const css = family.kind === "variable-split"
+ ? family.css
+ : family.kind === "external-split"
+ ? family.css
+ : `${weight}${style === "italic" ? "-italic" : ""}.css`;
+ const cssPath = require.resolve(`${family.packageName}/${css}`);
+ return [...readFileSync(cssPath, "utf8").matchAll(/@font-face\s*\{([\s\S]*?)\}/gu)].map((match) => {
+ const bodyText = match[1]!;
+ const file = /src:\s*url\((?:['"])?\.\/files\/([^)'";]+\.woff2)(?:['"])?\)/u.exec(bodyText)?.[1];
+ const unicodeRange = /unicode-range:\s*([^;]+);/u.exec(bodyText)?.[1]?.replace(/\s+/gu, "");
+ if (file === undefined || unicodeRange === undefined) throw new Error(`${cssPath} has unsupported @font-face CSS`);
+ return { file: require.resolve(`${family.packageName}/files/${file}`), unicodeRange };
+ });
+}
+
+export function captionPlaygroundPlugin(options: CaptionPlaygroundOptions): Plugin {
+ let current: CurrentState | undefined;
+ let failure: CaptionPlaygroundFailure | undefined;
+ let revision = 0;
+ let server: ViteDevServer | undefined;
+ let compileTimer: ReturnType<typeof setTimeout> | undefined;
+ const galleryFiles = new Map<string, string>();
+ const loaded = loadNodePackageSet(options.packageLock, options.packageRoot);
+
+ const compile = async (): Promise<CurrentState> => {
+ const packageSet = await loaded;
+ const compiler = createVideoCompiler({
+ packageContributions: packageSet.contributions,
+ workspaceRoot: dirname(options.source),
+ });
+ const [result, fontText, recipeText] = await Promise.all([
+ compiler.compileFile(options.source),
+ readFile(options.fontFile, "utf8"),
+ readFile(options.recipeFile, "utf8"),
+ ]);
+ const style = inlineExport(result, options.styleExport);
+ const display = inlineExport(result, options.displayExport);
+ assertRecord(style, "svml.caption-style@1", options.styleExport);
+ assertRecord(display, "svml.caption-display-sequence@1", options.displayExport);
+ if ((style.rendering as Record<string, unknown> | undefined)?.family !== FINE_CAPTION_FAMILY) {
+ throw new Error(`${options.styleExport} is not a Fine Caption Style`);
+ }
+ const recipe = parseSvs(options.recipeFile, maskedSourceHeader(recipeText)).recipes
+ .find((candidate) => candidate.value.path === options.recipePath);
+ if (recipe === undefined) throw new Error(`${options.recipeFile} contains no ${options.recipePath}`);
+ const selectedFont = fontTag(fontText, options.fontId);
+ const attachments = new Map(result.attachments.map((item) => [item.artifact.digest, item]));
+ revision += 1;
+ return {
+ snapshot: {
+ revision,
+ style: style as CaptionPlaygroundSnapshot["style"],
+ display: display as CaptionPlaygroundSnapshot["display"],
+ recipe: {
+ file: relative(process.cwd(), options.recipeFile),
+ path: options.recipePath,
+ digest: sha256(recipeText),
+ values: recipe.value.properties,
+ schema: fineCaptionRecipeSchema,
+ },
+ font: {
+ file: relative(process.cwd(), options.fontFile),
+ id: options.fontId,
+ digest: sha256(fontText),
+ family: selectedFont.family,
+ weight: selectedFont.weight,
+ style: selectedFont.style,
+ },
+ preview: { width: options.width, height: options.height, fps: options.fps },
+ fonts: catalog(),
+ artifacts: result.attachments.map((item) => ({ ...item.artifact })),
+ },
+ attachments,
+ };
+ };
+
+ const publish = async (): Promise<void> => {
+ try {
+ current = await compile();
+ failure = undefined;
+ server?.ws.send({ type: "custom", event: "caption:snapshot", data: current.snapshot });
+ } catch (error) {
+ revision += 1;
+ failure = { revision, error: error instanceof Error ? error.message : String(error) };
+ server?.ws.send({ type: "custom", event: "caption:error", data: failure });
+ }
+ };
+
+ const schedule = (): void => {
+ if (compileTimer !== undefined) clearTimeout(compileTimer);
+ compileTimer = setTimeout(() => void publish(), 80);
+ };
+
+ const patchRecipe = async (patch: RecipePatch): Promise<void> => {
+ const source = await readFile(options.recipeFile, "utf8");
+ if (sha256(source) !== patch.expectedDigest) throw Object.assign(new Error("SVS changed outside the browser; reloaded newest source"), { status: 409 });
+ const parsed = parseSvs(options.recipeFile, maskedSourceHeader(source)).recipes
+ .find((item) => item.value.path === options.recipePath);
+ if (parsed === undefined) throw new Error(`Recipe ${options.recipePath} no longer exists`);
+ const property = parsed.properties.find((item) => item.name === patch.name);
+ let next: string;
+ if (patch.remove === true) {
+ if (property === undefined) return;
+ next = `${source.slice(0, property.range.start)}${source.slice(property.range.end)}`;
+ } else {
+ if (patch.value === undefined) throw new Error("Recipe patch has no value");
+ const value = canonicalSource(patch.value);
+ if (property !== undefined) {
+ next = `${source.slice(0, property.valueRange.start)}${value}${source.slice(property.valueRange.end)}`;
+ } else {
+ const close = parsed.range.end - 1;
+ next = `${source.slice(0, close)}\n ${patch.name}: ${value};${source.slice(close)}`;
+ }
+ }
+ await atomicWrite(options.recipeFile, next);
+ };
+
+ const patchFont = async (patch: FontPatch): Promise<void> => {
+ const family = openFontFamilies[patch.family as keyof typeof openFontFamilies] as OpenFontFamily | undefined;
+ if (family === undefined) throw new Error(`Unknown open font ${patch.family}`);
+ if (!fontWeights(family).includes(patch.weight)
+ || !(family.styles as readonly OpenFontStyle[]).includes(patch.style)) {
+ throw new Error(`${patch.family} does not provide ${patch.weight} ${patch.style}`);
+ }
+ const source = await readFile(options.fontFile, "utf8");
+ if (sha256(source) !== patch.expectedDigest) throw Object.assign(new Error("SVML changed outside the browser; reloaded newest source"), { status: 409 });
+ const selected = fontTag(source, options.fontId);
+ let replacement = replaceAttribute(selected.text, "family", patch.family);
+ replacement = replaceAttribute(replacement, "weight", String(patch.weight));
+ replacement = replaceAttribute(replacement, "style", patch.style);
+ await atomicWrite(options.fontFile, `${source.slice(0, selected.start)}${replacement}${source.slice(selected.end)}`);
+ };
+
+ return {
+ name: "narratage-caption-playground",
+ configureServer(value) {
+ server = value;
+ value.watcher.add([options.source, options.recipeFile, options.fontFile]);
+ value.watcher.on("change", (path) => {
+ if (resolve(path) === options.source || resolve(path) === options.recipeFile || resolve(path) === options.fontFile) schedule();
+ });
+ value.middlewares.use(async (request, response, next) => {
+ const url = new URL(request.url ?? "/", "http://caption.local");
+ try {
+ if (request.method === "GET" && url.pathname === "/__caption/session") {
+ if (current === undefined && failure === undefined) await publish();
+ if (current !== undefined) json(response, 200, current.snapshot);
+ else json(response, 500, failure);
+ return;
+ }
+ if (request.method === "PATCH" && url.pathname === "/__caption/recipe") {
+ await patchRecipe(await body<RecipePatch>(request));
+ await publish();
+ json(response, 200, current?.snapshot ?? failure);
+ return;
+ }
+ if (request.method === "PATCH" && url.pathname === "/__caption/font") {
+ await patchFont(await body<FontPatch>(request));
+ await publish();
+ json(response, 200, current?.snapshot ?? failure);
+ return;
+ }
+ const artifact = /^\/__caption\/artifact\/(sha256:[a-f0-9]+)$/u.exec(url.pathname)?.[1];
+ if (request.method === "GET" && artifact !== undefined) {
+ const attachment = current?.attachments.get(artifact);
+ if (attachment === undefined) { response.statusCode = 404; response.end(); return; }
+ response.setHeader("content-type", attachment.artifact.mediaType);
+ response.setHeader("cache-control", "no-store");
+ response.end(Buffer.from(attachment.bytes));
+ return;
+ }
+ const familyId = /^\/__caption\/font-css\/([a-z0-9-]+)$/u.exec(url.pathname)?.[1];
+ if (request.method === "GET" && familyId !== undefined) {
+ const family = openFontFamilies[familyId as keyof typeof openFontFamilies] as OpenFontFamily | undefined;
+ if (family === undefined) { response.statusCode = 404; response.end(); return; }
+ const weights = fontWeights(family);
+ const weight = weights.includes(700) ? 700 : weights.includes(400) ? 400 : weights[0]!;
+ const style = family.styles.includes("normal") ? "normal" : family.styles[0]!;
+ const files = family.kind === "variable-split" || family.kind === "static-split" || family.kind === "external-split"
+ ? splitFontFiles(family, weight, style)
+ : [{ file: defaultFontFile(family, weight, style) }];
+ const css = files.map((item) => {
+ const token = createHash("sha256").update(item.file).digest("hex");
+ galleryFiles.set(token, item.file);
+ const range = "unicodeRange" in item ? `unicode-range:${item.unicodeRange};` : "";
+ return `@font-face{font-family:${JSON.stringify(`caption-gallery-${familyId}`)};src:url('/__caption/font-file/${token}') format('woff2');font-style:${style};font-weight:${weight};${range}font-display:swap;}`;
+ }).join("\n");
+ response.setHeader("content-type", "text/css; charset=utf-8");
+ response.setHeader("cache-control", "public, max-age=3600");
+ response.end(css);
+ return;
+ }
+ const token = /^\/__caption\/font-file\/([a-f0-9]+)$/u.exec(url.pathname)?.[1];
+ if (request.method === "GET" && token !== undefined) {
+ const path = galleryFiles.get(token);
+ if (path === undefined) { response.statusCode = 404; response.end(); return; }
+ response.setHeader("content-type", "font/woff2");
+ response.setHeader("cache-control", "public, max-age=3600");
+ response.end(await readFile(path));
+ return;
+ }
+ next();
+ } catch (error) {
+ const status = typeof error === "object" && error !== null && "status" in error
+ ? Number((error as { status: unknown }).status)
+ : 400;
+ if (status === 409) await publish();
+ json(response, status, { error: error instanceof Error ? error.message : String(error), snapshot: current?.snapshot });
+ }
+ });
+ },
+ };
+}
diff --git a/tools/caption-playground/src/shared.ts b/tools/caption-playground/src/shared.ts
new file mode 100644
index 00000000..512d4e6a
--- /dev/null
+++ b/tools/caption-playground/src/shared.ts
@@ -0,0 +1,67 @@
+import type { CaptionStyleIntent } from "@narratage/caption";
+import type { OpenFontCategory, OpenFontStyle } from "@narratage/fonts-open";
+import type { CaptionDisplaySequence } from "@narratage/narrative";
+import type { CanonicalValue, ValueSchema } from "@narratage/protocol";
+
+export type CaptionPlaygroundFont = {
+ readonly id: string;
+ readonly label: string;
+ readonly category: OpenFontCategory;
+ readonly intendedUse: string;
+ readonly license: string;
+ readonly weights: readonly number[];
+ readonly styles: readonly OpenFontStyle[];
+ readonly previewWeight: number;
+ readonly previewStyle: OpenFontStyle;
+};
+
+export type CaptionPlaygroundSnapshot = {
+ readonly revision: number;
+ readonly style: CaptionStyleIntent;
+ readonly display: CaptionDisplaySequence;
+ readonly recipe: {
+ readonly file: string;
+ readonly path: string;
+ readonly digest: string;
+ readonly values: Readonly<Record<string, CanonicalValue>>;
+ readonly schema: ValueSchema;
+ };
+ readonly font: {
+ readonly file: string;
+ readonly id: string;
+ readonly digest: string;
+ readonly family: string;
+ readonly weight: number;
+ readonly style: OpenFontStyle;
+ };
+ readonly preview: {
+ readonly width: number;
+ readonly height: number;
+ readonly fps: number;
+ };
+ readonly fonts: readonly CaptionPlaygroundFont[];
+ readonly artifacts: readonly {
+ readonly digest: string;
+ readonly mediaType: string;
+ readonly size: number;
+ }[];
+};
+
+export type CaptionPlaygroundFailure = {
+ readonly revision: number;
+ readonly error: string;
+};
+
+export type RecipePatch = {
+ readonly expectedDigest: string;
+ readonly name: string;
+ readonly value?: CanonicalValue;
+ readonly remove?: true;
+};
+
+export type FontPatch = {
+ readonly expectedDigest: string;
+ readonly family: string;
+ readonly weight: number;
+ readonly style: OpenFontStyle;
+};
diff --git a/tools/caption-playground/src/shims/node-crypto.ts b/tools/caption-playground/src/shims/node-crypto.ts
new file mode 100644
index 00000000..bcb11913
--- /dev/null
+++ b/tools/caption-playground/src/shims/node-crypto.ts
@@ -0,0 +1,60 @@
+const K = new Uint32Array([
+ 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
+ 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
+ 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
+ 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
+ 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
+ 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
+ 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
+ 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2,
+]);
+
+const rotr = (value: number, bits: number): number => ((value >>> bits) | (value << (32 - bits))) >>> 0;
+
+export function sha256Hex(bytes: Uint8Array): string {
+ const h = new Uint32Array([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]);
+ const padded = new Uint8Array(((((bytes.length + 8) / 64) | 0) + 1) * 64);
+ padded.set(bytes); padded[bytes.length] = 0x80;
+ const view = new DataView(padded.buffer); const bits = bytes.length * 8;
+ view.setUint32(padded.length - 8, Math.floor(bits / 0x1_0000_0000), false);
+ view.setUint32(padded.length - 4, bits >>> 0, false);
+ const w = new Uint32Array(64);
+ for (let offset = 0; offset < padded.length; offset += 64) {
+ for (let index = 0; index < 16; index += 1) w[index] = view.getUint32(offset + index * 4, false);
+ for (let index = 16; index < 64; index += 1) {
+ const x = w[index - 15]!; const y = w[index - 2]!;
+ const s0 = (rotr(x, 7) ^ rotr(x, 18) ^ (x >>> 3)) >>> 0;
+ const s1 = (rotr(y, 17) ^ rotr(y, 19) ^ (y >>> 10)) >>> 0;
+ w[index] = (w[index - 16]! + s0 + w[index - 7]! + s1) >>> 0;
+ }
+ let a=h[0]!,b=h[1]!,c=h[2]!,d=h[3]!,e=h[4]!,f=h[5]!,g=h[6]!,s=h[7]!;
+ for (let index = 0; index < 64; index += 1) {
+ const s1 = (rotr(e,6)^rotr(e,11)^rotr(e,25))>>>0;
+ const t1 = (s+s1+((e&f)^(~e&g))+K[index]!+w[index]!)>>>0;
+ const s0 = (rotr(a,2)^rotr(a,13)^rotr(a,22))>>>0;
+ const t2 = (s0+((a&b)^(a&c)^(b&c)))>>>0;
+ s=g;g=f;f=e;e=(d+t1)>>>0;d=c;c=b;b=a;a=(t1+t2)>>>0;
+ }
+ h[0]=(h[0]!+a)>>>0;h[1]=(h[1]!+b)>>>0;h[2]=(h[2]!+c)>>>0;h[3]=(h[3]!+d)>>>0;
+ h[4]=(h[4]!+e)>>>0;h[5]=(h[5]!+f)>>>0;h[6]=(h[6]!+g)>>>0;h[7]=(h[7]!+s)>>>0;
+ }
+ return [...h].map((value) => value.toString(16).padStart(8,"0")).join("");
+}
+
+const encoder = new TextEncoder();
+class Sha256Hash {
+ #chunks: Uint8Array[] = [];
+ update(chunk: string | Uint8Array): this { this.#chunks.push(typeof chunk === "string" ? encoder.encode(chunk) : chunk); return this; }
+ digest(encoding?: string): string {
+ if (encoding !== undefined && encoding !== "hex") throw new Error(`crypto shim supports hex, not ${encoding}`);
+ const size = this.#chunks.reduce((sum, chunk) => sum + chunk.length, 0);
+ const joined = new Uint8Array(size); let cursor = 0;
+ for (const chunk of this.#chunks) { joined.set(chunk, cursor); cursor += chunk.length; }
+ return sha256Hex(joined);
+ }
+}
+export function createHash(algorithm: string): Sha256Hash {
+ if (algorithm !== "sha256") throw new Error(`crypto shim supports sha256, not ${algorithm}`);
+ return new Sha256Hash();
+}
+export default { createHash };
diff --git a/tools/caption-playground/src/style.css b/tools/caption-playground/src/style.css
new file mode 100644
index 00000000..bb693630
--- /dev/null
+++ b/tools/caption-playground/src/style.css
@@ -0,0 +1,47 @@
+:root {
+ color-scheme: dark; --bg:#09090b; --panel:#131316; --panel2:#18181c; --line:#2a2a30;
+ --text:#f4f4f5; --muted:#96969f; --accent:#ee7b62; --danger:#ff6868;
+ font: 13px/1.45 Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+}
+* { box-sizing:border-box; }
+html, body, #app { margin:0; height:100%; overflow:hidden; background:var(--bg); color:var(--text); }
+#app { display:flex; flex-direction:column; }
+.topbar { height:54px; flex:none; display:flex; align-items:center; justify-content:space-between; padding:0 18px; border-bottom:1px solid var(--line); background:#101013; }
+.topbar strong { font-size:15px; letter-spacing:-.01em; }
+.topbar span { margin-left:10px; color:var(--muted); }
+.status { color:var(--muted); font-size:12px; }
+.status.ok { color:#75d69b; } .status.error { color:var(--danger); }
+main { flex:1; min-height:0; display:grid; grid-template-columns:minmax(0,1fr) 430px; }
+[data-stage] { min-width:0; min-height:0; }
+.stage { height:100%; display:flex; flex-direction:column; background:radial-gradient(circle at 50% 42%, #222228 0, #0c0c0f 60%); }
+.stage-viewport { flex:1; min-height:0; overflow:hidden; display:flex; align-items:center; justify-content:center; padding:16px; }
+.stage-scaler { position:relative; transform-origin:top left; }
+.stage iframe { display:block; transform-origin:top left; border:0; background:#000; box-shadow:0 24px 80px #0009, 0 0 0 1px #ffffff1c; }
+.stage-bar { height:48px; flex:none; display:flex; gap:12px; align-items:center; padding:0 14px; background:#111114; border-top:1px solid var(--line); color:var(--muted); font-variant-numeric:tabular-nums; }
+.stage-bar button { width:32px; height:28px; color:var(--text); border:1px solid var(--line); background:#1c1c21; border-radius:6px; cursor:pointer; }
+.stage-bar input { flex:1; accent-color:var(--accent); }
+.stage-error { position:absolute; left:16px; right:446px; bottom:64px; z-index:3; max-height:180px; overflow:auto; margin:0; padding:12px; color:#ffb0b0; background:#310f13e8; border:1px solid #8d3039; border-radius:8px; white-space:pre-wrap; }
+.stage-error:empty { display:none; }
+aside { min-height:0; overflow:auto; border-left:1px solid var(--line); background:var(--panel); padding-bottom:28px; }
+aside section, aside details { border-bottom:1px solid var(--line); }
+.section-heading { padding:17px 18px 10px; }
+.section-heading h2 { margin:0; font-size:14px; }
+.section-heading p { margin:3px 0 0; color:var(--muted); font-size:11px; }
+.font-current { display:grid; grid-template-columns:1fr 1fr; gap:8px; padding:0 18px 10px; }
+input, select { min-width:0; width:100%; padding:7px 9px; color:var(--text); background:#0f0f12; border:1px solid #35353c; border-radius:6px; outline:none; }
+input:focus, select:focus { border-color:var(--accent); }
+.font-search { width:calc(100% - 36px); margin:0 18px 10px; }
+.font-grid { height:250px; overflow:auto; padding:0 12px 12px; display:grid; grid-template-columns:1fr 1fr; gap:7px; }
+.font-card { min-width:0; text-align:left; display:flex; flex-direction:column; gap:2px; padding:9px; color:var(--text); background:#101013; border:1px solid var(--line); border-radius:8px; cursor:pointer; }
+.font-card:hover { border-color:#5a5a64; } .font-card.selected { border-color:var(--accent); box-shadow:inset 0 0 0 1px var(--accent); }
+.font-card strong { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:11px; color:var(--muted); }
+.font-card span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:17px; }
+.font-card small { color:#686872; }
+details summary { position:sticky; top:0; z-index:1; padding:13px 18px; cursor:pointer; background:var(--panel2); font-weight:650; }
+.property-grid { padding:8px 18px 15px; display:grid; gap:7px; }
+.property { min-height:34px; display:grid; grid-template-columns:16px minmax(130px,1fr) minmax(120px,1fr); align-items:center; gap:8px; }
+.property > span { color:#c7c7ce; font-family:ui-monospace, SFMono-Regular, Menlo, monospace; font-size:11px; }
+.property:not(:has(.property-toggle)) { grid-template-columns:minmax(154px,1fr) minmax(120px,1fr); padding-left:24px; }
+.property-toggle { width:14px; height:14px; padding:0; accent-color:var(--accent); }
+.property input:disabled, .property select:disabled { opacity:.35; }
+@media (max-width:900px) { main { grid-template-columns:1fr 360px; } .stage-error { right:376px; } }
diff --git a/tools/caption-playground/src/svml.ts b/tools/caption-playground/src/svml.ts
new file mode 100644
index 00000000..635d6d13
--- /dev/null
+++ b/tools/caption-playground/src/svml.ts
@@ -0,0 +1,12 @@
+export { resolveCaptionProgram } from "@narratage/caption";
+export type { CaptionStyleIntent, TimedCaptionProjection } from "@narratage/caption";
+export { renderFineCaption } from "@narratage/caption-fine";
+export type { CaptionDisplaySequence } from "@narratage/narrative";
+export { sealComposition } from "@narratage/composition";
+export type { Composition, Track } from "@narratage/composition";
+export { sealProgramSpace, programSpaceFrameCount } from "@narratage/program-space";
+export type { ProgramSpace } from "@narratage/program-space";
+export {
+ compileHyperframesDocument,
+ materializeHyperframesHtml,
+} from "../../../packages/hyperframes/src/document.js";
diff --git a/tools/caption-playground/src/ui/stage.ts b/tools/caption-playground/src/ui/stage.ts
new file mode 100644
index 00000000..dede647e
--- /dev/null
+++ b/tools/caption-playground/src/ui/stage.ts
@@ -0,0 +1,95 @@
+import type { PreviewOutput } from "../preview/render.js";
+
+type SeekWindow = Window & { __svmlSeekFrame?: (frame: number) => void };
+
+export type Stage = {
+ readonly element: HTMLElement;
+ show(output: PreviewOutput): void;
+ showError(message: string): void;
+};
+
+export function createStage(): Stage {
+ const element = document.createElement("section");
+ element.className = "stage";
+ element.innerHTML = `
+ <div class="stage-viewport"><div class="stage-scaler"><iframe title="Caption preview"></iframe></div></div>
+ <div class="stage-bar">
+ <button type="button" data-play aria-label="Play">▶</button>
+ <input type="range" min="0" max="0" step="1" value="0" data-scrub />
+ <span data-frame>0 / 0</span><span data-size></span>
+ </div>
+ <pre class="stage-error" data-error></pre>`;
+ const viewport = element.querySelector<HTMLElement>(".stage-viewport")!;
+ const scaler = element.querySelector<HTMLElement>(".stage-scaler")!;
+ const iframe = element.querySelector<HTMLIFrameElement>("iframe")!;
+ const play = element.querySelector<HTMLButtonElement>("[data-play]")!;
+ const scrub = element.querySelector<HTMLInputElement>("[data-scrub]")!;
+ const readout = element.querySelector<HTMLElement>("[data-frame]")!;
+ const size = element.querySelector<HTMLElement>("[data-size]")!;
+ const error = element.querySelector<HTMLElement>("[data-error]")!;
+ let canvas = { width: 1080, height: 1920 };
+ let frames = 1;
+ let fps = 30;
+ let ready = false;
+ let playing = false;
+ let raf = 0;
+
+ const fit = (): void => {
+ const room = viewport.getBoundingClientRect();
+ const scale = Math.min((room.width - 32) / canvas.width, (room.height - 32) / canvas.height, 1);
+ const valid = Number.isFinite(scale) && scale > 0 ? scale : 1;
+ scaler.style.width = `${canvas.width * valid}px`;
+ scaler.style.height = `${canvas.height * valid}px`;
+ iframe.style.width = `${canvas.width}px`;
+ iframe.style.height = `${canvas.height}px`;
+ iframe.style.transform = `scale(${valid})`;
+ };
+ const seek = (frame: number): void => {
+ readout.textContent = `${frame} / ${frames - 1}`;
+ if (ready) (iframe.contentWindow as SeekWindow | null)?.__svmlSeekFrame?.(frame);
+ };
+ const stop = (): void => {
+ playing = false;
+ play.textContent = "▶";
+ if (raf !== 0) cancelAnimationFrame(raf);
+ raf = 0;
+ };
+ play.addEventListener("click", () => {
+ if (playing) { stop(); return; }
+ playing = true;
+ play.textContent = "❚❚";
+ const start = performance.now();
+ const from = Number(scrub.value);
+ const step = (now: number): void => {
+ const at = from + Math.round((now - start) / 1000 * fps);
+ if (!playing || at >= frames) { scrub.value = String(frames - 1); seek(frames - 1); stop(); return; }
+ scrub.value = String(at);
+ seek(at);
+ raf = requestAnimationFrame(step);
+ };
+ raf = requestAnimationFrame(step);
+ });
+ scrub.addEventListener("input", () => { stop(); seek(Number(scrub.value)); });
+ iframe.addEventListener("load", () => { ready = true; seek(Number(scrub.value)); });
+ new ResizeObserver(fit).observe(viewport);
+
+ return {
+ element,
+ show(output) {
+ error.textContent = "";
+ canvas = output.canvas;
+ frames = Math.max(1, output.frameCount);
+ fps = output.fps;
+ const at = Math.min(Number(scrub.value), frames - 1);
+ scrub.max = String(frames - 1);
+ scrub.value = String(at);
+ readout.textContent = `${at} / ${frames - 1}`;
+ size.textContent = `${canvas.width}×${canvas.height}`;
+ ready = false;
+ iframe.srcdoc = output.srcdoc;
+ stop();
+ fit();
+ },
+ showError(message) { stop(); error.textContent = message; },
+ };
+}
diff --git a/tools/caption-playground/start.ts b/tools/caption-playground/start.ts
new file mode 100644
index 00000000..e9f976fa
--- /dev/null
+++ b/tools/caption-playground/start.ts
@@ -0,0 +1,106 @@
+import { readdirSync, readFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { createServer } from "vite";
+
+import { captionPlaygroundPlugin } from "./src/server.js";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(here, "../..");
+
+function usage(message?: string): never {
+ if (message !== undefined) process.stderr.write(`${message}\n\n`);
+ process.stderr.write(`Usage:
+ pnpm caption:playground -- \\
+ --source <main.svml> --package-lock <svml.packages.lock> \\
+ --style <export> --display <export> --recipe <file.svs#recipe.path> \\
+ --font <file.svml#font-stack-id> --canvas <width>x<height> --fps <number> \
+ [--package-root <directory>] [--port <number>]
+`);
+ process.exit(1);
+}
+
+function argumentsByName(argv: readonly string[]): ReadonlyMap<string, string> {
+ const result = new Map<string, string>();
+ for (let index = 0; index < argv.length; index += 2) {
+ const flag = argv[index];
+ const value = argv[index + 1];
+ if (flag === undefined || !flag.startsWith("--") || value === undefined || value.startsWith("--")) {
+ usage(`Malformed argument near ${flag ?? "end of command"}`);
+ }
+ result.set(flag.slice(2), value);
+ }
+ return result;
+}
+
+function required(values: ReadonlyMap<string, string>, name: string): string {
+ const value = values.get(name);
+ if (value === undefined || !value.trim()) usage(`Missing --${name}`);
+ return value;
+}
+
+function workspaceAliases(): Array<{ find: string; replacement: string }> {
+ const packages = join(repoRoot, "packages");
+ return readdirSync(packages, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
+ const manifestPath = join(packages, entry.name, "package.json");
+ let manifest: { name?: unknown; exports?: unknown };
+ try { manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as typeof manifest; } catch { return []; }
+ const target = (manifest.exports as Record<string, unknown> | undefined)?.["."];
+ return typeof manifest.name === "string" && typeof target === "string"
+ ? [{ find: manifest.name, replacement: join(packages, entry.name, target) }]
+ : [];
+ });
+}
+
+const rawArguments = process.argv.slice(2);
+const values = argumentsByName(rawArguments[0] === "--" ? rawArguments.slice(1) : rawArguments);
+const recipeArgument = required(values, "recipe");
+const hash = recipeArgument.lastIndexOf("#");
+if (hash <= 0 || hash === recipeArgument.length - 1) usage("--recipe must be <file.svs#recipe.path>");
+const fontArgument = required(values, "font");
+const fontHash = fontArgument.lastIndexOf("#");
+if (fontHash <= 0 || fontHash === fontArgument.length - 1) usage("--font must be <file.svml#font-stack-id>");
+const canvas = /^(\d+)x(\d+)$/u.exec(required(values, "canvas"));
+if (canvas === null) usage("--canvas must be <width>x<height>");
+const fps = Number(required(values, "fps"));
+const port = Number(values.get("port") ?? "5178");
+if (!Number.isSafeInteger(fps) || fps <= 0 || !Number.isSafeInteger(port) || port <= 0) usage("--fps and --port must be positive integers");
+
+const source = resolve(required(values, "source"));
+const recipeFile = resolve(recipeArgument.slice(0, hash));
+const fontFile = resolve(fontArgument.slice(0, fontHash));
+const packageRoot = resolve(values.get("package-root") ?? repoRoot);
+const server = await createServer({
+ configFile: false,
+ root: here,
+ resolve: {
+ alias: [
+ { find: "node:crypto", replacement: join(here, "src/shims/node-crypto.ts") },
+ ...workspaceAliases(),
+ ],
+ },
+ server: {
+ port,
+ fs: {
+ allow: [...new Set([repoRoot, packageRoot, dirname(source), dirname(recipeFile), dirname(fontFile)])],
+ },
+ },
+ plugins: [captionPlaygroundPlugin({
+ source,
+ packageLock: resolve(required(values, "package-lock")),
+ packageRoot,
+ styleExport: required(values, "style"),
+ displayExport: required(values, "display"),
+ recipeFile,
+ recipePath: recipeArgument.slice(hash + 1),
+ fontFile,
+ fontId: fontArgument.slice(fontHash + 1),
+ width: Number(canvas[1]),
+ height: Number(canvas[2]),
+ fps,
+ })],
+});
+
+await server.listen();
+server.printUrls();
diff --git a/tools/package-boundaries.test.mjs b/tools/package-boundaries.test.mjs
index d56a58b0..135116c9 100644
--- a/tools/package-boundaries.test.mjs
+++ b/tools/package-boundaries.test.mjs
@@ -107,7 +107,7 @@ test("official production packages have no dependency cycle", async () => {
for (const name of graph.keys()) visit(name, []);
});
-test("Playground cannot add semantics or metadata to production packages", async () => {
+test("Caption Playground cannot add semantics or metadata to production packages", async () => {
let productionSource = "";
for (const entry of await readdir(packageRoot, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
@@ -140,22 +140,30 @@ test("Playground cannot add semantics or metadata to production packages", async
}
});
-test("Playground has no hard-coded component registry", async () => {
- const root = new URL("../tools/playground/src/", import.meta.url);
- const allowedWaists = new Set([
+test("Caption Playground is a selected source editor, not a component registry", async () => {
+ const root = new URL("../tools/caption-playground/src/", import.meta.url);
+ const allowedPackages = new Set([
+ "@narratage/caption",
+ "@narratage/caption-fine",
"@narratage/composition",
- "@narratage/core",
+ "@narratage/fonts-open",
+ "@narratage/host",
+ "@narratage/narrative",
+ "@narratage/package-loader-node",
"@narratage/program-space",
"@narratage/protocol",
+ "@narratage/svs",
+ "@narratage/video-cli",
]);
for (const file of await sourceFiles(root)) {
const source = await readFile(file, "utf8");
for (const match of source.matchAll(/["'](@narratage\/[a-z0-9-]+)["']/gu)) {
- assert.ok(allowedWaists.has(match[1]),
- `${file.pathname} names ${match[1]}; components must be selected or discovered, never registered here`);
+ assert.ok(allowedPackages.has(match[1]), `${file.pathname} unexpectedly names ${match[1]}`);
}
assert.ok(!/\b(?:Story|Scenario|Recipe)Registry\b/u.test(source),
- `${file.pathname} introduces a parallel Playground registry`);
+ `${file.pathname} introduces a parallel Caption Playground registry`);
+ assert.ok(!/import\.meta\.glob|discoverPreviewProducers/u.test(source),
+ `${file.pathname} scans the workspace instead of editing the explicitly selected Caption source`);
}
});
diff --git a/tools/playground-sha256.test.mjs b/tools/playground-sha256.test.mjs
deleted file mode 100644
index 365a4697..00000000
--- a/tools/playground-sha256.test.mjs
+++ /dev/null
@@ -1,40 +0,0 @@
-import assert from "node:assert/strict";
-import { createHash } from "node:crypto";
-import test from "node:test";
-
-import { createHash as shimCreateHash } from "./playground/src/shims/node-crypto.ts";
-
-/**
- * The playground runs the compiler's own `digestOf` in a browser, where
- * `node:crypto` does not exist. Content addressing is only meaningful if the
- * substitute agrees with the real thing on every byte, so pin them together.
- */
-const cases = [
- "",
- "a",
- "abc",
- "svml.composition@1",
- // 55, 56 and 64 bytes straddle the SHA-256 padding boundary, where a wrong
- // implementation still passes short inputs.
- "x".repeat(55),
- "x".repeat(56),
- "x".repeat(64),
- "x".repeat(1000),
- "字幕轨道与画布",
- JSON.stringify({ contract: "svml.program-space@1", durationSec: 4 }),
-];
-
-test("the browser sha256 shim agrees with node:crypto", () => {
- for (const value of cases) {
- assert.equal(
- shimCreateHash("sha256").update(value).digest("hex"),
- createHash("sha256").update(value, "utf8").digest("hex"),
- `sha256 diverged for a ${value.length}-character input`,
- );
- }
-});
-
-test("the shim refuses algorithms and encodings it does not implement", () => {
- assert.throws(() => shimCreateHash("sha512"), /sha256/u);
- assert.throws(() => shimCreateHash("sha256").update("a").digest("base64"), /hex/u);
-});
diff --git a/tools/playground-source-bytes.test.mjs b/tools/playground-source-bytes.test.mjs
deleted file mode 100644
index e9bae2bb..00000000
--- a/tools/playground-source-bytes.test.mjs
+++ /dev/null
@@ -1,44 +0,0 @@
-import assert from "node:assert/strict";
-import { execFileSync } from "node:child_process";
-import { existsSync, readFileSync } from "node:fs";
-import test from "node:test";
-import { fileURLToPath } from "node:url";
-
-/**
- * Source files must stay text.
- *
- * A raw control byte in a string literal works at runtime and reads as an
- * ordinary separator in an editor, so it survives review — but git then treats
- * the file as binary and stops producing diffs or merging it at all. Writing
- * the escape sequence instead costs nothing and keeps the file reviewable.
- */
-
-const root = fileURLToPath(new URL("..", import.meta.url));
-
-function tracked() {
- return execFileSync(
- "git",
- ["ls-files", "-c", "-o", "--exclude-standard", "tools/playground", "test"],
- { cwd: root, encoding: "utf8" },
- ).trim().split("\n").filter((path) => /\.(?:ts|mjs|js|html|css|json)$/u.test(path));
-}
-
-test("no playground source carries a raw control byte", () => {
- const offenders = [];
- for (const path of tracked()) {
- const url = new URL(path, new URL("..", import.meta.url));
- // `git ls-files -c` includes a tracked deletion until it is staged. A
- // deleted source cannot contain a control byte and must not make this
- // source-content check depend on Git's index timing.
- if (!existsSync(url)) continue;
- const bytes = readFileSync(url);
- for (const [index, byte] of bytes.entries()) {
- // Tab, newline and carriage return are the only control bytes text needs.
- if (byte < 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d) {
- offenders.push(`${path}: byte 0x${byte.toString(16).padStart(2, "0")} at offset ${index}`);
- break;
- }
- }
- }
- assert.deepEqual(offenders, [], `write the escape sequence instead:\n${offenders.join("\n")}`);
-});
diff --git a/tools/playground/README.md b/tools/playground/README.md
deleted file mode 100644
index 66f902ce..00000000
--- a/tools/playground/README.md
+++ /dev/null
@@ -1,84 +0,0 @@
-# Component playground
-
-Look at a visual component without running a Build.
-
-```bash
-pnpm playground
-```
-
-Pick a producer, fill in its inputs, and it renders on a canvas whose size,
-frame rate, duration and background you choose.
-
-[The guide page](../../docs/guide/playground.md) covers using it. This file
-covers how it works.
-
-## Where everything comes from
-
-There is no registry here and no per-component code. Each answer is read at run
-time:
-
-| Question | Answered by |
-|---|---|
-| Which modules can be previewed | manifests declaring a Producer whose output type is `@narratage/composition.VisualTrack` |
-| What each needs | that Producer's `inputs`, each a `TypeRef` |
-| What shape each input has | the declaring module's `TypeDeclaration.schema` |
-| How to run it | the module's `component.producers[].handler` |
-
-A module that gains a visual Producer appears here on its own; one that loses it
-disappears. Neither requires editing anything in this directory.
-
-Nothing here validates. `validateStoredValue` and the modules' own `seal*` and
-`assert*` functions are the judge, since they are what a real Build runs. A
-rejected value shows the compiler's own message beside the form and leaves the
-last good frame up.
-
-## Two things a Build supplies that the document does not
-
-`compileHyperframesDocument` emits a page that is self-contained but not
-self-sufficient — a real render supplies a producer for the rest. The shim in
-`src/preview/runtime-shim.ts` stands in for it:
-
-- **Size.** The composition root carries `data-width` / `data-height` as data,
- not as layout. Unsized it computes to zero height, and `overflow: hidden`
- clips every Present away.
-- **Timeline.** Every clip is marked visible and every animation starts at load.
- The shim gates each Present to its span and seeks its animations with
- `getAnimations()` plus an explicit `currentTime` — the same technique the
- production renderer uses.
-
-## Dependency boundary
-
-Two rules are non-negotiable:
-
-1. The dependency is one-way. The Playground may consume public production
- contracts; Protocol, Core and every other package contain no Playground
- defaults, form hints, fixtures, facets or preview helpers.
-2. The Playground owns no component, Recipe, Story, Scenario or example
- registry. It discovers what a selected environment actually exposes and may
- read ordinary SVML/SVS/Run sources; it does not maintain a second data format
- describing the system.
-
-To become discoverable, a module only declares its real Producer, ports and
-structural input schemas. The Playground creates blank form state and its own
-canvas, duration, frame rate and background locally. Those values are UI session
-state, not SVML semantics.
-
-The generic form uses only schema kinds, enums and numeric bounds. A richer
-editor or fixture system must be implemented inside this tool; it must not make
-a production package change merely to improve a preview.
-
-The current workspace scan is discovery, not registration: it enumerates the
-selected workspace at startup and derives eligibility from an ordinary
-`VisualTrack` output. There is no checked-in list of package names. In a
-project-oriented Playground, the startup command and the imported source/lock
-closure will select the environment instead; no central catalog is introduced.
-
-## Known divergences from a real render
-
-- Fonts lower to a plain CSS `font-family` string. The production
- `FontArtifactRef` path with hashed `@font-face` families is not exercised.
-- Content-addressed media must currently be entered as an existing digest; the
- generic form does not infer that a string should be a file picker.
-- Audio tracks are not played.
-- A `ProgramSpace` input is filled from the canvas controls rather than offered
- in a form.
diff --git a/tools/playground/index.html b/tools/playground/index.html
deleted file mode 100644
index cb1d3ef4..00000000
--- a/tools/playground/index.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<!doctype html>
-<html lang="en">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width,initial-scale=1" />
- <link rel="icon" href="data:," />
- <title>SVML Component Playground</title>
- <style>
- :root {
- color-scheme: dark;
- --bg: #09090b;
- --panel: #131316;
- --line: #26262b;
- --text: #e4e4e7;
- --muted: #8b8b94;
- /* The documentation theme's own accent, so the tool reads as part of it. */
- --accent: #ee7b62;
- --accent-hover: #f59b88;
- --danger: #ff4d4f;
- }
- * { box-sizing: border-box; }
- html, body { margin: 0; height: 100%; }
- body {
- background: var(--bg);
- color: var(--text);
- font: 13px/1.5 ui-sans-serif, -apple-system, "Segoe UI", sans-serif;
- display: flex;
- flex-direction: column;
- }
- #app { flex: 1; min-height: 0; display: flex; }
- </style>
- </head>
- <body>
- <div id="app"></div>
- <script type="module" src="/src/main.ts"></script>
- </body>
-</html>
diff --git a/tools/playground/src/discovery/producers.ts b/tools/playground/src/discovery/producers.ts
deleted file mode 100644
index fcd3c1b1..00000000
--- a/tools/playground/src/discovery/producers.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-import type {
- CanonicalValue,
- ModuleManifest,
- ProducerDeclaration,
- TypeRef,
- ValueSchema,
-} from "../svml.js";
-
-/**
- * What the compiler already says about itself.
- *
- * Nothing here lists components. A module is previewable because it declares a
- * Producer that outputs a VisualTrack — that is what "puts pixels on the frame"
- * means, and the manifests already say it. A module added tomorrow appears here
- * without this file changing, and one that stops emitting a VisualTrack
- * disappears without anybody remembering to remove it.
- */
-
-const VISUAL_TRACK = { module: "@narratage/composition", name: "VisualTrack" } as const;
-
-type BoundProducer = {
- readonly producer: { readonly name: string };
- readonly handler: (invocation: {
- readonly inputs: Readonly<Record<string, { readonly value: unknown } | undefined>>;
- }) => { readonly outputs: Readonly<Record<string, { readonly value: unknown }>> };
-};
-
-type ComponentModule = {
- readonly name: string;
- readonly producers: readonly BoundProducer[];
-};
-
-export type PreviewInput = {
- readonly name: string;
- readonly type: TypeRef;
- readonly schema: ValueSchema | undefined;
-};
-
-export type PreviewProducer = {
- readonly id: string;
- readonly label: string;
- readonly moduleName: string;
- readonly inputs: readonly PreviewInput[];
- readonly outputName: string;
- readonly invoke: (values: Readonly<Record<string, CanonicalValue>>) => unknown;
-};
-
-function typeKey(ref: TypeRef): string {
- return `${ref.module.name}::${ref.name}`;
-}
-
-function outputsVisualTrack(producer: ProducerDeclaration): boolean {
- return producer.outputs.some((port) =>
- port.type.name === VISUAL_TRACK.name && port.type.module.name === VISUAL_TRACK.module);
-}
-
-/**
- * Names a producer by its module, and by itself only when its module offers a
- * choice.
- *
- * A producer name alone is often meaningless out of context — `project-visual`
- * says nothing — while a module name alone is ambiguous where one module emits
- * more than one Track.
- */
-function label(moduleName: string, producer: ProducerDeclaration, siblings: number): string {
- const short = moduleName.replace(/^@narratage\//u, "");
- if (siblings < 2) return short;
- const rest = producer.name
- .replace(/^(?:render|project|compile)-/u, "")
- .replace(new RegExp(`^${short}-`, "u"), "");
- return `${short} ${rest}`;
-}
-
-/**
- * Loads every workspace module and keeps the ones a browser can run.
- *
- * A module whose manifest or component cannot be imported here — because it
- * reaches for a filesystem, a process or a network — is simply not previewable.
- * That is a fact about the module, not a list to maintain, so it is discovered
- * rather than declared.
- */
-export type ModuleLoader = () => Promise<unknown>;
-
-export type PreviewSources = {
- readonly manifests: Readonly<Record<string, ModuleLoader>>;
- readonly components: Readonly<Record<string, ModuleLoader>>;
-};
-
-export async function discoverPreviewProducers(
- sources: PreviewSources,
-): Promise<readonly PreviewProducer[]> {
- // Keyed by module name: an entry file re-exports its own manifest, so the
- // same module arrives more than once and must be counted once.
- const byName = new Map<string, ModuleManifest>();
- for (const load of Object.values(sources.manifests)) {
- try {
- const module = await load() as Record<string, unknown>;
- for (const value of Object.values(module)) {
- if (isManifest(value) && !byName.has(value.name)) byName.set(value.name, value);
- }
- } catch {
- /* Not loadable here, therefore not previewable here. */
- }
- }
- const manifests = [...byName.values()];
-
- // Input types belong to whichever module declares them, which is often not
- // the module that produces the Track — a ProgramSpace comes from elsewhere.
- const types = new Map<string, { schema: ValueSchema }>();
- for (const manifest of manifests) {
- for (const declaration of manifest.types) {
- types.set(`${manifest.name}::${declaration.name}`, declaration);
- }
- }
-
- const components = new Map<string, ComponentModule>();
- for (const load of Object.values(sources.components)) {
- try {
- const module = await load() as Record<string, unknown>;
- for (const value of Object.values(module)) {
- if (isComponent(value) && !components.has(value.name)) components.set(value.name, value);
- }
- } catch {
- /* Same: a component that cannot load here cannot be previewed here. */
- }
- }
-
- const found: PreviewProducer[] = [];
- for (const manifest of manifests) {
- const visual = manifest.producers.filter(outputsVisualTrack);
- for (const declaration of visual) {
- const bound = components.get(manifest.name)
- ?.producers.find((entry) => entry.producer.name === declaration.name);
- // A declared Producer with no bound handler is declared but not runnable.
- if (bound === undefined) continue;
- const outputName = declaration.outputs.find((port) =>
- port.type.name === VISUAL_TRACK.name)!.name;
-
- found.push({
- id: `${manifest.name}#${declaration.name}`,
- label: label(manifest.name, declaration, visual.length),
- moduleName: manifest.name,
- outputName,
- inputs: declaration.inputs.map((port) => {
- const declared = types.get(typeKey(port.type));
- return {
- name: port.name,
- type: port.type,
- schema: declared?.schema,
- };
- }),
- invoke: (values) => bound.handler({
- inputs: Object.fromEntries(Object.entries(values)
- .map(([name, value]) => [name, { value: { kind: "inline", value } }])),
- }).outputs[outputName]?.value,
- });
- }
- }
- return found.sort((left, right) => left.label.localeCompare(right.label));
-}
-
-function isManifest(value: unknown): value is ModuleManifest {
- return value !== null && typeof value === "object"
- && (value as { format?: unknown }).format === "svml.module@1";
-}
-
-function isComponent(value: unknown): value is ComponentModule {
- return value !== null && typeof value === "object"
- && typeof (value as { name?: unknown }).name === "string"
- && Array.isArray((value as { producers?: unknown }).producers);
-}
diff --git a/tools/playground/src/discovery/workspace.ts b/tools/playground/src/discovery/workspace.ts
deleted file mode 100644
index 5a0fb1e9..00000000
--- a/tools/playground/src/discovery/workspace.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/// <reference types="vite/client" />
-
-import { discoverPreviewProducers } from "./producers.js";
-import type { PreviewProducer } from "./producers.js";
-
-/**
- * Every workspace module, handed to the discovery as loaders.
- *
- * The glob is the only part of discovery that is Vite's rather than the
- * compiler's, so it is the only part kept here — which also leaves the
- * discovery itself runnable, and testable, outside a browser.
- */
-export async function workspacePreviewProducers(): Promise<readonly PreviewProducer[]> {
- return await discoverPreviewProducers({
- // Manifests have a dedicated, browser-safe entry. Globbing package indexes
- // would also bundle Node Drivers and Providers merely to discover metadata.
- manifests: import.meta.glob("../../../../packages/*/src/manifest.ts"),
- components: import.meta.glob("../../../../packages/*/src/component.ts"),
- });
-}
diff --git a/tools/playground/src/main.ts b/tools/playground/src/main.ts
deleted file mode 100644
index 629e3dee..00000000
--- a/tools/playground/src/main.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { mountShell } from "./ui/shell.js";
-
-void mountShell(document.querySelector<HTMLElement>("#app")!);
diff --git a/tools/playground/src/preview/render.ts b/tools/playground/src/preview/render.ts
deleted file mode 100644
index 96e13279..00000000
--- a/tools/playground/src/preview/render.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import {
- compileHyperframesDocument,
- materializeHyperframesHtml,
- programSpaceFrameCount,
- sealComposition,
-} from "../svml.js";
-import type { Composition, ProgramSpace, Track } from "../svml.js";
-import { injectRuntimeShim } from "./runtime-shim.js";
-
-/** A grey card standing in for an Artifact the playground has not been given. */
-const MISSING_MEDIA = `data:image/svg+xml;utf8,${encodeURIComponent(
- `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">`
- + `<rect width="320" height="180" fill="#26262b"/>`
- + `<text x="160" y="96" fill="#8b8b94" font-family="sans-serif" font-size="15"`
- + ` text-anchor="middle">media not set</text></svg>`,
-)}`;
-
-export type PreviewInput = {
- readonly id: string;
- readonly canvas: Composition["canvas"];
- readonly programSpace: ProgramSpace;
- readonly tracks: readonly Track[];
-};
-
-export type PreviewOutput = {
- readonly srcdoc: string;
- readonly frameCount: number;
- readonly fps: number;
- /** The document's own frame size — what the stage must not let reflow. */
- readonly canvas: { readonly width: number; readonly height: number };
- readonly warnings: readonly string[];
-};
-
-/**
- * Composition to something an iframe can show.
- *
- * The seal and compile steps are the compiler's own, so anything the real Build
- * would reject is rejected here too — with the same message. Callers surface the
- * throw next to the form rather than clearing the stage.
- */
-export function renderPreview(input: PreviewInput): PreviewOutput {
- const composition = sealComposition({
- contract: "svml.composition@1",
- id: input.id,
- canvas: input.canvas,
- tracks: input.tracks,
- });
- const document = compileHyperframesDocument(composition, input.programSpace);
-
- const warnings: string[] = [];
- const html = materializeHyperframesHtml(document, (artifact) => {
- // Artifact fulfillment belongs to a normal author/run graph. The low-level
- // component inspector owns no parallel registry of files or fixtures.
- warnings.push(`No media registered for ${artifact.digest.slice(0, 19)}…`);
- return MISSING_MEDIA;
- });
-
- const { numerator, denominator } = input.programSpace.frameRate;
- return {
- srcdoc: injectRuntimeShim(html),
- frameCount: programSpaceFrameCount(input.programSpace),
- fps: numerator / denominator,
- canvas: document.canvas,
- warnings,
- };
-}
diff --git a/tools/playground/src/preview/runtime-shim.ts b/tools/playground/src/preview/runtime-shim.ts
deleted file mode 100644
index 31d4e87f..00000000
--- a/tools/playground/src/preview/runtime-shim.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * The timeline the compiled document does not carry.
- *
- * `compileHyperframesDocument` emits every Present as an always-visible clip and
- * gives its animations a duration but no delay — a real render supplies the
- * runtime that gates and seeks them. This is that runtime, reduced to what a
- * preview needs, and it uses the same technique the production renderer does:
- * `getAnimations()` plus an explicit `currentTime`.
- *
- * Injected into the materialized HTML. `compileHyperframesDocument` is never
- * touched, so what renders here stays the document the compiler produced.
- */
-export const RUNTIME_SHIM = String.raw`
-<script>
-(function () {
- var root = document.querySelector('[data-composition-id]');
- var fpsAttr = (root && root.getAttribute('data-fps')) || '30';
- var slash = fpsAttr.indexOf('/');
- var fps = slash === -1
- ? parseFloat(fpsAttr)
- : parseFloat(fpsAttr.slice(0, slash)) / parseFloat(fpsAttr.slice(slash + 1));
- var frameCount = parseInt((root && root.getAttribute('data-svml-frame-count')) || '0', 10);
-
- // The compiled stylesheet gives the composition root position and overflow but
- // no size — a real render sizes it from data-width/data-height. Left alone it
- // computes to zero height, and since every Present is absolutely positioned
- // inside it with overflow:hidden, the whole frame clips away to nothing.
- if (root) {
- root.style.width = (root.getAttribute('data-width') || '0') + 'px';
- root.style.height = (root.getAttribute('data-height') || '0') + 'px';
- }
-
- function clips() {
- return document.querySelectorAll('.svml-visual-present');
- }
-
- /** Seek to an absolute program time in seconds. */
- function seek(seconds) {
- var list = clips();
- for (var i = 0; i < list.length; i++) {
- var clip = list[i];
- var start = parseFloat(clip.getAttribute('data-start') || '0') || 0;
- var duration = parseFloat(clip.getAttribute('data-duration') || '0') || 0;
- var local = seconds - start;
- var inside = local >= 0 && local < duration;
- clip.style.visibility = inside ? 'visible' : 'hidden';
-
- var animations = clip.getAnimations({ subtree: true });
- for (var a = 0; a < animations.length; a++) {
- var animation = animations[a];
- try {
- animation.pause();
- // Clamp rather than skip: a Present's held first and last keyframes are
- // what the renderer shows at its edges, so the boundary frames match.
- var at = local < 0 ? 0 : (local > duration ? duration : local);
- animation.currentTime = at * 1000;
- } catch (error) {
- /* An animation that is not yet ready re-seeks on the next call. */
- }
- }
-
- var media = clip.querySelectorAll('video, audio');
- for (var m = 0; m < media.length; m++) {
- var element = media[m];
- element.pause();
- if (inside) {
- var offset = parseFloat(element.getAttribute('data-media-start') || '0') || 0;
- try { element.currentTime = offset + local; } catch (error) { /* not seekable yet */ }
- }
- }
- }
- }
-
- window.__svmlSeek = seek;
- window.__svmlFrameCount = frameCount;
- window.__svmlFps = fps;
- window.__svmlSeekFrame = function (frame) { seek(frame / fps); };
-
- // Paint the first frame correctly rather than whatever the CSS happened to be
- // mid-animation when the document loaded.
- seek(0);
- window.addEventListener('load', function () { seek(0); });
-})();
-</script>
-`;
-
-/** Places the shim last in the body so it observes the finished element tree. */
-export function injectRuntimeShim(html: string): string {
- const marker = "</body>";
- const at = html.lastIndexOf(marker);
- if (at === -1) return html + RUNTIME_SHIM;
- return html.slice(0, at) + RUNTIME_SHIM + html.slice(at);
-}
diff --git a/tools/playground/src/shims/node-crypto.ts b/tools/playground/src/shims/node-crypto.ts
deleted file mode 100644
index 4fd6daf5..00000000
--- a/tools/playground/src/shims/node-crypto.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-/**
- * The one `node:crypto` surface the compiler packages touch, for the browser.
- *
- * `digestOf` (packages/protocol/src/canonical.ts) runs `createHash("sha256")`
- * synchronously at module load — several manifests compute their digest as a
- * top-level constant — so Web Crypto's async `subtle.digest` cannot stand in.
- * This is a plain synchronous SHA-256, aliased over `node:crypto` by
- * tools/playground/vite.config.ts.
- *
- * Verified byte-for-byte against Node's implementation by
- * tools/playground-sha256.test.mjs.
- */
-
-const K = new Uint32Array([
- 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
- 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
- 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
- 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
- 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
- 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
- 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
- 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
-]);
-
-function rotr(value: number, bits: number): number {
- return ((value >>> bits) | (value << (32 - bits))) >>> 0;
-}
-
-export function sha256Hex(bytes: Uint8Array): string {
- const h = new Uint32Array([
- 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
- ]);
- const padded = new Uint8Array(((((bytes.length + 8) / 64) | 0) + 1) * 64);
- padded.set(bytes);
- padded[bytes.length] = 0x80;
- const view = new DataView(padded.buffer);
- const bits = bytes.length * 8;
- view.setUint32(padded.length - 8, Math.floor(bits / 0x1_0000_0000), false);
- view.setUint32(padded.length - 4, bits >>> 0, false);
-
- const w = new Uint32Array(64);
- for (let offset = 0; offset < padded.length; offset += 64) {
- for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(offset + i * 4, false);
- for (let i = 16; i < 64; i += 1) {
- const x = w[i - 15]!;
- const y = w[i - 2]!;
- const s0 = (rotr(x, 7) ^ rotr(x, 18) ^ (x >>> 3)) >>> 0;
- const s1 = (rotr(y, 17) ^ rotr(y, 19) ^ (y >>> 10)) >>> 0;
- w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) >>> 0;
- }
- let a = h[0]!, b = h[1]!, c = h[2]!, d = h[3]!;
- let e = h[4]!, f = h[5]!, g = h[6]!, s = h[7]!;
- for (let i = 0; i < 64; i += 1) {
- const S1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0;
- const ch = ((e & f) ^ (~e & g)) >>> 0;
- const t1 = (s + S1 + ch + K[i]! + w[i]!) >>> 0;
- const S0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0;
- const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0;
- const t2 = (S0 + maj) >>> 0;
- s = g; g = f; f = e; e = (d + t1) >>> 0;
- d = c; c = b; b = a; a = (t1 + t2) >>> 0;
- }
- h[0] = (h[0]! + a) >>> 0; h[1] = (h[1]! + b) >>> 0;
- h[2] = (h[2]! + c) >>> 0; h[3] = (h[3]! + d) >>> 0;
- h[4] = (h[4]! + e) >>> 0; h[5] = (h[5]! + f) >>> 0;
- h[6] = (h[6]! + g) >>> 0; h[7] = (h[7]! + s) >>> 0;
- }
-
- let hex = "";
- for (let i = 0; i < 8; i += 1) hex += h[i]!.toString(16).padStart(8, "0");
- return hex;
-}
-
-const encoder = new TextEncoder();
-
-class Sha256Hash {
- #chunks: Uint8Array[] = [];
-
- update(chunk: string | Uint8Array): this {
- this.#chunks.push(typeof chunk === "string" ? encoder.encode(chunk) : chunk);
- return this;
- }
-
- digest(encoding?: string): string {
- if (encoding !== undefined && encoding !== "hex") {
- throw new Error(`node:crypto shim supports hex digests, not ${encoding}.`);
- }
- let length = 0;
- for (const chunk of this.#chunks) length += chunk.length;
- const joined = new Uint8Array(length);
- let at = 0;
- for (const chunk of this.#chunks) { joined.set(chunk, at); at += chunk.length; }
- return sha256Hex(joined);
- }
-}
-
-export function createHash(algorithm: string): Sha256Hash {
- if (algorithm !== "sha256") {
- throw new Error(`node:crypto shim supports sha256, not ${algorithm}.`);
- }
- return new Sha256Hash();
-}
-
-export default { createHash };
diff --git a/tools/playground/src/svml.ts b/tools/playground/src/svml.ts
deleted file mode 100644
index d864c9d3..00000000
--- a/tools/playground/src/svml.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * The browser-safe surface of the compiler, in one place.
- *
- * HyperFrames keeps its browser-safe compiler at the package root and its
- * Node-only project staging behind `@narratage/hyperframes/project`. The
- * document module is imported directly here so that boundary stays visible.
- *
- * Only the render path is named here. Components are not: they are discovered
- * from the manifests at run time, and a list of them in this file would be the
- * very coupling the discovery exists to avoid.
- */
-
-export {
- assertHyperframesDocument,
- compileHyperframesDocument,
- materializeHyperframesHtml,
-} from "../../../packages/hyperframes/src/document.js";
-export type { HyperframesDocument } from "../../../packages/hyperframes/src/types.js";
-
-export { sealComposition } from "@narratage/composition";
-export type { Composition, Track, VisualTrack } from "@narratage/composition";
-
-export {
- programSpaceFrameCount,
- sealProgramSpace,
-} from "@narratage/program-space";
-export type { ProgramSpace } from "@narratage/program-space";
-
-export { validateStoredValue } from "@narratage/core";
-
-export type {
- CanonicalValue,
- ModuleManifest,
- ProducerDeclaration,
- TypeRef,
- ValueSchema,
-} from "@narratage/protocol";
diff --git a/tools/playground/src/ui/form.ts b/tools/playground/src/ui/form.ts
deleted file mode 100644
index dc5ccb13..00000000
--- a/tools/playground/src/ui/form.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-import type { CanonicalValue, ValueSchema } from "../svml.js";
-
-export const FORM_CSS = `
-.form { display: flex; flex-direction: column; gap: 2px; }
-.form-row { display: grid; grid-template-columns: 108px 1fr; gap: 8px; align-items: center; padding: 3px 0; }
-.form-row > label { color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; }
-.form-control { display: flex; gap: 6px; align-items: center; min-width: 0; }
-.form-control input[type=text], .form-control input[type=number], .form-control select {
- flex: 1; min-width: 0; background: #1c1c21; color: var(--text);
- border: 1px solid var(--line); border-radius: 5px; padding: 4px 7px; font: inherit; font-size: 12px;
-}
-.form-group { border: 1px solid var(--line); border-radius: 6px; padding: 8px 10px; margin: 5px 0; }
-.form-group > legend { color: var(--accent); font-size: 11px; padding: 0 5px; }
-.form-item { border-top: 1px dashed var(--line); padding-top: 7px; margin-top: 7px; }
-.form-item:first-of-type { border-top: 0; padding-top: 0; margin-top: 0; }
-.form-actions { display: flex; gap: 6px; margin-top: 7px; }
-.form-actions button {
- border: 1px solid var(--line); border-radius: 5px; background: #1c1c21;
- color: var(--text); cursor: pointer; padding: 3px 9px; font-size: 12px;
-}
-.form-actions button:hover:not(:disabled) { border-color: #3a3a42; }
-.form-actions button:disabled { opacity: .4; cursor: default; }
-.form-fixed { color: var(--muted); font-size: 12px; font-family: ui-monospace, monospace; }
-`;
-
-type Emit = () => void;
-
-function row(name: string, control: HTMLElement): HTMLElement {
- const element = document.createElement("div");
- element.className = "form-row";
- const caption = document.createElement("label");
- caption.textContent = name;
- caption.title = name;
- const holder = document.createElement("div");
- holder.className = "form-control";
- holder.append(control);
- element.append(caption, holder);
- return element;
-}
-
-/**
- * Builds controls from a ValueSchema.
- *
- * Only structural contract facts are consumed: `enum` becomes a list and
- * numeric bounds become input limits. Presentation conveniences belong to the
- * Playground and must never be added to a production schema to steer this UI.
- *
- * Nothing here validates. `validateStoredValue` and the packages' own assert
- * functions are the judge — they are what a real Build runs.
- */
-export function buildForm(
- schema: ValueSchema,
- value: CanonicalValue,
- emit: Emit,
-): HTMLElement {
- const container = document.createElement("div");
- container.className = "form";
- if (schema.kind !== "object") {
- container.append(row("value", scalarControl(schema, value, (next) => {
- // A non-object input is replaced wholesale by its caller.
- (emit as Emit & { replace?: (v: CanonicalValue) => void }).replace?.(next);
- emit();
- })));
- return container;
- }
-
- const bag = value as Record<string, CanonicalValue>;
- for (const [name, field] of Object.entries(schema.fields)) {
- const current = bag[name];
-
- if (field.schema.kind === "literal") {
- // A literal is the contract tag: shown so the shape is legible, never
- // offered, because changing it would only ever be wrong.
- const fixed = document.createElement("span");
- fixed.className = "form-fixed";
- fixed.textContent = String(field.schema.value);
- container.append(row(name, fixed));
- continue;
- }
- if (field.schema.kind === "array") {
- container.append(arrayGroup(name, field.schema, bag, emit));
- continue;
- }
- if (field.schema.kind === "object") {
- const group = document.createElement("fieldset");
- group.className = "form-group";
- const legend = document.createElement("legend");
- legend.textContent = name;
- if (bag[name] === undefined) bag[name] = {};
- group.append(legend, buildForm(field.schema, bag[name], emit));
- container.append(group);
- continue;
- }
- container.append(row(name, scalarControl(field.schema, current, (next) => {
- bag[name] = next;
- emit();
- })));
- }
- return container;
-}
-
-function scalarControl(
- schema: ValueSchema,
- current: CanonicalValue | undefined,
- onChange: (next: CanonicalValue) => void,
-): HTMLElement {
- if (schema.kind === "boolean") {
- const box = document.createElement("input");
- box.type = "checkbox";
- box.checked = current === true;
- box.addEventListener("input", () => onChange(box.checked));
- return box;
- }
-
- if (schema.kind === "number") {
- const input = document.createElement("input");
- input.type = "number";
- if (schema.minimum !== undefined) input.min = String(schema.minimum);
- if (schema.maximum !== undefined) input.max = String(schema.maximum);
- input.step = schema.integer === true ? "1" : "any";
- input.value = String(typeof current === "number" ? current : schema.minimum ?? 0);
- input.addEventListener("input", () => {
- if (input.value !== "") onChange(Number(input.value));
- });
- return input;
- }
-
- if (schema.kind === "string") {
- if (schema.enum !== undefined) {
- const select = document.createElement("select");
- for (const option of schema.enum) {
- const item = document.createElement("option");
- item.value = option;
- item.textContent = option;
- select.append(item);
- }
- select.value = typeof current === "string" ? current : (schema.enum[0] ?? "");
- select.addEventListener("input", () => onChange(select.value));
- return select;
- }
- const input = document.createElement("input");
- input.type = "text";
- input.value = typeof current === "string" ? current : "";
- input.addEventListener("input", () => onChange(input.value));
- return input;
- }
-
- const unsupported = document.createElement("span");
- unsupported.className = "form-fixed";
- unsupported.textContent = `(${schema.kind})`;
- return unsupported;
-}
-
-export function blankValue(schema: ValueSchema): CanonicalValue {
- if (schema.kind === "object") {
- return Object.fromEntries(Object.entries(schema.fields)
- .filter(([, field]) => field.optional !== true)
- .map(([name, field]) => [name, blankValue(field.schema)]));
- }
- if (schema.kind === "literal") return schema.value;
- if (schema.kind === "array") return [];
- if (schema.kind === "number") return schema.minimum ?? 0;
- if (schema.kind === "string") return schema.enum?.[0] ?? "";
- if (schema.kind === "boolean") return false;
- if (schema.kind === "oneOf") return blankValue(schema.variants[0] ?? { kind: "null" });
- return null;
-}
-
-function arrayGroup(
- name: string,
- schema: ValueSchema & { kind: "array" },
- bag: Record<string, CanonicalValue>,
- emit: Emit,
-): HTMLElement {
- const group = document.createElement("fieldset");
- group.className = "form-group";
- const legend = document.createElement("legend");
- legend.textContent = name;
- group.append(legend);
-
- const entries = Array.isArray(bag[name]) ? [...(bag[name] as CanonicalValue[])] : [];
- bag[name] = entries;
- const minItems = schema.minItems ?? 0;
-
- const rebuild = (): void => {
- // Adding or removing changes the control tree, so this subtree is rebuilt.
- // Scalar edits never come through here.
- group.replaceWith(arrayGroup(name, schema, bag, emit));
- emit();
- };
-
- entries.forEach((entry, index) => {
- const item = document.createElement("div");
- item.className = "form-item";
- item.append(buildForm(schema.items, entry, emit));
- const actions = document.createElement("div");
- actions.className = "form-actions";
- const remove = document.createElement("button");
- remove.type = "button";
- remove.textContent = "Remove";
- remove.disabled = entries.length <= minItems;
- remove.addEventListener("click", () => { entries.splice(index, 1); rebuild(); });
- actions.append(remove);
- item.append(actions);
- group.append(item);
- });
-
- const actions = document.createElement("div");
- actions.className = "form-actions";
- const add = document.createElement("button");
- add.type = "button";
- add.textContent = "Add";
- add.addEventListener("click", () => { entries.push(blankValue(schema.items)); rebuild(); });
- actions.append(add);
- group.append(actions);
- return group;
-}
diff --git a/tools/playground/src/ui/shell.ts b/tools/playground/src/ui/shell.ts
deleted file mode 100644
index e956874e..00000000
--- a/tools/playground/src/ui/shell.ts
+++ /dev/null
@@ -1,223 +0,0 @@
-import type { PreviewProducer } from "../discovery/producers.js";
-import { workspacePreviewProducers } from "../discovery/workspace.js";
-import { renderPreview } from "../preview/render.js";
-import { sealProgramSpace } from "../svml.js";
-import type { CanonicalValue, ProgramSpace, Track } from "../svml.js";
-import { FORM_CSS, blankValue, buildForm } from "./form.js";
-import { createStage } from "./stage.js";
-
-const CSS = `
-.rail {
- width: 356px; flex: 0 0 356px; border-right: 1px solid var(--line);
- background: var(--panel); display: flex; flex-direction: column; min-height: 0;
-}
-.rail-head { padding: 12px 14px; border-bottom: 1px solid var(--line); }
-.rail-head h1 { margin: 0 0 10px; font-size: 13px; font-weight: 600; letter-spacing: .02em; }
-.rail-body { flex: 1; min-height: 0; overflow-y: auto; padding: 10px 14px 24px; }
-.rail select, .rail input[type=number] {
- background: #1c1c21; color: var(--text); border: 1px solid var(--line);
- border-radius: 5px; padding: 4px 7px; font: inherit; font-size: 12px; min-width: 0; width: 100%;
-}
-.rail-canvas { display: grid; grid-template-columns: auto 1fr auto 1fr; gap: 6px; align-items: center; margin-top: 9px; }
-.rail-canvas span { color: var(--muted); font-size: 11px; }
-.section { color: var(--accent); font-size: 11px; margin: 15px 0 4px; }
-.section:first-child { margin-top: 0; }
-.module { color: var(--muted); font-size: 11px; font-family: ui-monospace, monospace; margin-top: 4px; }
-.hint { color: var(--muted); font-size: 12px; margin-top: 7px; }
-.rail-canvas input[type=color] {
- width: 100%; height: 24px; padding: 0; border: 1px solid var(--line);
- background: none; border-radius: 5px;
-}
-${FORM_CSS}
-`;
-
-// This is local UI session state. It is deliberately not exported by, read
-// from, or written back into any compiler, protocol or video-domain package.
-const INITIAL_PREVIEW_ENVIRONMENT = {
- canvas: { width: 1080, height: 1920, clearColor: "#09090b" },
- program: { durationSec: 4, frameRate: { numerator: 30, denominator: 1 } },
-} as const;
-
-export async function mountShell(root: HTMLElement): Promise<void> {
- const style = document.createElement("style");
- style.textContent = CSS;
- document.head.append(style);
-
- const rail = document.createElement("div");
- rail.className = "rail";
- rail.innerHTML = `
- <div class="rail-head">
- <h1>Component playground</h1>
- <select data-producer></select>
- <div class="module" data-module></div>
- <div class="rail-canvas">
- <span>W</span><input type="number" data-width min="16" step="2" />
- <span>H</span><input type="number" data-height min="16" step="2" />
- <span>fps</span><input type="number" data-fps min="1" step="1" />
- <span>sec</span><input type="number" data-duration min="0.1" step="0.1" />
- <span>bg</span><input type="color" data-background />
- </div>
- </div>
- <div class="rail-body"></div>
- `;
-
- const picker = rail.querySelector<HTMLSelectElement>("[data-producer]")!;
- const moduleLine = rail.querySelector<HTMLElement>("[data-module]")!;
- const body = rail.querySelector<HTMLElement>(".rail-body")!;
- const widthInput = rail.querySelector<HTMLInputElement>("[data-width]")!;
- const heightInput = rail.querySelector<HTMLInputElement>("[data-height]")!;
- const fpsInput = rail.querySelector<HTMLInputElement>("[data-fps]")!;
- const durationInput = rail.querySelector<HTMLInputElement>("[data-duration]")!;
- const backgroundInput = rail.querySelector<HTMLInputElement>("[data-background]")!;
-
- const stage = createStage();
- root.append(rail, stage.element);
-
- const producers = await workspacePreviewProducers();
- if (producers.length === 0) {
- stage.showError("No module declares a Producer that outputs a VisualTrack.");
- return;
- }
- for (const producer of producers) {
- const option = document.createElement("option");
- option.value = producer.id;
- option.textContent = producer.label;
- picker.append(option);
- }
-
- // The shell is a consumer of production contracts. These editable values
- // belong only to this preview session and carry no language-level default.
- const canvas: { width: number; height: number; clearColor: string } = {
- ...INITIAL_PREVIEW_ENVIRONMENT.canvas,
- };
- const space: { fps: number; durationSec: number } = {
- fps: INITIAL_PREVIEW_ENVIRONMENT.program.frameRate.numerator
- / INITIAL_PREVIEW_ENVIRONMENT.program.frameRate.denominator,
- durationSec: INITIAL_PREVIEW_ENVIRONMENT.program.durationSec,
- };
-
- /**
- * Values a ProgramSpace input must agree with.
- *
- * Producers take a ProgramSpace as an ordinary input, but the canvas controls
- * and the scrubber describe the same thing, so the shell owns it and the form
- * does not offer a second copy to disagree with.
- */
- function programSpace(): ProgramSpace {
- return sealProgramSpace({
- contract: "svml.program-space@1",
- durationSec: space.durationSec,
- frameRate: { numerator: space.fps, denominator: 1 },
- });
- }
-
- const drafts = new Map<string, Record<string, CanonicalValue>>();
- let active: PreviewProducer = producers[0]!;
- picker.value = active.id;
-
- function draft(producer: PreviewProducer): Record<string, CanonicalValue> {
- const existing = drafts.get(producer.id);
- if (existing !== undefined) return existing;
- const created: Record<string, CanonicalValue> = {};
- for (const input of producer.inputs) {
- created[input.name] = input.schema === undefined ? null : blankValue(input.schema);
- }
- drafts.set(producer.id, created);
- return created;
- }
-
- function isProgramSpace(name: string, producer: PreviewProducer): boolean {
- return producer.inputs.some((input) =>
- input.name === name && input.type.name === "ProgramSpace");
- }
-
- let queued = 0;
- function schedule(): void {
- if (queued !== 0) clearTimeout(queued);
- queued = window.setTimeout(render, 120);
- }
-
- function render(): void {
- const values = { ...draft(active) };
- try {
- const resolved = programSpace();
- for (const input of active.inputs) {
- if (isProgramSpace(input.name, active)) values[input.name] = resolved as never;
- }
- const track = active.invoke(values) as Track;
- stage.show(renderPreview({
- id: active.moduleName,
- canvas,
- programSpace: resolved,
- tracks: [track],
- }));
- } catch (error) {
- // The compiler's own message. The last good frame stays up.
- stage.showError(error instanceof Error ? error.message : String(error));
- }
- }
-
- function section(title: string): HTMLElement {
- const element = document.createElement("div");
- element.className = "section";
- element.textContent = title;
- return element;
- }
-
- function renderRail(): void {
- const values = draft(active);
- moduleLine.textContent = active.moduleName;
- body.replaceChildren();
-
- for (const input of active.inputs) {
- // The shell owns the frame domain; offering it again would be a second
- // answer free to disagree with the canvas controls.
- if (isProgramSpace(input.name, active)) continue;
- body.append(section(input.name));
- if (input.schema === undefined) {
- const missing = document.createElement("div");
- missing.className = "hint";
- missing.textContent = `${input.type.module.name} declares no schema for ${input.type.name}.`;
- body.append(missing);
- continue;
- }
- if (values[input.name] === null || values[input.name] === undefined) {
- const empty = document.createElement("div");
- empty.className = "hint";
- empty.textContent = `${input.type.module.name} requires an explicit ${input.type.name} value.`;
- body.append(empty);
- }
- body.append(buildForm(input.schema, values[input.name] ?? {}, schedule));
- }
- }
-
- picker.addEventListener("input", () => {
- active = producers.find((entry) => entry.id === picker.value) ?? active;
- renderRail();
- render();
- });
-
- widthInput.value = String(canvas.width);
- heightInput.value = String(canvas.height);
- fpsInput.value = String(space.fps);
- durationInput.value = String(space.durationSec);
- backgroundInput.value = canvas.clearColor;
- backgroundInput.addEventListener("input", () => {
- canvas.clearColor = backgroundInput.value;
- schedule();
- });
- for (const [input, apply] of [
- [widthInput, (n: number) => { canvas.width = n; }],
- [heightInput, (n: number) => { canvas.height = n; }],
- [fpsInput, (n: number) => { space.fps = n; }],
- [durationInput, (n: number) => { space.durationSec = n; }],
- ] as const) {
- input.addEventListener("input", () => {
- const value = Number(input.value);
- if (Number.isFinite(value) && value > 0) { apply(value); schedule(); }
- });
- }
-
- renderRail();
- render();
-}
diff --git a/tools/playground/src/ui/stage.ts b/tools/playground/src/ui/stage.ts
deleted file mode 100644
index a9d87c7f..00000000
--- a/tools/playground/src/ui/stage.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-import type { PreviewOutput } from "../preview/render.js";
-
-type SeekWindow = Window & {
- __svmlSeekFrame?: (frame: number) => void;
-};
-
-const CSS = `
-.stage { flex: 1; min-width: 0; display: flex; flex-direction: column; background: #0d0d10; }
-.stage-viewport {
- flex: 1; min-height: 0; position: relative; overflow: hidden;
- display: flex; align-items: center; justify-content: center; padding: 20px;
-}
-.stage-scaler { position: relative; transform-origin: center center; }
-.stage-scaler iframe {
- display: block; border: 0; background: #000;
- box-shadow: 0 0 0 1px #26262b, 0 18px 50px rgba(0, 0, 0, .55);
-}
-.stage-bar {
- display: flex; align-items: center; gap: 12px;
- padding: 10px 14px; border-top: 1px solid var(--line); background: var(--panel);
-}
-.stage-bar button {
- width: 30px; height: 26px; border: 1px solid var(--line); border-radius: 5px;
- background: #1c1c21; color: var(--text); cursor: pointer; font-size: 12px;
-}
-.stage-bar button:hover { border-color: #3a3a42; }
-.stage-bar input[type=range] { flex: 1; accent-color: var(--accent); }
-.stage-frame { font-variant-numeric: tabular-nums; color: var(--muted); min-width: 92px; }
-.stage-size { color: var(--muted); font-variant-numeric: tabular-nums; }
-.stage-note { padding: 9px 14px; font-size: 12px; border-top: 1px solid var(--line); white-space: pre-wrap; }
-.stage-note.error { background: #2a1416; color: var(--danger); font-family: ui-monospace, monospace; }
-.stage-note.warn { background: #241f12; color: #e3b341; }
-.stage-note:empty { display: none; }
-`;
-
-export type Stage = {
- readonly element: HTMLElement;
- show(output: PreviewOutput): void;
- showError(message: string): void;
-};
-
-export function createStage(): Stage {
- const style = document.createElement("style");
- style.textContent = CSS;
- document.head.append(style);
-
- const element = document.createElement("div");
- element.className = "stage";
- element.innerHTML = `
- <div class="stage-viewport"><div class="stage-scaler"><iframe title="preview"></iframe></div></div>
- <div class="stage-bar">
- <button type="button" data-play>▶</button>
- <input type="range" min="0" max="0" step="1" value="0" data-scrub />
- <span class="stage-frame" data-frame>0 / 0</span>
- <span class="stage-size" data-size></span>
- </div>
- <div class="stage-note error" data-error></div>
- <div class="stage-note warn" data-warn></div>
- `;
-
- const viewport = element.querySelector<HTMLElement>(".stage-viewport")!;
- const scaler = element.querySelector<HTMLElement>(".stage-scaler")!;
- const frame = element.querySelector<HTMLIFrameElement>("iframe")!;
- const play = element.querySelector<HTMLButtonElement>("[data-play]")!;
- const scrub = element.querySelector<HTMLInputElement>("[data-scrub]")!;
- const readout = element.querySelector<HTMLElement>("[data-frame]")!;
- const size = element.querySelector<HTMLElement>("[data-size]")!;
- const error = element.querySelector<HTMLElement>("[data-error]")!;
- const warn = element.querySelector<HTMLElement>("[data-warn]")!;
-
- let canvas = { width: 1080, height: 1920 };
- let frameCount = 1;
- let fps = 30;
- let ready = false;
- let playing = false;
- let raf = 0;
-
- /**
- * The iframe keeps its composition pixel size and is scaled by transform.
- * Letting it reflow at the viewport size would silently change every length
- * in the document, so a font-size read here would not be the rendered one.
- */
- function fit(): void {
- const room = viewport.getBoundingClientRect();
- const scale = Math.min(
- (room.width - 40) / canvas.width,
- (room.height - 40) / canvas.height,
- );
- const k = Number.isFinite(scale) && scale > 0 ? Math.min(scale, 1) : 1;
- scaler.style.transform = `scale(${k})`;
- scaler.style.width = `${canvas.width * k}px`;
- scaler.style.height = `${canvas.height * k}px`;
- scaler.style.transformOrigin = "top left";
- frame.style.width = `${canvas.width}px`;
- frame.style.height = `${canvas.height}px`;
- }
-
- function seek(at: number): void {
- readout.textContent = `${at} / ${frameCount - 1}`;
- if (!ready) return;
- (frame.contentWindow as SeekWindow | null)?.__svmlSeekFrame?.(at);
- }
-
- function stop(): void {
- playing = false;
- play.textContent = "▶";
- if (raf !== 0) cancelAnimationFrame(raf);
- raf = 0;
- }
-
- play.addEventListener("click", () => {
- if (playing) { stop(); return; }
- playing = true;
- play.textContent = "❚❚";
- const startedAt = performance.now();
- const from = Number(scrub.value);
- const step = (now: number): void => {
- if (!playing) return;
- const at = from + Math.round((now - startedAt) / 1000 * fps);
- if (at >= frameCount) { scrub.value = String(frameCount - 1); seek(frameCount - 1); stop(); return; }
- scrub.value = String(at);
- seek(at);
- raf = requestAnimationFrame(step);
- };
- raf = requestAnimationFrame(step);
- });
-
- scrub.addEventListener("input", () => { stop(); seek(Number(scrub.value)); });
- frame.addEventListener("load", () => { ready = true; seek(Number(scrub.value)); });
- new ResizeObserver(fit).observe(viewport);
-
- return {
- element,
- show(output) {
- error.textContent = "";
- warn.textContent = [...new Set(output.warnings)].join("\n");
- canvas = output.canvas;
- frameCount = Math.max(1, output.frameCount);
- fps = output.fps;
- stop();
- // Keep the playhead across edits so tweaking a value does not lose the
- // frame you were judging.
- const at = Math.min(Number(scrub.value), frameCount - 1);
- scrub.max = String(frameCount - 1);
- scrub.value = String(at);
- readout.textContent = `${at} / ${frameCount - 1}`;
- size.textContent = `${canvas.width}×${canvas.height}`;
- ready = false;
- frame.srcdoc = output.srcdoc;
- fit();
- },
- showError(message) {
- stop();
- error.textContent = message;
- },
- };
-}
diff --git a/tools/playground/vite.config.ts b/tools/playground/vite.config.ts
deleted file mode 100644
index f1e46264..00000000
--- a/tools/playground/vite.config.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { readdirSync, readFileSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-
-import { defineConfig } from "vite";
-
-const here = dirname(fileURLToPath(import.meta.url));
-const repoRoot = resolve(here, "../..");
-
-/**
- * Workspace packages publish raw TypeScript (`exports: { ".": "./src/index.ts" }`),
- * so they must reach Vite as project source rather than as prebundled
- * dependencies. Aliasing every package by its declared entry does that and picks
- * up transitive dependencies for free — enumerating them by hand would drift the
- * moment a package gains one.
- */
-function workspaceAliases(): Array<{ find: string; replacement: string }> {
- const packages = join(repoRoot, "packages");
- return readdirSync(packages, { withFileTypes: true })
- .filter((entry) => entry.isDirectory())
- .flatMap((entry) => {
- const manifestPath = join(packages, entry.name, "package.json");
- let manifest: { name?: unknown; exports?: unknown };
- try {
- manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as typeof manifest;
- } catch {
- return [];
- }
- const entryPoint = (manifest.exports as Record<string, unknown> | undefined)?.["."];
- if (typeof manifest.name !== "string" || typeof entryPoint !== "string") return [];
- // Exact-or-followed-by-slash matching keeps one package prefix from
- // swallowing another package whose name happens to extend it.
- return [{ find: manifest.name, replacement: join(packages, entry.name, entryPoint) }];
- });
-}
-
-export default defineConfig({
- root: here,
- resolve: {
- alias: [
- // `digestOf` hashes synchronously at module load, so Web Crypto cannot
- // stand in. See src/shims/node-crypto.ts.
- { find: "node:crypto", replacement: join(here, "src/shims/node-crypto.ts") },
- ...workspaceAliases(),
- ],
- },
- server: {
- port: 5178,
- // Workspace sources resolve through the aliases above, which point outside
- // this root. Stylesheets and media are chosen by the operator and read in
- // the browser, so the server serves no repository content of its own.
- fs: { allow: [repoRoot] },
- },
-});
diff --git a/tsconfig.json b/tsconfig.json
index 81153ba3..7966f520 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -249,6 +249,9 @@
"@narratage/cli": [
"packages/cli/src/index.ts"
],
+ "@narratage/video-cli": [
+ "packages/video-cli/src/index.ts"
+ ],
"@narratage/validation": [
"packages/validation/src/index.ts"
],
@@ -266,8 +269,8 @@
"include": [
"packages/**/*.ts",
"services/media-lambda/src/**/*.ts",
- "tools/playground/**/*.ts",
- "test/playground-*.test.ts"
+ "tools/caption-playground/**/*.ts",
+ "test/caption-playground-*.test.ts"
],
"exclude": [
"dist",