The VS Code of video editing, built for agents.
TypeScript
Refactor CLI and API structure by removing deprecated components
konstantin-pauluse85cee917a61
diff --git a/README.md b/README.mdindex 389f1a20..057fd81c 100644--- a/README.md+++ b/README.md@@ -8,12 +8,6 @@**Diffusion Studio** lets your agents make videos. The agent writes a composition in TSX. The `dapi` CLI mounts it into the editor. Every element stays editable. Think of it as **FFmpeg for agents**, with generative AI and multimodal understanding built in.-```sh-dapi open # use -b to run the editor headless-dapi mount hero.tsx # render a composition into it-dapi node render -o hero.mp4 # encode the scene to disk-```-## Getting startedUse with Claude Code, Codex, Cursor, Copilot, or Gemini CLI. Install the skill once, globally:@@ -123,23 +117,19 @@ dapi media filmstrip clip.mp4 # grid of video framesdapi media waveform track.mp3 # audio waveform, silence flaggeddapi media transcribe interview.wav # timed, word-level transcriptdapi media listen interview.mp4 -p "what is said in the intro?" # ask a multimodal model-dapi node capture # see the canvas itself+dapi capture 42 # see the canvas itself```## CLI at a glance| Command | Purpose || --- | --- |-| `dapi open` | Launch the app, open a file, or turn a folder of footage into a project || `dapi context` | Summary of the open project: scenes, playhead, fonts |-| `dapi mount` | Compile and mount a JSX composition |-| `dapi node …` | The scene graph: `ls`, `tree`, `grep`, `patch`, `insert`, `cp`, `rm`, `capture`, `render` |-| `dapi asset …` | The media library: `add`, `ls`, `tree`, `mv`, `rm`, `export` |+| `dapi capture` | Render a node in isolation to a labelled contact sheet, or one PNG per position || `dapi media …` | Inspect a file by id or path: `probe`, `grab`, `filmstrip`, `waveform`, `transcribe`, `listen` |-| `dapi project …` / `dapi folder …` / `dapi selection …` | Projects, library folders, canvas selection || `dapi models` / `dapi voices` / `dapi fonts` | Discover generation models, speech voices, local fonts || `dapi screenshot` / `dapi logs` | The app itself: capture the window, read recent console output |-| `dapi fetch` | Download a video from yt/tt/ig, ready for `dapi asset add` |+| `dapi fetch` | Download a video from yt/tt/ig || `dapi whoami` | The authenticated account || `dapi report` | Report a bug in the CLI or the app: diagnostics bundled, filed as a GitHub issue via `gh` |diff --git a/apps/cli/src/cli-channels.ts b/apps/cli/src/cli-channels.tsindex 82f3d29e..e6a7943e 100644--- a/apps/cli/src/cli-channels.ts+++ b/apps/cli/src/cli-channels.ts@@ -2,8 +2,6 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-import type { PatchProps } from "@diffusionstudio/jsx";-// Wire-level channel for the CLI handshake. Each CLI command hosts a// short-lived WebSocket server; main's only job is to relay the connect// info to the renderer, which then dials the CLI directly. Main never sees@@ -32,78 +30,6 @@ export type CliReply =| { ok: true; data: unknown }| { ok: false; error: string };-export type NodeRef = { id: number; name: string; type: string };--export type EntityRecord = { id: string; eid: number } & Record<string, unknown>;---export type NodeTree = NodeRef & {- description: string;- children?: NodeTree[]; // child nodes (masks listed separately)- masks?: NodeTree[];- paints?: NodeTree[]; // fills- strokes?: NodeTree[];- shadows?: NodeTree[];- effects?: NodeTree[];- colorStops?: NodeTree[]; // on gradient paints- textRanges?: NodeTree[]; // on text nodes- keyframeTracks?: NodeTree[]; // keyframes nest beneath their track- keyframes?: NodeTree[];- animations?: NodeTree[];-};--export type NodeGrepRequest = {- pattern: string;- ignoreCase?: boolean;- id?: number; // scope to this entity's subtree; omitted = the whole document- types?: string[]; // only match entities of these node types- components?: string[]; // restrict matching to these components-};--export type NodeGrepMatch = { component: string; value: string };--export type NodeGrepResult = NodeRef & { matches: NodeGrepMatch[] };--export type NodeDeleteResult = { id: number };--export type MountRequest = {- code: string;-};--export type NodeInsertRequest = {- code: string;- parentId: number;- index?: number;-};--export type NodePatch = { id: number } & PatchProps;--export type NodePatchResult = { id: number };--export type NodeDuplicateResult = { sourceId: number; newId: number };--export type EncoderConfigInput = {- format?: "mp4" | "webm" | "ogg" | "mov";- video?: {- codec?: "avc" | "hevc" | "vp9" | "av1" | "vp8";- enabled?: boolean;- bitrate?: number;- fps?: number;- resolution?: number;- };- audio?: {- enabled?: boolean;- codec?: "aac" | "opus";- bitrate?: number;- sampleRate?: number;- numberOfChannels?: number;- };- trim?: { end?: number }; // seconds; caps the encode end-};--export type NodeRenderRequest = { id?: number; output: string; config?: EncoderConfigInput };-export type NodeRenderResult = { path: string };-export type AssetRef = { id: string } | { path: string };export type MediaProbeRequest = AssetRef;@@ -131,14 +57,14 @@ export type TimecodedImage = { timecode: string; base64: string };export type MediaFrameResult = TimecodedImage[];-export type NodeCaptureRequest = {+export type CaptureRequest = {id: number;frames?: number[];combine?: boolean;perSheet?: number;};-export type NodeCaptureResult = TimecodedImage[];+export type CaptureResult = TimecodedImage[];export type MediaTranscribeRequest = AssetRef;export type TranscriptWord = { text: string; start: number; end: number };@@ -159,22 +85,6 @@ export type MediaListenResult = { result?: string; start?: number; end?: numberexport type GeneratedAsset = { id: string; name: string; type: string };-export type FolderInfo = { id: string; name: string; type: "folder" };--export type AssetTreeEntry = { id: string; name: string; type: string; children?: AssetTreeEntry[] };--export type AssetRecord = { id: string } & Record<string, unknown>;--export type AssetMoveResult = { id: string; folderId: string | null };--export type AssetsExportRequest = { ids: string[]; output: string; isDir: boolean };--export type AssetExportResult = { id: string; path: string };--export type FolderMoveResult = { id: string; parentId: string | null };--export type FolderDeleteResult = { id: string; deletedFolders: number; deletedAssets: number };-export type ModelsRequest = { type?: "image" | "video" | "audio" };export type ModelInfo = {@@ -188,13 +98,6 @@ export type ModelInfo = {export type VoiceInfo = { id: string; label: string; description: string };-export type ProjectSummary = {- id: string;- name: string;- createdAt: string;- lastAccessedAt: string;-};-export type ScreenshotResult = { base64: string; width: number; height: number };export type LogLevel = "debug" | "info" | "warning" | "error";diff --git a/apps/cli/src/compile-project.ts b/apps/cli/src/compile-project.tsdeleted file mode 100644index 62241999..00000000--- a/apps/cli/src/compile-project.ts+++ /dev/null@@ -1,297 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { existsSync, readFileSync } from "node:fs";-import { readFile } from "node:fs/promises";-import { isAbsolute, resolve } from "node:path";-import { transformAsync } from "@babel/core";-import { build } from "esbuild";-import type { NodePath, PluginObj, types as BabelTypes } from "@babel/core";-import type { Plugin } from "esbuild";-import presetSolid from "babel-preset-solid";-import presetTypescript from "@babel/preset-typescript";--/**- * Compiles a Solid JSX project module into a single-file ESM bundle for `dapi mount`.- *- * Import resolution splits modules into two worlds:- * - Host modules the app must provide as its own instance (the shared Solid- * reactive runtime and the JSX runtime) are left external under the- * "dapi-host:" prefix and shimmed to the app's namespaces at load time.- * - Everything else is userland: bare specifiers (three, gsap, ...) are left- * external and rewritten to a CDN URL, so authors never install anything and- * any npm package works without us hardcoding a dependency list. An optional- * `dapi.config.json` import map pins versions or redirects to a mirror.- */--// Prefix shared with the app's module loader — a specifier no user code would-// contain by accident, so the app-side rewrite is unambiguous.-export const HOST_MODULE_PREFIX = "dapi-host:";--// Modules that must be the app's own instance (a second copy of the Solid-// runtime would not share the reactive graph). These are never userland.-const HOST_MODULES_RE = /^(?:solid-js(?:\/store)?|@diffusionstudio\/jsx)$/;--// Userland bare imports resolve here at runtime unless the import map overrides-// them; the renderer imports the URL natively (a blob module can import-// absolute URLs). esm.sh resolves each package's own transitive deps.-const DEFAULT_CDN_BASE = "https://esm.sh";--type ResolverConfig = { cdnBase: string; importMap: Record<string, string> };--/**- * Config hook. `dapi.config.json` in the cwd may set `cdnBase` and `imports`- * (exact keys like "three" or trailing-slash prefixes like "three/"); env vars- * override for one-offs. Malformed config is ignored in favour of the defaults.- */-function loadResolverConfig(): ResolverConfig {- let cdnBase = process.env.DAPI_CDN_BASE || DEFAULT_CDN_BASE;- let importMap: Record<string, string> = {};-- const configPath = resolve(process.cwd(), "dapi.config.json");- if (existsSync(configPath)) {- try {- const cfg = JSON.parse(readFileSync(configPath, "utf8")) as {- cdnBase?: string;- imports?: Record<string, string>;- };- if (cfg.cdnBase) cdnBase = cfg.cdnBase;- if (cfg.imports) importMap = cfg.imports;- } catch {- // Ignore a malformed config; fall back to defaults.- }- }-- if (process.env.DAPI_IMPORT_MAP) {- try {- importMap = { ...importMap, ...(JSON.parse(process.env.DAPI_IMPORT_MAP) as Record<string, string>) };- } catch {- // Ignore malformed env override.- }- }-- return { cdnBase: cdnBase.replace(/\/+$/, ""), importMap };-}--/**- * Maps a bare specifier to a URL: an exact import-map hit wins, then the longest- * matching trailing-slash prefix, then the CDN default.- */-function resolveBareSpecifier(spec: string, { cdnBase, importMap }: ResolverConfig): string {- const exact = importMap[spec];- if (exact) return exact;-- let prefix: string | undefined;- for (const key of Object.keys(importMap)) {- if (key.endsWith("/") && spec.startsWith(key) && (prefix === undefined || key.length > prefix.length)) {- prefix = key;- }- }- if (prefix !== undefined) return importMap[prefix] + spec.slice(prefix.length);-- return `${cdnBase}/${spec}`;-}--// The camelCase composition vocabulary, canonicalized to the PascalCase-// components in packages/jsx/src/elements.ts before babel-preset-solid runs.-// Project files write `<rect>`; the renderer keeps receiving `Rect`, so a-// tag's case still decides its environment at runtime.-const BUILT_IN_TAGS: Record<string, string> = {- group: "Group", rect: "Rect", video: "Video", image: "Image",- audio: "Audio", text: "Text", sequence: "Sequence", captions: "Captions",- solidPaint: "SolidPaint", linearGradientPaint: "LinearGradientPaint",- radialGradientPaint: "RadialGradientPaint", colorStop: "ColorStop",- htmlPaint: "HtmlPaint", html: "Html", surfacePaint: "SurfacePaint", surface: "Surface",- shaderPaint: "ShaderPaint",-};--// Tags that exist in both vocabularies. Every collision is SVG-only (HTML has-// no <rect>/<text>/<image>), and SVG content always sits under an SVG-only-// container, so lexical ancestry resolves them: inside one of the containers-// below the tag is SVG content, everywhere else it's a composition element.-// SVG fragments split into their own components must keep an <svg> or <g>-// wrapper; a bare fragment compiles as composition and the mount rejects it.-const AMBIGUOUS_TAGS = new Set(["rect", "text", "image"]);--const SVG_CONTAINERS = new Set([- "svg", "g", "defs", "symbol", "marker", "mask", "clipPath", "pattern",- "filter", "linearGradient", "radialGradient", "textPath", "tspan", "switch",-]);--// Recognized-but-wrong capitalized tags fail at compile time with a pointed-// message; anything else unbound is left for the bundler/runtime as usual.-const PASCAL_ELEMENTS = new Map(Object.entries(BUILT_IN_TAGS).map(([camel, pascal]) => [pascal, camel]));--const SOLID_CONTROL_FLOW = new Set([- "For", "Show", "Switch", "Match", "Suspense", "SuspenseList", "Index", "ErrorBoundary",-]);--/**- * Rewrites camelCase composition tags to aliased imports of their PascalCase- * components. Aliases (rather than the component names themselves) keep a- * user binding that happens to be called `Text` or `Rect` from capturing a- * lowercase tag.- */-function canonicalizeTags({ types: t }: { types: typeof BabelTypes }): PluginObj {- const hasSvgAncestor = (path: NodePath): boolean =>- path.findParent(- (p) =>- p.isJSXElement() &&- t.isJSXIdentifier(p.node.openingElement.name) &&- SVG_CONTAINERS.has(p.node.openingElement.name.name),- ) !== null;-- return {- visitor: {- // The whole rewrite runs up front in Program enter: babel merges plugin- // and preset visitors into one traversal, and babel-preset-solid- // consumes an entire JSX tree on its first visit, so a JSXElement-level- // visitor here would lose the race for every non-root tag.- Program(path) {- // PascalCase name -> local alias, per file.- const aliases = new Map<string, string>();-- path.traverse({- JSXElement(elementPath) {- const name = elementPath.node.openingElement.name;- if (!t.isJSXIdentifier(name)) return;-- if (/^[A-Z]/.test(name.name) && !elementPath.scope.hasBinding(name.name)) {- const camel = PASCAL_ELEMENTS.get(name.name);- if (camel !== undefined) {- throw elementPath.buildCodeFrameError(- `<${name.name}> is not a tag; write the composition element as <${camel}>`,- );- }- if (SOLID_CONTROL_FLOW.has(name.name)) {- throw elementPath.buildCodeFrameError(- `<${name.name}> needs an import: add \`import { ${name.name} } from "solid-js"\``,- );- }- return;- }-- const pascal = BUILT_IN_TAGS[name.name];- if (pascal === undefined) return;- if (AMBIGUOUS_TAGS.has(name.name) && hasSvgAncestor(elementPath)) return;-- let alias = aliases.get(pascal);- if (alias === undefined) {- alias = `_$${pascal}`;- aliases.set(pascal, alias);- }- elementPath.node.openingElement.name = t.jsxIdentifier(alias);- if (elementPath.node.closingElement) {- elementPath.node.closingElement.name = t.jsxIdentifier(alias);- }- },- });-- if (aliases.size === 0) return;- const specifiers = [...aliases].map(([name, alias]) =>- t.importSpecifier(t.identifier(alias), t.identifier(name)),- );- path.unshiftContainer(- "body",- t.importDeclaration(specifiers, t.stringLiteral("@diffusionstudio/jsx")),- );- },- },- };-}--async function transformSolidJsx(source: string, filename: string): Promise<string> {- const result = await transformAsync(source, {- filename,- babelrc: false,- configFile: false,- plugins: [canonicalizeTags],- presets: [- [presetSolid, { generate: "universal", moduleName: "@diffusionstudio/jsx" }],- [presetTypescript, {}],- ],- sourceMaps: "inline",- });- if (!result?.code) {- throw new Error(`Failed to compile ${filename}`);- }- return result.code;-}--function resolverPlugin(config: ResolverConfig): Plugin {- return {- name: "dapi-resolver",- setup(pluginBuild) {- pluginBuild.onResolve({ filter: /.*/ }, (args) => {- const spec = args.path;-- // Let esbuild resolve the entry file itself on disk.- if (args.kind === "entry-point") return null;-- // App-provided singletons: externalized and shimmed at load time.- if (HOST_MODULES_RE.test(spec)) {- return { path: `${HOST_MODULE_PREFIX}${spec}`, external: true };- }-- // Explicit URL imports pass through to the renderer untouched.- if (/^https?:\/\//.test(spec)) return { external: true };-- // Relative or absolute-path imports resolve on disk as usual (multi-file- // samples, local helpers).- if (spec.startsWith(".") || isAbsolute(spec)) return null;-- // Anything else is a userland bare specifier -> CDN / import map.- return { path: resolveBareSpecifier(spec, config), external: true };- });-- // esbuild strips types from .ts natively; only JSX files go through babel- // so the Solid transform sees the untouched JSX.- pluginBuild.onLoad({ filter: /\.[jt]sx$/ }, async (args) => ({- contents: await transformSolidJsx(await readFile(args.path, "utf8"), args.path),- loader: "js",- }));- },- };-}--export type CompileInput = { path: string } | { code: string };--// `--code` ergonomics: a bare JSX expression (no `export default`) is wrapped-// into a component module, so one-liners like `--code '<rect width={10} />'`-function wrapBareJsx(code: string): string {- if (/\bexport\s+default\b/.test(code)) return code;- return `export default () => (\n${code.trim().replace(/;+\s*$/, "")}\n);`;-}--export async function compileProject(input: CompileInput): Promise<string> {- const common = {- bundle: true as const,- write: false as const,- format: "esm" as const,- platform: "browser" as const,- target: "es2022",- sourcemap: "inline" as const,- logLevel: "silent" as const,- plugins: [resolverPlugin(loadResolverConfig())],- };-- // Inline --code bypasses esbuild's loader pipeline (stdin skips onLoad), so- // it is babel-transformed up front and fed in as plain JS.- const result =- "path" in input- ? await build({ ...common, entryPoints: [input.path] })- : await build({- ...common,- stdin: {- contents: await transformSolidJsx(wrapBareJsx(input.code), "project.tsx"),- loader: "js",- resolveDir: process.cwd(),- sourcefile: "project.tsx",- },- });-- const out = result.outputFiles?.[0];- if (!out) throw new Error("Compilation produced no output");- return out.text;-}diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.tsindex b93896c2..9fd08255 100644--- a/apps/cli/src/index.ts+++ b/apps/cli/src/index.ts@@ -3,109 +3,24 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-import { spawn } from "node:child_process";import { randomUUID } from "node:crypto";-import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";-import { platform, tmpdir } from "node:os";-import { dirname, extname, isAbsolute, join, resolve } from "node:path";+import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, isAbsolute, join, resolve } from "node:path";import { Command } from "commander";import { version } from "../../../package.json";import { parseTime, TIME_FPS } from "@diffusionstudio/jsx";-import { editor, errnoCode, waitForCliSocket, GENERATE_TIMEOUT_MS } from "./cli-client";-import { compileProject } from "./compile-project";+import { editor, errnoCode, GENERATE_TIMEOUT_MS } from "./cli-client";import { listLocalFonts } from "./fonts";import { buildIssueBody, createIssue } from "./report";-import { openFolder } from "./open-folder";import { fetchVideo } from "./ytdlp";import { MAX_FRAMES_PER_SHEET } from "./protocol";-import type { AssetRef, EncoderConfigInput, FrameQuality, LogEntry, LogLevel, NodePatch, TimecodedImage } from "./protocol";+import type { AssetRef, FrameQuality, LogEntry, LogLevel, TimecodedImage } from "./protocol";// Long-running commands (renders, AI generation) override the default 60s.const GENERATE = { context: { timeoutMs: GENERATE_TIMEOUT_MS } };const APP_NAME = "Diffusion Studio";-const PROTOCOL = "diffusion";--// Forwarded to the app's process.argv;-const HIDDEN_FLAG = "--hidden";--function openApp(target?: string, background = false): void {- const isUrl = !!target && target.startsWith(`${PROTOCOL}://`);- const os = platform();- // The bin wrapper exports ELECTRON_RUN_AS_NODE to run this CLI through the- // app's Electron binary. `open`/`start` forward our environment to the app,- // where the flag would make Electron boot as plain Node and exit instantly,- // so launch with it stripped.- const { ELECTRON_RUN_AS_NODE: _, ...env } = process.env;-- if (os === "darwin") {- const args: string[] = [];- if (background) args.push("-g");- if (isUrl) {- args.push(target!);- } else {- args.push("-a", process.env.DIFFUSION_APP_PATH ?? APP_NAME);- if (target) args.push(target);- }-- if (background) {- args.push("--args", HIDDEN_FLAG);- }-- spawn("open", args, { detached: true, stdio: "ignore", env }).unref();- return;- }-- if (os === "win32") {- const arg = target ?? APP_NAME;- const args = ["/c", "start", "", arg];- if (background) args.push(HIDDEN_FLAG);- spawn("cmd", args, { detached: true, stdio: "ignore", env }).unref();- return;- }-- const candidates = [- "/usr/bin/diffusion-studio",- "/usr/local/bin/diffusion-studio",- join(process.env.HOME ?? "", ".local/bin/diffusion-studio"),- ];- const bin = candidates.find((p) => existsSync(p));- if (bin) {- const args = target ? [target] : [];- if (background) args.push(HIDDEN_FLAG);- spawn(bin, args, { detached: true, stdio: "ignore", env }).unref();- return;- }- if (isUrl) {- spawn("xdg-open", [target!], { detached: true, stdio: "ignore", env }).unref();- return;- }- console.error(`Could not locate "${APP_NAME}" on this system.`);- process.exit(1);-}--async function openTarget(target: string | undefined, background: boolean): Promise<void> {- if (target && !target.startsWith(`${PROTOCOL}://`)) {- const absPath = isAbsolute(target) ? target : resolve(process.cwd(), target);- if (!existsSync(absPath)) {- console.error(`Path not found: ${absPath}`);- process.exit(1);- }- if (statSync(absPath).isDirectory()) {- openApp(undefined, background);- try {- await waitForCliSocket();- const result = await openFolder(absPath);- console.log(JSON.stringify(result));- } catch (e) {- console.error((e as Error).message);- process.exit(1);- }- return;- }- }- openApp(target, background);-}function handleSocketError(e: unknown): never {const code = errnoCode(e);@@ -117,338 +32,6 @@ function handleSocketError(e: unknown): never {process.exit(1);}-// Node ids are entity ids — integers. argv is always string, so the-// conversion belongs here, at the one boundary, with a strict check. Coercing-// app-side with Number() would silently accept "0x1f", "1e3", " 7 ", "" → 0.-function parseNodeIds(ids: string[]): number[] {- return ids.map((id) => {- if (!/^\d+$/.test(id)) {- console.error(`Invalid node id: ${JSON.stringify(id)} (expected a non-negative integer)`);- process.exit(1);- }- return Number(id);- });-}--type AssetAddOptions = { folder?: string };--async function addAssets(paths: string[], opts: AssetAddOptions): Promise<void> {- if (paths.length === 0) {- console.error("No file paths provided.");- process.exit(1);- }-- const absolutePaths = paths.map((p) => (isAbsolute(p) ? p : resolve(process.cwd(), p)));- for (const p of absolutePaths) {- if (!existsSync(p)) {- console.error(`File not found: ${p}`);- process.exit(1);- }- if (!statSync(p).isFile()) {- console.error(`Not a file: ${p}`);- process.exit(1);- }- }-- try {- const results = await editor.asset.add.mutate({ paths: absolutePaths, folderId: opts.folder });- for (const result of results) {- console.log(JSON.stringify(result));- }- } catch (e) {- handleSocketError(e);- }-}--async function listAssets(ids: string[]): Promise<void> {- try {- // No ids → every asset in the library; with ids → those specific assets.- const results = await editor.asset.list.query({ ids: ids.length ? ids : undefined });- for (const result of results) {- console.log(JSON.stringify(result));- }- } catch (e) {- handleSocketError(e);- }-}--type AssetTreeOptions = { folder?: string; depth?: string };--async function assetTree(opts: AssetTreeOptions): Promise<void> {- let depth: number | undefined;- if (opts.depth !== undefined) {- const n = Number(opts.depth);- if (!Number.isInteger(n) || n <= 0) {- console.error(`--depth must be a positive integer (got "${opts.depth}")`);- process.exit(1);- }- depth = n;- }-- try {- const results = await editor.asset.tree.query({ folderId: opts.folder, depth });- for (const result of results) console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}--async function deleteAssets(ids: string[]): Promise<void> {- if (ids.length === 0) {- console.error("No ids provided.");- process.exit(1);- }- try {- const results = await editor.asset.delete.mutate({ ids });- for (const result of results) console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}--type MoveOptions = { to?: string };--async function moveAssets(ids: string[], opts: MoveOptions): Promise<void> {- if (ids.length === 0) {- console.error("No ids provided.");- process.exit(1);- }- try {- const results = await editor.asset.move.mutate({ ids, to: opts.to });- for (const result of results) console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}--type AssetExportOptions = { output?: string };--async function exportAssets(ids: string[], opts: AssetExportOptions): Promise<void> {- if (ids.length === 0) {- console.error("No ids provided.");- process.exit(1);- }-- let output: string;- let isDir: boolean;- if (opts.output === undefined) {- output = tmpdir();- isDir = true;- } else {- output = isAbsolute(opts.output) ? opts.output : resolve(process.cwd(), opts.output);- // A trailing separator always means a directory; so do multiple ids.- const wantsDir = /[\\/]$/.test(opts.output) || ids.length > 1;- if (existsSync(output) && statSync(output).isFile()) {- if (wantsDir) {- console.error(`--output must be a directory here, but resolves to an existing file: ${output}`);- process.exit(1);- }- isDir = false;- } else if (existsSync(output)) {- isDir = true;- } else {- isDir = wantsDir;- if (isDir) mkdirSync(output, { recursive: true });- }- }-- const stop = startSpinner(ids.length > 1 ? "Exporting assets" : "Exporting asset");- try {- const results = await editor.asset.export.mutate({ ids, output, isDir }, GENERATE);- stop();- for (const result of results) console.log(JSON.stringify(result));- } catch (e) {- stop();- handleSocketError(e);- }-}--async function listFolders(parentId: string | undefined): Promise<void> {- try {- const results = await editor.folder.list.query({ parentId });- for (const result of results) console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}--type FolderCreateOptions = { parent?: string };--async function createFolder(name: string, opts: FolderCreateOptions): Promise<void> {- try {- const result = await editor.folder.create.mutate({ name, parentId: opts.parent });- console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}--async function renameFolder(id: string, name: string): Promise<void> {- try {- const result = await editor.folder.rename.mutate({ id, name });- console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}--async function moveFolders(ids: string[], opts: MoveOptions): Promise<void> {- if (ids.length === 0) {- console.error("No ids provided.");- process.exit(1);- }- try {- const results = await editor.folder.move.mutate({ ids, to: opts.to });- for (const result of results) console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}--async function deleteFolders(ids: string[]): Promise<void> {- if (ids.length === 0) {- console.error("No ids provided.");- process.exit(1);- }- try {- const results = await editor.folder.delete.mutate({ ids });- for (const result of results) console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}--async function listSelection(): Promise<void> {- try {- const results = await editor.selection.list.query();- for (const result of results) console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}--async function setSelection(ids: string[]): Promise<void> {- try {- const results = await editor.selection.set.mutate({ ids: parseNodeIds(ids) });- for (const result of results) console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}--async function focusSelection(): Promise<void> {- try {- const results = await editor.selection.focus.mutate();- for (const result of results) {- console.log(JSON.stringify(result));- }- } catch (e) {- handleSocketError(e);- }-}--async function listNodes(ids: string[]): Promise<void> {- try {- // No ids → root scenes; with ids → those specific nodes.- const results = await editor.node.list.query({ ids: ids.length ? parseNodeIds(ids) : undefined });- for (const result of results) {- console.log(JSON.stringify(result));- }- } catch (e) {- handleSocketError(e);- }-}--type TreeOptions = { depth?: string };--async function nodeTree(id: string | undefined, opts: TreeOptions): Promise<void> {- const eid = id !== undefined ? parseNodeIds([id])[0] : undefined;-- let depth: number | undefined = 3;- if (opts.depth !== undefined) {- const n = Number(opts.depth);- if (!Number.isInteger(n) || n < 0) {- console.error(`--depth must be a non-negative integer (got "${opts.depth}")`);- process.exit(1);- }- depth = n === 0 ? undefined : n;- }-- try {- const results = await editor.node.tree.query({ id: eid, depth });- for (const result of results) {- console.log(JSON.stringify(result));- }- } catch (e) {- handleSocketError(e);- }-}--type NodeGrepOptions = {- ignoreCase?: boolean;- type?: string[];- component?: string[];- refsOnly?: boolean;- count?: boolean;-};--async function grepNodes(pattern: string, id: string | undefined, opts: NodeGrepOptions): Promise<void> {- // Validate the regex here so a bad pattern fails before the app is contacted.- try {- new RegExp(pattern);- } catch (e) {- console.error(`Invalid pattern: ${(e as Error).message}`);- process.exit(1);- }- const eid = id !== undefined ? parseNodeIds([id])[0] : undefined;-- try {- const results = await editor.node.grep.query({- pattern,- ignoreCase: opts.ignoreCase,- id: eid,- types: opts.type,- components: opts.component,- });- if (opts.count) {- console.log(JSON.stringify(results.length));- return;- }- for (const result of results) {- if (opts.refsOnly) {- const { matches, ...ref } = result;- console.log(JSON.stringify(ref));- } else {- console.log(JSON.stringify(result));- }- }- } catch (e) {- handleSocketError(e);- }-}--type CaptureOptions = { time?: string[]; output?: string; separate?: boolean; perSheet?: string };--async function nodeCapture(id: string, opts: CaptureOptions): Promise<void> {- const eid = parseNodeIds([id])[0];-- const times = (opts.time ?? ["0"]).map((t) => parseTimeArg(t, "--time"));- const frames = times.map((t) => Math.round(t * TIME_FPS));- const perSheet = parsePerSheet(opts.perSheet, opts.separate);-- const dir = opts.output ?? join(tmpdir(), `dapi-capture-${randomUUID().slice(0, 8)}`);- mkdirSync(dir, { recursive: true });- try {- const images = await editor.node.capture.query(- { id: eid, frames, combine: !opts.separate, perSheet },- GENERATE,- );- writeImages(images, dir);- } catch (e) {- handleSocketError(e);- }-}-const FRAME_QUALITIES: FrameQuality[] = ["small", "medium", "large", "fullres"];// Guardrail against accidentally decoding a huge number of frames; --uncapped lifts it.@@ -698,269 +281,34 @@ async function mediaWaveform(ref: string, opts: MediaPreviewOptions): Promise<vo}}-const MOUNT_EXTENSIONS = new Set([".tsx", ".jsx", ".ts", ".js"]);--type MountOptions = { code?: string };--// Validates the (<path> | --code) pair shared by `mount` and `node insert`,-// then compiles the module. Compile errors fail here, before the app is contacted.-async function compileProjectInput(path: string | undefined, code: string | undefined): Promise<string> {- if ((path === undefined) === (code === undefined)) {- console.error(`Provide exactly one of <path> or --code <str>.`);- process.exit(1);- }-- let input: { path: string } | { code: string };- if (path !== undefined) {- const absPath = isAbsolute(path) ? path : resolve(process.cwd(), path);- if (!existsSync(absPath) || !statSync(absPath).isFile()) {- console.error(`File not found: ${absPath}`);- process.exit(1);- }- if (!MOUNT_EXTENSIONS.has(extname(absPath).toLowerCase())) {- console.error(`Entry module must be a .tsx, .jsx, .ts, or .js file (got "${extname(absPath)}")`);- process.exit(1);- }- input = { path: absPath };- } else {- input = { code: code! };- }-- try {- return await compileProject(input);- } catch (e) {- console.error((e as Error).message);- process.exit(1);- }-}--async function mountProject(path: string | undefined, opts: MountOptions): Promise<void> {- const code = await compileProjectInput(path, opts.code);-- const stop = startSpinner("Mounting project");- try {- await editor.mount.mutate({ code }, GENERATE);- stop();- } catch (e) {- stop();- handleSocketError(e);- }-}--type NodeInsertOptions = { index?: string };--async function nodeInsert(parentId: string, source: string, opts: NodeInsertOptions): Promise<void> {- const [eid] = parseNodeIds([parentId]);-- let index: number | undefined;- if (opts.index !== undefined) {- const n = Number(opts.index);- if (!Number.isInteger(n) || n < 0) {- console.error(`--index must be a non-negative integer (got "${opts.index}")`);- process.exit(1);- }- index = n;- }-- // `insert` takes a JSX fragment inline, not a module or a file: it renders- // once and is discarded, so a live program has nothing to drive it. Validate- // loosely — reject the module form and require something that looks like a tag.- if (/\bexport\s+default\b/.test(source)) {- console.error("`dapi node insert` takes JSX tags, not a component module — drop `export default` (use `dapi mount` for a live program).");- process.exit(1);- }- if (!/<\s*[A-Za-z]/.test(source)) {- console.error("`dapi node insert` expects JSX tags, e.g. '<rect width={10} height={10} />'.");- process.exit(1);- }-- let code: string;- try {- code = await compileProject({ code: source });- } catch (e) {- console.error((e as Error).message);- process.exit(1);- }-- const stop = startSpinner("Inserting entities");- try {- await editor.node.insert.mutate({ code, parentId: eid, index }, GENERATE);- stop();- } catch (e) {- stop();- handleSocketError(e);- }-}--async function deleteNodes(ids: string[]): Promise<void> {- if (ids.length === 0) {- console.error("No ids provided.");- process.exit(1);- }- try {- const results = await editor.node.delete.mutate({ ids: parseNodeIds(ids) });- for (const result of results) console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}--type JsonPayloadOptions = { json?: string };--/**- * Unified JSON payload input, mirroring `mount`'s shape: a positional .json- * file path, or an inline --json string.- */-function readJsonPayload(- path: string | undefined,- json: string | undefined,- required: boolean,-): unknown {- if (path !== undefined && json !== undefined) {- console.error(`Provide only one of <path> or --json <str>.`);- process.exit(1);- }- if (path === undefined && json === undefined) {- if (!required) return undefined;- console.error(`Provide exactly one of <path> or --json <str>.`);- process.exit(1);- }- let raw: string;- if (path !== undefined) {- const absPath = isAbsolute(path) ? path : resolve(process.cwd(), path);- if (!existsSync(absPath) || !statSync(absPath).isFile()) {- console.error(`File not found: ${absPath}`);- process.exit(1);- }- if (extname(absPath).toLowerCase() !== ".json") {- console.error(`Payload must be a .json file (got "${extname(absPath)}")`);- process.exit(1);- }- raw = readFileSync(absPath, "utf8");- } else {- raw = json!;- }- try {- return JSON.parse(raw);- } catch {- console.error(`Payload is not valid JSON.`);- process.exit(1);- }-}--async function patchNodes(path: string | undefined, opts: JsonPayloadOptions): Promise<void> {- const payload = readJsonPayload(path, opts.json, true);- if (- !Array.isArray(payload) ||- payload.some(- (p) =>- typeof p !== "object" ||- p === null ||- !Number.isInteger((p as { id?: unknown }).id),- )- ) {- console.error(`Payload must be an array of { id: number } with JSX props.`);+// Node ids are entity ids — integers. argv is always string, so the+// conversion belongs here, at the one boundary, with a strict check. Coercing+// app-side with Number() would silently accept "0x1f", "1e3", " 7 ", "" → 0.+function parseNodeId(id: string): number {+ if (!/^\d+$/.test(id)) {+ console.error(`Invalid node id: ${JSON.stringify(id)} (expected a non-negative integer)`);process.exit(1);}- try {- const results = await editor.node.patch.mutate({ patches: payload as NodePatch[] });- for (const result of results) console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }+ return Number(id);}-async function duplicateNodes(ids: string[]): Promise<void> {- if (ids.length === 0) {- console.error("No ids provided.");- process.exit(1);- }- try {- const results = await editor.node.duplicate.mutate({ ids: parseNodeIds(ids) });- for (const result of results) console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}--type NodeRenderOptions = JsonPayloadOptions & { output?: string };--async function nodeRender(- idArg: string | undefined,- configArg: string | undefined,- opts: NodeRenderOptions,-): Promise<void> {- // Node ids are integers, so a lone non-numeric positional is the config file.- let id = idArg;- let configPath = configArg;- if (id !== undefined && configPath === undefined && !/^\d+$/.test(id)) {- configPath = id;- id = undefined;- }- const eid = id !== undefined ? parseNodeIds([id])[0] : undefined;-- const config = readJsonPayload(configPath, opts.json, false) as EncoderConfigInput | undefined;- if (config !== undefined && (typeof config !== "object" || config === null || Array.isArray(config))) {- console.error(`Encode config must be a JSON object.`);- process.exit(1);- }-- const format = config?.format ?? "mp4";- const output = opts.output !== undefined- ? (isAbsolute(opts.output) ? opts.output : resolve(process.cwd(), opts.output))- : join(tmpdir(), `${randomUUID()}.${format}`);-- const stop = startSpinner("Rendering scene");- try {- const { path } = await editor.node.render.mutate({ id: eid, output, config }, GENERATE);- stop();- console.log(JSON.stringify({ path }));- } catch (e) {- stop();- handleSocketError(e);- }-}--async function activeProject(): Promise<void> {- try {- const result = await editor.project.active.query();- console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}--async function listProjects(): Promise<void> {- try {- const result = await editor.project.list.query();- for (const project of result) console.log(JSON.stringify(project));- } catch (e) {- handleSocketError(e);- }-}+type CaptureOptions = { time?: string[]; output?: string; separate?: boolean; perSheet?: string };-async function createProject(name?: string): Promise<void> {- try {- const result = await editor.project.create.mutate({ name });- console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}+async function captureNode(id: string, opts: CaptureOptions): Promise<void> {+ const eid = parseNodeId(id);-async function openProject(id: string): Promise<void> {- try {- const result = await editor.project.open.mutate({ id });- console.log(JSON.stringify(result));- } catch (e) {- handleSocketError(e);- }-}+ const times = (opts.time ?? ["0"]).map((t) => parseTimeArg(t, "--time"));+ const frames = times.map((t) => Math.round(t * TIME_FPS));+ const perSheet = parsePerSheet(opts.perSheet, opts.separate);-async function deleteProject(id: string): Promise<void> {+ const dir = opts.output ?? join(tmpdir(), `dapi-capture-${randomUUID().slice(0, 8)}`);+ mkdirSync(dir, { recursive: true });try {- const result = await editor.project.delete.mutate({ id });- console.log(JSON.stringify(result));+ const images = await editor.capture.query(+ { id: eid, frames, combine: !opts.separate, perSheet },+ GENERATE,+ );+ writeImages(images, dir);} catch (e) {handleSocketError(e);}@@ -1228,79 +576,16 @@ program.action(() => context());program- .command("open")- .description(- `Launch Diffusion Studio, or open a target (does not require the app to be running). With no target, launches the app; a "${PROTOCOL}://" URL follows the deep link; a file path opens the file; a folder path creates a project from its contents (importing supported assets, mirroring subfolders) or reopens the one recorded in its .dapi marker.`,- )- .argument("[target]", `file path, folder path, or "${PROTOCOL}://" URL to open`)- .option("-b, --background", "launch with the window hidden (headless)")- .action((target: string | undefined, opts: { background?: boolean }) =>- openTarget(target, opts.background ?? false));--program- .command("mount")- .description(- `Compile a Solid JSX project module and mount its roots into the canvas. Re-mounting reconciles rather than duplicates: only a scene is mountable as a root, carrying its identity in \`scene\`, and a root replaces the scene with that identity or creates it (a new scene, promoted with \`scene\`, becomes the active scene and the camera focuses it). A mount stays live: its reactive graph keeps running (signals, effects, timers, \`useTicker\`), and the persisted module is re-executed in every context, so the mount is restored on reload and ticker-driven <surface>/<html> animate in exports and captures (structure must be deterministic). Long-running when the module declares AI assets (blocks until generation finishes). Compile errors fail before the app is contacted; inspect the result with \`dapi context\` or \`dapi node tree\`.`,- )- .argument("[path]", "path to a .tsx / .jsx / .ts / .js entry module")- .option("--code <str>", "inline module source; export default wrapper optional for bare JSX")- .action((path: string | undefined, opts: MountOptions) => mountProject(path, opts));--const asset = program- .command("asset")- .alias("a")- .description(- "Manage the asset library of the open project: add local files, list and organize records, and export original bytes.",- );--asset- .command("add")- .description(`Add one or more local files as assets in the open project (paths resolve against CWD).`)- .argument("<paths...>", "absolute or relative file paths to add")- .option("--folder <id>", "folder to place the new assets in (default: the library root); fails before importing anything if it doesn't resolve to a folder")- .action((paths: string[], opts: AssetAddOptions) => addAssets(paths, opts));--asset- .command("ls")- .aliases(["list", "get"])- .description(- `Print raw asset records: every persisted property except the file handles (name, type, mimeType, size, createdAt, folderId, per-type media metadata, any stored transcript).`,- )- .argument("[ids...]", "asset ids to list (optional). With no ids, lists every asset in the library.")- .action((ids: string[]) => listAssets(ids));--asset- .command("tree")- .description(- `Print the asset library as its folder tree: folders and assets interleaved, each folder carrying its contents (assets never do).`,- )- .option("--folder <id>", "folder whose contents to list (default: the library root); fails if it doesn't resolve to a folder")- .option("--depth <n>", "max depth to descend (positive integer; default = full tree)")- .action((opts: AssetTreeOptions) => assetTree(opts));--asset- .command("rm")- .alias("remove")- .description(`Delete one or more assets from the open project by id.`)- .argument("<ids...>", "asset ids to delete")- .action((ids: string[]) => deleteAssets(ids));--asset- .command("mv")- .alias("move")- .description(`Move one or more assets into a folder.`)- .argument("<ids...>", "asset ids to move")- .option("--to <folderId>", "destination folder (default: the library root); fails before moving anything if it doesn't resolve to a folder")- .action((ids: string[], opts: MoveOptions) => moveAssets(ids, opts));--asset- .command("export")+ .command("capture").description(- `Write one or more assets' original stored bytes to disk (no re-encode, no credits; any asset type except image sequences).`,+ `Render a node in isolation to PNGs. By default the positions are merged into contact sheets: up to 12 per image, each cell labelled with its timecode (\`08s10f\`, zero segments dropped) and rendered as large as fits, so a few positions arrive as one high-resolution picture instead of a directory to open one by one (\`--separate\` writes a PNG per position, at 720p height, keeping the alpha channel). The node is drawn offscreen, tightly framed to its own bounds on a transparent background; siblings and overlapping scene content are not included, so capture a scene id to check composition ("what plays at time T": layout, overlaps, text, timing). For a video asset's own full-resolution pixels use \`media grab\`.`,)- .argument("<ids...>", "asset ids to export")- .option("-o, --output <path>", "where to write (default: system temp dir); a directory when it exists as one, ends with a path separator, or multiple ids are given (each asset written under its own name), otherwise an exact file path for a single id")- .action((ids: string[], opts: AssetExportOptions) => exportAssets(ids, opts));+ .argument("<id>", "node id to capture")+ .option("-t, --time <time...>", `one or more positions to capture, relative to the node's start (0 = its first visible frame) — seconds ("1.5"), frames ("45f"), or "MM:SS" (default: 0, the node's first visible frame)`)+ .option("-S, --separate", "write one PNG per position instead of merging them into contact sheets")+ .option("--per-sheet <n>", "positions per contact sheet, 1-12; fewer means a larger cell each (default: as many as fit)")+ .option("-o, --output <dir>", "directory to write the PNGs into (default: a fresh dir in the system temp dir)")+ .action((id: string, opts: CaptureOptions) => captureNode(id, opts));const media = program.command("media")@@ -1329,7 +614,7 @@ media.command("grab").alias("sample").description(- `Decode frames of a video file and write them as PNGs (local render, no credits). By default the frames are merged into contact sheets: up to 12 per image, each cell labelled with its timecode (\`08s10f\`, zero segments dropped) and drawn as large as fits, so a handful of frames arrives as one high-resolution picture instead of a directory to open one by one (\`--separate\` writes a PNG per frame). Grabs the asset's own pixels, unlike \`node capture\` which renders the composited node. The recommended tool for understanding a video at the frame level; past ~12 frames prefer \`media filmstrip\`.`,+ `Decode frames of a video file and write them as PNGs (local render, no credits). By default the frames are merged into contact sheets: up to 12 per image, each cell labelled with its timecode (\`08s10f\`, zero segments dropped) and drawn as large as fits, so a handful of frames arrives as one high-resolution picture instead of a directory to open one by one (\`--separate\` writes a PNG per frame). Grabs the asset's own pixels, unlike \`capture\` which renders the composited node. The recommended tool for understanding a video at the frame level; past ~12 frames prefer \`media filmstrip\`.`,).argument("<id|path>", "video asset id, or a local video file to grab frames from").option("-t, --time <time...>", `one or more timestamps to grab — seconds ("1.5"), frames ("45f"), or "MM:SS"; negatives count back from the end, so -1 is one second before the end and -1f one frame before it (default: 0)`)@@ -1382,210 +667,10 @@ media.option("--keep-video", "for a video asset, keep the video track instead of stripping to audio, so the model also reads what is on screen (expensive: uploads the full video)").action((ref: string, opts: MediaListenOptions) => mediaListen(ref, opts));-const folder = program- .command("folder")- .alias("fld")- .description("Organize the asset library of the open project into folders");--folder- .command("ls")- .aliases(["list", "get"])- .description(- `List the direct child folders of a parent folder, sorted by name; with no id, the root-level folders. Folders nest arbitrarily, and assets reference their folder via folderId (null = library root).`,- )- .argument("[parentId]", "parent folder id (optional; omitted = the library root); fails if it doesn't resolve to a folder")- .action((parentId: string | undefined) => listFolders(parentId));--folder- .command("create")- .description(`Create a folder.`)- .argument("<name>", "folder name")- .option("-p, --parent <id>", "parent folder (default: the library root); fails if it doesn't resolve to a folder")- .action((name: string, opts: FolderCreateOptions) => createFolder(name, opts));--folder- .command("rename")- .description(`Rename a folder.`)- .argument("<id>", "folder id")- .argument("<name>", "new name")- .action((id: string, name: string) => renameFolder(id, name));--folder- .command("mv")- .alias("move")- .description(- `Move one or more folders under a new parent. A folder cannot move into itself or a descendant; such a move fails the command before anything moves.`,- )- .argument("<ids...>", "folder ids to move")- .option("--to <folderId>", "destination parent folder (default: the library root); fails before moving anything if it doesn't resolve to a folder")- .action((ids: string[], opts: MoveOptions) => moveFolders(ids, opts));--folder- .command("rm")- .alias("remove")- .description(- `Delete one or more folders. Deletion cascades: every nested folder and every asset inside is deleted too (the result reports how many of each were removed).`,- )- .argument("<ids...>", "folder ids to delete")- .action((ids: string[]) => deleteFolders(ids));--const selection = program- .command("selection")- .alias("sel")- .description("Read and mutate the current node selection");--selection- .command("ls")- .aliases(["list", "get"])- .description(- `List the currently selected nodes. \`set\` and \`focus\` return the resulting selection in the same shape.`,- )- .action(() => listSelection());--selection- .command("set")- .description(`Replace the current selection with exactly the given node ids (none = clear).`)- .argument("[ids...]", "node ids to select")- .action((ids: string[]) => setSelection(ids));--selection- .command("focus")- .description(`Pan and zoom the canvas to fit the current selection in view (no-op if nothing is selected).`)- .action(() => focusSelection());--const node = program- .command("node")- .aliases(["n", "entity"])- .description("Operate on one or more nodes in the open project");--node- .command("ls")- .aliases(["list", "get"])- .description(- `Print raw entity records, exactly as persisted: every component the entity carries, keyed by component name (Name, Size, Position, Paint, Trim, ChildOf, ...). With no ids, lists the top-level nodes. Values are raw engine units: times are frames at 30 fps, colors packed 0xRRGGBB, volume in dB (0 = unity).`,- )- .argument("[ids...]", "entity ids to list (optional)")- .action((ids: string[]) => listNodes(ids));--node- .command("tree")- .description(- `Print an entity's subtree as a nested JSON object: structure and ids only, with each node's key traits folded into a compact \`description\` string (use \`node ls\` for exact values). Sub-entities (masks, paints, strokes, keyframes, ...) nest under named arrays. With no id, prints one tree per top-level node.`,- )- .argument("[id]", "root entity id (optional; omitted = every top-level node)")- .option("--depth <n>", "max depth to descend (default: 3; 0 = full subtree)")- .action((id: string | undefined, opts: TreeOptions) => nodeTree(id, opts));--node- .command("grep")- .description(- `Search entity records for a regex and print the matching entities with the components that matched. The search corpus is the raw records \`node ls\` emits (stringified, so raw engine units), scoped to a subtree when [id] is given. The way to find ids to then read, select, or patch. Common case (find by name): \`dapi node grep -k Name Title\`.`,- )- .argument("<pattern>", "regex to match against stringified component values")- .argument("[id]", "root entity id to scope the search to a subtree (optional; omitted = the whole document)")- .option("-i, --ignore-case", "case-insensitive matching")- .option("-t, --type <types...>", "only match entities of these node types, e.g. -t text image")- .option("-k, --component <names...>", "restrict matching to these components, e.g. -k Name Chars")- .option("-l, --refs-only", "output only the matching entity refs, no match detail")- .option("-c, --count", "output only the number of matching entities")- .action((pattern: string, id: string | undefined, opts: NodeGrepOptions) => grepNodes(pattern, id, opts));--node- .command("capture")- .description(- `Render a node in isolation to PNGs. By default the positions are merged into contact sheets: up to 12 per image, each cell labelled with its timecode (\`08s10f\`, zero segments dropped) and rendered as large as fits, so a few positions arrive as one high-resolution picture instead of a directory to open one by one (\`--separate\` writes a PNG per position, at 720p height, keeping the alpha channel). The node is drawn offscreen, tightly framed to its own bounds on a transparent background; siblings and overlapping scene content are not included, so capture a scene id to check composition ("what plays at time T": layout, overlaps, text, timing). For a video asset's own full-resolution pixels use \`media grab\`.`,- )- .argument("<id>", "node id to capture")- .option("-t, --time <time...>", `one or more positions to capture, relative to the node's start (0 = its first visible frame) — seconds ("1.5"), frames ("45f"), or "MM:SS" (default: 0, the node's first visible frame)`)- .option("-S, --separate", "write one PNG per position instead of merging them into contact sheets")- .option("--per-sheet <n>", "positions per contact sheet, 1-12; fewer means a larger cell each (default: as many as fit)")- .option("-o, --output <dir>", "directory to write the PNGs into (default: a fresh dir in the system temp dir)")- .action((id: string, opts: CaptureOptions) => nodeCapture(id, opts));--node- .command("insert")- .description(- `Insert JSX tags as children of an existing entity. The payload is an inline JSX fragment, e.g. \`'<rect width={10} height={10} />'\` — bare tags, no \`export default\`: an insert renders once and is discarded, so there is no live graph to drive (use \`dapi mount\` for anything reactive). Otherwise it shares the \`mount\` pipeline, including AI asset generation, but inserts fresh entities every run rather than reconciling by key, and deletes nothing. Roots must be valid children of the parent (a node takes any element or paint except a scene root carrying \`scene\` and <colorStop>; a gradient paint takes only <colorStop> roots, which is how you add a stop to a gradient).`,- )- .argument("<parentId>", "entity id of the parent to insert into — a node, or a gradient paint for <colorStop> roots")- .argument("<code>", "JSX tags to insert, e.g. '<rect width={10} height={10} />' (no export default)")- .option("-i, --index <n>", "0-based position among the parent's existing children (node roots only; default: append at the end)")- .action((parentId: string, code: string, opts: NodeInsertOptions) => nodeInsert(parentId, code, opts));--node- .command("rm")- .alias("remove")- .description(`Delete one or more entities and all their descendants.`)- .argument("<ids...>", "entity ids to delete")- .action((ids: string[]) => deleteNodes(ids));--node- .command("cp")- .alias("duplicate")- .description(`Deep-clone one or more nodes, including all descendants.`)- .argument("<ids...>", "node ids to duplicate")- .action((ids: string[]) => duplicateNodes(ids));--node- .command("patch")- .description(- `Assign JSX props on one or more existing entities in a single call: the same properties, with the same value requirements, as \`mount\` (payload is an array of { id, ...props }, all optional; type PatchProps). Any live entity is addressable, not just nodes (paints and color stops too); renaming a node is patching its \`name\`, and \`fill\` recolors or creates the entity's solid fill.`,- )- .argument("[path]", "path to a .json file containing the patch array")- .option("--json <str>", "inline JSON array of { id, ...jsx props }")- .action((path: string | undefined, opts: JsonPayloadOptions) => patchNodes(path, opts));--node- .command("render")- .description(- `Render a scene to a video file (local, no credits, no account needed); long-running, with a progress spinner on stderr so stdout stays clean. The optional encode config (EncoderConfig) sets the container and codecs; omit it for the defaults: mp4/H.264, 1080p, 10 Mbps video, AAC 128 kbps stereo audio, the scene's fps.`,- )- .argument("[id]", "scene node id (optional; defaults to the active scene)")- .argument("[config]", "path to a .json encode config (EncoderConfig); its `format` may be mp4, webm, ogg, or mov, and `trim.end` caps the encode")- .option("-o, --output <path>", "write the video here (default: a temp file); the extension follows the config's format")- .option("--json <str>", "inline JSON encode config (EncoderConfig)")- .action((id: string | undefined, config: string | undefined, opts: NodeRenderOptions) =>- nodeRender(id, config, opts));--const project = program- .command("project")- .alias("p")- .description("Manage projects");--project- .command("active")- .description(`Print the currently active project, or null if none is open.`)- .action(() => activeProject());--project- .command("ls")- .alias("list")- .description(`List all projects, most recently accessed first.`)- .action(() => listProjects());--project- .command("create")- .description(`Create a new project and open it.`)- .argument("[name]", "optional project name")- .action((name?: string) => createProject(name));--project- .command("set")- .description(`Set the active project by id, opening it.`)- .argument("<id>", "project id to set active (null result if no project has this id)")- .action((id: string) => openProject(id));--project- .command("rm")- .alias("remove")- .description(`Delete a project by id.`)- .argument("<id>", "project id to delete")- .action((id: string) => deleteProject(id));-program.command("models").description(- `List available AI generation models and their per-model constraints (durations, aspect ratios, features), for \`generate.*\` asset declarations in a project module (there is no CLI generate command; generation happens on mount).`,+ `List available AI generation models and their per-model constraints (durations, aspect ratios, features), for \`generate.*\` asset declarations in a project module.`,).argument("[type]", `filter to one of "image", "video", "audio" (default: all three)`).action((type: string | undefined) => listModels(type));@@ -1612,7 +697,7 @@ programprogram.command("screenshot").description(- `Capture the entire application window as a PNG — the full UI as the user sees it (panels, timeline, asset library, canvas viewport), at the window's current size. The tool for checking what the app itself looks like; to render a node or scene cleanly for composition checks use \`node capture\` instead. Works even when the app was launched hidden (\`open --background\`).`,+ `Capture the entire application window as a PNG — the full UI as the user sees it (panels, timeline, asset library, canvas viewport), at the window's current size. The tool for checking what the app itself looks like; to render a node or scene cleanly for composition checks use \`capture\` instead.`,).option("-o, --output <dir>", "directory to write the PNG into (default: system temp dir)").action((opts: ScreenshotOptions) => appScreenshot(opts));@@ -1644,7 +729,7 @@ programprogram.command("fetch").description(- `Download a video with yt-dlp (installed separately; does not require the app). Writes files to disk only (a single URL can yield several, e.g. a playlist); pull one into the project afterwards with \`dapi asset add <path>\`.`,+ `Download a video with yt-dlp (installed separately; does not require the app). Writes files to disk only (a single URL can yield several, e.g. a playlist).`,).argument("<url>", "video or page URL to download").option("-o, --output <path>", "output file path or directory (yt-dlp -o template; default: yt-dlp's default)")diff --git a/apps/cli/src/open-folder.ts b/apps/cli/src/open-folder.tsdeleted file mode 100644index 598cd369..00000000--- a/apps/cli/src/open-folder.ts+++ /dev/null@@ -1,156 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";-import { readdir } from "node:fs/promises";-import { basename, extname, join } from "node:path";-import { editor } from "./cli-client";--const MARKER_FILENAME = ".dapi";-const MARKER_VERSION = 1;--// Asset extensions broadly aligned with the engine's media types. Used to-// filter recursive folder scans during `dapi open <folder>`.-const SUPPORTED_ASSET_EXTENSIONS: ReadonlySet<string> = new Set([- // images- ".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg", ".bmp", ".avif", ".heic", ".heif",- // video- ".mp4", ".webm", ".mov", ".m4v", ".mkv", ".avi",- // audio- ".mp3", ".wav", ".m4a", ".ogg", ".opus", ".flac", ".aac",-]);--type MarkerFile = {- version: number;- projectId: string;- createdAt: string;-};--type OpenFolderResult = {- project: { id: string; name: string };- created: boolean;- imported: number;-};--function readMarker(folderPath: string): MarkerFile | null {- const markerPath = join(folderPath, MARKER_FILENAME);- if (!existsSync(markerPath)) return null;- try {- const raw = readFileSync(markerPath, "utf8");- const parsed = JSON.parse(raw) as MarkerFile;- if (- typeof parsed !== "object" ||- parsed === null ||- typeof parsed.projectId !== "string" ||- parsed.projectId.length === 0- ) {- return null;- }- return parsed;- } catch {- return null;- }-}--function writeMarker(folderPath: string, projectId: string): void {- const marker: MarkerFile = {- version: MARKER_VERSION,- projectId,- createdAt: new Date().toISOString(),- };- writeFileSync(- join(folderPath, MARKER_FILENAME),- JSON.stringify(marker, null, 2),- );-}--type AssetDirectory = {- // Path segments relative to the import root; [] is the root itself.- segments: string[];- paths: string[];-};--async function collectSupportedAssets(folderPath: string) {- const results: AssetDirectory[] = [];-- async function walk(dir: string, segments: string[]): Promise<void> {- const entries = await readdir(dir, { withFileTypes: true });- const paths: string[] = [];- const subdirs: string[] = [];- for (const entry of entries) {- if (entry.isDirectory()) {- subdirs.push(entry.name);- continue;- }- if (!entry.isFile()) continue;- if (entry.name === MARKER_FILENAME && segments.length === 0) continue;- if (SUPPORTED_ASSET_EXTENSIONS.has(extname(entry.name).toLowerCase())) {- paths.push(join(dir, entry.name));- }- }- if (paths.length > 0) results.push({ segments, paths });- for (const name of subdirs) {- await walk(join(dir, name), [...segments, name]);- }- }-- await walk(folderPath, []);- return results;-}--async function ensureFolder(segments: string[], cache: Map<string, string>): Promise<string | undefined> {- if (segments.length === 0) return undefined; // the library root- const key = segments.join("/");- const cached = cache.get(key);- if (cached !== undefined) return cached;- const parentId = await ensureFolder(segments.slice(0, -1), cache);- const folder = await editor.folder.create.mutate({ name: segments[segments.length - 1]!, parentId });- cache.set(key, folder.id);- return folder.id;-}--async function waitForActiveProject(expectedId: string, timeoutMs = 10000): Promise<void> {- const start = Date.now();- while (Date.now() - start < timeoutMs) {- const active = await editor.project.active.query().catch(() => null);- if (active?.id === expectedId) return;- await new Promise((r) => setTimeout(r, 50));- }- throw new Error(`Timed out waiting for project ${expectedId} to become active`);-}--export async function openFolder(folderPath: string): Promise<OpenFolderResult> {- if (!existsSync(folderPath)) {- throw new Error(`Folder not found: ${folderPath}`);- }- if (!statSync(folderPath).isDirectory()) {- throw new Error(`Not a directory: ${folderPath}`);- }-- const marker = readMarker(folderPath);-- if (marker) {- const opened = await editor.project.open.mutate({ id: marker.projectId });- if (opened) {- await waitForActiveProject(opened.id);- return { project: opened, created: false, imported: 0 };- }- // Stale marker: fall through and run the first-time flow, overwriting it.- }-- const assetDirs = await collectSupportedAssets(folderPath);- const project = await editor.project.create.mutate({ name: basename(folderPath) });- await waitForActiveProject(project.id);-- let imported = 0;- const folderIds = new Map<string, string>();- for (const { segments, paths } of assetDirs) {- const folderId = await ensureFolder(segments, folderIds);- const results = await editor.asset.add.mutate({ paths, folderId });- imported += results.length;- }-- writeMarker(folderPath, project.id);- return { project, created: true, imported };-}diff --git a/apps/web/src/components/engine/api/assets.ts b/apps/web/src/components/engine/api/assets.tsindex 67fd257f..ca3b4169 100644--- a/apps/web/src/components/engine/api/assets.ts+++ b/apps/web/src/components/engine/api/assets.ts@@ -383,52 +383,6 @@ async function probeMediaMetadata(file: Blob, mimeType: string) {assert(false, 'Unsupported file type');}-/**- * Stores a compiled project module (the source a `dapi mount` executed) as a- * content-addressed SCRIPT asset, so any world can re-run it. The hash is a- * SHA-256 of the module text, so identical re-mounts dedup to one asset. The- * bytes live as a `.js` file in the same OPFS `assets` folder as any media.- */-export async function createScriptAsset(world: EngineWorld, code: string): Promise<Asset> {- const state = assetState(world);-- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(code));- const hash = 'script:' + Array.from(new Uint8Array(digest))- .map((b) => b.toString(16).padStart(2, '0'))- .join('');-- const existing = Array.from(world.assets.values()).find((asset) => asset.hash === hash);- if (existing) return existing;-- const id = allocateId(world);- const mimeType = 'text/javascript';- const uniqueName = id + mimeTypeToExtension(mimeType);-- const directory = await state.directoryHandle;- const assetsFolder = await directory.getDirectoryHandle('assets', { create: true });- const fileHandle = await assetsFolder.getFileHandle(uniqueName, { create: true });- const writable = await fileHandle.createWritable();- await writable.write(new Blob([code], { type: mimeType }));- await writable.close();-- const file = await fileHandle.getFile();-- return saveAsset(world, {- id,- hash,- createdAt: new Date().toISOString(),- lastModified: file.lastModified,- name: uniqueName,- mimeType,- size: file.size,- handle: fileHandle,- generationId: null,- generationKey: null,- folderId: null,- type: 'SCRIPT',- });-}-/*** Describes a local file as an ephemeral Asset: full metadata, but no id* allocation and no persistence — the library is never touched. The pathdiff --git a/apps/web/src/components/engine/api/engine.ts b/apps/web/src/components/engine/api/engine.tsindex 06e567cb..895936d7 100644--- a/apps/web/src/components/engine/api/engine.ts+++ b/apps/web/src/components/engine/api/engine.ts@@ -15,7 +15,6 @@ import { inputSystem } from '../systems/input-system';import { createCameraController } from '../systems';import { hudSystem } from '../systems/hud';import { createKeyboardSystem } from '../systems/keyboard';-import { realizeMounts } from '@/utils/mount';import { createSignal } from 'solid-js';import type Stats from 'stats.js';@@ -43,7 +42,6 @@ export function createEngine(id: string) {keyboard.init();await restoreWorld(world);- await realizeMounts(world);const c = world.components;// Auto-select the first scene as the active timelinediff --git a/apps/web/src/components/engine/encode/encoder.ts b/apps/web/src/components/engine/encode/encoder.tsindex f500246f..aafb10bb 100644--- a/apps/web/src/components/engine/encode/encoder.ts+++ b/apps/web/src/components/engine/encode/encoder.ts@@ -27,7 +27,6 @@ import { renderSystem } from '../systems/render';import { cloneFromRecords, serializeEntity } from '../api/serialize';import { getEntityTree } from '../api/query';import { AudioBus } from '../services/audio-bus';-import { realizeMounts } from '@/utils/mount';import type { EngineWorld } from '../api/world';import type { EncoderConfig } from './interfaces';@@ -128,11 +127,6 @@ export async function createEncoder(sourceWorld: EngineWorld, config: EncoderConc.AudioPlayback.contextOffsetInSeconds[sceneEid] = 0;c.AudioPlayback.timelineOffsetInSeconds[sceneEid] = playheadStartSeconds;- // Re-execute any mounts into this offline world so it owns its own reactive- // graphs + runtime hosts (surface/html). The per-frame playbackSystem then- // drives them via world.liveMounts, so ticker-animated surfaces render.- const mounts = videoEnabled ? await realizeMounts(world) : null;-// Set up mediabunny outputconst buffer = await TargetBuffer.create(config.target);const format = await createOutputFormat(buffer, config.format);@@ -334,10 +328,6 @@ export async function createEncoder(sourceWorld: EngineWorld, config: EncoderCon};} finally {URL.revokeObjectURL(audioWorkletUrl);- // Free the graphs + hosts realized above (this offline world is- // discarded, so nothing else disposes them — an HtmlHost otherwise- // leaks a canvas on document.body).- mounts?.disposeAll();}};diff --git a/apps/web/src/components/engine/encode/image-encoder.ts b/apps/web/src/components/engine/encode/image-encoder.tsindex 38d251f9..cb44003e 100644--- a/apps/web/src/components/engine/encode/image-encoder.ts+++ b/apps/web/src/components/engine/encode/image-encoder.ts@@ -16,7 +16,6 @@ import { transformSystem } from '../systems/transform';import { renderSystem } from '../systems/render';import { cloneFromRecords, serializeEntity } from '../api/serialize';import { getEntityTree } from '../api/query';-import { realizeMounts } from '@/utils/mount';import { framesToSeconds, formatTimecode } from '../utils';import { assert } from '@/utils';@@ -84,8 +83,6 @@ export async function createImageEncoder(sourceWorld: EngineWorld, config: Imageconst rootEid = eidMap.get(config.eid);assert(rootEid !== undefined, 'Failed to clone entity subtree');- const mounts = await realizeMounts(world);-const clonedEids = [...eidMap.values()];const c = world.components;@@ -219,10 +216,6 @@ export async function createImageEncoder(sourceWorld: EngineWorld, config: Imagetype: 'error',error: e instanceof Error ? e : new Error('Unknown error'),};- } finally {- // Free the graphs + hosts realized above (this offline world is- // discarded; realized HtmlHosts otherwise leak a canvas on document.body).- mounts.disposeAll();}};diff --git a/apps/web/src/components/engine/utils/live-mounts.ts b/apps/web/src/components/engine/utils/live-mounts.tsindex 97961708..7caadf68 100644--- a/apps/web/src/components/engine/utils/live-mounts.ts+++ b/apps/web/src/components/engine/utils/live-mounts.ts@@ -3,7 +3,7 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. *//**- * JSX mounts (`dapi mount`) keep their Solid reactive graph running after+ * JSX mounts keep their Solid reactive graph running after* the mount lands, so signals, effects, and timers keep driving the mounted* entities. A run stays alive until the world is* disposed or a later mount claims one of its root keys: the keyed rootdiff --git a/apps/web/src/context/dapi/api.tsx b/apps/web/src/context/dapi/api.tsxindex 21e3aafd..9418550e 100644--- a/apps/web/src/context/dapi/api.tsx+++ b/apps/web/src/context/dapi/api.tsx@@ -3,19 +3,13 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { createEffect, createContext, useContext, onCleanup, onMount, createResource } from "solid-js";-import { useSearchParams } from "@solidjs/router";import { useEngine } from '@/context/engine';import { useProjectId } from '@/hooks/use-project-id';import { useAuth } from '@/context/auth';-import { t, q, m, q0, m0 } from "@/lib/cli-rpc";+import { t, q, q0 } from "@/lib/cli-rpc";import { handleContextGet } from "./context";-import { handleAssetsAdd, handleAssetsList, handleAssetTree, handleAssetsDelete, handleAssetsMove, handleAssetsExport } from "./assets";import { handleMediaProbe, handleMediaFrame, handleMediaTranscribe, handleMediaFilmstrip, handleMediaWaveform, handleMediaListen } from "./media";-import { handleFoldersList, handleFolderCreate, handleFolderRename, handleFoldersMove, handleFoldersDelete } from "./folders";-import { handleSelectionFocus, handleSelectionList, handleSelectionSet } from "./selection";-import { handleNodeList, handleNodeTree, handleNodeGrep, handleNodeCapture, handleNodeDelete, handleNodePatch, handleNodeDuplicate, handleNodeRender } from "./node";-import { handleMount, handleNodeInsert } from "./mount";-import { handleProjectActive, handleProjectList, handleProjectCreate, handleProjectDelete, handleProjectOpen } from "./project";+import { handleCapture } from "./capture";import { handleLogs } from "./logs";import { handleModels } from "./models";import { handleVoices } from "./voices";@@ -44,7 +38,6 @@ export function EditorApiProvider(props: EditorApiProviderProps) {const projectId = useProjectId();const engine = useEngine();const auth = useAuth();- const [, setParams] = useSearchParams();const [isFullscreen, { mutate }] = createResource(handleGetFullscreenState, { initialValue: false });const requireAuth = <I, O>(fn: (data: I) => Promise<O>) => (data: I) => {@@ -73,7 +66,7 @@ export function EditorApiProvider(props: EditorApiProviderProps) {if (!window.desktop || !engine.initialized() || projectId() !== engine.world.projectId) return;- const router = createAppRouter({ getEngine, getUser, requireAuth, setParams });+ const router = createAppRouter({ getEngine, getUser, requireAuth });onCleanup(cliBridge.register(createRouterCaller(router)));});@@ -94,27 +87,18 @@ type AppRouterDeps = {getEngine: () => Engine;getUser: () => User;requireAuth: <I, O>(fn: (data: I) => Promise<O>) => (data: I) => Promise<O>;- setParams: ReturnType<typeof useSearchParams>[1];};-function createAppRouter({ getEngine, getUser, requireAuth, setParams }: AppRouterDeps) {+function createAppRouter({ getEngine, getUser, requireAuth }: AppRouterDeps) {return t.router({ping: t.procedure.query(() => {}),whoami: t.procedure.query(() => getUser()),context: q0(handleContextGet(getEngine)),- mount: m(handleMount(getEngine)),+ capture: q(handleCapture(getEngine)),models: q(handleModels()),logs: q(handleLogs()),screenshot: q0(handleWindowScreenshot()),voices: q0(handleVoices()),- asset: t.router({- add: m(handleAssetsAdd(getEngine)),- list: q(handleAssetsList(getEngine)),- tree: q(handleAssetTree(getEngine)),- delete: m(handleAssetsDelete(getEngine)),- move: m(handleAssetsMove(getEngine)),- export: m(handleAssetsExport(getEngine)),- }),media: t.router({probe: q(handleMediaProbe(getEngine)),frame: q(handleMediaFrame(getEngine)),@@ -123,36 +107,6 @@ function createAppRouter({ getEngine, getUser, requireAuth, setParams }: AppRoutwaveform: q(handleMediaWaveform(getEngine)),listen: q(requireAuth(handleMediaListen(getEngine))),}),- folder: t.router({- list: q(handleFoldersList(getEngine)),- create: m(handleFolderCreate(getEngine)),- rename: m(handleFolderRename(getEngine)),- move: m(handleFoldersMove(getEngine)),- delete: m(handleFoldersDelete(getEngine)),- }),- selection: t.router({- list: q0(handleSelectionList(getEngine)),- set: m(handleSelectionSet(getEngine)),- focus: m0(handleSelectionFocus(getEngine)),- }),- node: t.router({- list: q(handleNodeList(getEngine)),- tree: q(handleNodeTree(getEngine)),- grep: q(handleNodeGrep(getEngine)),- capture: q(handleNodeCapture(getEngine)),- insert: m(handleNodeInsert(getEngine)),- delete: m(handleNodeDelete(getEngine)),- patch: m(handleNodePatch(getEngine)),- duplicate: m(handleNodeDuplicate(getEngine)),- render: m(handleNodeRender(getEngine)),- }),- project: t.router({- active: q0(handleProjectActive(getEngine)),- list: q0(handleProjectList()),- create: m(handleProjectCreate(getEngine, setParams)),- delete: m(handleProjectDelete(getEngine, setParams)),- open: m(handleProjectOpen(getEngine, setParams)),- }),});}diff --git a/apps/web/src/context/dapi/assets.ts b/apps/web/src/context/dapi/assets.tsdeleted file mode 100644index bdbcc036..00000000--- a/apps/web/src/context/dapi/assets.ts+++ /dev/null@@ -1,212 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { ElectronFileHandle } from '@/lib/electron-file-handle';-import { ElectronWritableFileHandle } from '@/lib/electron-file-writable';-import { loadAsset, removeAsset, getAssetFile } from '@/components/engine';-import { assert, mimeTypeToExtension } from '@/utils';-import {- assetFolderId,- moveAssetsToFolder,- useFolders,-} from '@/components/engine';--import type { Engine } from "@/components/engine";-import type { Asset } from "@/components/engine/db";-import type { AssetExportResult, AssetMoveResult, AssetRecord, AssetsExportRequest, AssetTreeEntry } from "@diffusionstudio/cli/channels";-import type { Accessor } from "solid-js";--export function handleAssetsAdd(engine: Accessor<Engine>) {- return async ({ paths, folderId }: { paths: string[]; folderId?: string }): Promise<AssetRecord[]> => {- const { world } = engine();- if (folderId !== undefined) {- assert(world.folders.has(folderId), `Folder ${folderId} not found.`);- }- const assets = await Promise.all(- paths.map(async (path) => {- try {- return await loadAsset(world, new ElectronFileHandle(path), { folderId });- } catch (e) {- throw new Error(`${path}: ${(e as Error)?.message ?? String(e)}`);- }- })- );- return assets.map(toAssetRecord);- }-}--/**- * The persisted asset record minus the props that can't cross the wire- */-function toAssetRecord(asset: Asset): AssetRecord {- const record: Record<string, unknown> = { ...asset };- delete record.handle;- delete record.directoryHandle;- delete record.hash;- delete record.transcript;- return record as AssetRecord;-}--export function handleAssetsList(engine: Accessor<Engine>) {- return async ({ ids }: { ids?: string[] }): Promise<AssetRecord[]> => {- const { world } = engine();-- // No ids → every asset in the library- if (ids === undefined || ids.length === 0) {- return Array.from(world.assets.values()).map(toAssetRecord);- }-- return resolveAssets(world, ids).map(toAssetRecord);- };-}--function resolveAssets(world: Engine["world"], ids: string[]): Asset[] {- return ids.map((id) => {- const asset = world.assets.get(id);- assert(asset, `No such asset: ${id}`);- return asset;- });-}--export function handleAssetTree(engine: Accessor<Engine>) {- return async ({ folderId, depth }: { folderId?: string; depth?: number }): Promise<AssetTreeEntry[]> => {- const { world } = engine();- if (folderId !== undefined) {- assert(world.folders.has(folderId), `Folder ${folderId} not found.`);- }-- const { childrenOf } = useFolders(world);- const assets = Array.from(world.assets.values());-- // Visited set guards against parentId cycles in corrupt data.- const visited = new Set<string>();- const entries = (parentId: string | null, remaining: number | undefined): AssetTreeEntry[] => {- const folderEntries = childrenOf(parentId)- .filter((folder) => !visited.has(folder.id))- .map((folder) => {- visited.add(folder.id);- const next = remaining === undefined ? undefined : remaining - 1;- const children = next === undefined || next > 0 ? entries(folder.id, next) : [];- return {- id: folder.id,- name: folder.name,- type: "folder",- ...(children.length > 0 && { children }),- };- });- const assetEntries = assets- .filter((asset) => assetFolderId(world, asset) === parentId)- .map((asset) => ({ id: asset.id, name: asset.name, type: asset.type }));- return [...folderEntries, ...assetEntries];- };-- return entries(folderId ?? null, depth);- }-}--export function handleAssetsMove(engine: Accessor<Engine>) {- return async ({ ids, to }: { ids: string[]; to?: string }): Promise<AssetMoveResult[]> => {- const { world } = engine();- if (to !== undefined) {- assert(world.folders.has(to), `Folder ${to} not found.`);- }- const folderId = to ?? null;- resolveAssets(world, ids);- await moveAssetsToFolder(world, ids, folderId);- return ids.map((id) => ({ id, folderId }));- }-}--export function handleAssetsDelete(engine: Accessor<Engine>) {- return async ({ ids }: { ids: string[] }): Promise<Array<{ id: string; name: string }>> => {- const { world } = engine();- const results = resolveAssets(world, ids).map((asset) => ({ id: asset.id, name: asset.name }));- await removeAsset(world, ...ids);- return results;- }-}--export function handleAssetsExport(engine: Accessor<Engine>) {- return async ({ ids, output, isDir }: AssetsExportRequest): Promise<AssetExportResult[]> => {- const { world } = engine();- const assets = resolveAssets(world, ids);- for (const asset of assets) {- assert(asset.type !== "SEQUENCE", `Asset ${asset.id} is an image sequence; export is not supported.`);- }- const results: AssetExportResult[] = [];- for (const asset of assets) {- const blob = await getAssetFile(asset);- const path = isDir- ? await streamBlobToDir(blob, output, exportFileName(asset))- : await streamBlobToFile(blob, output);- results.push({ id: asset.id, path });- }- return results;- };-}--/**- * Strips characters that are path separators or invalid on Windows- */-function exportFileName(asset: Asset): string {- // eslint-disable-next-line no-control-regex -- control chars are stripped deliberately- const sanitized = asset.name.replace(/[\\/:*?"<>|\u0000-\u001f]/g, "_").trim();- const name = sanitized || asset.id;- return /\.[^.\s]{1,8}$/.test(name) ? name : name + mimeTypeToExtension(asset.mimeType);-}--const MAX_UNIQUIFY = 1000;--async function streamBlobToDir(blob: Blob, dir: string, fileName: string): Promise<string> {- // Joining with "/" is safe on Windows too — node's fs accepts it.- const base = dir.replace(/[\\/]+$/, "");- const dot = fileName.lastIndexOf(".");- const stem = dot > 0 ? fileName.slice(0, dot) : fileName;- const ext = dot > 0 ? fileName.slice(dot) : "";- for (let n = 0; n < MAX_UNIQUIFY; n++) {- const path = `${base}/${n === 0 ? fileName : `${stem} (${n})${ext}`}`;- const handle = new ElectronWritableFileHandle(path);- let writable: WritableStream;- try {- writable = await handle.createWritable({ exclusive: true });- } catch (e) {- if (/EEXIST/.test((e as Error)?.message ?? "")) continue; // name taken — try the next suffix- throw e;- }- await pumpBlob(blob, writable, handle);- return path;- }- throw new Error(`Could not find a free file name for "${fileName}" in ${base}.`);-}--async function streamBlobToFile(blob: Blob, path: string): Promise<string> {- const handle = new ElectronWritableFileHandle(path);- await pumpBlob(blob, await handle.createWritable(), handle);- return path;-}--/**- * Streams the blob chunk-by-chunk to the open writable- */-async function pumpBlob(- blob: Blob,- writable: WritableStream,- handle: ElectronWritableFileHandle,-): Promise<void> {- const writer = writable.getWriter();- const reader = blob.stream().getReader();- let position = 0;- try {- for (; ;) {- const { done, value } = await reader.read();- if (done) break;- await writer.write({ type: "write", data: value, position });- position += value.byteLength;- }- await writer.close();- } catch (e) {- await handle.dispose().catch(() => { });- throw e;- }-}diff --git a/apps/web/src/context/dapi/capture.ts b/apps/web/src/context/dapi/capture.tsnew file mode 100644index 00000000..32ea9a11--- /dev/null+++ b/apps/web/src/context/dapi/capture.ts@@ -0,0 +1,113 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { entityExists, hasComponent } from "bitecs";++import { createImageEncoder } from "@/components/engine/encode/image-encoder";++import {+ getSceneAncestor,+ composeSheet,+ decodePngBase64,+ planSheet,+ planSheetSizes,+ sheetTimecode,+} from "@/components/engine";++import type { EngineWorld, Engine } from "@/components/engine";+import type { CaptureRequest, CaptureResult, TimecodedImage } from "@diffusionstudio/cli/channels";+import type { Accessor } from "solid-js";++// Scenes are nodes too, so capture accepts them alongside geometry, groups,+// and adjustment layers.+function isNode(world: EngineWorld, eid: number): boolean {+ const c = world.components;+ return (+ hasComponent(world, eid, c.Geometry) ||+ hasComponent(world, eid, c.Group) ||+ hasComponent(world, eid, c.AdjustmentLayer) ||+ hasComponent(world, eid, c.Scene)+ );+}++function resolveNodeEid(world: EngineWorld, eid: number): number {+ if (+ !Number.isInteger(eid) ||+ !entityExists(world, eid) ||+ hasComponent(world, eid, world.components.Deleted) ||+ !isNode(world, eid)+ ) {+ throw new Error(`No such node: ${eid}`);+ }+ return eid;+}++// Ceiling on the height a sheet cell renders a node at.+const SHEET_CAPTURE_HEIGHT = 1080;++export function handleCapture(engine: Accessor<Engine>) {+ return async ({ id, frames, combine = true, perSheet }: CaptureRequest): Promise<CaptureResult> => {+ const e = engine();+ const w = e.world;++ const eid = resolveNodeEid(w, id);++ if (!hasComponent(w, eid, w.components.Playback)) {+ const scene = getSceneAncestor(w, eid);+ const hint = scene !== null ? ` Capture its scene (id ${scene}) instead.` : "";+ throw new Error(+ `Node ${id} has no timeline clock and cannot be captured on its own.${hint}`,+ );+ }++ // `undefined` means the node's first visible frame (the encoder's frame 0).+ let shots = frames;+ if (shots === undefined || shots.length === 0) {+ shots = [0];+ }++ const encoder = await createImageEncoder(w, {+ eid,+ frames: shots,+ resolution: 720,+ });++ // Sheets render at their cell size instead of the flat 720p: with a few+ // frames that is sharper than a standalone capture, never coarser. A node+ // is drawn, not decoded, so a small one is worth rendering past its own+ // bounds; beyond SHEET_CAPTURE_HEIGHT that only costs tokens.+ const aspect = encoder.bounds.width / encoder.bounds.height;+ const height = Math.max(encoder.bounds.height, SHEET_CAPTURE_HEIGHT);+ const sizes = combine ? planSheetSizes(shots.length, perSheet) : [];+ const plans = sizes.map((n) => planSheet(n, { width: height * aspect, height }));+ if (combine) {+ encoder.resize(Math.max(...plans.map((plan) => plan.cellHeight)));+ }++ const result = await encoder.render();++ if (result.type === "canceled") throw new Error("Capture canceled");+ if (result.type === "error") throw result.error;++ if (!combine) return result.data;++ const sheets: TimecodedImage[] = [];+ let offset = 0;+ for (const [sheet, size] of sizes.entries()) {+ const group = result.data.slice(offset, offset + size);+ const cells = group.map(({ timecode }, k) => ({ at: shots[offset + k], timecode }));+ offset += size;+ const images = await Promise.all(group.map((image) => decodePngBase64(image.base64)));+ sheets.push({+ timecode: sheetTimecode(cells),+ base64: composeSheet(+ images.map((image, k) => ({ image, label: group[k].timecode })),+ plans[sheet],+ ),+ });+ for (const image of images) image.close();+ }+ return sheets;+ };+}diff --git a/apps/web/src/context/dapi/context.ts b/apps/web/src/context/dapi/context.tsindex 18fea80d..5077ff9e 100644--- a/apps/web/src/context/dapi/context.ts+++ b/apps/web/src/context/dapi/context.ts@@ -3,12 +3,16 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { ChildOf } from "@/components/engine/components";-import { getAllEntities, hasComponent, Not, query } from "bitecs";-import { selectedNodeIds } from "./selection";+import { getAllEntities, hasComponent, Not, Or, query } from "bitecs";-import type { Engine } from "@/components/engine";+import type { Engine, EngineWorld } from "@/components/engine";import type { Accessor } from "solid-js";+function selectedNodeIds(world: EngineWorld): number[] {+ const c = world.components;+ return [...query(world, [c.Selected, Or(c.Geometry, c.Group, c.AdjustmentLayer), Not(c.Deleted)])];+}+export function handleContextGet(engine: Accessor<Engine>) {return async () => {const { world } = engine();diff --git a/apps/web/src/context/dapi/folders.ts b/apps/web/src/context/dapi/folders.tsdeleted file mode 100644index 51545a87..00000000--- a/apps/web/src/context/dapi/folders.ts+++ /dev/null@@ -1,90 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { assert } from '@/utils';-import {- createFolder,- deleteFolder,- isDescendantFolder,- moveFolder,- renameFolder,- useFolders,-} from '@/components/engine';--import type { Engine } from "@/components/engine";-import type { FolderDeleteResult, FolderInfo, FolderMoveResult } from "@diffusionstudio/cli/channels";-import type { Accessor } from "solid-js";--const toWire = (folder: { id: string; name: string }): FolderInfo => ({- id: folder.id,- name: folder.name,- type: "folder",-});--export function handleFoldersList(engine: Accessor<Engine>) {- return async ({ parentId }: { parentId?: string }): Promise<FolderInfo[]> => {- const { world } = engine();- if (parentId !== undefined) {- assert(world.folders.has(parentId), `Folder ${parentId} not found.`);- }- return useFolders(world).childrenOf(parentId ?? null).map(toWire);- }-}--export function handleFolderCreate(engine: Accessor<Engine>) {- return async ({ name, parentId }: { name: string; parentId?: string }): Promise<FolderInfo> => {- const { world } = engine();- if (parentId !== undefined) {- assert(world.folders.has(parentId), `Folder ${parentId} not found.`);- }- const folder = await createFolder(world, name, parentId ?? null);- return toWire(folder);- }-}--export function handleFolderRename(engine: Accessor<Engine>) {- return async ({ id, name }: { id: string; name: string }): Promise<FolderInfo> => {- const { world } = engine();- assert(world.folders.has(id), `Folder ${id} not found.`);- await renameFolder(world, id, name);- return toWire(world.folders.get(id)!);- }-}--export function handleFoldersMove(engine: Accessor<Engine>) {- return async ({ ids, to }: { ids: string[]; to?: string }): Promise<FolderMoveResult[]> => {- const { world } = engine();- if (to !== undefined) {- assert(world.folders.has(to), `Folder ${to} not found.`);- }- const parentId = to ?? null;- // Validate every move before applying any, so a bad id changes nothing.- for (const id of ids) {- assert(world.folders.has(id), `No such folder: ${id}`);- assert(- parentId === null || (parentId !== id && !isDescendantFolder(world, parentId, id)),- `Cannot move folder ${id} into itself or one of its descendants`,- );- }- for (const id of ids) {- await moveFolder(world, id, parentId);- }- return ids.map((id) => ({ id, parentId }));- }-}--export function handleFoldersDelete(engine: Accessor<Engine>) {- return async ({ ids }: { ids: string[] }): Promise<FolderDeleteResult[]> => {- const { world } = engine();- for (const id of ids) {- assert(world.folders.has(id), `No such folder: ${id}`);- }- const results: FolderDeleteResult[] = [];- for (const id of ids) {- const { deletedFolders, deletedAssets } = await deleteFolder(world, id);- results.push({ id, deletedFolders, deletedAssets });- }- return results;- }-}diff --git a/apps/web/src/context/dapi/mount.ts b/apps/web/src/context/dapi/mount.tsdeleted file mode 100644index 34d01186..00000000--- a/apps/web/src/context/dapi/mount.ts+++ /dev/null@@ -1,135 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { renderProject } from "@diffusionstudio/jsx";-import { nanoid } from "nanoid";--import { reorderEntity, switchActiveScene } from "@/components/engine";-import { createScriptAsset } from "@/components/engine/api/assets";-import { WorldDocument, importProjectModule } from "@/utils/jsx";-import { documentRootKeys } from "@/utils/mount";-import { assert } from "@/utils";-import { resolveEntityEid } from "./node";-import { hasComponent } from "bitecs";--import type { Accessor } from "solid-js";-import type { MountRequest, NodeInsertRequest } from "@diffusionstudio/cli/channels";-import type { Engine } from "@/components/engine";--/**- * `dapi mount` — evaluates a compiled project module and renders it directly into the ECS world- */-export function handleMount(engine: Accessor<Engine>) {- return async ({ code }: MountRequest): Promise<void> => {- const e = engine();- const world = e.world;- const c = world.components;- let dispose = () => { };- let registered = false;-- try {- // Evaluate — top-level code (including top-level await) runs here.- const module = await importProjectModule(code);- const project = module.default as () => unknown;- assert(typeof project === "function", "The project module must default-export a Solid component");-- // Persist the compiled module as a content-addressed SCRIPT asset so any- // world (export, capture, reload) can re-run it in adopt mode. `mountId`- // ties every entity of this mount together for that re-run.- const scriptAsset = await createScriptAsset(world, code);- const mountId = nanoid();-- const document = new WorldDocument(world, {- engine: e,- mode: "author",- mountId,- scriptAssetId: scriptAsset.id,- });-- try {- world.history.startTransaction("Render project");- dispose = renderProject(project, document);- world.history.commitTransaction();- } catch (error) {- world.history.rollbackTransaction();- throw error;- }-- // The keyed root replacement above deleted any same-key entities, so- // graphs that were driving them are dead; dispose them before their- // next effect can write to a recycled entity id.- world.liveMounts.supersede(documentRootKeys(world, document));-- try {- world.history.startTransaction("Commit document");- await document.commit();- } finally {- world.history.commitTransaction();- }-- // A mount always stays live: its reactive graph keeps driving the- // entities until a later mount claims a root key or the app closes.- world.liveMounts.register({- mountId,- rootKeys: () => documentRootKeys(world, document),- advance: () => document.advanceTicker(),- dispose,- });- registered = true;-- if (document.rootEid && hasComponent(world, document.rootEid, c.Scene)) {- switchActiveScene(world, document.rootEid);- e.camera.fitToActiveScene();- }- } finally {- // Only the error path (before registration) needs to dispose the graph.- if (!registered) dispose?.();- }- };-}--/**- * `dapi node insert` — the mount pipeline, but rendered into an existing- * parent entity instead of the document: roots take no key, nothing is- * reconciled or deleted, every run inserts fresh entities. The parent may be- * any live entity that takes children — a node, or a gradient paint for- * `<ColorStop>` roots.- */-export function handleNodeInsert(engine: Accessor<Engine>) {- return async ({ code, parentId, index }: NodeInsertRequest): Promise<void> => {- const e = engine();- const world = e.world;- let dispose = () => { };-- try {- const parentEid = resolveEntityEid(world, parentId);- const module = await importProjectModule(code);- const project = module.default as () => unknown;- assert(typeof project === "function", "The project module must default-export a Solid component");-- const document = new WorldDocument(e.world, { parentEid, engine: e });-- try {- world.history.startTransaction("Insert nodes");- dispose = renderProject(project, document);- if (index !== undefined && document.rootEid !== null) {- reorderEntity(world, document.rootEid, index);- }- world.history.commitTransaction();- } catch (error) {- world.history.rollbackTransaction();- throw error;- }-- try {- world.history.startTransaction("Commit document");- await document.commit();- } finally {- world.history.commitTransaction();- }- } finally {- dispose?.();- }- };-}diff --git a/apps/web/src/context/dapi/node.ts b/apps/web/src/context/dapi/node.tsdeleted file mode 100644index f015cba6..00000000--- a/apps/web/src/context/dapi/node.ts+++ /dev/null@@ -1,480 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { entityExists, hasComponent, query, Not } from "bitecs";--import { createImageEncoder } from "@/components/engine/encode/image-encoder";-import { ElectronWritableFileHandle } from "@/lib/electron-file-writable";-import { renderScene } from "@/context/render";--import {- AnimationPhase,- deleteEntity,- isText,- isScene,- getSceneAncestor,- getEntityTree,- cloneSubtree,- serializeEntity,- composeSheet,- decodePngBase64,- planSheet,- planSheetSizes,- sheetTimecode,-} from "@/components/engine";-import { ChildOf } from "@/components/engine/components";-import { ANIMATION_TYPE_MAP, CAPTION_ALIGN_MAP, WorldDocument } from "@/utils/jsx";-import { entityType } from "./selection";--import type { EngineWorld, Engine } from "@/components/engine";-import type {- EntityRecord,- NodeDeleteResult,- NodeDuplicateResult,- NodeGrepMatch,- NodeGrepRequest,- NodeGrepResult,- NodePatch,- NodePatchResult,- NodeRef,- NodeTree,- NodeRenderRequest,- NodeRenderResult,- NodeCaptureRequest,- NodeCaptureResult,- TimecodedImage,-} from "@diffusionstudio/cli/channels";-import type { EncoderConfig } from "@/components/engine/encode/interfaces";-import type { Accessor } from "solid-js";--// The JSX animation names, keyed by engine preset.-const ANIMATION_TYPE_NAMES: Record<number, string> = Object.fromEntries(- Object.entries(ANIMATION_TYPE_MAP).map(([name, type]) => [type, name]),-);--// The JSX caption alignment names, keyed by engine enum.-const CAPTION_ALIGN_NAMES: Record<number, string> = Object.fromEntries(- Object.entries(CAPTION_ALIGN_MAP).map(([name, align]) => [align, name]),-);--// Scenes are nodes too, so node ops accept them alongside geometry, groups,-// and adjustment layers.-export function isNode(world: EngineWorld, eid: number): boolean {- const c = world.components;- return (- hasComponent(world, eid, c.Geometry) ||- hasComponent(world, eid, c.Group) ||- hasComponent(world, eid, c.AdjustmentLayer) ||- hasComponent(world, eid, c.Scene)- );-}--// Any live entity — `ls`, `tree`, `rm`, `patch`, and `insert` also target-// paints and color stops, which are sub-entities rather than nodes.-export function resolveEntityEid(world: EngineWorld, eid: number): number {- if (- !Number.isInteger(eid) ||- !entityExists(world, eid) ||- hasComponent(world, eid, world.components.Deleted)- ) {- throw new Error(`No such entity: ${eid}`);- }- return eid;-}--export function resolveNodeEid(world: EngineWorld, eid: number): number {- resolveEntityEid(world, eid);- if (!isNode(world, eid)) {- throw new Error(`No such node: ${eid}`);- }- return eid;-}--export function handleNodeList(engine: Accessor<Engine>) {- return async ({ ids }: { ids?: number[] }): Promise<EntityRecord[]> => {- const { world } = engine();- const c = world.components;-- // No ids → the root: top-level nodes- if (ids === undefined || ids.length === 0) {- const roots = [...query(world, [c.Geometry, Not(ChildOf("*")), Not(c.Deleted)])];- return roots.map((eid) => serializeEntity(world, eid) as EntityRecord);- }-- return ids.map((id) => serializeEntity(world, resolveEntityEid(world, id)) as EntityRecord);- };-}--/**- * Key characteristics of an entity, from whatever components it carries —- * e.g. "hidden; size: 200x300; text: Hello World". Times print as seconds.- */-function describeEntity(world: EngineWorld, eid: number): string {- const c = world.components;- const parts: string[] = [];- const fmtTime = (frames: number) => `${Math.round((frames / world.frameRate) * 100) / 100}s`;- const hex = (packed: number) => `#${((packed >>> 0) & 0xffffff).toString(16).padStart(6, "0")}`;-- if (hasComponent(world, eid, c.Hidden)) parts.push("hidden");- if (hasComponent(world, eid, c.Size)) {- parts.push(`size: ${c.Size.width[eid] ?? 0}x${c.Size.height[eid] ?? 0}`);- }- if (hasComponent(world, eid, c.Position)) {- const x = c.Position.x[eid] ?? 0;- const y = c.Position.y[eid] ?? 0;- if (x !== 0 || y !== 0) parts.push(`pos: ${x},${y}`);- }- if (hasComponent(world, eid, c.Offset)) {- const x = c.Offset.x[eid] ?? 0;- const y = c.Offset.y[eid] ?? 0;- if (x !== 0 || y !== 0) parts.push(`offset: ${x},${y}`);- }- if (hasComponent(world, eid, c.Rotation) && c.Rotation[eid]) {- parts.push(`rotation: ${c.Rotation[eid]}°`);- }- if (hasComponent(world, eid, c.CornerRadius) && c.CornerRadius[eid]) {- parts.push(`cornerRadius: ${c.CornerRadius[eid]}`);- }- if (hasComponent(world, eid, c.Appearance)) {- const opacity = c.Appearance.opacity[eid];- if (opacity !== undefined && opacity !== 1) parts.push(`opacity: ${opacity}`);- }- const delay = hasComponent(world, eid, c.Delay) ? c.Delay[eid] ?? 0 : 0;- const hasTrim = hasComponent(world, eid, c.Trim);- const sourceIn = hasTrim ? c.Trim.start[eid] : undefined;- const sourceOut = hasTrim ? c.Trim.end[eid] : undefined;- const timelineStart = delay + (sourceIn ?? 0);- if (timelineStart !== 0) parts.push(`start: ${fmtTime(timelineStart)}`);- if (sourceOut !== undefined) parts.push(`end: ${fmtTime(delay + sourceOut)}`);- if (sourceIn) parts.push(`sourceIn: ${fmtTime(sourceIn)}`);- if (sourceIn && sourceOut !== undefined) parts.push(`sourceOut: ${fmtTime(sourceOut)}`);- if (hasComponent(world, eid, c.Volume)) {- const db = c.Volume[eid] ?? 0;- parts.push(`volume: ${db === -Infinity ? "-inf" : Math.round(db * 10) / 10} dB`);- }- if (hasComponent(world, eid, c.AssetId)) parts.push(`asset: ${c.AssetId[eid]}`);- if (hasComponent(world, eid, c.Caption)) {- const align = c.Caption.verticalAlign[eid];- if (align !== undefined) parts.push(`verticalAlign: ${CAPTION_ALIGN_NAMES[align]}`);- }- if (hasComponent(world, eid, c.TextStyle)) {- const family = c.TextStyle.fontFamily[eid];- const size = c.TextStyle.fontSize[eid];- const font = [family, size !== undefined ? `${size}px` : undefined].filter(Boolean).join(" ");- if (font) parts.push(`font: ${font}`);- }- if (hasComponent(world, eid, c.Color)) parts.push(`color: ${hex(c.Color[eid] ?? 0)}`);- if (hasComponent(world, eid, c.ColorStop)) {- const offset = c.ColorStop.offset[eid];- const color = c.ColorStop.color[eid];- const opacity = c.ColorStop.opacity[eid];- if (offset !== undefined) parts.push(`offset: ${offset}`);- if (color !== undefined) parts.push(`color: ${hex(color)}`);- if (opacity !== undefined && opacity !== 1) parts.push(`opacity: ${opacity}`);- }- if (hasComponent(world, eid, c.StrokeStyle) && c.StrokeStyle.width[eid] !== undefined) {- parts.push(`width: ${c.StrokeStyle.width[eid]}`);- }- if (hasComponent(world, eid, c.KeyframeTrack)) {- parts.push(`property: ${c.KeyframeTrack.property[eid]}`);- }- if (hasComponent(world, eid, c.Keyframe)) {- parts.push(`time: ${fmtTime(c.Keyframe.time[eid] ?? 0)}`, `value: ${c.Keyframe.value[eid]}`);- if (c.Keyframe.easing[eid]) parts.push(`easing: ${c.Keyframe.easing[eid]}`);- }- if (hasComponent(world, eid, c.Animation)) {- parts.push(- `type: ${ANIMATION_TYPE_NAMES[c.Animation.type[eid] ?? 0] ?? c.Animation.type[eid]}`,- `phase: ${c.Animation.phase[eid] === AnimationPhase.OUT ? "out" : "in"}`,- `duration: ${fmtTime(c.Animation.duration[eid] ?? 0)}`,- );- if (c.Animation.delay[eid]) parts.push(`delay: ${fmtTime(c.Animation.delay[eid])}`);- }- if (hasComponent(world, eid, c.TextRange)) {- parts.push(`range: ${c.TextRange.start[eid] ?? 0}–${c.TextRange.end[eid] ?? "end"}`);- }- if (isText(world, eid)) {- const text = c.Chars[eid] ?? "";- parts.push(`text: ${text.length > 80 ? `${text.slice(0, 79)}…` : text}`);- }-- return parts.join("; ");-}--type TreeBucket = keyof Omit<NodeTree, keyof NodeRef | "description">;--// First match wins: masks carry IsMask + Geometry, shadows carry Shadow + Effect.-function childBucket(world: EngineWorld, eid: number): TreeBucket | null {- const c = world.components;- if (hasComponent(world, eid, c.IsMask)) return "masks";- if (isNode(world, eid)) return "children";- if (hasComponent(world, eid, c.ColorStop)) return "colorStops";- if (hasComponent(world, eid, c.Paint)) return "paints";- if (hasComponent(world, eid, c.Stroke)) return "strokes";- if (hasComponent(world, eid, c.Shadow)) return "shadows";- if (hasComponent(world, eid, c.Effect)) return "effects";- if (hasComponent(world, eid, c.TextRange)) return "textRanges";- if (hasComponent(world, eid, c.KeyframeTrack)) return "keyframeTracks";- if (hasComponent(world, eid, c.Keyframe)) return "keyframes";- if (hasComponent(world, eid, c.Animation)) return "animations";- return null;-}--export function handleNodeTree(engine: Accessor<Engine>) {- return async ({ id, depth }: { id?: number; depth?: number }): Promise<NodeTree[]> => {- const { world } = engine();- const c = world.components;-- // depth caps how many levels of descendants to descend into; the root is- // level 0, so --depth 1 yields the root plus its immediate children.- const build = (eid: number, level: number): NodeTree => {- const node: NodeTree = {- id: eid,- name: c.Name[eid] ?? "",- type: entityType(world, eid),- description: describeEntity(world, eid),- };- if (depth !== undefined && level + 1 > depth) return node;- for (const cid of query(world, [ChildOf(eid), Not(c.Deleted)])) {- const bucket = childBucket(world, cid);- if (bucket === null) continue;- (node[bucket] ??= []).push(build(cid, level + 1));- }- return node;- };-- if (id === undefined) {- const roots = [...query(world, [c.Geometry, Not(ChildOf("*")), Not(c.Deleted)])];- return roots.map((eid) => build(eid, 0));- }-- return [build(resolveEntityEid(world, id), 0)];- };-}--export function handleNodeGrep(engine: Accessor<Engine>) {- return async ({- pattern,- ignoreCase,- id,- types,- components,- }: NodeGrepRequest): Promise<NodeGrepResult[]> => {- const { world } = engine();- const c = world.components;- const re = new RegExp(pattern, ignoreCase ? "i" : "");-- // The corpus: the given entity's subtree, or every live entity.- const eids =- id !== undefined- ? getEntityTree(world, resolveEntityEid(world, id))- : [...query(world, [c.Geometry, Not(ChildOf("*")), Not(c.Deleted)])].flatMap((root) =>- getEntityTree(world, root),- );-- const results: NodeGrepResult[] = [];- for (const eid of eids) {- const type = entityType(world, eid);- if (types !== undefined && types.length > 0 && !types.includes(type)) continue;-- const record = serializeEntity(world, eid);- const matches: NodeGrepMatch[] = [];- for (const [component, value] of Object.entries(record)) {- if (component === "id" || component === "eid") continue;- if (components !== undefined && components.length > 0 && !components.includes(component)) {- continue;- }- const text = typeof value === "string" ? value : JSON.stringify(value);- if (re.test(text)) matches.push({ component, value: text });- }- if (matches.length > 0) {- results.push({ id: eid, name: c.Name[eid] ?? "", type, matches });- }- }- return results;- };-}--// Ceiling on the height a sheet cell renders a node at.-const SHEET_CAPTURE_HEIGHT = 1080;--export function handleNodeCapture(engine: Accessor<Engine>) {- return async ({ id, frames, combine = true, perSheet }: NodeCaptureRequest): Promise<NodeCaptureResult> => {- const e = engine();- const w = e.world;-- const eid = resolveNodeEid(w, id);-- if (!hasComponent(w, eid, w.components.Playback)) {- const scene = getSceneAncestor(w, eid);- const hint = scene !== null ? ` Capture its scene (id ${scene}) instead.` : "";- throw new Error(- `Node ${id} has no timeline clock and cannot be captured on its own.${hint}`,- );- }-- // `undefined` means the node's first visible frame (the encoder's frame 0).- let shots = frames;- if (shots === undefined || shots.length === 0) {- shots = [0];- }-- const encoder = await createImageEncoder(w, {- eid,- frames: shots,- resolution: 720,- });-- // Sheets render at their cell size instead of the flat 720p: with a few- // frames that is sharper than a standalone capture, never coarser. A node- // is drawn, not decoded, so a small one is worth rendering past its own- // bounds; beyond SHEET_CAPTURE_HEIGHT that only costs tokens.- const aspect = encoder.bounds.width / encoder.bounds.height;- const height = Math.max(encoder.bounds.height, SHEET_CAPTURE_HEIGHT);- const sizes = combine ? planSheetSizes(shots.length, perSheet) : [];- const plans = sizes.map((n) => planSheet(n, { width: height * aspect, height }));- if (combine) {- encoder.resize(Math.max(...plans.map((plan) => plan.cellHeight)));- }-- const result = await encoder.render();-- if (result.type === "canceled") throw new Error("Capture canceled");- if (result.type === "error") throw result.error;-- if (!combine) return result.data;-- const sheets: TimecodedImage[] = [];- let offset = 0;- for (const [sheet, size] of sizes.entries()) {- const group = result.data.slice(offset, offset + size);- const cells = group.map(({ timecode }, k) => ({ at: shots[offset + k], timecode }));- offset += size;- const images = await Promise.all(group.map((image) => decodePngBase64(image.base64)));- sheets.push({- timecode: sheetTimecode(cells),- base64: composeSheet(- images.map((image, k) => ({ image, label: group[k].timecode })),- plans[sheet],- ),- });- for (const image of images) image.close();- }- return sheets;- };-}--export function handleNodeRender(engine: Accessor<Engine>) {- return async ({ id, output, config }: NodeRenderRequest): Promise<NodeRenderResult> => {- const e = engine();- const w = e.world;-- const sceneEid = id ?? w.selection.scene;- if (sceneEid === null || sceneEid === undefined) {- throw new Error("No active scene. Provide a scene id, or open a scene first.");- }- if (!entityExists(w, sceneEid) || !isScene(w, sceneEid)) {- throw new Error(`Node ${sceneEid} is not a scene.`);- }-- const target = new ElectronWritableFileHandle(output);- const result = await renderScene(e, {- scene: sceneEid,- target,- config: config as Partial<EncoderConfig>,- });-- if (result.type !== "success") {- // Clean up the partial file on cancel / error.- await target.dispose().catch(() => { });- if (result.type === "canceled") throw new Error("Export canceled");- throw new Error(result.error.message || "Export failed");- }-- return { path: output };- };-}--export function handleNodeDelete(engine: Accessor<Engine>) {- return async ({ ids }: { ids: number[] }): Promise<NodeDeleteResult[]> => {- const { world } = engine();- const eids = ids.map((id) => resolveEntityEid(world, id));-- world.history.transaction("deleting nodes", () => {- for (const eid of eids) {- deleteEntity(world, eid);- }- });-- return ids.map((id) => ({ id }));- };-}--export function handleNodeDuplicate(engine: Accessor<Engine>) {- return async ({ ids }: { ids: number[] }): Promise<NodeDuplicateResult[]> => {- const { world } = engine();- const resolved = ids.map((id) => ({- id,- tree: getEntityTree(world, resolveNodeEid(world, id)),- }));-- const newRootEids = new Map<number, number>();- world.history.transaction("duplicating nodes", () => {- for (const { id, tree } of resolved) {- newRootEids.set(id, cloneSubtree(world, tree).get(id)!);- }- });-- return ids.map((id) => ({ sourceId: id, newId: newRootEids.get(id)! }));- };-}--export function handleNodePatch(engine: Accessor<Engine>) {- return async ({ patches }: { patches: NodePatch[] }): Promise<NodePatchResult[]> => {- const e = engine();- const world = e.world;-- // Entity ids are validated upfront; a failing patch still aborts the- // batch mid-way, leaving earlier patches applied (and its own props- // rolled back).- for (const patch of patches) {- resolveEntityEid(world, patch.id);- }-- const results: NodePatchResult[] = [];- for (const patch of patches) {- const doc = new WorldDocument(e.world, { engine: e });-- try {- world.history.startTransaction("patching node");- try {- const node = doc.element(resolveEntityEid(world, patch.id));- for (const [key, value] of Object.entries(patch)) {- if (key === "id") continue;- doc.setProperty(node, key, value);- }- world.history.commitTransaction();- } catch (error) {- world.history.rollbackTransaction();- throw error;- }-- // `src` mounts asynchronously; a failed mount rejects this patch, but- // its synchronous props are committed at this point regardless.- world.history.startTransaction("Commit document");- try {- await doc.commit();- } finally {- world.history.commitTransaction();- }- } catch (error) {- throw new Error(`Entity ${patch.id}: ${(error as Error).message}`);- }-- results.push({ id: patch.id });- }-- return results;- };-}diff --git a/apps/web/src/context/dapi/project.ts b/apps/web/src/context/dapi/project.tsdeleted file mode 100644index 6751db1e..00000000--- a/apps/web/src/context/dapi/project.ts+++ /dev/null@@ -1,69 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import type { Engine } from "@/components/engine";-import type { Accessor } from "solid-js";--import { createProject, deleteProject, getProject, getProjectName, listRecentProjects, DEFAULT_PROJECT_ID } from "@/components/engine/db";-import { whenProjectReady } from "@/context/engine";-import { useSearchParams } from "@solidjs/router";--export function handleProjectActive(engine: Accessor<Engine>) {- return async () => {- const { world } = engine();- const id = world.projectId;- if (!id || id === DEFAULT_PROJECT_ID) return null;- const name = await getProjectName(id);- return { id, name };- }-}--export function handleProjectList() {- return async () => {- const entries = await listRecentProjects(Number.MAX_SAFE_INTEGER);- return entries.map(({ id, name, createdAt, lastAccessedAt }) => ({- id,- name,- createdAt,- lastAccessedAt,- }));- }-}--export function handleProjectCreate(_engine: Accessor<Engine>, setParams: ReturnType<typeof useSearchParams>[1]) {- return async ({ name }: { name?: string }) => {- const entry = await createProject(name);- setParams({ project: entry.id, dashboard: undefined }, { replace: true });- // Opening is a search param write; the engine for the new project mounts- // and restores after it. Hold the reply until that lands so the next CLI- // command can't run against the outgoing project's world.- await whenProjectReady(entry.id);- return { id: entry.id, name: entry.name };- }-}--export function handleProjectDelete(engine: Accessor<Engine>, setParams: ReturnType<typeof useSearchParams>[1]) {- return async ({ id }: { id: string }) => {- const { world } = engine();- if (id === DEFAULT_PROJECT_ID) {- throw new Error("Cannot delete the default project");- }- const name = await getProjectName(id);- await deleteProject(id);- if (world.projectId === id) {- setParams({ project: undefined, dashboard: "projects" }, { replace: true });- }- return { id, name };- }-}--export function handleProjectOpen(_engine: Accessor<Engine>, setParams: ReturnType<typeof useSearchParams>[1]) {- return async ({ id }: { id: string }) => {- const entry = await getProject(id);- if (!entry) return null;- setParams({ project: entry.id, dashboard: undefined }, { replace: true });- await whenProjectReady(entry.id);- return { id: entry.id, name: entry.name };- }-}diff --git a/apps/web/src/context/dapi/selection.ts b/apps/web/src/context/dapi/selection.tsdeleted file mode 100644index 6f391bf1..00000000--- a/apps/web/src/context/dapi/selection.ts+++ /dev/null@@ -1,129 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import type { Accessor } from "solid-js";--import {- addComponent,- removeComponent,- findGeometryAsset,- isScene,- isGroup,- isText,- isCaption,- isAdjustmentLayer,- PaintType,-} from "@/components/engine";-import { Not, Or, query, hasComponent, entityExists } from "bitecs";--import type { EngineWorld, Engine } from "@/components/engine";-import type { NodeRef } from "@diffusionstudio/cli/channels";--function resolveNodeEids(world: EngineWorld, ids: number[]): number[] {- const c = world.components;- return ids.map((eid) => {- if (- !Number.isInteger(eid) ||- !entityExists(world, eid) ||- hasComponent(world, eid, c.Deleted) ||- !isNode(world, eid)- ) {- throw new Error(`No such node: ${eid}`);- }- return eid;- });-}--function isNode(world: EngineWorld, eid: number): boolean {- const c = world.components;- return (- hasComponent(world, eid, c.Geometry) ||- hasComponent(world, eid, c.Group) ||- hasComponent(world, eid, c.AdjustmentLayer)- );-}--export function entityType(world: EngineWorld, eid: number): string {- const c = world.components;- if (hasComponent(world, eid, c.ColorStop)) return "colorStop";- if (hasComponent(world, eid, c.Paint)) {- switch (c.Paint[eid]) {- case PaintType.SOLID: return "solidPaint";- case PaintType.LINEAR_GRADIENT: return "linearGradientPaint";- case PaintType.RADIAL_GRADIENT: return "radialGradientPaint";- case PaintType.IMAGE: return "imagePaint";- case PaintType.VIDEO: return "videoPaint";- case PaintType.HTML: return "htmlPaint";- case PaintType.SURFACE: return "surfacePaint";- case PaintType.SHADER: return "shaderPaint";- default: return "paint";- }- }- if (hasComponent(world, eid, c.Stroke)) return "stroke";- if (hasComponent(world, eid, c.Shadow)) return "shadow";- if (hasComponent(world, eid, c.Effect)) return "effect";- if (hasComponent(world, eid, c.TextRange)) return "textRange";- if (hasComponent(world, eid, c.KeyframeTrack)) return "keyframeTrack";- if (hasComponent(world, eid, c.Keyframe)) return "keyframe";- if (hasComponent(world, eid, c.Animation)) return "animation";- if (isScene(world, eid)) return "scene";- if (isAdjustmentLayer(world, eid)) return "adjustmentLayer";- if (isGroup(world, eid)) return "group";- if (isCaption(world, eid)) return "caption";- if (isText(world, eid)) return "text";-- const asset = findGeometryAsset(world, eid);- if (asset?.type === "IMAGE") return "image";- if (asset?.type === "VIDEO") return "video";- if (asset?.type === "AUDIO") return "audio";-- return "rect";-}--function toNodeRef(world: EngineWorld, eid: number): NodeRef {- const c = world.components;- return {- id: eid,- name: c.Name[eid] ?? "",- type: entityType(world, eid),- };-}--export function selectedNodeIds(world: EngineWorld): number[] {- const c = world.components;- return [...query(world, [c.Selected, Or(c.Geometry, c.Group, c.AdjustmentLayer), Not(c.Deleted)])];-}--function selectedNodes(world: EngineWorld): NodeRef[] {- return selectedNodeIds(world).map((eid) => toNodeRef(world, eid));-}--export function handleSelectionList(engine: Accessor<Engine>) {- return async () => {- const { world } = engine();- return selectedNodes(world);- }-}--export function handleSelectionSet(engine: Accessor<Engine>) {- return async ({ ids }: { ids: number[] }) => {- const { world } = engine();- const c = world.components;- const eids = resolveNodeEids(world, ids);- // Scope clearing to nodes so a co-existing keyframe selection survives.- for (const eid of query(world, [c.Selected, Or(c.Geometry, c.Group, c.AdjustmentLayer)])) {- removeComponent(world, eid, c.Selected, false);- }- for (const eid of eids) addComponent(world, eid, c.Selected, false);- return selectedNodes(world);- }-}--export function handleSelectionFocus(engine: Accessor<Engine>) {- return async () => {- const { world, camera } = engine();- camera.focusEntities(selectedNodeIds(world));- return selectedNodes(world);- }-}diff --git a/apps/web/src/context/render.ts b/apps/web/src/context/render.tsindex 24c7618c..816c0575 100644--- a/apps/web/src/context/render.ts+++ b/apps/web/src/context/render.ts@@ -12,14 +12,9 @@ import type { ExportResult } from "@/components/engine/encode/types";import type { ExportConfig } from "@/components/sidebar-right/inspector/export-progress";/**- * Unified scene render path.- *- * Both the UI export (`ExportProvider.exportScene`) and the headless CLI render- * (`handleNodeRender` for `dapi node render`) funnel through {@link renderScene}- * so they share one implementation of: the "Exporting Composition" overlay, the- * engine stop/start lifecycle, encoder creation, progress reporting, and cancel- * wiring. Callers only supply what differs (where the file comes from, and any- * analytics/toasts/cleanup around the result).+ * Unified scene render path, used by the UI export (`ExportProvider.exportScene`):+ * the "Exporting Composition" overlay, the engine stop/start lifecycle, encoder+ * creation, progress reporting, and cancel wiring all live in {@link renderScene}.*/export type RenderOverlayState = {diff --git a/apps/web/src/utils/jsx.ts b/apps/web/src/utils/jsx.tsdeleted file mode 100644index e08e434a..00000000--- a/apps/web/src/utils/jsx.ts+++ /dev/null@@ -1,2045 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { hasComponent, query, Not } from "bitecs";-import { getAssetSpec, isAssetRef, parseTime } from "@diffusionstudio/jsx";-import * as solid from "solid-js";-import * as solidStore from "solid-js/store";-import { SVGElements } from "solid-js/web";-import * as diffusionJsx from "@diffusionstudio/jsx";-import {- AnimationPhase,- AnimationType,- CaptionAlign,- CaptionType,- FontStyle,- GeometryType,- PaintType,- ScaleMode,- TextAlign,- TextBaseline,- TransitionType,- addComponent,- appendChild,- computeAudioSyncOffsetCached,- createEntity,- deleteEntity,- findAssetDuration,- findGeometryAsset,- getAssetFile,- getEntityTree,- getNextName,- getParentEntity,- getSceneAncestor,- hasAudioSources,- removeChild,- removeComponent,- resizeEntity,- setComponent,- setKeyframeTrack,- transcribeScene,- transcriptTrim,-} from "@/components/engine";-import { HtmlHost, isHtmlInCanvasSupported } from "@/components/engine/decoders/html";-import { SurfaceHost } from "@/components/engine/decoders/surface";-import { resolveTranscript } from "@/components/engine/decoders/caption/utils";-import { ChildOf } from "@/components/engine/components";-import { ASPECT_RATIO_DIMENSIONS, findEmptyPlacement } from "@/utils/genai";-import { resolveAsset, resolveGeneratedAsset } from "@/utils/jsx-generation";-import { assert, assertAllSettled, parseColor } from "@/utils";--import type { AssetInput, AssetRef, AssetSpecInput, ProjectDocument, ProjectTick } from "@diffusionstudio/jsx";-import type { AABB, Engine, EngineWorld, MountData } from "@/components/engine";-import type { GenerationMemo } from "@/utils/jsx-generation";--export class EntityNode {- public constructor(public readonly eid: number) { }-}--/**- * The renderer's host node: an entity handle, or a DOM node for <HtmlPaint>- * content — the ECS world and the DOM are the scene graph, with no shadow- * tree in between. A tag's case decides which side a node lands on at- * creation (PascalCase composition elements mint entities, lowercase tags- * mint DOM nodes), so `setProperty` always has a live target. Project files- * author camelCase tags; the CLI compile canonicalizes them to the PascalCase- * components (SVG ancestry keeps the shared rect/text/image names DOM-side),- * so the case split holds by the time tags reach this document.- */-type HostNode = EntityNode | Element | Text;--const STAGE = new EntityNode(-1);--/**- * Reads a timing prop as local frames. The record always holds raw `Time`- * values (numbers are seconds), so every read parses; an unparsable value- * reads as absent until its own apply rejects it.- */-function timingProp(props: Record<string, unknown> | undefined, name: "start" | "end" | "sourceIn" | "sourceOut"): number | undefined {- const value = props?.[name];- return value === undefined ? undefined : parseFrames(String(value), 30);-}--const SVG_NS = "http://www.w3.org/2000/svg";--// `src` values an html `<img>` carries straight to the browser; anything else-// is a composition source the host has to resolve first.-const DIRECT_SRC_RE = /^(?:data|blob):/i;--// Multiple new scenes are laid side by side in render order.-const PLACEMENT_GAP = 40;--const SCALE_MODE_MAP = {- cover: ScaleMode.COVER,- contain: ScaleMode.FIT,- fill: ScaleMode.FILL,-} as const;--const FONT_STYLE_MAP = {- normal: FontStyle.NORMAL,- italic: FontStyle.ITALIC,- oblique: FontStyle.OBLIQUE,-} as const;--const TEXT_ALIGN_MAP = {- left: TextAlign.LEFT,- center: TextAlign.CENTER,- right: TextAlign.RIGHT,-} as const;--const TEXT_BASELINE_MAP = {- top: TextBaseline.TOP,- middle: TextBaseline.MIDDLE,- bottom: TextBaseline.BOTTOM,-} as const;--// Named easing presets, expanded to the descriptors the interpolation-// inspector writes so JSX-authored keyframes match hand-edited ones.-const EASING_PRESET_MAP: Record<string, string> = {- linear: "",- easeIn: "cubicBezier(0.42,0,1,1)",- easeOut: "cubicBezier(0,0,0.58,1)",- easeInOut: "cubicBezier(0.42,0,0.58,1)",- gentle: "spring(0.5,628)",- snappy: "spring(0.15,300)",- bouncy: "spring(0.4,500)",- strong: "spring(0.65,400)",-};--function parseEasing(value: unknown): string {- assert(typeof value === "string", "keyframe `easing` must be a string" + `, value: ${value}`);- const preset = EASING_PRESET_MAP[value];- if (preset !== undefined) return preset;-- const valid =- /^cubicBezier\(-?[\d.]+,-?[\d.]+,-?[\d.]+,-?[\d.]+\)$/.test(value) ||- /^spring\(-?[\d.]+,-?[\d.]+\)$/.test(value) ||- /^steps\(\d+(,(true|false))?\)$/.test(value);- assert(valid, `invalid keyframe easing: "${value}"`);- return value;-}--/**- * Parses a keyframe-list prop value: times to local frames (0 = the node's- * in point), values through `convert` into the property's authored unit,- * easings through the preset map. Returns the list sorted by time — callers- * land `[0].value` as the authored value and hand the list to- * `setKeyframeTrack`.- */-function parseKeyframes(- name: string,- entries: unknown[],- convert: (value: unknown) => number,-): { time: number; value: number; easing: string }[] {- assert(entries.length > 0, `\`${name}\` keyframe list must not be empty`);-- const frames = new Set<number>();- const keyframes = entries.map((entry) => {- assert(- typeof entry === "object" && entry !== null && !Array.isArray(entry),- `\`${name}\` keyframes must be { time, value, easing? } objects`,- );- const { time, value, easing } = entry as Record<string, unknown>;- const frame = parseFrames(String(time), 30);- assert(typeof frame === "number", `\`${name}\` keyframe \`time\` must be a time value` + `, value: ${time}`);- assert(!frames.has(frame), `\`${name}\` has two keyframes at frame ${frame}`);- frames.add(frame);- return {- time: frame,- value: convert(value),- easing: easing === undefined ? "" : parseEasing(easing),- };- });-- return keyframes.sort((a, b) => a.time - b.time);-}--const TRANSITION_TYPE_MAP = {- dissolve: TransitionType.DISSOLVE,- slideFromRight: TransitionType.SLIDE_FROM_RIGHT,- slideFromLeft: TransitionType.SLIDE_FROM_LEFT,- fadeToBlack: TransitionType.FADE_TO_BLACK,- fadeToWhite: TransitionType.FADE_TO_WHITE,-} as const;--// 1 second at the canonical 30 fps — the transition inspector's default.-const TRANSITION_DEFAULT_DURATION = 30;--function parseTransitionType(value: unknown): number {- assert(typeof value === "string", "transition `type` must be a string" + `, value: ${value}`);- const type = TRANSITION_TYPE_MAP[value as keyof typeof TRANSITION_TYPE_MAP];- assert(type !== undefined, `invalid transition type: "${value}"`);- return type;-}--function parseTransitionDuration(value: unknown): number {- const frames = parseFrames(String(value), 30);- assert(typeof frames === "number", "transition `duration` must be a time value" + `, value: ${value}`);- assert(frames > 0, "transition `duration` must be > 0");- return frames;-}--// JSX animation names, mapped to the presets the animations inspector writes.-// Exported for `node tree`'s entity descriptions.-export const ANIMATION_TYPE_MAP = {- fade: AnimationType.FADE,- gain: AnimationType.GAIN,- grow: AnimationType.GROW,- shrink: AnimationType.SHRINK,- blur: AnimationType.BLUR,- slideLeft: AnimationType.SLIDE_LEFT,- slideRight: AnimationType.SLIDE_RIGHT,- slideUp: AnimationType.SLIDE_UP,- slideDown: AnimationType.SLIDE_DOWN,- spin: AnimationType.SPIN,- twist: AnimationType.TWIST,- appearWord: AnimationType.APPEAR_WORD,- appearChar: AnimationType.APPEAR_CHAR,- scramble: AnimationType.SCRAMBLE,-} as const;--const TEXT_ANIMATION_TYPES: ReadonlySet<AnimationType> = new Set([- AnimationType.APPEAR_WORD,- AnimationType.APPEAR_CHAR,- AnimationType.SCRAMBLE,-]);--// 1 second at the canonical 30 fps — the animations inspector's default.-const ANIMATION_DEFAULT_DURATION = 30;--function parseAnimationSpec(- entry: unknown,- isTextNode: boolean,-): { type: AnimationType; phase: AnimationPhase; duration: number; delay: number } {- assert(- typeof entry === "object" && entry !== null && !Array.isArray(entry),- "`animations` entries must be { type, phase?, duration?, delay? } objects" + `, value: ${entry}`,- );- const { type, phase, duration, delay } = entry as Record<string, unknown>;-- assert(typeof type === "string", "animation `type` must be a string" + `, value: ${type}`);- const parsedType = ANIMATION_TYPE_MAP[type as keyof typeof ANIMATION_TYPE_MAP];- assert(parsedType !== undefined, `invalid animation type: "${type}"`);- assert(- isTextNode || !TEXT_ANIMATION_TYPES.has(parsedType),- `animation type "${type}" only applies to text elements`,- );-- let parsedPhase = AnimationPhase.IN;- if (phase !== undefined) {- assert(phase === "in" || phase === "out", 'animation `phase` must be "in" or "out"' + `, value: ${phase}`);- if (phase === "out") parsedPhase = AnimationPhase.OUT;- }-- let parsedDuration = ANIMATION_DEFAULT_DURATION;- if (duration !== undefined) {- const frames = parseFrames(String(duration), 30);- assert(typeof frames === "number", "animation `duration` must be a time value" + `, value: ${duration}`);- assert(frames > 0, "animation `duration` must be > 0");- parsedDuration = frames;- }-- let parsedDelay = 0;- if (delay !== undefined) {- const frames = parseFrames(String(delay), 30);- assert(typeof frames === "number", "animation `delay` must be a time value" + `, value: ${delay}`);- assert(frames >= 0, "animation `delay` must be >= 0");- parsedDelay = frames;- }-- return { type: parsedType, phase: parsedPhase, duration: parsedDuration, delay: parsedDelay };-}--const CAPTION_PRESET_MAP = {- classic: CaptionType.CLASSIC,- cascade: CaptionType.CASCADE,- spotlight: CaptionType.SPOTLIGHT,- whisper: CaptionType.WHISPER,- paper: CaptionType.PAPER,- guinea: CaptionType.GUINEA,- stark: CaptionType.STARK,-} as const;--export const CAPTION_ALIGN_MAP = {- top: CaptionAlign.TOP,- center: CaptionAlign.CENTER,- bottom: CaptionAlign.BOTTOM,-} as const;--type GenaiQueueItem = {- eid: number;- ref?: AssetRef;- targetKey?: string;- type: "asset" | "caption" | "sync";-};--/**- * A surface awaiting its box size (and ref) until its subtree connects.- */-type PendingSurface = {- eid: number;- host: SurfaceHost;- paint: boolean;- ref?: (target: unknown) => void;-};--type PendingHtmlHost = {- eid: number;- host: HtmlHost;- paint: boolean;-};--export interface WorldDocumentOptions {- /** Mount into an existing parent entity (e.g. `dapi node insert`). */- parentEid?: number;- /** Only needed for `commit()`'s captioning phase (`author` mode). */- engine?: Engine;- /**- * `author` (default) mints entities and defines structure — an explicit- * `dapi mount`. `adopt` binds the re-run to already-persisted entities by- * their `MountPath`, rebuilding runtime hosts without re-authoring structure- * (restore, export, capture).- */- mode?: "author" | "adopt";- /** Identity shared by every entity of this mount (author stamps, adopt matches). */- mountId?: string;- /** SCRIPT asset holding the compiled module, stamped onto the mount root. */- scriptAssetId?: string;- /** `adopt` mode: creation ordinal (`MountPath.path`) -> existing entity id, built from the world. */- adoptIndex?: Map<string, number>;-}--export class WorldDocument implements ProjectDocument<HostNode> {- public promises: Promise<void>[] = [];- public stage: HostNode = STAGE;- public roots: HostNode[] = [];- public rootEid: number | null = null;- public world: EngineWorld;- public engine?: Engine;-- private readonly mode: "author" | "adopt";- private readonly stageEid?: number;- private readonly mountId?: string;- private readonly scriptAssetId?: string;- private readonly adoptIndex?: Map<string, number>;-- // Runtime hosts this render created. Offline (export/capture) worlds are- // discarded without an entity-delete pass, so their hosts (an HtmlHost- // appends a canvas to document.body) must be freed explicitly on dispose.- private createdHosts: { dispose(): void }[] = [];-- private queue: GenaiQueueItem[] = [];-- // Entities mint in module-execution order; the ordinal is each element's- // persisted identity (`MountPath.path`). A re-run of the same module mints- // in the same order, which is what lets adopt bind in `createElement`.- private nextOrdinal = 0;-- // Surfaces whose box size (and so ref) can only resolve once their- // ancestor chain exists — flushed when the subtree connects to the stage.- private pendingSurfaces: PendingSurface[] = [];-- // Html hosts awaiting their initial box size, resolved once the ancestor- // chain exists — flushed alongside surfaces when the subtree connects.- private pendingHtmlHosts: PendingHtmlHost[] = [];-- // Entities this render minted or adopted — exactly the renderer's element- // nodes. Traversal filters ECS children through this set so internal- // sub-entities (a <Text>'s paint) and hand-added children stay invisible- // to Solid's reconciler, which deletes whatever it can see but no longer- // tracks.- private managed = new Set<number>();-- // Adopted entities keep their persisted (possibly hand-edited) values- // through the initial adopt render; only post-commit effects write.- private adopted = new Set<number>();-- // World-space boxes of the new roots this mount has already placed. A fresh- // root has no computed layout yet, so `findEmptyPlacement` cannot see it in- // the world; recording each placement here keeps sibling roots from stacking.- private placedRootBoxes: AABB[] = [];-- // Entities this render soft-deleted via removeNode. Solid's reconciler- // shuffles by removing and re-inserting nodes, so re-attaching one of- // these resurrects it — but only these: an entity deleted from outside- // (keyed replace, user delete) must stay dead even if a stale reconcile- // still references it.- private removed = new Set<number>();-- // DOM containers back to their owning entity, as Solid knows it: an html- // host element maps to the element Solid inserts DOM content under, a text- // fragment to its <Text> entity.- private nodeOwner = new WeakMap<Node, number>();-- // Html host per element the renderer inserts DOM content under (the- // wrapper for <Html>, the paint entity for <HtmlPaint>).- private htmlHosts = new Map<number, HtmlHost>();-- // Object URLs minted for host-resolved <img> sources: a reactive `src` swap- // frees the one its element held, and teardown frees whatever is left.- private objectUrls = new Map<HTMLImageElement, string>();-- // Per-element request counter, so a slow resolution that a newer `src` has- // already superseded doesn't land on top of it.- private imageEpochs = new WeakMap<HTMLImageElement, number>();-- // One stable handle per entity: Solid's reconciliation compares host nodes- // by object identity, so traversal must return the same instance that- // `createElement` handed out.- private entityNodes = new Map<number, EntityNode>();-- /** The entity's stable renderer handle, created on first touch. */- private entity(eid: number): EntityNode {- let node = this.entityNodes.get(eid);- if (node === undefined) {- node = new EntityNode(eid);- this.entityNodes.set(eid, node);- }- return node;- }-- /** The entity's runtime renderer state, created on first touch. */- private data(eid: number): MountData {- const c = this.world.components;- if (!hasComponent(this.world, eid, c.Data)) {- addComponent(this.world, eid, c.Data, false);- c.Data[eid] = { props: {} };- }- return c.Data[eid]!;- }-- /** The entity's recorded raw props, if any were recorded. */- private props(eid: number): Record<string, unknown> | undefined {- const c = this.world.components;- return hasComponent(this.world, eid, c.Data) ? c.Data[eid]?.props : undefined;- }-- private trackHost<T extends { dispose(): void }>(host: T): T {- this.createdHosts.push(host);- return host;- }-- /** Frees the runtime hosts this render created (paired with the graph dispose). */- public disposeHosts(): void {- for (const host of this.createdHosts) host.dispose();- this.createdHosts.length = 0;- for (const url of this.objectUrls.values()) URL.revokeObjectURL(url);- this.objectUrls.clear();- }-- // Set once `commit()` finishes. A mount keeps its reactive graph running- // past commit, so later writes flow through the same paths, untracked;- // otherwise the undo stack would fill with one entry per reactive update.- private committed = false;-- private track<T>(fn: () => T): T {- if (!this.committed) return fn();- let result!: T;- this.world.history.untrack(() => {- result = fn();- });- return result;- }-- public constructor(world: EngineWorld, options: WorldDocumentOptions = {}) {- this.world = world;- this.engine = options.engine;- this.stageEid = options.parentEid;- this.mode = options.mode ?? "author";- this.mountId = options.mountId;- this.scriptAssetId = options.scriptAssetId;- this.adoptIndex = options.adoptIndex;- }-- /**- * Waits for the rendering to complete and then handles the genai queue.- */- public async commit(): Promise<void> {- const world = this.world;- const c = world.components;-- // Wait for assets to settle- {- const results = await Promise.allSettled(this.promises);- assertAllSettled(results);- }-- // Handle generative queue- {- const memo: GenerationMemo = new Map();-- const results = await Promise.allSettled(this.queue.map(({ eid, ref, type }) => {- if (type !== "asset" || !ref) return;- return this.generateInto(eid, ref, memo);- }));-- assertAllSettled(results);- }-- // Handle sync queue: after generated assets have landed (either side may- // be generated), before captions read the scene's final placement.- {- for (const { eid: nodeEid, targetKey, type } of this.queue) {- if (type !== "sync" || !targetKey || hasComponent(world, nodeEid, c.Deleted)) continue;- const targetEid = query(world, [c.Key, Not(c.Deleted)]).find(eid => c.Key[eid] === targetKey);-- assert(targetEid !== undefined, `syncTo: no other element carries key "${targetKey}"`);-- const source = findGeometryAsset(world, nodeEid);- assert(- source !== null && (source.type === "AUDIO" || source.type === "VIDEO"),- `syncTo: node ${nodeEid} has no audio or video source to align`,- );- const targetSource = findGeometryAsset(world, targetEid);- assert(- targetSource !== null && (targetSource.type === "AUDIO" || targetSource.type === "VIDEO"),- `syncTo: target "${targetKey}" has no audio or video source to align against`,- );-- const { offsetSeconds } = await computeAudioSyncOffsetCached(source, targetSource);-- const offsetFrames = Math.round(offsetSeconds * world.frameRate);- const parentEid = getParentEntity(world, nodeEid);- const parentDelay = parentEid !== null ? (c.Computed.delay[parentEid] ?? 0) : 0;- const delay = (c.Computed.delay[targetEid] ?? 0) + offsetFrames - parentDelay;-- setComponent(world, nodeEid, c.Delay, delay);-- const targetStart = (c.Computed.start[targetEid] ?? 0) - parentDelay;- const targetEnd = (c.Computed.end[targetEid] ?? 0) - parentDelay;- const duration = findAssetDuration(world, nodeEid);-- // `sourceIn`/`sourceOut` are source-relative; default to the overlap- // with the target window. `end` (timeline) converts through `delay`.- const props = this.data(nodeEid).props;- const end = timingProp(props, "end");- const trimStart = timingProp(props, "sourceIn") ?? Math.max(0, targetStart - delay);- const trimEnd = timingProp(props, "sourceOut")- ?? (end !== undefined- ? end - delay- : (duration !== null ? Math.min(duration, targetEnd - delay) : targetEnd - delay));- assert(trimEnd > trimStart, `syncTo: the aligned clip does not overlap the window of "${targetKey}"`);- setComponent(world, nodeEid, c.Trim, { start: trimStart, end: trimEnd });- props.sourceIn = `${trimStart}f`;- props.sourceOut = `${trimEnd}f`;- delete props.end;- props.start = `${delay + trimStart}f`;- }- }-- // Handle captioning queue- {- for (const { eid: nodeEid, type } of this.queue) {- if (hasComponent(world, nodeEid, c.Deleted) || type !== "caption") continue;-- const props = this.data(nodeEid).props;- const seed = props.seed as number | undefined;- if (c.AssetId[nodeEid] && (seed === undefined || props.src !== undefined)) continue;-- const sceneEid = getSceneAncestor(world, nodeEid);- if (!sceneEid || !hasAudioSources(world, sceneEid)) continue;-- assert(this.engine, "captioning requires an engine (author-mode mount)");- const { asset, trim } = await transcribeScene(this.engine, sceneEid, undefined, seed);- setComponent(world, nodeEid, c.AssetId, asset.id);-- const hasIn = timingProp(props, "sourceIn") !== undefined;- const hasOut = timingProp(props, "sourceOut") !== undefined || timingProp(props, "end") !== undefined;- setComponent(world, nodeEid, c.Trim, {- start: hasIn ? c.Trim.start[nodeEid] : trim.start,- end: hasOut ? c.Trim.end[nodeEid] : trim.end,- });- }- }-- this.queue.length = 0;- this.committed = true;- }-- private ticker = solid.createSignal<ProjectTick>(- { time: 0, frame: 0, delta: 0, playing: false },- { equals: (a, b) => a.time === b.time && a.frame === b.frame && a.delta === b.delta && a.playing === b.playing },- );- private lastTickTime: number | null = null;-- public tick(): ProjectTick {- return this.ticker[0]();- }-- /**- * Backs `useFile`: resolves a source (path, URL, asset id, or `AssetRef`) to- * its `File`, the same input `src` accepts. A `generate.*` ref generates on- * demand (content-cached in the library, so it collapses with the mount's own- * generation of the same spec).- */- public loadFile(input: AssetInput): Promise<File> {- const promise = (async () => {- const asset = isAssetRef(input)- ? await resolveGeneratedAsset(this.world, input, new Map())- : await resolveAsset(this.world, input);- return await asset.handle.getFile();- })();-- // Let commit() await the initial resolution so the first exported/captured- // frame reflects a `useFile`-driven draw rather than rendering before the- // file lands. Post-commit refetches update reactively and aren't tracked.- if (!this.committed) {- this.promises.push(promise.then(() => undefined, () => undefined));- }-- return promise;- }-- /**- * Reads the playhead of the nearest Playback-carrying ancestor of the- * mount's root (the root itself for a mounted scene) into the ticker- * signal. Called by the playback system once per tick.- */- public advanceTicker(): void {- const c = this.world.components;- const sid = this.playbackRoot();- const time = sid !== null ? (c.Computed.localTimeInSeconds[sid] ?? 0) : 0;- const delta = this.lastTickTime === null ? 0 : time - this.lastTickTime;- this.lastTickTime = time;- this.ticker[1]({- time,- frame: sid !== null ? (c.Computed.localTime[sid] ?? 0) : 0,- delta,- playing: sid !== null && c.Playback.playing[sid] === 1,- });- }-- private playbackRoot(): number | null {- // Resolved per tick rather than cached: the root lands after component- // bodies run (so it is null during the first render), and reparenting or- // keyed replacement can change the answer later.-- const world = this.world;- const c = world.components;- let current = this.rootEid ?? this.stageEid ?? null;- while (current !== null && !hasComponent(world, current, c.Deleted)) {- if (hasComponent(world, current, c.Playback)) return current;- current = getParentEntity(world, current);- }- return null;- }-- /**- * Resolves a generated asset and attaches it: during commit via the genai- * queue, or immediately when a live mount sets an asset ref after commit.- */- private async generateInto(eid: number, ref: AssetRef, memo: GenerationMemo): Promise<void> {- const world = this.world;- const c = world.components;- if (hasComponent(world, eid, c.Deleted)) return;- try {- const asset = await resolveGeneratedAsset(world, ref, memo);- await this.mountSource(eid, asset.id);- } finally {- world.history.untrack(() => removeComponent(world, eid, c.Generating));- }- }-- public createElement(tag: string): HostNode {- // When the tag starts with a lowercase letter, it's a DOM vocabulary- if (tag[0] === tag[0].toLowerCase()) {- // Media doesn't play under a paint host — playback and the timeline- // belong to the composition elements.- assert(- tag !== "audio" && tag !== "video",- `<${tag}> is not supported as html content; media plays through the <${tag}> composition element outside the html subtree`,- );- return SVGElements.has(tag)- ? document.createElementNS(SVG_NS, tag)- : document.createElement(tag);- }- return this.entity(this.track(() => this.bindEntity(tag)));- }-- /**- * Binds a composition element to its entity: adopt mode looks up the- * persisted entity minted at the same creation ordinal, author mode creates- * one and stamps the ordinal as its `MountPath`. New elements an adopted- * mount's effects create later (no persisted counterpart) author as usual.- */- private bindEntity(tag: string): number {- const path = String(this.nextOrdinal++);- const adoptedEid = this.mode === "adopt" ? this.adoptIndex?.get(path) : undefined;-- let eid: number;- if (adoptedEid !== undefined) {- eid = adoptedEid;- this.adopted.add(eid);- this.reattachRuntimeHostsForTag(tag, eid);- } else {- eid = this.createEntityForTag(tag);- if (this.mountId !== undefined) {- setComponent(this.world, eid, this.world.components.MountPath, { mountId: this.mountId, path });- }- }-- this.managed.add(eid);- return eid;- }-- public createTextNode(text: string): HostNode {- return document.createTextNode(text);- }-- /** Tag-specific entity setup for a composition element. */- private createEntityForTag(tag: string): number {- const world = this.world;- const c = world.components;- const eid = createEntity(world);-- switch (tag) {- case "Group": {- setComponent(world, eid, c.Geometry, GeometryType.RECT);- addComponent(world, eid, c.Group);- setComponent(world, eid, c.Name, getNextName(world, "Group"));- break;- } case "Rect": {- setComponent(world, eid, c.Geometry, GeometryType.RECT);- setComponent(world, eid, c.Name, getNextName(world, "Rect"));- break;- } case "Sequence": {- addComponent(world, eid, c.Group);- addComponent(world, eid, c.Sequential);- setComponent(world, eid, c.Name, getNextName(world, "Sequence"));- break;- } case "Video": {- setComponent(world, eid, c.Geometry, GeometryType.RECT);- setComponent(world, eid, c.Name, getNextName(world, "Video"));- break;- } case "Image": {- setComponent(world, eid, c.Geometry, GeometryType.RECT);- setComponent(world, eid, c.Name, getNextName(world, "Image"));- break;- } case "Audio": {- addComponent(world, eid, c.Audio);- setComponent(world, eid, c.Geometry, GeometryType.RECT);- setComponent(world, eid, c.Name, getNextName(world, "Audio"));- break;- } case "Text": {- setComponent(world, eid, c.Geometry, GeometryType.TEXT);- const fid = createEntity(world);- setComponent(world, fid, c.Paint, PaintType.SOLID);- setComponent(world, fid, c.Color, 0xffffff);- appendChild(world, fid, eid);- break;- } case "Captions": {- assert(!this.committed, "<Captions> cannot be created after commit; re-mount instead");- setComponent(world, eid, c.Geometry, GeometryType.TEXT);- setComponent(world, eid, c.Caption, {});- setComponent(world, eid, c.Name, getNextName(world, "Captions"));- this.queue.push({ eid, type: "caption" });- break;- } case "SolidPaint": {- setComponent(world, eid, c.Paint, PaintType.SOLID);- setComponent(world, eid, c.Color, 0xE0E0E0);- break;- } case "LinearGradientPaint": {- setComponent(world, eid, c.Paint, PaintType.LINEAR_GRADIENT);- break;- } case "RadialGradientPaint": {- setComponent(world, eid, c.Paint, PaintType.RADIAL_GRADIENT);- break;- } case "ColorStop": {- setComponent(world, eid, c.ColorStop, {});- break;- } case "HtmlPaint": {- assert(- isHtmlInCanvasSupported(),- "<HtmlPaint> requires the html-in-canvas API; enable chrome://flags/#canvas-draw-element",- );- setComponent(world, eid, c.Paint, PaintType.HTML);- const host = this.trackHost(new HtmlHost());- addComponent(world, eid, c.HtmlHost, false);- c.HtmlHost[eid] = host;- this.registerHtmlHost(eid, host, true);- break;- } case "Html": {- // A rect carrying an html paint; the element's children are the- // paint's DOM content, so the wrapper routes to the paint's host.- assert(- isHtmlInCanvasSupported(),- "<Html> requires the html-in-canvas API; enable chrome://flags/#canvas-draw-element",- );- setComponent(world, eid, c.Geometry, GeometryType.RECT);- setComponent(world, eid, c.Name, getNextName(world, "HTML"));- const fid = createEntity(world);- setComponent(world, fid, c.Paint, PaintType.HTML);- const host = this.trackHost(new HtmlHost());- addComponent(world, fid, c.HtmlHost, false);- c.HtmlHost[fid] = host;- appendChild(world, fid, eid);- this.registerHtmlHost(eid, host, false);- break;- } case "ShaderPaint": {- setComponent(world, eid, c.Paint, PaintType.SHADER);- break;- } case "SurfacePaint": {- setComponent(world, eid, c.Paint, PaintType.SURFACE);- const host = this.trackHost(new SurfaceHost());- addComponent(world, eid, c.SurfaceHost, false);- c.SurfaceHost[eid] = host;- this.pendingSurfaces.push({ eid, host, paint: true });- break;- } case "Surface": {- // A rect carrying a surface paint; the element's ref receives the- // paint's backing canvas.- setComponent(world, eid, c.Geometry, GeometryType.RECT);- setComponent(world, eid, c.Name, getNextName(world, "Surface"));- const fid = createEntity(world);- setComponent(world, fid, c.Paint, PaintType.SURFACE);- const host = this.trackHost(new SurfaceHost());- addComponent(world, fid, c.SurfaceHost, false);- c.SurfaceHost[fid] = host;- appendChild(world, fid, eid);- this.pendingSurfaces.push({ eid, host, paint: false });- break;- } default: {- assert(false, `<${tag}> is not a composition element`);- }- }-- return eid;- }-- /**- * Wraps an existing entity so props can be applied to it through the same- * `setProperty` path a fresh render uses (e.g. `dapi node patch`). Timing- * state is hydrated from the entity's components so a partial patch (say,- * only `sourceIn`) composes with its existing delay/trim like a full render.- */- public element(eid: number): EntityNode {- const world = this.world;- const c = world.components;- const props = this.data(eid).props;- // Reset the timing record from the entity's components — they are the- // source of truth (hand-edits bypass any props a live mount recorded).- delete props.start;- delete props.end;- delete props.sourceIn;- delete props.sourceOut;- const delay = hasComponent(world, eid, c.Delay) ? c.Delay[eid] : 0;- if (hasComponent(world, eid, c.Trim)) {- const start = c.Trim.start[eid];- const end = c.Trim.end[eid];- if (start !== undefined) {- props.sourceIn = `${start}f`;- }- if (end !== undefined) {- props.sourceOut = `${end}f`;- }- }- // start = timeline placement of source-0 (Delay) shifted by the source in point.- if (hasComponent(world, eid, c.Delay) || props.sourceIn !== undefined) {- props.start = `${delay + (timingProp(props, "sourceIn") ?? 0)}f`;- }- return this.entity(eid);- }-- private reconcileTiming(eid: number) {- const world = this.world;- const c = world.components;- const props = this.props(eid);- const sourceIn = timingProp(props, "sourceIn") ?? 0;- const start = timingProp(props, "start") ?? 0;- const end = timingProp(props, "end");- const sourceOut = timingProp(props, "sourceOut");- const delay = start - sourceIn;- setComponent(world, eid, c.Delay, delay);-- if (timingProp(props, "sourceIn") !== undefined) {- setComponent(world, eid, c.Trim, { start: sourceIn });- }- if (sourceOut !== undefined) {- setComponent(world, eid, c.Trim, { end: sourceOut });- } else if (end !== undefined) {- const trimEnd = end - delay;- assert(trimEnd > sourceIn, `\`end\` must be after \`start\`, got start=${start}, end=${end}`);- setComponent(world, eid, c.Trim, { end: trimEnd });- }- }-- public replaceText(node: HostNode, text: string) {- assert(node instanceof Text, "replaceText target is not a text node");- node.data = text;- // Text inside a <Text> element (a live mount updating a signal) must- // land in the world too.- const owner = node.parentNode !== null ? this.nodeOwner.get(node.parentNode) : undefined;- if (owner !== undefined && this.isTextEntity(owner)) {- this.track(() => this.syncChars(owner));- }- }-- public isTextNode(node: HostNode): boolean {- return node instanceof Text;- }-- private isTextEntity(eid: number): boolean {- const c = this.world.components;- return c.Geometry[eid] === GeometryType.TEXT;- }-- /**- * Chars mirrors the concatenation of a text element's text runs, held in- * its Data fragment — a reactive segment compiles to its own text node- * (`frame {frame()}` is two).- */- private syncChars(eid: number): void {- const c = this.world.components;- // Adopted text keeps its persisted (possibly hand-edited) Chars through- // the initial adopt render; only actively re-running effects write.- if (this.adopted.has(eid) && !this.committed) return;- const textBox = hasComponent(this.world, eid, c.Data) ? c.Data[eid]?.textBox : undefined;-- if (textBox === undefined || textBox.firstChild === null) {- removeComponent(this.world, eid, c.Chars);- } else {- setComponent(this.world, eid, c.Chars, textBox.textContent ?? "");- }- }-- public setProperty(node: HostNode, name: string, value: unknown) {- if (name === "children" || name === "ref" || value === undefined || node instanceof Text) return;-- if (node instanceof Element) {- if (name === "src" && node instanceof HTMLImageElement) {- this.setImageSource(node, value);- return;- }- setDomProperty(node, name, value);- return;- }- const eid = node.eid;- // Recorded even when not applied: timing, sync, and box-size resolution- // read the raw props back.- this.data(eid).props[name] = value;- // Adopted entities keep their persisted (possibly hand-edited) values- // through the initial adopt render; only actively re-running effects write.- if (this.adopted.has(eid) && !this.committed) return;- this.track(() => this.applyEcsProperty(eid, name, value));- }-- private applyEcsProperty(eid: number, name: string, value: unknown) {- const world = this.world;- const c = world.components;-- switch (name) {- case "name": {- assert(typeof value === "string", "`name` must be a string" + `, value: ${value}`);- setComponent(world, eid, c.Name, value);- break;- } case "x": {- if (Array.isArray(value)) {- const keyframes = parseKeyframes(name, value, (v) => {- assert(typeof v === "number", "`x` must be a number" + `, value: ${v}`);- return Math.round(v);- });- setComponent(world, eid, c.Position, { x: keyframes[0].value });- setKeyframeTrack(world, eid, "position.x", keyframes);- break;- }- setKeyframeTrack(world, eid, "position.x", []);- assert(typeof value === "number", "`x` must be a number" + `, value: ${value}`);- setComponent(world, eid, c.Position, { x: Math.round(value) });- break;- } case "y": {- if (Array.isArray(value)) {- const keyframes = parseKeyframes(name, value, (v) => {- assert(typeof v === "number", "`y` must be a number" + `, value: ${v}`);- return Math.round(v);- });- setComponent(world, eid, c.Position, { y: keyframes[0].value });- setKeyframeTrack(world, eid, "position.y", keyframes);- break;- }- setKeyframeTrack(world, eid, "position.y", []);- assert(typeof value === "number", "`y` must be a number" + `, value: ${value}`);- setComponent(world, eid, c.Position, { y: Math.round(value) });- break;- } case "offsetX": {- if (Array.isArray(value)) {- const keyframes = parseKeyframes(name, value, (v) => {- assert(typeof v === "number", "`offsetX` must be a number" + `, value: ${v}`);- return v;- });- setComponent(world, eid, c.Offset, { x: keyframes[0].value });- setKeyframeTrack(world, eid, "offset.x", keyframes);- break;- }- setKeyframeTrack(world, eid, "offset.x", []);- assert(typeof value === "number", "`offsetX` must be a number" + `, value: ${value}`);- setComponent(world, eid, c.Offset, { x: value });- break;- } case "offsetY": {- if (Array.isArray(value)) {- const keyframes = parseKeyframes(name, value, (v) => {- assert(typeof v === "number", "`offsetY` must be a number" + `, value: ${v}`);- return v;- });- setComponent(world, eid, c.Offset, { y: keyframes[0].value });- setKeyframeTrack(world, eid, "offset.y", keyframes);- break;- }- setKeyframeTrack(world, eid, "offset.y", []);- assert(typeof value === "number", "`offsetY` must be a number" + `, value: ${value}`);- setComponent(world, eid, c.Offset, { y: value });- break;- } case "width": {- if (Array.isArray(value)) {- const keyframes = parseKeyframes(name, value, (v) => {- assert(typeof v === "number", "`width` must be a number" + `, value: ${v}`);- assert(v >= 0, "`width` must be >= 0");- return Math.round(v);- });- resizeEntity(world, eid, { width: keyframes[0].value });- setKeyframeTrack(world, eid, "width", keyframes);- break;- }- setKeyframeTrack(world, eid, "width", []);- assert(typeof value === "number", "`width` must be a number" + `, value: ${value}`);- assert(value >= 0, "`width` must be >= 0");- resizeEntity(world, eid, { width: Math.round(value) });- break;- } case "height": {- if (Array.isArray(value)) {- const keyframes = parseKeyframes(name, value, (v) => {- assert(typeof v === "number", "`height` must be a number" + `, value: ${v}`);- assert(v >= 0, "`height` must be >= 0");- return Math.round(v);- });- resizeEntity(world, eid, { height: keyframes[0].value });- setKeyframeTrack(world, eid, "height", keyframes);- break;- }- setKeyframeTrack(world, eid, "height", []);- assert(typeof value === "number", "`height` must be a number" + `, value: ${value}`);- assert(value >= 0, "`height` must be >= 0");- resizeEntity(world, eid, { height: Math.round(value) });- break;- } case "rotation": {- if (Array.isArray(value)) {- const keyframes = parseKeyframes(name, value, (v) => {- assert(typeof v === "number", "`rotation` must be a number" + `, value: ${v}`);- return v;- });- setComponent(world, eid, c.Rotation, keyframes[0].value);- setKeyframeTrack(world, eid, "rotation", keyframes);- break;- }- setKeyframeTrack(world, eid, "rotation", []);- assert(typeof value === "number", "`rotation` must be a number" + `, value: ${value}`);- setComponent(world, eid, c.Rotation, value);- break;- } case "opacity": {- const isStop = hasComponent(world, eid, c.ColorStop);- if (Array.isArray(value)) {- const keyframes = parseKeyframes(name, value, (v) => {- assert(typeof v === "number", "`opacity` must be a number" + `, value: ${v}`);- return Math.min(1, Math.max(0, v));- });- if (isStop) setComponent(world, eid, c.ColorStop, { opacity: keyframes[0].value });- else setComponent(world, eid, c.Appearance, { opacity: keyframes[0].value });- setKeyframeTrack(world, eid, isStop ? "stop.opacity" : "opacity", keyframes);- break;- }- setKeyframeTrack(world, eid, isStop ? "stop.opacity" : "opacity", []);- assert(typeof value === "number", "`opacity` must be a number" + `, value: ${value}`);- const opacity = Math.min(1, Math.max(0, value));- if (isStop) {- setComponent(world, eid, c.ColorStop, { opacity });- } else {- setComponent(world, eid, c.Appearance, { opacity });- }- break;- } case "cornerRadius": {- if (Array.isArray(value)) {- const keyframes = parseKeyframes(name, value, (v) => {- assert(typeof v === "number", "`cornerRadius` must be a number" + `, value: ${v}`);- assert(v >= 0, "`cornerRadius` must be >= 0");- return Math.round(v);- });- setComponent(world, eid, c.CornerRadius, keyframes[0].value);- setKeyframeTrack(world, eid, "vertexRadius", keyframes);- break;- }- setKeyframeTrack(world, eid, "vertexRadius", []);- assert(typeof value === "number", "`cornerRadius` must be a number" + `, value: ${value}`);- assert(value >= 0, "`cornerRadius` must be >= 0");- setComponent(world, eid, c.CornerRadius, Math.round(value));- break;- } case "start": {- const parsed = parseFrames(String(value), 30);- assert(typeof parsed === "number", "`start` must be a string or number" + `, value: ${value}`);- this.reconcileTiming(eid);- break;- } case "end": {- const parsed = parseFrames(String(value), 30);- assert(typeof parsed === "number", "`end` must be a string or number" + `, value: ${value}`);- delete this.data(eid).props.sourceOut;- this.reconcileTiming(eid);- break;- } case "sourceIn": {- const parsed = parseFrames(String(value), 30);- assert(typeof parsed === "number", "`sourceIn` must be a string or number" + `, value: ${value}`);- this.reconcileTiming(eid);- break;- } case "sourceOut": {- const parsed = parseFrames(String(value), 30);- assert(typeof parsed === "number", "`sourceOut` must be a string or number" + `, value: ${value}`);- delete this.data(eid).props.end;- this.reconcileTiming(eid);- break;- }- case "fill": {- assert(typeof value === "string", "`fill` must be a string" + `, value: ${value}`);- const color = parseColor(value);- assert(color !== null, `fill is not a valid CSS color: "${value}"`);- const fills = [...query(world, [c.Paint, ChildOf(eid), Not(c.Deleted)])]- .filter((fid) => c.Paint[fid] === PaintType.SOLID);-- if (fills.length === 0) {- const fid = createEntity(world);- setComponent(world, fid, c.Paint, PaintType.SOLID);- appendChild(world, fid, eid);- fills.push(fid);- }--- for (const fid of fills) {- setComponent(world, fid, c.Color, color);- }- break;- }- case "volume": {- if (Array.isArray(value)) {- const keyframes = parseKeyframes(name, value, (v) => {- assert(typeof v === "number", "`volume` must be a number (dB)" + `, value: ${v}`);- // Keyframed silence floors at -60 dB so segments toward it- // interpolate over finite values.- return Math.max(v, -60);- });- setComponent(world, eid, c.Volume, keyframes[0].value);- setKeyframeTrack(world, eid, "volume", keyframes);- break;- }- setKeyframeTrack(world, eid, "volume", []);- assert(typeof value === "number", "`volume` must be a number (dB)" + `, value: ${value}`);- setComponent(world, eid, c.Volume, value);- break;- } case "muted": {- assert(typeof value === "boolean", "`muted` must be a boolean" + `, value: ${value}`);- if (value) addComponent(world, eid, c.Muted);- else removeComponent(world, eid, c.Muted);- break;- } case "syncTo": {- assert(typeof value === "string", "`syncTo` must be a string" + `, value: ${value}`);- assert(value.trim().length > 0, "`syncTo` must be a non-empty string");- assert(!this.committed, "`syncTo` cannot change after commit; re-mount instead");- this.queue.push({ eid, targetKey: value.trim(), type: "sync" });- break;- } case "transition": {- if (value === null) {- removeComponent(world, eid, c.Transition);- break;- }- assert(- typeof value === "object" && !Array.isArray(value),- "`transition` must be a { type?, duration? } object or null" + `, value: ${value}`,- );- const { type, duration } = value as Record<string, unknown>;- const spec: { type?: number; duration?: number } = {};- if (type !== undefined) spec.type = parseTransitionType(type);- if (duration !== undefined) spec.duration = parseTransitionDuration(duration);-- if (!hasComponent(world, eid, c.Transition)) {- spec.type ??= TransitionType.DISSOLVE;- spec.duration ??= TRANSITION_DEFAULT_DURATION;- }- setComponent(world, eid, c.Transition, spec);- break;- } case "animations": {- assert(- Array.isArray(value),- "`animations` must be an array of { type, phase?, duration?, delay? } objects" + `, value: ${value}`,- );- const isTextNode = c.Geometry[eid] === GeometryType.TEXT;- const specs = value.map((entry) => parseAnimationSpec(entry, isTextNode));-- // The list replaces the node's existing animations; [] clears them.- // Materialized before deleting — removal mutates the live query.- for (const aid of [...query(world, [c.Animation, ChildOf(eid), Not(c.Deleted)])]) {- deleteEntity(world, aid);- }- for (const spec of specs) {- const aid = createEntity(world);- setComponent(world, aid, c.Animation, spec);- appendChild(world, aid, eid);- }- break;- } case "src": {- if (isAssetRef(value)) {- world.history.untrack(() => addComponent(world, eid, c.Generating));- if (!hasComponent(world, eid, c.Size)) {- resizeEntity(world, eid, placeholderSize(getAssetSpec(value)));- }- // Post-commit (live mount) nothing drains the queue; resolve now.- if (this.committed) this.generateInto(eid, value, new Map()).catch(console.error);- else this.queue.push({ eid, ref: value, type: "asset" });- break;- }- assert(typeof value === "string", "`src` must be a string" + `, value: ${value}`);- assert(value.trim().length > 0, "`src` must be a non-empty string");-- if (this.committed) this.mountSource(eid, value).catch(console.error);- else this.promises.push(this.mountSource(eid, value));- break;- } case "objectFit": {- assert(typeof value === "string", "`objectFit` must be a string" + `, value: ${value}`);- assert(value in SCALE_MODE_MAP, `invalid objectFit value: "${value}"`);- const mode = SCALE_MODE_MAP[value as keyof typeof SCALE_MODE_MAP];-- for (const pid of query(world, [c.Paint, ChildOf(eid), Not(c.Deleted)])) {- if (c.Paint[pid] === PaintType.IMAGE || c.Paint[pid] === PaintType.VIDEO) {- setComponent(world, pid, c.ScaleMode, mode);- }- }- break;- }- case "key": {- assert(typeof value === "string", "`key` must be a string" + `, value: ${value}`);- assert(value.trim().length > 0, "`key` must be a non-empty string");- setComponent(world, eid, c.Key, value.trim());- break;- }- case "scene": {- // Promotes a rectangle geometry to a scene (mount root): it carries the- // Scene markers, and the `scene` value is the root's identity (stamped- // onto Key, which insertRoot uses to replace a scene on re-mount).- assert(typeof value === "string", "`scene` must be a string" + `, value: ${value}`);- assert(value.trim().length > 0, "`scene` must be a non-empty string");- assert(- c.Geometry[eid] === GeometryType.RECT,- "`scene` only applies to a rectangle geometry (`<rect>`, `<group>`, `<html>`, `<image>`, `<video>`)",- );- if (!hasComponent(world, eid, c.Scene)) {- addComponent(world, eid, c.Scene);- addComponent(world, eid, c.ClipsContent);- setComponent(world, eid, c.Playback, {});- }- setComponent(world, eid, c.Key, value.trim());- break;- }- case "wgsl": {- assert(c.Paint[eid] === PaintType.SHADER, "`wgsl` only applies to <ShaderPaint>");- assert(typeof value === "string", "`wgsl` must be a string" + `, value: ${value}`);- assert(value.trim().length > 0, "`wgsl` must be a non-empty string");- setComponent(world, eid, c.Shader, { code: value });- break;- }- case "uniforms": {- assert(c.Paint[eid] === PaintType.SHADER, "`uniforms` only applies to <ShaderPaint>");- assert(- typeof value === "object" && value !== null && !Array.isArray(value),- "`uniforms` must be an object of numbers, number arrays, or CSS colors" + `, value: ${value}`,- );- for (const [uniform, entry] of Object.entries(value)) {- if (typeof entry === "number") {- assert(Number.isFinite(entry), `uniform \`${uniform}\` must be finite, value: ${entry}`);- } else if (Array.isArray(entry)) {- assert(- entry.length >= 2 && entry.length <= 4 && entry.every((v) => typeof v === "number" && Number.isFinite(v)),- `uniform \`${uniform}\` must be an array of 2-4 finite numbers, value: ${entry}`,- );- } else {- assert(typeof entry === "string", `uniform \`${uniform}\` must be a number, number array, or CSS color, value: ${entry}`);- assert(parseColor(entry) !== null, `uniform \`${uniform}\` is not a valid CSS color: "${entry}"`);- }- }- setComponent(world, eid, c.Shader, { uniforms: { ...value } });- break;- }- case "fontFamily":- assert(typeof value === "string", "`fontFamily` must be a string" + `, value: ${value}`);- assert(value.trim().length > 0, "`fontFamily` must be a non-empty string");- setComponent(world, eid, c.TextStyle, { fontFamily: value.trim() });- break;- case "fontSize":- assert(typeof value === "number", "`fontSize` must be a number" + `, value: ${value}`);- assert(value > 0, "`fontSize` must be > 0");- setComponent(world, eid, c.TextStyle, { fontSize: Math.round(value) });- break;- case "fontWeight":- if (value === "normal") value = "400";- else if (value === "bold") value = "700";- else if (typeof value === "number") value = String(value);- assert(typeof value === "string", "`fontWeight` must be a number, \"normal\", or \"bold\"" + `, value: ${value}`);- assert(Number.isFinite(Number(value)), "`fontWeight` must be a number");- setComponent(world, eid, c.TextStyle, { fontWeight: value });- break;- case "fontStyle":- assert(typeof value === "string", "`fontStyle` must be a string" + `, value: ${value}`);- assert(value in FONT_STYLE_MAP, `invalid fontStyle value: "${value}"`);- setComponent(world, eid, c.TextStyle, { fontStyle: FONT_STYLE_MAP[value as keyof typeof FONT_STYLE_MAP] });- break;- case "textAlign":- assert(typeof value === "string", "`textAlign` must be a string" + `, value: ${value}`);- assert(value in TEXT_ALIGN_MAP, `invalid textAlign value: "${value}"`);- setComponent(world, eid, c.TextStyle, { textAlign: TEXT_ALIGN_MAP[value as keyof typeof TEXT_ALIGN_MAP] });- break;- case "textBaseline":- assert(typeof value === "string", "`textBaseline` must be a string" + `, value: ${value}`);- assert(value in TEXT_BASELINE_MAP, `invalid textBaseline value: "${value}"`);- setComponent(world, eid, c.TextStyle, { textBaseline: TEXT_BASELINE_MAP[value as keyof typeof TEXT_BASELINE_MAP] });- break;- case "color": {- const isStop = hasComponent(world, eid, c.ColorStop);- assert(isStop || hasComponent(world, eid, c.Paint), "`color` only applies to paints or color stops");- if (Array.isArray(value)) {- const keyframes = parseKeyframes(name, value, (v) => {- assert(typeof v === "string", "`color` must be a string" + `, value: ${v}`);- const color = parseColor(v);- assert(color !== null, `color is not a valid CSS color: "${v}"`);- return color;- });- if (isStop) setComponent(world, eid, c.ColorStop, { color: keyframes[0].value });- else setComponent(world, eid, c.Color, keyframes[0].value);- setKeyframeTrack(world, eid, isStop ? "stop.color" : "color", keyframes);- break;- }- setKeyframeTrack(world, eid, isStop ? "stop.color" : "color", []);- assert(typeof value === "string", "`color` must be a string" + `, value: ${value}`);- const color = parseColor(value);- assert(color !== null, `color is not a valid CSS color: "${value}"`);- if (isStop) {- setComponent(world, eid, c.ColorStop, { color });- } else {- setComponent(world, eid, c.Color, color);- }- break;- } case "offset": {- assert(hasComponent(world, eid, c.ColorStop), "`offset` only applies to <ColorStop>");- if (Array.isArray(value)) {- const keyframes = parseKeyframes(name, value, (v) => {- assert(typeof v === "number", "`offset` must be a number" + `, value: ${v}`);- assert(v >= 0 && v <= 1, "`offset` must be between 0 and 1");- return v;- });- setComponent(world, eid, c.ColorStop, { offset: keyframes[0].value });- setKeyframeTrack(world, eid, "stop.offset", keyframes);- break;- }- setKeyframeTrack(world, eid, "stop.offset", []);- assert(typeof value === "number", "`offset` must be a number" + `, value: ${value}`);- assert(value >= 0 && value <= 1, "`offset` must be between 0 and 1");- setComponent(world, eid, c.ColorStop, { offset: value });- break;- } case "preset": {- assert(hasComponent(world, eid, c.Caption), "`preset` only applies to <Captions>");- assert(typeof value === "string", "`preset` must be a string" + `, value: ${value}`);- assert(value in CAPTION_PRESET_MAP, `invalid preset value: "${value}"`);- setComponent(world, eid, c.Caption, { type: CAPTION_PRESET_MAP[value as keyof typeof CAPTION_PRESET_MAP] });- break;- } case "colors": {- assert(hasComponent(world, eid, c.Caption), "`colors` only applies to <Captions>");- assert(Array.isArray(value), "`colors` must be an array of CSS colors" + `, value: ${value}`);- const colors = value.map((entry) => {- assert(typeof entry === "string", "`colors` entries must be strings" + `, value: ${entry}`);- const color = parseColor(entry);- assert(color !== null, `colors entry is not a valid CSS color: "${entry}"`);- return color;- });- setComponent(world, eid, c.Caption, { colors });- break;- } case "verticalAlign": {- assert(hasComponent(world, eid, c.Caption), "`verticalAlign` only applies to <Captions>");- assert(typeof value === "string", "`verticalAlign` must be a string" + `, value: ${value}`);- assert(value in CAPTION_ALIGN_MAP, `invalid verticalAlign value: "${value}"`);- setComponent(world, eid, c.Caption, { verticalAlign: CAPTION_ALIGN_MAP[value as keyof typeof CAPTION_ALIGN_MAP] });- // A live decoder has already placed the box from the old alignment.- c.CaptionDecoder[eid]?.reposition(world, eid);- break;- } case "seed": {- assert(hasComponent(world, eid, c.Caption), "`seed` only applies to <Captions>");- assert(typeof value === "number", "`seed` must be a number" + `, value: ${value}`);- if (!this.committed && !this.queue.some((item) => item.type === "caption" && item.eid === eid)) {- this.queue.push({ eid, type: "caption" });- }- break;- }- }- }-- public insertNode(parent: HostNode, node: HostNode, anchor?: HostNode) {- this.track(() => this.attach(parent, node, anchor));- this.flushConnectedSurfaces();- this.flushConnectedHtmlHosts();- }-- /**- * Links `node` under its parent: DOM nodes into the parent's DOM (an- * <HtmlPaint>'s host element, or an element under one), entities into the- * ECS tree. Both sides already exist — the tag's case decided the- * environment at creation — so insertion only validates and links.- */- private attach(parent: HostNode, node: HostNode, anchor?: HostNode): void {- const world = this.world;- const c = world.components;-- if (parent instanceof Element) {- assert(- node instanceof Element || node instanceof Text,- "a composition element cannot be <html> content; an SVG fragment (<rect>/<text>/<image>) compiles as SVG only inside <svg> or <g>; wrap it",- );- parent.insertBefore(node, anchor instanceof Node ? anchor : null);- return;- }- assert(parent instanceof EntityNode, "text nodes cannot contain children");-- // DOM content lands in the parent's html host (the wrapper's paint host- // for <Html>); text runs of a <Text> element land in its Data fragment.- if (node instanceof Element || node instanceof Text) {- if (parent === STAGE) {- // Only Solid's empty placeholders may sit at the stage; they hold- // root positions in `roots` but never touch the world.- assert(node instanceof Text && node.data === "", "the stage cannot contain content");- this.insertRoot(node, anchor);- return;- }-- const host = this.htmlHosts.get(parent.eid);- if (host !== undefined) {- host.element.insertBefore(node, anchor instanceof Node && anchor.parentNode === host.element ? anchor : null);- return;- }-- if (this.isTextEntity(parent.eid)) {- assert(node instanceof Text, "a text element can only contain text");- const data = this.data(parent.eid);- if (data.textBox === undefined) {- data.textBox = document.createDocumentFragment();- this.nodeOwner.set(data.textBox, parent.eid);- }- data.textBox.insertBefore(node, anchor instanceof Node && anchor.parentNode === data.textBox ? anchor : null);- this.syncChars(parent.eid);- return;- }-- // Anywhere else only the empty placeholders Solid's control flow- // leaves behind pass; they stay unparented and act as inert anchors.- assert(node instanceof Text && node.data === "", "this element cannot contain text or DOM content");- return;- }-- if (parent !== STAGE) {- assert(- !this.htmlHosts.has(parent.eid),- "a composition element cannot be <html> content; an SVG fragment (<rect>/<text>/<image>) compiles as SVG only inside <svg> or <g>; wrap it",- );- assert(- this.adopted.has(node.eid) || !hasComponent(world, node.eid, c.Scene),- "a scene cannot be nested: the `scene` property is valid only at the document root",- );- // Adopted entities already sit under their persisted parent, so this- // no-ops for them on the initial adopt render; afterwards it moves and- // resurrects them like any other entity (e.g. a <For> shuffling rows).- this.attachEntity(node.eid, parent.eid);- return;- }-- this.insertRoot(node, anchor);- const eid = node.eid;-- // An adopted root is already placed and parented in the world; re-running- // placement/replace would overwrite its persisted position and delete it.- if (this.adopted.has(eid)) {- this.rootEid = eid;- return;- }-- if (this.stageEid !== undefined) {- this.attachEntity(eid, this.stageEid);- } else {- assert(- hasComponent(world, eid, c.Scene),- 'only a scene can be a mount root: promote a rectangle geometry with `scene`, e.g. <rect scene="main" width={1920} height={1080}>',- );- const key = c.Key[eid];-- // Find and replace node with the same key- const existing = query(world, [c.Key, Not(c.Deleted)])- .find((other) => other !== eid && c.Key[other] === key);-- if (existing === undefined) {- const { width, height } = this.props(eid) ?? {};- assert(- typeof width === "number" && typeof height === "number",- "a scene requires numeric `width` and `height`",- );- setComponent(world, eid, c.Position, this.findPlacement(width, height));- } else {- setComponent(world, eid, c.Position, {- x: c.Position.x[existing] ?? 0,- y: c.Position.y[existing] ?? 0,- });- deleteEntity(world, existing);- }- }-- // Stamp the mount's identity on its root so any world can re-run the- // module (export, capture, reload) in adopt mode.- if (this.mode === "author" && this.mountId !== undefined && this.scriptAssetId !== undefined) {- setComponent(world, eid, c.MountScript, {- mountId: this.mountId,- scriptAssetId: this.scriptAssetId,- });- }-- this.rootEid = eid;- }-- /** Places a node into the stage's `roots` list (its only bookkeeping). */- private insertRoot(node: HostNode, anchor?: HostNode): void {- const existing = this.roots.indexOf(node);- if (existing !== -1) this.roots.splice(existing, 1);- const index = anchor !== undefined ? this.roots.indexOf(anchor) : -1;- if (index === -1) this.roots.push(node);- else this.roots.splice(index, 0, node);- }-- // Fresh entities append; an entity that already has a parent is a Solid- // reorder or reparent (e.g. a <For> moving rows in a live mount).- private attachEntity(eid: number, parentEid: number): void {- const c = this.world.components;- if (hasComponent(this.world, eid, c.Deleted)) {- // Like a DOM node, an entity this render just removed re-attaches- // intact; anything something else deleted stays dead.- if (!this.removed.delete(eid)) return;- for (const e of getEntityTree(this.world, eid)) {- removeComponent(this.world, e, c.Deleted);- }- this.managed.add(eid);- }- const currentParent = getParentEntity(this.world, eid);- if (currentParent === null) {- appendChild(this.world, eid, parentEid);- return;- }- if (currentParent !== parentEid) {- removeChild(this.world, eid, currentParent);- appendChild(this.world, eid, parentEid);- }- }-- /**- * A `ref` callback (the renderer's `use`). DOM elements exist eagerly, so- * their refs fire immediately; surface refs receive the paint's backing- * canvas, which is only sized once the ancestor chain exists, so they wait- * for the subtree to connect to the stage.- */- public applyRef(node: HostNode, ref: (target: unknown) => void): void {- if (node instanceof Element || node instanceof Text) {- solid.untrack(() => ref(node));- return;- }- const pending = this.pendingSurfaces.find((entry) => entry.eid === node.eid);- assert(pending !== undefined, "`ref` is only supported on surface elements");- pending.ref = ref;- }-- /**- * The box a canvas paint's bitmap is initially allocated at: the nearest- * explicit size up the entity's ancestor chain (every element's box- * defaults to its parent's), falling back to a live ancestor's computed- * size for mounts into existing entities (`dapi node insert`).- */- private resolveBoxSize(eid: number): { width: number; height: number } {- const c = this.world.components;- let width: number | undefined;- let height: number | undefined;-- // Recorded props first — entities in the mounted subtree are fresh, so- // their Computed sizes are defaults, not layout. Live ancestors'- // Computed only backstops mounts into existing entities (node insert).- for (let cursor: number | null = eid; cursor !== null; cursor = getParentEntity(this.world, cursor)) {- const props = this.props(cursor);- width ??= sizeProp(props?.width);- height ??= sizeProp(props?.height);- if (width !== undefined && height !== undefined) return { width, height };- }- for (let cursor: number | null = eid; cursor !== null; cursor = getParentEntity(this.world, cursor)) {- // Freshly created entities carry no Size yet; only already live ones- // (e.g. the target of a `node insert`) carry a real box.- if (!hasComponent(this.world, cursor, c.Size)) continue;- width ??= c.Computed.width[cursor] || undefined;- height ??= c.Computed.height[cursor] || undefined;- if (width !== undefined && height !== undefined) break;- }-- return { width: width ?? 300, height: height ?? 150 };- }-- /** Whether the entity's ancestor chain reaches the stage. */- private isConnected(eid: number): boolean {- for (let cursor: number | null = eid; cursor !== null; cursor = getParentEntity(this.world, cursor)) {- if (cursor === this.stageEid) return true;- const handle = this.entityNodes.get(cursor);- if (handle !== undefined && this.roots.includes(handle)) return true;- }- return false;- }-- /**- * Sizes and hands out the canvases of surfaces whose subtree just connected- * to the stage: the box size walks ancestor props, and Solid attaches a- * subtree's root last, so only now is the chain complete. Disconnected- * surfaces stay pending — a Solid reorder removes and re-inserts them.- */- private flushConnectedSurfaces(): void {- if (this.pendingSurfaces.length === 0) return;- this.pendingSurfaces = this.pendingSurfaces.filter((entry) => {- if (!this.isConnected(entry.eid)) return true;-- const boxEid = entry.paint ? getParentEntity(this.world, entry.eid) ?? entry.eid : entry.eid;- const box = this.resolveBoxSize(boxEid);- entry.host.setSize(box.width, box.height);- if (entry.ref !== undefined) {- const ref = entry.ref;- solid.untrack(() => ref(entry.host.canvas));- }- return false;- });- }-- private flushConnectedHtmlHosts(): void {- if (this.pendingHtmlHosts.length === 0) return;- this.pendingHtmlHosts = this.pendingHtmlHosts.filter((entry) => {- if (!this.isConnected(entry.eid)) return true;-- const boxEid = entry.paint ? getParentEntity(this.world, entry.eid) ?? entry.eid : entry.eid;- const box = this.resolveBoxSize(boxEid);- entry.host.setSize(box.width, box.height);- return false;- });- }-- /**- * Wires an html host to the element the renderer inserts DOM content under- */- private registerHtmlHost(eid: number, host: HtmlHost, paint: boolean): void {- this.htmlHosts.set(eid, host);- this.nodeOwner.set(host.element, eid);- this.pendingHtmlHosts.push({ eid, host, paint });- }-- /**- * Adopt mode: rebuild the runtime-only hosts a persisted entity can't carry,- * binding a fresh host to the existing (adopted) paint entity. Mirrors the- * host setup in `createEntityForTag` but never creates structural entities.- */- private reattachRuntimeHostsForTag(tag: string, eid: number): void {- const world = this.world;- const c = world.components;-- switch (tag) {- case "SurfacePaint": {- const host = this.trackHost(new SurfaceHost());- addComponent(world, eid, c.SurfaceHost, false);- c.SurfaceHost[eid] = host;- this.pendingSurfaces.push({ eid, host, paint: true });- break;- }- case "Surface": {- const fid = this.findPaintChild(eid, PaintType.SURFACE);- assert(fid !== undefined, "adopted <Surface> has no surface paint child");- const host = this.trackHost(new SurfaceHost());- addComponent(world, fid, c.SurfaceHost, false);- c.SurfaceHost[fid] = host;- this.pendingSurfaces.push({ eid, host, paint: false });- break;- }- case "HtmlPaint": {- const host = this.trackHost(new HtmlHost());- addComponent(world, eid, c.HtmlHost, false);- c.HtmlHost[eid] = host;- this.registerHtmlHost(eid, host, true);- break;- }- case "Html": {- const fid = this.findPaintChild(eid, PaintType.HTML);- assert(fid !== undefined, "adopted <Html> has no html paint child");- const host = this.trackHost(new HtmlHost());- addComponent(world, fid, c.HtmlHost, false);- c.HtmlHost[fid] = host;- this.registerHtmlHost(eid, host, false);- break;- }- }- }-- /** The child paint entity of `eid` carrying the given paint type, if any. */- private findPaintChild(eid: number, paint: PaintType): number | undefined {- const world = this.world;- const c = world.components;- for (const fid of query(world, [ChildOf(eid), c.Paint, Not(c.Deleted)])) {- if (c.Paint[fid] === paint) return fid;- }- return undefined;- }-- public removeNode(parent: HostNode, node: HostNode) {- this.track(() => {- if (node instanceof Element || node instanceof Text) {- const owner = node.parentNode !== null ? this.nodeOwner.get(node.parentNode) : undefined;- node.remove();- if (owner !== undefined && this.isTextEntity(owner)) this.syncChars(owner);- const index = this.roots.indexOf(node);- if (index !== -1) this.roots.splice(index, 1);- return;- }- if (parent === STAGE) {- // Stage roots persist in the world past their mount — removal only- // forgets the renderer's bookkeeping.- const index = this.roots.indexOf(node);- if (index !== -1) this.roots.splice(index, 1);- return;- }- if (parent instanceof EntityNode) {- // A stale removal of an already-dead entity (the old graph of a- // superseded mount racing its dispose) must not detach or re-arm it.- if (hasComponent(this.world, node.eid, this.world.components.Deleted)) return;- removeChild(this.world, node.eid, parent.eid);- deleteEntity(this.world, node.eid);- this.managed.delete(node.eid);- this.removed.add(node.eid);- }- });- }-- public getParentNode(node: HostNode): HostNode | undefined {- if (node instanceof Element || node instanceof Text) {- const parent = node.parentNode;- if (parent === null) return undefined;- const owner = this.nodeOwner.get(parent);- if (owner !== undefined) return this.entity(owner);- return parent instanceof Element ? parent : undefined;- }- if (this.roots.includes(node)) return STAGE;- const parent = getParentEntity(this.world, node.eid);- return parent === null ? undefined : this.entity(parent);- }-- public getFirstChild(node: HostNode): HostNode | undefined {- if (node instanceof Element) return node.firstChild as Element | Text | null ?? undefined;- if (node instanceof Text) return undefined;- if (node === STAGE) return this.roots[0];- const host = this.htmlHosts.get(node.eid);- if (host !== undefined) return host.element.firstChild as Element | Text | null ?? undefined;- if (this.isTextEntity(node.eid)) {- const c = this.world.components;- const textBox = hasComponent(this.world, node.eid, c.Data) ? c.Data[node.eid]?.textBox : undefined;- return textBox?.firstChild as Text | null ?? undefined;- }- const first = this.entityChildren(node.eid)[0];- return first === undefined ? undefined : this.entity(first);- }-- public getNextSibling(node: HostNode): HostNode | undefined {- if (node instanceof Element || node instanceof Text) {- return node.nextSibling as Element | Text | null ?? undefined;- }- const parent = getParentEntity(this.world, node.eid);- if (parent === null) {- const index = this.roots.indexOf(node);- return index === -1 ? undefined : this.roots[index + 1];- }- const siblings = this.entityChildren(parent);- const index = siblings.indexOf(node.eid);- const next = index === -1 ? undefined : siblings[index + 1];- return next === undefined ? undefined : this.entity(next);- }-- /**- * The renderer-visible entity children of `eid`: its ECS children filtered- * to this render's managed set, so internal sub-entities (a <Text>'s paint)- * and hand-added children stay out of Solid's reconciliation.- */- private entityChildren(eid: number): number[] {- const c = this.world.components;- return [...query(this.world, [ChildOf(eid), Not(c.Deleted)])].filter((child) => this.managed.has(child));- }-- private findPlacement(width: number, height: number): { x: number; y: number } {- const center = findEmptyPlacement(this.world, width, height, PLACEMENT_GAP, this.placedRootBoxes);- this.placedRootBoxes.push({- minX: center.x - width / 2,- minY: center.y - height / 2,- maxX: center.x + width / 2,- maxY: center.y + height / 2,- });- return {- x: Math.round(center.x - width / 2),- y: Math.round(center.y - height / 2),- };- }-- /**- * Attaches a resolved asset to a media element — shared by plain `src`- * values (resolved during mount) and generated assets (landing after commit).- */- private async mountSource(eid: number, src: string) {- const asset = await resolveAsset(this.world, src);- const transcript = asset.type === 'TRANSCRIPT' ? await resolveTranscript(asset) : null;-- this.track(() => {- const world = this.world;- const c = world.components;-- if (asset.type === 'TRANSCRIPT') {- // AssetId set here makes commit's caption phase skip transcription.- setComponent(world, eid, c.AssetId, asset.id);- setComponent(world, eid, c.Trim, transcriptTrim(transcript!));- } else if (asset.type === 'AUDIO') {- setComponent(world, eid, c.AssetId, asset.id);- resizeEntity(world, eid, { width: 500, height: 150 });- } else if (asset.type === 'IMAGE' || asset.type === 'VIDEO') {- const fid = createEntity(world);- setComponent(world, fid, c.Paint, asset.type === 'IMAGE' ? PaintType.IMAGE : PaintType.VIDEO);- const objectFit = this.props(eid)?.objectFit as keyof typeof SCALE_MODE_MAP | undefined;- setComponent(world, fid, c.ScaleMode, objectFit ? SCALE_MODE_MAP[objectFit] : ScaleMode.COVER);- setComponent(world, fid, c.AssetId, asset.id);- // The asset resolves after the element's JSX paint children have- // attached, but the media paint belongs at the bottom of the stack:- // paint children draw over it, and a shader paint reads it.- const fills = query(world, [c.Paint, ChildOf(eid), Not(c.Deleted)]);- if (fills.length > 0) {- setComponent(world, fid, c.ItemIndex, Math.min(...fills.map((f) => c.ItemIndex[f] ?? 0)) - 1);- }- appendChild(world, fid, eid);-- if (!hasComponent(world, eid, c.Size)) {- resizeEntity(world, eid, { width: asset.width, height: asset.height });- }- }-- setComponent(world, eid, c.Name, asset.name);- });- }-- /**- * `src` of an `<img>` inside html content. It takes the same inputs as a- * composition `src` — a path, an asset id, a URL, or a `generate.*` ref —- * which the module can't read itself, so they resolve through the host into- * an object URL. Sources the browser can already fetch (`data:`, `blob:`)- * are set as they are.- */- private setImageSource(el: HTMLImageElement, value: unknown): void {- const epoch = (this.imageEpochs.get(el) ?? 0) + 1;- this.imageEpochs.set(el, epoch);-- if (typeof value === "string" && DIRECT_SRC_RE.test(value)) {- this.pointImageAt(el, value, false);- return;- }-- // An empty `src` is the placeholder a signal reads before its source- // exists, so it clears the element rather than failing the render.- if (typeof value === "string" && value.trim().length === 0) {- this.releaseImageUrl(el);- el.removeAttribute("src");- return;- }-- assert(- isAssetRef(value) || typeof value === "string",- "an <img> `src` must be a path, URL, asset id, or `generate.*` ref" + `, value: ${value}`,- );-- this.trackImageLoad((async () => {- const input = value as AssetInput;- const asset = isAssetRef(input)- ? await resolveGeneratedAsset(this.world, input, new Map())- : await resolveAsset(this.world, input);- const file = await getAssetFile(asset);-- // A newer `src` claimed this element while the old one resolved.- if (this.imageEpochs.get(el) !== epoch) return;-- this.pointImageAt(el, URL.createObjectURL(file), true);- // Decoded here rather than at draw time so the first frame that samples- // this subtree already has pixels; a broken source just paints nothing.- await el.decode().catch(() => undefined);- })());- }-- /** Points the element at `url`, freeing the object URL it held before. */- private pointImageAt(el: HTMLImageElement, url: string, owned: boolean): void {- this.releaseImageUrl(el);- if (owned) this.objectUrls.set(el, url);- el.src = url;- }-- /** Frees the object URL this element holds, if it minted one. */- private releaseImageUrl(el: HTMLImageElement): void {- const url = this.objectUrls.get(el);- if (url === undefined) return;- URL.revokeObjectURL(url);- this.objectUrls.delete(el);- }-- /**- * Makes an image source part of what a render waits for: `commit()` for the- * initial mount, so export and capture have it by frame 0, and the world's- * promise queue, which offline renders drain before every frame — that is- * what catches a live mount swapping `src` mid-timeline. Only the commit- * copy rejects; a source that breaks later must not take an export down.- */- private trackImageLoad(promise: Promise<void>): void {- this.world.promises?.push(promise.catch(() => undefined));- if (this.committed) promise.catch(console.error);- else this.promises.push(promise);- }--}--/**- * Prop assignment for DOM nodes inside <HtmlPaint>: enough of Solid's DOM- * conventions (style objects, class, classList, innerHTML) for drawn markup.- * Event handlers are dropped — the content is painted, not interactive.- */-function setDomProperty(el: Element, name: string, value: unknown): void {- if (typeof value === "function") return;-- if (name === "style") {- const style = (el as HTMLElement).style;- if (typeof value === "string") {- style.cssText = value;- } else if (typeof value === "object" && value !== null) {- Object.assign(style, value);- }- } else if (name === "class" || name === "className") {- el.setAttribute("class", String(value));- } else if (name === "classList") {- if (typeof value === "object" && value !== null) {- for (const [key, on] of Object.entries(value)) {- el.classList.toggle(key, !!on);- }- }- } else if (name === "innerHTML") {- el.innerHTML = String(value);- } else if (name === "textContent") {- el.textContent = String(value);- } else if (value === false || value === null) {- el.removeAttribute(name);- } else {- el.setAttribute(name, value === true ? "" : String(value));- }-}--function placeholderSize(spec: AssetSpecInput): { width: number; height: number } {- if (spec.type === "image" || spec.type === "video") {- return ASPECT_RATIO_DIMENSIONS[spec.aspectRatio ?? "16:9"] ?? { width: 1920, height: 1080 };- }- return { width: 500, height: 150 };-}--function parseFrames(value: string | null | undefined, fps: number): number | undefined {- const seconds = parseTime(value);- return seconds === undefined ? undefined : Math.round(seconds * fps);-}--/**- * Reads a recorded width/height prop as a number; keyframed sizes read as their first keyframe.- */-function sizeProp(value: unknown): number | undefined {- if (typeof value === "number") return value;- if (Array.isArray(value) && typeof (value[0] as { value?: unknown })?.value === "number") {- return (value[0] as { value: number }).value;- }- return undefined;-}--/**- * Evaluates a compiled project module. The CLI ships a- * single-file ESM bundle whose host modules are left external under the- * "dapi-host:" prefix- */--// Must match HOST_MODULE_PREFIX in @diffusionstudio/cli's compile step.-const HOST_MODULE_PREFIX = "dapi-host:";--const HOST_MODULES: Record<string, object> = {- "solid-js": solid,- "solid-js/store": solidStore,- "@diffusionstudio/jsx": diffusionJsx,-};--declare global {- var __dapiHostModules__: Record<string, object> | undefined;-}--const shimUrls = new Map<string, string>();--// A blob module cannot import bare specifiers, so the shim reaches its target-// namespace through a global and re-exports every name statically.-function getShimUrl(name: string): string {- const cached = shimUrls.get(name);- if (cached) return cached;-- const ns = HOST_MODULES[name]!;- globalThis.__dapiHostModules__ ??= {};- globalThis.__dapiHostModules__[name] = ns;-- const lines = [`const m = globalThis.__dapiHostModules__[${JSON.stringify(name)}];`];- for (const key of Object.keys(ns)) {- if (key === "default") continue;- lines.push(`export const ${key} = m[${JSON.stringify(key)}];`);- }- if ("default" in ns) lines.push("export default m.default;");-- const url = URL.createObjectURL(new Blob([lines.join("\n")], { type: "text/javascript" }));- shimUrls.set(name, url);- return url;-}--export async function importProjectModule(code: string): Promise<Record<string, unknown>> {- let rewritten = code;- for (const name of Object.keys(HOST_MODULES)) {- rewritten = rewritten.replaceAll(- JSON.stringify(`${HOST_MODULE_PREFIX}${name}`),- JSON.stringify(getShimUrl(name)),- );- }-- const url = URL.createObjectURL(new Blob([rewritten], { type: "text/javascript" }));- try {- // Top-level code (including top-level await) runs to completion here.- return (await import(/* @vite-ignore */ url)) as Record<string, unknown>;- } finally {- URL.revokeObjectURL(url);- }-}diff --git a/apps/web/src/utils/mount.ts b/apps/web/src/utils/mount.tsdeleted file mode 100644index f7f44b9a..00000000--- a/apps/web/src/utils/mount.ts+++ /dev/null@@ -1,135 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { query, Not } from "bitecs";-import { renderProject } from "@diffusionstudio/jsx";--import { EntityNode, WorldDocument, importProjectModule } from "@/utils/jsx";-import { getAssetFile } from "@/components/engine/api/assets";-import { assert } from "@/utils";--import type { Engine, EngineWorld } from "@/components/engine";--export interface RenderMountOptions {- mode: "author" | "adopt";- mountId: string;- scriptAssetId: string;- adoptIndex?: Map<string, number>;- parentEid?: number;- engine?: Engine;-}--export interface RealizedMount {- document: WorldDocument;- /** Tears down the reactive graph AND frees the runtime hosts it created. */- dispose: () => void;-}--/** Root keys of a rendered mount (its top-level entities' `Key` values). */-export function documentRootKeys(world: EngineWorld, document: WorldDocument): string[] {- const keys: string[] = [];- for (const node of document.roots) {- if (!(node instanceof EntityNode)) continue;- const key = world.components.Key[node.eid];- if (key !== undefined) keys.push(key);- }- return keys;-}--/**- * Evaluates a compiled project module and renders it into `world` through a- * WorldDocument, then settles async work (asset loads, generation). Shared by- * the author path (`dapi mount`) and the adopt path (restore/export/capture).- * The returned `dispose` frees both the reactive graph and the hosts it made.- */-export async function renderMount(- world: EngineWorld,- code: string,- options: RenderMountOptions,-): Promise<RealizedMount> {- const module = await importProjectModule(code);- const project = module.default as () => unknown;- assert(typeof project === "function", "The project module must default-export a Solid component");-- const document = new WorldDocument(world, options);- const disposeGraph = renderProject(project, document);- await document.commit();-- return {- document,- dispose: () => {- disposeGraph();- document.disposeHosts();- },- };-}--/** Creation ordinal (`MountPath.path`) -> entity id for one mount, so adopt can bind the re-run. */-export function buildAdoptIndex(world: EngineWorld, mountId: string): Map<string, number> {- const c = world.components;- const index = new Map<string, number>();- for (const eid of query(world, [c.MountPath, Not(c.Deleted)])) {- if (c.MountPath.mountId[eid] !== mountId) continue;- index.set(c.MountPath.path[eid], eid);- }- return index;-}--/**- * Re-executes every mount recorded in `world` (via its `MountScript` root) in- * adopt mode: binds the re-run to the world's existing entities by `MountPath`,- * rebuilds the runtime-only hosts, and registers the graph so the per-frame- * `playbackSystem` drives it. This is how a cloned (export/capture) or restored- * (reload) world gets animated surfaces without host-sharing.- *- * A world's own re-entry is a no-op (`liveMounts.hasMount`). Every mount stays- * registered so the world's per-frame `playbackSystem` keeps driving it (live- * in the editor, per-frame during an offline export/capture render).- */-export async function realizeMounts(- world: EngineWorld,- options: { engine?: Engine } = {},-): Promise<{ disposeAll: () => void }> {- const c = world.components;- const seen = new Set<string>();-- const roots = [...query(world, [c.MountScript, Not(c.Deleted)])].filter((eid) => {- const mountId = c.MountScript.mountId[eid];- if (seen.has(mountId) || world.liveMounts.hasMount(mountId)) return false;- seen.add(mountId);- return true;- });-- for (const eid of roots) {- const mountId = c.MountScript.mountId[eid];- const scriptAssetId = c.MountScript.scriptAssetId[eid];-- try {- const asset = world.assets.get(scriptAssetId);- assert(asset, `mount ${mountId}: SCRIPT asset ${scriptAssetId} not found`);- const code = await getAssetFile(asset).then((file) => file.text());-- const adoptIndex = buildAdoptIndex(world, mountId);- const { document, dispose } = await renderMount(world, code, {- mode: "adopt",- mountId,- scriptAssetId,- adoptIndex,- engine: options.engine,- });-- world.liveMounts.register({- mountId,- rootKeys: () => documentRootKeys(world, document),- advance: () => document.advanceTicker(),- dispose,- });- } catch (error) {- // A single malformed mount must not break loading/exporting the world.- console.error(`realizeMounts: failed to realize mount ${mountId}`, error);- }- }-- return { disposeAll: () => world.liveMounts.disposeAll() };-}diff --git a/examples/README.md b/examples/README.mdindex e1754002..9a2a98f6 100644--- a/examples/README.md+++ b/examples/README.md@@ -1,19 +1,18 @@# ExamplesSelf-contained compositions demonstrating the JSX API (see [reference/jsx](../reference/jsx/README.md)).-Run from the repo root with the editor open (`dapi open`). Each root carries a stable `scene`-identity, so re-mounting an example replaces its scene in place.+Each root carries a stable `scene` identity, so re-mounting an example replaces its scene in place.-| Example | Command | Shows |-| --- | --- | --- |-| [01-basics.tsx](01-basics.tsx) | `dapi mount examples/01-basics.tsx` | the `scene` prop promoting a root, `<sequence>` with a dissolve, `<video>`, `<audio>`, `<image>`, `<text>` titles from data via `<For>` |-| [02-genai.tsx](02-genai.tsx) | `dapi mount examples/02-genai.tsx` | multi-stage generation: `generate.image` refs feeding `generate.video`, TTS voiceover, generated ambience, `<captions>` |-| [03-ticker.tsx](03-ticker.tsx) | `dapi mount examples/03-ticker.tsx` | declarative animation: `useTicker` + `createMemo` derived values driving props |-| [04-html-in-canvas.tsx](04-html-in-canvas.tsx) | `dapi mount examples/04-html-in-canvas.tsx` | `<html>`: an AI prompt box as real DOM, typed out from the playhead |-| [05-anime-timeline.tsx](05-anime-timeline.tsx) | `dapi mount examples/05-anime-timeline.tsx` | anime.js timeline seeked from `useTicker`, driving an ECS node and `<html>` content in lockstep |-| [06-three.tsx](06-three.tsx) | `dapi mount examples/06-three.tsx` | three.js WebGL renderer owning a `<surface>`, glTF model loaded over the network |-| [07-webgpu.tsx](07-webgpu.tsx) | `dapi mount examples/07-webgpu.tsx` | raw WebGPU on a `<surface>`: a triangle whose colors cycle with composition time |-| [08-shader-paint.tsx](08-shader-paint.tsx) | `dapi mount examples/08-shader-paint.tsx` | `<shaderPaint>` post-processing a `<video>`: WGSL chromatic aberration + vignette, uniforms patchable live |+| Example | Shows |+| --- | --- |+| [01-basics.tsx](01-basics.tsx) | the `scene` prop promoting a root, `<sequence>` with a dissolve, `<video>`, `<audio>`, `<image>`, `<text>` titles from data via `<For>` |+| [02-genai.tsx](02-genai.tsx) | multi-stage generation: `generate.image` refs feeding `generate.video`, TTS voiceover, generated ambience, `<captions>` |+| [03-ticker.tsx](03-ticker.tsx) | declarative animation: `useTicker` + `createMemo` derived values driving props |+| [04-html-in-canvas.tsx](04-html-in-canvas.tsx) | `<html>`: an AI prompt box as real DOM, typed out from the playhead |+| [05-anime-timeline.tsx](05-anime-timeline.tsx) | anime.js timeline seeked from `useTicker`, driving an ECS node and `<html>` content in lockstep |+| [06-three.tsx](06-three.tsx) | three.js WebGL renderer owning a `<surface>`, glTF model loaded over the network |+| [07-webgpu.tsx](07-webgpu.tsx) | raw WebGPU on a `<surface>`: a triangle whose colors cycle with composition time |+| [08-shader-paint.tsx](08-shader-paint.tsx) | `<shaderPaint>` post-processing a `<video>`: WGSL chromatic aberration + vignette, uniforms patchable live |Requirements: `02-genai.tsx` consumes generation credits (results are cached per session);`01-basics.tsx`, `06-three.tsx`, and `08-shader-paint.tsx` fetch remote media.diff --git a/packages/jsx/src/types.ts b/packages/jsx/src/types.tsindex 554507d6..50b142d1 100644--- a/packages/jsx/src/types.ts+++ b/packages/jsx/src/types.ts@@ -110,10 +110,10 @@ export type CaptionPreset =| "stark";/**- * Every property assignable through the renderer — exactly the set- * `WorldDocument.setProperty` accepts. This is the single property table:- * element props pick from it, and `dapi node patch` takes any subset per- * patch entry with identical value requirements, so JSX and CLI can't drift.+ * Every property assignable through the renderer's property-write path. This+ * is the single property table: element props pick from it, and a patch-style+ * command takes any subset per patch entry with identical value requirements,+ * so JSX and any patch API can't drift.*/export type PatchProps = {/**@@ -237,7 +237,7 @@ export type PatchProps = {seed?: number;};-/** Every PatchProps key, at runtime — the `dapi node patch` allowlist. */+/** Every PatchProps key, at runtime — the patch-command allowlist. */export const PATCH_PROP_KEYS = Object.keys({key: true,scene: true,diff --git a/packages/runtime/src/utils/live-mounts.ts b/packages/runtime/src/utils/live-mounts.tsindex 97961708..7caadf68 100644--- a/packages/runtime/src/utils/live-mounts.ts+++ b/packages/runtime/src/utils/live-mounts.ts@@ -3,7 +3,7 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. *//**- * JSX mounts (`dapi mount`) keep their Solid reactive graph running after+ * JSX mounts keep their Solid reactive graph running after* the mount lands, so signals, effects, and timers keep driving the mounted* entities. A run stays alive until the world is* disposed or a later mount claims one of its root keys: the keyed rootdiff --git a/reference/README.md b/reference/README.mdindex 7c112f01..80e139fa 100644--- a/reference/README.md+++ b/reference/README.md@@ -2,33 +2,25 @@Reference for `dapi`, the Diffusion Studio CLI. Every canvas and project command talks to the running app over a local socket. Responses are JSON written to stdout; errors are human-readable messages on stderr with a non-zero exit.-Each feature command has its own file (linked below). The JSX code syntax consumed by [`mount`](./mount.md) and [`node insert`](./node/insert.md) is specified in [jsx/](./jsx/README.md); the markup is **pseudo-SVG**, mirroring SVG's shape-and-paint model with the editor's own tags and props rather than the SVG spec.+Each feature command has its own file (linked below). The JSX code syntax specified in [jsx/](./jsx/README.md) is **pseudo-SVG**, mirroring SVG's shape-and-paint model with the editor's own tags and props rather than the SVG spec.## Groups-**Top-level:** [`open`](./open.md), [`whoami`](./whoami.md), [`logs`](./logs.md), [`screenshot`](./screenshot.md), [`report`](./report.md), [`context`](./context.md) (alias `ctx`), [`mount`](./mount.md), [`models`](./models.md), [`voices`](./voices.md), [`fonts`](./fonts.md), [`fetch`](./fetch.md).+**Top-level:** [`whoami`](./whoami.md), [`logs`](./logs.md), [`screenshot`](./screenshot.md), [`report`](./report.md), [`context`](./context.md) (alias `ctx`), [`capture`](./capture.md), [`models`](./models.md), [`voices`](./voices.md), [`fonts`](./fonts.md), [`fetch`](./fetch.md).| Group | Alias | Scope || ----- | ----- | ----- |-| `selection` | `sel` | Read and mutate the current node selection. |-| `node` | `n`, `entity` | Anything that targets one or more nodes; scenes are nodes too. |-| `project` | `p` | Create, list, open, and delete projects. |-| `asset` | `a` | Manage and inspect assets in the open project. |-| `folder` | `fld` | Organize the asset library into folders. |+| `media` | `m` | Inspect a media file by asset id or local path, without adding it to the project. |How the surface is divided:-- Declarative composition happens through `mount`, which renders a Solid JSX project into the canvas (see [jsx/](./jsx/README.md)); `node insert` runs the same pipeline but inserts the rendered nodes into an existing parent entity instead of mounting document roots.-- Scenes are created declaratively via `mount` (the `scene` property on a root, e.g. `<rect scene="...">`); there is no imperative scene command.-- AI asset generation (image / video / speech / audio) is declared in the project module (`generate.*`, see [jsx/generate.md](./jsx/generate.md)) and produced on mount. `models` and `voices` list what those declarations can reference.-- Inspecting an existing asset (probe / transcribe / listen / filmstrip / waveform / grab) lives under `media`; writing an asset's original file back to disk is `asset export`.-- Organizing the library lives under `folder`; moving assets between folders is `asset mv`.+- AI asset generation (image / video / speech / audio) is declared in the project module (`generate.*`, see [jsx/generate.md](./jsx/generate.md)). `models` and `voices` list what those declarations can reference.+- Inspecting an existing asset (probe / transcribe / listen / filmstrip / waveform / grab) lives under `media`.## Commands### App-- [`dapi open`](./open.md): launch the app, or open a file, folder, or deep link- [`dapi whoami`](./whoami.md): print the authenticated account- [`dapi logs`](./logs.md): recent console output from the running app- [`dapi screenshot`](./screenshot.md): capture the entire application window as a PNG@@ -37,42 +29,7 @@ How the surface is divided:### Document- [`dapi context`](./context.md): essential context about the open project-- [`dapi mount`](./mount.md): compile a Solid JSX project module and mount it into the canvas--### Selection--- [`dapi selection ls`](./selection/ls.md): list the selected nodes-- [`dapi selection set`](./selection/set.md): replace the selection-- [`dapi selection focus`](./selection/focus.md): frame the selection on the canvas--### Nodes--- [`dapi node ls`](./node/ls.md): raw entity records-- [`dapi node tree`](./node/tree.md): an entity's subtree as nested JSON-- [`dapi node grep`](./node/grep.md): search entity records with a regex-- [`dapi node capture`](./node/capture.md): capture a node to a labelled contact sheet, or one PNG per position-- [`dapi node insert`](./node/insert.md): insert JSX tags into an existing parent-- [`dapi node rm`](./node/rm.md): delete entities-- [`dapi node cp`](./node/cp.md): deep-clone nodes-- [`dapi node patch`](./node/patch.md): assign JSX props on existing entities-- [`dapi node render`](./node/render.md): render a scene to a video file--### Projects--- [`dapi project active`](./project/active.md): print the active project-- [`dapi project ls`](./project/ls.md): list projects-- [`dapi project create`](./project/create.md): create and open a project-- [`dapi project set`](./project/set.md): set the active project-- [`dapi project rm`](./project/rm.md): delete a project--### Assets--- [`dapi asset add`](./asset/add.md): add local files as assets-- [`dapi asset ls`](./asset/ls.md): raw asset records-- [`dapi asset tree`](./asset/tree.md): the library as its folder tree-- [`dapi asset rm`](./asset/rm.md): delete assets-- [`dapi asset mv`](./asset/mv.md): move assets into a folder-- [`dapi asset export`](./asset/export.md): write assets' original bytes to disk+- [`dapi capture`](./capture.md): render a node in isolation to a labelled contact sheet, or one PNG per position### Media@@ -83,14 +40,6 @@ How the surface is divided:- [`dapi media waveform`](./media/waveform.md): audio waveform PNG with silence highlighting- [`dapi media listen`](./media/listen.md): AI description of an audio track-### Folders--- [`dapi folder ls`](./folder/ls.md): list child folders-- [`dapi folder create`](./folder/create.md): create a folder-- [`dapi folder rename`](./folder/rename.md): rename a folder-- [`dapi folder mv`](./folder/mv.md): reparent folders-- [`dapi folder rm`](./folder/rm.md): delete folders (cascades)-### Generation reference- [`dapi models`](./models.md): list generation models and constraints@@ -107,20 +56,16 @@ How the surface is divided:## Shared types```ts-NodeRef = { id: number; name: string; type: string } // node ids are entity ids: integers-Size = { width: number; height: number }-Asset = { id: string; name: string; type: string } // asset ids are opaque strings (sqids)-Folder = { id: string; name: string; type: 'folder' } // folder ids are opaque strings (sqids)-Time = number | `${number}f` | "MM:SS" // seconds, frames at 30 fps ("45f"), or a clock string; see jsx/timing.md+Asset = { id: string; name: string; type: string } // asset ids are opaque strings (sqids)+Time = number | `${number}f` | "MM:SS" // seconds, frames at 30 fps ("45f"), or a clock string; see jsx/timing.md```-Time inputs take the `Time` format unless noted otherwise. Times in **outputs** are plain seconds, except the raw records of `node ls`, which use engine units (frames at 30 fps, packed colors, dB).+Time inputs take the `Time` format unless noted otherwise. Times in **outputs** are plain seconds.## Conventions-- **Stdout is JSON.** Commands that return a single record emit one JSON value. Commands that return a collection emit JSON Lines (one object per line, no surrounding array) so per-item results stay streamable. `node tree` and `asset tree` emit one nested object per root. Exceptions: `open` for file / URL / no-target writes nothing; `fonts --names-only` writes plain family names; `logs` writes plain formatted log lines; `mount` and `node insert` write nothing.-- **Batch commands are fail-fast** (`node rm`, `node patch`, `asset add`, …): one invalid input fails the whole command with a single stderr message and exit `1`. Ids are validated before anything changes, so a failed `rm`/`mv`/`cp` changes nothing; there are no per-item partial results.-- **Unix-style names are canonical:** list/read is `ls`, delete is `rm`, duplicate is `cp`, move/reparent is `mv`, search is `grep`. The longer English forms (`list`, `remove`, `duplicate`, `move`) are aliases of the Unix forms, not the other way around. `get` is a universal alias for `ls`. Commands without a natural Unix equivalent (`tree`, `rename`, `patch`, `add`, `create`, `active`, `context`, `whoami`, `open`, `focus`, `set`) keep their descriptive names.+- **Stdout is JSON.** Commands that return a single record emit one JSON value. Commands that return a collection emit JSON Lines (one object per line, no surrounding array) so per-item results stay streamable. Exceptions: `fonts --names-only` writes plain family names; `logs` writes plain formatted log lines.+- **Unix-style names are canonical.** Commands without a natural Unix equivalent (`context`, `whoami`) keep their descriptive names.- **Stderr:** human-readable error messages.- **Exit codes:** `0` on success, `1` on any error (missing file, app not running, invalid input, IPC error).-- **App must be running:** every command except `open`, `fonts`, and `fetch` talks to the open Diffusion Studio instance. If the app isn't running, the CLI prints an instruction to launch it and exits `1`. `report` is the one command that reads from the app but tolerates its absence, recording it in the issue instead of failing.+- **App must be running:** every command except `fonts` and `fetch` talks to the open Diffusion Studio instance. If the app isn't running, the CLI prints an instruction to launch it and exits `1`. `report` is the one command that reads from the app but tolerates its absence, recording it in the issue instead of failing.diff --git a/reference/asset/add.md b/reference/asset/add.mddeleted file mode 100644index b9d39b04..00000000--- a/reference/asset/add.md+++ /dev/null@@ -1,16 +0,0 @@-# `dapi asset add <paths...>`--Adds one or more local files as assets in the open project. The counterpart of [`asset export`](./export.md).--## Input--- `<paths...>`: absolute or relative file paths (resolved against CWD)-- `--folder <id>`: folder to place the new assets in (optional; default the library root)--## Output--JSON Lines on stdout, one `AssetRecord` per added file (the same shape [`asset ls`](./ls.md) prints).--## Errors--Exits non-zero before importing anything if `--folder` doesn't resolve to a folder. A file that fails to import fails the whole command with `<path>: <reason>` on stderr; files imported before the failure stay in the library.diff --git a/reference/asset/export.md b/reference/asset/export.mddeleted file mode 100644index cdb8827d..00000000--- a/reference/asset/export.md+++ /dev/null@@ -1,22 +0,0 @@-# `dapi asset export <ids...>`--Writes one or more assets' original file bytes to a location on the file system: the exact bytes stored in the library, streamed to disk in chunks (never buffered whole). No re-encode, no processing, no credits. Any asset type is accepted except image sequences. The counterpart of [`asset add`](./add.md).--## Input--- `<ids...>`: asset ids (required)-- `-o, --output <path>`: where to write (optional; default the system temp directory). Interpreted as:- - **a directory** when the path is an existing directory, ends with a path separator, or multiple ids are given. Created if missing. Each asset is written into it named after the asset, with an extension derived from its media type when the name lacks one. A name that collides with an existing file is uniquified with a ` (N)` suffix, never overwritten.- - **a file path** otherwise (single id only). Written exactly there, overwriting an existing file.--## Output--JSON Lines on stdout, one per exported asset, in the requested order:--```ts-{ id: string; path: string } // path = the file actually written-```--## Errors--Exits non-zero before writing anything if `--output` must be a directory (multiple ids, or a trailing path separator) but resolves to an existing file, if the output directory can't be created, if an id is unknown, or if an id is an image-sequence asset. An I/O failure mid-batch aborts the remaining writes and leaves no partial file for the failing asset; files written before it stay.diff --git a/reference/asset/ls.md b/reference/asset/ls.mddeleted file mode 100644index 425856a8..00000000--- a/reference/asset/ls.md+++ /dev/null@@ -1,20 +0,0 @@-# `dapi asset ls [ids...]`--The raw asset records, as persisted minus the file handles: every serializable property the asset carries (per-type media metadata, `folderId`, a stored `transcript`, …). The property-level counterpart to [`asset tree`](./tree.md)'s structure. With no ids, returns every asset in the library. Alias: `get`.--## Input--- `[ids...]`: zero or more asset ids (optional)--## Output--JSON Lines, one per asset:--```ts-AssetRecord = { id: string } & { [property: string]: unknown }-// e.g. name, type, mimeType, size, createdAt, folderId; duration/width/height/… by type-```--## Errors--An unknown id fails the whole command: nothing is printed to stdout and it exits non-zero with `No such asset: <id>` on stderr.diff --git a/reference/asset/mv.md b/reference/asset/mv.mddeleted file mode 100644index 0305f6a2..00000000--- a/reference/asset/mv.md+++ /dev/null@@ -1,20 +0,0 @@-# `dapi asset mv <ids...> [--to <folderId>]`--Moves one or more assets into a folder. Alias: `move`.--## Input--- `<ids...>`: asset ids (required)-- `--to <folderId>`: destination folder (optional; omitted = the library root)--## Output--JSON Lines on stdout, one per moved asset:--```ts-{ id: string; folderId: string | null }-```--## Errors--An unknown asset id, or a `--to` that doesn't resolve to a folder, fails the whole command before anything is moved.diff --git a/reference/asset/rm.md b/reference/asset/rm.mddeleted file mode 100644index 6236b1c0..00000000--- a/reference/asset/rm.md+++ /dev/null@@ -1,19 +0,0 @@-# `dapi asset rm <ids...>`--Deletes one or more assets from the open project by id. Alias: `remove`.--## Input--- `<ids...>`: asset ids (required)--## Output--JSON Lines on stdout, one per deleted asset:--```ts-{ id: string; name: string }-```--## Errors--An unknown id fails the whole command before anything is deleted.diff --git a/reference/asset/tree.md b/reference/asset/tree.mddeleted file mode 100644index ff0d4fe0..00000000--- a/reference/asset/tree.md+++ /dev/null@@ -1,22 +0,0 @@-# `dapi asset tree`--Prints the asset library of the open project as its folder tree: folders and assets interleaved in one array, each folder carrying its contents in `children`.--## Input--- `--folder <id>`: folder whose contents to list (optional; default the library root)-- `--depth <N>`: max depth, positive integer (optional; default = full tree). `--depth 1` yields just the direct entries of the listing root; a folder at the cutoff is listed without `children` (indistinguishable from a genuinely empty folder; raise the depth to tell them apart).--## Output--JSON Lines, one per entry of the listing root (no output if the listing root is empty); each entry carries its own subtree in `children`:--```ts-AssetTree = Array<(Asset | Folder) & { children?: AssetTree }> // one root entry per line-```--Folders are the entries with type `folder`. `children` is present only on folders with contents; assets never carry it.--## Errors--Exits non-zero if `--folder` doesn't resolve to a folder.diff --git a/reference/node/capture.md b/reference/capture.mdsimilarity index 96%rename from reference/node/capture.mdrename to reference/capture.mdindex 3304e9e3..910c1240 100644--- a/reference/node/capture.md+++ b/reference/capture.md@@ -1,6 +1,6 @@-# `dapi node capture <id> [-t, --time <time...>]`+# `dapi capture <id> [-t, --time <time...>]`-Renders a node in isolation at one or more timeline positions and merges them into **contact sheets**: up to 12 positions per PNG, each cell labelled with the timecode of the frame actually rendered and drawn as large as the sheet allows, so a few positions arrive as one high-resolution picture instead of a directory to open one by one. `--separate` writes a PNG per position instead. The node is drawn offscreen, tightly framed to its own bounds; siblings and overlapping scene content are not included, so capture a scene id to check composition. To grab a video asset's own pixels instead of the composited node, use [`media grab`](../media/grab.md).+Renders a node in isolation at one or more timeline positions and merges them into **contact sheets**: up to 12 positions per PNG, each cell labelled with the timecode of the frame actually rendered and drawn as large as the sheet allows, so a few positions arrive as one high-resolution picture instead of a directory to open one by one. `--separate` writes a PNG per position instead. The node is drawn offscreen, tightly framed to its own bounds; siblings and overlapping scene content are not included, so capture a scene id to check composition. To grab a video asset's own pixels instead of the composited node, use [`media grab`](./media/grab.md).## Inputdiff --git a/reference/fetch.md b/reference/fetch.mdindex 3c70e138..1ed87627 100644--- a/reference/fetch.md+++ b/reference/fetch.md@@ -2,7 +2,7 @@Downloads a video with [yt-dlp](https://github.com/yt-dlp/yt-dlp). Does not require the app to be running. yt-dlp is not bundled: install it separately (`brew install yt-dlp`, or `pipx install yt-dlp`). If it is not on `PATH`, the command exits `1` with an install hint; set `YT_DLP_PATH` to point at a specific binary.-This writes the file to disk only. To pull a downloaded file into the open project, add it afterwards: `dapi asset add <path>` (see [asset add](./asset/add.md)).+This writes the file to disk only; it does not touch the open project.## Argumentsdiff --git a/reference/folder/create.md b/reference/folder/create.mddeleted file mode 100644index a4dd1448..00000000--- a/reference/folder/create.md+++ /dev/null@@ -1,20 +0,0 @@-# `dapi folder create <name> [-p, --parent <id>]`--Creates a folder.--## Input--- `<name>`: folder name (required)-- `-p, --parent <id>`: parent folder (optional; omitted = the library root)--## Output--One JSON object:--```ts-Folder // { id: string; name: string; type: 'folder' }-```--## Errors--Exits non-zero if `--parent` doesn't resolve to a folder.diff --git a/reference/folder/ls.md b/reference/folder/ls.mddeleted file mode 100644index 001d58de..00000000--- a/reference/folder/ls.md+++ /dev/null@@ -1,21 +0,0 @@-# `dapi folder ls [parentId]`--Lists the direct child folders of a parent folder, sorted by name. With no id, lists the root-level folders. Aliases: `list`, `get`.--Folders organize the asset library and nest arbitrarily; assets reference their containing folder via `folderId` (`null` = library root). Everywhere a folder id is optional, omitting it means the library root; there is no sentinel value for the root. Read the full hierarchy (folders and assets together) with [`asset tree`](../asset/tree.md); move assets between folders with [`asset mv`](../asset/mv.md).--## Input--- `[parentId]`: parent folder id (optional; omitted = the library root)--## Output--JSON Lines, one per child folder (no output if the parent has no subfolders):--```ts-Folder // { id: string; name: string; type: 'folder' }-```--## Errors--Exits non-zero if `[parentId]` doesn't resolve to a folder.diff --git a/reference/folder/mv.md b/reference/folder/mv.mddeleted file mode 100644index c409aee5..00000000--- a/reference/folder/mv.md+++ /dev/null@@ -1,20 +0,0 @@-# `dapi folder mv <ids...> [--to <folderId>]`--Moves one or more folders under a new parent. A folder cannot be moved into itself or any of its descendants; such a move fails the command. Alias: `move`.--## Input--- `<ids...>`: folder ids (required)-- `--to <folderId>`: destination parent folder (optional; omitted = the library root)--## Output--JSON Lines on stdout, one per moved folder:--```ts-{ id: string; parentId: string | null }-```--## Errors--An unknown id, a cycle, or a `--to` that doesn't resolve to a folder fails the whole command before anything is moved.diff --git a/reference/folder/rename.md b/reference/folder/rename.mddeleted file mode 100644index 61830086..00000000--- a/reference/folder/rename.md+++ /dev/null@@ -1,16 +0,0 @@-# `dapi folder rename <id> <name>`--Renames a folder.--## Input--- `<id>`: folder id (required)-- `<name>`: new name (required)--## Output--One JSON object:--```ts-Folder // { id: string; name: string; type: 'folder' }-```diff --git a/reference/folder/rm.md b/reference/folder/rm.mddeleted file mode 100644index 6deaad12..00000000--- a/reference/folder/rm.md+++ /dev/null@@ -1,20 +0,0 @@-# `dapi folder rm <ids...>`--Deletes one or more folders. **Deletion cascades:** every descendant folder and every asset inside the subtree is deleted with it. The fulfilled record reports what the cascade removed, so callers can detect when a delete swept more than intended. Alias: `remove`.--## Input--- `<ids...>`: folder ids (required)--## Output--JSON Lines on stdout, one per deleted folder:--```ts-{ id: string; deletedFolders: number; deletedAssets: number }-// deletedFolders counts the folder itself plus all descendants-```--## Errors--An unknown id fails the whole command before anything is deleted.diff --git a/reference/jsx/README.md b/reference/jsx/README.mdindex 8fb44115..6f850ba1 100644--- a/reference/jsx/README.md+++ b/reference/jsx/README.md@@ -6,7 +6,7 @@ A project is structured like a SolidJS app: a **root** is established on the canThe markup is **pseudo-SVG**: elements like `<rect>`, `<text>`, `<linearGradientPaint>`, and `<colorStop>` mirror SVG's shape-and-paint model, but the tags and props are the editor's own (see [elements.md](./elements.md)), not the SVG spec.-The pipeline is driven by two commands: [`dapi mount`](../mount.md) renders the project's roots into the document, and [`dapi node insert`](../node/insert.md) runs the same pipeline into an existing parent entity. [`dapi node patch`](../node/patch.md) assigns the same props on existing nodes.+> **Status:** the CLI commands that drove this pipeline (`dapi mount`, `dapi node insert`, `dapi node patch`, and the rest of `dapi node`/`dapi asset`/`dapi project`/`dapi folder`/`dapi selection`) have been removed pending a rebuild where JSX becomes the source of truth for the document. This file documents the contract they will implement again: mounting a project's roots into the document, inserting into an existing parent entity, and assigning props on existing nodes. `dapi node capture` survived the cut as the top-level [`dapi capture`](../capture.md), unrelated to authoring — it only renders an existing node to PNGs.## Contents@@ -35,8 +35,8 @@ The pipeline is driven by two commands: [`dapi mount`](../mount.md) renders the## Pipeline-1. **Compile**: the CLI bundles the entry file with esbuild + `babel-preset-solid` in `universal` mode, so JSX compiles against the editor's renderer runtime (`@diffusionstudio/jsx`) instead of the DOM. Compile errors fail here, before the app is contacted.-2. **Ship**: the resulting single-file ESM bundle is sent to the running app over the local socket.+1. **Compile**: the entry file bundles with esbuild + `babel-preset-solid` in `universal` mode, so JSX compiles against the editor's renderer runtime (`@diffusionstudio/jsx`) instead of the DOM. Compile errors fail here, before the app is contacted.+2. **Ship**: the resulting single-file ESM bundle is delivered to the running app.3. **Evaluate**: the app imports the module. Top-level code (including top-level `await`) runs to completion. The module's **default export** is the project component.4. **Mount**: the component tree is rendered into a **staging root**. The universal renderer materializes each element as an ECS entity with the appropriate components (see [elements.md](./elements.md)). Mounting is synchronous; an error here aborts the import with nothing inserted.5. **Commit**: the rendered roots are reconciled against the document (see [roots.md](./roots.md)) as a **single undoable operation** that also covers the generated assets below.diff --git a/reference/jsx/animations.md b/reference/jsx/animations.mdindex 73afcc7a..d2faca93 100644--- a/reference/jsx/animations.md+++ b/reference/jsx/animations.md@@ -48,4 +48,3 @@ Text types apply only to [`<text>`](./text.md) and [`<captions>`](./captions.md)- `duration` and `delay` take any [time format](./timing.md#time-formats). An `"in"` animation plays over `[delay, delay + duration]` from the clip's in point; an `"out"` animation ends `delay` before the clip's out point. Both track the clip when it is retimed.- A node takes **any number of animations**; overlapping entries apply in list order, later ones writing over earlier ones on the properties they share. A [keyframe](./keyframes.md) track on the same property (say, keyframed `opacity` next to `"fade"`) overrides the preset while it has effect; presets and keyframes on distinct properties compose freely.- The list is **mount-shaped**: setting `animations` replaces the node's existing animations, `[]` removes them all, and an omitted prop leaves hand-added ones untouched.-- Animations land as regular editor animations, editable in the inspector. Part of the shared property table: [`dapi node patch`](../node/patch.md) accepts `animations` with identical semantics, e.g. `--json '[{ "id": 42, "animations": [{ "type": "fade" }] }]'`, and they list under `animations` in [`dapi node tree`](../node/tree.md).diff --git a/reference/jsx/audio-sync.md b/reference/jsx/audio-sync.mdindex 67c6b715..7883040d 100644--- a/reference/jsx/audio-sync.md+++ b/reference/jsx/audio-sync.md@@ -20,5 +20,3 @@## ExecutionAlignment runs at the sync stage of the [pipeline](./README.md#pipeline): after generated assets land (either side may be generated), before captions read the scene. It is local, consumes no credits, and blocks the command, so exit `0` means final placement. A correlation too weak to trust fails the command (see [errors.md](./errors.md)) while the node keeps its default placement. Offsets are **cached** by the pair of source contents, so re-mounting an unchanged project re-measures nothing.--Because `syncTo` is part of the shared property table, [`dapi node patch`](../node/patch.md) accepts it too: patching `syncTo` onto an existing node re-aligns it against the document node carrying that key.diff --git a/reference/jsx/captions.md b/reference/jsx/captions.mdindex 78ddbf0d..e114618d 100644--- a/reference/jsx/captions.md+++ b/reference/jsx/captions.md@@ -1,6 +1,6 @@# Captions-`<captions />` inside a scene transcribes that scene's audio into a caption node: a styled, timed transcript, produced on import. To caption an already-open scene, insert one with [`dapi node insert`](../node/insert.md).+`<captions />` inside a scene transcribes that scene's audio into a caption node: a styled, timed transcript, produced on import. To caption an already-open scene, insert one with `dapi node insert`.```tsx<captions />diff --git a/reference/jsx/elements.md b/reference/jsx/elements.mdindex c99d0cb5..bdad0516 100644--- a/reference/jsx/elements.md+++ b/reference/jsx/elements.md@@ -49,6 +49,3 @@ All visual elements accept:`Animatable` props also take a keyframe list; see [keyframes.md](./keyframes.md).-## One property table--Common and per-element props share a single property table, exported as `PatchProps` from `@diffusionstudio/jsx`. [`dapi node patch`](../node/patch.md) accepts exactly these keys, with the same value requirements, as patch entries on existing nodes; JSX and CLI cannot drift.diff --git a/reference/jsx/html.md b/reference/jsx/html.mdindex 61485632..c0a9f496 100644--- a/reference/jsx/html.md+++ b/reference/jsx/html.md@@ -40,7 +40,7 @@ The `<html>` box carries all [common props](./elements.md#common-props). Its pai## Reactivity-The children are part of the project's Solid graph: signals in attributes and text update the live DOM, and the drawn content follows on the next frame. A [`dapi mount`](../mount.md) stays live, so the graph keeps running and `useTicker` or timers can drive the markup:+The children are part of the project's Solid graph: signals in attributes and text update the live DOM, and the drawn content follows on the next frame. A `dapi mount` stays live, so the graph keeps running and `useTicker` or timers can drive the markup:```tsxconst [count, setCount] = createSignal(0);@@ -67,7 +67,7 @@ Like all paints, `<htmlPaint>` stacks with siblings in document order and clips## Persistence and export-The compiled module is persisted with the document: on reload, export, and `dapi node capture` the engine re-executes it and rebuilds the DOM content in that context. Exports wait for the browser's rendering update before sampling each frame, so the drawn HTML appears in the output; ticker-driven signals follow the playhead and animate frame-accurately. This assumes the module's structure is deterministic (`Math.random()`/`Date.now()` must not decide the shape of the tree).+The compiled module is persisted with the document: on reload, export, and `dapi capture` the engine re-executes it and rebuilds the DOM content in that context. Exports wait for the browser's rendering update before sampling each frame, so the drawn HTML appears in the output; ticker-driven signals follow the playhead and animate frame-accurately. This assumes the module's structure is deterministic (`Math.random()`/`Date.now()` must not decide the shape of the tree).## Requirements and limitationsdiff --git a/reference/jsx/keyframes.md b/reference/jsx/keyframes.mdindex e6142907..ce8774c3 100644--- a/reference/jsx/keyframes.md+++ b/reference/jsx/keyframes.md@@ -19,7 +19,7 @@ type Keyframe<T> = { time: Time; value: T; easing?: Easing };type Animatable<T> = T | Keyframe<T>[];```-Animatable props: `x`, `y`, `offsetX`, `offsetY`, `width`, `height`, `rotation`, `opacity`, `cornerRadius`, `volume`, `color`, `offset`. As part of the shared property table this applies to [`dapi node patch`](../node/patch.md) identically, and to [paints and color stops](./paints.md) (`color`, `opacity`, `offset` animate gradients). For preset in/out effects (fade, slides, text reveals, ...) use the [`animations` prop](./animations.md) instead.+Animatable props: `x`, `y`, `offsetX`, `offsetY`, `width`, `height`, `rotation`, `opacity`, `cornerRadius`, `volume`, `color`, `offset`. As part of the shared property table this applies to `dapi node patch` identically, and to [paints and color stops](./paints.md) (`color`, `opacity`, `offset` animate gradients). For preset in/out effects (fade, slides, text reveals, ...) use the [`animations` prop](./animations.md) instead.## Semanticsdiff --git a/reference/jsx/media.md b/reference/jsx/media.mdindex 50db6107..cc1f2fd4 100644--- a/reference/jsx/media.md+++ b/reference/jsx/media.md@@ -4,10 +4,10 @@- **Global path**: e.g. `"/Movies/video.mp4"`, resolved against the user's OS.- **Remote URL**: e.g. `"https://my.videoarchive.com/audio/clip.wav"`, registered as a remote asset.-- **Asset id**: e.g. `"gbHJ"`, an imported asset (discover ids with [`dapi asset ls`](../asset/ls.md) or [`dapi asset tree`](../asset/tree.md)).+- **Asset id**: e.g. `"gbHJ"`, an imported asset (discover ids with `dapi asset ls` or `dapi asset tree`).- **`AssetRef`**: the value returned by a `generate.*` declaration (see [generate.md](./generate.md)). The node is inserted immediately as a placeholder and its paint is attached once the asset has generated.-In [`dapi node patch`](../node/patch.md), `src` takes a path, URL, or asset id; `generate.*` declarations are JSX-only.+In `dapi node patch`, `src` takes a path, URL, or asset id; `generate.*` declarations are JSX-only.An `<img>` additionally takes a `data:` or `blob:` URL, which goes to the browser as it is.diff --git a/reference/jsx/paints.md b/reference/jsx/paints.mdindex 7f180456..ab20f970 100644--- a/reference/jsx/paints.md+++ b/reference/jsx/paints.md@@ -25,4 +25,4 @@ Paint elements are valid inside any filled visual element (`<rect>`, `<text>`, `Colors accept any CSS color; alpha is ignored (use `opacity`). `color`, `opacity`, and `offset` are animatable (see [keyframes.md](./keyframes.md)), so gradients can animate. Paints have no spatial or timing props and cannot be document roots.-Paints are live entities like any other: patch them with [`dapi node patch`](../node/patch.md), and add a stop to an existing gradient with [`dapi node insert`](../node/insert.md) (`node insert <paintId> '<colorStop offset={0.5} color="#FF0055" />'`).+Paints are live entities like any other: patch them with `dapi node patch`, and add a stop to an existing gradient with `dapi node insert` (`node insert <paintId> '<colorStop offset={0.5} color="#FF0055" />'`).diff --git a/reference/jsx/roots.md b/reference/jsx/roots.mdindex fb14827f..2b9955bb 100644--- a/reference/jsx/roots.md+++ b/reference/jsx/roots.md@@ -10,7 +10,7 @@ Identities must be unique within a render, and rebuilding keeps the scene's entiThe `scene` property is valid **only** at the document root.-[`dapi node insert`](../node/insert.md) skips this reconciliation entirely: its roots are inserted as children and every run inserts fresh entities.+`dapi node insert` skips this reconciliation entirely: its roots are inserted as children and every run inserts fresh entities.## Canvas placement@@ -19,4 +19,4 @@ The canvas holds many roots, but a root's position on the canvas is an **editor- **Rebuilt roots** (matched by `scene`) keep their existing canvas position.- **New roots** are placed automatically: in the nearest empty space around the current viewport center, gapped so they never overlap existing content (the same auto-placement the editor uses when generating onto the canvas). A mount that creates multiple roots places them side by side in render order.-The camera is not moved; because placement anchors to the viewport center, new roots typically land in view. Use [`dapi selection focus`](../selection/focus.md) to frame them explicitly.+The camera is not moved; because placement anchors to the viewport center, new roots typically land in view. Use `dapi selection focus` to frame them explicitly.diff --git a/reference/jsx/shader-paint.md b/reference/jsx/shader-paint.mdindex 8155254d..0125ab60 100644--- a/reference/jsx/shader-paint.md+++ b/reference/jsx/shader-paint.md@@ -84,7 +84,7 @@ Like all paints it stacks with siblings in document order; `<shaderPaint>` takes## Patching-Shader paints are live entities: find the paint id under the element with [`dapi node tree`](../node/tree.md), then patch [`dapi node patch`](../node/patch.md):+Shader paints are live entities: find the paint id under the element with `dapi node tree`, then patch `dapi node patch`:```bash# tweak parameters (hot update, no recompile)@@ -94,7 +94,7 @@ dapi node patch '[{ "id": 42, "uniforms": { "strength": 2 } }]'dapi node patch '[{ "id": 42, "wgsl": "..." }]'```-Attach one to an existing video with [`dapi node insert`](../node/insert.md) (`node insert <videoId> '<shaderPaint wgsl={...} />'`).+Attach one to an existing video with `dapi node insert` (`node insert <videoId> '<shaderPaint wgsl={...} />'`).## Errors and limitationsdiff --git a/reference/jsx/surface-paint.md b/reference/jsx/surface-paint.mdindex c9fecdd1..8c2f41ee 100644--- a/reference/jsx/surface-paint.md+++ b/reference/jsx/surface-paint.md@@ -25,7 +25,7 @@ An element backed by a **canvas you draw yourself**. The `ref` callback receives## Reactivity-The engine samples the canvas every frame, so anything you draw shows up on the next frame. A [`dapi mount`](../mount.md) stays live, so the reactive graph keeps running: create effects in the ref to redraw from signals, or drive frame-accurate motion from the ticker's composition time:+The engine samples the canvas every frame, so anything you draw shows up on the next frame. A `dapi mount` stays live, so the reactive graph keeps running: create effects in the ref to redraw from signals, or drive frame-accurate motion from the ticker's composition time:```tsx<surface width={400} height={400}@@ -81,7 +81,7 @@ Like all paints it stacks with siblings in document order and clips to the paren## Persistence and export-The compiled module is persisted with the document, so the drawing is reproducible, not ephemeral: on reload, export, and `dapi node capture` the engine re-executes it and redraws into a fresh canvas driven by that context's playhead, so ticker surfaces animate in exports. The bitmap itself is not stored; your code reproduces it. This assumes the module's structure is deterministic (`Math.random()`/`Date.now()` must not decide the shape of the tree; using them inside a draw effect is fine).+The compiled module is persisted with the document, so the drawing is reproducible, not ephemeral: on reload, export, and `dapi capture` the engine re-executes it and redraws into a fresh canvas driven by that context's playhead, so ticker surfaces animate in exports. The bitmap itself is not stored; your code reproduces it. This assumes the module's structure is deterministic (`Math.random()`/`Date.now()` must not decide the shape of the tree; using them inside a draw effect is fine).## Requirements and limitationsdiff --git a/reference/jsx/timing.md b/reference/jsx/timing.mdindex 50bc8b96..3ebd0e8c 100644--- a/reference/jsx/timing.md+++ b/reference/jsx/timing.md@@ -40,4 +40,4 @@ The canonical internal unit is frames at **30 fps**; all formats are converted o| `"MM:SS"` | `"02:30"` | Minutes and seconds. || `"HH:MM:SS"` | `"01:02:30"` | Hours, minutes, seconds. |-CLI flags documented as taking a `Time` value (e.g. `--time` on [`node capture`](../node/capture.md) and [`media grab`](../media/grab.md)) accept the same formats.+CLI flags documented as taking a `Time` value (e.g. `--time` on [`capture`](../capture.md) and [`media grab`](../media/grab.md)) accept the same formats.diff --git a/reference/jsx/transitions.md b/reference/jsx/transitions.mdindex 0b008390..f1810402 100644--- a/reference/jsx/transitions.md+++ b/reference/jsx/transitions.md@@ -34,4 +34,4 @@ The editor's transition inspector options:- `duration` takes any [time format](./timing.md#time-formats) and is centered on the cut: half plays before it, half after.- A **partial value merges** into the clip's existing transition: `transition={{ duration: 2 }}` keeps the current type; `transition={{}}` applies the defaults.- **`null` removes** the clip's transition.-- Part of the shared property table: [`dapi node patch`](../node/patch.md) accepts `transition` with identical semantics, e.g. `--json '[{ "id": 42, "transition": { "type": "dissolve" } }]'`.+- Part of the shared property table: `dapi node patch` accepts `transition` with identical semantics, e.g. `--json '[{ "id": 42, "transition": { "type": "dissolve" } }]'`.diff --git a/reference/media/grab.md b/reference/media/grab.mdindex cfbe5ad6..95f04e2d 100644--- a/reference/media/grab.md+++ b/reference/media/grab.md@@ -1,6 +1,6 @@# `dapi media grab <id|path>`-Decodes one or more frames of a video asset at the given times and merges them into **contact sheets**: up to 12 frames per PNG, each cell labelled with its timecode and drawn as large as the sheet allows, so a handful of frames arrives as one high-resolution picture instead of a directory to open one by one. `--separate` writes a PNG per frame instead. Like [`node capture`](../node/capture.md), but grabs the asset's own pixels (unlike `node capture`, which renders the composited node). Renders locally; no credits. Past ~12 frames, [`media filmstrip`](./filmstrip.md) is the cheaper way to scan a clip.+Decodes one or more frames of a video asset at the given times and merges them into **contact sheets**: up to 12 frames per PNG, each cell labelled with its timecode and drawn as large as the sheet allows, so a handful of frames arrives as one high-resolution picture instead of a directory to open one by one. `--separate` writes a PNG per frame instead. Like [`capture`](../capture.md), but grabs the asset's own pixels (unlike `capture`, which renders the composited node). Renders locally; no credits. Past ~12 frames, [`media filmstrip`](./filmstrip.md) is the cheaper way to scan a clip.## Inputdiff --git a/reference/mount.md b/reference/mount.mddeleted file mode 100644index b91a3d79..00000000--- a/reference/mount.md+++ /dev/null@@ -1,26 +0,0 @@-# `dapi mount (<path> | --code <str>)`--Compiles a Solid JSX project module and executes it in the app, mounting the rendered roots into the document. Like reloading a webpage, re-mounting rebuilds the roots in place instead of adding copies: only a scene is mountable as a root, declaring its identity in the JSX with `scene`, and `<rect scene="intro">` replaces the scene carrying that identity (or creates it).--The full JSX code syntax lives in [jsx/](./jsx/README.md); start with the [pipeline](./jsx/README.md#pipeline) and [roots](./jsx/roots.md).--## Input--Exactly one of:--- `<path>`: path to a `.tsx` / `.jsx` / `.ts` / `.js` entry module.-- `--code <str>`: inline module source, compiled identically. The `export default () =>` wrapper is optional; a bare JSX expression (no `export default` in the source) is wrapped into a component module automatically.--## Lifecycle--A mount stays live: its reactive graph keeps running after the command returns, so signals, effects, timers, and [`useTicker`](./jsx/lifecycle.md#useticker) keep driving the mounted entities. The compiled module is persisted with the document and re-executed in every context, so the mount is restored on reload and its ticker-driven [`<surface>`](./jsx/surface-paint.md)/[`<html>`](./jsx/html.md) animate in exports and captures (the module's structure must be deterministic). See [jsx/lifecycle.md](./jsx/lifecycle.md).--## Output--None. The command exits `0` once the tree is committed and every declared asset has generated; inspect the result with [`dapi context`](./context.md), [`dapi node ls`](./node/ls.md), or [`dapi node tree`](./node/tree.md).--## Notes--- A newly added top-level scene becomes the active scene.-- The command is long-running when assets are declared: it blocks until generation finishes (see [jsx/generate.md](./jsx/generate.md)).-- Compile errors fail before the app is contacted; mount errors insert nothing (see [jsx/errors.md](./jsx/errors.md)).diff --git a/reference/node/cp.md b/reference/node/cp.mddeleted file mode 100644index f80d5516..00000000--- a/reference/node/cp.md+++ /dev/null@@ -1,19 +0,0 @@-# `dapi node cp <ids...>`--Deep-clones one or more nodes, including all descendants. Alias: `duplicate`.--## Input--- `<ids...>`: one or more node ids (required)--## Output--JSON Lines on stdout, one per cloned node:--```ts-{ sourceId: number; newId: number }-```--## Errors--An unknown id fails the whole command before anything is cloned.diff --git a/reference/node/grep.md b/reference/node/grep.mddeleted file mode 100644index f7ca9f5d..00000000--- a/reference/node/grep.md+++ /dev/null@@ -1,32 +0,0 @@-# `dapi node grep <pattern> [id]`--Searches entity records for a pattern and prints the matching entities, with the components that matched. The search corpus is the raw records [`node ls`](./ls.md) would emit (component values stringified), so anything `ls` can show, `grep` can find; the caveat carries over too: values are raw engine units (frames at 30 fps, packed colors, dB). `[id]` scopes the search to a subtree, like giving `grep -r` a path.--The structural counterpart of [`tree`](./tree.md) (find entities by content rather than by position) and the discovery front-end to `ls`, [`selection set`](../selection/set.md), and [`patch`](./patch.md): `grep` to find ids, then read, select, or edit them.--The common case (find nodes by name) is `dapi node grep -k Name Title`. Presence queries work with a match-anything pattern: `dapi node grep -k Trim .` lists every entity carrying a `Trim` component.--## Input--- `<pattern>`: JavaScript regex, unanchored (required). Case-sensitive unless `-i` is given.-- `[id]`: root entity id (optional; omitted = every top-level node's subtree)-- `-i, --ignore-case`: case-insensitive matching-- `-t, --type <types...>`: only match entities of these node types (e.g. `-t text image`; the `type` values of `node tree`)-- `-k, --component <names...>`: restrict matching to these components (e.g. `-k Name Chars`; the component keys of `node ls`)-- `-l, --refs-only`: output only the matching entity refs, no match detail-- `-c, --count`: output only the number of matching entities--## Output--JSON Lines, one per matching entity (no output if nothing matches; this is a successful run, exit `0`); the structured analog of grep's `file:line:content`:--```ts-NodeRef & { matches: Array<{ component: string; value: string }> }-// value is the stringified component value the pattern matched-```--With `--refs-only`, plain `NodeRef` lines; with `--count`, a single number.--## Errors--Exits non-zero if the pattern is not a valid regex, or if `[id]` doesn't resolve to a live entity.diff --git a/reference/node/insert.md b/reference/node/insert.mddeleted file mode 100644index bff0319d..00000000--- a/reference/node/insert.md+++ /dev/null@@ -1,21 +0,0 @@-# `dapi node insert <parentId> <code> [--index <N>]`--Compiles an inline JSX fragment and inserts its rendered roots as children of an existing entity; the same pipeline as [`mount`](../mount.md), including declared asset generation, but instead of mounting into the document it inserts under an existing parent. Because the result is inserted rather than reconciled, root elements take no `key`: every run inserts fresh entities; there is no replace-or-create matching and nothing is deleted.--The payload is **bare JSX tags** — no `export default`, no file path. Unlike `mount`, an insert renders once and is then discarded: it is never persisted, restored, or kept live, so a component that relies on reactivity (signals, effects, `useTicker`) has nothing to drive it. Reach for [`mount`](../mount.md) when you want a live, reproducible program. The full JSX syntax lives in [jsx/](../jsx/README.md).--The rendered roots must be valid as children of the target parent, following the JSX containment rules: a node parent takes any element or paint root except a scene (an element carrying `scene`, which exists only at the document top level) and `<colorStop>`; a gradient paint parent takes only `<colorStop>` roots. That is how a stop is added to an existing gradient (`node insert <paintId> '<colorStop offset={0.5} color="#FF0055" />'`); other sub-entities take no children.--## Input--- `<parentId>`: entity id of the parent to insert into (required)-- `<code>`: inline JSX tags to insert, e.g. `'<rect width={100} height={100} />'` (required). Bare tags only — the source is rejected before contacting the app if it contains `export default` or doesn't look like JSX.-- `-i, --index <N>`: the inserted node's 0-based position among the parent's children, a non-negative integer (optional; default = append after the last child; values past the end are clamped). Node roots only: paints stack in insertion order and color stops render sorted by `offset`, so `--index` is rejected for them.--## Output--None.--## Errors--Exits non-zero if `<code>` is not a bare JSX fragment (contains `export default`, or has no tags), if `<parentId>` doesn't resolve to a live entity, if compilation or evaluation fails, if a rendered root is invalid as a child of the parent (e.g. a scene carrying `scene`, or a non-`<colorStop>` in a gradient paint), or if `--index` is given for a paint or color stop root. On any of these, **nothing is inserted**.diff --git a/reference/node/ls.md b/reference/node/ls.mddeleted file mode 100644index 6f4696c1..00000000--- a/reference/node/ls.md+++ /dev/null@@ -1,22 +0,0 @@-# `dapi node ls [ids...]`--The raw entity records, exactly as persisted: every component the entity carries, keyed by component name. The property-level counterpart to [`node tree`](./tree.md)'s structure. With no ids, returns the root (top-level nodes). Alias: `get`.--## Input--- `[ids...]`: zero or more entity ids (optional)--## Output--JSON Lines, one per entity:--```ts-EntityRecord = { id: string; eid: number } & { [component: string]: unknown }-// e.g. Name, Size, Position, Rotation, Paint, Color, Trim, ChildOf (parent eid), …-```--Records are raw engine data: times are frames at 30 fps, colors are packed `0xRRGGBB` integers, volume is dB.--## Errors--An unknown id fails the whole command: nothing is printed to stdout and it exits non-zero with `No such entity: <id>` on stderr.diff --git a/reference/node/patch.md b/reference/node/patch.mddeleted file mode 100644index 40a692ad..00000000--- a/reference/node/patch.md+++ /dev/null@@ -1,40 +0,0 @@-# `dapi node patch ([path] | --json <str>)`--Assigns JSX props on one or more existing entities in a single call. Every patch entry takes the same properties, with the same value requirements, as a JSX element in [`mount`](../mount.md); the single property table lives in [jsx/elements.md](../jsx/elements.md) and is not repeated here (the payload type is `PatchProps` from `@diffusionstudio/jsx`). Patches are applied through the same setters as a render, so the two surfaces cannot diverge. Changes are tracked for undo like a UI edit.--Any live entity is addressable, not just nodes: paints and color stops can be patched too (`color`, `offset`, `opacity`, gradient `rotation`). There is no separate rename command: renaming a node is patching its `name`.--## Input--Exactly one of:--- `[path]`: path to a `.json` file containing the patch array-- `--json <str>`: the array inline--Payload shape:--```ts-Array<{ id: number } & PatchProps>-```--All props are optional; a patch may set any subset. An unsupported property or an out-of-range value fails the command at that entity; the failing patch applies none of its props (no half-applied patches). Notes beyond the JSX table:--- `fill` recolors the entity's existing solid fill(s), or creates one if the entity has none.-- `src` takes a path, URL, or asset id (`generate.*` declarations are JSX-only). The source resolves asynchronously after the other props land; if resolution fails, the command fails at that entity even though its other props were applied. Patch `src` on its own to avoid ambiguity.-- `syncTo` re-runs audio alignment against the document node carrying the given key and writes the entity's `start` from the measured offset (see [jsx/audio-sync.md](../jsx/audio-sync.md)). The command blocks until alignment settles; a failed alignment rejects the entity.-- `transition` sets, merges into, or (with `null`) removes the clip's transition into the next clip (see [jsx/transitions.md](../jsx/transitions.md)).-- `animations` replaces the entity's preset in/out animations with the given list; `[]` removes them all (see [jsx/animations.md](../jsx/animations.md)).-- Keyframe lists are accepted wherever the property is animatable, with the same semantics as mount (see [jsx/keyframes.md](../jsx/keyframes.md)); a static value replaces any existing keyframes.-- Element applicability is not checked: props are applied wherever `mount` would apply them (e.g. `fontSize` only makes sense on a text node).--## Output--JSON Lines on stdout, one per patched entity:--```ts-{ id: number }-```--## Errors--An unknown id fails the whole command before anything is patched. A patch that fails to apply aborts the command at that entity with `Entity <id>: <reason>` on stderr: the failing entity applies none of its props, entities patched before it stay patched, and later entries are not applied.diff --git a/reference/node/render.md b/reference/node/render.mddeleted file mode 100644index 0c749121..00000000--- a/reference/node/render.md+++ /dev/null@@ -1,51 +0,0 @@-# `dapi node render [id] ([config] | --json <str>)`--Renders a scene to a video file. Composes the scene frame-by-frame and muxes the result, writing it to disk. Operates on one scene; scenes are nodes, so this is the node-level render. If `[id]` is omitted, renders the active scene.--Encode settings are passed as a single JSON config: the same object the in-app render method takes (`EncoderConfig`), minus the runtime-only fields the CLI fills in for you (`scene`, `target`, `onProgress`). Renders locally; **no credits** and no authenticated account required.--Like the generators, this is **long-running**: the CLI blocks until the render finishes (or fails) before printing. While waiting, a progress spinner with elapsed time is shown on **stderr** (a single static line when stderr isn't a TTY), so stdout stays clean JSON for piping.--## Input--- `[id]`: scene node id (optional; defaults to the active scene).-- `-o, --output <path>`: write the video here (optional; default a uuid-named file in the system temp directory). The container extension is derived from the config's `format`.-- Encode config (optional), at most one of:- - `[config]`: path to a `.json` file containing the config object. Node ids are integers, so a lone non-numeric positional is read as the config path (`dapi node render encode.json` works without an id).- - `--json <str>`: the object inline--Config shape (every field optional; all defaults shown):--```ts-{- format?: "mp4" | "webm" | "ogg" | "mov"; // default "mp4"; sets the output extension- video?: {- codec?: "avc" | "hevc" | "vp9" | "av1" | "vp8"; // default "avc" (H.264); valid codecs depend on format- enabled?: boolean; // default true- bitrate?: number; // bits/sec, default 10_000_000 (10 Mbps)- fps?: number; // default the scene's frame rate- resolution?: number; // target height in px (e.g. 720, 1080, 1440, 2160); default 1080. Width follows the scene's aspect ratio- };- audio?: {- enabled?: boolean; // default true; set false to render video only- codec?: "aac" | "opus"; // default "aac"; valid codecs depend on format- bitrate?: number; // bits/sec, default 128_000 (128 kbps)- sampleRate?: number; // Hz, e.g. 44100, 48000, 96000; default 48000- numberOfChannels?: number; // default 2- };-}-```--## Output--One JSON object: the absolute path to the written video file.--```ts-{ path: string } // e.g. "/tmp/3f2c1a8e-....mp4", or the --output path-```--> Note: you can use `dapi screenshot` to monitor the progress--## Errors--Exits non-zero if the id is unknown or the node is not a scene (`Not a scene`), if no scene is active and `[id]` is omitted, if the config is malformed or holds a value out of range or incompatible with the chosen `format` (e.g. an unsupported codec), if `--output` can't be written, or if the render fails or is canceled.diff --git a/reference/node/rm.md b/reference/node/rm.mddeleted file mode 100644index c39c5dac..00000000--- a/reference/node/rm.md+++ /dev/null@@ -1,19 +0,0 @@-# `dapi node rm <ids...>`--Deletes one or more entities and all their descendants. Alias: `remove`.--## Input--- `<ids...>`: one or more entity ids (required)--## Output--JSON Lines on stdout, one per deleted entity:--```ts-{ id: number }-```--## Errors--An unknown id fails the whole command before anything is deleted.diff --git a/reference/node/tree.md b/reference/node/tree.mddeleted file mode 100644index f54071d5..00000000--- a/reference/node/tree.md+++ /dev/null@@ -1,29 +0,0 @@-# `dapi node tree [id] [--depth N]`--An entity's subtree as a nested JSON object: structure only, every entity and sub-entity included, and the way to discover their ids. Key characteristics are folded into a compact `description` built from whatever the entity carries; use [`node ls`](./ls.md) for exact property values. The root is level 0, so `--depth 1` yields the root plus its immediate children.--## Input--- `[id]`: root entity id (optional; omitted = one tree per top-level node, mirroring `ls`)-- `--depth <N>`: max depth, non-negative integer (optional; default `3`, `0` = full subtree)--## Output--JSON Lines, one nested object per root; category arrays are omitted when empty:--```ts-NodeTree = NodeRef & {- description: string; // e.g. "hidden; size: 200x300; text: Hello World"- children?: NodeTree[]; // child nodes (masks listed separately)- masks?: NodeTree[];- paints?: NodeTree[]; // fills- strokes?: NodeTree[];- shadows?: NodeTree[];- effects?: NodeTree[];- colorStops?: NodeTree[]; // on gradient paints- textRanges?: NodeTree[]; // on text nodes- keyframeTracks?: NodeTree[]; // keyframes nest beneath their track- keyframes?: NodeTree[];- animations?: NodeTree[];-}-```diff --git a/reference/open.md b/reference/open.mddeleted file mode 100644index 1f7b4672..00000000--- a/reference/open.md+++ /dev/null@@ -1,59 +0,0 @@-# `dapi open [target]`--Launches Diffusion Studio, or opens a target. Behavior depends on what `[target]` resolves to. Does not require the app to already be running.--## Input--- `[target]` (optional), one of:- - *omitted*: launches the app.- - **`diffusion://...` URL**: follows the deep link.- - **file path**: opens the file in the app.- - **folder path**: see [Folder open](#folder-open) below.--## Options--- `-b, --background`: launch with the window hidden (`show: false`), so the app runs headlessly and can be driven by other CLI commands without any visible UI.--## Output--- File / URL / no target: nothing.-- Folder: one JSON object (see below).--## Folder open--When `[target]` is a directory, `open` either creates a project from the folder's contents or switches to a previously created one. The decision is driven by a `.dapi` marker file at the folder root.--**First time** (no marker present):--1. Creates a new project named after the folder.-2. Imports every supported asset file under the folder (recursively, excluding the marker itself), mirroring the on-disk directory structure as library folders. Directories without any supported assets beneath them produce no folder.-3. Writes the `.dapi` marker at the folder root with the new project id.-4. Opens the project.--**Subsequent times** (marker present):--1. Reads the project id from the marker.-2. Switches to that project. No re-import.-3. If the referenced project no longer exists, the marker is treated as stale and the first-time flow runs again, overwriting the marker.--**Marker file**: `.dapi` at the folder root. JSON:--```ts-{- version: 1;- projectId: string;- createdAt: string; // ISO 8601-}-```--Add it to `.gitignore` to keep the project association per-clone, or commit it to share the same project across teammates.--**Output:** one JSON object--```ts-{- project: { id: string; name: string };- created: boolean; // true if a new project was created this run (first-time or stale-marker)- imported: number; // assets imported this run; 0 on switch-only-}-```diff --git a/reference/project/active.md b/reference/project/active.mddeleted file mode 100644index 5156dba5..00000000--- a/reference/project/active.md+++ /dev/null@@ -1,15 +0,0 @@-# `dapi project active`--Prints the currently active project, or `null` if none is open.--## Input--None.--## Output--One JSON value:--```ts-{ id: string; name: string } | null-```diff --git a/reference/project/create.md b/reference/project/create.mddeleted file mode 100644index 9f8d65e5..00000000--- a/reference/project/create.md+++ /dev/null@@ -1,15 +0,0 @@-# `dapi project create [name]`--Creates a new project and opens it.--## Input--- `[name]`: optional project name--## Output--One JSON object:--```ts-{ id: string; name: string }-```diff --git a/reference/project/ls.md b/reference/project/ls.mddeleted file mode 100644index d03c330c..00000000--- a/reference/project/ls.md+++ /dev/null@@ -1,15 +0,0 @@-# `dapi project ls`--Lists all projects, most recently accessed first. Alias: `list`.--## Input--None.--## Output--JSON Lines, one per project:--```ts-{ id: string; name: string; createdAt: string; lastAccessedAt: string }-```diff --git a/reference/project/rm.md b/reference/project/rm.mddeleted file mode 100644index 6cff8561..00000000--- a/reference/project/rm.md+++ /dev/null@@ -1,15 +0,0 @@-# `dapi project rm <id>`--Deletes a project by id. Alias: `remove`.--## Input--- `<id>`: project id (required)--## Output--One JSON object:--```ts-{ id: string; name: string }-```diff --git a/reference/project/set.md b/reference/project/set.mddeleted file mode 100644index 666cec4a..00000000--- a/reference/project/set.md+++ /dev/null@@ -1,15 +0,0 @@-# `dapi project set <id>`--Sets the active project by id, opening it. Returns `null` if no project has that id.--## Input--- `<id>`: project id (required)--## Output--One JSON value:--```ts-{ id: string; name: string } | null-```diff --git a/reference/report.md b/reference/report.mdindex 913875ef..c3c73632 100644--- a/reference/report.md+++ b/reference/report.md@@ -4,7 +4,7 @@ Reports a bug in `dapi` itself or in the app behind it: a command that errors, cThe issue is submitted immediately, in the background, with no review step: the command returns once the issue exists. Filing goes through the [`gh`](https://cli.github.com) CLI, which must be installed and authenticated (`gh auth login`); without it the command exits `1` and files nothing.-This is for defects in the tooling, not for problems inside a project: a composition that looks wrong, a node in the wrong place, or a generation that missed the prompt are editing problems, fixed with `node patch` / `mount`, not reported here.+This is for defects in the tooling, not for problems inside a project: a composition that looks wrong, a node in the wrong place, or a generation that missed the prompt are editing problems, not reported here.Does not require the app to be running. If the app is down or unreachable, the report records that instead of failing, since that is often the bug being reported.@@ -15,7 +15,7 @@ Does not require the app to be running. If the app is down or unreachable, the r## Options- `-b, --body <text>`: what happened, in markdown: what you expected, what you got, and anything the diagnostics won't show.-- `-c, --command <cmd...>`: the `dapi` command(s) that reproduce it, in order. Repeatable (`-c "dapi node ls 5" -c "dapi node capture 5"`); rendered as a shell block under `## Repro`.+- `-c, --command <cmd...>`: the `dapi` command(s) that reproduce it, in order. Repeatable (`-c "dapi context" -c "dapi capture 5"`); rendered as a shell block under `## Repro`.- `--logs <n>`: trailing app log entries to attach (default: 50). `--logs 0` omits the section, and then the app is not contacted at all.## Output@@ -38,7 +38,7 @@ The title is the issue title; the body is assembled from the options and the dia## Repro```sh-dapi node capture 42+dapi capture 42```## Environmentdiff --git a/reference/screenshot.md b/reference/screenshot.mdindex f59fb877..70116903 100644--- a/reference/screenshot.md+++ b/reference/screenshot.md@@ -1,8 +1,8 @@# `dapi screenshot`-Captures the entire application window as a PNG: the full UI as the user sees it (panels, timeline, asset library, canvas viewport), at the window's current size. Use it to check what the app itself looks like; to render a node or scene cleanly for composition checks use [`node capture`](./node/capture.md) instead.+Captures the entire application window as a PNG: the full UI as the user sees it (panels, timeline, asset library, canvas viewport), at the window's current size. Use it to check what the app itself looks like; to render a node or scene cleanly for composition checks use [`capture`](./capture.md) instead.-The shot is taken from the app's own window buffer, so it works even when the window is hidden (launched with `open --background`) or covered by other windows, and never includes anything outside the app.+The shot is taken from the app's own window buffer, so it works even when the window is hidden or covered by other windows, and never includes anything outside the app.## Optionsdiff --git a/reference/selection/focus.md b/reference/selection/focus.mddeleted file mode 100644index 8509b11c..00000000--- a/reference/selection/focus.md+++ /dev/null@@ -1,15 +0,0 @@-# `dapi selection focus`--Pans and zooms the canvas to fit the currently selected nodes in view, framing them with padding; the same focus [`node capture`](../node/capture.md) uses before it captures. No-op if nothing is selected (the canvas is left unchanged).--## Input--None.--## Output--JSON Lines, one per selected node (no output if nothing is selected):--```ts-NodeRef // { id: number; name: string; type: string }-```diff --git a/reference/selection/ls.md b/reference/selection/ls.mddeleted file mode 100644index 57f538b1..00000000--- a/reference/selection/ls.md+++ /dev/null@@ -1,17 +0,0 @@-# `dapi selection ls`--The currently selected nodes. Alias: `get`.--Mutating selection commands ([`set`](./set.md), [`focus`](./focus.md)) return the resulting selection state in this same shape, so callers can chain or assert without a follow-up read.--## Input--None.--## Output--JSON Lines, one per selected node (no output if nothing is selected):--```ts-NodeRef // { id: number; name: string; type: string }-```diff --git a/reference/selection/set.md b/reference/selection/set.mddeleted file mode 100644index c28b8f77..00000000--- a/reference/selection/set.md+++ /dev/null@@ -1,15 +0,0 @@-# `dapi selection set [ids...]`--Replaces the current selection with exactly the given node ids. No ids = clear the selection.--## Input--- `[ids...]`: zero or more node ids--## Output--JSON Lines, one per selected node (no output when clearing):--```ts-NodeRef // { id: number; name: string; type: string }-```