Skip to content

Write HTML. Render video. Built for agents.

initial code (#2)

Vance Ingalls9f8e5ba5a161
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000000..b8d357843c
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,5 @@
+# No environment variables required for basic usage.
+# Run `pnpm dev` to start the studio, `npx hyperframes render` to render video.
+
+# Optional integrations:
+# ANTHROPIC_API_KEY= # For AI-assisted composition via MCP
diff --git a/.gitattributes b/.gitattributes
index f83b814c34..6e7f67f1f2 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1 +1,2 @@
+# Golden baseline videos for regression tests
packages/producer/tests/*/output/output.mp4 filter=lfs diff=lfs merge=lfs -text
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index 2b43df2429..b1edaa9fa9 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -30,7 +30,7 @@ Examples of unacceptable behavior:
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
-reported to the project maintainers at **[email protected]**. All complaints will
+reported to the project maintainers via [GitHub Issues](https://github.com/heygen-com/hyperframes/issues). All complaints will
be reviewed and investigated promptly and fairly.
## Attribution
diff --git a/SECURITY.md b/SECURITY.md
index 15ad63de63..5a3d44678b 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -6,7 +6,7 @@ If you discover a security vulnerability in Hyperframes, please report it respon
**Do not open a public GitHub issue for security vulnerabilities.**
-Instead, email **[email protected]** with:
+Instead, open a [GitHub Security Advisory](https://github.com/heygen-com/hyperframes/security/advisories/new) with:
- A description of the vulnerability
- Steps to reproduce
diff --git a/package.json b/package.json
new file mode 100644
index 0000000000..c9d95fc0d2
--- /dev/null
+++ b/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "hyperframes",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "pnpm studio",
+ "build": "pnpm -r build",
+ "build:producer": "pnpm --filter @hyperframes/producer build",
+ "studio": "pnpm --filter @hyperframes/studio dev",
+ "build:hyperframes-runtime": "pnpm --filter @hyperframes/core build:hyperframes-runtime",
+ "build:hyperframes-runtime:modular": "pnpm --filter @hyperframes/core build:hyperframes-runtime:modular"
+ },
+ "devDependencies": {
+ "@types/node": "^25.0.10",
+ "concurrently": "^8.2.0",
+ "tsx": "^4.21.0",
+ "typescript": "^5.0.0"
+ }
+}
diff --git a/packages/cli/package.json b/packages/cli/package.json
new file mode 100644
index 0000000000..373d2e38e9
--- /dev/null
+++ b/packages/cli/package.json
@@ -0,0 +1,54 @@
+{
+ "name": "hyperframes",
+ "version": "0.1.0",
+ "description": "HyperFrames CLI — create, preview, and render HTML video compositions",
+ "type": "module",
+ "bin": {
+ "hyperframes": "./dist/cli.js"
+ },
+ "files": [
+ "dist"
+ ],
+ "scripts": {
+ "dev": "tsx src/cli.ts",
+ "build": "pnpm build:studio && tsup && pnpm build:runtime && pnpm build:copy",
+ "build:studio": "cd ../studio && pnpm build",
+ "build:runtime": "tsx scripts/build-runtime.ts",
+ "build:copy": "mkdir -p dist/studio dist/docs dist/templates && cp -r ../studio/dist/* dist/studio/ && cp -r src/templates/warm-grain src/templates/play-mode src/templates/swiss-grid src/templates/vignelli dist/templates/ && (cp src/docs/*.md dist/docs/ 2>/dev/null || true)",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@hono/node-server": "^1.8.0",
+ "@puppeteer/browsers": "^2.13.0",
+ "adm-zip": "^0.5.16",
+ "cheerio": "^1.2.0",
+ "citty": "^0.2.1",
+ "esbuild": "^0.25.0",
+ "hono": "^4.0.0",
+ "mime-types": "^3.0.2",
+ "open": "^10.0.0",
+ "puppeteer-core": "^24.39.1"
+ },
+ "devDependencies": {
+ "@hyperframes/core": "workspace:*",
+ "@clack/prompts": "^1.1.0",
+ "@hono/node-server": "^1.0.0",
+ "@hyperframes/engine": "workspace:*",
+ "@hyperframes/producer": "workspace:*",
+ "@types/adm-zip": "^0.5.7",
+ "@types/mime-types": "^3.0.1",
+ "@types/node": "^22.0.0",
+ "adm-zip": "^0.5.16",
+ "cheerio": "^1.2.0",
+ "hono": "^4.0.0",
+ "linkedom": "^0.18.12",
+ "mime-types": "^3.0.2",
+ "picocolors": "^1.1.1",
+ "tsup": "^8.0.0",
+ "tsx": "^4.0.0",
+ "typescript": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+}
diff --git a/packages/cli/scripts/build-runtime.ts b/packages/cli/scripts/build-runtime.ts
new file mode 100644
index 0000000000..465b96cd3e
--- /dev/null
+++ b/packages/cli/scripts/build-runtime.ts
@@ -0,0 +1,4 @@
+import { loadHyperframeRuntimeSource } from "@hyperframes/core";
+import { writeFileSync } from "node:fs";
+
+writeFileSync("dist/hyperframe-runtime.js", loadHyperframeRuntimeSource());
diff --git a/packages/cli/src/browser/ffmpeg.ts b/packages/cli/src/browser/ffmpeg.ts
new file mode 100644
index 0000000000..b9e1d28947
--- /dev/null
+++ b/packages/cli/src/browser/ffmpeg.ts
@@ -0,0 +1,25 @@
+import { execSync } from "node:child_process";
+
+export function findFFmpeg(): string | undefined {
+ try {
+ const result = execSync("which ffmpeg", {
+ encoding: "utf-8",
+ stdio: ["pipe", "pipe", "pipe"],
+ timeout: 5000,
+ }).trim();
+ return result || undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+export function getFFmpegInstallHint(): string {
+ switch (process.platform) {
+ case "darwin":
+ return "brew install ffmpeg";
+ case "linux":
+ return "sudo apt install ffmpeg";
+ default:
+ return "https://ffmpeg.org/download.html";
+ }
+}
diff --git a/packages/cli/src/browser/manager.ts b/packages/cli/src/browser/manager.ts
new file mode 100644
index 0000000000..9a0c7bee4f
--- /dev/null
+++ b/packages/cli/src/browser/manager.ts
@@ -0,0 +1,161 @@
+import { execSync } from "node:child_process";
+import { existsSync, rmSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import {
+ Browser,
+ detectBrowserPlatform,
+ getInstalledBrowsers,
+ install,
+} from "@puppeteer/browsers";
+
+const CHROME_VERSION = "131.0.6778.85";
+const CACHE_DIR = join(homedir(), ".cache", "hyperframes", "chrome");
+
+/** Override browser path via --browser-path flag. Takes priority over env var. */
+let _browserPathOverride: string | undefined;
+export function setBrowserPath(path: string): void {
+ _browserPathOverride = path;
+}
+
+export type BrowserSource =
+ | "env"
+ | "cache"
+ | "system"
+ | "download";
+
+export interface BrowserResult {
+ executablePath: string;
+ source: BrowserSource;
+}
+
+export interface EnsureBrowserOptions {
+ onProgress?: (downloadedBytes: number, totalBytes: number) => void;
+}
+
+// --- Internal helpers -------------------------------------------------------
+
+const SYSTEM_CHROME_PATHS: ReadonlyArray<string> =
+ process.platform === "darwin"
+ ? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"]
+ : [
+ "/usr/bin/google-chrome",
+ "/usr/bin/google-chrome-stable",
+ "/usr/bin/chromium",
+ "/usr/bin/chromium-browser",
+ ];
+
+function whichBinary(name: string): string | undefined {
+ try {
+ const result = execSync(`which ${name}`, {
+ encoding: "utf-8",
+ stdio: ["pipe", "pipe", "pipe"],
+ timeout: 5000,
+ }).trim();
+ return result || undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function findFromEnv(): BrowserResult | undefined {
+ // --browser-path flag takes priority
+ if (_browserPathOverride && existsSync(_browserPathOverride)) {
+ return { executablePath: _browserPathOverride, source: "env" };
+ }
+ const envPath = process.env["HYPERFRAMES_BROWSER_PATH"];
+ if (envPath && existsSync(envPath)) {
+ return { executablePath: envPath, source: "env" };
+ }
+ return undefined;
+}
+
+async function findFromCache(): Promise<BrowserResult | undefined> {
+ if (!existsSync(CACHE_DIR)) {
+ return undefined;
+ }
+
+ const installed = await getInstalledBrowsers({ cacheDir: CACHE_DIR });
+ const match = installed.find(
+ (b) => b.browser === Browser.CHROMEHEADLESSSHELL,
+ );
+ if (match) {
+ return { executablePath: match.executablePath, source: "cache" };
+ }
+
+ return undefined;
+}
+
+function findFromSystem(): BrowserResult | undefined {
+ for (const p of SYSTEM_CHROME_PATHS) {
+ if (existsSync(p)) {
+ return { executablePath: p, source: "system" };
+ }
+ }
+
+ const fromWhich =
+ whichBinary("google-chrome") ?? whichBinary("chromium");
+ if (fromWhich) {
+ return { executablePath: fromWhich, source: "system" };
+ }
+
+ return undefined;
+}
+
+// --- Public API -------------------------------------------------------------
+
+/**
+ * Find an existing browser without downloading.
+ * Resolution: env var -> cached download -> system Chrome.
+ */
+export async function findBrowser(): Promise<BrowserResult | undefined> {
+ const fromEnv = findFromEnv();
+ if (fromEnv) return fromEnv;
+
+ const fromCache = await findFromCache();
+ if (fromCache) return fromCache;
+
+ return findFromSystem();
+}
+
+/**
+ * Find or download a browser.
+ * Resolution: env var -> cached download -> system Chrome -> auto-download.
+ */
+export async function ensureBrowser(
+ options?: EnsureBrowserOptions,
+): Promise<BrowserResult> {
+ const existing = await findBrowser();
+ if (existing) return existing;
+
+ const platform = detectBrowserPlatform();
+ if (!platform) {
+ throw new Error(
+ `Unsupported platform: ${process.platform} ${process.arch}`,
+ );
+ }
+
+ const installed = await install({
+ cacheDir: CACHE_DIR,
+ browser: Browser.CHROMEHEADLESSSHELL,
+ buildId: CHROME_VERSION,
+ platform,
+ downloadProgressCallback: options?.onProgress,
+ });
+
+ return { executablePath: installed.executablePath, source: "download" };
+}
+
+/**
+ * Remove the cached Chrome download directory.
+ * Returns true if anything was removed.
+ */
+export function clearBrowser(): boolean {
+ if (!existsSync(CACHE_DIR)) {
+ return false;
+ }
+ rmSync(CACHE_DIR, { recursive: true, force: true });
+ return true;
+}
+
+export { CHROME_VERSION, CACHE_DIR };
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
new file mode 100644
index 0000000000..2c66c6f1a3
--- /dev/null
+++ b/packages/cli/src/cli.ts
@@ -0,0 +1,27 @@
+#!/usr/bin/env node
+
+import { defineCommand, runMain } from "citty";
+import { VERSION } from "./version.js";
+
+const main = defineCommand({
+ meta: {
+ name: "hyperframes",
+ version: VERSION,
+ description: "Create and render HTML video compositions",
+ },
+ subCommands: {
+ init: () => import("./commands/init.js").then((m) => m.default),
+ dev: () => import("./commands/dev.js").then((m) => m.default),
+ render: () => import("./commands/render.js").then((m) => m.default),
+ lint: () => import("./commands/lint.js").then((m) => m.default),
+ info: () => import("./commands/info.js").then((m) => m.default),
+ compositions: () => import("./commands/compositions.js").then((m) => m.default),
+ benchmark: () => import("./commands/benchmark.js").then((m) => m.default),
+ browser: () => import("./commands/browser.js").then((m) => m.default),
+ docs: () => import("./commands/docs.js").then((m) => m.default),
+ doctor: () => import("./commands/doctor.js").then((m) => m.default),
+ upgrade: () => import("./commands/upgrade.js").then((m) => m.default),
+ },
+});
+
+runMain(main);
diff --git a/packages/cli/src/commands/benchmark.ts b/packages/cli/src/commands/benchmark.ts
new file mode 100644
index 0000000000..cb3c30c255
--- /dev/null
+++ b/packages/cli/src/commands/benchmark.ts
@@ -0,0 +1,226 @@
+import { defineCommand } from "citty";
+import { existsSync, statSync } from "node:fs";
+import { resolve, join } from "node:path";
+import { resolveProject } from "../utils/project.js";
+import { loadProducer } from "../utils/producer.js";
+import { c } from "../ui/colors.js";
+import { formatBytes, formatDuration, errorBox } from "../ui/format.js";
+import * as clack from "@clack/prompts";
+
+interface BenchmarkConfig {
+ label: string;
+ fps: 24 | 30 | 60;
+ quality: "draft" | "standard" | "high";
+ workers: number;
+}
+
+interface RunResult {
+ elapsedMs: number;
+ fileSize: number | null;
+}
+
+interface ConfigResult {
+ config: BenchmarkConfig;
+ runs: RunResult[];
+ failures: number;
+ avgTime: number | null;
+ avgSize: number | null;
+}
+
+const DEFAULT_CONFIGS: BenchmarkConfig[] = [
+ { label: "30fps \u00B7 draft \u00B7 2w", fps: 30, quality: "draft", workers: 2 },
+ { label: "30fps \u00B7 standard \u00B7 2w", fps: 30, quality: "standard", workers: 2 },
+ { label: "30fps \u00B7 high \u00B7 2w", fps: 30, quality: "high", workers: 2 },
+ { label: "30fps \u00B7 standard \u00B7 4w", fps: 30, quality: "standard", workers: 4 },
+ { label: "60fps \u00B7 standard \u00B7 4w", fps: 60, quality: "standard", workers: 4 },
+];
+
+export default defineCommand({
+ meta: { name: "benchmark", description: "Run multiple render configurations and compare results" },
+ args: {
+ dir: { type: "positional", description: "Project directory", required: false },
+ runs: { type: "string", description: "Number of runs per config", default: "3" },
+ json: { type: "boolean", description: "Output results as JSON", default: false },
+ },
+ async run({ args }) {
+ // ── Resolve project ──────────────────────────────────────────────────
+ const project = resolveProject(args.dir);
+
+ // ── Parse runs ───────────────────────────────────────────────────────
+ const runsPerConfig = parseInt(args.runs ?? "3", 10);
+ if (isNaN(runsPerConfig) || runsPerConfig < 1 || runsPerConfig > 20) {
+ errorBox("Invalid runs", `Got "${args.runs ?? "3"}". Must be between 1 and 20.`);
+ process.exit(1);
+ }
+
+ const jsonOutput = args.json ?? false;
+
+ // ── Temp output for benchmark renders ────────────────────────────────
+ const benchDir = resolve("renders", ".benchmark");
+
+ // ── Load producer ────────────────────────────────────────────────────
+ let producer: Awaited<ReturnType<typeof loadProducer>> | null = null;
+ try {
+ producer = await loadProducer();
+ } catch {
+ if (jsonOutput) {
+ console.log(JSON.stringify({ error: "Producer module not available. Is the project built?" }));
+ } else {
+ errorBox(
+ "Producer module not available",
+ "The rendering pipeline could not be loaded.",
+ "Ensure @hyperframes/producer is built and linked.",
+ );
+ }
+ process.exit(1);
+ }
+
+ // ── Print header ─────────────────────────────────────────────────────
+ if (!jsonOutput) {
+ console.log("");
+ console.log(
+ c.accent("\u25C6") +
+ " Benchmarking " +
+ c.accent(project.name) +
+ c.dim(` (${runsPerConfig} runs each)`),
+ );
+ console.log("");
+ }
+
+ // ── Run benchmarks ───────────────────────────────────────────────────
+ const results: ConfigResult[] = [];
+
+ for (const config of DEFAULT_CONFIGS) {
+ const runs: RunResult[] = [];
+ let failures = 0;
+
+ const s = !jsonOutput ? clack.spinner() : undefined;
+ s?.start(`Benchmarking ${config.label}...`);
+
+ for (let i = 0; i < runsPerConfig; i++) {
+ s?.message(`${config.label} — run ${i + 1}/${runsPerConfig}`);
+ const outputPath = join(benchDir, `${config.label.replace(/[^a-zA-Z0-9]/g, "_")}_run${i}.mp4`);
+
+ try {
+ const startTime = Date.now();
+ await producer.renderComposition(project.dir, {
+ output: outputPath,
+ fps: config.fps,
+ quality: config.quality,
+ workers: config.workers,
+ quiet: true,
+ });
+ const elapsedMs = Date.now() - startTime;
+
+ let fileSize: number | null = null;
+ if (existsSync(outputPath)) {
+ const stat = statSync(outputPath);
+ fileSize = stat.size;
+ }
+
+ runs.push({ elapsedMs, fileSize });
+ } catch {
+ failures++;
+ }
+ }
+
+ s?.stop(`${config.label} — ${runs.length} runs${failures > 0 ? `, ${failures} failed` : ""}`);
+
+ const successfulRuns = runs.filter((r) => r.elapsedMs > 0);
+ const avgTime =
+ successfulRuns.length > 0
+ ? successfulRuns.reduce((sum, r) => sum + r.elapsedMs, 0) / successfulRuns.length
+ : null;
+ const sizesWithValues = runs.map((r) => r.fileSize).filter((s): s is number => s != null);
+ const avgSize =
+ sizesWithValues.length > 0
+ ? sizesWithValues.reduce((sum, s) => sum + s, 0) / sizesWithValues.length
+ : null;
+
+ results.push({ config, runs, failures, avgTime, avgSize });
+ }
+
+ // ── Output results ───────────────────────────────────────────────────
+ if (jsonOutput) {
+ console.log(
+ JSON.stringify(
+ results.map((r) => ({
+ config: r.config.label,
+ fps: r.config.fps,
+ quality: r.config.quality,
+ workers: r.config.workers,
+ avgTimeMs: r.avgTime,
+ avgSizeBytes: r.avgSize,
+ failures: r.failures,
+ runs: r.runs,
+ })),
+ null,
+ 2,
+ ),
+ );
+ return;
+ }
+
+ // ── Table output ─────────────────────────────────────────────────────
+ const configColWidth = 26;
+ const timeColWidth = 10;
+ const sizeColWidth = 10;
+
+ const header =
+ " " +
+ c.bold("Config".padEnd(configColWidth)) +
+ c.bold("Time".padEnd(timeColWidth)) +
+ c.bold("Size".padEnd(sizeColWidth));
+ const separator = " " + c.dim("\u2500".repeat(configColWidth + timeColWidth + sizeColWidth));
+
+ console.log(header);
+ console.log(separator);
+
+ for (const result of results) {
+ const timeStr =
+ result.avgTime != null ? formatDuration(result.avgTime) : c.dim("failed");
+ const sizeStr =
+ result.avgSize != null ? formatBytes(result.avgSize) : c.dim("n/a");
+ const failStr =
+ result.failures > 0 ? c.warn(` (${result.failures} failed)`) : "";
+
+ console.log(
+ " " +
+ result.config.label.padEnd(configColWidth) +
+ timeStr.padEnd(timeColWidth) +
+ sizeStr.padEnd(sizeColWidth) +
+ failStr,
+ );
+ }
+
+ // ── Summary ──────────────────────────────────────────────────────────
+ const successfulResults = results.filter((r) => r.avgTime != null);
+ if (successfulResults.length > 0) {
+ let fastest = successfulResults[0];
+ for (const r of successfulResults) {
+ if (fastest == null || r.avgTime == null) continue;
+ if (fastest.avgTime == null || r.avgTime < fastest.avgTime) {
+ fastest = r;
+ }
+ }
+
+ if (fastest?.avgTime != null) {
+ console.log("");
+ console.log(
+ c.success("\u25C7") +
+ " Fastest: " +
+ c.accent(fastest.config.label) +
+ c.dim(` (${formatDuration(fastest.avgTime)})`),
+ );
+ }
+ } else {
+ console.log("");
+ console.log(
+ c.error("\u2717") +
+ " All configurations failed. Ensure the rendering pipeline is set up.",
+ );
+ }
+
+ console.log("");
+ },
+});
diff --git a/packages/cli/src/commands/browser.ts b/packages/cli/src/commands/browser.ts
new file mode 100644
index 0000000000..24d0757937
--- /dev/null
+++ b/packages/cli/src/commands/browser.ts
@@ -0,0 +1,133 @@
+import { defineCommand } from "citty";
+import * as clack from "@clack/prompts";
+import { c } from "../ui/colors.js";
+import { formatBytes } from "../ui/format.js";
+import {
+ ensureBrowser,
+ findBrowser,
+ clearBrowser,
+ CHROME_VERSION,
+ CACHE_DIR,
+} from "../browser/manager.js";
+
+async function runEnsure(): Promise<void> {
+ clack.intro(c.bold("hyperframes browser ensure"));
+
+ const s = clack.spinner();
+ s.start("Looking for an existing browser...");
+
+ const existing = await findBrowser();
+ if (existing) {
+ s.stop(c.success("Browser found"));
+ console.log();
+ console.log(` ${c.dim("Source:")} ${c.bold(existing.source)}`);
+ console.log(` ${c.dim("Path:")} ${c.bold(existing.executablePath)}`);
+ console.log();
+ clack.outro(c.success("Ready to render."));
+ return;
+ }
+
+ s.stop("No browser found — downloading");
+
+ const downloadSpinner = clack.spinner();
+ downloadSpinner.start(
+ `Downloading Chrome Headless Shell ${c.dim("v" + CHROME_VERSION)}...`,
+ );
+
+ let lastPct = -1;
+ const result = await ensureBrowser({
+ onProgress: (downloaded, total) => {
+ if (total <= 0) return;
+ const pct = Math.floor((downloaded / total) * 100);
+ if (pct > lastPct) {
+ lastPct = pct;
+ downloadSpinner.message(
+ `Downloading Chrome Headless Shell ${c.dim("v" + CHROME_VERSION)} — ${c.progress(pct + "%")} ${c.dim("(" + formatBytes(downloaded) + " / " + formatBytes(total) + ")")}`,
+ );
+ }
+ },
+ });
+
+ downloadSpinner.stop(c.success("Download complete"));
+
+ console.log();
+ console.log(` ${c.dim("Source:")} ${c.bold(result.source)}`);
+ console.log(` ${c.dim("Path:")} ${c.bold(result.executablePath)}`);
+ console.log();
+
+ clack.outro(c.success("Ready to render."));
+}
+
+async function runPath(): Promise<void> {
+ const result = await findBrowser();
+ if (!result) {
+ // Try a full ensure (which includes download) but write only the path
+ try {
+ const ensured = await ensureBrowser();
+ process.stdout.write(ensured.executablePath + "\n");
+ } catch (err: unknown) {
+ console.error(
+ err instanceof Error ? err.message : "Failed to find browser",
+ );
+ process.exit(1);
+ }
+ return;
+ }
+ process.stdout.write(result.executablePath + "\n");
+}
+
+function runClear(): void {
+ clack.intro(c.bold("hyperframes browser clear"));
+
+ const removed = clearBrowser();
+ if (removed) {
+ clack.outro(
+ c.success("Removed cached browser from ") + c.dim(CACHE_DIR),
+ );
+ } else {
+ clack.outro(c.dim("No cached browser to remove."));
+ }
+}
+
+export default defineCommand({
+ meta: { name: "browser", description: "Manage the Chrome browser used for rendering" },
+ args: {
+ subcommand: { type: "positional", description: "Subcommand: ensure, path, clear", required: false },
+ },
+ async run({ args }) {
+ const subcommand = args.subcommand;
+
+ if (!subcommand || subcommand === "") {
+ console.log(`
+${c.bold("hyperframes browser")} ${c.dim("<subcommand>")}
+
+Manage the Chrome browser used for rendering.
+
+${c.bold("SUBCOMMANDS:")}
+ ${c.accent("ensure")} ${c.dim("Find or download Chrome for rendering")}
+ ${c.accent("path")} ${c.dim("Print browser executable path (for scripting)")}
+ ${c.accent("clear")} ${c.dim("Remove cached Chrome download")}
+
+${c.bold("EXAMPLES:")}
+ ${c.accent("npx hyperframes browser ensure")} ${c.dim("Download Chrome if needed")}
+ ${c.accent("npx hyperframes browser path")} ${c.dim("Print path for scripts")}
+ ${c.accent("npx hyperframes browser clear")} ${c.dim("Remove cached browser")}
+`);
+ return;
+ }
+
+ switch (subcommand) {
+ case "ensure":
+ return runEnsure();
+ case "path":
+ return runPath();
+ case "clear":
+ return runClear();
+ default:
+ console.error(
+ `${c.error("Unknown subcommand:")} ${subcommand}\n\nRun ${c.accent("hyperframes browser --help")} for usage.`,
+ );
+ process.exit(1);
+ }
+ },
+});
diff --git a/packages/cli/src/commands/compositions.ts b/packages/cli/src/commands/compositions.ts
new file mode 100644
index 0000000000..35b7e1b150
--- /dev/null
+++ b/packages/cli/src/commands/compositions.ts
@@ -0,0 +1,107 @@
+import { defineCommand } from "citty";
+import { readFileSync } from "node:fs";
+import { c } from "../ui/colors.js";
+import { ensureDOMParser } from "../utils/dom.js";
+import { resolveProject } from "../utils/project.js";
+
+interface CompositionInfo {
+ id: string;
+ duration: number;
+ width: number;
+ height: number;
+ elementCount: number;
+}
+
+function parseCompositions(html: string): CompositionInfo[] {
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, "text/html");
+
+ const compositionDivs = doc.querySelectorAll("[data-composition-id]");
+ const compositions: CompositionInfo[] = [];
+
+ compositionDivs.forEach((div) => {
+ const id = div.getAttribute("data-composition-id") ?? "unknown";
+ const width = parseInt(div.getAttribute("data-width") ?? "1920", 10);
+ const height = parseInt(div.getAttribute("data-height") ?? "1080", 10);
+
+ const timedChildren = div.querySelectorAll("[data-start]");
+ let maxEnd = 0;
+ let elementCount = 0;
+
+ timedChildren.forEach((el) => {
+ elementCount++;
+ const start = parseFloat(el.getAttribute("data-start") ?? "0");
+ const endAttr = el.getAttribute("data-end");
+ const durationAttr = el.getAttribute("data-duration");
+
+ let end: number;
+ if (endAttr) {
+ end = parseFloat(endAttr);
+ } else if (durationAttr) {
+ end = start + parseFloat(durationAttr);
+ } else {
+ end = start + 5;
+ }
+
+ if (end > maxEnd) {
+ maxEnd = end;
+ }
+ });
+
+ compositions.push({
+ id,
+ duration: maxEnd,
+ width,
+ height,
+ elementCount,
+ });
+ });
+
+ return compositions;
+}
+
+export default defineCommand({
+ meta: { name: "compositions", description: "List all compositions in a project" },
+ args: {
+ dir: { type: "positional", description: "Project directory", required: false },
+ json: { type: "boolean", description: "Output as JSON", default: false },
+ },
+ async run({ args }) {
+ const project = resolveProject(args.dir);
+ const html = readFileSync(project.indexPath, "utf-8");
+
+ ensureDOMParser();
+ const compositions = parseCompositions(html);
+
+ if (compositions.length === 0) {
+ console.log(`${c.success("◇")} ${c.accent(project.name)} — no compositions found`);
+ return;
+ }
+
+ if (args.json) {
+ console.log(JSON.stringify(compositions, null, 2));
+ return;
+ }
+
+ const compositionLabel =
+ compositions.length === 1 ? "1 composition" : `${compositions.length} compositions`;
+ console.log(
+ `${c.success("◇")} ${c.accent(project.name)} ${c.dim("—")} ${c.dim(compositionLabel)}`,
+ );
+ console.log();
+
+ // Calculate padding for alignment
+ const maxIdLen = compositions.reduce((max, comp) => Math.max(max, comp.id.length), 0);
+
+ for (const comp of compositions) {
+ const id = c.accent(comp.id.padEnd(maxIdLen));
+ const duration = c.bold(`${comp.duration.toFixed(1)}s`);
+ const resolution = c.dim(`${comp.width}×${comp.height}`);
+ const elements = c.dim(
+ `${comp.elementCount} ${comp.elementCount === 1 ? "element" : "elements"}`,
+ );
+
+ console.log(` ${id} ${duration} ${resolution} ${elements}`);
+ }
+ },
+});
diff --git a/packages/cli/src/commands/dev.ts b/packages/cli/src/commands/dev.ts
new file mode 100644
index 0000000000..499cc71332
--- /dev/null
+++ b/packages/cli/src/commands/dev.ts
@@ -0,0 +1,186 @@
+import { defineCommand } from "citty";
+import { spawn } from "node:child_process";
+import {
+ existsSync,
+ lstatSync,
+ symlinkSync,
+ unlinkSync,
+ readlinkSync,
+ mkdirSync,
+} from "node:fs";
+import { resolve, dirname, basename, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import * as clack from "@clack/prompts";
+import { c } from "../ui/colors.js";
+
+/**
+ * Check if a port is available by trying to listen on it briefly.
+ */
+function isPortAvailable(port: number): Promise<boolean> {
+ return new Promise((resolvePromise) => {
+ const { createServer } = require("node:net") as typeof import("node:net");
+ const server = createServer();
+ server.once("error", () => resolvePromise(false));
+ server.once("listening", () => {
+ server.close(() => resolvePromise(true));
+ });
+ server.listen(port);
+ });
+}
+
+/**
+ * Find an available port starting from the given port.
+ */
+async function findAvailablePort(startPort: number): Promise<number> {
+ for (let port = startPort; port < startPort + 10; port++) {
+ if (await isPortAvailable(port)) return port;
+ }
+ return startPort; // fallback — let the server fail with a clear error
+}
+
+/**
+ * Detect whether we're running from source (monorepo dev) or from the built bundle.
+ * When running via tsx from source, the file is at cli/src/commands/dev.ts.
+ * When running from the built bundle, the file is at cli/dist/cli.js.
+ * We check the filename portion of the URL to avoid false positives from
+ * directory names (e.g., /Users/someone/src/...).
+ */
+function isDevMode(): boolean {
+ const url = new URL(import.meta.url);
+ // In dev mode the file is a .ts source file; in production it's a bundled .js
+ return url.pathname.endsWith(".ts");
+}
+
+export default defineCommand({
+ meta: { name: "dev", description: "Start the studio for local development" },
+ args: {
+ dir: { type: "positional", description: "Project directory", required: false },
+ },
+ async run({ args }) {
+ const dir = resolve(args.dir ?? ".");
+
+ if (isDevMode()) {
+ return runDevMode(dir);
+ }
+ const port = await findAvailablePort(3002);
+ return runEmbeddedMode(dir, port);
+ },
+});
+
+/**
+ * Dev mode: spawn pnpm studio from the monorepo (existing behavior).
+ */
+async function runDevMode(dir: string): Promise<void> {
+ // Find monorepo root by navigating from packages/cli/src/commands/
+ const thisFile = fileURLToPath(import.meta.url);
+ const repoRoot = resolve(dirname(thisFile), "..", "..", "..", "..");
+
+ // Symlink project into the studio's data directory
+ const projectsDir = join(repoRoot, "packages", "studio", "data", "projects");
+ const projectName = basename(dir);
+ const symlinkPath = join(projectsDir, projectName);
+
+ mkdirSync(projectsDir, { recursive: true });
+
+ let createdSymlink = false;
+ if (dir !== symlinkPath) {
+ if (existsSync(symlinkPath)) {
+ try {
+ const stat = lstatSync(symlinkPath);
+ if (stat.isSymbolicLink()) {
+ const target = readlinkSync(symlinkPath);
+ if (resolve(target) !== resolve(dir)) {
+ unlinkSync(symlinkPath);
+ }
+ }
+ // If it's a real directory, leave it alone
+ } catch {
+ // Not a symlink — don't touch it
+ }
+ }
+
+ if (!existsSync(symlinkPath)) {
+ symlinkSync(dir, symlinkPath, "dir");
+ createdSymlink = true;
+ }
+ }
+
+ clack.intro(c.bold("hyperframes dev"));
+
+ const s = clack.spinner();
+ s.start("Starting studio...");
+
+ // Run the new consolidated studio (single Vite dev server with API plugin)
+ const studioPkgDir = join(repoRoot, "packages", "studio");
+ const child = spawn("pnpm", ["exec", "vite"], {
+ cwd: studioPkgDir,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+
+ let frontendUrl = "";
+
+ function handleOutput(data: Buffer): void {
+ const text = data.toString();
+
+ // Detect Vite URL
+ const localMatch = text.match(/Local:\s+(http:\/\/localhost:\d+)/);
+ if (localMatch && !frontendUrl) {
+ frontendUrl = localMatch[1] ?? "";
+ s.stop(c.success("Studio running"));
+ console.log();
+ console.log(` ${c.dim("Project")} ${c.accent(projectName)}`);
+ console.log(` ${c.dim("Studio")} ${c.accent(frontendUrl)}`);
+ console.log();
+ console.log(` ${c.dim("Press Ctrl+C to stop")}`);
+ console.log();
+
+ const urlToOpen = `${frontendUrl}#/project/${projectName}`;
+ import("open").then((mod) => mod.default(urlToOpen)).catch(() => {});
+
+ child.stdout?.removeListener("data", handleOutput);
+ child.stderr?.removeListener("data", handleOutput);
+ }
+ }
+
+ child.stdout?.on("data", handleOutput);
+ child.stderr?.on("data", handleOutput);
+
+ // If child exits before we detect readiness, show what we have
+ child.on("error", (err) => {
+ s.stop(c.error("Failed to start studio"));
+ console.error(c.dim(err.message));
+ });
+
+ function cleanup(): void {
+ if (createdSymlink && existsSync(symlinkPath)) {
+ try {
+ unlinkSync(symlinkPath);
+ } catch {
+ /* ignore */
+ }
+ }
+ }
+
+ return new Promise<void>((resolvePromise) => {
+ // Temporarily ignore SIGINT on the parent so Ctrl+C only kills the child.
+ // The child gets SIGINT from the terminal's process group signal.
+ // When the child exits, we clean up and resolve back to the caller.
+ const noop = (): void => {};
+ process.on("SIGINT", noop);
+
+ child.on("close", () => {
+ process.removeListener("SIGINT", noop);
+ cleanup();
+ resolvePromise();
+ });
+ });
+}
+
+/**
+ * Embedded mode — not yet available.
+ * TODO: Migrate to use @hyperframes/studio's built-in Vite server for published CLI.
+ */
+async function runEmbeddedMode(_dir: string, _port: number): Promise<void> {
+ console.error(c.error("Embedded mode not yet available. Run from the monorepo root with: hyperframes dev <dir>"));
+ process.exit(1);
+}
diff --git a/packages/cli/src/commands/docs.ts b/packages/cli/src/commands/docs.ts
new file mode 100644
index 0000000000..3c11fe9bcd
--- /dev/null
+++ b/packages/cli/src/commands/docs.ts
@@ -0,0 +1,129 @@
+import { defineCommand } from "citty";
+import { readFileSync, existsSync } from "node:fs";
+import { resolve, dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { c } from "../ui/colors.js";
+
+interface TopicEntry {
+ file: string;
+ description: string;
+}
+
+const TOPICS: Record<string, TopicEntry> = {
+ "data-attributes": {
+ file: "data-attributes.md",
+ description: "Timing, media, and composition attributes",
+ },
+ templates: {
+ file: "templates.md",
+ description: "Built-in project templates for init",
+ },
+ rendering: {
+ file: "rendering.md",
+ description: "Render compositions to MP4 (local & Docker)",
+ },
+ gsap: {
+ file: "gsap.md",
+ description: "GSAP animation setup and usage",
+ },
+ troubleshooting: {
+ file: "troubleshooting.md",
+ description: "Common issues and fixes",
+ },
+ compositions: {
+ file: "compositions.md",
+ description: "Composition structure, nesting, and variables",
+ },
+};
+
+function docsDir(): string {
+ const thisFile = fileURLToPath(import.meta.url);
+ const dir = dirname(thisFile);
+ // In dev: cli/src/commands/ → ../docs = cli/src/docs/
+ // In built: cli/dist/ → docs = cli/dist/docs/
+ const devPath = resolve(dir, "..", "docs");
+ const builtPath = resolve(dir, "docs");
+ return existsSync(devPath) ? devPath : builtPath;
+}
+
+function formatInlineCode(line: string): string {
+ // Replace inline backtick spans with accented text
+ return line.replace(/`([^`]+)`/g, (_match, code: string) => c.accent(code));
+}
+
+function renderMarkdown(content: string): void {
+ const lines = content.split("\n");
+
+ for (const line of lines) {
+ // Skip code fences
+ if (line.trim().startsWith("```")) {
+ continue;
+ }
+
+ // H1 heading
+ if (line.startsWith("# ")) {
+ console.log(c.bold(line.slice(2)));
+ continue;
+ }
+
+ // H2 subheading
+ if (line.startsWith("## ")) {
+ console.log(c.bold(c.dim(line.slice(3))));
+ continue;
+ }
+
+ // List items
+ if (line.startsWith("- ")) {
+ const rest = formatInlineCode(line.slice(2));
+ console.log(`${c.dim(" \u2022")} ${rest}`);
+ continue;
+ }
+
+ // Everything else
+ console.log(formatInlineCode(line));
+ }
+}
+
+export default defineCommand({
+ meta: { name: "docs", description: "View inline documentation in the terminal" },
+ args: {
+ topic: { type: "positional", description: "Topic to view", required: false },
+ },
+ async run({ args }) {
+ const topic = args.topic;
+
+ // No topic: list available topics
+ if (topic === undefined || topic === "") {
+ console.log(c.bold("Available topics:"));
+ console.log();
+ for (const [name, entry] of Object.entries(TOPICS)) {
+ console.log(` ${c.accent(name.padEnd(20))} ${c.dim(entry.description)}`);
+ }
+ console.log();
+ console.log(c.dim(`Run ${c.accent("hyperframes docs <topic>")} to view a topic.`));
+ return;
+ }
+
+ // Look up the topic
+ const entry = TOPICS[topic];
+ if (entry === undefined) {
+ console.error(c.error(`Unknown topic: ${topic}`));
+ console.error();
+ console.error("Available topics:");
+ for (const name of Object.keys(TOPICS)) {
+ console.error(` ${c.accent(name)}`);
+ }
+ process.exit(1);
+ }
+
+ const filePath = join(docsDir(), entry.file);
+ if (!existsSync(filePath)) {
+ console.error(c.error(`Doc file not found: ${filePath}`));
+ process.exit(1);
+ }
+
+ const content = readFileSync(filePath, "utf-8");
+ console.log();
+ renderMarkdown(content);
+ },
+});
diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.ts
new file mode 100644
index 0000000000..45ec046a35
--- /dev/null
+++ b/packages/cli/src/commands/doctor.ts
@@ -0,0 +1,131 @@
+import { defineCommand } from "citty";
+import { execSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import { c } from "../ui/colors.js";
+import { findBrowser } from "../browser/manager.js";
+import { findFFmpeg } from "../browser/ffmpeg.js";
+
+interface Check {
+ name: string;
+ run: () => CheckResult | Promise<CheckResult>;
+}
+
+interface CheckResult {
+ ok: boolean;
+ detail: string;
+ hint?: string;
+}
+
+function checkFFmpeg(): CheckResult {
+ const path = findFFmpeg();
+ if (path) {
+ try {
+ const version = execSync("ffmpeg -version", { encoding: "utf-8", timeout: 5000 })
+ .split("\n")[0] ?? "";
+ return { ok: true, detail: version.trim() };
+ } catch {
+ return { ok: true, detail: path };
+ }
+ }
+ return {
+ ok: false,
+ detail: "Not found",
+ hint: process.platform === "darwin" ? "brew install ffmpeg" : "sudo apt install ffmpeg",
+ };
+}
+
+function checkFFprobe(): CheckResult {
+ try {
+ const result = execSync("which ffprobe", { encoding: "utf-8", timeout: 5000 }).trim();
+ return { ok: true, detail: result };
+ } catch {
+ return {
+ ok: false,
+ detail: "Not found",
+ hint: "Installed with ffmpeg",
+ };
+ }
+}
+
+async function checkChrome(): Promise<CheckResult> {
+ const info = await findBrowser();
+ if (info) {
+ return { ok: true, detail: `${info.source}: ${info.executablePath}` };
+ }
+ return {
+ ok: false,
+ detail: "Not found",
+ hint: "Run: npx hyperframes browser ensure",
+ };
+}
+
+function checkDocker(): CheckResult {
+ try {
+ const version = execSync("docker --version", { encoding: "utf-8", timeout: 5000 }).trim();
+ return { ok: true, detail: version };
+ } catch {
+ return {
+ ok: false,
+ detail: "Not found",
+ hint: "https://docs.docker.com/get-docker/",
+ };
+ }
+}
+
+function checkDockerRunning(): CheckResult {
+ try {
+ execSync("docker info", { stdio: "pipe", timeout: 5000 });
+ return { ok: true, detail: "Running" };
+ } catch {
+ return {
+ ok: false,
+ detail: "Not running",
+ hint: "Start Docker Desktop or run: sudo systemctl start docker",
+ };
+ }
+}
+
+function checkNode(): CheckResult {
+ return { ok: true, detail: `${process.version} (${process.platform} ${process.arch})` };
+}
+
+
+export default defineCommand({
+ meta: { name: "doctor", description: "Check system dependencies and environment" },
+ args: {},
+ async run() {
+ console.log();
+ console.log(c.bold("hyperframes doctor"));
+ console.log();
+
+ const checks: Check[] = [
+ { name: "Node.js", run: checkNode },
+ { name: "FFmpeg", run: checkFFmpeg },
+ { name: "FFprobe", run: checkFFprobe },
+ { name: "Chrome", run: checkChrome },
+ { name: "Docker", run: checkDocker },
+ { name: "Docker running", run: checkDockerRunning },
+ ];
+
+ let allOk = true;
+
+ for (const check of checks) {
+ const result = await check.run();
+ const icon = result.ok ? c.success("\u2713") : c.error("\u2717");
+ const name = check.name.padEnd(16);
+ console.log(` ${icon} ${c.bold(name)} ${result.ok ? c.dim(result.detail) : c.error(result.detail)}`);
+ if (!result.ok && result.hint) {
+ console.log(` ${" ".repeat(19)}${c.accent(result.hint)}`);
+ }
+ if (!result.ok) allOk = false;
+ }
+
+ console.log();
+ if (allOk) {
+ console.log(` ${c.success("\u25C7")} ${c.success("All checks passed")}`);
+ } else {
+ console.log(` ${c.warn("\u25C7")} ${c.warn("Some checks failed — see hints above")}`);
+ }
+ console.log();
+ },
+});
diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.ts
new file mode 100644
index 0000000000..61d561b534
--- /dev/null
+++ b/packages/cli/src/commands/info.ts
@@ -0,0 +1,75 @@
+import { defineCommand } from "citty";
+import { readFileSync, readdirSync, statSync } from "node:fs";
+import { join } from "node:path";
+import { parseHtml } from "@hyperframes/core";
+import { c } from "../ui/colors.js";
+import { formatBytes, label } from "../ui/format.js";
+import { ensureDOMParser } from "../utils/dom.js";
+import { resolveProject } from "../utils/project.js";
+
+function totalSize(dir: string): number {
+ let total = 0;
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ total += totalSize(path);
+ } else {
+ total += statSync(path).size;
+ }
+ }
+ return total;
+}
+
+export default defineCommand({
+ meta: { name: "info", description: "Print project metadata" },
+ args: {
+ dir: { type: "positional", description: "Project directory", required: false },
+ json: { type: "boolean", description: "Output as JSON", default: false },
+ },
+ async run({ args }) {
+ const project = resolveProject(args.dir);
+ const html = readFileSync(project.indexPath, "utf-8");
+
+ ensureDOMParser();
+ const parsed = parseHtml(html);
+
+ const tracks = new Set(parsed.elements.map((el) => el.zIndex));
+ const maxEnd = parsed.elements.reduce(
+ (max, el) => Math.max(max, el.startTime + el.duration),
+ 0,
+ );
+ const resolution =
+ parsed.resolution === "portrait" ? "1080x1920" : "1920x1080";
+ const size = totalSize(project.dir);
+
+ const typeCounts: Record<string, number> = {};
+ for (const el of parsed.elements) {
+ typeCounts[el.type] = (typeCounts[el.type] ?? 0) + 1;
+ }
+ const typeStr = Object.entries(typeCounts)
+ .map(([t, count]) => `${count} ${t}`)
+ .join(", ");
+
+ if (args.json) {
+ console.log(JSON.stringify({
+ name: project.name,
+ resolution: parsed.resolution,
+ width: parsed.resolution === "portrait" ? 1080 : 1920,
+ height: parsed.resolution === "portrait" ? 1920 : 1080,
+ duration: maxEnd,
+ elements: parsed.elements.length,
+ tracks: tracks.size,
+ types: typeCounts,
+ size,
+ }, null, 2));
+ return;
+ }
+
+ console.log(`${c.success("◇")} ${c.accent(project.name)}`);
+ console.log(label("Resolution", resolution));
+ console.log(label("Duration", `${maxEnd.toFixed(1)}s`));
+ console.log(label("Elements", `${parsed.elements.length}${typeStr ? ` (${typeStr})` : ""}`));
+ console.log(label("Tracks", `${tracks.size}`));
+ console.log(label("Size", formatBytes(size)));
+ },
+});
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
new file mode 100644
index 0000000000..1537f4b2d9
--- /dev/null
+++ b/packages/cli/src/commands/init.ts
@@ -0,0 +1,492 @@
+import { defineCommand, runCommand } from "citty";
+import {
+ existsSync,
+ mkdirSync,
+ copyFileSync,
+ cpSync,
+ writeFileSync,
+ readFileSync,
+ readdirSync,
+} from "node:fs";
+import { resolve, basename, join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+import { execSync, execFileSync, spawn } from "node:child_process";
+import * as clack from "@clack/prompts";
+import { c } from "../ui/colors.js";
+import {
+ TEMPLATES,
+ type TemplateId,
+} from "../templates/generators.js";
+
+const ALL_TEMPLATE_IDS = TEMPLATES.map((t) => t.id);
+
+interface VideoMeta {
+ durationSeconds: number;
+ width: number;
+ height: number;
+ fps: number;
+ hasAudio: boolean;
+ videoCodec: string;
+}
+
+const WEB_CODECS = new Set(["h264", "vp8", "vp9", "av1", "theora"]);
+
+const DEFAULT_META: VideoMeta = {
+ durationSeconds: 5,
+ width: 1920,
+ height: 1080,
+ fps: 30,
+ hasAudio: false,
+ videoCodec: "h264",
+};
+
+// ---------------------------------------------------------------------------
+// ffprobe helper — shells out to ffprobe to avoid engine dependency
+// ---------------------------------------------------------------------------
+
+function probeVideo(filePath: string): VideoMeta | undefined {
+ try {
+ const raw = execFileSync(
+ "ffprobe",
+ ["-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", filePath],
+ { encoding: "utf-8", timeout: 15_000 },
+ );
+
+ const parsed: {
+ streams?: { codec_type?: string; codec_name?: string; width?: number; height?: number; r_frame_rate?: string; avg_frame_rate?: string }[];
+ format?: { duration?: string };
+ } = JSON.parse(raw);
+
+ const streams = parsed.streams ?? [];
+ const videoStream = streams.find((s) => s.codec_type === "video");
+ if (!videoStream) return undefined;
+
+ const hasAudio = streams.some((s) => s.codec_type === "audio");
+
+ let fps = 30;
+ const fpsStr = videoStream.avg_frame_rate ?? videoStream.r_frame_rate;
+ if (fpsStr) {
+ const parts = fpsStr.split("/");
+ const num = parseFloat(parts[0] ?? "");
+ const den = parseFloat(parts[1] ?? "1");
+ if (den !== 0 && !Number.isNaN(num) && !Number.isNaN(den)) {
+ fps = Math.round((num / den) * 100) / 100;
+ }
+ }
+
+ const durationStr = parsed.format?.duration;
+ const durationSeconds =
+ durationStr !== undefined ? parseFloat(durationStr) : 5;
+
+ return {
+ durationSeconds: Number.isNaN(durationSeconds) ? 5 : durationSeconds,
+ width: videoStream.width ?? 1920,
+ height: videoStream.height ?? 1080,
+ fps,
+ hasAudio,
+ videoCodec: videoStream.codec_name ?? "unknown",
+ };
+ } catch {
+ return undefined;
+ }
+}
+
+function isWebCompatible(codec: string): boolean {
+ return WEB_CODECS.has(codec.toLowerCase());
+}
+
+function hasFFmpeg(): boolean {
+ try {
+ execSync("ffmpeg -version", { stdio: "ignore", timeout: 5000 });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function transcodeToMp4(inputPath: string, outputPath: string): Promise<boolean> {
+ return new Promise((resolvePromise) => {
+ const child = spawn("ffmpeg", [
+ "-i", inputPath,
+ "-c:v", "libx264", "-preset", "fast", "-crf", "18",
+ "-c:a", "aac", "-b:a", "192k",
+ "-y", outputPath,
+ ], { stdio: "pipe" });
+
+ child.on("close", (code) => resolvePromise(code === 0));
+ child.on("error", () => resolvePromise(false));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Static template helpers
+// ---------------------------------------------------------------------------
+
+function getStaticTemplateDir(templateId: string): string {
+ const dir = dirname(fileURLToPath(import.meta.url));
+ // In dev: cli/src/commands/ → ../templates = cli/src/templates/
+ // In built: cli/dist/ → templates = cli/dist/templates/
+ const devPath = resolve(dir, "..", "templates", templateId);
+ const builtPath = resolve(dir, "templates", templateId);
+ return existsSync(devPath) ? devPath : builtPath;
+}
+
+function patchVideoSrc(dir: string, videoFilename: string | undefined): void {
+ const htmlFiles = readdirSync(dir, { withFileTypes: true, recursive: true })
+ .filter(e => e.isFile() && e.name.endsWith(".html"))
+ .map(e => join(e.parentPath ?? e.path, e.name));
+
+ for (const file of htmlFiles) {
+ let content = readFileSync(file, "utf-8");
+ if (videoFilename) {
+ content = content.replaceAll("__VIDEO_SRC__", videoFilename);
+ } else {
+ // Remove video elements with placeholder src
+ content = content.replace(/<video[^>]*src="__VIDEO_SRC__"[^>]*>[\s\S]*?<\/video>/g, "");
+ content = content.replace(/<video[^>]*src="__VIDEO_SRC__"[^>]*>/g, "");
+ }
+ writeFileSync(file, content, "utf-8");
+ }
+}
+
+// ---------------------------------------------------------------------------
+// handleVideoFile — probe, check codec, optionally transcode, copy to destDir
+// ---------------------------------------------------------------------------
+
+async function handleVideoFile(
+ videoPath: string,
+ destDir: string,
+ interactive: boolean,
+): Promise<{ meta: VideoMeta; localVideoName: string }> {
+ const probed = probeVideo(videoPath);
+ let meta: VideoMeta = { ...DEFAULT_META };
+ let localVideoName = basename(videoPath);
+
+ if (probed) {
+ meta = probed;
+ if (interactive) {
+ clack.log.info(
+ `Video: ${meta.width}x${meta.height}, ${meta.durationSeconds.toFixed(1)}s, ${meta.fps}fps${meta.hasAudio ? ", has audio" : ""}`,
+ );
+ }
+ } else {
+ const msg =
+ "ffprobe not found — using defaults (1920x1080, 5s, 30fps). Install: brew install ffmpeg";
+ if (interactive) {
+ clack.log.warn(msg);
+ } else {
+ console.log(c.warn(msg));
+ }
+ }
+
+ // Check codec compatibility
+ if (probed && !isWebCompatible(probed.videoCodec)) {
+ if (interactive) {
+ clack.log.warn(
+ c.warn(`Video codec "${probed.videoCodec}" is not supported by web browsers.`),
+ );
+ } else {
+ console.log(c.warn(`Video codec "${probed.videoCodec}" is not supported by browsers.`));
+ }
+
+ if (hasFFmpeg()) {
+ let shouldTranscode = !interactive; // non-interactive auto-transcodes
+
+ if (interactive) {
+ const transcode = await clack.select({
+ message: "Transcode to H.264 MP4 for browser playback?",
+ options: [
+ { value: "yes", label: "Yes, transcode", hint: "converts to H.264 MP4" },
+ { value: "no", label: "No, keep original", hint: "video won't play in browser" },
+ ],
+ });
+ if (clack.isCancel(transcode)) {
+ clack.cancel("Setup cancelled.");
+ process.exit(0);
+ }
+ shouldTranscode = transcode === "yes";
+ }
+
+ if (shouldTranscode) {
+ const mp4Name = localVideoName.replace(/\.[^.]+$/, ".mp4");
+ const mp4Path = resolve(destDir, mp4Name);
+ const spin = clack.spinner();
+ spin.start("Transcoding to H.264 MP4...");
+ const ok = await transcodeToMp4(videoPath, mp4Path);
+ if (ok) {
+ spin.stop(c.success(`Transcoded to ${mp4Name}`));
+ localVideoName = mp4Name;
+ } else {
+ spin.stop(c.warn("Transcode failed — copying original file"));
+ copyFileSync(videoPath, resolve(destDir, localVideoName));
+ }
+ } else {
+ copyFileSync(videoPath, resolve(destDir, localVideoName));
+ }
+ } else {
+ if (interactive) {
+ clack.log.warn(c.dim("ffmpeg not installed — cannot transcode."));
+ clack.log.info(c.accent("Install: brew install ffmpeg"));
+ } else {
+ console.log(c.warn("ffmpeg not installed — cannot transcode. Copying original."));
+ console.log(c.dim("Install: ") + c.accent("brew install ffmpeg"));
+ }
+ copyFileSync(videoPath, resolve(destDir, localVideoName));
+ }
+ } else {
+ copyFileSync(videoPath, resolve(destDir, localVideoName));
+ }
+
+ return { meta, localVideoName };
+}
+
+// ---------------------------------------------------------------------------
+// scaffoldProject — copy template, patch video refs, write meta.json
+// ---------------------------------------------------------------------------
+
+function scaffoldProject(
+ destDir: string,
+ name: string,
+ templateId: TemplateId,
+ localVideoName: string | undefined,
+): void {
+ mkdirSync(destDir, { recursive: true });
+
+ const templateDir = getStaticTemplateDir(templateId);
+ cpSync(templateDir, destDir, { recursive: true });
+ patchVideoSrc(destDir, localVideoName);
+
+ writeFileSync(
+ resolve(destDir, "meta.json"),
+ JSON.stringify(
+ {
+ id: name,
+ name,
+ createdAt: new Date().toISOString(),
+ },
+ null,
+ 2,
+ ),
+ "utf-8",
+ );
+}
+
+// ---------------------------------------------------------------------------
+// nextStepLoop — "What do you want to do?" loop after scaffolding
+// ---------------------------------------------------------------------------
+
+async function nextStepLoop(destDir: string): Promise<void> {
+ while (true) {
+ const next = await clack.select({
+ message: "What do you want to do?",
+ options: [
+ { value: "dev", label: "Open in studio", hint: "full editor with timeline" },
+ { value: "render", label: "Render to MP4", hint: "export video now" },
+ { value: "done", label: "Done for now" },
+ ],
+ });
+
+ if (clack.isCancel(next) || next === "done") {
+ clack.outro(c.success("Happy editing!"));
+ return;
+ }
+
+ // Hand off to the selected command — use explicit imports so the
+ // bundler can resolve them (dynamic import with a variable fails in bundles)
+ try {
+ if (next === "dev") {
+ const devCmd = await import("./dev.js").then((m) => m.default);
+ await runCommand(devCmd, { rawArgs: [destDir] });
+ } else if (next === "render") {
+ const renderCmd = await import("./render.js").then((m) => m.default);
+ await runCommand(renderCmd, { rawArgs: [destDir] });
+ }
+ } catch {
+ // Command may throw on Ctrl+C — that's fine, loop back
+ }
+
+ // Wait a tick so any lingering SIGINT state clears before Clack prompts again
+ await new Promise((r) => setTimeout(r, 100));
+ console.log();
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Exported command
+// ---------------------------------------------------------------------------
+
+export default defineCommand({
+ meta: { name: "init", description: "Scaffold a new composition project" },
+ args: {
+ name: { type: "positional", description: "Project name", required: false },
+ template: { type: "string", description: `Template: ${ALL_TEMPLATE_IDS.join(", ")}`, alias: "t" },
+ video: { type: "string", description: "Path to a source video file", alias: "V" },
+ },
+ async run({ args }) {
+ const templateFlag = args.template;
+ const videoFlag = args.video;
+
+ // -----------------------------------------------------------------------
+ // Non-interactive mode: flags provided
+ // -----------------------------------------------------------------------
+ if (templateFlag) {
+ if (!ALL_TEMPLATE_IDS.includes(templateFlag as TemplateId)) {
+ console.error(c.error(`Unknown template: ${templateFlag}`));
+ console.error(`Available: ${ALL_TEMPLATE_IDS.join(", ")}`);
+ process.exit(1);
+ }
+ const templateId = templateFlag as TemplateId;
+ const name = args.name ?? "my-video";
+ const destDir = resolve(name);
+
+ if (existsSync(destDir) && readdirSync(destDir).length > 0) {
+ console.error(
+ c.error(`Directory already exists and is not empty: ${name}`),
+ );
+ process.exit(1);
+ }
+
+ mkdirSync(destDir, { recursive: true });
+
+ let localVideoName: string | undefined;
+
+ if (videoFlag) {
+ const videoPath = resolve(videoFlag);
+ if (!existsSync(videoPath)) {
+ console.error(c.error(`Video file not found: ${videoFlag}`));
+ process.exit(1);
+ }
+ const result = await handleVideoFile(videoPath, destDir, false);
+ localVideoName = result.localVideoName;
+ }
+
+ scaffoldProject(destDir, basename(destDir), templateId, localVideoName);
+
+ console.log(c.success(`\nCreated ${c.accent(name + "/")}`));
+ for (const f of readdirSync(destDir)) {
+ console.log(` ${c.accent(f)}`);
+ }
+ return;
+ }
+
+ // -----------------------------------------------------------------------
+ // Interactive mode
+ // -----------------------------------------------------------------------
+ clack.intro("Create a new HyperFrames project");
+
+ // 1. Project name
+ let name: string;
+ const hasPositionalName = args.name !== undefined && args.name !== "";
+ if (hasPositionalName) {
+ name = args.name ?? "my-video";
+ } else {
+ const nameResult = await clack.text({
+ message: "Project name",
+ placeholder: "my-video",
+ defaultValue: "my-video",
+ });
+ if (clack.isCancel(nameResult)) {
+ clack.cancel("Setup cancelled.");
+ process.exit(0);
+ }
+ name = nameResult;
+ }
+
+ const destDir = resolve(name);
+
+ if (existsSync(destDir) && readdirSync(destDir).length > 0) {
+ const overwrite = await clack.confirm({
+ message: `Directory ${c.accent(name)} already exists and is not empty. Overwrite?`,
+ initialValue: false,
+ });
+ if (clack.isCancel(overwrite) || !overwrite) {
+ clack.cancel("Setup cancelled.");
+ process.exit(0);
+ }
+ }
+
+ // 2. Got a video?
+ let localVideoName: string | undefined;
+
+ if (videoFlag) {
+ // Video supplied via --video flag even in interactive mode
+ const videoPath = resolve(videoFlag);
+ if (!existsSync(videoPath)) {
+ clack.log.error(`Video file not found: ${videoFlag}`);
+ clack.cancel("Setup cancelled.");
+ process.exit(1);
+ }
+ mkdirSync(destDir, { recursive: true });
+ const result = await handleVideoFile(videoPath, destDir, true);
+ localVideoName = result.localVideoName;
+ } else {
+ const videoChoice = await clack.select({
+ message: "Got a video file?",
+ options: [
+ { value: "yes", label: "Yes", hint: "MP4 or WebM recommended" },
+ {
+ value: "no",
+ label: "No",
+ hint: "Start with motion graphics or text",
+ },
+ ],
+ initialValue: "no" as "yes" | "no",
+ });
+ if (clack.isCancel(videoChoice)) {
+ clack.cancel("Setup cancelled.");
+ process.exit(0);
+ }
+
+ if (videoChoice === "yes") {
+ const pathResult = await clack.text({
+ message: "Path to your video file (drag and drop or paste)",
+ placeholder: "/path/to/video.mp4",
+ validate(val) {
+ const trimmed = val?.trim();
+ if (!trimmed) return "Please enter a file path";
+ if (!existsSync(resolve(trimmed))) return "File not found";
+ return undefined;
+ },
+ });
+ if (clack.isCancel(pathResult)) {
+ clack.cancel("Setup cancelled.");
+ process.exit(0);
+ }
+
+ const videoPath = resolve(String(pathResult).trim());
+
+ mkdirSync(destDir, { recursive: true });
+ const result = await handleVideoFile(videoPath, destDir, true);
+ localVideoName = result.localVideoName;
+ }
+ }
+
+ // 3. Pick template — single list for all templates
+ const templateResult = await clack.select({
+ message: "Pick a template",
+ options: TEMPLATES.map((t) => ({
+ value: t.id,
+ label: t.label,
+ hint: t.hint,
+ })),
+ initialValue: TEMPLATES[0]?.id,
+ });
+ if (clack.isCancel(templateResult)) {
+ clack.cancel("Setup cancelled.");
+ process.exit(0);
+ }
+
+ const templateId: TemplateId = templateResult;
+
+ // 4. Copy template and patch
+ scaffoldProject(destDir, name, templateId, localVideoName);
+
+ const files = readdirSync(destDir);
+ clack.note(
+ files.map((f) => c.accent(f)).join("\n"),
+ c.success(`Created ${name}/`),
+ );
+
+ await nextStepLoop(destDir);
+ },
+});
diff --git a/packages/cli/src/commands/lint.ts b/packages/cli/src/commands/lint.ts
new file mode 100644
index 0000000000..daaa3e222e
--- /dev/null
+++ b/packages/cli/src/commands/lint.ts
@@ -0,0 +1,44 @@
+import { defineCommand } from "citty";
+import { readFileSync } from "node:fs";
+import { lintHyperframeHtml } from "@hyperframes/core/lint";
+import { c } from "../ui/colors.js";
+import { resolveProject } from "../utils/project.js";
+
+export default defineCommand({
+ meta: { name: "lint", description: "Validate a composition for common mistakes" },
+ args: {
+ dir: { type: "positional", description: "Project directory", required: false },
+ json: { type: "boolean", description: "Output findings as JSON", default: false },
+ },
+ async run({ args }) {
+ const project = resolveProject(args.dir);
+ const html = readFileSync(project.indexPath, "utf-8");
+ const result = lintHyperframeHtml(html, { filePath: project.indexPath });
+
+ if (args.json) {
+ console.log(JSON.stringify(result, null, 2));
+ process.exit(result.ok ? 0 : 1);
+ }
+
+ console.log(`${c.accent("◆")} Linting ${c.accent(project.name + "/index.html")}`);
+ console.log();
+
+ if (result.ok) {
+ console.log(`${c.success("◇")} ${c.success("0 errors, 0 warnings")}`);
+ return;
+ }
+
+ for (const finding of result.findings) {
+ const prefix = finding.severity === "error" ? c.error("✗") : c.warn("⚠");
+ const loc = finding.elementId ? ` ${c.accent(`[${finding.elementId}]`)}` : "";
+ console.log(`${prefix} ${c.bold(finding.code)}${loc}: ${finding.message}`);
+ if (finding.fixHint) {
+ console.log(` ${c.dim(`Fix: ${finding.fixHint}`)}`);
+ }
+ }
+
+ const summaryIcon = result.errorCount > 0 ? c.error("◇") : c.success("◇");
+ console.log(`\n${summaryIcon} ${result.errorCount} error(s), ${result.warningCount} warning(s)`);
+ process.exit(result.errorCount > 0 ? 1 : 0);
+ },
+});
diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts
new file mode 100644
index 0000000000..ee7ab41446
--- /dev/null
+++ b/packages/cli/src/commands/render.ts
@@ -0,0 +1,210 @@
+import { defineCommand } from "citty";
+import { existsSync, mkdirSync, statSync } from "node:fs";
+import { resolve, dirname, join } from "node:path";
+import { resolveProject } from "../utils/project.js";
+import { loadProducer } from "../utils/producer.js";
+import { c } from "../ui/colors.js";
+import { formatBytes, formatDuration, errorBox } from "../ui/format.js";
+import { renderProgress } from "../ui/progress.js";
+
+const VALID_FPS = new Set([24, 30, 60]);
+const VALID_QUALITY = new Set(["draft", "standard", "high"]);
+
+export default defineCommand({
+ meta: { name: "render", description: "Render a composition to MP4" },
+ args: {
+ dir: { type: "positional", description: "Project directory", required: false },
+ output: { type: "string", description: "Output path (default: renders/<name>.mp4)" },
+ fps: { type: "string", description: "Frame rate: 24, 30, 60", default: "30" },
+ quality: { type: "string", description: "Quality: draft, standard, high", default: "standard" },
+ workers: { type: "string", description: "Parallel workers 1-8" },
+ docker: { type: "boolean", description: "Use Docker for deterministic render", default: false },
+ gpu: { type: "boolean", description: "Use GPU encoding", default: false },
+ quiet: { type: "boolean", description: "Suppress verbose output", default: false },
+ },
+ async run({ args }) {
+ // ── Resolve project ────────────────────────────────────────────────────
+ const project = resolveProject(args.dir);
+
+ // ── Validate fps ───────────────────────────────────────────────────────
+ const fpsRaw = parseInt(args.fps ?? "30", 10);
+ if (!VALID_FPS.has(fpsRaw)) {
+ errorBox("Invalid fps", `Got "${args.fps ?? "30"}". Must be 24, 30, or 60.`);
+ process.exit(1);
+ }
+ const fps = fpsRaw as 24 | 30 | 60;
+
+ // ── Validate quality ───────────────────────────────────────────────────
+ const qualityRaw = args.quality ?? "standard";
+ if (!VALID_QUALITY.has(qualityRaw)) {
+ errorBox("Invalid quality", `Got "${qualityRaw}". Must be draft, standard, or high.`);
+ process.exit(1);
+ }
+ const quality = qualityRaw as "draft" | "standard" | "high";
+
+ // ── Validate workers ──────────────────────────────────────────────────
+ let workers: number | undefined;
+ if (args.workers != null) {
+ const parsed = parseInt(args.workers, 10);
+ if (isNaN(parsed) || parsed < 1 || parsed > 8) {
+ errorBox("Invalid workers", `Got "${args.workers}". Must be between 1 and 8.`);
+ process.exit(1);
+ }
+ workers = parsed;
+ }
+
+ // ── Resolve output path ───────────────────────────────────────────────
+ const rendersDir = resolve("renders");
+ const outputPath = args.output
+ ? resolve(args.output)
+ : join(rendersDir, `${project.name}.mp4`);
+
+ // Ensure output directory exists
+ const outputDir = dirname(outputPath);
+ if (!existsSync(outputDir)) {
+ mkdirSync(outputDir, { recursive: true });
+ }
+
+ const useDocker = args.docker ?? false;
+ const useGpu = args.gpu ?? false;
+ const quiet = args.quiet ?? false;
+
+ // ── Print render plan ─────────────────────────────────────────────────
+ const workerCount = workers ?? 4;
+ if (!quiet) {
+ console.log("");
+ console.log(c.accent("\u25C6") + " Rendering " + c.accent(project.name) + c.dim(" \u2192 " + outputPath));
+ console.log(c.dim(" " + fps + "fps \u00B7 " + quality + " \u00B7 " + workerCount + " workers"));
+ console.log("");
+ }
+
+ // ── Check FFmpeg for local renders ───────────────────────────────────
+ if (!useDocker) {
+ const { findFFmpeg, getFFmpegInstallHint } = await import("../browser/ffmpeg.js");
+ if (!findFFmpeg()) {
+ errorBox(
+ "FFmpeg not found",
+ "Rendering requires FFmpeg for video encoding.",
+ `Install: ${getFFmpegInstallHint()}`,
+ );
+ process.exit(1);
+ }
+ }
+
+ // ── Ensure browser for local renders ────────────────────────────────
+ if (!useDocker) {
+ const { ensureBrowser } = await import("../browser/manager.js");
+ const clack = await import("@clack/prompts");
+ const s = clack.spinner();
+ s.start("Checking browser...");
+ try {
+ const info = await ensureBrowser({
+ onProgress: (downloaded, total) => {
+ if (total <= 0) return;
+ const pct = Math.floor((downloaded / total) * 100);
+ s.message(`Downloading Chrome... ${c.progress(pct + "%")} ${c.dim("(" + formatBytes(downloaded) + " / " + formatBytes(total) + ")")}`);
+ },
+ });
+ s.stop(c.dim(`Browser: ${info.source}`));
+ } catch (err: unknown) {
+ s.stop(c.error("Browser not available"));
+ errorBox(
+ "Chrome not found",
+ err instanceof Error ? err.message : String(err),
+ "Run: npx hyperframes browser ensure",
+ );
+ process.exit(1);
+ }
+ }
+
+ // ── Render ────────────────────────────────────────────────────────────
+ if (useDocker) {
+ await renderDocker(project.dir, outputPath, { fps, quality, workers, gpu: useGpu, quiet });
+ } else {
+ await renderLocal(project.dir, outputPath, { fps, quality, workers, gpu: useGpu, quiet });
+ }
+ },
+});
+
+interface RenderOptions {
+ fps: 24 | 30 | 60;
+ quality: "draft" | "standard" | "high";
+ workers?: number;
+ gpu: boolean;
+ quiet: boolean;
+}
+
+async function renderDocker(
+ projectDir: string,
+ outputPath: string,
+ options: RenderOptions,
+): Promise<void> {
+ const producer = await loadProducer();
+ const startTime = Date.now();
+
+ try {
+ await producer.renderComposition(projectDir, {
+ output: outputPath,
+ fps: options.fps,
+ quality: options.quality,
+ workers: options.workers ?? null,
+ gpu: options.gpu,
+ quiet: options.quiet,
+ });
+ } catch (error: unknown) {
+ const message = error instanceof Error ? error.message : String(error);
+ errorBox("Render failed", message, "Try --docker for containerized rendering");
+ process.exit(1);
+ }
+
+ const elapsed = Date.now() - startTime;
+ printRenderComplete(outputPath, elapsed, options.quiet);
+}
+
+async function renderLocal(
+ projectDir: string,
+ outputPath: string,
+ options: RenderOptions,
+): Promise<void> {
+ const producer = await loadProducer();
+ const startTime = Date.now();
+
+ const job = producer.createRenderJob({
+ fps: options.fps,
+ quality: options.quality,
+ workers: options.workers,
+ useGpu: options.gpu,
+ });
+
+ const onProgress = options.quiet
+ ? undefined
+ : (progressJob: { progress: number }, message: string) => {
+ renderProgress(progressJob.progress, message);
+ };
+
+ try {
+ await producer.executeRenderJob(job, projectDir, outputPath, onProgress);
+ } catch (error: unknown) {
+ const message = error instanceof Error ? error.message : String(error);
+ errorBox("Render failed", message, "Try --docker for containerized rendering");
+ process.exit(1);
+ }
+
+ const elapsed = Date.now() - startTime;
+ printRenderComplete(outputPath, elapsed, options.quiet);
+}
+
+function printRenderComplete(outputPath: string, elapsedMs: number, quiet: boolean): void {
+ if (quiet) return;
+
+ let fileSize = "unknown";
+ if (existsSync(outputPath)) {
+ const stat = statSync(outputPath);
+ fileSize = formatBytes(stat.size);
+ }
+
+ const duration = formatDuration(elapsedMs);
+ console.log("");
+ console.log(c.success("\u25C7") + " " + c.accent(outputPath));
+ console.log(" " + c.bold(fileSize) + c.dim(" \u00B7 " + duration + " \u00B7 completed"));
+}
diff --git a/packages/cli/src/commands/upgrade.ts b/packages/cli/src/commands/upgrade.ts
new file mode 100644
index 0000000000..50989001ab
--- /dev/null
+++ b/packages/cli/src/commands/upgrade.ts
@@ -0,0 +1,61 @@
+import { defineCommand } from "citty";
+import * as clack from "@clack/prompts";
+import { c } from "../ui/colors.js";
+import { VERSION } from "../version.js";
+
+export default defineCommand({
+ meta: { name: "upgrade", description: "Check for updates and show upgrade instructions" },
+ args: {},
+ async run() {
+ clack.intro(c.bold("hyperframes upgrade"));
+
+ const s = clack.spinner();
+ s.start("Checking for updates...");
+
+ let latest: string;
+ try {
+ const res = await fetch("https://registry.npmjs.org/hyperframes/latest");
+ if (!res.ok) {
+ s.stop("Could not check for updates");
+ clack.outro(c.dim("Package not yet published to npm."));
+ return;
+ }
+ const data = (await res.json()) as { version?: string };
+ latest = data.version ?? VERSION;
+ } catch {
+ s.stop("Could not check for updates");
+ clack.outro(c.dim("Network error. Check your connection."));
+ return;
+ }
+
+ if (latest === VERSION) {
+ s.stop(c.success("Already up to date"));
+ clack.outro(`${c.success("◇")} ${c.bold("v" + VERSION)}`);
+ return;
+ }
+
+ s.stop("Update available");
+
+ console.log();
+ console.log(` ${c.dim("Current:")} ${c.bold("v" + VERSION)}`);
+ console.log(` ${c.dim("Latest:")} ${c.bold(c.accent("v" + latest))}`);
+ console.log();
+
+ const shouldUpgrade = await clack.confirm({
+ message: "Upgrade now?",
+ });
+
+ if (clack.isCancel(shouldUpgrade) || !shouldUpgrade) {
+ clack.outro(c.dim("Skipped."));
+ return;
+ }
+
+ console.log();
+ console.log(` ${c.accent("npm install -g hyperframes@" + latest)}`);
+ console.log(` ${c.dim("or")}`);
+ console.log(` ${c.accent("npx hyperframes@" + latest + " --version")}`);
+ console.log();
+
+ clack.outro(c.success("Run one of the commands above to upgrade."));
+ },
+});
diff --git a/packages/cli/src/docs/compositions.md b/packages/cli/src/docs/compositions.md
new file mode 100644
index 0000000000..98a103f539
--- /dev/null
+++ b/packages/cli/src/docs/compositions.md
@@ -0,0 +1,26 @@
+# Compositions
+
+A composition is an HTML document that defines a video timeline.
+
+## Structure
+Every composition needs a root element with `data-composition-id`:
+```html
+<div id="root" data-composition-id="root" data-width="1920" data-height="1080">
+ <!-- Elements go here -->
+</div>
+```
+
+## Nested Compositions
+Embed one composition inside another:
+```html
+<div data-composition-src="./intro.html" data-start="0" data-duration="5"></div>
+```
+
+## Listing Compositions
+Use `npx hyperframes compositions` to see all compositions in a project.
+
+## Variables
+Compositions can expose variables for dynamic content:
+```html
+<div data-composition-id="card" data-var-title="string" data-var-color="color">
+```
diff --git a/packages/cli/src/docs/data-attributes.md b/packages/cli/src/docs/data-attributes.md
new file mode 100644
index 0000000000..9eaf5d8ce1
--- /dev/null
+++ b/packages/cli/src/docs/data-attributes.md
@@ -0,0 +1,22 @@
+# Data Attributes
+
+Core attributes for controlling element timing and behavior.
+
+## Timing
+- `data-start="0"` — Start time in seconds
+- `data-duration="5"` — Duration in seconds
+- `data-track-index="0"` — Timeline track number (controls z-ordering)
+
+## Media
+- `data-media-start="2"` — Media playback offset / trim point (seconds)
+- `data-volume="0.8"` — Audio/video volume, 0 to 1
+- `data-has-audio="true"` — Indicates video has an audio track
+
+## Composition
+- `data-composition-id="root"` — Unique ID for composition wrapper (required)
+- `data-width="1920"` — Composition width in pixels
+- `data-height="1080"` — Composition height in pixels
+- `data-composition-src="./intro.html"` — Nested composition source
+
+## Element Visibility
+Add `class="clip"` to timed elements so the runtime can manage their visibility lifecycle.
diff --git a/packages/cli/src/docs/gsap.md b/packages/cli/src/docs/gsap.md
new file mode 100644
index 0000000000..4058cb4b59
--- /dev/null
+++ b/packages/cli/src/docs/gsap.md
@@ -0,0 +1,23 @@
+# GSAP Animation
+
+HyperFrames uses GSAP for animation. Timelines are paused and controlled by the runtime.
+
+## Setup
+```html
+<script src="https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.min.js"></script>
+<script>
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#title", { opacity: 1, duration: 0.5 }, 0);
+ window.__timelines = window.__timelines || {};
+ window.__timelines["root"] = tl;
+</script>
+```
+
+## Key Rules
+- Always create timelines with `{ paused: true }`
+- Register timelines on `window.__timelines` with the composition ID as key
+- Position parameter (3rd arg) sets absolute time: `tl.to(el, vars, 1.5)`
+- Supported methods: `set`, `to`, `from`, `fromTo`
+
+## Supported Properties
+opacity, x, y, scale, scaleX, scaleY, rotation, width, height, visibility
diff --git a/packages/cli/src/docs/rendering.md b/packages/cli/src/docs/rendering.md
new file mode 100644
index 0000000000..1ae283aa4d
--- /dev/null
+++ b/packages/cli/src/docs/rendering.md
@@ -0,0 +1,23 @@
+# Rendering
+
+Render compositions to MP4 with `npx hyperframes render`.
+
+## Local Mode (default)
+Uses Puppeteer (bundled Chromium) + system FFmpeg. Fast for iteration.
+Requires: FFmpeg installed (`brew install ffmpeg` or `apt install ffmpeg`).
+
+## Docker Mode (--docker)
+Deterministic output with exact Chrome version and fonts. For production.
+Requires: Docker installed and running.
+
+## Options
+- `-f, --fps` — 24, 30, or 60 (default: 30)
+- `-q, --quality` — draft, standard, high (default: standard)
+- `-w, --workers` — Parallel workers 1-8 (default: auto)
+- `--gpu` — Use GPU encoding (NVENC, VideoToolbox, VAAPI)
+- `-o, --output` — Custom output path
+
+## Tips
+- Use `draft` quality for fast previews during development
+- Use `npx hyperframes benchmark` to find optimal settings
+- 4 workers is usually the sweet spot for most compositions
diff --git a/packages/cli/src/docs/templates.md b/packages/cli/src/docs/templates.md
new file mode 100644
index 0000000000..9a562b6dba
--- /dev/null
+++ b/packages/cli/src/docs/templates.md
@@ -0,0 +1,15 @@
+# Templates
+
+Built-in templates available via `npx hyperframes init --template <name>`.
+
+## blank
+Empty 1920x1080 composition with GSAP timeline wired up. Start from scratch.
+
+## title-card
+Animated title and subtitle with GSAP fade-in/out. Good for intro cards.
+
+## video-edit
+Video element with trimming, audio, and track controls. Starting point for video editing.
+
+## Custom Templates
+Any directory with an `index.html` can serve as a template. Copy it manually or build your own init workflow.
diff --git a/packages/cli/src/docs/troubleshooting.md b/packages/cli/src/docs/troubleshooting.md
new file mode 100644
index 0000000000..8fac308621
--- /dev/null
+++ b/packages/cli/src/docs/troubleshooting.md
@@ -0,0 +1,22 @@
+# Troubleshooting
+
+## "No composition found"
+Your directory needs an `index.html`. Run `npx hyperframes init` to create one.
+
+## "FFmpeg not found"
+Local rendering requires FFmpeg. Install it:
+- macOS: `brew install ffmpeg`
+- Ubuntu: `sudo apt install ffmpeg`
+- Windows: Download from https://ffmpeg.org/download.html
+
+## Lint errors
+Run `npx hyperframes lint` to check for common issues:
+- Missing `data-composition-id` on root element
+- Missing `class="clip"` on timed elements
+- Overlapping timelines or invalid data attributes
+
+## Preview not updating
+Make sure you're editing the `index.html` in the project directory. The preview server watches for file changes and auto-reloads.
+
+## Render looks different from preview
+Use `--docker` mode for deterministic output. Local renders may differ due to font availability and Chrome version.
diff --git a/packages/cli/src/templates/generators.ts b/packages/cli/src/templates/generators.ts
new file mode 100644
index 0000000000..8d2657477d
--- /dev/null
+++ b/packages/cli/src/templates/generators.ts
@@ -0,0 +1,14 @@
+export type TemplateId = "warm-grain" | "play-mode" | "swiss-grid" | "vignelli";
+
+export interface TemplateOption {
+ id: TemplateId;
+ label: string;
+ hint: string;
+}
+
+export const TEMPLATES: TemplateOption[] = [
+ { id: "warm-grain", label: "Warm Grain", hint: "Cream aesthetic with grain texture" },
+ { id: "play-mode", label: "Play Mode", hint: "Playful elastic animations" },
+ { id: "swiss-grid", label: "Swiss Grid", hint: "Structured grid layout" },
+ { id: "vignelli", label: "Vignelli", hint: "Bold typography with red accents" },
+];
diff --git a/packages/cli/src/templates/play-mode/compositions/captions.html b/packages/cli/src/templates/play-mode/compositions/captions.html
new file mode 100644
index 0000000000..14f2a8fdd2
--- /dev/null
+++ b/packages/cli/src/templates/play-mode/compositions/captions.html
@@ -0,0 +1,97 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1920" data-height="1080" data-duration="16.04">
+ <div id="captions-container"></div>
+
+ <style>
+ [data-composition-id="captions"] {
+ width: 1920px;
+ height: 1080px;
+ pointer-events: none;
+ }
+
+ [data-composition-id="captions"] #captions-container {
+ position: absolute;
+ bottom: 100px; /* Position in bottom 1/3 */
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ height: 150px; /* Fixed height for the caption box */
+ }
+
+ .caption-box {
+ position: absolute; /* Stacked in the same place */
+ background-color: #FF2D8A;
+ color: white;
+ padding: 20px 40px;
+ border-radius: 16px;
+ font-family: 'Nunito', sans-serif;
+ font-weight: 900; /* Nunito Black */
+ font-size: 64px;
+ text-align: center;
+ display: inline-block;
+ white-space: nowrap;
+ opacity: 0;
+ visibility: hidden;
+ transform: scale(0);
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.839, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics.', 'start': 3.579, 'end': 4.639}, {'text': 'Sixty-two', 'start': 4.659, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.099, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.479}, {'text': 'look', 'start': 10.52, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.86}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Hyperframes', 'start': 15.079, 'end': 15.42}];
+ const container = document.getElementById('captions-container');
+ const tl = gsap.timeline({ paused: true });
+
+ // Group transcript into lines (max 5 words)
+ const lines = [];
+ for (let i = 0; i < TRANSCRIPT.length; i += 5) {
+ lines.push(TRANSCRIPT.slice(i, i + 5));
+ }
+
+ lines.forEach((lineWords, index) => {
+ const lineText = lineWords.map(w => w.text).join(' ');
+ const startTime = lineWords[0].start;
+ const endTime = lineWords[lineWords.length - 1].end;
+
+ // Create element
+ const el = document.createElement('div');
+ el.className = 'caption-box';
+ el.textContent = lineText;
+ el.id = `caption-line-${index}`;
+ container.appendChild(el);
+
+ // Animation: Pop in with scale-up bounce (0% to 110% to 100%)
+ tl.to(el, {
+ autoAlpha: 1,
+ scale: 1.1,
+ duration: 0.2,
+ ease: "power2.out"
+ }, startTime);
+
+ tl.to(el, {
+ scale: 1,
+ duration: 0.1,
+ ease: "power2.inOut"
+ }, startTime + 0.2);
+
+ // Stay visible until next line or end of its duration
+ // We hide it when the next line starts or at its own end time
+ const hideTime = (index < lines.length - 1) ? Math.min(endTime, lines[index+1][0].start) : endTime;
+
+ tl.to(el, {
+ autoAlpha: 0,
+ scale: 0,
+ duration: 0.15,
+ ease: "power2.in"
+ }, hideTime);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/cli/src/templates/play-mode/compositions/intro.html b/packages/cli/src/templates/play-mode/compositions/intro.html
new file mode 100644
index 0000000000..5ea591cab6
--- /dev/null
+++ b/packages/cli/src/templates/play-mode/compositions/intro.html
@@ -0,0 +1,88 @@
+<template id="intro-template">
+ <div id="intro-comp" data-composition-id="intro" data-start="0" data-duration="16.04" data-width="1920" data-height="1080">
+ <div class="intro-container">
+ <h1 class="title">HYPERFRAMES</h1>
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@900&display=swap');
+
+ [data-composition-id="intro"] .intro-container {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ pointer-events: none;
+ }
+
+ [data-composition-id="intro"] .title {
+ font-family: 'Nunito', sans-serif;
+ font-weight: 900;
+ font-size: 180px;
+ color: #FF2D8A; /* Hot Pink */
+ text-transform: uppercase;
+ transform: rotate(-5deg); /* Tilted 5 degrees */
+ margin: 0;
+ padding: 20px;
+ /* Layered offset shadow for depth without suffocating letterforms */
+ filter: drop-shadow(8px 8px 0 #FFFFFF) drop-shadow(15px 15px 0 rgba(0,0,0,0.1));
+ opacity: 0;
+ scale: 0;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // --- INTRO SEQUENCE ---
+ // Animation: Scale-up bounce (0% to 110% to 100%) with elastic overshoot
+ // Starts at 0.5s, lasts until 3s
+ tl.to('[data-composition-id="intro"] .title', {
+ opacity: 1,
+ scale: 1.1,
+ duration: 0.6,
+ ease: "back.out(1.7)",
+ delay: 0.5
+ })
+ .to('[data-composition-id="intro"] .title', {
+ scale: 1,
+ duration: 0.4,
+ ease: "elastic.out(1, 0.3)"
+ })
+ // Ambient motion
+ .to('[data-composition-id="intro"] .title', {
+ rotation: "-3deg",
+ duration: 1,
+ repeat: 1,
+ yoyo: true,
+ ease: "sine.inOut"
+ }, "-=0.5")
+ // Exit intro
+ .to('[data-composition-id="intro"] .title', {
+ opacity: 0,
+ scale: 0.5,
+ duration: 0.3,
+ ease: "power2.in"
+ }, 1.4);
+
+ // --- END CARD SEQUENCE ---
+ // Appears at 14.619s (after Moment 3 finishes exiting at 14.239 + 0.3)
+ tl.to('[data-composition-id="intro"] .title', {
+ opacity: 1,
+ scale: 1.1,
+ duration: 0.6,
+ ease: "back.out(1.7)"
+ }, 14.619)
+ .to('[data-composition-id="intro"] .title', {
+ scale: 1,
+ duration: 0.4,
+ ease: "elastic.out(1, 0.3)"
+ });
+
+ window.__timelines["intro"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/cli/src/templates/play-mode/compositions/stats.html b/packages/cli/src/templates/play-mode/compositions/stats.html
new file mode 100644
index 0000000000..d96b6acd3d
--- /dev/null
+++ b/packages/cli/src/templates/play-mode/compositions/stats.html
@@ -0,0 +1,252 @@
+<template id="stats-template">
+ <div data-composition-id="stats" data-width="1920" data-height="1080" data-duration="16.04">
+ <div id="stats-container">
+ <!-- Moment 1: 47% NEED MOTION GRAPHICS -->
+ <div id="moment-1" class="moment" style="opacity: 0; transform: scale(0) rotate(8deg);">
+ <div class="sticker-stack">
+ <div class="sticker-bg blue-bg"></div>
+ <div class="sticker-content white-bg blue-border">
+ <div class="stat-number blue-text">47%</div>
+ <div class="stat-label blue-text">NEED MOTION GRAPHICS</div>
+ </div>
+ </div>
+ <!-- Decorative shapes -->
+ <div class="shape circle pink-bg" style="top: -40px; left: -40px; width: 80px; height: 80px;"></div>
+ <div class="shape pill lime-bg" style="bottom: -30px; right: -50px; width: 120px; height: 40px; transform: rotate(-15deg);"></div>
+ </div>
+
+ <!-- Moment 2: 62% STRUGGLE WITH STATIC CONTENT -->
+ <div id="moment-2" class="moment" style="opacity: 0; transform: scale(0) rotate(-5deg);">
+ <div class="sticker-stack">
+ <div class="sticker-bg white-bg"></div>
+ <div class="sticker-content blue-bg white-border">
+ <div class="stat-number white-text">62%</div>
+ <div class="stat-label white-text">STRUGGLE WITH STATIC CONTENT</div>
+ </div>
+ </div>
+ <!-- Decorative shapes -->
+ <div class="shape blob yellow-bg" style="top: -50px; right: -30px; width: 100px; height: 100px; border-radius: 40% 60% 70% 30% / 40% 50% 60% 50%;"></div>
+ <div class="shape circle pink-bg" style="bottom: -20px; left: -40px; width: 60px; height: 60px;"></div>
+ </div>
+
+ <!-- Moment 3: 75% LACK EDITING SKILLS -->
+ <div id="moment-3" class="moment" style="opacity: 0; transform: scale(0) rotate(3deg);">
+ <div class="sticker-stack">
+ <div class="sticker-bg pink-bg"></div>
+ <div class="sticker-content white-bg pink-border">
+ <div class="stat-number pink-text">75%</div>
+ <div class="stat-label pink-text">LACK EDITING SKILLS</div>
+ </div>
+ </div>
+ <!-- Decorative shapes -->
+ <div class="shape pill blue-bg" style="top: -30px; left: 50%; transform: translateX(-50%) rotate(5deg); width: 150px; height: 45px;"></div>
+ <div class="shape circle yellow-bg" style="bottom: -40px; right: -20px; width: 90px; height: 90px;"></div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="stats"] {
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ font-family: 'Nunito', sans-serif;
+ overflow: hidden;
+ }
+
+ [data-composition-id="stats"] #stats-container {
+ width: 100%;
+ height: 100%;
+ position: relative;
+ }
+
+ [data-composition-id="stats"] .moment {
+ position: absolute;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 40px;
+ z-index: 100;
+ }
+
+ /* Layout Positions */
+ [data-composition-id="stats"] #moment-1 {
+ top: 200px;
+ right: 150px; /* Right side when A-roll is Left */
+ width: 600px;
+ }
+
+ [data-composition-id="stats"] #moment-2 {
+ top: 250px;
+ left: 100px; /* Left side when A-roll is Right */
+ width: 700px;
+ }
+
+ [data-composition-id="stats"] #moment-3 {
+ bottom: 100px; /* Below A-roll when centered */
+ left: 50%;
+ transform: translateX(-50%);
+ width: 800px;
+ }
+
+ /* Sticker Stack Effect */
+ [data-composition-id="stats"] .sticker-stack {
+ position: relative;
+ width: 100%;
+ padding: 40px;
+ filter: drop-shadow(0 15px 0 rgba(0, 87, 255, 0.2));
+ }
+
+ [data-composition-id="stats"] .sticker-bg {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ border-radius: 40px;
+ z-index: -1;
+ transform: rotate(-2deg);
+ }
+
+ [data-composition-id="stats"] .sticker-content {
+ position: relative;
+ padding: 40px;
+ border-radius: 35px;
+ border: 8px solid currentColor;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ text-align: center;
+ }
+
+ /* Colors */
+ [data-composition-id="stats"] .blue-bg { background-color: #0057FF; }
+ [data-composition-id="stats"] .pink-bg { background-color: #FF2D8A; }
+ [data-composition-id="stats"] .lime-bg { background-color: #7FFF00; }
+ [data-composition-id="stats"] .yellow-bg { background-color: #FFE500; }
+ [data-composition-id="stats"] .white-bg { background-color: #FFFFFF; }
+
+ [data-composition-id="stats"] .blue-text { color: #0057FF; }
+ [data-composition-id="stats"] .white-text { color: #FFFFFF; }
+ [data-composition-id="stats"] .pink-text { color: #FF2D8A; }
+
+ [data-composition-id="stats"] .blue-border { border-color: #0057FF; }
+ [data-composition-id="stats"] .white-border { border-color: #FFFFFF; }
+ [data-composition-id="stats"] .pink-border { border-color: #FF2D8A; }
+
+ /* Typography */
+ [data-composition-id="stats"] .stat-number {
+ font-size: 180px;
+ font-weight: 900;
+ line-height: 1;
+ margin-bottom: 10px;
+ }
+
+ [data-composition-id="stats"] .stat-label {
+ font-size: 48px;
+ font-weight: 900;
+ line-height: 1.1;
+ max-width: 500px;
+ }
+
+ /* Shapes */
+ [data-composition-id="stats"] .shape {
+ position: absolute;
+ z-index: -2;
+ border-radius: 50%;
+ }
+ [data-composition-id="stats"] .pill {
+ border-radius: 100px;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.839, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics.', 'start': 3.579, 'end': 4.639}, {'text': 'Sixty-two', 'start': 4.659, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.099, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.479}, {'text': 'look', 'start': 10.52, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.86}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Hyperframes', 'start': 15.079, 'end': 15.42}];
+ const tl = gsap.timeline({ paused: true });
+
+ // Helper to find word timing
+ function getWordTime(wordText) {
+ const word = TRANSCRIPT.find(w =>
+ w.text.toLowerCase().replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"").startsWith(wordText.toLowerCase())
+ );
+ return word ? word.start : null;
+ }
+
+ // Timings from transcript
+ const t1 = getWordTime("Forty-seven") || 1.839;
+ const t2 = getWordTime("Sixty-two") || 4.659;
+ const t3 = getWordTime("three") || 8.88;
+
+ // Moment 1 Animation (approx 5s)
+ tl.to('#moment-1', {
+ opacity: 1,
+ scale: 1,
+ duration: 0.8,
+ ease: "elastic.out(1, 0.6)",
+ onStart: () => gsap.set('#moment-1', { transformOrigin: "center center" })
+ }, t1);
+
+ // Moment 1 Exit (before Moment 2)
+ tl.to('#moment-1', {
+ opacity: 0,
+ scale: 0.5,
+ duration: 0.3,
+ ease: "back.in(1.7)"
+ }, t2 - 0.4);
+
+ // Moment 2 Animation (approx 9s)
+ tl.to('#moment-2', {
+ opacity: 1,
+ scale: 1,
+ duration: 0.8,
+ ease: "elastic.out(1, 0.6)",
+ onStart: () => gsap.set('#moment-2', { transformOrigin: "center center" })
+ }, t2);
+
+ // Moment 2 Exit (before Moment 3)
+ tl.to('#moment-2', {
+ opacity: 0,
+ scale: 0.5,
+ duration: 0.3,
+ ease: "back.in(1.7)"
+ }, t3 - 0.4);
+
+ // Moment 3 Animation (approx 13s)
+ tl.to('#moment-3', {
+ opacity: 1,
+ scale: 1,
+ duration: 0.8,
+ ease: "elastic.out(1, 0.6)",
+ onStart: () => gsap.set('#moment-3', { transformOrigin: "center center" })
+ }, t3);
+
+ // Moment 3 Exit: 3 words before 'Hyperframes'
+ // 'Editor' is at 15.079. 3 words before is 'So' at 14.239.
+ tl.to('#moment-3', {
+ opacity: 0,
+ scale: 0.5,
+ duration: 0.3,
+ ease: "back.in(1.7)"
+ }, 14.239);
+
+ // Ambient Motion (Finite)
+ const totalDuration = 16.04;
+ gsap.utils.toArray('.shape').forEach((shape, i) => {
+ const stepDuration = 2 + (i * 0.2);
+ const steps = Math.ceil(totalDuration / stepDuration);
+ for(let s = 0; s < steps; s++) {
+ tl.to(shape, {
+ y: (s % 2 === 0 ? 15 : -15),
+ rotation: (s % 2 === 0 ? 5 : -5),
+ duration: stepDuration,
+ ease: "sine.inOut"
+ }, s * stepDuration);
+ }
+ });
+
+ window.__timelines["stats"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/cli/src/templates/play-mode/index.html b/packages/cli/src/templates/play-mode/index.html
new file mode 100644
index 0000000000..1e50e10d08
--- /dev/null
+++ b/packages/cli/src/templates/play-mode/index.html
@@ -0,0 +1,173 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Hyperframes - Play Mode</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1920px;
+ height: 1080px;
+ overflow: hidden;
+ background-color: #FFFFFF;
+ font-family: 'Nunito', sans-serif;
+ }
+
+ #main-composition {
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ }
+
+ #bg-comp,
+ #aroll-comp,
+ #intro-comp,
+ #stats-comp,
+ #captions-comp {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ }
+
+ #bg-comp {
+ z-index: 1;
+ }
+
+ #aroll-comp {
+ z-index: 10;
+ }
+
+ #intro-comp {
+ z-index: 100;
+ }
+
+ #stats-comp {
+ z-index: 150;
+ }
+
+ #captions-comp {
+ z-index: 200;
+ }
+
+ #aroll-container {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ z-index: 0;
+ }
+
+ #short_mag_cut {
+ border-radius: 16px;
+ box-shadow: 0 20px 60px rgba(0,0,0,0.4);
+ border: 8px solid #FFFFFF;
+ }
+
+ #background-layer {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-color: #FFFFFF;
+ z-index: 0;
+ }
+ </style>
+ <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@900&display=swap" rel="stylesheet">
+</head>
+<body>
+ <div id="main-composition" data-composition-id="main-video" data-start="0" data-duration="16.04" data-width="1920" data-height="1080">
+ <!-- Background Layer Composition -->
+ <div id="bg-comp" data-composition-id="background" data-start="0" data-duration="16.04" data-width="1920" data-height="1080" data-track-index="1">
+ <div id="background-layer"></div>
+ <style>
+ #background-layer {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-color: #FFFFFF;
+ }
+ </style>
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const bg = document.getElementById('background-layer');
+ // Sync with A-roll framing 3 (4.659s)
+ tl.to(bg, { backgroundColor: "#0057FF", duration: 0.5 }, 4.659);
+ // Sync with A-roll framing 4 (8.88s)
+ tl.to(bg, { backgroundColor: "#FFFFFF", duration: 0.5 }, 8.88);
+ window.__timelines["background"] = tl;
+ })();
+ </script>
+ </div>
+
+ <!-- A-roll Layer Composition -->
+ <div id="aroll-comp" data-composition-id="aroll-layer" data-start="0" data-duration="16.04" data-width="1920" data-height="1080" data-track-index="10">
+ <div id="aroll-container">
+ <video id="short_mag_cut"
+ src="__VIDEO_SRC__"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="1"
+ style="width: 100%; height: auto;"></video>
+ </div>
+ <style>
+ #aroll-container {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ }
+ #short_mag_cut {
+ border-radius: 16px;
+ box-shadow: 0 20px 60px rgba(0,0,0,0.4);
+ border: 8px solid #FFFFFF;
+ }
+ </style>
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const container = document.getElementById('aroll-container');
+ gsap.set(container, { y: -1100, scale: 0.8 });
+ tl.to(container, { y: 0, duration: 1.2, ease: "elastic.out(1, 0.6)" }, 0);
+ tl.to(container, { scale: 1.4, x: -300, duration: 1, ease: "back.out(1.7)" }, 1.839);
+ tl.to(container, { scale: 0.7, x: 400, duration: 1, ease: "back.out(1.7)" }, 4.659);
+ tl.to(container, { scale: 0.9, x: 0, duration: 1, ease: "back.out(1.7)" }, 8.88);
+ window.__timelines["aroll-layer"] = tl;
+ })();
+ </script>
+ </div>
+
+ <!-- Compositions -->
+ <div id="intro-comp" data-composition-id="intro" data-composition-src="compositions/intro.html" data-start="0" data-duration="16.04" data-width="1920" data-height="1080" data-track-index="100"></div>
+ <div id="captions-comp" data-composition-id="captions" data-composition-src="compositions/captions.html" data-start="0" data-duration="16.04" data-width="1920" data-height="1080" data-track-index="200"></div>
+ <div id="stats-comp" data-composition-id="stats" data-composition-src="compositions/stats.html" data-start="0" data-duration="16.04" data-width="1920" data-height="1080" data-track-index="150"></div>
+
+ <!-- Audio Clips -->
+ <audio id="sfx-bounce-0" src="" data-start="0" data-track-index="5"></audio>
+ <audio id="sfx-whoosh-1" src="" data-start="1.839" data-track-index="6"></audio>
+ <audio id="sfx-pop-1" src="" data-start="2.039" data-track-index="7"></audio>
+ <audio id="sfx-whoosh-2" src="" data-start="4.659" data-track-index="6"></audio>
+ <audio id="sfx-pop-2" src="" data-start="4.859" data-track-index="7"></audio>
+ <audio id="sfx-whoosh-3" src="" data-start="8.88" data-track-index="6"></audio>
+ <audio id="sfx-pop-3" src="" data-start="9.08" data-track-index="7"></audio>
+
+ <script>
+ window.__timelines = window.__timelines || {};
+ const tl = gsap.timeline({ paused: true });
+ window.__timelines["main-video"] = tl;
+ </script>
+ </div>
+</body>
+</html>
\ No newline at end of file
diff --git a/packages/cli/src/templates/swiss-grid/assets/swiss-grid.svg b/packages/cli/src/templates/swiss-grid/assets/swiss-grid.svg
new file mode 100644
index 0000000000..a3fb54f753
--- /dev/null
+++ b/packages/cli/src/templates/swiss-grid/assets/swiss-grid.svg
@@ -0,0 +1,116 @@
+<svg viewBox="0 0 1920 1080" xmlns="http://www.w3.org/2000/svg">
+ <rect width="1920" height="1080" fill="#F2F2F2" />
+
+ <g id="thin-grid-lines" stroke="#0A1E3D" stroke-width="1" opacity="0.1">
+ <line id="v-thin-1" x1="60" y1="0" x2="60" y2="1080" />
+ <line id="v-thin-2" x1="120" y1="0" x2="120" y2="1080" />
+ <line id="v-thin-3" x1="180" y1="0" x2="180" y2="1080" />
+ <line id="v-thin-5" x1="300" y1="0" x2="300" y2="1080" />
+ <line id="v-thin-6" x1="360" y1="0" x2="360" y2="1080" />
+ <line id="v-thin-7" x1="420" y1="0" x2="420" y2="1080" />
+ <line id="v-thin-9" x1="540" y1="0" x2="540" y2="1080" />
+ <line id="v-thin-10" x1="600" y1="0" x2="600" y2="1080" />
+ <line id="v-thin-11" x1="660" y1="0" x2="660" y2="1080" />
+ <line id="v-thin-13" x1="780" y1="0" x2="780" y2="1080" />
+ <line id="v-thin-14" x1="840" y1="0" x2="840" y2="1080" />
+ <line id="v-thin-15" x1="900" y1="0" x2="900" y2="1080" />
+ <line id="v-thin-17" x1="1020" y1="0" x2="1020" y2="1080" />
+ <line id="v-thin-18" x1="1080" y1="0" x2="1080" y2="1080" />
+ <line id="v-thin-19" x1="1140" y1="0" x2="1140" y2="1080" />
+ <line id="v-thin-21" x1="1260" y1="0" x2="1260" y2="1080" />
+ <line id="v-thin-22" x1="1320" y1="0" x2="1320" y2="1080" />
+ <line id="v-thin-23" x1="1380" y1="0" x2="1380" y2="1080" />
+ <line id="v-thin-25" x1="1500" y1="0" x2="1500" y2="1080" />
+ <line id="v-thin-26" x1="1560" y1="0" x2="1560" y2="1080" />
+ <line id="v-thin-27" x1="1620" y1="0" x2="1620" y2="1080" />
+ <line id="v-thin-29" x1="1740" y1="0" x2="1740" y2="1080" />
+ <line id="v-thin-30" x1="1800" y1="0" x2="1800" y2="1080" />
+ <line id="v-thin-31" x1="1860" y1="0" x2="1860" y2="1080" />
+ <line id="h-thin-1" x1="0" y1="60" x2="1920" y2="60" />
+ <line id="h-thin-2" x1="0" y1="120" x2="1920" y2="120" />
+ <line id="h-thin-3" x1="0" y1="180" x2="1920" y2="180" />
+ <line id="h-thin-5" x1="0" y1="300" x2="1920" y2="300" />
+ <line id="h-thin-6" x1="0" y1="360" x2="1920" y2="360" />
+ <line id="h-thin-7" x1="0" y1="420" x2="1920" y2="420" />
+ <line id="h-thin-9" x1="0" y1="540" x2="1920" y2="540" />
+ <line id="h-thin-10" x1="0" y1="600" x2="1920" y2="600" />
+ <line id="h-thin-11" x1="0" y1="660" x2="1920" y2="660" />
+ <line id="h-thin-13" x1="0" y1="780" x2="1920" y2="780" />
+ <line id="h-thin-14" x1="0" y1="840" x2="1920" y2="840" />
+ <line id="h-thin-15" x1="0" y1="900" x2="1920" y2="900" />
+ <line id="h-thin-17" x1="0" y1="1020" x2="1920" y2="1020" />
+ </g>
+
+ <g id="thick-grid-lines" stroke="#0A1E3D" stroke-width="3" opacity="0.2">
+ <line id="v-thick-1" x1="240" y1="0" x2="240" y2="1080" />
+ <line id="v-thick-2" x1="480" y1="0" x2="480" y2="1080" />
+ <line id="v-thick-3" x1="720" y1="0" x2="720" y2="1080" />
+ <line id="v-thick-4" x1="960" y1="0" x2="960" y2="1080" />
+ <line id="v-thick-5" x1="1200" y1="0" x2="1200" y2="1080" />
+ <line id="v-thick-6" x1="1440" y1="0" x2="1440" y2="1080" />
+ <line id="v-thick-7" x1="1680" y1="0" x2="1680" y2="1080" />
+ <line id="h-thick-1" x1="0" y1="240" x2="1920" y2="240" />
+ <line id="h-thick-2" x1="0" y1="480" x2="1920" y2="480" />
+ <line id="h-thick-3" x1="0" y1="720" x2="1920" y2="720" />
+ <line id="h-thick-4" x1="0" y1="960" x2="1920" y2="960" />
+ </g>
+
+ <g id="intersections" stroke="#0A1E3D" stroke-width="2" opacity="0.3">
+ <line x1="230" y1="240" x2="250" y2="240" />
+ <line x1="240" y1="230" x2="240" y2="250" />
+ <line x1="230" y1="480" x2="250" y2="480" />
+ <line x1="240" y1="470" x2="240" y2="490" />
+ <line x1="230" y1="720" x2="250" y2="720" />
+ <line x1="240" y1="710" x2="240" y2="730" />
+ <line x1="230" y1="960" x2="250" y2="960" />
+ <line x1="240" y1="950" x2="240" y2="970" />
+ <line x1="470" y1="240" x2="490" y2="240" />
+ <line x1="480" y1="230" x2="480" y2="250" />
+ <line x1="470" y1="480" x2="490" y2="480" />
+ <line x1="480" y1="470" x2="480" y2="490" />
+ <line x1="470" y1="720" x2="490" y2="720" />
+ <line x1="480" y1="710" x2="480" y2="730" />
+ <line x1="470" y1="960" x2="490" y2="960" />
+ <line x1="480" y1="950" x2="480" y2="970" />
+ <line x1="710" y1="240" x2="730" y2="240" />
+ <line x1="720" y1="230" x2="720" y2="250" />
+ <line x1="710" y1="480" x2="730" y2="480" />
+ <line x1="720" y1="470" x2="720" y2="490" />
+ <line x1="710" y1="720" x2="730" y2="720" />
+ <line x1="720" y1="710" x2="720" y2="730" />
+ <line x1="710" y1="960" x2="730" y2="960" />
+ <line x1="720" y1="950" x2="720" y2="970" />
+ <line x1="950" y1="240" x2="970" y2="240" />
+ <line x1="960" y1="230" x2="960" y2="250" />
+ <line x1="950" y1="480" x2="970" y2="480" />
+ <line x1="960" y1="470" x2="960" y2="490" />
+ <line x1="950" y1="720" x2="970" y2="720" />
+ <line x1="960" y1="710" x2="960" y2="730" />
+ <line x1="950" y1="960" x2="970" y2="960" />
+ <line x1="960" y1="950" x2="960" y2="970" />
+ <line x1="1190" y1="240" x2="1210" y2="240" />
+ <line x1="1200" y1="230" x2="1200" y2="250" />
+ <line x1="1190" y1="480" x2="1210" y2="480" />
+ <line x1="1200" y1="470" x2="1200" y2="490" />
+ <line x1="1190" y1="720" x2="1210" y2="720" />
+ <line x1="1200" y1="710" x2="1200" y2="730" />
+ <line x1="1190" y1="960" x2="1210" y2="960" />
+ <line x1="1200" y1="950" x2="1200" y2="970" />
+ <line x1="1430" y1="240" x2="1450" y2="240" />
+ <line x1="1440" y1="230" x2="1440" y2="250" />
+ <line x1="1430" y1="480" x2="1450" y2="480" />
+ <line x1="1440" y1="470" x2="1440" y2="490" />
+ <line x1="1430" y1="720" x2="1450" y2="720" />
+ <line x1="1440" y1="710" x2="1440" y2="730" />
+ <line x1="1430" y1="960" x2="1450" y2="960" />
+ <line x1="1440" y1="950" x2="1440" y2="970" />
+ <line x1="1670" y1="240" x2="1690" y2="240" />
+ <line x1="1680" y1="230" x2="1680" y2="250" />
+ <line x1="1670" y1="480" x2="1690" y2="480" />
+ <line x1="1680" y1="470" x2="1680" y2="490" />
+ <line x1="1670" y1="720" x2="1690" y2="720" />
+ <line x1="1680" y1="710" x2="1680" y2="730" />
+ <line x1="1670" y1="960" x2="1690" y2="960" />
+ <line x1="1680" y1="950" x2="1680" y2="970" />
+ </g>
+</svg>
\ No newline at end of file
diff --git a/packages/cli/src/templates/swiss-grid/compositions/captions.html b/packages/cli/src/templates/swiss-grid/compositions/captions.html
new file mode 100644
index 0000000000..f2594daf26
--- /dev/null
+++ b/packages/cli/src/templates/swiss-grid/compositions/captions.html
@@ -0,0 +1,95 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1920" data-height="1080" data-duration="16.04">
+ <div id="caption-container"></div>
+
+ <style>
+ [data-composition-id="captions"] {
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ font-family: 'Helvetica', 'Arial', sans-serif;
+ font-weight: bold;
+ overflow: hidden;
+ }
+
+ [data-composition-id="captions"] #caption-container {
+ position: absolute;
+ bottom: 120px; /* Consistent bottom positioning */
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ }
+
+ [data-composition-id="captions"] .caption-box {
+ background-color: #0A1E3D; /* Solid navy */
+ padding: 20px 40px;
+ display: none; /* Hidden by default, shown via GSAP */
+ justify-content: center;
+ align-items: center;
+ /* Swiss Grid: sharp corners, solid block */
+ }
+
+ [data-composition-id="captions"] .caption-text {
+ color: #F2F2F2; /* Off-white */
+ font-size: 72px;
+ text-transform: uppercase; /* Swiss style often uses uppercase for impact */
+ letter-spacing: -2px;
+ line-height: 1;
+ white-space: nowrap;
+ text-align: center;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.86, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics,', 'start': 3.579, 'end': 4.599}, {'text': 'sixty-two', 'start': 4.679, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.079, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.42}, {'text': 'look', 'start': 10.519, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.86}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Hyperframes', 'start': 15.079, 'end': 15.42}];
+ const container = document.getElementById('caption-container');
+ const tl = gsap.timeline({ paused: true });
+
+ if (!TRANSCRIPT || TRANSCRIPT.length === 0) {
+ window.__timelines["captions"] = tl;
+ return;
+ }
+
+ // Group transcript into max 5 words per group
+ const groups = [];
+ let currentGroup = [];
+
+ TRANSCRIPT.forEach((word, index) => {
+ currentGroup.push(word);
+ // Group by 5 words OR if it's the last word
+ if (currentGroup.length === 5 || index === TRANSCRIPT.length - 1) {
+ groups.push([...currentGroup]);
+ currentGroup = [];
+ }
+ });
+
+ // Create DOM elements and timeline for each group
+ groups.forEach((group, i) => {
+ const box = document.createElement('div');
+ box.className = 'caption-box';
+ box.id = `group-${i}`;
+
+ const text = document.createElement('div');
+ text.className = 'caption-text';
+ text.textContent = group.map(w => w.text).join(' ');
+
+ box.appendChild(text);
+ container.appendChild(box);
+
+ const startTime = group[0].start;
+ const endTime = group[group.length - 1].end;
+
+ // Hard cut animation (no fades) as requested
+ tl.set(box, { display: 'flex' }, startTime);
+ tl.set(box, { display: 'none' }, endTime);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/cli/src/templates/swiss-grid/compositions/graphics.html b/packages/cli/src/templates/swiss-grid/compositions/graphics.html
new file mode 100644
index 0000000000..64134a57a5
--- /dev/null
+++ b/packages/cli/src/templates/swiss-grid/compositions/graphics.html
@@ -0,0 +1,198 @@
+<template id="graphics-template">
+ <div data-composition-id="graphics" data-width="1920" data-height="1080" data-duration="15">
+ <div class="grid-container">
+ <!-- Stat 1: 47% -->
+ <div id="stat1" class="stat-group">
+ <div class="stat-value">47%</div>
+ <div class="stat-label">NEED MOTION GRAPHICS</div>
+ </div>
+
+ <!-- Stat 2: 62% -->
+ <div id="stat2" class="stat-group">
+ <div class="stat-value">62%</div>
+ <div class="stat-label">LOSING ATTENTION</div>
+ <div class="progress-container">
+ <div class="progress-bar"></div>
+ </div>
+ </div>
+
+ <!-- Stat 3: 3 OF 4 -->
+ <div id="stat3" class="stat-group">
+ <div class="stat-value">3 OF 4</div>
+ <div class="stat-label">LACK EDITING SKILLS</div>
+ <div class="grid-blocks">
+ <div class="block gold"></div>
+ <div class="block gold"></div>
+ <div class="block gold"></div>
+ <div class="block navy"></div>
+ </div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="graphics"] {
+ font-family: 'Helvetica', Arial, sans-serif;
+ color: #0A1E3D;
+ background: transparent;
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ overflow: hidden;
+ }
+
+ [data-composition-id="graphics"] .grid-container {
+ display: grid;
+ grid-template-columns: repeat(12, 1fr);
+ grid-template-rows: repeat(12, 1fr);
+ width: 100%;
+ height: 100%;
+ padding: 80px;
+ gap: 20px;
+ }
+
+ [data-composition-id="graphics"] .stat-group {
+ opacity: 0;
+ display: flex;
+ flex-direction: column;
+ justify-content: flex-start;
+ align-items: flex-start;
+ background: #F2F2F2;
+ padding: 40px;
+ border-left: 10px solid #D4A017;
+ box-shadow: 20px 20px 0px rgba(10, 30, 61, 0.1);
+ }
+
+ /* Positioning Stats on Grid - Adjusted for A-roll structure */
+ [data-composition-id="graphics"] #stat1 {
+ grid-column: 2 / 6;
+ grid-row: 3 / 7;
+ }
+
+ [data-composition-id="graphics"] #stat2 {
+ grid-column: 2 / 6;
+ grid-row: 3 / 7;
+ }
+
+ [data-composition-id="graphics"] #stat3 {
+ grid-column: 7 / 12;
+ grid-row: 3 / 7;
+ }
+
+ [data-composition-id="graphics"] .stat-value {
+ font-size: 140px;
+ font-weight: 900;
+ color: #D4A017;
+ line-height: 0.8;
+ margin-bottom: 15px;
+ }
+
+ [data-composition-id="graphics"] .stat-label {
+ font-size: 24px;
+ font-weight: 300; /* Lighter weight */
+ color: #0A1E3D;
+ letter-spacing: 2px;
+ text-transform: uppercase;
+ }
+
+ /* Progress Bar for Stat 2 */
+ [data-composition-id="graphics"] .progress-container {
+ width: 100%;
+ height: 24px;
+ background: #E0E0E0;
+ margin-top: 30px;
+ border: 2px solid #0A1E3D;
+ position: relative;
+ }
+
+ [data-composition-id="graphics"] .progress-bar {
+ width: 0%;
+ height: 100%;
+ background: #D4A017;
+ }
+
+ /* Grid Blocks for Stat 3 */
+ [data-composition-id="graphics"] .grid-blocks {
+ display: flex;
+ gap: 20px;
+ margin-top: 30px;
+ }
+
+ [data-composition-id="graphics"] .block {
+ width: 80px;
+ height: 80px;
+ border: 3px solid #0A1E3D;
+ }
+
+ [data-composition-id="graphics"] .block.gold {
+ background: #D4A017;
+ }
+
+ [data-composition-id="graphics"] .block.navy {
+ background: #0A1E3D;
+ }
+ </style>
+
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // Timing Constants
+ const S1_START = 1.86;
+ const S1_END = 4.5;
+ const S2_START = 4.68;
+ const S2_END = 8.6;
+ const S3_START = 8.88;
+ const S3_END = 14.2;
+
+ const SLIDE_DUR = 0.25; // 250ms
+ const SHARP_EASE = "power2.out";
+
+ // Stat 1 Animation
+ tl.fromTo('#stat1',
+ { x: -200, opacity: 0 },
+ { x: 0, opacity: 1, duration: SLIDE_DUR, ease: SHARP_EASE },
+ S1_START
+ );
+ tl.to('#stat1',
+ { x: 200, opacity: 0, duration: SLIDE_DUR, ease: "power2.in" },
+ S1_END - SLIDE_DUR
+ );
+
+ // Stat 2 Animation
+ tl.fromTo('#stat2',
+ { y: 200, opacity: 0 },
+ { y: 0, opacity: 1, duration: SLIDE_DUR, ease: SHARP_EASE },
+ S2_START
+ );
+ // Progress bar fill
+ tl.to('#stat2 .progress-bar',
+ { width: '62%', duration: S2_END - S2_START - (SLIDE_DUR * 2), ease: "none" },
+ S2_START + SLIDE_DUR
+ );
+ tl.to('#stat2',
+ { y: -200, opacity: 0, duration: SLIDE_DUR, ease: "power2.in" },
+ S2_END - SLIDE_DUR
+ );
+
+ // Stat 3 Animation
+ tl.fromTo('#stat3',
+ { x: 200, opacity: 0 },
+ { x: 0, opacity: 1, duration: SLIDE_DUR, ease: SHARP_EASE },
+ S3_START
+ );
+ // Stagger blocks
+ tl.from('#stat3 .block',
+ { scale: 0, duration: 0.3, stagger: 0.1, ease: "back.out(1.7)" },
+ S3_START + SLIDE_DUR
+ );
+ tl.to('#stat3',
+ { x: -200, opacity: 0, duration: SLIDE_DUR, ease: "power2.in" },
+ S3_END - SLIDE_DUR
+ );
+
+ window.__timelines["graphics"] = tl;
+ })();
+ </script>
+ </div>
+</template>
\ No newline at end of file
diff --git a/packages/cli/src/templates/swiss-grid/compositions/intro.html b/packages/cli/src/templates/swiss-grid/compositions/intro.html
new file mode 100644
index 0000000000..dd89ed6905
--- /dev/null
+++ b/packages/cli/src/templates/swiss-grid/compositions/intro.html
@@ -0,0 +1,114 @@
+<template id="intro-template">
+ <div data-composition-id="intro" data-width="1920" data-height="1080" data-duration="1.86">
+ <div class="container">
+ <div class="grid-line"></div>
+ <div class="text-wrapper">
+ <h1 class="title">HYPERFRAMES</h1>
+ <h2 class="subtitle">THE SURVEY FINDINGS</h2>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="intro"] {
+ background-color: #F5F5F5; /* Off-white */
+ width: 1920px;
+ height: 1080px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ overflow: hidden;
+ }
+
+ [data-composition-id="intro"] .container {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ padding-left: 160px; /* Swiss grid alignment */
+ }
+
+ [data-composition-id="intro"] .grid-line {
+ position: absolute;
+ left: 160px;
+ top: 50%;
+ width: 0px;
+ height: 12px;
+ background-color: #0A1E3D; /* Navy */
+ transform: translateY(-180px); /* Positioned above the text */
+ }
+
+ [data-composition-id="intro"] .text-wrapper {
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+ overflow: hidden;
+ }
+
+ [data-composition-id="intro"] .title {
+ color: #0A1E3D;
+ font-size: 180px;
+ font-weight: 900; /* Black weight */
+ line-height: 0.9;
+ margin: 0;
+ letter-spacing: -0.04em;
+ text-transform: uppercase;
+ transform: translateX(-100%); /* Start off-screen left */
+ }
+
+ [data-composition-id="intro"] .subtitle {
+ color: #0A1E3D;
+ font-size: 64px;
+ font-weight: 300; /* Lighter weight for contrast */
+ line-height: 1.2;
+ margin: 0;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ transform: translateX(-100%); /* Start off-screen left */
+ margin-top: 20px;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // Mechanical timing: 200ms (0.2s)
+ const MECHANICAL_DURATION = 0.2;
+ const STAGGER = 0.1;
+
+ // 1. Animate the grid line first
+ tl.to('.grid-line', {
+ width: '1200px',
+ duration: 0.4,
+ ease: 'power4.out'
+ }, 0.2);
+
+ // 2. Slide in the title
+ tl.to('.title', {
+ x: 0,
+ duration: MECHANICAL_DURATION,
+ ease: 'power2.inOut'
+ }, 0.5);
+
+ // 3. Slide in the subtitle with a slight stagger
+ tl.to('.subtitle', {
+ x: 0,
+ duration: MECHANICAL_DURATION,
+ ease: 'power2.inOut'
+ }, 0.5 + STAGGER);
+
+ // 4. Subtle ambient motion (slow drift) to keep it alive
+ tl.to('.text-wrapper', {
+ x: 30,
+ duration: 1.16, // Adjusted to fit 1.86s total
+ ease: 'none'
+ }, 0.7);
+
+ window.__timelines["intro"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/cli/src/templates/swiss-grid/index.html b/packages/cli/src/templates/swiss-grid/index.html
new file mode 100644
index 0000000000..10a0e3bd8d
--- /dev/null
+++ b/packages/cli/src/templates/swiss-grid/index.html
@@ -0,0 +1,172 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Swiss Grid - Hyperframes</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1920px;
+ height: 1080px;
+ background-color: #F2F2F2;
+ overflow: hidden;
+ font-family: 'Helvetica', Arial, sans-serif;
+ }
+
+ #master-root {
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ }
+
+ .background-grid {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 0;
+ }
+
+ /* A-roll styling */
+ #short_mag_cut_frame {
+ position: absolute;
+ border-radius: 8px; /* Required */
+ z-index: 1;
+ box-shadow: 0 20px 40px rgba(0,0,0,0.3);
+ overflow: hidden;
+ background: #000;
+ }
+
+ #short_mag_cut,
+ #short_mag_cut_frame > img.__render_frame__,
+ #short_mag_cut_frame > img.__preview_render_frame__ {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ object-position: center;
+ display: block;
+ }
+
+ /* Overlay layers */
+ .overlay-layer {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ }
+
+ #intro-comp { z-index: 2; }
+ #graphics-comp { z-index: 3; }
+ #captions-comp { z-index: 4; }
+ </style>
+</head>
+<body>
+ <div id="master-root" data-composition-id="master" data-width="1920" data-height="1080" data-duration="16.04">
+
+ <!-- Background Grid -->
+ <img id="bg-grid"
+ class="background-grid"
+ src="assets/swiss-grid.svg"
+ alt="Grid"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="0">
+
+ <!-- A-roll Video -->
+ <div id="short_mag_cut_frame">
+ <video id="short_mag_cut"
+ src="__VIDEO_SRC__"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="1">
+ </video>
+ </div>
+
+ <!-- Intro Sub-composition -->
+ <div id="intro-comp"
+ class="overlay-layer"
+ data-composition-id="intro"
+ data-composition-src="compositions/intro.html"
+ data-start="0"
+ data-duration="1.86"
+ data-track-index="2">
+ </div>
+
+ <!-- Graphics Sub-composition -->
+ <div id="graphics-comp"
+ class="overlay-layer"
+ data-composition-id="graphics"
+ data-composition-src="compositions/graphics.html"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="3">
+ </div>
+
+ <!-- Captions Sub-composition -->
+ <div id="captions-comp"
+ class="overlay-layer"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="4">
+ </div>
+
+ <!-- Sound Effects -->
+ <audio id="sfx-intro" data-start="0" data-track-index="5" data-duration="1" src=""></audio>
+ <audio id="sfx-stat1" data-start="1.86" data-track-index="5" data-duration="1" src=""></audio>
+ <audio id="sfx-stat2" data-start="4.68" data-track-index="5" data-duration="1" src=""></audio>
+ <audio id="sfx-stat3" data-start="8.88" data-track-index="5" data-duration="1" src=""></audio>
+
+ <script>
+ window.__timelines = window.__timelines || {};
+
+ const masterTL = gsap.timeline({ paused: true });
+ const v = document.getElementById('short_mag_cut_frame');
+
+ // --- A-ROLL MOVEMENT (Structured Swiss Layout) ---
+
+ // 1. Entrance (0-1.86s): Slide in from left, settle centered for Intro
+ masterTL.fromTo(v,
+ { x: -1000, y: 120, width: 960, height: 840 },
+ { x: 480, y: 120, width: 960, height: 840, duration: 0.8, ease: "power2.out" },
+ 0
+ );
+
+ // 2. Stat 1 (1.86s - 4.68s): Move to right side (Graphic is on left)
+ masterTL.to(v, {
+ x: 1080, y: 120, width: 720, height: 720,
+ duration: 0.25, ease: "expo.out"
+ }, 1.86);
+
+ // 3. Stat 2 (4.68s - 8.88s): Stay right, zoom in slightly
+ masterTL.to(v, {
+ x: 1080, y: 60, width: 780, height: 780,
+ duration: 0.25, ease: "expo.out"
+ }, 4.68);
+
+ // 4. Stat 3 (8.88s - 14.2s): Move to left side (Graphic is on right)
+ masterTL.to(v, {
+ x: 120, y: 120, width: 720, height: 720,
+ duration: 0.25, ease: "expo.out"
+ }, 8.88);
+
+ // 5. Conclusion (14.2s - 16.04s): Center large
+ masterTL.to(v, {
+ x: 240, y: 60, width: 1440, height: 810,
+ duration: 0.5, ease: "expo.out"
+ }, 14.2);
+
+ window.__timelines["master"] = masterTL;
+ </script>
+ </div>
+</body>
+</html>
diff --git a/packages/cli/src/templates/vignelli/compositions/captions.html b/packages/cli/src/templates/vignelli/compositions/captions.html
new file mode 100644
index 0000000000..6b3f62f312
--- /dev/null
+++ b/packages/cli/src/templates/vignelli/compositions/captions.html
@@ -0,0 +1,122 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1080" data-height="1920" data-duration="13.88">
+ <div id="captions-container"></div>
+
+ <style>
+ [data-composition-id="captions"] {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ font-family: "Helvetica", "Helvetica Neue", Arial, sans-serif;
+ font-weight: 900; /* Helvetica Black/Bold */
+ text-transform: uppercase;
+ pointer-events: none;
+ }
+
+ [data-composition-id="captions"] #captions-container {
+ position: absolute;
+ inset: 0;
+ }
+
+ [data-composition-id="captions"] .caption-group {
+ position: absolute;
+ left: 50%;
+ transform: translateX(-50%);
+ width: auto;
+ max-width: 920px; /* 1080 - 2*80 */
+ bottom: 672px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ text-align: center;
+ opacity: 0;
+ z-index: 10;
+ }
+
+ [data-composition-id="captions"] .caption-text {
+ font-size: 64px;
+ line-height: 1.1;
+ color: #000000;
+ background-color: #FFFFFF;
+ padding: 15px 30px;
+ border-top: 8px solid #CC0000; /* Vignelli Red top border accent */
+ display: inline-block;
+ letter-spacing: -0.02em; /* Tight Helvetica spacing */
+ white-space: nowrap; /* Prevent wrapping at the element level */
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.14, 'end': 0.239}, {'text': 'asked', 'start': 0.28, 'end': 0.459}, {'text': 'what', 'start': 0.5, 'end': 0.619}, {'text': 'you', 'start': 0.659, 'end': 0.779}, {'text': 'needed.', 'start': 0.8, 'end': 1.179}, {'text': 'Forty-seven', 'start': 1.199, 'end': 1.619}, {'text': 'percent', 'start': 1.699, 'end': 1.96}, {'text': 'of', 'start': 1.979, 'end': 2.059}, {'text': 'you', 'start': 2.099, 'end': 2.299}, {'text': 'said', 'start': 2.319, 'end': 2.499}, {'text': 'motion', 'start': 2.559, 'end': 2.839}, {'text': 'graphics,', 'start': 2.899, 'end': 3.759}, {'text': 'sixty-two', 'start': 3.799, 'end': 4.159}, {'text': 'percent', 'start': 4.239, 'end': 4.559}, {'text': 'said', 'start': 4.639, 'end': 4.799}, {'text': 'static', 'start': 4.859, 'end': 5.199}, {'text': 'content', 'start': 5.239, 'end': 5.639}, {'text': 'was', 'start': 5.679, 'end': 5.779}, {'text': 'costing', 'start': 5.859, 'end': 6.219}, {'text': 'you', 'start': 6.259, 'end': 6.339}, {'text': 'attention,', 'start': 6.379, 'end': 7.299}, {'text': 'and', 'start': 7.319, 'end': 7.439}, {'text': 'three', 'start': 7.48, 'end': 7.599}, {'text': 'out', 'start': 7.679, 'end': 7.779}, {'text': 'of', 'start': 7.799, 'end': 7.879}, {'text': 'four', 'start': 7.94, 'end': 8.139}, {'text': 'said', 'start': 8.279, 'end': 8.46}, {'text': 'you', 'start': 8.519, 'end': 8.6}, {'text': 'know', 'start': 8.619, 'end': 8.739}, {'text': 'the', 'start': 8.8, 'end': 8.88}, {'text': 'look', 'start': 8.92, 'end': 9.079}, {'text': 'you', 'start': 9.119, 'end': 9.259}, {'text': 'want', 'start': 9.279, 'end': 9.619}, {'text': 'but', 'start': 9.779, 'end': 9.88}, {'text': "don't", 'start': 9.92, 'end': 10.1}, {'text': 'have', 'start': 10.159, 'end': 10.3}, {'text': 'the', 'start': 10.3, 'end': 10.42}, {'text': 'editing', 'start': 10.5, 'end': 10.779}, {'text': 'skills', 'start': 10.86, 'end': 11.139}, {'text': 'to', 'start': 11.159, 'end': 11.239}, {'text': 'get', 'start': 11.279, 'end': 11.439}, {'text': 'there.', 'start': 11.46, 'end': 12.239}, {'text': 'So', 'start': 12.3, 'end': 12.38}, {'text': 'we', 'start': 12.399, 'end': 12.519}, {'text': 'built', 'start': 12.539, 'end': 12.759}, {'text': 'Hyperframes', 'start': 12.84, 'end': 13.119}];
+ const tl = gsap.timeline({ paused: true });
+ const container = document.getElementById('captions-container');
+
+ // Group words into single lines (max words or based on pauses/sentence ends)
+ function groupTranscript(transcript, maxWords = 3) {
+ const groups = [];
+ let currentGroup = [];
+
+ transcript.forEach((word, index) => {
+ currentGroup.push(word);
+
+ const nextWord = transcript[index + 1];
+ const isPause = nextWord && (nextWord.start - word.end > 0.15);
+ const isSentenceEnd = word.text.includes('.') || word.text.includes('?') || word.text.includes('!');
+
+ if (currentGroup.length >= maxWords || isPause || isSentenceEnd || !nextWord) {
+ groups.push({
+ words: currentGroup,
+ start: currentGroup[0].start,
+ end: currentGroup[currentGroup.length - 1].end,
+ text: currentGroup.map(w => w.text).join(' ')
+ });
+ currentGroup = [];
+ }
+ });
+ return groups;
+ }
+
+ const captionGroups = groupTranscript(TRANSCRIPT);
+
+ captionGroups.forEach((group, index) => {
+ const div = document.createElement('div');
+ div.className = 'caption-group';
+ div.id = `group-${index}`;
+
+ const textSpan = document.createElement('span');
+ textSpan.className = 'caption-text';
+ textSpan.innerText = group.text;
+
+ div.appendChild(textSpan);
+ container.appendChild(div);
+
+ // Animation: Modern "expo.out" transitions
+ // Entrance
+ tl.fromTo(div,
+ { opacity: 0, y: 20 },
+ {
+ opacity: 1,
+ y: 0,
+ duration: 0.4,
+ ease: "expo.out"
+ },
+ group.start
+ );
+
+ // Exit
+ tl.to(div, {
+ opacity: 0,
+ y: -10,
+ duration: 0.3,
+ ease: "expo.out"
+ }, group.end - 0.3);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/cli/src/templates/vignelli/compositions/overlays.html b/packages/cli/src/templates/vignelli/compositions/overlays.html
new file mode 100644
index 0000000000..e2a13c7b1b
--- /dev/null
+++ b/packages/cli/src/templates/vignelli/compositions/overlays.html
@@ -0,0 +1,271 @@
+<template id="overlays-template">
+ <div data-composition-id="overlays" data-width="1080" data-height="1920" data-duration="16.88">
+ <!-- 6-Column Grid Overlay (for visual reference during development, hidden by default) -->
+ <div class="vignelli-grid">
+ <div class="col"></div>
+ <div class="col"></div>
+ <div class="col"></div>
+ <div class="col"></div>
+ <div class="col"></div>
+ <div class="col"></div>
+ </div>
+
+ <!-- 1. 47% Motion Graphics -->
+ <div class="overlay-item motion-graphics-stat" id="stat-47">
+ <div class="red-bar"></div>
+ <div class="stat-content">
+ <div class="number">47%</div>
+ <div class="label">Motion Graphics</div>
+ </div>
+ </div>
+
+ <!-- 2. 62% Static Content (Full Canvas) -->
+ <div class="overlay-item static-content-stat" id="stat-62">
+ <div class="bg-charcoal"></div>
+ <div class="full-content">
+ <div class="large-number">62%</div>
+ <div class="large-label">Static Content</div>
+ <div class="red-accent"></div>
+ </div>
+ </div>
+
+ <!-- 3. 3 out of 4 lack editing skills -->
+ <div class="overlay-item editing-skills-stat" id="stat-3-4">
+ <div class="text-block">
+ <span class="highlight">3 out of 4</span>
+ <br>lack editing skills
+ </div>
+ <div class="side-bar"></div>
+ </div>
+
+ <!-- 4. Hyperframes Branding -->
+ <div class="overlay-item branding-reveal" id="branding">
+ <div class="logo-container">
+ <div class="logo-text"><span class="heavy">HYPERFRAMES</span></div>
+ <div class="logo-underline"></div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="overlays"] {
+ position: relative;
+ width: 1080px;
+ height: 1920px;
+ font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ color: #000000;
+ overflow: hidden;
+ pointer-events: none;
+ }
+
+ /* Grid System */
+ [data-composition-id="overlays"] .vignelli-grid {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ display: grid;
+ grid-template-columns: repeat(6, 1fr);
+ pointer-events: none;
+ z-index: 100;
+ opacity: 0; /* Hidden */
+ }
+ [data-composition-id="overlays"] .vignelli-grid .col {
+ border-right: 1px solid rgba(204, 0, 0, 0.1);
+ }
+
+ [data-composition-id="overlays"] .overlay-item {
+ position: absolute;
+ opacity: 0;
+ display: flex;
+ z-index: 10;
+ }
+
+ /* 1. 47% Stat Styles */
+ [data-composition-id="overlays"] #stat-47 {
+ bottom: 200px;
+ left: 0;
+ width: 540px; /* 3 columns */
+ height: 240px;
+ background: #FFFFFF;
+ flex-direction: row;
+ align-items: stretch;
+ }
+ [data-composition-id="overlays"] #stat-47 .red-bar {
+ width: 20px;
+ background: #CC0000;
+ }
+ [data-composition-id="overlays"] #stat-47 .stat-content {
+ padding: 40px;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ }
+ [data-composition-id="overlays"] #stat-47 .number {
+ font-size: 120px;
+ font-weight: 900;
+ line-height: 1;
+ letter-spacing: -2px;
+ }
+ [data-composition-id="overlays"] #stat-47 .label {
+ font-size: 32px;
+ font-weight: 700;
+ text-transform: uppercase;
+ margin-top: 10px;
+ }
+
+ /* 2. 62% Stat Styles (Full Canvas) */
+ [data-composition-id="overlays"] #stat-62 {
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ z-index: 50;
+ }
+ [data-composition-id="overlays"] #stat-62 .bg-charcoal {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: #1A1A1A;
+ }
+ [data-composition-id="overlays"] #stat-62 .full-content {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ padding: 0 90px; /* Align with grid */
+ }
+ [data-composition-id="overlays"] #stat-62 .large-number {
+ font-size: 400px;
+ font-weight: 900;
+ color: #FFFFFF;
+ line-height: 0.8;
+ letter-spacing: -10px;
+ }
+ [data-composition-id="overlays"] #stat-62 .large-label {
+ font-size: 80px;
+ font-weight: 700;
+ color: #FFFFFF;
+ text-transform: uppercase;
+ margin-top: 20px;
+ max-width: 600px;
+ }
+ [data-composition-id="overlays"] #stat-62 .red-accent {
+ position: absolute;
+ top: 0;
+ right: 0;
+ width: 180px; /* 1 column */
+ height: 100%;
+ background: #CC0000;
+ }
+
+ /* 3. 3 out of 4 Stat Styles */
+ [data-composition-id="overlays"] #stat-3-4 {
+ top: 400px;
+ right: 0;
+ width: 360px; /* 2 columns */
+ background: #FFFFFF;
+ padding: 40px;
+ flex-direction: row-reverse;
+ }
+ [data-composition-id="overlays"] #stat-3-4 .text-block {
+ font-size: 48px;
+ font-weight: 700;
+ line-height: 1.1;
+ text-align: right;
+ }
+ [data-composition-id="overlays"] #stat-3-4 .highlight {
+ color: #CC0000;
+ font-size: 64px;
+ font-weight: 900;
+ }
+ [data-composition-id="overlays"] #stat-3-4 .side-bar {
+ width: 10px;
+ background: #000000;
+ margin-left: 20px;
+ }
+
+ /* 4. Branding Styles */
+ [data-composition-id="overlays"] #branding {
+ bottom: 100px;
+ left: 90px;
+ width: 900px;
+ justify-content: center;
+ z-index: 60;
+ }
+ [data-composition-id="overlays"] #branding .logo-container {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ }
+ [data-composition-id="overlays"] #branding .logo-text {
+ font-size: 64px;
+ letter-spacing: 10px;
+ color: #000000;
+ }
+ [data-composition-id="overlays"] #branding .logo-text .heavy {
+ font-weight: 900;
+ }
+ [data-composition-id="overlays"] #branding .logo-text .light {
+ font-weight: 300;
+ }
+ [data-composition-id="overlays"] #branding .logo-underline {
+ width: 100%;
+ height: 8px;
+ background: #CC0000;
+ margin-top: 10px;
+ transform-origin: left;
+ }
+ </style>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.14, 'end': 0.239}, {'text': 'asked', 'start': 0.28, 'end': 0.459}, {'text': 'what', 'start': 0.5, 'end': 0.619}, {'text': 'you', 'start': 0.659, 'end': 0.779}, {'text': 'needed.', 'start': 0.8, 'end': 1.179}, {'text': 'Forty-seven', 'start': 1.199, 'end': 1.619}, {'text': 'percent', 'start': 1.699, 'end': 1.96}, {'text': 'of', 'start': 1.979, 'end': 2.059}, {'text': 'you', 'start': 2.099, 'end': 2.299}, {'text': 'said', 'start': 2.319, 'end': 2.499}, {'text': 'motion', 'start': 2.559, 'end': 2.839}, {'text': 'graphics,', 'start': 2.899, 'end': 3.759}, {'text': 'sixty-two', 'start': 3.799, 'end': 4.159}, {'text': 'percent', 'start': 4.239, 'end': 4.559}, {'text': 'said', 'start': 4.639, 'end': 4.799}, {'text': 'static', 'start': 4.859, 'end': 5.199}, {'text': 'content', 'start': 5.239, 'end': 5.639}, {'text': 'was', 'start': 5.679, 'end': 5.779}, {'text': 'costing', 'start': 5.859, 'end': 6.219}, {'text': 'you', 'start': 6.259, 'end': 6.339}, {'text': 'attention,', 'start': 6.379, 'end': 7.299}, {'text': 'and', 'start': 7.319, 'end': 7.439}, {'text': 'three', 'start': 7.48, 'end': 7.599}, {'text': 'out', 'start': 7.679, 'end': 7.779}, {'text': 'of', 'start': 7.799, 'end': 7.879}, {'text': 'four', 'start': 7.94, 'end': 8.139}, {'text': 'said', 'start': 8.279, 'end': 8.46}, {'text': 'you', 'start': 8.519, 'end': 8.6}, {'text': 'know', 'start': 8.619, 'end': 8.739}, {'text': 'the', 'start': 8.8, 'end': 8.88}, {'text': 'look', 'start': 8.92, 'end': 9.079}, {'text': 'you', 'start': 9.119, 'end': 9.259}, {'text': 'want', 'start': 9.279, 'end': 9.619}, {'text': 'but', 'start': 9.779, 'end': 9.88}, {'text': "don't", 'start': 9.92, 'end': 10.1}, {'text': 'have', 'start': 10.159, 'end': 10.3}, {'text': 'the', 'start': 10.3, 'end': 10.42}, {'text': 'editing', 'start': 10.5, 'end': 10.779}, {'text': 'skills', 'start': 10.86, 'end': 11.139}, {'text': 'to', 'start': 11.159, 'end': 11.239}, {'text': 'get', 'start': 11.279, 'end': 11.439}, {'text': 'there.', 'start': 11.46, 'end': 12.239}, {'text': 'So', 'start': 12.3, 'end': 12.38}, {'text': 'we', 'start': 12.399, 'end': 12.519}, {'text': 'built', 'start': 12.539, 'end': 12.759}, {'text': 'Hyperframes', 'start': 12.84, 'end': 13.119}];
+
+ // Requirement 1: "47% Motion Graphics" (Start: 1.199, End: 3.759)
+ // Positioned in bottom half, columns 1-3.
+ tl.fromTo("#stat-47",
+ { x: -540, opacity: 1 },
+ { x: 0, duration: 0.8, ease: "expo.out" },
+ 1.199
+ );
+ tl.to("#stat-47",
+ { x: -540, duration: 0.6, ease: "expo.in" },
+ 3.759 - 0.6
+ );
+
+ // Requirement 2: "62% Static Content" (Start: 3.799, End: 7.299)
+ // Full canvas moment. Large bold typography across columns.
+ tl.set("#stat-62", { opacity: 1 }, 3.799);
+ tl.from("#stat-62 .bg-charcoal", { x: "100%", duration: 0.8, ease: "expo.out" }, 3.799);
+ tl.from("#stat-62 .red-accent", { x: "100%", duration: 0.8, ease: "expo.out" }, 3.899);
+ tl.from("#stat-62 .large-number", { y: 100, opacity: 0, duration: 1, ease: "expo.out" }, 4.099);
+ tl.from("#stat-62 .large-label", { y: 50, opacity: 0, duration: 1, ease: "expo.out" }, 4.299);
+
+ tl.to("#stat-62", { x: "-100%", duration: 0.8, ease: "expo.in" }, 7.299 - 0.8);
+
+ // Requirement 3: "3 out of 4 lack editing skills" (Start: 7.319, End: 12.239)
+ // Positioned in columns 5-6 (right side) to avoid face (x: 300-776)
+ tl.fromTo("#stat-3-4",
+ { x: 360, opacity: 1 },
+ { x: 0, duration: 0.8, ease: "expo.out" },
+ 7.319
+ );
+ tl.to("#stat-3-4",
+ { x: 360, duration: 0.6, ease: "expo.in" },
+ 12.239 - 0.6
+ );
+
+ // Requirement 4: "Hyperframes" (Start: 12.84, End: 13.84)
+ tl.set("#branding", { opacity: 1 }, 12.84);
+ tl.from("#branding .logo-text", { y: 20, opacity: 0, duration: 0.6, ease: "expo.out" }, 12.84);
+ tl.from("#branding .logo-underline", { scaleX: 0, duration: 0.8, ease: "expo.out" }, 13.04);
+
+ window.__timelines["overlays"] = tl;
+ </script>
+ </div>
+</template>
diff --git a/packages/cli/src/templates/vignelli/index.html b/packages/cli/src/templates/vignelli/index.html
new file mode 100644
index 0000000000..f37079ff2f
--- /dev/null
+++ b/packages/cli/src/templates/vignelli/index.html
@@ -0,0 +1,171 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <title>Massimo Vignelli Video</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body,
+ html {
+ margin: 0;
+ padding: 0;
+ background: #FFFFFF;
+ overflow: hidden;
+ width: 1080px;
+ height: 1920px;
+ font-family: 'Helvetica', Arial, sans-serif;
+ }
+
+ /* 6-Column Grid System */
+ .grid-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ display: grid;
+ grid-template-columns: repeat(6, 1fr);
+ pointer-events: none;
+ z-index: 1000;
+ opacity: 0; /* Keep grid invisible but present for layout references */
+ }
+
+ .grid-column {
+ border-right: 1px solid rgba(204, 0, 0, 0.2); /* Vignelli Red accent */
+ }
+
+ #main-composition {
+ position: relative;
+ width: 1080px;
+ height: 1920px;
+ background: #FFFFFF;
+ overflow: hidden;
+ }
+
+ /* Layer Hosts */
+ #a-roll-wrapper {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 10;
+ overflow: hidden;
+ }
+
+ #a-roll,
+ #a-roll-wrapper img.__render_frame__,
+ #a-roll-wrapper img.__preview_render_frame__ {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+
+ #overlays-comp,
+ #captions-comp {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ pointer-events: none;
+ }
+
+ #overlays-comp {
+ z-index: 20;
+ }
+
+ #captions-comp {
+ z-index: 30;
+ }
+
+ /* Curtain Transition Layer */
+ .curtain {
+ position: absolute;
+ top: 0;
+ left: -100%;
+ width: 100%;
+ height: 100%;
+ background: #1A1A1A;
+ z-index: 25;
+ pointer-events: none;
+ }
+
+ .curtain.red {
+ background: #CC0000;
+ z-index: 26;
+ }
+
+ </style>
+</head>
+<body>
+ <div id="main-composition" data-composition-id="main-comp" data-width="1080" data-height="1920" data-duration="13.88">
+
+ <!-- A-Roll -->
+ <div id="a-roll-wrapper">
+ <video id="a-roll"
+ src="__VIDEO_SRC__"
+ data-start="0"
+ data-duration="13.88"
+ data-track-index="0">
+ </video>
+ </div>
+
+ <!-- Transitions -->
+ <div id="curtain-black" class="curtain"></div>
+ <div id="curtain-red" class="curtain red"></div>
+
+ <!-- Overlays Composition -->
+ <div id="overlays-comp"
+ data-composition-id="overlays"
+ data-composition-src="compositions/overlays.html"
+ data-start="0"
+ data-duration="13.88"
+ data-track-index="2">
+ </div>
+
+ <!-- Captions Composition -->
+ <div id="captions-comp"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="13.88"
+ data-track-index="3">
+ </div>
+
+ <!-- Grid Visualization -->
+ <div class="grid-container">
+ <div class="grid-column"></div>
+ <div class="grid-column"></div>
+ <div class="grid-column"></div>
+ <div class="grid-column"></div>
+ <div class="grid-column"></div>
+ <div class="grid-column"></div>
+ </div>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+
+ // Transition: Curtain Pull logic
+ // A-roll leaves the screen at least once.
+ // Timing: Let's do a curtain pull at 3.7s (transitioning to the 62% stat)
+ // and return at 7.3s (end of attention stat).
+
+ // Curtain Out (A-roll hidden)
+ tl.to("#curtain-black", { left: "0%", duration: 0.2, ease: "power2.inOut" }, 3.5);
+ tl.to("#a-roll-wrapper", { opacity: 0, duration: 0 }, 3.7);
+ tl.to("#curtain-black", { left: "100%", duration: 0.4, ease: "power2.inOut" }, 3.7);
+
+ // Curtain In (A-roll return)
+ tl.set("#curtain-red", { left: "-100%" }, 7.1);
+ tl.to("#curtain-red", { left: "0%", duration: 0.2, ease: "power2.inOut" }, 7.1);
+ tl.to("#a-roll-wrapper", { opacity: 1, duration: 0 }, 7.3);
+ tl.to("#curtain-red", { left: "100%", duration: 0.4, ease: "power2.inOut" }, 7.3);
+
+ window.__timelines["main-comp"] = tl;
+ </script>
+ </div>
+</body>
+</html>
diff --git a/packages/cli/src/templates/warm-grain/compositions/captions.html b/packages/cli/src/templates/warm-grain/compositions/captions.html
new file mode 100644
index 0000000000..522e8d053e
--- /dev/null
+++ b/packages/cli/src/templates/warm-grain/compositions/captions.html
@@ -0,0 +1,133 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1920" data-height="1080" data-duration="18">
+ <div class="captions-container">
+ <div id="caption-box" class="caption-box">
+ <span id="caption-text" class="caption-text"></span>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="captions"] .captions-container {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: flex-end;
+ padding-bottom: 230px; /* Position at y: 850 (1080 - 230 = 850) */
+ pointer-events: none;
+ }
+
+ [data-composition-id="captions"] .caption-box {
+ background-color: #7A6248;
+ padding: 12px 32px;
+ border-radius: 24px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ min-width: 100px;
+ max-width: 80%;
+ opacity: 0;
+ box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
+ }
+
+ [data-composition-id="captions"] .caption-text {
+ color: #F5F0E0;
+ font-family: 'Outfit', sans-serif;
+ font-size: 48px;
+ font-weight: 700;
+ text-align: center;
+ line-height: 1.2;
+ white-space: nowrap;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const script = [
+ {"text": "We", "start": 0.119, "end": 0.259},
+ {"text": "asked", "start": 0.319, "end": 0.479},
+ {"text": "what", "start": 0.519, "end": 0.659},
+ {"text": "you", "start": 0.699, "end": 0.819},
+ {"text": "needed.", "start": 0.859, "end": 1.819},
+ {"text": "Forty-seven", "start": 1.86, "end": 2.299},
+ {"text": "percent", "start": 2.399, "end": 2.679},
+ {"text": "of", "start": 2.7, "end": 2.799},
+ {"text": "you", "start": 2.839, "end": 2.939},
+ {"text": "said", "start": 3.039, "end": 3.179},
+ {"text": "motion", "start": 3.24, "end": 3.559},
+ {"text": "graphics,", "start": 3.579, "end": 4.599},
+ {"text": "sixty-two", "start": 4.679, "end": 5.179},
+ {"text": "percent", "start": 5.299, "end": 5.759},
+ {"text": "said", "start": 5.859, "end": 5.98},
+ {"text": "static", "start": 6.079, "end": 6.399},
+ {"text": "content", "start": 6.46, "end": 6.879},
+ {"text": "was", "start": 6.92, "end": 7.079},
+ {"text": "costing", "start": 7.099, "end": 7.48},
+ {"text": "you", "start": 7.5, "end": 7.579},
+ {"text": "attention,", "start": 7.679, "end": 8.659},
+ {"text": "and", "start": 8.699, "end": 8.86},
+ {"text": "three", "start": 8.88, "end": 9.06},
+ {"text": "out", "start": 9.079, "end": 9.18},
+ {"text": "of", "start": 9.199, "end": 9.34},
+ {"text": "four", "start": 9.38, "end": 9.799},
+ {"text": "said", "start": 9.84, "end": 10.0},
+ {"text": "you", "start": 10.019, "end": 10.159},
+ {"text": "know", "start": 10.179, "end": 10.36},
+ {"text": "the", "start": 10.38, "end": 10.42},
+ {"text": "look", "start": 10.519, "end": 10.699},
+ {"text": "you", "start": 10.739, "end": 10.859},
+ {"text": "want", "start": 10.98, "end": 11.34},
+ {"text": "but", "start": 11.359, "end": 11.52},
+ {"text": "don't", "start": 11.56, "end": 11.779},
+ {"text": "have", "start": 11.819, "end": 11.94},
+ {"text": "the", "start": 11.96, "end": 12.06},
+ {"text": "editing", "start": 12.079, "end": 12.4},
+ {"text": "skills", "start": 12.52, "end": 12.86},
+ {"text": "to", "start": 12.88, "end": 13.0},
+ {"text": "get", "start": 13.019, "end": 13.18},
+ {"text": "there.", "start": 13.22, "end": 14.22},
+ {"text": "So", "start": 14.239, "end": 14.399},
+ {"text": "we", "start": 14.42, "end": 14.52},
+ {"text": "built", "start": 14.619, "end": 14.88},
+ {"text": "Hyperframes.", "start": 15.079, "end": 16.02}
+ ];
+
+ // Group words into lines (max 5 words per line)
+ const lines = [];
+ for (let i = 0; i < script.length; i += 5) {
+ const lineWords = script.slice(i, i + 5);
+ lines.push({
+ text: lineWords.map(w => w.text).join(' '),
+ start: lineWords[0].start,
+ end: lineWords[lineWords.length - 1].end
+ });
+ }
+
+ const tl = gsap.timeline({ paused: true });
+ const box = document.querySelector('[data-composition-id="captions"] #caption-box');
+ const textEl = document.querySelector('[data-composition-id="captions"] #caption-text');
+
+ lines.forEach((line, index) => {
+ // Fade in and set text
+ tl.to(box, {
+ opacity: 1,
+ duration: 0.1,
+ ease: "power2.out",
+ onStart: () => {
+ textEl.textContent = line.text;
+ }
+ }, line.start);
+
+ // Fade out at the end of the line
+ tl.to(box, {
+ opacity: 0,
+ duration: 0.1,
+ ease: "power2.in"
+ }, line.end);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/cli/src/templates/warm-grain/compositions/graphics.html b/packages/cli/src/templates/warm-grain/compositions/graphics.html
new file mode 100644
index 0000000000..e684da13de
--- /dev/null
+++ b/packages/cli/src/templates/warm-grain/compositions/graphics.html
@@ -0,0 +1,157 @@
+<template id="graphics-template">
+ <div data-composition-id="graphics" data-width="1920" data-height="1080" data-duration="14">
+ <!-- Moment 1: 47% Stat (1.8s - 4.5s) -->
+ <div id="moment-1" class="moment circle-stat">
+ <div class="stat-content">
+ <div class="stat-text">47%</div>
+ <div class="stat-desc">Need Motion Graphics</div>
+ </div>
+ </div>
+
+ <!-- Moment 2: 62% Stat (4.6s - 8.6s) -->
+ <div id="moment-2" class="moment pill-stat">
+ <div class="stat-text">62%</div>
+ </div>
+
+ <!-- Moment 3: Editing Skills (8.8s - 14s) -->
+ <div id="moment-3" class="moment rect-stat">
+ <div class="icon-shape">
+ <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
+ <path d="M20,20 Q50,0 80,20 Q100,50 80,80 Q50,100 20,80 Q0,50 20,20" fill="currentColor" />
+ </svg>
+ </div>
+ <div class="stat-text">Editing Skills</div>
+ </div>
+
+ <style>
+ [data-composition-id="graphics"] {
+ position: relative;
+ width: 1920px;
+ height: 1080px;
+ font-family: 'Outfit', sans-serif;
+ color: white;
+ overflow: hidden;
+ }
+
+ [data-composition-id="graphics"] .moment {
+ position: absolute;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0;
+ /* We'll use GSAP to handle the centering and drift */
+ }
+
+ /* Moment 1: Forest Green Circle */
+ [data-composition-id="graphics"] #moment-1 {
+ width: 500px;
+ height: 500px;
+ background-color: #3B5E3A;
+ border-radius: 50%;
+ left: 1400px;
+ top: 540px;
+ transform: translate(-50%, -50%);
+ }
+
+ [data-composition-id="graphics"] .stat-content {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ text-align: center;
+ }
+
+ [data-composition-id="graphics"] .stat-desc {
+ font-size: 36px;
+ font-weight: 400;
+ margin-top: 10px;
+ max-width: 300px;
+ line-height: 1.2;
+ }
+
+ /* Moment 2: Ochre Pill */
+ [data-composition-id="graphics"] #moment-2 {
+ width: 500px;
+ height: 220px;
+ background-color: #CC8832;
+ border-radius: 110px;
+ left: 960px;
+ top: 200px;
+ transform: translate(-50%, -50%);
+ }
+
+ /* Moment 3: Terracotta Rounded Rect */
+ [data-composition-id="graphics"] #moment-3 {
+ width: 550px;
+ height: 180px;
+ background-color: #C45D3E;
+ border-radius: 40px;
+ left: 400px;
+ top: 540px;
+ transform: translate(-50%, -50%);
+ padding: 0 40px;
+ justify-content: center;
+ gap: 30px;
+ }
+
+ [data-composition-id="graphics"] .stat-text {
+ font-size: 80px;
+ font-weight: 700;
+ letter-spacing: -2px;
+ }
+
+ [data-composition-id="graphics"] #moment-3 .stat-text {
+ font-size: 54px;
+ letter-spacing: -1px;
+ }
+
+ [data-composition-id="graphics"] .icon-shape {
+ width: 80px;
+ height: 80px;
+ color: rgba(255, 255, 255, 0.9);
+ }
+
+ [data-composition-id="graphics"] .icon-shape svg {
+ width: 100%;
+ height: 100%;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // Moment 1: 1.8s - 4.5s
+ // Gentle drift into place and settle
+ tl.fromTo('#moment-1',
+ { opacity: 0, x: '+=40', y: '+=15', scale: 0.8 },
+ { opacity: 1, x: 0, y: 0, scale: 1, duration: 1.2, ease: 'back.out(1.7)' },
+ 1.8
+ );
+ // Hold until 4.5s, then fade out
+ tl.to('#moment-1', { opacity: 0, scale: 0.8, duration: 0.3, ease: 'power2.in' }, 4.2);
+
+ // Moment 2: 4.6s - 8.6s
+ // Gentle drift into place and settle
+ tl.fromTo('#moment-2',
+ { opacity: 0, y: '-=40', x: '+=10', scale: 0.8 },
+ { opacity: 1, y: 0, x: 0, scale: 1, duration: 1.2, ease: 'back.out(1.7)' },
+ 4.6
+ );
+ // Hold until 8.6s, then fade out
+ tl.to('#moment-2', { opacity: 0, scale: 0.8, duration: 0.3, ease: 'power2.in' }, 8.3);
+
+ // Moment 3: 8.8s - 14s
+ // Gentle drift into place and settle
+ tl.fromTo('#moment-3',
+ { opacity: 0, x: '-=40', y: '-=10', scale: 0.8 },
+ { opacity: 1, x: 0, y: 0, scale: 1, duration: 1.2, ease: 'back.out(1.7)' },
+ 8.8
+ );
+ // Hold until end (14s)
+ tl.to('#moment-3', { opacity: 0, duration: 0.5, ease: 'power2.in' }, 13.5);
+
+ window.__timelines["graphics"] = tl;
+ })();
+ </script>
+ </div>
+</template>
\ No newline at end of file
diff --git a/packages/cli/src/templates/warm-grain/compositions/intro.html b/packages/cli/src/templates/warm-grain/compositions/intro.html
new file mode 100644
index 0000000000..dd1f549e82
--- /dev/null
+++ b/packages/cli/src/templates/warm-grain/compositions/intro.html
@@ -0,0 +1,77 @@
+<template id="intro-template">
+ <div data-composition-id="intro" data-width="1920" data-height="1080" data-duration="3">
+ <div class="container">
+ <div class="title-card">
+ <h1 class="title">Hyperframes</h1>
+ <p class="subtitle">Design simplified.</p>
+ </div>
+ </div>
+
+ <style>
+ /* Import a rounded humanist sans-serif font */
+ @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;600&display=swap');
+
+ [data-composition-id="intro"] .container {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: flex-start; /* Align to left for speaker card */
+ align-items: center;
+ padding-left: 5%;
+ font-family: 'Outfit', sans-serif;
+ background: transparent;
+ }
+
+ [data-composition-id="intro"] .title-card {
+ background-color: #3B5E3A; /* Forest Green for contrast */
+ padding: 40px 60px;
+ border-radius: 30px;
+ box-shadow: 0 15px 40px rgba(0,0,0,0.2);
+ text-align: left;
+ opacity: 0;
+ transform: translateX(-100%); /* Start off-screen left */
+ }
+
+ [data-composition-id="intro"] .title {
+ font-size: 100px;
+ font-weight: 600;
+ color: #F5F0E0; /* Cream text on green card */
+ margin: 0;
+ line-height: 1.1;
+ letter-spacing: -2px;
+ }
+
+ [data-composition-id="intro"] .subtitle {
+ font-size: 50px;
+ font-weight: 400;
+ color: #CC8832; /* Ochre accent */
+ margin: 10px 0 0 0;
+ line-height: 1.2;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // Animation: Speaker card slides in from the left
+ tl.to('[data-composition-id="intro"] .title-card', {
+ opacity: 1,
+ x: 0,
+ duration: 0.8,
+ ease: 'power2.out'
+ }, 0.2);
+
+ // Exit: Slide off left at 1.8s (synced with 47% graphic)
+ tl.to('[data-composition-id="intro"] .title-card', {
+ x: '-120%',
+ opacity: 0,
+ duration: 0.6,
+ ease: 'power2.in'
+ }, 1.8);
+
+ window.__timelines["intro"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/cli/src/templates/warm-grain/index.html b/packages/cli/src/templates/warm-grain/index.html
new file mode 100644
index 0000000000..93e29020d7
--- /dev/null
+++ b/packages/cli/src/templates/warm-grain/index.html
@@ -0,0 +1,195 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Warm Grain - Hyperframes</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1920px;
+ height: 1080px;
+ overflow: hidden;
+ background-color: #F5F0E0; /* Cream background */
+ font-family: 'Outfit', 'Lexend', sans-serif;
+ }
+
+ #main-composition {
+ position: relative;
+ width: 1920px;
+ height: 1080px;
+ overflow: hidden;
+ }
+
+ /* Paper texture and Grain overlay */
+ #grain-overlay-comp {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ z-index: 100;
+ }
+
+ /* Grain animation */
+ @keyframes grain-noise {
+ 0%, 100% { transform: translate(0, 0); }
+ 10% { transform: translate(-5%, -5%); }
+ 20% { transform: translate(-10%, 5%); }
+ 30% { transform: translate(5%, -10%); }
+ 40% { transform: translate(-5%, 15%); }
+ 50% { transform: translate(-10%, 5%); }
+ 60% { transform: translate(15%, 0); }
+ 70% { transform: translate(0, 10%); }
+ 80% { transform: translate(-15%, 0); }
+ 90% { transform: translate(10%, 5%); }
+ }
+
+ .grain-texture {
+ position: absolute;
+ top: -50%;
+ left: -50%;
+ width: 200%;
+ height: 200%;
+ background: url('https://www.transparenttextures.com/patterns/natural-paper.png');
+ opacity: 0.15;
+ animation: grain-noise 0.5s steps(1) infinite;
+ }
+
+ #a-roll {
+ position: absolute;
+ border-radius: 16px;
+ object-fit: cover;
+ box-shadow: 0 10px 30px rgba(0,0,0,0.1);
+ }
+
+ .comp-layer {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ }
+ </style>
+</head>
+<body>
+ <div id="main-composition" data-composition-id="main-video" data-width="1920" data-height="1080" data-duration="17">
+
+ <!-- Background Layer -->
+ <div id="grain-overlay-comp" data-composition-id="grain-overlay" data-width="1920" data-height="1080" data-duration="17" data-track-index="100">
+ <div class="grain-texture"></div>
+ <script>
+ const grainTl = gsap.timeline({ paused: true });
+ window.__timelines["grain-overlay"] = grainTl;
+ </script>
+ </div>
+
+ <!-- A-Roll Video -->
+ <video id="a-roll"
+ src="__VIDEO_SRC__"
+ data-start="0"
+ data-duration="17"
+ data-track-index="0">
+ </video>
+
+ <!-- Compositions -->
+ <div id="intro-layer" class="comp-layer"
+ data-composition-id="intro"
+ data-composition-src="compositions/intro.html"
+ data-start="0"
+ data-duration="2.5"
+ data-track-index="1">
+ </div>
+
+ <div id="graphics-layer" class="comp-layer"
+ data-composition-id="graphics"
+ data-composition-src="compositions/graphics.html"
+ data-start="0"
+ data-duration="17"
+ data-track-index="2">
+ </div>
+
+ <div id="captions-layer" class="comp-layer"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="17"
+ data-track-index="3">
+ </div>
+
+ <!-- SFX -->
+ <audio id="sfx-swipe-1" src="" data-start="1.8" data-duration="1" data-track-index="4"></audio>
+ <audio id="sfx-swipe-2" src="" data-start="4.6" data-duration="1" data-track-index="4"></audio>
+ <audio id="sfx-swipe-3" src="" data-start="8.8" data-duration="1" data-track-index="4"></audio>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+
+ // A-Roll Framing Strategy
+ // 1. 0s-1.8s: Intro scale up from small (60%) to medium (80%) - Shifted right slightly to clear speaker card
+ // 2. 1.8s-4.6s: Grid view / Shift Left (x: 600, scale: 70%) for 47% graphic
+ // 3. 4.6s-8.8s: Shift Center-Bottom (y: 800, scale: 70%) for 62% graphic (top)
+ // 4. 8.8s-14s: Shift Right (x: 1320, scale: 75%) for Editing Skills graphic (left)
+ // 5. 14s-17s: Final Reveal (Center, scale: 100%)
+
+ // Initial state
+ gsap.set('#a-roll', { x: 1100, y: 540, xPercent: -50, yPercent: -50, width: 1920 * 0.6, height: 1080 * 0.6 });
+
+ // 1. Intro Scale Up (0s - 1.8s)
+ tl.to('#a-roll', {
+ x: 1200,
+ width: 1920 * 0.8,
+ height: 1080 * 0.8,
+ duration: 1.8,
+ ease: "power2.inOut"
+ }, 0);
+
+ // 2. Moment 1: 47% Graphic Trigger (1.8s) - Shift Left
+ tl.to('#a-roll', {
+ x: 600,
+ y: 540,
+ width: 1920 * 0.7,
+ height: 1080 * 0.7,
+ duration: 0.5,
+ ease: "power2.inOut"
+ }, 1.8);
+
+ // 3. Moment 2: 62% Graphic Trigger (4.6s) - Shift Center-Bottom
+ tl.to('#a-roll', {
+ x: 960,
+ y: 750,
+ width: 1920 * 0.7,
+ height: 1080 * 0.7,
+ duration: 0.5,
+ ease: "power2.inOut"
+ }, 4.6);
+
+ // 4. Moment 3: Editing Skills Trigger (8.8s) - Shift Right
+ tl.to('#a-roll', {
+ x: 1320,
+ y: 540,
+ width: 1920 * 0.75,
+ height: 1080 * 0.75,
+ duration: 0.5,
+ ease: "power2.inOut"
+ }, 8.8);
+
+ // 5. Final Reveal (14s - 17s)
+ tl.to('#a-roll', {
+ x: 960,
+ y: 540,
+ width: 1920 * 1.0,
+ height: 1080 * 1.0,
+ duration: 1.0,
+ ease: "power2.inOut"
+ }, 14);
+
+ window.__timelines["main-video"] = tl;
+ </script>
+ </div>
+</body>
+</html>
diff --git a/packages/cli/src/ui/colors.ts b/packages/cli/src/ui/colors.ts
new file mode 100644
index 0000000000..5af3996c96
--- /dev/null
+++ b/packages/cli/src/ui/colors.ts
@@ -0,0 +1,23 @@
+import pc from "picocolors";
+
+const isColorSupported =
+ process.stdout.isTTY === true &&
+ !process.env["NO_COLOR"] &&
+ process.env["FORCE_COLOR"] !== "0";
+
+function wrap(fn: (s: string) => string): (s: string) => string {
+ return isColorSupported ? fn : (s: string) => s;
+}
+
+export const c = {
+ success: wrap(pc.green),
+ error: wrap(pc.red),
+ warn: wrap(pc.yellow),
+ dim: wrap(pc.dim),
+ bold: wrap(pc.bold),
+ accent: wrap(pc.cyan),
+ progress: wrap(pc.magenta),
+ reset: isColorSupported ? pc.reset : (s: string) => s,
+};
+
+export { isColorSupported };
diff --git a/packages/cli/src/ui/format.ts b/packages/cli/src/ui/format.ts
new file mode 100644
index 0000000000..7fe028439b
--- /dev/null
+++ b/packages/cli/src/ui/format.ts
@@ -0,0 +1,27 @@
+import { c } from "./colors.js";
+
+export function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+export function formatDuration(ms: number): string {
+ const seconds = ms / 1000;
+ if (seconds < 60) return `${seconds.toFixed(1)}s`;
+ const minutes = Math.floor(seconds / 60);
+ const remaining = seconds - minutes * 60;
+ return `${minutes}m ${remaining.toFixed(1)}s`;
+}
+
+export function label(name: string, value: string): string {
+ const pad = 14 - name.length;
+ return ` ${c.dim(name)}${" ".repeat(Math.max(1, pad))}${c.bold(value)}`;
+}
+
+export function errorBox(title: string, hint?: string, suggestion?: string): void {
+ console.error(`\n${c.error("\u2717")} ${c.bold(title)}`);
+ if (hint) console.error(`\n ${c.dim(hint)}`);
+ if (suggestion) console.error(` ${c.accent(suggestion)}`);
+ console.error();
+}
diff --git a/packages/cli/src/ui/progress.ts b/packages/cli/src/ui/progress.ts
new file mode 100644
index 0000000000..d50fec345b
--- /dev/null
+++ b/packages/cli/src/ui/progress.ts
@@ -0,0 +1,20 @@
+import { c } from "./colors.js";
+
+const { stdout } = process;
+
+export function renderProgress(percent: number, stage: string, row?: number): void {
+ const width = 25;
+ const filled = Math.floor(percent / (100 / width));
+ const empty = width - filled;
+ const bar =
+ c.progress("\u2588".repeat(filled)) +
+ c.dim("\u2591".repeat(empty));
+
+ const line = ` ${bar} ${c.bold(String(Math.round(percent)) + "%")} ${c.dim(stage)}`;
+
+ if (row !== undefined && stdout.isTTY) {
+ stdout.write(`\x1b[${row};1H\x1b[2K${line}`);
+ } else {
+ stdout.write(`\r\x1b[2K${line}`);
+ }
+}
diff --git a/packages/cli/src/utils/dom.ts b/packages/cli/src/utils/dom.ts
new file mode 100644
index 0000000000..e4d178f065
--- /dev/null
+++ b/packages/cli/src/utils/dom.ts
@@ -0,0 +1,11 @@
+import { DOMParser } from "linkedom";
+
+/**
+ * Polyfill DOMParser on globalThis so @hyperframes/core's parseHtml works in Node.js.
+ * Safe to call multiple times — only sets the global once.
+ */
+export function ensureDOMParser(): void {
+ if (typeof globalThis.DOMParser === "undefined") {
+ (globalThis as Record<string, unknown>).DOMParser = DOMParser;
+ }
+}
diff --git a/packages/cli/src/utils/mime.ts b/packages/cli/src/utils/mime.ts
new file mode 100644
index 0000000000..e6234e06c0
--- /dev/null
+++ b/packages/cli/src/utils/mime.ts
@@ -0,0 +1,21 @@
+export const MIME_TYPES: Record<string, string> = {
+ ".html": "text/html",
+ ".css": "text/css",
+ ".js": "application/javascript",
+ ".json": "application/json",
+ ".svg": "image/svg+xml",
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+ ".mp4": "video/mp4",
+ ".webm": "video/webm",
+ ".mp3": "audio/mpeg",
+ ".wav": "audio/wav",
+ ".ogg": "audio/ogg",
+ ".woff2": "font/woff2",
+ ".woff": "font/woff",
+ ".ttf": "font/ttf",
+ ".ico": "image/x-icon",
+};
diff --git a/packages/cli/src/utils/producer.ts b/packages/cli/src/utils/producer.ts
new file mode 100644
index 0000000000..cf5fa15eaa
--- /dev/null
+++ b/packages/cli/src/utils/producer.ts
@@ -0,0 +1,7 @@
+/**
+ * Dynamically load the producer module. tsup inlines @hyperframes/producer
+ * via noExternal so this resolves in the published bundle.
+ */
+export async function loadProducer() {
+ return await import("@hyperframes/producer");
+}
diff --git a/packages/cli/src/utils/project.ts b/packages/cli/src/utils/project.ts
new file mode 100644
index 0000000000..cf701a8e17
--- /dev/null
+++ b/packages/cli/src/utils/project.ts
@@ -0,0 +1,30 @@
+import { existsSync, statSync } from "node:fs";
+import { resolve, basename } from "node:path";
+import { errorBox } from "../ui/format.js";
+
+export interface ProjectDir {
+ dir: string;
+ name: string;
+ indexPath: string;
+}
+
+export function resolveProject(dirArg: string | undefined): ProjectDir {
+ const dir = resolve(dirArg ?? ".");
+ const name = basename(dir);
+ const indexPath = resolve(dir, "index.html");
+
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) {
+ errorBox("Not a directory: " + dir);
+ process.exit(1);
+ }
+ if (!existsSync(indexPath)) {
+ errorBox(
+ "No composition found in " + dir,
+ "No index.html file found.",
+ "Run npx hyperframes init to create a new composition.",
+ );
+ process.exit(1);
+ }
+
+ return { dir, name, indexPath };
+}
diff --git a/packages/cli/src/version.ts b/packages/cli/src/version.ts
new file mode 100644
index 0000000000..52c905c111
--- /dev/null
+++ b/packages/cli/src/version.ts
@@ -0,0 +1 @@
+export const VERSION = "0.1.0";
diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.json
new file mode 100644
index 0000000000..441b14aeeb
--- /dev/null
+++ b/packages/cli/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "declaration": true
+ },
+ "include": ["src"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/packages/cli/tsup.config.ts b/packages/cli/tsup.config.ts
new file mode 100644
index 0000000000..1f6d69589f
--- /dev/null
+++ b/packages/cli/tsup.config.ts
@@ -0,0 +1,53 @@
+import { defineConfig } from "tsup";
+import { resolve } from "node:path";
+
+export default defineConfig({
+ entry: ["src/cli.ts"],
+ format: ["esm"],
+ outDir: "dist",
+ target: "node22",
+ platform: "node",
+ bundle: true,
+ splitting: false,
+ sourcemap: false,
+ clean: true,
+ banner: {
+ js: `import { createRequire as __hf_createRequire } from "node:module";
+import { fileURLToPath as __hf_fileURLToPath } from "node:url";
+import { dirname as __hf_dirname } from "node:path";
+const require = __hf_createRequire(import.meta.url);
+const __filename = __hf_fileURLToPath(import.meta.url);
+const __dirname = __hf_dirname(__filename);`,
+ },
+ external: [
+ "puppeteer-core",
+ "puppeteer",
+ "@puppeteer/browsers",
+ "open",
+ "hono",
+ "hono/*",
+ "@hono/node-server",
+ "cheerio",
+ "mime-types",
+ "adm-zip",
+ "esbuild",
+ ],
+ noExternal: [
+ "@hyperframes/core",
+ "@hyperframes/producer",
+ "@hyperframes/studio-backend",
+ "@hyperframes/engine",
+ "@clack/prompts",
+ "@clack/core",
+ "picocolors",
+ "linkedom",
+ "sisteransi",
+ "is-unicode-supported",
+ "citty",
+ ],
+ esbuildOptions(options) {
+ options.alias = {
+ "@hyperframes/producer": resolve(__dirname, "../producer/src/index.ts"),
+ };
+ },
+});
diff --git a/packages/core/README.md b/packages/core/README.md
new file mode 100644
index 0000000000..0cd4fb4a98
--- /dev/null
+++ b/packages/core/README.md
@@ -0,0 +1,125 @@
+# HyperFrames Core
+
+> Create videos by writing HTML. The HTML is the source of truth - timing, layout, content. Scripts define how clips animate.
+
+HyperFrames Core is the foundational library for video composition. It defines the data attributes and HTML structure that represent video timelines, with GSAP animations to bring clips to life.
+
+Frame adapter direction:
+
+- [`../FRAME.md`](../FRAME.md) - repository-level frame model and deterministic renderer direction
+- [`adapters/README.md`](adapters/README.md) - adapter contract and contribution guide
+
+## Philosophy
+
+```
+HTML = Scene description (content, timing, layout)
+CSS = Styling
+JS = GSAP animations (motion)
+```
+
+Every element in the video timeline is represented as an HTML element with data attributes that define its position in time.
+
+---
+
+## Documentation
+
+### Schema
+
+The specification for valid HyperFrames HTML:
+
+- **[schema.md](docs/schema.md)** - Element types, data attributes, HTML patterns
+
+### Guides
+
+For AI agents and developers working with HyperFrames:
+
+| Document | Description |
+| --------------------------------------------------------- | -------------------------------------- |
+| [Cheat Sheet](docs/guides/cheat-sheet.md) | Quick reference for common actions |
+| [Position Guide](docs/guides/position.md) | Natural language → position mappings |
+| [Text Style Guide](docs/guides/text-style.md) | Natural language → text style mappings |
+| [Motion Design Guide](docs/guides/motion-design/guide.md) | Creating and editing motion designs |
+| [Caption Guide](docs/guides/motion-design/captions.md) | Adding captions to videos |
+
+---
+
+## Quick Start
+
+### Using the Editor (Recommended)
+
+```bash
+pnpm install
+pnpm dev
+```
+
+This starts the studio dev server.
+
+### Writing Compositions Manually
+
+```html
+<!DOCTYPE html>
+<html>
+ <head>
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
+ <style>
+ * {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+ }
+ html,
+ body {
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ background: #000;
+ }
+ #stage {
+ position: relative;
+ width: 1920px;
+ height: 1080px;
+ overflow: hidden;
+ }
+ </style>
+ </head>
+ <body>
+ <div id="stage">
+ <video id="el-1" data-start="0" data-end="10" src="video.mp4" muted playsinline></video>
+ <div id="el-2" data-start="2" data-end="6" data-type="text">
+ <div>Hello World</div>
+ </div>
+ </div>
+ <script>
+ const tl = gsap.timeline({ paused: true });
+ // Add animations...
+ </script>
+ </body>
+</html>
+```
+
+---
+
+## Element Types
+
+| Type | HTML Tag | Purpose |
+| ----------- | ------------------------------- | -------------------- |
+| video | `<video>` | Video clips |
+| image | `<img>` | Static images |
+| text | `<div data-type="text">` | Text overlays |
+| audio | `<audio>` | Music, sound effects |
+| composition | `<div data-type="composition">` | Motion designs |
+
+## Data Attributes
+
+| Attribute | Purpose | Required |
+| ------------ | --------------------------------- | -------- |
+| `data-start` | When element appears (seconds) | Yes |
+| `data-end` | When element disappears (seconds) | No |
+| `data-name` | Display name in UI | No |
+| `data-layer` | Z-index for stacking | No |
+
+See [schema.md](docs/schema.md) for the complete reference.
+
+---
+
+**Remember:** HTML is the storyboard. CSS is the art direction. JS is just for motion.
diff --git a/packages/core/docs/common-mistakes.md b/packages/core/docs/common-mistakes.md
new file mode 100644
index 0000000000..7924570ced
--- /dev/null
+++ b/packages/core/docs/common-mistakes.md
@@ -0,0 +1,73 @@
+# Common Mistakes
+
+Pitfalls that break HyperFrames compositions that can't be caught by the linter.
+
+> **Linter:** Run `lintHyperframeHtml()` on your composition to catch most issues automatically. The linter detects: missing timeline registration, unmuted video, nested video in timed elements, missing `class="clip"`, deprecated attribute names (`data-layer`, `data-end`), and missing dimensions. See `core/src/lint/` for the full rule list.
+
+---
+
+## 1. Animating video element dimensions with GSAP
+
+**Symptom:** Video frames stop updating, or browser performance drops.
+
+**Cause:** GSAP animating `width`, `height`, `top`, `left` directly on a `<video>` element can cause the browser to stop rendering frames.
+
+```js
+// BROKEN — animating video element dimensions
+tl.to("#el-video", { width: 500, height: 280, top: 700, left: 1400 }, 26);
+
+// FIXED — animate a wrapper div, video fills it at 100%
+tl.to("#pip-wrapper", { width: 500, height: 280, top: 700, left: 1400 }, 26);
+```
+
+Use a non-timed wrapper div for visual effects like picture-in-picture. Animate the wrapper; let the video fill it.
+
+---
+
+## 2. Controlling media playback in scripts
+
+**Symptom:** Audio/video playback is out of sync, or plays when it shouldn't.
+
+**Cause:** Calling `video.play()`, `video.pause()`, `audio.currentTime = ...` in your scripts. The framework owns all media playback.
+
+```js
+// BROKEN — conflicts with framework media sync
+document.getElementById("el-video").play();
+document.getElementById("el-audio").currentTime = 5;
+
+// FIXED — don't do this. The framework handles it.
+// Use GSAP for visual animations only:
+tl.to("#el-video", { opacity: 1, duration: 0.5 }, 0);
+```
+
+---
+
+## 3. Composition duration shorter than video
+
+**Symptom:** Video plays for a few seconds then stops. Timeline shows 8-10 seconds even though the video is minutes long.
+
+**Cause:** The composition duration equals the GSAP timeline duration, not `data-duration` on the video. If your last GSAP animation ends at 8 seconds, the composition is 8 seconds long.
+
+```js
+// BROKEN — timeline is only 8s long, video cuts off
+tl.to("#lower-third", { left: -640, duration: 0.6 }, 7.2);
+// Last tween ends at 7.8s → composition = 7.8s
+
+// FIXED — extend timeline to match video length
+tl.to("#lower-third", { left: -640, duration: 0.6 }, 7.2);
+tl.set({}, {}, 283); // ← extends timeline to 283 seconds
+```
+
+`tl.set({}, {}, TIME)` adds a zero-duration tween at the specified time, which extends the timeline without affecting any elements.
+
+---
+
+## Debugging checklist
+
+When something doesn't work, check in this order:
+
+1. Run the linter: `lintHyperframeHtml(html)` — catches most structural issues
+2. Is `window.__timelines["<id>"]` registered? Does the key match `data-composition-id`?
+3. Are GSAP animations only on visual properties (opacity, transform, color)?
+4. Is the GSAP timeline long enough? (`tl.set({}, {}, DURATION)` at the end)
+5. Open browser console — runtime errors show up as `[Browser:ERROR]` or `[Browser:PAGEERROR]`
diff --git a/packages/core/docs/core.md b/packages/core/docs/core.md
new file mode 100644
index 0000000000..c1ab6163cc
--- /dev/null
+++ b/packages/core/docs/core.md
@@ -0,0 +1,532 @@
+# HyperFrames Schema
+
+Reference for generating and editing HyperFrames HTML compositions. This is your source of truth for how to author compositions.
+
+**New to HyperFrames?** Start with the [quickstart template](./quickstart-template.html) — a copy-paste composition with inline comments explaining every required piece. See [common mistakes](./common-mistakes.md) for pitfalls that break compositions.
+
+For Frame adapters and deterministic frame rendering direction, see [`../../FRAME.md`](../../FRAME.md) and [`../adapters/README.md`](../adapters/README.md).
+
+Producer-canonical parity note:
+
+- Producer render behavior is the source of truth for deterministic parity.
+- Preview should emulate producer seek semantics (`renderSeek`, frame quantization, readiness gates) in parity mode.
+- Non-parity smooth playback can exist, but parity mode is the correctness baseline.
+
+## Overview
+
+HyperFrames uses HTML as the source of truth for describing a video:
+
+- **HTML clips** = video, image, audio, composition
+- **Data attributes** = timing, metadata, styling
+- **CSS** = positioning and appearance
+- **GSAP timeline** = animations and playback sync
+
+### Framework-Managed Behavior
+
+The framework reads data attributes and automatically manages:
+
+- **Primitive clip timeline entries** — the framework reads `data-start`, `data-duration`, and `data-track-index` from primitive clips and adds them to the composition's GSAP timeline. You do not manually add primitive clips to the timeline in scripts.
+- **Media playback** (play, pause, seek) for `<video>` and `<audio>`
+- **Clip lifecycle** — clips are **mounted** (made visible on screen) and **unmounted** (removed from screen) based on `data-start` and `data-duration`
+- **Timeline synchronization** (keeping media in sync with the GSAP master timeline)
+- **Media loading** — the framework waits for all media elements to load before resolving timing and starting playback
+
+Mounting and unmounting controls **presence**, not appearance. A clip that is mounted is on screen; a clip that is unmounted is not. Transitions (fade in, slide in, etc.) are separate — they are animated in scripts and happen _after_ a clip is mounted or _before_ it is unmounted.
+
+The framework does **not** handle transitions, effects, or visual animation — those are driven by GSAP in JavaScript.
+
+Do not manually call `video.play()`, `video.pause()`, set `audio.currentTime`, or mount/unmount clips in scripts. The framework owns media playback and clip lifecycle. Animating visual properties like `opacity` or `transform` for transitions is fine — that's what scripts are for.
+
+## Viewport
+
+Every composition must include `data-width` and `data-height` so scripts and CSS can reference concrete pixel dimensions for layout. Common sizes:
+
+- **Landscape**: `data-width="1920" data-height="1080"`
+- **Portrait**: `data-width="1080" data-height="1920"`
+
+e.g.,
+
+```html
+<div id="main" data-composition-id="my-video" data-start="0" data-width="1920" data-height="1080">
+ <!-- clips -->
+</div>
+```
+
+Every composition's container is full-screen within the viewport by default. The framework applies full-screen sizing to composition containers automatically.
+
+To position or size individual clips (e.g., picture-in-picture, overlay placement), use standard CSS on the element.
+
+## Compositions
+
+A composition is the fundamental grouping unit in HyperFrames. Every clip — video, image, audio — must live inside a composition. The `index.html` file is itself a composition (the top-level one), and it can contain nested compositions within it. Any composition can be imported into another composition as a sub-composition — there is no special "root" type.
+
+A composition carries the same core attributes as any other clip (`id`, `data-start`, `data-track-index`), so it can be placed and timed on a timeline just like a video or image. A composition's length is determined by its GSAP timeline — there is no `data-duration` on compositions. This means compositions can be nested: a composition clip inside another composition behaves like a self-contained video within the parent timeline.
+
+### Composition File Structure
+
+**Each composition should be defined in its own HTML file.** This keeps compositions modular, reusable, and maintainable. The file contains the complete composition: HTML structure, inline styles, and script.
+
+```
+project/
+├── index.html # Root composition
+├── compositions/
+│ ├── intro-anim.html # Intro animation composition
+│ ├── caption-overlay.html # Caption composition
+│ └── outro-title.html # Outro composition
+```
+
+**Composition file format** (`compositions/intro-anim.html`):
+
+```html
+<!-- Define the composition as a template that can be loaded -->
+<template id="intro-anim-template">
+ <div data-composition-id="intro-anim" data-width="1920" data-height="1080">
+ <div class="title">Welcome!</div>
+ <div class="subtitle">Let's get started</div>
+
+ <style>
+ [data-composition-id="intro-anim"] .title {
+ font-size: 72px;
+ color: white;
+ text-align: center;
+ }
+ [data-composition-id="intro-anim"] .subtitle {
+ font-size: 36px;
+ color: #ccc;
+ text-align: center;
+ }
+ </style>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+ tl.from(".title", { opacity: 0, y: -50, duration: 1 });
+ tl.from(".subtitle", { opacity: 0, y: 50, duration: 1 }, 0.5);
+ window.__timelines["intro-anim"] = tl;
+ </script>
+ </div>
+</template>
+```
+
+### Loading Compositions
+
+Use the `data-composition-src` attribute to load a composition from an external HTML file. The framework will automatically fetch the template and instantiate it:
+
+```html
+<div id="comp-1" data-composition-id="my-video" data-start="0" data-width="1920" data-height="1080">
+ <!-- Primitive clips -->
+ <video id="el-1" data-start="0" data-duration="10" data-track-index="0" src="..."></video>
+ <video id="el-2" data-start="el-1" data-duration="8" data-track-index="0" src="..."></video>
+ <img id="el-3" data-start="5" data-duration="4" data-track-index="1" src="..." />
+ <audio id="el-4" data-start="0" data-duration="30" data-track-index="2" src="..." />
+
+ <!-- Load composition from external file -->
+ <div
+ id="el-5"
+ data-composition-id="intro-anim"
+ data-composition-src="compositions/intro-anim.html"
+ data-start="0"
+ data-track-index="3"
+ ></div>
+
+ <!-- Another loaded composition -->
+ <div
+ id="el-6"
+ data-composition-id="captions"
+ data-composition-src="compositions/caption-overlay.html"
+ data-start="0"
+ data-track-index="4"
+ ></div>
+</div>
+```
+
+The framework will:
+
+1. Fetch the HTML file specified in `data-composition-src`
+2. Extract the `<template>` content
+3. Clone and mount it into the composition element
+4. Execute any `<script>` tags within the template
+5. Register the timeline in `window.__timelines`
+
+### Best Practices for Composition Files
+
+**Use separate HTML files when:**
+
+- The composition is reusable across multiple projects or scenes
+- The composition has complex logic, styling, or structure (>20 lines)
+- You want to keep the main `index.html` clean and focused on orchestration
+- The composition represents a distinct functional unit (captions, titles, animations)
+
+**Use inline compositions when:**
+
+- The composition is truly one-off and project-specific
+- The composition is very simple (<10 lines total)
+- You're prototyping and iterating quickly
+
+**File naming conventions:**
+
+- Use kebab-case: `intro-anim.html`, `caption-overlay.html`, `emoji-burst.html`
+- Name files descriptively based on their purpose or visual function
+- Group related compositions in subdirectories if you have many: `compositions/titles/`, `compositions/overlays/`
+
+## Clip Types
+
+A clip is any discrete block on the timeline. We represent clips as HTML elements and apply data-attributes to describe them.
+
+- `<video>` — Video clips, B-roll, A-roll
+- `<img>` — Static images, overlays
+- `<audio>` — Music, sound effects
+- `<div data-composition-id="...">` — Nested compositions (animations, grouped sequences)
+
+## HTML Attributes
+
+### All Clips
+
+- `id` — Unique identifier (e.g., "el-1")
+- `data-start` — Start time in seconds, or a clip `id` reference. See [Relative Timing](#relative-timing).
+- `data-duration` — Duration in seconds. Required for `<img>` clips. Optional for `<video>` and `<audio>` (defaults to the source media's full duration). Not used on compositions.
+- `data-track-index` — Timeline track number. Tracks serve two purposes: they determine visual layering (higher tracks render in front) and they group clips into rows on the timeline. Clips on the same track **cannot overlap in time**.
+
+### Media Clips (video, audio)
+
+- `data-media-start` — (optional) Playback begins at this time in the source file, in seconds. Defaults to `0`.
+
+### Composition Clips
+
+- `data-composition-id` — Unique composition ID
+- `data-composition-src` — (optional) Path to external HTML file containing the composition template. The framework will fetch, instantiate, and mount the template automatically.
+
+> Compositions do **not** use `data-duration`. Their duration is determined by their GSAP timeline.
+
+## Relative Timing
+
+Instead of calculating absolute start times, a clip can reference another clip's `id` in its `data-start` attribute. This means "start when that clip ends." The referenced clip must be in the same composition and must have a known duration (either an explicit `data-duration` or an inferred duration from the source media).
+
+### Basic Sequential Clips
+
+```html
+<video id="intro" data-start="0" data-duration="10" data-track-index="0" src="..."></video>
+<video id="main" data-start="intro" data-duration="20" data-track-index="0" src="..."></video>
+<video id="outro" data-start="main" data-duration="5" data-track-index="0" src="..."></video>
+```
+
+`main` resolves to second 10, `outro` resolves to second 30. If `intro`'s duration changes to 15, `main` and `outro` shift automatically.
+
+### Offsets (gaps and overlaps)
+
+Add `+ N` or `- N` after the ID to offset from the end of the referenced clip:
+
+```html
+<!-- intro ends at 10. "intro + 2" = 10 + 2 = starts at second 12 (2s gap) -->
+<video id="scene-a" data-start="intro + 2" data-duration="20" data-track-index="0" src="..."></video>
+
+<!-- intro ends at 10. "intro - 0.5" = 10 - 0.5 = starts at second 9.5 (0.5s overlap for crossfade) -->
+<!-- Different track because clips on the same track cannot overlap -->
+<video id="scene-b" data-start="intro - 0.5" data-duration="20" data-track-index="1" src="..."></video>
+```
+
+### Rules
+
+- **Same composition only** — references resolve within the clip's parent composition
+- **No circular references** — A cannot start after B if B starts after A
+- **Referenced clip must have a known duration** — the system needs a known end time to resolve the reference (either explicit `data-duration` or inferred from source media)
+- **Parsing** — if the value is a valid number, it is absolute seconds; otherwise it is parsed as `<id>`, `<id> + <number>`, or `<id> - <number>`
+
+## Video Clips
+
+Full-screen or positioned video clips. Videos sync their playback to the timeline position.
+
+```html
+<video
+ id="el-1"
+ data-start="0"
+ data-duration="15"
+ data-track-index="0"
+ src="./assets/video.mp4"
+></video>
+```
+
+- `data-media-start` — Playback begins at this time in the source video file (seconds). Default: `0`.
+- `data-duration` — (optional) How long the clip occupies on the timeline, in seconds. Playback runs from `data-media-start` for up to `data-duration` seconds. If the source media runs out before `data-duration` elapses, playback naturally stops (the clip remains mounted showing the last frame). If omitted, defaults to the remaining duration of the source file from `data-media-start`.
+
+## Image Clips
+
+Static images that appear for a duration.
+
+```html
+<img
+ id="el-2"
+ data-start="5"
+ data-duration="4"
+ data-track-index="1"
+ src="./assets/video.mp4"
+/>
+```
+
+## Audio Clips
+
+Background music or sound effects. Audio clips are invisible.
+
+```html
+<audio
+ id="el-4"
+ data-start="0"
+ data-duration="30"
+ data-track-index="2"
+ src="./assets/music.mp3"
+></audio>
+```
+
+- `data-media-start` — Playback begins at this time in the source audio file (seconds). Default: `0`.
+- `data-duration` — (optional) How long the clip occupies on the timeline, in seconds. Playback runs from `data-media-start` for up to `data-duration` seconds. If the source media runs out before `data-duration` elapses, playback naturally stops (the clip remains mounted but silent). If omitted, defaults to the remaining duration of the source file from `data-media-start`.
+
+## Two Layers: Primitives and Scripts
+
+Every composition — master or sub — has the same two layers:
+
+- **HTML** — primitive clips (`video`, `img`, `audio`, nested `div[data-composition-id]`). This is the declarative structure: what plays, when, and on which track.
+- **Script** — effects, transitions, dynamic DOM, canvas, SVG — creative animation and visuals via GSAP. Scripts do **not** control media playback or clip visibility; the framework handles those via data attributes.
+
+Both layers are available to every composition. The schema defines the primitives and the timeline contract; scripts handle visual creativity on top of that.
+
+> **Warning:** Never use scripts to play/pause/seek media elements or to show/hide clips based on timing. The framework does this automatically from `data-start`, `data-duration`, and `data-media-start`. Scripts that duplicate this behavior will conflict with the framework.
+
+### Script Isolation
+
+Each composition's script is scoped to that composition. When a composition is loaded from an external HTML file via `data-composition-src`, its inline `<script>` and `<style>` tags are automatically included and scoped to that composition.
+
+**Preferred approach** — Composition in separate HTML file:
+
+```html
+<!-- In index.html -->
+<div
+ id="el-5"
+ data-composition-id="intro-anim"
+ data-composition-src="compositions/intro-anim.html"
+ data-start="0"
+ data-track-index="2"
+></div>
+```
+
+**Alternative approach** — External JS file:
+
+```html
+<!-- In index.html -->
+<div
+ id="el-5"
+ data-composition-id="intro-anim"
+ data-start="0"
+ data-track-index="2"
+ data-width="1920"
+ data-height="1080"
+>
+ <script src="intro-anim.js"></script>
+</div>
+```
+
+The separate HTML file approach is preferred because it keeps all composition code (structure, style, script) in one self-contained, reusable file.
+
+The only required file is `index.html`. Every composition must have at least a script to create and register its GSAP timeline.
+
+### Top-Level Composition
+
+The top-level composition is the `index.html` entry point. It acts as the conductor — sequencing clips and placing sub-composition timelines into an overall master timeline. It can technically do anything in its script, but its primary purpose is high-level orchestration. Any composition can serve as a top-level composition or be nested into another — there is no structural difference.
+
+```html
+<div id="comp-1" data-composition-id="my-video" data-start="0" data-width="1920" data-height="1080">
+ <!-- Primitive clips -->
+ <video id="el-1" data-start="0" data-duration="10" data-track-index="0" src="..."></video>
+ <video id="el-2" data-start="el-1" data-duration="8" data-track-index="0" src="..."></video>
+ <img id="el-3" data-start="5" data-duration="4" data-track-index="1" src="..." />
+ <audio id="el-4" data-start="0" data-duration="30" data-track-index="2" src="..." />
+
+ <!-- Load sub-compositions from external files -->
+ <div
+ id="el-5"
+ data-composition-id="intro-anim"
+ data-composition-src="compositions/intro-anim.html"
+ data-start="0"
+ data-track-index="3"
+ ></div>
+
+ <div
+ id="el-6"
+ data-composition-id="captions"
+ data-composition-src="compositions/caption-overlay.html"
+ data-start="0"
+ data-track-index="4"
+ ></div>
+
+ <script>
+ // Just register the timeline - framework auto-nests sub-compositions
+ const tl = gsap.timeline({ paused: true });
+ window.__timelines["my-video"] = tl;
+ </script>
+</div>
+```
+
+### Sub-Compositions
+
+Sub-compositions are a spectrum. One might simply group a few primitive clips. Another might be a fully custom program with its own HTML, CSS, and JavaScript — creating, animating, and destroying DOM however it sees fit. There are no categories or constraints on what a sub-composition does internally. The only rule: it must be driven by a GSAP timeline and export it. If children use `position: absolute`, always set explicit `left`/`top`/`bottom`/`right` — the composition root is a positioned container, so omitting coordinates produces unpredictable placement.
+
+## Wrapping Dynamic Content in Compositions
+
+**Critical Rule: All visual content must live inside a composition with data attributes to appear in the timeline.**
+
+When you have dynamic or script-animated content (captions, emojis, overlays, text animations), wrap them in a composition element with `data-start`, `data-duration` (or let the timeline determine duration), and `data-track-index`. The children inside can be freely created and animated via JavaScript—they don't need individual data attributes.
+
+### Wrong: Dynamic content outside a composition
+
+```html
+<!-- BAD: captions-container is not a composition - won't appear in timeline -->
+<div id="ui-layer">
+ <div id="captions-container">
+ <!-- Dynamically created caption groups via JS -->
+ </div>
+ <div class="emoji" id="emoji-1">🤩</div>
+</div>
+
+<script>
+ // These animations work visually but elements don't appear in timeline
+ tl.to(".caption-group", { opacity: 1 }, 0.5);
+ tl.to("#emoji-1", { scale: 1.2 }, 2);
+</script>
+```
+
+### Correct: Dynamic content wrapped in compositions
+
+**Preferred approach** — Load from external HTML files:
+
+```html
+<!-- GOOD: Each logical group is a composition loaded from its own file -->
+<div
+ id="captions-comp"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-track-index="5"
+></div>
+
+<div
+ id="emojis-comp"
+ data-composition-id="emojis"
+ data-composition-src="compositions/emojis.html"
+ data-start="0"
+ data-track-index="6"
+></div>
+```
+
+**Alternative approach** — Inline composition (useful for one-off custom compositions):
+
+```html
+<div
+ id="captions-comp"
+ data-composition-id="captions"
+ data-start="0"
+ data-track-index="5"
+ data-width="1080"
+ data-height="1920"
+>
+ <!-- Children created/animated by script - no data attributes needed -->
+ <div id="captions-container"></div>
+ <script>
+ const captionTL = gsap.timeline({ paused: true });
+ // Dynamically create and animate caption groups...
+ window.__timelines["captions"] = captionTL;
+ </script>
+</div>
+
+<div
+ id="emojis-comp"
+ data-composition-id="emojis"
+ data-start="0"
+ data-track-index="6"
+ data-width="1080"
+ data-height="1920"
+>
+ <div class="emoji" id="emoji-1">🤩</div>
+ <div class="emoji" id="emoji-2">🏔️</div>
+ <script>
+ const emojiTL = gsap.timeline({ paused: true });
+ emojiTL.to("#emoji-1", { opacity: 1, scale: 1.2 }, 2);
+ emojiTL.to("#emoji-2", { opacity: 1, scale: 1.2 }, 4);
+ window.__timelines["emojis"] = emojiTL;
+ </script>
+</div>
+```
+
+### When to create separate compositions
+
+- **Captions**: One composition for all captions, script manages word groups
+- **Emojis/Stickers**: One composition for the emoji layer
+- **Hooks/Titles**: One composition per distinct title sequence
+- **Overlays**: Group related overlays into compositions by purpose
+
+The composition appears in the timeline with its start time and duration (determined by its GSAP timeline). Everything inside is managed by the script but inherits the composition's timeline position.
+
+### Caption discoverability contract
+
+To make caption previews deterministic and easy to isolate in downstream UIs (timeline, mini-player, editor overlays), caption compositions should expose a stable root selector.
+
+Use these attributes on the caption root node:
+
+- `data-timeline-role="captions"` (required)
+- `data-caption-root="true"` (recommended)
+
+Example:
+
+```html
+<div
+ id="captions-comp"
+ data-composition-id="captions"
+ data-start="0"
+ data-track-index="5"
+ data-width="1080"
+ data-height="1920"
+ data-timeline-role="captions"
+ data-caption-root="true"
+>
+ <div id="caption-container"></div>
+ <script>
+ const captionTL = gsap.timeline({ paused: true });
+ window.__timelines["captions"] = captionTL;
+ </script>
+</div>
+```
+
+## Timeline Contract
+
+The framework initializes `window.__timelines = {}` before any scripts run. Every composition **must** have a script that creates a GSAP timeline and registers it:
+
+```js
+const tl = gsap.timeline({ paused: true });
+// ... add tweens, nested timelines, etc.
+window.__timelines["<data-composition-id>"] = tl;
+```
+
+### Rules
+
+- **Every composition needs a script** — at minimum, to create and register its timeline. A composition without a script has no timeline and cannot participate in the hierarchy.
+- **All timelines start paused** — create timelines with `{ paused: true }`. The top-level timeline is controlled externally by the frontend player or renderer.
+- **Framework auto-nests sub-timelines** — you do **not** need to manually add sub-composition timelines to the master timeline. The framework automatically nests any timeline registered in `window.__timelines` into its parent based on the composition's `data-start` attribute.
+- **Duration comes from the timeline** — a composition's duration is `tl.duration()`. The timeline is the sole source of truth; there is no `data-duration` on compositions.
+- **Timelines must be finite** — every timeline must have a finite duration. Infinite or indefinite timelines are not supported.
+
+### What NOT to do
+
+```js
+// UNNECESSARY - the framework does this automatically
+if (window.__timelines["captions"]) {
+ masterTL.add(window.__timelines["captions"], 0);
+}
+```
+
+Just register your timeline in `window.__timelines` and the framework handles the rest.
+
+## Output Checklist
+
+- [ ] Every composition has `data-width` and `data-height` attributes
+- [ ] Each reusable composition is in its own HTML file (in `compositions/` directory)
+- [ ] Compositions loaded via `data-composition-src` attribute
+- [ ] Each composition file uses `<template>` tag to wrap its content
+- [ ] `window.__timelines` given all compositions' timelines
+- [ ] Complex/dynamic animations are handled by scripts in compositions
diff --git a/packages/core/docs/core_notes.md b/packages/core/docs/core_notes.md
new file mode 100644
index 0000000000..00fc052870
--- /dev/null
+++ b/packages/core/docs/core_notes.md
@@ -0,0 +1,61 @@
+# Core Notes
+
+Extended design rationale and context for decisions in `core.md`. This file is for humans reviewing the design — it is not consumed by the LLM agent.
+
+## Interactive Compositions
+
+### Why `data-start="interactive"`
+
+We considered three alternatives:
+
+1. **`data-interactive` boolean attribute** — Keeps `data-start` clean, but then `data-start` must either be omitted (breaking the convention that every clip has `data-start`) or present but meaningless. Two attributes to express what one value handles.
+
+2. **Event-driven `data-start="on:click:#element"`** — More expressive and extensible to other events (`on:hover`, `on:end:#video`), but complex to parse, harder for an LLM to author correctly, and the trigger/target relationship is declared on the target which reads backwards.
+
+3. **`data-start="interactive"` (chosen)** — Reuses the existing `data-start` attribute with a new keyword value. Reads naturally: "when does this start?" → "interactively." One attribute, no ambiguity, easy to parse (`=== "interactive"` check).
+
+The tradeoff is that `data-start` is now overloaded (was purely numeric/reference, now has a keyword). We accepted this because the parsing is trivial and the readability gain is significant.
+
+### Why `window.__navigate()` instead of `data-goto`
+
+Navigation is behavior, not structure. The framework's philosophy separates these: HTML declares structure and timing, scripts handle behavior.
+
+A `data-goto="composition-id"` attribute on trigger elements would be declarative and concise, but limits what authors can do. With a runtime API, scripts can:
+
+- Add conditional logic (`if (score > 50) navigate('win') else navigate('lose')`)
+- Animate a transition before navigating
+- Add delays or timeouts
+- Chain multiple actions on a single click
+- Use any DOM event, not just clicks
+
+The trigger element is just normal HTML with a normal `addEventListener`. The LLM only needs to know `window.__navigate(id)` — plain JS.
+
+### Navigation Behavior: Replace
+
+When `__navigate()` is called:
+
+1. The currently active composition's timeline pauses
+2. The current composition hides (visibility/display)
+3. The target interactive composition shows
+4. The target's timeline seeks to 0 and plays
+
+We chose Replace (parent hides entirely) over Overlay (target plays on top) or Pause-and-branch (parent pauses, resumes when target ends) because it's the simplest mental model and matches how most interactive video works (YouTube branching, Netflix Bandersnatch).
+
+### Ownership Model
+
+Interactive compositions are children of the composition that branches to them in the DOM tree. The parent composition is the "root" of its branching experience — it owns its branches.
+
+However, `window.__navigate()` resolves composition IDs globally across the full tree, not scoped to the current parent. This means:
+
+- A deeply nested interactive composition can navigate to any other interactive composition by ID
+- A shared "game over" or "credits" composition can be reached from anywhere
+- Circular navigation is possible (A → B → A) — the framework does not prevent loops
+
+### Future Extensions
+
+These are not implemented but the design accommodates them without breaking changes:
+
+- **Overlay mode**: `window.__navigate(id, { mode: 'overlay' })` — target plays on top, parent pauses or continues
+- **History / back**: `window.__navigate('$back')` to return to the previous composition, `window.__navigateHistory` to read the stack
+- **Auto-advance / timeout**: Scripts can implement this today with `setTimeout(() => window.__navigate('default'), 10000)`. A declarative shorthand could be added later.
+- **Pause-and-branch**: `window.__navigate(id, { mode: 'branch' })` — parent pauses, resumes when target ends
diff --git a/packages/core/docs/quickstart-template.html b/packages/core/docs/quickstart-template.html
new file mode 100644
index 0000000000..32fbf6a3a3
--- /dev/null
+++ b/packages/core/docs/quickstart-template.html
@@ -0,0 +1,180 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <!--
+ REQUIRED: viewport must match your composition dimensions.
+ Landscape: width=1920, height=1080
+ Portrait: width=1080, height=1920
+ -->
+ <meta name="viewport" content="width=1920, height=1080" />
+
+ <!--
+ REQUIRED: data-composition-id identifies this composition.
+ Must match the key you register in window.__timelines below.
+ Optional: data-width/data-height help the producer determine resolution.
+ -->
+ <meta data-composition-id="my-video" data-width="1920" data-height="1080" />
+
+ <title>My Video</title>
+
+ <!-- REQUIRED: GSAP for timeline animations -->
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
+
+ <style>
+ * {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+ }
+ html,
+ body {
+ width: 1920px;
+ height: 1080px;
+ overflow: hidden;
+ background: #000;
+ }
+
+ #stage {
+ position: relative;
+ width: 1920px;
+ height: 1080px;
+ overflow: hidden;
+ }
+
+ /*
+ REQUIRED: All timed clips need visibility: hidden.
+ The framework toggles visibility based on data-start/data-duration.
+ Never toggle visibility yourself in scripts.
+ */
+ .clip {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ visibility: hidden;
+ object-fit: cover;
+ }
+ </style>
+ </head>
+ <body>
+ <div id="stage">
+ <!--
+ ════════════════════════════════════════════════════
+ VIDEO CLIPS
+ ════════════════════════════════════════════════════
+
+ REQUIRED attributes:
+ data-start — when the clip appears (seconds)
+ data-duration — how long the clip stays on screen (seconds)
+ (optional for video/audio — defaults to source duration)
+ data-track-index — z-stacking order + timeline track grouping
+ (higher = in front, clips on same track cannot overlap)
+
+ REQUIRED on <video>:
+ muted — framework manages audio via separate <audio> element
+ playsinline — prevents fullscreen on mobile
+
+ REQUIRED:
+ class="clip" — sets visibility: hidden so framework can manage lifecycle
+
+ DO NOT:
+ - Call video.play(), video.pause(), or set video.currentTime in scripts
+ - Toggle visibility in scripts
+ - Use the video element for audio (use a separate <audio> element)
+ -->
+ <video
+ id="el-video"
+ class="clip"
+ data-start="0"
+ data-duration="10"
+ data-track-index="0"
+ src="my-video.mp4"
+ muted
+ playsinline
+ ></video>
+
+ <!--
+ ════════════════════════════════════════════════════
+ IMAGE CLIPS
+ ════════════════════════════════════════════════════
+
+ data-duration is REQUIRED for images (they have no intrinsic duration).
+ -->
+ <img id="el-image" class="clip" data-start="10" data-duration="5" data-track-index="0" src="my-image.png" />
+
+ <!--
+ ════════════════════════════════════════════════════
+ AUDIO
+ ════════════════════════════════════════════════════
+
+ Audio is invisible — no class="clip" needed (no visual to hide).
+ Use a separate <audio> element even if the source is the same .mp4 file.
+ The framework syncs audio playback to the timeline position.
+
+ Optional: data-volume="0.5" (0-1, default 1)
+ -->
+ <audio
+ id="el-audio"
+ data-start="0"
+ data-duration="15"
+ data-track-index="1"
+ data-volume="0.8"
+ src="my-video.mp4"
+ ></audio>
+
+ <!--
+ ════════════════════════════════════════════════════
+ TEXT / HTML OVERLAYS
+ ════════════════════════════════════════════════════
+
+ Any div with data-start becomes a timed clip.
+ Content inside can be freely styled with CSS.
+ Animate visual properties (opacity, transform) with GSAP — fine.
+ Do NOT animate visibility — the framework owns that.
+ -->
+ <div
+ id="el-title"
+ class="clip"
+ data-start="1"
+ data-duration="4"
+ data-track-index="2"
+ style="display: flex; align-items: center; justify-content: center; z-index: 10"
+ >
+ <h1 style="font-family: sans-serif; font-size: 72px; color: white; opacity: 0">Hello World</h1>
+ </div>
+ </div>
+
+ <script>
+ /*
+ ════════════════════════════════════════════════════
+ GSAP TIMELINE
+ ════════════════════════════════════════════════════
+
+ REQUIRED: Create a paused GSAP timeline.
+ REQUIRED: Register it in window.__timelines with the SAME ID
+ as data-composition-id on the <meta> tag.
+
+ Without this registration, NOTHING works — no playback,
+ no seeking, no rendering. This is the #1 mistake.
+ */
+ var tl = gsap.timeline({ paused: true });
+
+ // Animate visual properties only — opacity, transform, color, etc.
+ // The framework handles clip mounting/unmounting and media playback.
+ tl.to("#el-video", { opacity: 1, duration: 0.5 }, 0);
+ tl.to("#el-video", { opacity: 0, duration: 0.5 }, 9.5);
+
+ tl.to("#el-image", { opacity: 1, duration: 0.5 }, 10);
+ tl.to("#el-image", { opacity: 0, duration: 0.5 }, 14.5);
+
+ tl.to("#el-title h1", { opacity: 1, y: 0, duration: 0.8, ease: "power2.out" }, 1);
+ tl.to("#el-title h1", { opacity: 0, duration: 0.5 }, 4);
+
+ // REQUIRED: Register the timeline. The key MUST match data-composition-id.
+ window.__timelines = window.__timelines || {};
+ window.__timelines["my-video"] = tl;
+ </script>
+ </body>
+</html>
diff --git a/packages/core/docs/versions/changelog.md b/packages/core/docs/versions/changelog.md
new file mode 100644
index 0000000000..90f6876459
--- /dev/null
+++ b/packages/core/docs/versions/changelog.md
@@ -0,0 +1,5 @@
+# HyperFrames Core Changelog
+
+## v0.1
+
+Initial schema specification. Defines the foundational HTML-as-video format: compositions, clip types (video, image, audio, nested compositions), data attributes for timing and tracks, relative timing with offsets, the two-layer primitives + scripts model, and the GSAP timeline contract.
diff --git a/packages/core/docs/versions/v0.1/core.md b/packages/core/docs/versions/v0.1/core.md
new file mode 100644
index 0000000000..58567c7351
--- /dev/null
+++ b/packages/core/docs/versions/v0.1/core.md
@@ -0,0 +1,326 @@
+# HyperFrames Schema
+
+Reference for generating and editing HyperFrames HTML compositions. This is your source of truth for how to author compositions.
+
+## Overview
+
+HyperFrames uses HTML as the source of truth for describing a video:
+
+- **HTML clips** = video, image, audio, composition
+- **Data attributes** = timing, metadata, styling
+- **CSS** = positioning and appearance
+- **GSAP timeline** = animations and playback sync
+
+### Framework-Managed Behavior
+
+The framework reads data attributes and automatically manages:
+
+- **Primitive clip timeline entries** — the framework reads `data-start`, `data-duration`, and `data-track-index` from primitive clips and adds them to the composition's GSAP timeline. You do not manually add primitive clips to the timeline in scripts.
+- **Media playback** (play, pause, seek) for `<video>` and `<audio>`
+- **Clip lifecycle** — clips are **mounted** (made visible on screen) and **unmounted** (removed from screen) based on `data-start` and `data-duration`
+- **Timeline synchronization** (keeping media in sync with the GSAP master timeline)
+- **Media loading** — the framework waits for all media elements to load before resolving timing and starting playback
+
+Mounting and unmounting controls **presence**, not appearance. A clip that is mounted is on screen; a clip that is unmounted is not. Transitions (fade in, slide in, etc.) are separate — they are animated in scripts and happen _after_ a clip is mounted or _before_ it is unmounted.
+
+The framework does **not** handle transitions, effects, or visual animation — those are driven by GSAP in JavaScript.
+
+Do not manually call `video.play()`, `video.pause()`, set `audio.currentTime`, or mount/unmount clips in scripts. The framework owns media playback and clip lifecycle. Animating visual properties like `opacity` or `transform` for transitions is fine — that's what scripts are for.
+
+## Viewport
+
+The root composition must declare its intended render dimensions using `data-width` and `data-height` attributes. Common sizes:
+
+- **Landscape**: `data-width="1920" data-height="1080"`
+- **Portrait**: `data-width="1080" data-height="1920"`
+
+e.g.,
+
+```html
+<div id="main" data-composition-id="my-video" data-start="0" data-width="1920" data-height="1080">
+ <!-- clips -->
+</div>
+```
+
+Every composition's container is full-screen within the viewport by default. The framework applies full-screen sizing to composition containers automatically.
+
+To position or size individual clips (e.g., picture-in-picture, overlay placement), use standard CSS on the element.
+
+## Compositions
+
+A composition is the fundamental grouping unit in HyperFrames. Every clip — video, image, audio — must live inside a composition. The `index.html` file is itself a composition (the top-level one), and it can contain nested compositions within it. Any composition can be imported into another composition as a sub-composition — there is no special "root" type.
+
+A composition carries the same core attributes as any other clip (`id`, `data-start`, `data-track-index`), so it can be placed and timed on a timeline just like a video or image. A composition's length is determined by its GSAP timeline — there is no `data-duration` on compositions. This means compositions can be nested: a composition clip inside another composition behaves like a self-contained video within the parent timeline.
+
+```html
+<div id="comp-1" data-composition-id="my-video" data-start="0" data-width="1920" data-height="1080">
+ <!-- Clips live inside the composition -->
+ <video id="el-1" data-start="0" data-duration="10" data-track-index="0" src="..."></video>
+ <video id="el-2" data-start="el-1" data-duration="8" data-track-index="0" src="..."></video>
+ <img id="el-3" data-start="5" data-duration="4" data-track-index="1" src="..." />
+ <audio id="el-4" data-start="0" data-duration="30" data-track-index="2" src="..." />
+
+ <!-- Nested composition (e.g. a motion graphic or title sequence) -->
+ <div id="el-5" data-composition-id="intro-anim" data-start="0" data-track-index="3">
+ <!-- its own clips, timeline, and script -->
+ <script src="intro-anim.js"></script>
+ </div>
+</div>
+```
+
+> Note: `data-width` and `data-height` are only required on the **root** composition. Nested compositions inherit the viewport dimensions.
+
+## Clip Types
+
+A clip is any discrete block on the timeline. We represent clips as HTML elements and apply data-attributes to describe them.
+
+- `<video>` — Video clips, B-roll, A-roll
+- `<img>` — Static images, overlays
+- `<audio>` — Music, sound effects
+- `<div data-composition-id="...">` — Nested compositions (animations, grouped sequences)
+
+## HTML Attributes
+
+### All Clips
+
+- `id` — Unique identifier (e.g., "el-1")
+- `data-start` — Start time in seconds, or a clip `id` reference. See [Relative Timing](#relative-timing).
+- `data-duration` — Duration in seconds. Required for `<img>` clips. Optional for `<video>` and `<audio>` (defaults to the source media's full duration). Not used on compositions.
+- `data-track-index` — Timeline track number. Tracks serve two purposes: they determine visual layering (higher tracks render in front) and they group clips into rows on the timeline. Clips on the same track **cannot overlap in time**.
+
+### Media Clips (video, audio)
+
+- `data-media-start` — (optional) Playback begins at this time in the source file, in seconds. Defaults to `0`.
+
+### Composition Clips
+
+- `data-composition-id` — Unique composition ID
+
+> Compositions do **not** use `data-duration`. Their duration is determined by their GSAP timeline.
+
+## Relative Timing
+
+Instead of calculating absolute start times, a clip can reference another clip's `id` in its `data-start` attribute. This means "start when that clip ends." The referenced clip must be in the same composition and must have a known duration (either an explicit `data-duration` or an inferred duration from the source media).
+
+### Basic Sequential Clips
+
+```html
+<video id="intro" data-start="0" data-duration="10" data-track-index="0" src="..."></video>
+<video id="main" data-start="intro" data-duration="20" data-track-index="0" src="..."></video>
+<video id="outro" data-start="main" data-duration="5" data-track-index="0" src="..."></video>
+```
+
+`main` resolves to second 10, `outro` resolves to second 30. If `intro`'s duration changes to 15, `main` and `outro` shift automatically.
+
+### Offsets (gaps and overlaps)
+
+Add `+ N` or `- N` after the ID to offset from the end of the referenced clip:
+
+```html
+<!-- intro ends at 10. "intro + 2" = 10 + 2 = starts at second 12 (2s gap) -->
+<video id="scene-a" data-start="intro + 2" data-duration="20" data-track-index="0" src="..."></video>
+
+<!-- intro ends at 10. "intro - 0.5" = 10 - 0.5 = starts at second 9.5 (0.5s overlap for crossfade) -->
+<!-- Different track because clips on the same track cannot overlap -->
+<video id="scene-b" data-start="intro - 0.5" data-duration="20" data-track-index="1" src="..."></video>
+```
+
+### Rules
+
+- **Same composition only** — references resolve within the clip's parent composition
+- **No circular references** — A cannot start after B if B starts after A
+- **Referenced clip must have a known duration** — the system needs a known end time to resolve the reference (either explicit `data-duration` or inferred from source media)
+- **Parsing** — if the value is a valid number, it is absolute seconds; otherwise it is parsed as `<id>`, `<id> + <number>`, or `<id> - <number>`
+
+## Video Clips
+
+Full-screen or positioned video clips. Videos sync their playback to the timeline position.
+
+```html
+<video
+ id="el-1"
+ data-start="0"
+ data-duration="15"
+ data-track-index="0"
+ src="./assets/video.mp4"
+></video>
+```
+
+- `data-media-start` — Playback begins at this time in the source video file (seconds). Default: `0`.
+- `data-duration` — (optional) How long the clip occupies on the timeline, in seconds. Playback runs from `data-media-start` for up to `data-duration` seconds. If the source media runs out before `data-duration` elapses, playback naturally stops (the clip remains mounted showing the last frame). If omitted, defaults to the remaining duration of the source file from `data-media-start`.
+
+## Image Clips
+
+Static images that appear for a duration.
+
+```html
+<img
+ id="el-2"
+ data-start="5"
+ data-duration="4"
+ data-track-index="1"
+ src="./assets/video.mp4"
+/>
+```
+
+## Audio Clips
+
+Background music or sound effects. Audio clips are invisible.
+
+```html
+<audio
+ id="el-4"
+ data-start="0"
+ data-duration="30"
+ data-track-index="2"
+ src="./assets/music.mp3"
+></audio>
+```
+
+- `data-media-start` — Playback begins at this time in the source audio file (seconds). Default: `0`.
+- `data-duration` — (optional) How long the clip occupies on the timeline, in seconds. Playback runs from `data-media-start` for up to `data-duration` seconds. If the source media runs out before `data-duration` elapses, playback naturally stops (the clip remains mounted but silent). If omitted, defaults to the remaining duration of the source file from `data-media-start`.
+
+## Two Layers: Primitives and Scripts
+
+Every composition — master or sub — has the same two layers:
+
+- **HTML** — primitive clips (`video`, `img`, `audio`, nested `div[data-composition-id]`). This is the declarative structure: what plays, when, and on which track.
+- **Script** — effects, transitions, dynamic DOM, canvas, SVG — creative animation and visuals via GSAP. Scripts do **not** control media playback or clip visibility; the framework handles those via data attributes.
+
+Both layers are available to every composition. The schema defines the primitives and the timeline contract; scripts handle visual creativity on top of that.
+
+> **Warning:** Never use scripts to play/pause/seek media elements or to show/hide clips based on timing. The framework does this automatically from `data-start`, `data-duration`, and `data-media-start`. Scripts that duplicate this behavior will conflict with the framework.
+
+### Script Isolation
+
+Each composition's script is scoped to that composition. For sub-compositions, external JS files are the natural way to keep them self-contained and reusable:
+
+```html
+<div id="el-5" data-composition-id="intro-anim" data-start="0" data-track-index="2">
+ <script src="intro-anim.js"></script>
+</div>
+```
+
+Inline scripts are fine when the script belongs to that composition. The JS file itself is the documentation for what a composition does — the schema doesn't need to describe its internals.
+
+The only required file is `index.html`. Every composition must have at least a script to create and register its GSAP timeline.
+
+### Top-Level Composition
+
+The top-level composition is the `index.html` entry point. It acts as the conductor — sequencing clips and placing sub-composition timelines into an overall master timeline. It can technically do anything in its script, but its primary purpose is high-level orchestration. Any composition can serve as a top-level composition or be nested into another — there is no structural difference.
+
+```html
+<div id="comp-1" data-composition-id="my-video" data-start="0" data-width="1920" data-height="1080">
+ <video id="el-1" data-start="0" data-duration="10" data-track-index="0" src="..."></video>
+ <video id="el-2" data-start="el-1" data-duration="8" data-track-index="0" src="..."></video>
+ <img id="el-3" data-start="5" data-duration="4" data-track-index="1" src="..." />
+ <audio id="el-4" data-start="0" data-duration="30" data-track-index="2" src="..." />
+
+ <div id="el-5" data-composition-id="intro-anim" data-start="0" data-track-index="3">
+ <script src="intro-anim.js"></script>
+ </div>
+
+ <script>
+ // Just register the timeline - framework auto-nests sub-compositions
+ const tl = gsap.timeline({ paused: true });
+ window.__timelines["my-video"] = tl;
+ </script>
+</div>
+```
+
+### Sub-Compositions
+
+Sub-compositions are a spectrum. One might simply group a few primitive clips. Another might be a fully custom program with its own HTML, CSS, and JavaScript — creating, animating, and destroying DOM however it sees fit. There are no categories or constraints on what a sub-composition does internally. All compositions default to full-screen within the viewport. The only rule: it must be driven by a GSAP timeline and export it.
+
+## Wrapping Dynamic Content in Compositions
+
+**Critical Rule: All visual content must live inside a composition with data attributes to appear in the timeline.**
+
+When you have dynamic or script-animated content (captions, emojis, overlays, text animations), wrap them in a composition element with `data-start`, `data-duration` (or let the timeline determine duration), and `data-track-index`. The children inside can be freely created and animated via JavaScript—they don't need individual data attributes.
+
+### Wrong: Dynamic content outside a composition
+
+```html
+<!-- BAD: captions-container is not a composition - won't appear in timeline -->
+<div id="ui-layer">
+ <div id="captions-container">
+ <!-- Dynamically created caption groups via JS -->
+ </div>
+ <div class="emoji" id="emoji-1">🤩</div>
+</div>
+
+<script>
+ // These animations work visually but elements don't appear in timeline
+ tl.to(".caption-group", { opacity: 1 }, 0.5);
+ tl.to("#emoji-1", { scale: 1.2 }, 2);
+</script>
+```
+
+### Correct: Dynamic content wrapped in compositions
+
+```html
+<!-- GOOD: Each logical group is a composition that appears in timeline -->
+<div id="captions-comp" data-composition-id="captions" data-start="0" data-track-index="5">
+ <!-- Children created/animated by script - no data attributes needed -->
+ <div id="captions-container"></div>
+ <script>
+ const captionTL = gsap.timeline({ paused: true });
+ // Dynamically create and animate caption groups...
+ window.__timelines["captions"] = captionTL;
+ </script>
+</div>
+
+<div id="emojis-comp" data-composition-id="emojis" data-start="0" data-track-index="6">
+ <div class="emoji" id="emoji-1">🤩</div>
+ <div class="emoji" id="emoji-2">🏔️</div>
+ <script>
+ const emojiTL = gsap.timeline({ paused: true });
+ emojiTL.to("#emoji-1", { opacity: 1, scale: 1.2 }, 2);
+ emojiTL.to("#emoji-2", { opacity: 1, scale: 1.2 }, 4);
+ window.__timelines["emojis"] = emojiTL;
+ </script>
+</div>
+```
+
+### When to create separate compositions
+
+- **Captions**: One composition for all captions, script manages word groups
+- **Emojis/Stickers**: One composition for the emoji layer
+- **Hooks/Titles**: One composition per distinct title sequence
+- **Overlays**: Group related overlays into compositions by purpose
+
+The composition appears in the timeline with its start time and duration (determined by its GSAP timeline). Everything inside is managed by the script but inherits the composition's timeline position.
+
+## Timeline Contract
+
+The framework initializes `window.__timelines = {}` before any scripts run. Every composition **must** have a script that creates a GSAP timeline and registers it:
+
+```js
+const tl = gsap.timeline({ paused: true });
+// ... add tweens, nested timelines, etc.
+window.__timelines["<data-composition-id>"] = tl;
+```
+
+### Rules
+
+- **Every composition needs a script** — at minimum, to create and register its timeline. A composition without a script has no timeline and cannot participate in the hierarchy.
+- **All timelines start paused** — create timelines with `{ paused: true }`. The top-level timeline is controlled externally by the frontend player or renderer.
+- **Framework auto-nests sub-timelines** — you do **not** need to manually add sub-composition timelines to the master timeline. The framework automatically nests any timeline registered in `window.__timelines` into its parent based on the composition's `data-start` attribute.
+- **Duration comes from the timeline** — a composition's duration is `tl.duration()`. The timeline is the sole source of truth; there is no `data-duration` on compositions.
+
+### What NOT to do
+
+```js
+// UNNECESSARY - the framework does this automatically
+if (window.__timelines["captions"]) {
+ masterTL.add(window.__timelines["captions"], 0);
+}
+```
+
+Just register your timeline in `window.__timelines` and the framework handles the rest.
+
+## Output Checklist
+
+- [ ] Root composition has `data-width` and `data-height` attributes
+- [ ] `window.__timelines` given all compositions' timelines
+- [ ] Complex/dynamic animations are handled by scripts in compositions
diff --git a/packages/core/package.json b/packages/core/package.json
new file mode 100644
index 0000000000..92590801dc
--- /dev/null
+++ b/packages/core/package.json
@@ -0,0 +1,83 @@
+{
+ "name": "@hyperframes/core",
+ "version": "0.1.0",
+ "type": "module",
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "exports": {
+ ".": {
+ "import": "./src/index.ts",
+ "types": "./src/index.ts"
+ },
+ "./lint": {
+ "import": "./src/lint/index.ts",
+ "types": "./src/lint/index.ts"
+ },
+ "./compiler": {
+ "import": "./src/compiler/index.ts",
+ "types": "./src/compiler/index.ts"
+ },
+ "./runtime": "./dist/hyperframe.runtime.iife.js"
+ },
+ "files": [
+ "dist",
+ "docs",
+ "README.md"
+ ],
+ "publishConfig": {
+ "access": "public",
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "import": "./dist/index.js",
+ "types": "./dist/index.d.ts"
+ },
+ "./lint": {
+ "import": "./dist/lint/index.js",
+ "types": "./dist/lint/index.d.ts"
+ },
+ "./compiler": {
+ "import": "./dist/compiler/index.js",
+ "types": "./dist/compiler/index.d.ts"
+ },
+ "./runtime": "./dist/hyperframe.runtime.iife.js"
+ }
+ },
+ "scripts": {
+ "build": "tsc && pnpm build:hyperframes-runtime",
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "test:coverage": "vitest run --coverage",
+ "typecheck": "tsc --noEmit",
+ "lint:runtime-preview-guards": "tsx scripts/lint-runtime-preview-guards.ts",
+ "build:hyperframes-runtime": "tsx scripts/build-hyperframes-runtime-artifact.ts",
+ "build:hyperframes-runtime:modular": "SANDBOX_RUNTIME_VARIANT=modular tsx scripts/build-hyperframes-runtime-artifact.ts",
+ "build:hyperframe-runtime": "tsx scripts/build-hyperframes-runtime-artifact.ts",
+
+ "test:hyperframe-runtime-contract": "tsx scripts/test-hyperframe-runtime-contract.ts",
+ "test:hyperframe-runtime-behavior": "tsx scripts/test-hyperframe-runtime-behavior.ts",
+ "test:hyperframe-runtime-seek": "tsx scripts/test-hyperframe-runtime-seek.ts",
+ "test:hyperframe-runtime-duration-guards": "tsx scripts/test-hyperframe-runtime-duration-guards.ts",
+ "test:hyperframe-runtime-parity": "tsx scripts/test-hyperframe-runtime-parity.ts",
+ "test:hyperframe-runtime-security": "tsx scripts/test-hyperframe-runtime-security.ts",
+ "test:hyperframe-linter": "tsx scripts/test-hyperframe-linter.ts",
+ "test:hyperframe-runtime-ci": "pnpm build:hyperframes-runtime && pnpm test:hyperframe-runtime-contract && pnpm test:hyperframe-runtime-behavior && pnpm test:hyperframe-runtime-seek && pnpm test:hyperframe-runtime-duration-guards && pnpm test:hyperframe-runtime-parity && pnpm test:hyperframe-runtime-security",
+ "check:hyperframe-html": "tsx scripts/check-hyperframe-static.ts",
+ "debug:timeline": "tsx scripts/debug-timeline.ts",
+ "prepublishOnly": "pnpm build"
+ },
+ "optionalDependencies": {
+ "cheerio": "^1.2.0",
+ "esbuild": "^0.25.12"
+ },
+ "devDependencies": {
+ "@types/jsdom": "^28.0.0",
+ "@types/node": "^24.10.13",
+ "@vitest/coverage-v8": "^3.2.4",
+ "jsdom": "^29.0.0",
+ "tsx": "^4.21.0",
+ "typescript": "^5.0.0",
+ "vitest": "^3.2.4"
+ }
+}
diff --git a/packages/core/scripts/build-hyperframes-runtime-artifact.ts b/packages/core/scripts/build-hyperframes-runtime-artifact.ts
new file mode 100644
index 0000000000..bf556cfc1b
--- /dev/null
+++ b/packages/core/scripts/build-hyperframes-runtime-artifact.ts
@@ -0,0 +1,62 @@
+import { createHash } from "node:crypto";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { buildSync } from "esbuild";
+import {
+ HYPERFRAME_RUNTIME_ARTIFACTS,
+ HYPERFRAME_RUNTIME_CONTRACT,
+ loadHyperframeRuntimeSource,
+} from "../src/inline-scripts/hyperframe";
+
+const thisDir = dirname(fileURLToPath(import.meta.url));
+const distDir = resolve(thisDir, "../dist");
+const iifePath = resolve(distDir, HYPERFRAME_RUNTIME_ARTIFACTS.iife);
+const esmPath = resolve(distDir, HYPERFRAME_RUNTIME_ARTIFACTS.esm);
+const manifestPath = resolve(distDir, HYPERFRAME_RUNTIME_ARTIFACTS.manifest);
+
+const runtimeSource = `${loadHyperframeRuntimeSource()}\n`;
+const runtimeSha256 = createHash("sha256").update(runtimeSource, "utf8").digest("hex");
+const buildId = process.env.HYPERFRAME_RUNTIME_BUILD_ID?.trim() || "dev";
+const runtimeEntryPath = resolve(thisDir, "../src/runtime/entry.ts");
+const esmBuild = buildSync({
+ entryPoints: [runtimeEntryPath],
+ bundle: true,
+ write: false,
+ platform: "browser",
+ format: "esm",
+ target: ["es2020"],
+ minify: true,
+ legalComments: "none",
+});
+const esmSource = `${esmBuild.outputFiles[0]?.text ?? ""}\n`;
+
+const manifest = {
+ version: process.env.HYPERFRAME_RUNTIME_VERSION?.trim() || "0.1.0",
+ buildId,
+ sha256: runtimeSha256,
+ artifacts: {
+ iife: HYPERFRAME_RUNTIME_ARTIFACTS.iife,
+ esm: HYPERFRAME_RUNTIME_ARTIFACTS.esm,
+ },
+ contract: HYPERFRAME_RUNTIME_CONTRACT,
+};
+
+mkdirSync(distDir, { recursive: true });
+writeFileSync(iifePath, runtimeSource, "utf8");
+writeFileSync(esmPath, esmSource, "utf8");
+writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
+
+console.log(
+ JSON.stringify({
+ event: "hyperframe_runtime_artifacts_generated",
+ buildId,
+ distDir,
+ iifePath,
+ esmPath,
+ manifestPath,
+ sourceBytes: Buffer.byteLength(runtimeSource, "utf8"),
+ esmBytes: Buffer.byteLength(esmSource, "utf8"),
+ sha256: runtimeSha256,
+ }),
+);
diff --git a/packages/core/scripts/check-hyperframe-static.ts b/packages/core/scripts/check-hyperframe-static.ts
new file mode 100644
index 0000000000..6fc4b0a540
--- /dev/null
+++ b/packages/core/scripts/check-hyperframe-static.ts
@@ -0,0 +1,65 @@
+import fs from "node:fs";
+import path from "node:path";
+import { lintHyperframeHtml } from "../src/lint/hyperframeLinter";
+import type { HyperframeLintResult } from "../src/lint/types";
+
+function formatHumanOutput(result: HyperframeLintResult, resolvedPath: string): string {
+ const lines = [
+ result.ok
+ ? `PASS ${resolvedPath} (${result.warningCount} warning${result.warningCount === 1 ? "" : "s"})`
+ : `FAIL ${resolvedPath} (${result.errorCount} error${result.errorCount === 1 ? "" : "s"}, ${result.warningCount} warning${result.warningCount === 1 ? "" : "s"})`,
+ ];
+
+ for (const finding of result.findings) {
+ lines.push(`- [${finding.severity.toUpperCase()}] ${finding.code}: ${finding.message}`);
+ if (finding.selector) {
+ lines.push(` selector: ${finding.selector}`);
+ }
+ if (finding.elementId) {
+ lines.push(` elementId: ${finding.elementId}`);
+ }
+ if (finding.fixHint) {
+ lines.push(` fix: ${finding.fixHint}`);
+ }
+ }
+
+ return lines.join("\n");
+}
+
+function main() {
+ const args = process.argv.slice(2);
+ const normalizedArgs = args[0] === "--" ? args.slice(1) : args;
+ const jsonOutput = normalizedArgs.includes("--json");
+ const positionalArgs = normalizedArgs.filter((arg) => arg !== "--json");
+ const inputPath = positionalArgs[0];
+ if (!inputPath) {
+ console.error(
+ "Usage: pnpm check:hyperframe-html [--json] <path-to-html>\nExample: pnpm check:hyperframe-html core/src/tests/broken-video.html",
+ );
+ process.exit(2);
+ }
+
+ const resolvedPath = path.resolve(process.cwd(), inputPath);
+ if (!fs.existsSync(resolvedPath)) {
+ console.error(`File not found: ${resolvedPath}`);
+ process.exit(2);
+ }
+
+ const html = fs.readFileSync(resolvedPath, "utf-8");
+ const result = lintHyperframeHtml(html, { filePath: resolvedPath });
+
+ if (jsonOutput) {
+ console.log(JSON.stringify(result, null, 2));
+ process.exit(result.ok ? 0 : 1);
+ }
+
+ if (result.ok) {
+ console.log(formatHumanOutput(result, resolvedPath));
+ process.exit(0);
+ }
+
+ console.error(formatHumanOutput(result, resolvedPath));
+ process.exit(1);
+}
+
+main();
diff --git a/packages/core/scripts/debug-timeline.ts b/packages/core/scripts/debug-timeline.ts
new file mode 100644
index 0000000000..4a5cd48aef
--- /dev/null
+++ b/packages/core/scripts/debug-timeline.ts
@@ -0,0 +1,297 @@
+import fs from "node:fs";
+import path from "node:path";
+
+type AttrMap = Record<string, string>;
+
+type ParsedTag = {
+ tagName: string;
+ attrs: AttrMap;
+ raw: string;
+};
+
+type TimelineClip = {
+ id: string | null;
+ label: string;
+ start: number;
+ duration: number;
+ track: number;
+ kind: "video" | "audio" | "image" | "element";
+ tagName: string | null;
+ compositionId: string | null;
+ compositionSrc: string | null;
+ assetUrl: string | null;
+ durationSource: "deterministic" | "fallback";
+};
+
+type TimelinePayload = {
+ source: "hf-preview";
+ type: "timeline";
+ durationInFrames: number;
+ clips: TimelineClip[];
+ scenes: [];
+ compositionWidth: number;
+ compositionHeight: number;
+};
+
+function parseNum(value: string | null | undefined): number | null {
+ if (value == null) return null;
+ const parsed = Number.parseFloat(String(value));
+ return Number.isFinite(parsed) ? parsed : null;
+}
+
+function parseArgs() {
+ const args = process.argv.slice(2);
+ const normalizedArgs = args[0] === "--" ? args.slice(1) : args;
+ const inputPath = normalizedArgs[0];
+ let forcedFps: number | null = null;
+ let forcedMaxDuration: number | null = null;
+ for (let i = 1; i < normalizedArgs.length; i += 1) {
+ const arg = normalizedArgs[i];
+ if (arg === "--fps" && normalizedArgs[i + 1]) {
+ forcedFps = parseNum(normalizedArgs[i + 1]);
+ i += 1;
+ continue;
+ }
+ if (arg === "--max-duration" && normalizedArgs[i + 1]) {
+ forcedMaxDuration = parseNum(normalizedArgs[i + 1]);
+ i += 1;
+ }
+ }
+ return { inputPath, forcedFps, forcedMaxDuration };
+}
+
+function parseAttributes(rawAttrs: string): AttrMap {
+ const attrs: AttrMap = {};
+ const attrRegex = /([^\s=/>]+)\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/g;
+ let match: RegExpExecArray | null = null;
+ while (true) {
+ match = attrRegex.exec(rawAttrs);
+ if (!match) break;
+ const key = match[1];
+ const value = match[3] ?? match[4] ?? match[5] ?? "";
+ attrs[key] = value;
+ }
+ return attrs;
+}
+
+function parseTags(html: string): ParsedTag[] {
+ const tags: ParsedTag[] = [];
+ const tagRegex = /<([a-zA-Z][\w:-]*)([^>]*)>/g;
+ let match: RegExpExecArray | null = null;
+ while (true) {
+ match = tagRegex.exec(html);
+ if (!match) break;
+ const raw = match[0];
+ if (raw.startsWith("</") || raw.startsWith("<!")) continue;
+ const tagName = String(match[1] || "").toLowerCase();
+ if (!tagName) continue;
+ tags.push({
+ tagName,
+ raw,
+ attrs: parseAttributes(match[2] || ""),
+ });
+ }
+ return tags;
+}
+
+function extractWindowNumber(html: string, key: string): number | null {
+ const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const regex = new RegExp(`${escapedKey}\\s*=\\s*([0-9]+(?:\\.[0-9]+)?)`, "i");
+ const match = html.match(regex);
+ if (!match) return null;
+ return parseNum(match[1]);
+}
+
+function normalizeDurationSeconds(
+ rawDuration: number | null,
+ fallbackDuration: number | null,
+ maxDuration: number,
+): number {
+ const safeFallback = fallbackDuration != null && fallbackDuration > 0 ? fallbackDuration : 0;
+ const safeRaw = rawDuration != null && Number.isFinite(rawDuration) && rawDuration > 0 ? rawDuration : 0;
+ if (safeRaw > 0) return Math.min(safeRaw, maxDuration);
+ if (safeFallback > 0) return Math.min(safeFallback, maxDuration);
+ return 0;
+}
+
+function shouldIncludeTimelineNode(tag: ParsedTag, rootCompositionId: string | null): boolean {
+ const attrs = tag.attrs;
+ if (attrs["data-composition-id"] && rootCompositionId && attrs["data-composition-id"] === rootCompositionId) {
+ return false;
+ }
+ if (tag.tagName === "script" || tag.tagName === "style" || tag.tagName === "link" || tag.tagName === "meta") {
+ return false;
+ }
+ if ((attrs.class || "").split(/\s+/).includes("__preview_render_frame__")) return false;
+ if (attrs["data-start"] != null) return true;
+ if (attrs["data-track-index"] != null) return true;
+ if (attrs["data-composition-src"] != null) return true;
+ if (attrs["data-composition-id"] != null) return true;
+ return tag.tagName === "video" || tag.tagName === "audio" || tag.tagName === "img";
+}
+
+function inferClipDuration(tag: ParsedTag, start: number, maxDuration: number): number | null {
+ const attrs = tag.attrs;
+ const durationAttr = parseNum(attrs["data-duration"]);
+ if (durationAttr != null && durationAttr > 0) return normalizeDurationSeconds(durationAttr, null, maxDuration);
+
+ const endAttr = parseNum(attrs["data-end"]);
+ if (endAttr != null && endAttr > start) {
+ return normalizeDurationSeconds(endAttr - start, null, maxDuration);
+ }
+
+ if (tag.tagName === "video" || tag.tagName === "audio") {
+ const sourceDuration = parseNum(attrs["data-source-duration"]);
+ const playbackStart = parseNum(attrs["data-playback-start"]) ?? parseNum(attrs["data-playbackStart"]) ?? 0;
+ if (sourceDuration != null && sourceDuration > 0) {
+ return normalizeDurationSeconds(Math.max(0, sourceDuration - playbackStart), null, maxDuration);
+ }
+ }
+
+ if (attrs["data-composition-id"]) {
+ const sourceDuration = parseNum(attrs["data-source-duration"]);
+ if (sourceDuration != null && sourceDuration > 0) {
+ return normalizeDurationSeconds(sourceDuration, null, maxDuration);
+ }
+ }
+
+ return null;
+}
+
+function resolveNodeAssetUrl(tag: ParsedTag): string | null {
+ const attrs = tag.attrs;
+ return (
+ attrs.src ??
+ attrs["data-src"] ??
+ attrs["data-asset-src"] ??
+ attrs["data-video-src"] ??
+ attrs["data-image-src"] ??
+ null
+ );
+}
+
+function resolveRootTag(tags: ParsedTag[]): ParsedTag | null {
+ const explicitRoot = tags.find((tag) => tag.attrs["data-composition-id"] === "master");
+ if (explicitRoot) return explicitRoot;
+ return tags.find((tag) => tag.attrs["data-composition-id"] != null) ?? null;
+}
+
+function main() {
+ const { inputPath, forcedFps, forcedMaxDuration } = parseArgs();
+ if (!inputPath) {
+ console.error("Usage: pnpm debug:timeline <path-to-html> [--fps 30] [--max-duration 1800]");
+ process.exit(2);
+ }
+
+ const resolvedPath = path.resolve(process.cwd(), inputPath);
+ if (!fs.existsSync(resolvedPath)) {
+ console.error(`File not found: ${resolvedPath}`);
+ process.exit(2);
+ }
+
+ const html = fs.readFileSync(resolvedPath, "utf-8");
+ const tags = parseTags(html);
+ const root = resolveRootTag(tags);
+ const rootCompositionId = root?.attrs["data-composition-id"] ?? null;
+
+ const maxDuration =
+ (forcedMaxDuration != null && forcedMaxDuration > 0
+ ? forcedMaxDuration
+ : extractWindowNumber(html, "window.__HF_MAX_DURATION_SEC")) ?? 1800;
+ const canonicalFps =
+ (forcedFps != null && forcedFps > 0
+ ? forcedFps
+ : (parseNum(root?.attrs["data-fps"]) ?? extractWindowNumber(html, "window.__HF_FPS"))) ?? 30;
+
+ const rootDurationRaw =
+ parseNum(root?.attrs["data-composition-duration"]) ??
+ parseNum(root?.attrs["data-duration"]) ??
+ parseNum(tags.find((tag) => tag.tagName === "html")?.attrs["data-composition-duration"] ?? null);
+ const rootDuration = normalizeDurationSeconds(rootDurationRaw, null, maxDuration);
+
+ const nodes = tags.filter((tag) => shouldIncludeTimelineNode(tag, rootCompositionId));
+ const clips: TimelineClip[] = [];
+ let maxEnd = 0;
+ let unresolvedClipCount = 0;
+
+ for (let i = 0; i < nodes.length; i += 1) {
+ const node = nodes[i];
+ const attrs = node.attrs;
+ const start = Math.max(0, parseNum(attrs["data-start"]) ?? 0);
+ const inferredDuration = inferClipDuration(node, start, maxDuration);
+ const hasDeterministicDuration = inferredDuration != null && inferredDuration > 0;
+ let duration = hasDeterministicDuration ? normalizeDurationSeconds(inferredDuration, 0, maxDuration) : 0;
+ let durationSource: "deterministic" | "fallback" = "deterministic";
+ if (duration <= 0 && rootDuration > start) {
+ duration = normalizeDurationSeconds(rootDuration - start, 0, maxDuration);
+ durationSource = "fallback";
+ }
+ if (duration <= 0) {
+ unresolvedClipCount += 1;
+ continue;
+ }
+ if (hasDeterministicDuration) {
+ const end = start + duration;
+ if (end > maxEnd) maxEnd = end;
+ }
+ const kind =
+ node.tagName === "video"
+ ? "video"
+ : node.tagName === "audio"
+ ? "audio"
+ : node.tagName === "img"
+ ? "image"
+ : "element";
+ const trackRaw = parseNum(attrs["data-track-index"]);
+ const track = trackRaw != null && Number.isFinite(trackRaw) ? Math.floor(trackRaw) : i;
+ clips.push({
+ id: attrs.id ?? null,
+ label: attrs["data-label"] ?? attrs["aria-label"] ?? attrs.id ?? kind,
+ start,
+ duration,
+ track,
+ kind,
+ tagName: node.tagName || null,
+ compositionId: attrs["data-composition-id"] ?? null,
+ compositionSrc: attrs["data-composition-src"] ?? null,
+ assetUrl: resolveNodeAssetUrl(node),
+ durationSource,
+ });
+ }
+
+ let effectiveDuration = 0;
+ if (maxEnd > 0) effectiveDuration = normalizeDurationSeconds(maxEnd, 0, maxDuration);
+ if (effectiveDuration <= 0) effectiveDuration = normalizeDurationSeconds(rootDuration, 1, maxDuration);
+ if (effectiveDuration <= 0) effectiveDuration = 1;
+
+ const compositionWidth = parseNum(root?.attrs["data-width"]) ?? 1920;
+ const compositionHeight = parseNum(root?.attrs["data-height"]) ?? 1080;
+ const payload: TimelinePayload = {
+ source: "hf-preview",
+ type: "timeline",
+ durationInFrames: Math.max(1, Math.round(effectiveDuration * canonicalFps)),
+ clips,
+ scenes: [],
+ compositionWidth,
+ compositionHeight,
+ };
+
+ const output = {
+ file: resolvedPath,
+ debug: {
+ canonicalFps,
+ maxDurationSeconds: maxDuration,
+ rootCompositionId,
+ rootDurationSeconds: rootDuration,
+ deterministicMaxEndSeconds: maxEnd,
+ effectiveDurationSeconds: effectiveDuration,
+ unresolvedClipCount,
+ clipCount: clips.length,
+ },
+ payload,
+ };
+
+ console.log(JSON.stringify(output, null, 2));
+}
+
+main();
diff --git a/packages/core/scripts/lint-runtime-preview-guards.ts b/packages/core/scripts/lint-runtime-preview-guards.ts
new file mode 100644
index 0000000000..fdfc481557
--- /dev/null
+++ b/packages/core/scripts/lint-runtime-preview-guards.ts
@@ -0,0 +1,119 @@
+import fs from "node:fs";
+import path from "node:path";
+
+type GuardSpec = {
+ id: string;
+ description: string;
+ filePath: string;
+ pattern: RegExp;
+};
+
+type GuardCheckResult = {
+ passed: GuardSpec[];
+ failed: GuardSpec[];
+};
+
+const GUARD_SPECS: GuardSpec[] = [
+ {
+ id: "external_compositions_gate",
+ description: "Do not bind timelines before external compositions are loaded",
+ filePath: "src/runtime/init.ts",
+ pattern: /if\s*\(\s*!externalCompositionsReady\s*\)\s*return\s+false;/,
+ },
+ {
+ id: "usable_timeline_gate",
+ description: "Skip rebinding when current timeline is already usable",
+ filePath: "src/runtime/init.ts",
+ pattern: /if\s*\(\s*currentTimeline\s*&&\s*currentTimelineUsable\s*\)\s*return\s+false;/,
+ },
+ {
+ id: "child_timeline_activation",
+ description: "Force root child timelines active before composition binding",
+ filePath: "src/runtime/init.ts",
+ pattern: /timelineWithPaused\.paused\(false\)/,
+ },
+ {
+ id: "root_unusable_fallback",
+ description: "Fallback to composite timeline when root duration is unusable",
+ filePath: "src/runtime/init.ts",
+ pattern:
+ /if\s*\(\s*!isUsableTimelineDuration\(rootDurationSeconds\)\s*&&\s*rootChildCandidates\.length\s*>\s*0\s*\)/,
+ },
+ {
+ id: "loop_guard_rebind",
+ description: "Enable loop guard based timeline rebinding",
+ filePath: "src/runtime/init.ts",
+ pattern: /if\s*\(\s*rebindTimelineFromResolution\(resolution,\s*"loop_guard"\)\s*\)/,
+ },
+ {
+ id: "early_play_rebind_hold",
+ description: "Hold rebinding during first playback seconds",
+ filePath: "src/runtime/init.ts",
+ pattern: /shouldHoldRebindDuringEarlyPlay/,
+ },
+ {
+ id: "external_script_ordering",
+ description: "Inject external composition scripts with deterministic ordering",
+ filePath: "src/runtime/compositionLoader.ts",
+ pattern: /injectedScript\.async\s*=\s*false;/,
+ },
+ {
+ id: "external_script_load_wait",
+ description: "Await external composition script load before continuing",
+ filePath: "src/runtime/compositionLoader.ts",
+ pattern: /await\s+waitForExternalScriptLoad\(injectedScript\);/,
+ },
+];
+
+function resolveFilePath(relativePath: string): string {
+ return path.resolve(process.cwd(), relativePath);
+}
+
+function checkGuards(guards: GuardSpec[]): GuardCheckResult {
+ const passed: GuardSpec[] = [];
+ const failed: GuardSpec[] = [];
+
+ for (const guard of guards) {
+ const absolutePath = resolveFilePath(guard.filePath);
+ if (!fs.existsSync(absolutePath)) {
+ failed.push(guard);
+ continue;
+ }
+ const content = fs.readFileSync(absolutePath, "utf8");
+ if (guard.pattern.test(content)) {
+ passed.push(guard);
+ } else {
+ failed.push(guard);
+ }
+ }
+
+ return { passed, failed };
+}
+
+function main(): void {
+ const result = checkGuards(GUARD_SPECS);
+ if (result.failed.length === 0) {
+ console.log(
+ JSON.stringify({
+ event: "runtime_preview_guards_lint_passed",
+ checkedGuards: GUARD_SPECS.length,
+ }),
+ );
+ return;
+ }
+
+ console.error(
+ JSON.stringify({
+ event: "runtime_preview_guards_lint_failed",
+ checkedGuards: GUARD_SPECS.length,
+ missingGuards: result.failed.map((guard) => ({
+ id: guard.id,
+ filePath: guard.filePath,
+ description: guard.description,
+ })),
+ }),
+ );
+ process.exit(1);
+}
+
+main();
diff --git a/packages/core/scripts/test-hyperframe-linter.ts b/packages/core/scripts/test-hyperframe-linter.ts
new file mode 100644
index 0000000000..6aa488c556
--- /dev/null
+++ b/packages/core/scripts/test-hyperframe-linter.ts
@@ -0,0 +1,89 @@
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { lintHyperframeHtml } from "../src/lint/hyperframeLinter";
+
+const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..");
+
+function testCleanFixturePasses() {
+ const fixturePath = path.join(ROOT, "src/tests/chat-project-9/index.html");
+ const html = fs.readFileSync(fixturePath, "utf8");
+ const result = lintHyperframeHtml(html, { filePath: fixturePath });
+
+ assert.equal(result.ok, true, "chat-project-9 should pass without lint errors");
+ assert.equal(result.errorCount, 0, "chat-project-9 should have zero lint errors");
+}
+
+function testDetectsMissingCompositionHostId() {
+ const html = `
+ <html>
+ <body>
+ <div id="root" data-width="1080" data-height="1920">
+ <div data-composition-src="compositions/overlays.html"></div>
+ </div>
+ <script>
+ window.__timelines = {};
+ const tl = gsap.timeline({ paused: true });
+ window.__timelines["root"] = tl;
+ </script>
+ </body>
+ </html>
+ `;
+
+ const result = lintHyperframeHtml(html);
+ const codes = result.findings.map((finding) => finding.code);
+
+ assert.equal(result.ok, false, "missing composition ids should fail lint");
+ assert.ok(codes.includes("root_missing_composition_id"));
+ assert.ok(codes.includes("host_missing_composition_id"));
+}
+
+function testDetectsOverlappingGsapTweens() {
+ const html = `
+ <html>
+ <body>
+ <div id="main" data-composition-id="main" data-width="1080" data-height="1920">
+ <div id="frame"></div>
+ </div>
+ <script>
+ window.__timelines = {};
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#frame", { y: 15, duration: 2.5, repeat: 1, yoyo: true }, 1.5);
+ tl.to("#frame", { y: 400, duration: 1.2 }, 4.5);
+ window.__timelines["main"] = tl;
+ </script>
+ </body>
+ </html>
+ `;
+
+ const result = lintHyperframeHtml(html);
+ const overlapFinding = result.findings.find((finding) => finding.code === "overlapping_gsap_tweens");
+
+ assert.ok(overlapFinding, "expected an overlapping GSAP tween warning");
+ assert.equal(overlapFinding?.severity, "warning");
+}
+
+function testCliJsonOutput() {
+ const fixturePath = path.join(ROOT, "src/tests/chat-project-9/index.html");
+ const tsxBin = path.join(ROOT, "node_modules/.bin/tsx");
+ const stdout = execFileSync(tsxBin, ["scripts/check-hyperframe-static.ts", "--json", fixturePath], {
+ cwd: ROOT,
+ encoding: "utf8",
+ });
+ const payload = JSON.parse(stdout);
+
+ assert.equal(payload.ok, true);
+ assert.equal(typeof payload.errorCount, "number");
+ assert.ok(Array.isArray(payload.findings));
+}
+
+function main() {
+ testCleanFixturePasses();
+ testDetectsMissingCompositionHostId();
+ testDetectsOverlappingGsapTweens();
+ testCliJsonOutput();
+ console.log("hyperframe linter tests passed");
+}
+
+main();
diff --git a/packages/core/scripts/test-hyperframe-runtime-behavior.ts b/packages/core/scripts/test-hyperframe-runtime-behavior.ts
new file mode 100644
index 0000000000..0ac5325f9f
--- /dev/null
+++ b/packages/core/scripts/test-hyperframe-runtime-behavior.ts
@@ -0,0 +1,32 @@
+import { buildHyperframesRuntimeScript } from "../src/inline-scripts/hyperframesRuntime.engine";
+
+function assert(condition: unknown, message: string): void {
+ if (!condition) {
+ throw new Error(message);
+ }
+}
+
+const baseline = buildHyperframesRuntimeScript();
+const parityEnabled = buildHyperframesRuntimeScript({ defaultParityMode: true });
+const parityDisabled = buildHyperframesRuntimeScript({ defaultParityMode: false });
+const withSourceUrl = buildHyperframesRuntimeScript({
+ sourceUrl: "hyperframe.runtime.iife.js",
+});
+
+assert(baseline.includes("window.__player"), "Baseline runtime should include player contract");
+assert(parityEnabled.length > 0, "Parity-enabled build should produce non-empty runtime source");
+assert(parityDisabled.length > 0, "Parity-disabled build should produce non-empty runtime source");
+assert(
+ withSourceUrl.includes("//# sourceURL=hyperframe.runtime.iife.js"),
+ "Build with sourceUrl should append sourceURL comment",
+);
+
+console.log(
+ JSON.stringify({
+ event: "hyperframe_runtime_behavior_verified",
+ baselineBytes: baseline.length,
+ parityEnabledBytes: parityEnabled.length,
+ parityDisabledBytes: parityDisabled.length,
+ sourceUrlBytes: withSourceUrl.length,
+ }),
+);
diff --git a/packages/core/scripts/test-hyperframe-runtime-contract.ts b/packages/core/scripts/test-hyperframe-runtime-contract.ts
new file mode 100644
index 0000000000..949cdfa757
--- /dev/null
+++ b/packages/core/scripts/test-hyperframe-runtime-contract.ts
@@ -0,0 +1,43 @@
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { loadHyperframeRuntimeSource } from "../src/inline-scripts/hyperframe";
+
+function assert(condition: unknown, message: string): void {
+ if (!condition) {
+ throw new Error(message);
+ }
+}
+
+const runtimeSource = loadHyperframeRuntimeSource();
+
+const requiredSnippets = [
+ "window.__player",
+ "window.__playerReady",
+ "window.__renderReady",
+ "hf-preview",
+ "hf-parent",
+ "renderSeek",
+];
+
+for (const snippet of requiredSnippets) {
+ assert(runtimeSource.includes(snippet), `Runtime contract snippet missing: ${snippet}`);
+}
+
+const scriptDir = resolve(fileURLToPath(new URL(".", import.meta.url)));
+const manifestPath = resolve(scriptDir, "../dist/hyperframe.manifest.json");
+try {
+ const manifestRaw = readFileSync(manifestPath, "utf8");
+ const manifest = JSON.parse(manifestRaw) as { artifacts?: { iife?: string; esm?: string } };
+ assert(Boolean(manifest.artifacts?.iife), "Manifest is missing iife artifact");
+ assert(Boolean(manifest.artifacts?.esm), "Manifest is missing esm artifact");
+} catch {
+ // Build may not have run yet; contract-only checks above still provide signal.
+}
+
+console.log(
+ JSON.stringify({
+ event: "hyperframe_runtime_contract_verified",
+ requiredSnippetsChecked: requiredSnippets.length,
+ }),
+);
diff --git a/packages/core/scripts/test-hyperframe-runtime-duration-guards.ts b/packages/core/scripts/test-hyperframe-runtime-duration-guards.ts
new file mode 100644
index 0000000000..55c1e6df91
--- /dev/null
+++ b/packages/core/scripts/test-hyperframe-runtime-duration-guards.ts
@@ -0,0 +1,45 @@
+import { readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+function assert(condition: unknown, message: string): void {
+ if (!condition) {
+ throw new Error(message);
+ }
+}
+
+const scriptDir = dirname(fileURLToPath(import.meta.url));
+const initPath = resolve(scriptDir, "../src/runtime/init.ts");
+const timelinePath = resolve(scriptDir, "../src/runtime/timeline.ts");
+
+const initSource = readFileSync(initPath, "utf8");
+const timelineSource = readFileSync(timelinePath, "utf8");
+
+// Guard against regressions where preview duration gets capped by earliest video.
+assert(!initSource.includes("resolveMainVideoDurationSeconds"), "init.ts should not use first-video duration helper");
+assert(
+ !initSource.includes("Math.max(0, Math.min(safeDuration, mediaFloor))"),
+ "init.ts should not hard-clamp safe duration to media floor",
+);
+assert(
+ initSource.includes("resolveMediaWindowDurationSeconds"),
+ "init.ts should compute media window duration across timed media",
+);
+
+// Timeline payload windowing should also avoid first-video truncation.
+assert(
+ !timelineSource.includes("resolveMainVideoWindowEndSeconds"),
+ "timeline.ts should not use first-video window end helper",
+);
+assert(
+ timelineSource.includes("resolveMediaWindowEndSeconds"),
+ "timeline.ts should compute media window end across timed media",
+);
+
+console.log(
+ JSON.stringify({
+ event: "hyperframe_runtime_duration_guards_verified",
+ initPath,
+ timelinePath,
+ }),
+);
diff --git a/packages/core/scripts/test-hyperframe-runtime-parity.ts b/packages/core/scripts/test-hyperframe-runtime-parity.ts
new file mode 100644
index 0000000000..e2804b6e09
--- /dev/null
+++ b/packages/core/scripts/test-hyperframe-runtime-parity.ts
@@ -0,0 +1,44 @@
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { HYPERFRAME_RUNTIME_ARTIFACTS } from "../src/inline-scripts/hyperframe";
+
+function assert(condition: unknown, message: string): void {
+ if (!condition) throw new Error(message);
+}
+
+const scriptsDir = resolve(fileURLToPath(new URL(".", import.meta.url)));
+const distDir = resolve(scriptsDir, "../dist");
+const iifePath = resolve(distDir, HYPERFRAME_RUNTIME_ARTIFACTS.iife);
+const manifestPath = resolve(distDir, HYPERFRAME_RUNTIME_ARTIFACTS.manifest);
+
+const iifeSource = readFileSync(iifePath, "utf8");
+const manifestRaw = readFileSync(manifestPath, "utf8");
+const manifest = JSON.parse(manifestRaw) as {
+ sha256?: string;
+ artifacts?: { iife?: string; esm?: string };
+};
+
+assert(iifeSource.length > 0, "IIFE runtime artifact is empty");
+assert(
+ manifest.artifacts?.iife === HYPERFRAME_RUNTIME_ARTIFACTS.iife,
+ "Manifest iife artifact name is not strict expected value",
+);
+assert(
+ manifest.artifacts?.esm === HYPERFRAME_RUNTIME_ARTIFACTS.esm,
+ "Manifest esm artifact name is not strict expected value",
+);
+assert(Boolean(manifest.artifacts?.iife), "Manifest missing iife artifact entry");
+assert(Boolean(manifest.artifacts?.esm), "Manifest missing esm artifact entry");
+
+const runtimeSha = createHash("sha256").update(iifeSource, "utf8").digest("hex");
+assert(runtimeSha === manifest.sha256, "Manifest sha256 does not match runtime artifact");
+
+console.log(
+ JSON.stringify({
+ event: "hyperframe_runtime_parity_verified",
+ bytes: iifeSource.length,
+ sha256: runtimeSha,
+ }),
+);
diff --git a/packages/core/scripts/test-hyperframe-runtime-security.ts b/packages/core/scripts/test-hyperframe-runtime-security.ts
new file mode 100644
index 0000000000..6a2350071d
--- /dev/null
+++ b/packages/core/scripts/test-hyperframe-runtime-security.ts
@@ -0,0 +1,96 @@
+function assert(condition: unknown, message: string): void {
+ if (!condition) {
+ throw new Error(message);
+ }
+}
+
+const ALLOWED_HOSTS = new Set(["runtime.example.com"]);
+const ALLOWED_PATH_PREFIX = "/static/hyperframes-runtime/";
+
+function isAllowedRuntimeUrl(candidate: string): boolean {
+ try {
+ const parsed = new URL(candidate);
+ return (
+ parsed.protocol === "https:" &&
+ ALLOWED_HOSTS.has(parsed.hostname.toLowerCase()) &&
+ parsed.pathname.startsWith(ALLOWED_PATH_PREFIX) &&
+ parsed.pathname.endsWith(".js")
+ );
+ } catch {
+ return false;
+ }
+}
+
+function isGuardedPreviewMessage(data: unknown): boolean {
+ if (!data || typeof data !== "object") {
+ return false;
+ }
+ const record = data as { source?: unknown; type?: unknown };
+ const source = typeof record.source === "string" ? record.source : null;
+ const type = typeof record.type === "string" ? record.type : null;
+ const guardedTypes = new Set([
+ "state",
+ "timeline",
+ "element-picked",
+ "element-picked-many",
+ "element-pick-candidates",
+ "pick-mode-cancelled",
+ ]);
+ if (!type || !guardedTypes.has(type)) {
+ return false;
+ }
+ return source === "hf-preview";
+}
+
+const allowedRuntimeFixtures = [
+ "https://runtime.example.com/static/hyperframes-runtime/hyperframe.runtime.iife.js",
+ "https://runtime.example.com/static/hyperframes-runtime/v2026.02.20/hyperframe.runtime.iife.js",
+];
+
+const blockedRuntimeFixtures = [
+ "http://runtime.example.com/static/hyperframes-runtime/hyperframe.runtime.iife.js",
+ "javascript:alert(1)",
+ "data:text/javascript,alert(1)",
+ "https://evil.example/static/hyperframes-runtime/hyperframe.runtime.iife.js",
+ "https://runtime.example.com/static/other/hyperframe.runtime.iife.js",
+ "https://runtime.example.com/static/hyperframes-runtime/hyperframe.runtime.iife.css",
+];
+
+for (const fixture of allowedRuntimeFixtures) {
+ assert(isAllowedRuntimeUrl(fixture), `Expected runtime URL to be allowed: ${fixture}`);
+}
+
+for (const fixture of blockedRuntimeFixtures) {
+ assert(!isAllowedRuntimeUrl(fixture), `Expected runtime URL to be blocked: ${fixture}`);
+}
+
+const allowedMessages = [
+ { type: "state", source: "hf-preview" },
+ { type: "timeline", source: "hf-preview" },
+ { type: "element-picked", source: "hf-preview" },
+];
+const blockedMessages = [
+ { type: "state", source: "hf-parent" },
+ { type: "timeline", source: "evil-origin" },
+ { type: "element-picked", source: "hf-parent" },
+ { type: "pick-mode-cancelled", source: null },
+ { type: "unknown-type", source: "hf-preview" },
+];
+
+for (const fixture of allowedMessages) {
+ assert(isGuardedPreviewMessage(fixture), `Expected message fixture to pass guard: ${JSON.stringify(fixture)}`);
+}
+
+for (const fixture of blockedMessages) {
+ assert(!isGuardedPreviewMessage(fixture), `Expected message fixture to fail guard: ${JSON.stringify(fixture)}`);
+}
+
+console.log(
+ JSON.stringify({
+ event: "hyperframe_runtime_security_fixtures_verified",
+ allowedRuntimeFixtures: allowedRuntimeFixtures.length,
+ blockedRuntimeFixtures: blockedRuntimeFixtures.length,
+ allowedMessages: allowedMessages.length,
+ blockedMessages: blockedMessages.length,
+ }),
+);
diff --git a/packages/core/scripts/test-hyperframe-runtime-seek.ts b/packages/core/scripts/test-hyperframe-runtime-seek.ts
new file mode 100644
index 0000000000..34ed25c49f
--- /dev/null
+++ b/packages/core/scripts/test-hyperframe-runtime-seek.ts
@@ -0,0 +1,122 @@
+import assert from "node:assert/strict";
+import { createGsapAdapter } from "../src/runtime/adapters/gsap";
+import { createRuntimePlayer } from "../src/runtime/player";
+import type { RuntimeTimelineLike } from "../src/runtime/types";
+
+type Call = {
+ method: "pause" | "seek" | "totalTime";
+ time?: number;
+ suppressEvents?: boolean;
+};
+
+function createTimeline(withTotalTime: boolean): { calls: Call[]; timeline: RuntimeTimelineLike } {
+ const calls: Call[] = [];
+ const timeline: RuntimeTimelineLike = {
+ play: () => undefined,
+ pause: () => {
+ calls.push({ method: "pause" });
+ },
+ seek: (timeSeconds: number, suppressEvents?: boolean) => {
+ calls.push({ method: "seek", time: timeSeconds, suppressEvents });
+ },
+ time: () => 0,
+ duration: () => 12,
+ add: () => undefined,
+ paused: () => undefined,
+ set: () => undefined,
+ };
+ if (withTotalTime) {
+ timeline.totalTime = (timeSeconds: number, suppressEvents?: boolean) => {
+ calls.push({ method: "totalTime", time: timeSeconds, suppressEvents });
+ };
+ }
+ return { calls, timeline };
+}
+
+function createPlayer(timeline: RuntimeTimelineLike) {
+ const deterministicSeekCalls: number[] = [];
+ const syncMediaCalls: number[] = [];
+ const renderFrameSeekCalls: number[] = [];
+ const player = createRuntimePlayer({
+ getTimeline: () => timeline,
+ setTimeline: () => undefined,
+ getIsPlaying: () => false,
+ setIsPlaying: () => undefined,
+ getPlaybackRate: () => 1,
+ setPlaybackRate: () => undefined,
+ getCanonicalFps: () => 30,
+ onSyncMedia: (timeSeconds) => {
+ syncMediaCalls.push(timeSeconds);
+ },
+ onStatePost: () => undefined,
+ onDeterministicSeek: (timeSeconds) => {
+ deterministicSeekCalls.push(timeSeconds);
+ },
+ onDeterministicPause: () => undefined,
+ onDeterministicPlay: () => undefined,
+ onRenderFrameSeek: (timeSeconds) => {
+ renderFrameSeekCalls.push(timeSeconds);
+ },
+ onShowNativeVideos: () => undefined,
+ getSafeDuration: () => 12,
+ });
+ return { player, deterministicSeekCalls, syncMediaCalls, renderFrameSeekCalls };
+}
+
+function testSeekUsesDeterministicGsapPath(): void {
+ const { calls, timeline } = createTimeline(true);
+ const { player, deterministicSeekCalls, syncMediaCalls, renderFrameSeekCalls } = createPlayer(timeline);
+ const quantizedTime = 2;
+
+ player.seek(2.017);
+
+ assert.deepEqual(
+ calls,
+ [{ method: "pause" }, { method: "totalTime", time: quantizedTime, suppressEvents: false }],
+ "player.seek() should use quantized totalTime() when available",
+ );
+ assert.deepEqual(
+ deterministicSeekCalls,
+ [quantizedTime],
+ "player.seek() should notify adapters with the quantized time",
+ );
+ assert.deepEqual(syncMediaCalls, [quantizedTime], "media sync should use quantized time");
+ assert.deepEqual(renderFrameSeekCalls, [quantizedTime], "render frame seek should use quantized time");
+}
+
+function testGsapAdapterPreservesTotalTime(): void {
+ const { calls, timeline } = createTimeline(true);
+ const adapter = createGsapAdapter({ getTimeline: () => timeline });
+
+ adapter.seek({ time: 2.033333333333333 });
+
+ assert.deepEqual(
+ calls,
+ [{ method: "pause" }, { method: "totalTime", time: 2.033333333333333, suppressEvents: false }],
+ "GSAP adapter should not downgrade deterministic seeks back to seek()",
+ );
+}
+
+function testGsapAdapterFallsBackToSeek(): void {
+ const { calls, timeline } = createTimeline(false);
+ const adapter = createGsapAdapter({ getTimeline: () => timeline });
+
+ adapter.seek({ time: 1.5 });
+
+ assert.deepEqual(
+ calls,
+ [{ method: "pause" }, { method: "seek", time: 1.5, suppressEvents: false }],
+ "GSAP adapter should keep working with timelines that only expose seek()",
+ );
+}
+
+testSeekUsesDeterministicGsapPath();
+testGsapAdapterPreservesTotalTime();
+testGsapAdapterFallsBackToSeek();
+
+console.log(
+ JSON.stringify({
+ event: "hyperframe_runtime_seek_verified",
+ assertions: 3,
+ }),
+);
diff --git a/packages/core/src/adapters/gsap.test.ts b/packages/core/src/adapters/gsap.test.ts
new file mode 100644
index 0000000000..cf2b42e0e4
--- /dev/null
+++ b/packages/core/src/adapters/gsap.test.ts
@@ -0,0 +1,136 @@
+import { describe, it, expect, vi } from "vitest";
+import { createGSAPFrameAdapter } from "./gsap.js";
+import type { FrameAdapter, FrameAdapterContext } from "./types.js";
+
+function makeMockTimeline(duration = 10, totalDuration?: number) {
+ return {
+ duration: vi.fn().mockReturnValue(duration),
+ totalDuration: totalDuration !== undefined ? vi.fn().mockReturnValue(totalDuration) : undefined,
+ seek: vi.fn(),
+ pause: vi.fn(),
+ };
+}
+
+describe("createGSAPFrameAdapter", () => {
+ it("returns a FrameAdapter with required properties", () => {
+ const timeline = makeMockTimeline(10);
+ const adapter = createGSAPFrameAdapter({ fps: 30, timeline });
+
+ expect(adapter.id).toBe("gsap");
+ expect(typeof adapter.init).toBe("function");
+ expect(typeof adapter.getDurationFrames).toBe("function");
+ expect(typeof adapter.seekFrame).toBe("function");
+ });
+
+ it("uses custom id when provided", () => {
+ const timeline = makeMockTimeline(10);
+ const adapter = createGSAPFrameAdapter({ id: "custom-gsap", fps: 30, timeline });
+
+ expect(adapter.id).toBe("custom-gsap");
+ });
+
+ it("getDurationFrames returns correct frame count", () => {
+ const timeline = makeMockTimeline(10); // 10 seconds
+ const adapter = createGSAPFrameAdapter({ fps: 30, timeline });
+
+ // 10 seconds * 30 fps = 300 frames
+ expect(adapter.getDurationFrames()).toBe(300);
+ });
+
+ it("getDurationFrames uses totalDuration when available", () => {
+ const timeline = makeMockTimeline(5, 15); // duration=5, totalDuration=15
+ const adapter = createGSAPFrameAdapter({ fps: 30, timeline });
+
+ // Should use totalDuration (15) not duration (5)
+ // 15 seconds * 30 fps = 450 frames
+ expect(adapter.getDurationFrames()).toBe(450);
+ });
+
+ it("getDurationFrames returns 0 for zero-duration timeline", () => {
+ const timeline = makeMockTimeline(0);
+ const adapter = createGSAPFrameAdapter({ fps: 30, timeline });
+
+ expect(adapter.getDurationFrames()).toBe(0);
+ });
+
+ it("init pauses the timeline", () => {
+ const timeline = makeMockTimeline(10);
+ const adapter = createGSAPFrameAdapter({ fps: 30, timeline });
+
+ adapter.init!({} as FrameAdapterContext);
+
+ expect(timeline.pause).toHaveBeenCalled();
+ });
+
+ it("seekFrame seeks to the correct time in seconds", () => {
+ const timeline = makeMockTimeline(10);
+ const adapter = createGSAPFrameAdapter({ fps: 30, timeline });
+
+ adapter.seekFrame(90); // Frame 90 at 30fps = 3 seconds
+
+ expect(timeline.seek).toHaveBeenCalledWith(3, false);
+ expect(timeline.pause).toHaveBeenCalled();
+ });
+
+ it("seekFrame clamps negative frames to 0", () => {
+ const timeline = makeMockTimeline(10);
+ const adapter = createGSAPFrameAdapter({ fps: 30, timeline });
+
+ adapter.seekFrame(-5);
+
+ expect(timeline.seek).toHaveBeenCalledWith(0, false);
+ });
+
+ it("seekFrame handles non-finite frame numbers", () => {
+ const timeline = makeMockTimeline(10);
+ const adapter = createGSAPFrameAdapter({ fps: 30, timeline });
+
+ adapter.seekFrame(NaN);
+
+ expect(timeline.seek).toHaveBeenCalledWith(0, false);
+ });
+
+ it("seekFrame handles Infinity", () => {
+ const timeline = makeMockTimeline(10);
+ const adapter = createGSAPFrameAdapter({ fps: 30, timeline });
+
+ adapter.seekFrame(Infinity);
+
+ // Infinity is not finite, so it gets clamped to 0
+ expect(timeline.seek).toHaveBeenCalledWith(0, false);
+ });
+
+ it("works without pause method on timeline", () => {
+ const timeline = {
+ duration: vi.fn().mockReturnValue(5),
+ seek: vi.fn(),
+ // No pause method
+ };
+
+ const adapter = createGSAPFrameAdapter({ fps: 30, timeline });
+
+ // Should not throw
+ adapter.init!({} as FrameAdapterContext);
+ adapter.seekFrame(0);
+
+ expect(timeline.seek).toHaveBeenCalled();
+ });
+
+ it("getDurationFrames ceiling the frame count", () => {
+ const timeline = makeMockTimeline(1.05); // 1.05 seconds * 30 fps = 31.5 -> ceil = 32
+ const adapter = createGSAPFrameAdapter({ fps: 30, timeline });
+
+ expect(adapter.getDurationFrames()).toBe(32);
+ });
+});
+
+describe("FrameAdapter type", () => {
+ it("adapter conforms to FrameAdapter interface", () => {
+ const timeline = makeMockTimeline(10);
+ const adapter: FrameAdapter = createGSAPFrameAdapter({ fps: 30, timeline });
+
+ expect(adapter.id).toBeDefined();
+ expect(adapter.getDurationFrames).toBeDefined();
+ expect(adapter.seekFrame).toBeDefined();
+ });
+});
diff --git a/packages/core/src/adapters/gsap.ts b/packages/core/src/adapters/gsap.ts
new file mode 100644
index 0000000000..392ab21266
--- /dev/null
+++ b/packages/core/src/adapters/gsap.ts
@@ -0,0 +1,43 @@
+import type { FrameAdapter } from "./types";
+
+export interface GSAPTimelineLike {
+ // Base timeline span excluding repeats.
+ duration: () => number;
+ // Full span including repeats/yoyo when available.
+ totalDuration?: () => number;
+ seek: (timeInSeconds: number, suppressEvents?: boolean) => unknown;
+ pause?: () => unknown;
+}
+
+export interface CreateGSAPFrameAdapterOptions {
+ id?: string;
+ fps: number;
+ timeline: GSAPTimelineLike;
+}
+
+export function createGSAPFrameAdapter(options: CreateGSAPFrameAdapterOptions): FrameAdapter {
+ const { fps, timeline } = options;
+ const adapterId = options.id ?? "gsap";
+
+ const getDurationSeconds = (): number => {
+ const totalDuration = typeof timeline.totalDuration === "function" ? timeline.totalDuration() : timeline.duration();
+ return Number.isFinite(totalDuration) && totalDuration > 0 ? totalDuration : 0;
+ };
+
+ return {
+ id: adapterId,
+ init: () => {
+ timeline.pause?.();
+ },
+ getDurationFrames: () => {
+ const durationSeconds = getDurationSeconds();
+ return Math.max(0, Math.ceil(durationSeconds * fps));
+ },
+ seekFrame: (frame: number) => {
+ const clampedFrame = Number.isFinite(frame) ? Math.max(0, frame) : 0;
+ const targetSeconds = clampedFrame / fps;
+ timeline.pause?.();
+ timeline.seek(targetSeconds, false);
+ },
+ };
+}
diff --git a/packages/core/src/adapters/index.ts b/packages/core/src/adapters/index.ts
new file mode 100644
index 0000000000..254c28bd51
--- /dev/null
+++ b/packages/core/src/adapters/index.ts
@@ -0,0 +1,3 @@
+export type { FrameAdapter, FrameAdapterContext } from "./types";
+export type { GSAPTimelineLike, CreateGSAPFrameAdapterOptions } from "./gsap";
+export { createGSAPFrameAdapter } from "./gsap";
diff --git a/packages/core/src/adapters/types.ts b/packages/core/src/adapters/types.ts
new file mode 100644
index 0000000000..484064d21e
--- /dev/null
+++ b/packages/core/src/adapters/types.ts
@@ -0,0 +1,15 @@
+export interface FrameAdapterContext {
+ compositionId: string;
+ fps: number;
+ width: number;
+ height: number;
+ rootElement?: HTMLElement;
+}
+
+export interface FrameAdapter {
+ id: string;
+ init?: (ctx: FrameAdapterContext) => Promise<void> | void;
+ getDurationFrames: () => number;
+ seekFrame: (frame: number) => Promise<void> | void;
+ destroy?: () => Promise<void> | void;
+}
diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts
new file mode 100644
index 0000000000..d466973725
--- /dev/null
+++ b/packages/core/src/compiler/htmlBundler.ts
@@ -0,0 +1,402 @@
+import { readFileSync, existsSync } from "fs";
+import { join, resolve, isAbsolute, sep } from "path";
+import * as cheerio from "cheerio";
+import { transformSync } from "esbuild";
+import { compileHtml, type MediaDurationProber } from "./htmlCompiler";
+import { validateHyperframeHtmlContract } from "./staticGuard";
+
+/** Resolve a relative path within projectDir, rejecting traversal outside it. */
+function safePath(projectDir: string, relativePath: string): string | null {
+ const resolved = resolve(projectDir, relativePath);
+ const normalizedBase = resolve(projectDir) + sep;
+ if (!resolved.startsWith(normalizedBase) && resolved !== resolve(projectDir)) return null;
+ return resolved;
+}
+
+const RUNTIME_BOOTSTRAP_ATTR = "data-hyperframes-preview-runtime";
+const DEFAULT_RUNTIME_SCRIPT_URL = "";
+
+function stripEmbeddedRuntimeScripts(html: string): string {
+ if (!html) return html;
+ const scriptRe = /<script\b[^>]*>[\s\S]*?<\/script>/gi;
+ const runtimeSrcMarkers = [
+ "hyperframe.runtime.iife.js",
+ "hyperframe-runtime.modular-runtime.inline.js",
+ RUNTIME_BOOTSTRAP_ATTR,
+ ];
+ const runtimeInlineMarkers = [
+ "__hyperframeRuntimeBootstrapped",
+ "__hyperframeRuntime",
+ "__hyperframeRuntimeTeardown",
+ "window.__player =",
+ "window.__playerReady",
+ "window.__renderReady",
+ ];
+
+ const shouldStrip = (block: string): boolean => {
+ const lowered = block.toLowerCase();
+ for (const marker of runtimeSrcMarkers) {
+ if (lowered.includes(marker.toLowerCase())) return true;
+ }
+ for (const marker of runtimeInlineMarkers) {
+ if (block.includes(marker)) return true;
+ }
+ return false;
+ };
+
+ return html.replace(scriptRe, (block) => (shouldStrip(block) ? "" : block));
+}
+
+function getRuntimeScriptUrl(): string {
+ const configured = (process.env.HYPERFRAME_RUNTIME_URL || "").trim();
+ return configured || DEFAULT_RUNTIME_SCRIPT_URL;
+}
+
+function injectInterceptor(html: string): string {
+ const sanitized = stripEmbeddedRuntimeScripts(html);
+ if (sanitized.includes(RUNTIME_BOOTSTRAP_ATTR)) return sanitized;
+
+ const runtimeScriptUrl = getRuntimeScriptUrl().replace(/"/g, "&quot;");
+ const tag = `<script ${RUNTIME_BOOTSTRAP_ATTR}="1" src="${runtimeScriptUrl}"></script>`;
+ if (sanitized.includes("</head>")) {
+ return sanitized.replace("</head>", `${tag}\n</head>`);
+ }
+ const doctypeIdx = sanitized.toLowerCase().indexOf("<!doctype");
+ if (doctypeIdx >= 0) {
+ const insertPos = sanitized.indexOf(">", doctypeIdx) + 1;
+ return sanitized.slice(0, insertPos) + tag + sanitized.slice(insertPos);
+ }
+ return tag + sanitized;
+}
+
+function isRelativeUrl(url: string): boolean {
+ if (!url) return false;
+ return !url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("//") && !url.startsWith("data:") && !isAbsolute(url);
+}
+
+function safeReadFile(filePath: string): string | null {
+ if (!existsSync(filePath)) return null;
+ try { return readFileSync(filePath, "utf-8"); } catch { return null; }
+}
+
+function safeReadFileBuffer(filePath: string): Buffer | null {
+ if (!existsSync(filePath)) return null;
+ try { return readFileSync(filePath); } catch { return null; }
+}
+
+function splitUrlSuffix(urlValue: string): { basePath: string; suffix: string } {
+ const queryIdx = urlValue.indexOf("?");
+ const hashIdx = urlValue.indexOf("#");
+ if (queryIdx < 0 && hashIdx < 0) return { basePath: urlValue, suffix: "" };
+ const cutIdx = queryIdx < 0 ? hashIdx : hashIdx < 0 ? queryIdx : Math.min(queryIdx, hashIdx);
+ return { basePath: urlValue.slice(0, cutIdx), suffix: urlValue.slice(cutIdx) };
+}
+
+function appendSuffixToUrl(baseUrl: string, suffix: string): string {
+ if (!suffix) return baseUrl;
+ if (suffix.startsWith("#")) return `${baseUrl}${suffix}`;
+ if (suffix.startsWith("?")) {
+ const queryWithOptionalHash = suffix.slice(1);
+ if (!queryWithOptionalHash) return baseUrl;
+ const hashIdx = queryWithOptionalHash.indexOf("#");
+ const queryPart = hashIdx >= 0 ? queryWithOptionalHash.slice(0, hashIdx) : queryWithOptionalHash;
+ const hashPart = hashIdx >= 0 ? queryWithOptionalHash.slice(hashIdx) : "";
+ if (!queryPart) return `${baseUrl}${hashPart}`;
+ const joiner = baseUrl.includes("?") ? "&" : "?";
+ return `${baseUrl}${joiner}${queryPart}${hashPart}`;
+ }
+ return baseUrl;
+}
+
+function guessMimeType(filePath: string): string {
+ const l = filePath.toLowerCase();
+ if (l.endsWith(".svg")) return "image/svg+xml";
+ if (l.endsWith(".json")) return "application/json";
+ if (l.endsWith(".txt")) return "text/plain";
+ if (l.endsWith(".xml")) return "application/xml";
+ return "application/octet-stream";
+}
+
+function shouldInlineAsDataUrl(filePath: string): boolean {
+ const l = filePath.toLowerCase();
+ return l.endsWith(".svg") || l.endsWith(".json") || l.endsWith(".txt") || l.endsWith(".xml");
+}
+
+function maybeInlineRelativeAssetUrl(urlValue: string, projectDir: string): string | null {
+ if (!urlValue || !isRelativeUrl(urlValue)) return null;
+ const { basePath, suffix } = splitUrlSuffix(urlValue.trim());
+ if (!basePath) return null;
+ const filePath = safePath(projectDir, basePath);
+ if (!filePath || !shouldInlineAsDataUrl(filePath)) return null;
+ const content = safeReadFileBuffer(filePath);
+ if (content == null) return null;
+ const mimeType = guessMimeType(filePath);
+ const dataUrl = `data:${mimeType};base64,${content.toString("base64")}`;
+ return appendSuffixToUrl(dataUrl, suffix);
+}
+
+function rewriteSrcsetWithInlinedAssets(srcsetValue: string, projectDir: string): string {
+ if (!srcsetValue) return srcsetValue;
+ return srcsetValue.split(",").map((rawCandidate) => {
+ const candidate = rawCandidate.trim();
+ if (!candidate) return candidate;
+ const parts = candidate.split(/\s+/);
+ if (parts.length === 0) return candidate;
+ const maybeInlined = maybeInlineRelativeAssetUrl(parts[0] ?? "", projectDir);
+ if (maybeInlined) parts[0] = maybeInlined;
+ return parts.join(" ");
+ }).join(", ");
+}
+
+function rewriteCssUrlsWithInlinedAssets(cssText: string, projectDir: string): string {
+ if (!cssText) return cssText;
+ return cssText.replace(
+ /\burl\(\s*(["']?)([^)"']+)\1\s*\)/g,
+ (_full, quote: string, rawUrl: string) => {
+ const maybeInlined = maybeInlineRelativeAssetUrl((rawUrl || "").trim(), projectDir);
+ if (!maybeInlined) return _full;
+ return `url(${quote || ""}${maybeInlined}${quote || ""})`;
+ },
+ );
+}
+
+function enforceCompositionPixelSizing($: cheerio.CheerioAPI): void {
+ const compositionEls = $("[data-composition-id][data-width][data-height]").toArray();
+ if (compositionEls.length === 0) return;
+ const sizeMap = new Map<string, { w: number; h: number }>();
+ for (const el of compositionEls) {
+ const compId = $(el).attr("data-composition-id");
+ const w = Number($(el).attr("data-width"));
+ const h = Number($(el).attr("data-height"));
+ if (compId && Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0) {
+ sizeMap.set(compId, { w, h });
+ }
+ }
+ if (sizeMap.size === 0) return;
+ $("style").each((_, styleEl) => {
+ let css = $(styleEl).html() || "";
+ let modified = false;
+ for (const [compId, { w, h }] of sizeMap) {
+ const escaped = compId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const blockRe = new RegExp(`(\\[data-composition-id=["']${escaped}["']\\]\\s*\\{)([^}]*)(})`, "g");
+ css = css.replace(blockRe, (_, open, body, close) => {
+ const newBody = body.replace(/(\bwidth\s*:\s*)100%/g, `$1${w}px`).replace(/(\bheight\s*:\s*)100%/g, `$1${h}px`);
+ if (newBody !== body) modified = true;
+ return open + newBody + close;
+ });
+ }
+ if (modified) $(styleEl).text(css);
+ });
+}
+
+function autoHealMissingCompositionIds($: cheerio.CheerioAPI): void {
+ const compositionIdRe = /data-composition-id=["']([^"']+)["']/gi;
+ const referencedIds = new Set<string>();
+ $("style, script").each((_, el) => {
+ const text = ($(el).html() || "").trim();
+ if (!text) return;
+ let match: RegExpExecArray | null;
+ while ((match = compositionIdRe.exec(text)) !== null) {
+ const compId = (match[1] || "").trim();
+ if (compId) referencedIds.add(compId);
+ }
+ });
+ if (referencedIds.size === 0) return;
+
+ const existingIds = new Set<string>();
+ $("[data-composition-id]").each((_, el) => {
+ const id = ($(el).attr("data-composition-id") || "").trim();
+ if (id) existingIds.add(id);
+ });
+
+ for (const compId of referencedIds) {
+ if (compId === "root" || existingIds.has(compId)) continue;
+ const candidates = [`${compId}-layer`, `${compId}-comp`, compId];
+ for (const targetId of candidates) {
+ const match = $(`#${targetId}`).first();
+ if (match.length > 0 && !match.attr("data-composition-id")) {
+ match.attr("data-composition-id", compId);
+ break;
+ }
+ }
+ }
+}
+
+function coalesceHeadStylesAndBodyScripts($: cheerio.CheerioAPI): void {
+ const headStyleEls = $("head style").toArray();
+ if (headStyleEls.length > 1) {
+ const importRe = /@import\s+url\([^)]*\)\s*;|@import\s+["'][^"']+["']\s*;/gi;
+ const imports: string[] = [];
+ const cssParts: string[] = [];
+ const seenImports = new Set<string>();
+ for (const el of headStyleEls) {
+ const raw = ($(el).html() || "").trim();
+ if (!raw) continue;
+ const nonImportCss = raw.replace(importRe, (match) => {
+ const cleaned = match.trim();
+ if (!seenImports.has(cleaned)) { seenImports.add(cleaned); imports.push(cleaned); }
+ return "";
+ });
+ const trimmed = nonImportCss.trim();
+ if (trimmed) cssParts.push(trimmed);
+ }
+ const merged = [...imports, ...cssParts].join("\n\n").trim();
+ if (merged) {
+ $(headStyleEls[0]).text(merged);
+ for (let i = 1; i < headStyleEls.length; i++) $(headStyleEls[i]).remove();
+ }
+ }
+
+ const bodyInlineScripts = $("body script").toArray().filter((el) => {
+ const src = ($(el).attr("src") || "").trim();
+ if (src) return false;
+ const type = ($(el).attr("type") || "").trim().toLowerCase();
+ return !type || type === "text/javascript" || type === "application/javascript";
+ });
+ if (bodyInlineScripts.length > 0) {
+ const mergedJs = bodyInlineScripts.map((el) => ($(el).html() || "").trim()).filter(Boolean).join("\n;\n").trim();
+ for (const el of bodyInlineScripts) $(el).remove();
+ if (mergedJs) {
+ const stripped = stripJsCommentsParserSafe(mergedJs);
+ $("body").append(`<script>${stripped}</script>`);
+ }
+ }
+}
+
+function stripJsCommentsParserSafe(source: string): string {
+ if (!source) return source;
+ try {
+ const result = transformSync(source, { loader: "js", minify: false, legalComments: "none" });
+ return result.code.trim();
+ } catch { return source; }
+}
+
+export interface BundleOptions {
+ /** Optional media duration prober (e.g., ffprobe). If omitted, media durations are not resolved. */
+ probeMediaDuration?: MediaDurationProber;
+}
+
+/**
+ * Bundle a project's index.html into a single self-contained HTML file.
+ *
+ * - Compiles timing attributes and optionally resolves media durations
+ * - Injects the HyperFrames runtime script
+ * - Inlines local CSS and JS files
+ * - Inlines sub-composition HTML fragments (data-composition-src)
+ * - Inlines small textual assets as data URLs
+ */
+export async function bundleToSingleHtml(projectDir: string, options?: BundleOptions): Promise<string> {
+ const indexPath = join(projectDir, "index.html");
+ if (!existsSync(indexPath)) throw new Error("index.html not found in project directory");
+
+ const rawHtml = readFileSync(indexPath, "utf-8");
+ const compiled = await compileHtml(rawHtml, projectDir, options?.probeMediaDuration);
+
+ const staticGuard = validateHyperframeHtmlContract(compiled);
+ if (!staticGuard.isValid) {
+ console.warn(`[StaticGuard] Invalid HyperFrame contract: ${staticGuard.missingKeys.join("; ")}`);
+ }
+
+ const withInterceptor = injectInterceptor(compiled);
+ const $ = cheerio.load(withInterceptor);
+
+ // Inline local CSS
+ const localCssChunks: string[] = [];
+ let cssAnchorPlaced = false;
+ $('link[rel="stylesheet"]').each((_, el) => {
+ const href = $(el).attr("href");
+ if (!href || !isRelativeUrl(href)) return;
+ const cssPath = safePath(projectDir, href);
+ const css = cssPath ? safeReadFile(cssPath) : null;
+ if (css == null) return;
+ localCssChunks.push(css);
+ if (!cssAnchorPlaced) { $(el).replaceWith('<style data-hf-bundled-local-css="1"></style>'); cssAnchorPlaced = true; } else { $(el).remove(); }
+ });
+ if (localCssChunks.length > 0) {
+ const $anchor = $('style[data-hf-bundled-local-css="1"]').first();
+ if ($anchor.length) $anchor.removeAttr("data-hf-bundled-local-css").text(localCssChunks.join("\n\n"));
+ else $("head").append(`<style>${localCssChunks.join("\n\n")}</style>`);
+ }
+
+ // Inline local JS
+ const localJsChunks: string[] = [];
+ let jsAnchorPlaced = false;
+ $("script[src]").each((_, el) => {
+ const src = $(el).attr("src");
+ if (!src || !isRelativeUrl(src)) return;
+ const jsPath = safePath(projectDir, src);
+ const js = jsPath ? safeReadFile(jsPath) : null;
+ if (js == null) return;
+ localJsChunks.push(js);
+ if (!jsAnchorPlaced) { $(el).replaceWith('<script data-hf-bundled-local-js="1"></script>'); jsAnchorPlaced = true; } else { $(el).remove(); }
+ });
+ if (localJsChunks.length > 0) {
+ const $anchor = $('script[data-hf-bundled-local-js="1"]').first();
+ if ($anchor.length) $anchor.removeAttr("data-hf-bundled-local-js").text(localJsChunks.join("\n;\n"));
+ else $("body").append(`<script>${localJsChunks.join("\n;\n")}</script>`);
+ }
+
+ // Inline sub-compositions
+ const compStyleChunks: string[] = [];
+ const compScriptChunks: string[] = [];
+ $("[data-composition-src]").each((_, hostEl) => {
+ const src = $(hostEl).attr("data-composition-src");
+ if (!src || !isRelativeUrl(src)) return;
+ const compPath = safePath(projectDir, src);
+ const compHtml = compPath ? safeReadFile(compPath) : null;
+ if (compHtml == null) { console.warn(`[Bundler] Composition file not found: ${src}`); return; }
+
+ const $comp = cheerio.load(compHtml);
+ const compId = $(hostEl).attr("data-composition-id");
+ const $contentRoot = $comp("template").first();
+ const contentHtml = $contentRoot.length ? $contentRoot.html() || "" : $comp("body").html() || "";
+ const $content = cheerio.load(contentHtml);
+ const $innerRoot = compId ? $content(`[data-composition-id="${compId}"]`).first() : $content("[data-composition-id]").first();
+
+ $content("style").each((_, s) => { compStyleChunks.push($content(s).html() || ""); $content(s).remove(); });
+ $content("script").each((_, s) => {
+ compScriptChunks.push(`(function(){ try { ${$content(s).html() || ""} } catch (_err) { console.error('[HyperFrames] composition script error:', _err); } })();`);
+ $content(s).remove();
+ });
+
+ if ($innerRoot.length) {
+ const innerCompId = $innerRoot.attr("data-composition-id");
+ const innerW = $innerRoot.attr("data-width");
+ const innerH = $innerRoot.attr("data-height");
+ if (innerCompId && !$(hostEl).attr("data-composition-id")) $(hostEl).attr("data-composition-id", innerCompId);
+ if (innerW && !$(hostEl).attr("data-width")) $(hostEl).attr("data-width", innerW);
+ if (innerH && !$(hostEl).attr("data-height")) $(hostEl).attr("data-height", innerH);
+ $innerRoot.find("style, script").remove();
+ $(hostEl).html($innerRoot.html() || "");
+ } else {
+ $content("style, script").remove();
+ $(hostEl).html($content.html() || "");
+ }
+ $(hostEl).removeAttr("data-composition-src");
+ });
+
+ if (compStyleChunks.length) $("head").append(`<style>${compStyleChunks.join("\n\n")}</style>`);
+ if (compScriptChunks.length) $("body").append(`<script>${compScriptChunks.join("\n;\n")}</script>`);
+
+ enforceCompositionPixelSizing($);
+ autoHealMissingCompositionIds($);
+ coalesceHeadStylesAndBodyScripts($);
+
+ // Inline textual assets
+ $("[src], [href], [poster], [xlink\\:href]").each((_, el) => {
+ for (const attr of ["src", "href", "poster", "xlink:href"] as const) {
+ const value = $(el).attr(attr);
+ if (!value) continue;
+ const inlined = maybeInlineRelativeAssetUrl(value, projectDir);
+ if (inlined) $(el).attr(attr, inlined);
+ }
+ });
+ $("[srcset]").each((_, el) => {
+ const srcset = $(el).attr("srcset");
+ if (srcset) $(el).attr("srcset", rewriteSrcsetWithInlinedAssets(srcset, projectDir));
+ });
+ $("style").each((_, el) => { $(el).text(rewriteCssUrlsWithInlinedAssets($(el).html() || "", projectDir)); });
+ $("[style]").each((_, el) => { $(el).attr("style", rewriteCssUrlsWithInlinedAssets($(el).attr("style") || "", projectDir)); });
+
+ return $.html();
+}
diff --git a/packages/core/src/compiler/htmlCompiler.ts b/packages/core/src/compiler/htmlCompiler.ts
new file mode 100644
index 0000000000..4efc446592
--- /dev/null
+++ b/packages/core/src/compiler/htmlCompiler.ts
@@ -0,0 +1,90 @@
+import { resolve } from "path";
+import {
+ compileTimingAttrs,
+ injectDurations,
+ extractResolvedMedia,
+ clampDurations,
+ type ResolvedDuration,
+} from "./timingCompiler";
+
+/**
+ * Callback to probe media duration. If not provided, media duration resolution is skipped.
+ * Return duration in seconds, or 0 if unknown.
+ */
+export type MediaDurationProber = (src: string) => Promise<number>;
+
+function resolveMediaSrc(src: string, projectDir: string): string {
+ return src.startsWith("http://") || src.startsWith("https://")
+ ? src
+ : resolve(projectDir, src);
+}
+
+/**
+ * Compile HTML with full duration resolution.
+ *
+ * 1. Static pass: compileTimingAttrs() adds data-end where data-duration exists
+ * 2. For unresolved video/audio (no data-duration): probe via probeMediaDuration, inject durations
+ * 3. For pre-resolved video/audio: validate data-duration against actual source, clamp if needed
+ *
+ * @param rawHtml - The raw HTML string
+ * @param projectDir - The project directory for resolving relative paths
+ * @param probeMediaDuration - Optional callback to probe media duration (e.g., via ffprobe)
+ */
+export async function compileHtml(
+ rawHtml: string,
+ projectDir: string,
+ probeMediaDuration?: MediaDurationProber,
+): Promise<string> {
+ const { html: staticCompiled, unresolved } = compileTimingAttrs(rawHtml);
+ let html = staticCompiled;
+
+ if (!probeMediaDuration) return html;
+
+ // Phase 1: Resolve missing durations
+ const mediaUnresolved = unresolved.filter(
+ (el) => el.tagName === "video" || el.tagName === "audio",
+ );
+
+ if (mediaUnresolved.length > 0) {
+ const resolutions: ResolvedDuration[] = [];
+
+ for (const el of mediaUnresolved) {
+ if (!el.src) continue;
+ const src = resolveMediaSrc(el.src, projectDir);
+ const fileDuration = await probeMediaDuration(src);
+ if (fileDuration <= 0) continue;
+
+ const effectiveDuration = fileDuration - el.mediaStart;
+ resolutions.push({
+ id: el.id,
+ duration: effectiveDuration > 0 ? effectiveDuration : fileDuration,
+ });
+ }
+
+ if (resolutions.length > 0) {
+ html = injectDurations(html, resolutions);
+ }
+ }
+
+ // Phase 2: Validate pre-resolved media — clamp data-duration to actual source duration
+ const preResolved = extractResolvedMedia(html);
+ const clampList: ResolvedDuration[] = [];
+
+ for (const el of preResolved) {
+ if (!el.src) continue;
+ const src = resolveMediaSrc(el.src, projectDir);
+ const fileDuration = await probeMediaDuration(src);
+ if (fileDuration <= 0) continue;
+
+ const maxDuration = fileDuration - el.mediaStart;
+ if (maxDuration > 0 && el.duration > maxDuration) {
+ clampList.push({ id: el.id, duration: maxDuration });
+ }
+ }
+
+ if (clampList.length > 0) {
+ html = clampDurations(html, clampList);
+ }
+
+ return html;
+}
diff --git a/packages/core/src/compiler/index.ts b/packages/core/src/compiler/index.ts
new file mode 100644
index 0000000000..feed7c1b6f
--- /dev/null
+++ b/packages/core/src/compiler/index.ts
@@ -0,0 +1,24 @@
+// Timing compiler (browser-safe)
+export {
+ compileTimingAttrs,
+ injectDurations,
+ extractResolvedMedia,
+ clampDurations,
+ type UnresolvedElement,
+ type ResolvedDuration,
+ type ResolvedMediaElement,
+ type CompilationResult,
+} from "./timingCompiler";
+
+// HTML compiler (Node.js — requires fs)
+export { compileHtml, type MediaDurationProber } from "./htmlCompiler";
+
+// HTML bundler (Node.js — requires fs, cheerio, esbuild)
+export { bundleToSingleHtml, type BundleOptions } from "./htmlBundler";
+
+// Static guard
+export {
+ validateHyperframeHtmlContract,
+ type HyperframeStaticFailureReason,
+ type HyperframeStaticGuardResult,
+} from "./staticGuard";
diff --git a/packages/core/src/compiler/staticGuard.ts b/packages/core/src/compiler/staticGuard.ts
new file mode 100644
index 0000000000..372d538b1e
--- /dev/null
+++ b/packages/core/src/compiler/staticGuard.ts
@@ -0,0 +1,39 @@
+import { lintHyperframeHtml } from "../lint/hyperframeLinter";
+
+export type HyperframeStaticFailureReason =
+ | "missing_composition_id"
+ | "missing_composition_dimensions"
+ | "missing_timeline_registry"
+ | "invalid_script_syntax"
+ | "invalid_static_hyperframe_contract";
+
+export type HyperframeStaticGuardResult = {
+ isValid: boolean;
+ missingKeys: string[];
+ failureReason: HyperframeStaticFailureReason | null;
+};
+
+export function validateHyperframeHtmlContract(html: string): HyperframeStaticGuardResult {
+ const result = lintHyperframeHtml(html);
+ const missingKeys = result.findings
+ .filter((finding) => finding.severity === "error")
+ .map((finding) => finding.message);
+
+ if (missingKeys.length === 0) {
+ return { isValid: true, missingKeys: [], failureReason: null };
+ }
+
+ const joined = missingKeys.join(" ").toLowerCase();
+ let failureReason: HyperframeStaticFailureReason = "invalid_static_hyperframe_contract";
+ if (joined.includes("data-composition-id")) {
+ failureReason = "missing_composition_id";
+ } else if (joined.includes("data-width") || joined.includes("data-height")) {
+ failureReason = "missing_composition_dimensions";
+ } else if (joined.includes("window.__timelines")) {
+ failureReason = "missing_timeline_registry";
+ } else if (joined.includes("script syntax")) {
+ failureReason = "invalid_script_syntax";
+ }
+
+ return { isValid: false, missingKeys, failureReason };
+}
diff --git a/packages/core/src/compiler/timingCompiler.test.ts b/packages/core/src/compiler/timingCompiler.test.ts
new file mode 100644
index 0000000000..13ec8ff73b
--- /dev/null
+++ b/packages/core/src/compiler/timingCompiler.test.ts
@@ -0,0 +1,112 @@
+import { describe, it, expect } from "vitest";
+import { compileTimingAttrs, injectDurations, extractResolvedMedia, clampDurations } from "./timingCompiler.js";
+
+describe("compileTimingAttrs", () => {
+ it("adds data-end when data-start and data-duration are present on a video", () => {
+ const html = '<video id="v1" src="a.mp4" data-start="2" data-duration="5">';
+ const { html: compiled, unresolved } = compileTimingAttrs(html);
+
+ expect(compiled).toContain('data-end="7"');
+ expect(compiled).toContain('data-has-audio="true"');
+ expect(unresolved).toHaveLength(0);
+ });
+
+ it("leaves data-end unchanged when already present", () => {
+ const html = '<video id="v1" src="a.mp4" data-start="0" data-end="3">';
+ const { html: compiled, unresolved } = compileTimingAttrs(html);
+
+ expect(compiled).toContain('data-end="3"');
+ expect(compiled).not.toContain("data-duration");
+ expect(unresolved).toHaveLength(0);
+ });
+
+ it("marks video as unresolved when data-duration and data-end are missing", () => {
+ const html = '<video id="v1" src="a.mp4" data-start="1">';
+ const { unresolved } = compileTimingAttrs(html);
+
+ expect(unresolved).toHaveLength(1);
+ expect(unresolved[0].id).toBe("v1");
+ expect(unresolved[0].tagName).toBe("video");
+ expect(unresolved[0].start).toBe(1);
+ });
+
+ it("compiles audio tags the same as video (minus data-has-audio)", () => {
+ const html = '<audio id="a1" src="music.mp3" data-start="0" data-duration="10">';
+ const { html: compiled } = compileTimingAttrs(html);
+
+ expect(compiled).toContain('data-end="10"');
+ expect(compiled).not.toContain("data-has-audio");
+ });
+
+ it("detects unresolved div/section elements with data-start but no data-end", () => {
+ const html = '<div id="comp1" data-start="0" data-composition-src="comp.html">';
+ const { unresolved } = compileTimingAttrs(html);
+
+ expect(unresolved).toHaveLength(1);
+ expect(unresolved[0].id).toBe("comp1");
+ expect(unresolved[0].tagName).toBe("div");
+ expect(unresolved[0].compositionSrc).toBe("comp.html");
+ });
+
+ it("does not report div as unresolved when data-end is present", () => {
+ const html = '<div id="comp1" data-start="0" data-end="5">';
+ const { unresolved } = compileTimingAttrs(html);
+
+ expect(unresolved).toHaveLength(0);
+ });
+});
+
+describe("injectDurations", () => {
+ it("adds data-duration and data-end for resolved elements", () => {
+ const html = '<video id="v1" src="a.mp4" data-start="2">';
+ const result = injectDurations(html, [{ id: "v1", duration: 4 }]);
+
+ expect(result).toContain('data-duration="4"');
+ expect(result).toContain('data-end="6"');
+ });
+
+ it("does not overwrite existing data-duration", () => {
+ const html = '<video id="v1" src="a.mp4" data-start="0" data-duration="3">';
+ const result = injectDurations(html, [{ id: "v1", duration: 10 }]);
+
+ // data-duration already present, should not be duplicated
+ expect(result).toContain('data-duration="3"');
+ });
+});
+
+describe("extractResolvedMedia", () => {
+ it("extracts video and audio elements with data-duration set", () => {
+ const html = [
+ '<video id="v1" src="vid.mp4" data-start="1" data-duration="5" data-media-start="0">',
+ '<audio id="a1" src="song.mp3" data-start="0" data-duration="10">',
+ '<video id="v2" src="other.mp4" data-start="0">', // no duration
+ ].join("\n");
+
+ const resolved = extractResolvedMedia(html);
+
+ expect(resolved).toHaveLength(2);
+ expect(resolved[0].id).toBe("v1");
+ expect(resolved[0].tagName).toBe("video");
+ expect(resolved[0].duration).toBe(5);
+ expect(resolved[0].start).toBe(1);
+ expect(resolved[1].id).toBe("a1");
+ expect(resolved[1].tagName).toBe("audio");
+ expect(resolved[1].duration).toBe(10);
+ });
+
+ it("skips elements with invalid durations", () => {
+ const html = '<video id="v1" src="a.mp4" data-start="0" data-duration="NaN">';
+ const resolved = extractResolvedMedia(html);
+ expect(resolved).toHaveLength(0);
+ });
+});
+
+describe("clampDurations", () => {
+ it("replaces data-duration and recomputes data-end", () => {
+ const html = '<video id="v1" src="a.mp4" data-start="2" data-duration="10" data-end="12">';
+ const result = clampDurations(html, [{ id: "v1", duration: 5 }]);
+
+ expect(result).toContain('data-duration="5"');
+ expect(result).toContain('data-end="7"');
+ });
+});
diff --git a/packages/core/src/compiler/timingCompiler.ts b/packages/core/src/compiler/timingCompiler.ts
new file mode 100644
index 0000000000..60a429a0d4
--- /dev/null
+++ b/packages/core/src/compiler/timingCompiler.ts
@@ -0,0 +1,250 @@
+/**
+ * Timing Compiler
+ *
+ * Shared, pure HTML compilation that normalizes timing attributes.
+ * Works in both Node.js and browser (no dependencies, regex-based).
+ *
+ * Guarantees every timed element gets:
+ * - data-end (computed from data-start + data-duration when possible)
+ * - data-has-audio="true" on <video> elements
+ *
+ * For elements without data-duration (e.g. videos relying on source duration),
+ * this compiler identifies them as "unresolved" so the caller can provide
+ * durations via an environment-specific resolver (ffprobe, el.duration, etc.)
+ * and call injectDurations() to complete the compilation.
+ */
+
+// ── Types ────────────────────────────────────────────────────────────────
+
+export interface UnresolvedElement {
+ id: string;
+ tagName: string;
+ src?: string;
+ start: number;
+ end?: number;
+ duration?: number;
+ mediaStart: number;
+ compositionSrc?: string;
+}
+
+export interface ResolvedDuration {
+ id: string;
+ duration: number;
+}
+
+export interface ResolvedMediaElement {
+ id: string;
+ tagName: string;
+ src?: string;
+ start: number;
+ duration: number;
+ mediaStart: number;
+}
+
+export interface CompilationResult {
+ html: string;
+ unresolved: UnresolvedElement[];
+}
+
+// ── Helpers ──────────────────────────────────────────────────────────────
+
+function getAttr(tag: string, attr: string): string | null {
+ const match = tag.match(new RegExp(`${attr}=["']([^"']+)["']`));
+ return match ? match[1] ?? null : null;
+}
+
+function hasAttr(tag: string, attr: string): boolean {
+ return new RegExp(`${attr}=["']`).test(tag);
+}
+
+function injectAttr(tag: string, attr: string, value: string): string {
+ return tag.replace(/>$/, ` ${attr}="${value}">`);
+}
+
+// ── Core compilation ─────────────────────────────────────────────────────
+
+function compileTag(tag: string, isVideo: boolean): { tag: string; unresolved: UnresolvedElement | null } {
+ let result = tag;
+ let unresolved: UnresolvedElement | null = null;
+
+ const id = getAttr(result, "id");
+ const startStr = getAttr(result, "data-start");
+ const start = startStr !== null ? parseFloat(startStr) : 0;
+ const mediaStartStr = getAttr(result, "data-media-start");
+ const mediaStart = mediaStartStr ? parseFloat(mediaStartStr) : 0;
+
+ // 1. Compute data-end from data-start + data-duration
+ if (!hasAttr(result, "data-end")) {
+ const durationStr = getAttr(result, "data-duration");
+ if (durationStr !== null) {
+ const end = start + parseFloat(durationStr);
+ result = injectAttr(result, "data-end", String(end));
+ } else if (id) {
+ // No data-duration: mark as unresolved so caller can provide it
+ unresolved = {
+ id,
+ tagName: isVideo ? "video" : "audio",
+ src: getAttr(result, "src") ?? undefined,
+ start,
+ mediaStart,
+ };
+ }
+ }
+
+ // 2. Add data-has-audio="true" to <video> elements
+ if (isVideo && !hasAttr(result, "data-has-audio")) {
+ result = injectAttr(result, "data-has-audio", "true");
+ }
+
+ return { tag: result, unresolved };
+}
+
+/**
+ * Compile timing attributes in HTML.
+ *
+ * Phase 1 (static): Adds data-end where data-duration exists,
+ * adds data-has-audio on videos.
+ *
+ * Returns the compiled HTML and a list of elements that could not be
+ * resolved statically (missing data-duration). The caller should resolve
+ * these via ffprobe / el.duration and call injectDurations().
+ */
+export function compileTimingAttrs(html: string): CompilationResult {
+ const unresolved: UnresolvedElement[] = [];
+
+ // Process <video ...> tags
+ html = html.replace(/<video[^>]*>/gi, (match) => {
+ const { tag, unresolved: u } = compileTag(match, true);
+ if (u) unresolved.push(u);
+ return tag;
+ });
+
+ // Process <audio ...> tags
+ html = html.replace(/<audio[^>]*>/gi, (match) => {
+ const { tag, unresolved: u } = compileTag(match, false);
+ if (u) unresolved.push(u);
+ return tag;
+ });
+
+ // Identify unresolved timed elements (divs with data-start but no data-end/data-duration)
+ // These are typically compositions whose duration depends on GSAP timelines
+ html.replace(/<(?:div|section)[^>]*>/gi, (match) => {
+ if (!hasAttr(match, "data-start")) return match;
+ if (hasAttr(match, "data-end") || hasAttr(match, "data-duration")) return match;
+
+ const id = getAttr(match, "id");
+ const compositionSrc = getAttr(match, "data-composition-src");
+ if (id) {
+ const startStr = getAttr(match, "data-start");
+ unresolved.push({
+ id,
+ tagName: "div",
+ start: startStr ? parseFloat(startStr) : 0,
+ mediaStart: 0,
+ compositionSrc: compositionSrc ?? undefined,
+ });
+ }
+
+ return match;
+ });
+
+ return { html, unresolved };
+}
+
+/**
+ * Inject resolved durations into compiled HTML.
+ *
+ * For each resolved element, adds data-duration and data-end attributes.
+ * Call this after resolving durations via ffprobe, el.duration, or
+ * GSAP timeline queries.
+ */
+export function injectDurations(html: string, resolutions: ResolvedDuration[]): string {
+ for (const { id, duration } of resolutions) {
+ // Match the element's opening tag by id
+ const idPattern = new RegExp(`(<[^>]*id=["']${escapeRegex(id)}["'][^>]*>)`, "gi");
+
+ html = html.replace(idPattern, (tag) => {
+ let result = tag;
+
+ // Add data-duration if missing
+ if (!hasAttr(result, "data-duration")) {
+ result = injectAttr(result, "data-duration", String(duration));
+ }
+
+ // Add data-end if missing
+ if (!hasAttr(result, "data-end")) {
+ const startStr = getAttr(result, "data-start");
+ const start = startStr ? parseFloat(startStr) : 0;
+ result = injectAttr(result, "data-end", String(start + duration));
+ }
+
+ return result;
+ });
+ }
+
+ return html;
+}
+
+function escapeRegex(str: string): string {
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+/**
+ * Extract video/audio elements that already have data-duration set.
+ * Used by callers to validate declared durations against actual source durations.
+ */
+export function extractResolvedMedia(html: string): ResolvedMediaElement[] {
+ const resolved: ResolvedMediaElement[] = [];
+
+ const mediaRegex = /<(?:video|audio)[^>]*>/gi;
+ let match: RegExpExecArray | null;
+ while ((match = mediaRegex.exec(html)) !== null) {
+ const tag = match[0];
+ const id = getAttr(tag, "id");
+ const durationStr = getAttr(tag, "data-duration");
+ if (!id || durationStr === null) continue;
+
+ const duration = parseFloat(durationStr);
+ if (!Number.isFinite(duration) || duration <= 0) continue;
+
+ const isVideo = /^<video/i.test(tag);
+ const startStr = getAttr(tag, "data-start");
+ const mediaStartStr = getAttr(tag, "data-media-start");
+
+ resolved.push({
+ id,
+ tagName: isVideo ? "video" : "audio",
+ src: getAttr(tag, "src") ?? undefined,
+ start: startStr !== null ? parseFloat(startStr) : 0,
+ duration,
+ mediaStart: mediaStartStr ? parseFloat(mediaStartStr) : 0,
+ });
+ }
+
+ return resolved;
+}
+
+/**
+ * Clamp existing data-duration and data-end on media elements.
+ * For each resolution, replaces the declared duration with the clamped value
+ * and recomputes data-end accordingly.
+ */
+export function clampDurations(html: string, clamps: ResolvedDuration[]): string {
+ for (const { id, duration } of clamps) {
+ const idPattern = new RegExp(`(<[^>]*id=["']${escapeRegex(id)}["'][^>]*>)`, "gi");
+
+ html = html.replace(idPattern, (tag) => {
+ // Replace data-duration value
+ tag = tag.replace(/data-duration=["'][^"']*["']/, `data-duration="${duration}"`);
+
+ // Recompute data-end from data-start + clamped duration
+ const startStr = getAttr(tag, "data-start");
+ const start = startStr ? parseFloat(startStr) : 0;
+ tag = tag.replace(/data-end=["'][^"']*["']/, `data-end="${start + duration}"`);
+
+ return tag;
+ });
+ }
+
+ return html;
+}
diff --git a/packages/core/src/core.types.ts b/packages/core/src/core.types.ts
new file mode 100644
index 0000000000..80806c395b
--- /dev/null
+++ b/packages/core/src/core.types.ts
@@ -0,0 +1,364 @@
+// ── Shared cross-package types ──────────────────────────────────────────────
+
+export type ExecutionMode = "planning" | "design" | "execution" | null;
+
+/** Video orientation / aspect ratio. */
+export type Orientation = "16:9" | "9:16";
+
+export interface Asset {
+ id: string;
+ url: string;
+ type: string;
+ is_reference?: boolean;
+ /** Duration in seconds for video/audio assets */
+ duration?: number;
+}
+
+// ── Timeline types ──────────────────────────────────────────────────────────
+
+export type TimelineElementType = "video" | "image" | "text" | "audio" | "composition";
+export type MediaElementType = "video" | "image" | "audio";
+
+export type CanvasResolution = "landscape" | "portrait";
+
+export const CANVAS_DIMENSIONS = {
+ landscape: { width: 1920, height: 1080 },
+ portrait: { width: 1080, height: 1920 },
+} as const;
+
+export interface TimelineElementBase {
+ id: string;
+ type: TimelineElementType;
+ name: string;
+ startTime: number;
+ duration: number;
+ zIndex: number;
+ x?: number;
+ y?: number;
+ scale?: number;
+ opacity?: number;
+}
+
+export interface TimelineMediaElement extends TimelineElementBase {
+ type: MediaElementType;
+ src: string;
+ mediaStartTime?: number;
+ sourceDuration?: number;
+ isAroll?: boolean;
+ sourceWidth?: number;
+ sourceHeight?: number;
+ volume?: number; // 0-1 (0% to 100%), default 1.0
+ hasAudio?: boolean; // For videos - indicates if video has audio track
+}
+
+export interface WaveformData {
+ peaks: number[];
+ duration: number;
+ sampleRate?: number;
+}
+
+export interface TimelineTextElement extends TimelineElementBase {
+ type: "text";
+ content: string;
+ color?: string;
+ fontSize?: number;
+ textShadow?: boolean;
+ fontFamily?: string;
+ fontWeight?: number;
+ textOutline?: boolean;
+ textOutlineColor?: string;
+ textOutlineWidth?: number;
+ textHighlight?: boolean;
+ textHighlightColor?: string;
+ textHighlightPadding?: number;
+ textHighlightRadius?: number;
+}
+
+export interface TimelineCompositionElement extends TimelineElementBase {
+ type: "composition";
+ src: string;
+ compositionId: string;
+ scale?: number;
+ sourceDuration?: number;
+ variableValues?: Record<string, string | number | boolean>;
+ sourceWidth?: number;
+ sourceHeight?: number;
+}
+
+// Composition Variable Types
+export type CompositionVariableType = "string" | "number" | "color" | "boolean" | "enum";
+
+export interface CompositionVariableBase {
+ id: string;
+ type: CompositionVariableType;
+ label: string;
+ description?: string;
+}
+
+export interface StringVariable extends CompositionVariableBase {
+ type: "string";
+ default: string;
+ placeholder?: string;
+ maxLength?: number;
+}
+
+export interface NumberVariable extends CompositionVariableBase {
+ type: "number";
+ default: number;
+ min?: number;
+ max?: number;
+ step?: number;
+ unit?: string;
+}
+
+export interface ColorVariable extends CompositionVariableBase {
+ type: "color";
+ default: string;
+}
+
+export interface BooleanVariable extends CompositionVariableBase {
+ type: "boolean";
+ default: boolean;
+}
+
+export interface EnumVariable extends CompositionVariableBase {
+ type: "enum";
+ default: string;
+ options: { value: string; label: string }[];
+}
+
+export type CompositionVariable = StringVariable | NumberVariable | ColorVariable | BooleanVariable | EnumVariable;
+
+export interface CompositionSpec {
+ id: string;
+ duration: number;
+ variables: CompositionVariable[];
+}
+
+export function isStringVariable(v: CompositionVariable): v is StringVariable {
+ return v.type === "string";
+}
+
+export function isNumberVariable(v: CompositionVariable): v is NumberVariable {
+ return v.type === "number";
+}
+
+export function isColorVariable(v: CompositionVariable): v is ColorVariable {
+ return v.type === "color";
+}
+
+export function isBooleanVariable(v: CompositionVariable): v is BooleanVariable {
+ return v.type === "boolean";
+}
+
+export function isEnumVariable(v: CompositionVariable): v is EnumVariable {
+ return v.type === "enum";
+}
+
+export type TimelineElement = TimelineMediaElement | TimelineTextElement | TimelineCompositionElement;
+
+export function isTextElement(el: TimelineElement): el is TimelineTextElement {
+ return el.type === "text";
+}
+
+export function isMediaElement(el: TimelineElement): el is TimelineMediaElement {
+ return el.type === "video" || el.type === "image" || el.type === "audio";
+}
+
+export function isCompositionElement(el: TimelineElement): el is TimelineCompositionElement {
+ return el.type === "composition";
+}
+
+export interface MediaFile {
+ id: string;
+ name: string;
+ type: TimelineElementType;
+ src: string;
+ file?: File;
+ duration?: number;
+ compositionId?: string;
+ sourceWidth?: number; // Intrinsic width for compositions
+ sourceHeight?: number; // Intrinsic height for compositions
+}
+
+export const TIMELINE_COLORS: Record<TimelineElementType, string> = {
+ video: "#ec4899",
+ image: "#3b82f6",
+ text: "#06b6d4",
+ audio: "#10b981",
+ composition: "#f97316",
+};
+
+export const DEFAULT_DURATIONS: Record<TimelineElementType, number> = {
+ video: 5,
+ image: 5,
+ text: 2,
+ audio: 5,
+ composition: 5,
+};
+
+export interface CompositionAPI {
+ id: string;
+ duration: number;
+ seek(time: number): void;
+ getTime(): number;
+ getDuration(): number;
+}
+
+// ── Player API types (used by runtime) ────────────────────────────────────
+
+export interface PlayerAPI {
+ play(): void;
+ pause(): void;
+ seek(time: number): void;
+ getTime(): number;
+ getDuration(): number;
+ isPlaying(): boolean;
+ getMainTimeline(): unknown;
+ getElementBounds(elementId: string): void;
+ getElementsAtPoint(x: number, y: number): void;
+ setElementPosition(elementId: string, x: number, y: number): void;
+ previewElementPosition(elementId: string, x: number, y: number): void;
+ setElementKeyframes(
+ elementId: string,
+ keyframes: Array<{
+ id: string;
+ time: number;
+ properties: { x?: number; y?: number };
+ }> | null
+ ): void;
+ setElementScale(elementId: string, scale: number): void;
+ setElementFontSize(elementId: string, fontSize: number): void;
+ setElementTextContent(elementId: string, content: string): void;
+ setElementTextColor(elementId: string, color: string): void;
+ setElementTextShadow(elementId: string, enabled: boolean): void;
+ setElementTextFontWeight(elementId: string, weight: number): void;
+ setElementTextFontFamily(elementId: string, fontFamily: string): void;
+ setElementTextOutline(elementId: string, enabled: boolean, color?: string, width?: number): void;
+ setElementTextHighlight(elementId: string, enabled: boolean, color?: string, padding?: number, radius?: number): void;
+ setElementVolume(elementId: string, volume: number): void;
+ setStageZoom(scale: number, focusX: number, focusY: number): void;
+ getStageZoom(): { scale: number; focusX: number; focusY: number };
+ setStageZoomKeyframes(
+ keyframes: Array<{
+ id: string;
+ time: number;
+ zoom: { scale: number; focusX: number; focusY: number };
+ ease?: string;
+ }> | null
+ ): void;
+ getStageZoomKeyframes(): Array<{
+ id: string;
+ time: number;
+ zoom: { scale: number; focusX: number; focusY: number };
+ ease?: string;
+ }>;
+ addElement(data: AddElementData): boolean;
+ removeElement(elementId: string): boolean;
+ updateElementTiming(elementId: string, start?: number, end?: number): boolean;
+ setElementTiming(elementId: string, startTime: number, duration: number, mediaStartTime?: number): void;
+ updateElementSrc(elementId: string, src: string): boolean;
+ updateElementLayer(elementId: string, zIndex: number): boolean;
+ updateElementBasePosition(elementId: string, x?: number, y?: number, scale?: number): boolean;
+ markTimelineDirty(): void;
+ isTimelineDirty(): boolean;
+ rebuildTimeline(): void;
+ ensureTimeline(): void;
+ enableRenderMode(): void;
+ disableRenderMode(): void;
+ renderSeek(time: number): void;
+ getElementVisibility(elementId: string): { visible: boolean; opacity?: number };
+ getVisibleElements(): Array<{ id: string; tagName: string; start: number; end: number }>;
+ getRenderState(): { time: number; duration: number; isPlaying: boolean; renderMode: boolean; timelineDirty: boolean };
+}
+
+export interface AddElementData {
+ id: string;
+ type: "video" | "image" | "text" | "audio" | "composition";
+ name?: string;
+ src?: string;
+ content?: string;
+ start: number;
+ end: number;
+ zIndex?: number;
+ x?: number;
+ y?: number;
+ scale?: number;
+ fontSize?: number;
+ color?: string;
+ textShadow?: boolean;
+ fontWeight?: number;
+ textOutline?: boolean;
+ textOutlineColor?: string;
+ textOutlineWidth?: number;
+ textHighlight?: boolean;
+ textHighlightColor?: string;
+ textHighlightPadding?: number;
+ textHighlightRadius?: number;
+ compositionId?: string;
+ sourceWidth?: number;
+ sourceHeight?: number;
+ isAroll?: boolean;
+}
+
+export interface ValidationResult {
+ valid: boolean;
+ errors: string[];
+ warnings: string[];
+}
+
+export interface CompositionAsset {
+ id: string;
+ name: string;
+ type: "composition";
+ src: string;
+ duration: number;
+ compositionId: string;
+ thumbnail?: string;
+}
+
+export interface Keyframe {
+ id: string;
+ time: number;
+ properties: Partial<KeyframeProperties>;
+ ease?: string;
+}
+
+export interface KeyframeProperties {
+ x: number;
+ y: number;
+ opacity: number;
+ scale: number;
+ scaleX: number;
+ scaleY: number;
+ rotation: number;
+ width: number;
+ height: number;
+}
+
+export interface ElementKeyframes {
+ elementId: string;
+ keyframes: Keyframe[];
+}
+
+export interface StageZoom {
+ scale: number;
+ focusX: number;
+ focusY: number;
+}
+
+export interface StageZoomKeyframe {
+ id: string;
+ time: number;
+ zoom: StageZoom;
+ ease?: string;
+}
+
+export function getDefaultStageZoom(resolution: CanvasResolution): StageZoom {
+ const { width, height } = CANVAS_DIMENSIONS[resolution];
+ return {
+ scale: 1,
+ focusX: width / 2,
+ focusY: height / 2,
+ };
+}
diff --git a/packages/core/src/generators/hyperframes.test.ts b/packages/core/src/generators/hyperframes.test.ts
new file mode 100644
index 0000000000..84430eebfc
--- /dev/null
+++ b/packages/core/src/generators/hyperframes.test.ts
@@ -0,0 +1,296 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { describe, it, expect } from "vitest";
+import { generateHyperframesHtml, generateGsapTimelineScript, generateHyperframesStyles } from "./hyperframes.js";
+import { GSAP_CDN } from "../templates/constants.js";
+import type { TimelineTextElement, TimelineMediaElement, TimelineCompositionElement } from "../core.types";
+
+function makeTextElement(overrides: Partial<TimelineTextElement> = {}): TimelineTextElement {
+ return {
+ id: "text-1",
+ type: "text",
+ name: "Title",
+ content: "Hello World",
+ startTime: 0,
+ duration: 5,
+ zIndex: 1,
+ ...overrides,
+ };
+}
+
+function makeVideoElement(overrides: Partial<TimelineMediaElement> = {}): TimelineMediaElement {
+ return {
+ id: "vid-1",
+ type: "video",
+ name: "Background",
+ src: "video.mp4",
+ startTime: 0,
+ duration: 10,
+ zIndex: 0,
+ ...overrides,
+ };
+}
+
+describe("generateHyperframesHtml", () => {
+ it("generates valid HTML with proper data attributes", () => {
+ const elements = [makeTextElement()];
+ const html = generateHyperframesHtml(elements, 5);
+
+ expect(html).toContain("<!DOCTYPE html>");
+ expect(html).toContain("data-composition-id=");
+ expect(html).toContain("data-composition-duration=");
+ expect(html).toContain('id="stage"');
+ expect(html).toContain('id="stage-zoom-container"');
+ });
+
+ it("includes element data attributes", () => {
+ const elements = [makeTextElement({ id: "my-text", startTime: 2, duration: 3 })];
+ const html = generateHyperframesHtml(elements, 5);
+
+ expect(html).toContain('id="my-text"');
+ expect(html).toContain('data-start="2"');
+ expect(html).toContain('data-end="5"');
+ expect(html).toContain('data-layer="1"');
+ });
+
+ it("includes GSAP CDN script tag when includeScripts is true", () => {
+ const elements = [makeTextElement()];
+ const html = generateHyperframesHtml(elements, 5, { includeScripts: true });
+
+ expect(html).toContain(`<script src="${GSAP_CDN}"></script>`);
+ });
+
+ it("does NOT include GSAP CDN by default", () => {
+ const elements = [makeTextElement()];
+ const html = generateHyperframesHtml(elements, 5);
+
+ expect(html).not.toContain(GSAP_CDN);
+ });
+
+ it("includes timeline script when includeScripts is true", () => {
+ const elements = [makeTextElement()];
+ const html = generateHyperframesHtml(elements, 5, { includeScripts: true });
+
+ expect(html).toContain("gsap.timeline({ paused: true })");
+ });
+
+ it("generates GSAP timeline with visibility animations when includeScripts is true", () => {
+ const elements = [makeTextElement({ id: "el-1", startTime: 1, duration: 3 })];
+ const html = generateHyperframesHtml(elements, 5, { includeScripts: true });
+
+ // Default animations include visibility bookends
+ expect(html).toContain('tl.set("#el-1"');
+ expect(html).toContain('visibility: "hidden"');
+ expect(html).toContain('visibility: "visible"');
+ });
+
+ it("sets resolution data attribute", () => {
+ const elements = [makeTextElement()];
+
+ const landscapeHtml = generateHyperframesHtml(elements, 5, { resolution: "landscape" });
+ expect(landscapeHtml).toContain('data-resolution="landscape"');
+
+ const portraitHtml = generateHyperframesHtml(elements, 5, { resolution: "portrait" });
+ expect(portraitHtml).toContain('data-resolution="portrait"');
+ });
+
+ it("generates video elements with proper tags", () => {
+ const elements = [makeVideoElement()];
+ const html = generateHyperframesHtml(elements, 10);
+
+ expect(html).toContain("<video");
+ expect(html).toContain('src="video.mp4"');
+ expect(html).toContain("playsinline");
+ });
+
+ it("generates text elements with content wrapper div", () => {
+ const elements = [makeTextElement({ content: "My Content" })];
+ const html = generateHyperframesHtml(elements, 5);
+
+ expect(html).toContain("<div>My Content</div>");
+ });
+
+ it("includes custom compositionId", () => {
+ const elements = [makeTextElement()];
+ const html = generateHyperframesHtml(elements, 5, { compositionId: "test-comp-123" });
+
+ expect(html).toContain('data-composition-id="test-comp-123"');
+ });
+
+ it("calculates total duration from elements if they exceed provided duration", () => {
+ const elements = [makeTextElement({ startTime: 0, duration: 15 })];
+ const html = generateHyperframesHtml(elements, 5);
+
+ expect(html).toContain('data-composition-duration="15"');
+ });
+
+ it("includes style tags when includeStyles is true", () => {
+ const elements = [makeTextElement()];
+ const html = generateHyperframesHtml(elements, 5, { includeStyles: true });
+
+ expect(html).toContain('<style data-hf-core="true">');
+ });
+
+ it("includes custom styles when provided", () => {
+ const elements = [makeTextElement()];
+ const html = generateHyperframesHtml(elements, 5, {
+ styles: ".custom { color: red; }",
+ includeStyles: true,
+ });
+
+ expect(html).toContain('<style data-hf-custom="true">');
+ expect(html).toContain(".custom { color: red; }");
+ });
+
+ it("serializes keyframes as data attributes", () => {
+ const elements = [makeTextElement({ id: "text-kf" })];
+ const keyframes = {
+ "text-kf": [
+ { id: "kf1", time: 0, properties: { opacity: 0 } },
+ { id: "kf2", time: 1, properties: { opacity: 1 } },
+ ],
+ };
+ const html = generateHyperframesHtml(elements, 5, { keyframes });
+
+ expect(html).toContain("data-keyframes=");
+ expect(html).toContain("kf1");
+ expect(html).toContain("kf2");
+ });
+
+ it("serializes zoom keyframes on zoom container", () => {
+ const elements = [makeTextElement()];
+ const stageZoomKeyframes = [
+ { id: "z1", time: 0, zoom: { scale: 1, focusX: 960, focusY: 540 } },
+ { id: "z2", time: 5, zoom: { scale: 2, focusX: 400, focusY: 300 } },
+ ];
+ const html = generateHyperframesHtml(elements, 10, { stageZoomKeyframes });
+
+ expect(html).toContain("data-zoom-keyframes=");
+ });
+
+ it("includes x, y, scale data attributes for non-default values", () => {
+ const elements = [makeVideoElement({ x: 100, y: 200, scale: 1.5, opacity: 0.8 })];
+ const html = generateHyperframesHtml(elements, 10);
+
+ expect(html).toContain('data-x="100"');
+ expect(html).toContain('data-y="200"');
+ expect(html).toContain('data-scale="1.5"');
+ expect(html).toContain('data-opacity="0.8"');
+ });
+
+ it("omits x, y, scale, opacity data attributes when at default values", () => {
+ const elements = [makeVideoElement({ x: 0, y: 0, scale: 1, opacity: 1 })];
+ const html = generateHyperframesHtml(elements, 10);
+
+ expect(html).not.toContain("data-x=");
+ expect(html).not.toContain("data-y=");
+ expect(html).not.toContain("data-scale=");
+ expect(html).not.toContain("data-opacity=");
+ });
+});
+
+describe("generateGsapTimelineScript", () => {
+ it("generates a timeline script with visibility animations", () => {
+ const elements = [makeTextElement({ id: "el1", startTime: 1, duration: 4 })];
+ const script = generateGsapTimelineScript(elements, 5);
+
+ expect(script).toContain("const tl = gsap.timeline({ paused: true });");
+ expect(script).toContain('tl.set("#el1"');
+ expect(script).toContain('visibility: "hidden"');
+ expect(script).toContain('visibility: "visible"');
+ });
+
+ it("generates empty timeline for no elements", () => {
+ const script = generateGsapTimelineScript([], 5);
+
+ expect(script).toContain("const tl = gsap.timeline({ paused: true });");
+ expect(script).toContain("duration: 5");
+ });
+
+ it("includes media sync for video elements", () => {
+ const elements = [makeVideoElement()];
+ const script = generateGsapTimelineScript(elements, 10);
+
+ expect(script).toContain("Sync media playback");
+ expect(script).toContain("media.currentTime");
+ });
+
+ it("generates initial position sets for elements with x/y offsets", () => {
+ const elements = [makeVideoElement({ id: "vid-pos", x: 100, y: 200 })];
+ const script = generateGsapTimelineScript(elements, 10);
+
+ expect(script).toContain('tl.set("#vid-pos", { x: 100, y: 200 }');
+ });
+
+ it("generates animations from keyframes", () => {
+ const elements = [makeTextElement({ id: "el-kf", startTime: 0, duration: 5 })];
+ const keyframes = {
+ "el-kf": [
+ { id: "kf1", time: 0, properties: { opacity: 0 } },
+ { id: "kf2", time: 1, properties: { opacity: 1 } },
+ ],
+ };
+ const script = generateGsapTimelineScript(elements, 5, { keyframes });
+
+ // Should contain keyframe-based animations
+ expect(script).toContain("el-kf");
+ });
+});
+
+describe("generateHyperframesStyles", () => {
+ it("generates core CSS with stage dimensions for landscape", () => {
+ const elements = [makeTextElement()];
+ const { coreCss } = generateHyperframesStyles(elements, "landscape");
+
+ expect(coreCss).toContain("width: 1920px");
+ expect(coreCss).toContain("height: 1080px");
+ expect(coreCss).toContain("#stage");
+ });
+
+ it("generates core CSS with stage dimensions for portrait", () => {
+ const elements = [makeTextElement()];
+ const { coreCss } = generateHyperframesStyles(elements, "portrait");
+
+ expect(coreCss).toContain("width: 1080px");
+ expect(coreCss).toContain("height: 1920px");
+ });
+
+ it("generates element-specific styles for text", () => {
+ const elements = [makeTextElement({ id: "styled-text", fontSize: 72, color: "red" })];
+ const { coreCss } = generateHyperframesStyles(elements, "landscape");
+
+ expect(coreCss).toContain("#styled-text");
+ expect(coreCss).toContain("position: absolute");
+ });
+
+ it("generates element-specific styles for video", () => {
+ const elements = [makeVideoElement({ id: "vid-styled" })];
+ const { coreCss } = generateHyperframesStyles(elements, "landscape");
+
+ expect(coreCss).toContain("#vid-styled");
+ expect(coreCss).toContain("object-fit: contain");
+ });
+
+ it("includes custom CSS when provided", () => {
+ const elements = [makeTextElement()];
+ const { customCss } = generateHyperframesStyles(elements, "landscape", ".custom { color: blue; }");
+
+ expect(customCss).toContain(".custom { color: blue; }");
+ });
+
+ it("generates Google Fonts link for Inter (always included)", () => {
+ const elements = [makeTextElement()];
+ const { googleFontsLink } = generateHyperframesStyles(elements, "landscape");
+
+ expect(googleFontsLink).toContain("fonts.googleapis.com");
+ expect(googleFontsLink).toContain("Inter");
+ });
+
+ it("includes additional font families from text elements", () => {
+ const elements = [makeTextElement({ fontFamily: "Montserrat" })];
+ const { googleFontsLink } = generateHyperframesStyles(elements, "landscape");
+
+ expect(googleFontsLink).toContain("Montserrat");
+ });
+});
diff --git a/packages/core/src/generators/hyperframes.ts b/packages/core/src/generators/hyperframes.ts
new file mode 100644
index 0000000000..af7780c708
--- /dev/null
+++ b/packages/core/src/generators/hyperframes.ts
@@ -0,0 +1,737 @@
+import type {
+ TimelineElement,
+ CanvasResolution,
+ Keyframe,
+ StageZoomKeyframe,
+} from "../core.types";
+import {
+ CANVAS_DIMENSIONS,
+ isTextElement,
+ isMediaElement,
+ isCompositionElement,
+} from "../core.types";
+import type { GsapAnimation } from "../parsers/gsapParser";
+import { serializeGsapAnimations, keyframesToGsapAnimations } from "../parsers/gsapParser";
+import { GSAP_CDN, BASE_STYLES, ZOOM_CONTAINER_STYLES } from "../templates/constants";
+
+const GOOGLE_FONTS_BASE = "https://fonts.googleapis.com/css2";
+const FONT_WEIGHTS: Record<string, string> = {
+ Inter: "400;500;600;700;800;900",
+ Roboto: "400;500;700;900",
+ Montserrat: "400;500;600;700;800;900",
+ Poppins: "400;500;600;700;800;900",
+ "Bebas Neue": "400",
+ Oswald: "400;500;600;700",
+ Anton: "400",
+ "Playfair Display": "400;500;600;700;800;900",
+ Lora: "400;500;600;700",
+ Pacifico: "400",
+ "Permanent Marker": "400",
+ "Fira Code": "400;500;600;700",
+};
+
+function generateGoogleFontsUrl(fontFamilies: string[]): string | null {
+ if (fontFamilies.length === 0) return null;
+
+ const families = fontFamilies
+ .filter((f) => f in FONT_WEIGHTS)
+ .map((f) => {
+ const weights = FONT_WEIGHTS[f];
+ const encodedName = f.replace(/ /g, "+");
+ return `family=${encodedName}:wght@${weights}`;
+ });
+
+ if (families.length === 0) return null;
+ return `${GOOGLE_FONTS_BASE}?${families.join("&")}&display=swap`;
+}
+
+export interface SerializeOptions {
+ animations?: GsapAnimation[];
+ styles?: string;
+ generateDefaultAnimations?: boolean;
+ resolution?: CanvasResolution;
+ compositionId?: string;
+ keyframes?: Record<string, Keyframe[]>;
+ stageZoomKeyframes?: StageZoomKeyframe[];
+ includeScripts?: boolean;
+ includeStyles?: boolean;
+}
+
+/**
+ * Stage Positioning Conventions:
+ *
+ * 1. All elements are absolutely positioned relative to the #stage container
+ * 2. The #stage has position: relative and fixed dimensions (1920x1080 or 1080x1920)
+ * 3. Elements start with opacity: 0 and are revealed via GSAP animations
+ *
+ * Media Elements (video, image):
+ * - position: absolute (relative to #stage)
+ * - width: 100%, height: 100% (fill the stage)
+ * - object-fit: contain (preserve aspect ratio, centered, no cropping)
+ * - This ensures media is always visible and centered within the stage
+ *
+ * Text Elements:
+ * - position: absolute, width/height: 100%
+ * - Inner div uses flexbox to center content (selected via > div)
+ *
+ * Audio Elements:
+ * - position: absolute (invisible, for timing only)
+ */
+function sortElements(elements: TimelineElement[]): TimelineElement[] {
+ return [...elements].sort((a, b) => {
+ if (a.zIndex !== b.zIndex) {
+ return (a.zIndex ?? 0) - (b.zIndex ?? 0);
+ }
+ return a.startTime - b.startTime;
+ });
+}
+
+export function generateHyperframesStyles(
+ elements: TimelineElement[],
+ resolution: CanvasResolution,
+ customStyles?: string,
+): { coreCss: string; customCss: string; googleFontsLink: string } {
+ const { width, height } = CANVAS_DIMENSIONS[resolution];
+ const sortedElements = sortElements(elements);
+ const elementStyles = sortedElements.map((el) => generateElementStyles(el)).join("\n");
+
+ // Collect unique font families from text elements
+ const usedFonts = new Set<string>();
+ for (const el of sortedElements) {
+ if (isTextElement(el) && el.fontFamily) {
+ usedFonts.add(el.fontFamily);
+ }
+ }
+ // Always include Inter as the default
+ usedFonts.add("Inter");
+ const googleFontsUrl = generateGoogleFontsUrl([...usedFonts]);
+
+ const googleFontsLink = googleFontsUrl
+ ? `<link data-hf-fonts="true" rel="preconnect" href="https://fonts.googleapis.com">
+ <link data-hf-fonts="true" rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link data-hf-fonts="true" href="${googleFontsUrl}" rel="stylesheet">`
+ : "";
+
+ const coreCss = `${BASE_STYLES}
+#stage { position: relative; width: ${width}px; height: ${height}px; overflow: hidden; background: #fff; }
+#stage-zoom-container { ${ZOOM_CONTAINER_STYLES} }
+${elementStyles}`.trim();
+
+ const customCss = customStyles?.trim() ? customStyles.trim() : "";
+
+ return { coreCss, customCss, googleFontsLink };
+}
+
+function generateElementStyles(element: TimelineElement): string {
+ const baseStyles = "position: absolute;";
+
+ if (isTextElement(element)) {
+ const fontSize = element.fontSize ?? 48;
+ const fontWeight = element.fontWeight ?? 700;
+ const fontFamily = element.fontFamily ?? "Inter";
+ const color = element.color ?? "white";
+ const textShadow = element.textShadow !== false ? "text-shadow: 2px 2px 4px rgba(0,0,0,0.8);" : "";
+
+ // Text outline using -webkit-text-stroke
+ const textOutline = element.textOutline
+ ? `-webkit-text-stroke: ${element.textOutlineWidth ?? 2}px ${
+ element.textOutlineColor ?? "#000000"
+ }; paint-order: stroke fill;`
+ : "";
+
+ // Text highlight using background
+ const textHighlight = element.textHighlight
+ ? `background-color: ${element.textHighlightColor ?? "yellow"}; padding: ${element.textHighlightPadding ?? 4}px ${
+ (element.textHighlightPadding ?? 4) * 1.5
+ }px; border-radius: ${
+ element.textHighlightRadius ?? 4
+ }px; box-decoration-break: clone; -webkit-box-decoration-break: clone;`
+ : "";
+
+ return ` #${element.id} { ${baseStyles} width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; pointer-events: none; }
+ #${element.id} > div { font-family: '${fontFamily}', sans-serif; font-size: ${fontSize}px; font-weight: ${fontWeight}; color: ${color}; ${textShadow} ${textOutline} ${textHighlight} pointer-events: auto; cursor: grab; white-space: pre-wrap; text-align: center; }`;
+ }
+
+ switch (element.type) {
+ case "video":
+ // Videos fill the stage with standard CSS positioning (0,0 = top-left)
+ return ` #${element.id} { ${baseStyles} width: 100%; height: 100%; object-fit: contain; transform-origin: center center; }`;
+ case "image":
+ // Images use standard CSS positioning (0,0 = top-left)
+ return ` #${element.id} { ${baseStyles} max-width: 100%; max-height: 100%; transform-origin: center center; }`;
+ case "audio":
+ return ` #${element.id} { ${baseStyles} }`;
+ case "composition":
+ // Compositions use standard CSS positioning (0,0 = top-left)
+ return ` #${element.id} { ${baseStyles} width: 100%; height: 100%; position: absolute; }`;
+ }
+}
+
+export function generateGsapTimelineScript(
+ elements: TimelineElement[],
+ totalDuration: number,
+ options: SerializeOptions = {},
+): string {
+ const {
+ animations,
+ generateDefaultAnimations = true,
+ resolution = "landscape",
+ keyframes,
+ stageZoomKeyframes,
+ } = options;
+
+ const { width, height } = CANVAS_DIMENSIONS[resolution];
+ const sortedElements = sortElements(elements);
+
+ const hasMedia = sortedElements.some((el) => el.type === "video" || el.type === "audio");
+
+ // Convert keyframes to GSAP animations
+ let keyframeAnimations: GsapAnimation[] = [];
+ if (keyframes) {
+ for (const element of sortedElements) {
+ const elementKeyframes = keyframes[element.id];
+ if (elementKeyframes && elementKeyframes.length > 0) {
+ const baseScale = isMediaElement(element) || isCompositionElement(element) ? (element.scale ?? 1) : 1;
+ const converted = keyframesToGsapAnimations(element.id, elementKeyframes, element.startTime, {
+ x: element.x ?? 0,
+ y: element.y ?? 0,
+ scale: baseScale,
+ });
+ keyframeAnimations = keyframeAnimations.concat(converted);
+ }
+ }
+ }
+
+ // Generate zoom keyframes GSAP animations
+ const zoomAnimations = generateZoomGsapAnimations(stageZoomKeyframes || [], width, height);
+
+ // Generate initial position/scale set() calls for all elements
+ // This must be included regardless of keyframe animations
+ const initialPositionSets = generateInitialPositionSets(sortedElements, keyframes);
+
+ // Generate visibility animations for elements without keyframes
+ // When using keyframes path, elements without keyframes need explicit visibility
+ const visibilityAnimations = generateVisibilityForElementsWithoutKeyframes(sortedElements, keyframes);
+
+ let gsapScript: string;
+ if (animations && animations.length > 0) {
+ // Merge provided animations with keyframe animations
+ const allAnimations = [...animations, ...keyframeAnimations];
+ gsapScript = serializeGsapAnimations(allAnimations, "tl", {
+ includeMediaSync: hasMedia,
+ });
+ // Prepend initial positions and visibility for elements without keyframes, append zoom animations
+ const prependAnimations = [initialPositionSets, visibilityAnimations].filter(Boolean).join("\n");
+ if (prependAnimations) {
+ gsapScript = gsapScript.replace(
+ "const tl = gsap.timeline({ paused: true });",
+ `const tl = gsap.timeline({ paused: true });\n${prependAnimations}`,
+ );
+ }
+ if (zoomAnimations) {
+ gsapScript += "\n" + zoomAnimations;
+ }
+ } else if (keyframeAnimations.length > 0) {
+ // Use only keyframe animations
+ gsapScript = serializeGsapAnimations(keyframeAnimations, "tl", {
+ includeMediaSync: hasMedia,
+ });
+ // Prepend initial positions and visibility for elements without keyframes, append zoom animations
+ const prependAnimations = [initialPositionSets, visibilityAnimations].filter(Boolean).join("\n");
+ if (prependAnimations) {
+ gsapScript = gsapScript.replace(
+ "const tl = gsap.timeline({ paused: true });",
+ `const tl = gsap.timeline({ paused: true });\n${prependAnimations}`,
+ );
+ }
+ if (zoomAnimations) {
+ gsapScript += "\n" + zoomAnimations;
+ }
+ } else if (generateDefaultAnimations) {
+ gsapScript = generateDefaultGsapAnimations(sortedElements, totalDuration, stageZoomKeyframes, width, height);
+ } else {
+ gsapScript = `
+ const tl = gsap.timeline({ paused: true });
+${initialPositionSets ? initialPositionSets + "\n" : ""} tl.to({}, { duration: ${totalDuration || 1} });
+ `;
+ // Append zoom animations
+ if (zoomAnimations) {
+ gsapScript += "\n" + zoomAnimations;
+ }
+ }
+
+ return gsapScript;
+}
+
+export function generateHyperframesHtml(
+ elements: TimelineElement[],
+ totalDuration: number,
+ options: SerializeOptions = {},
+): string {
+ const {
+ animations,
+ styles,
+ generateDefaultAnimations = true,
+ resolution = "landscape",
+ compositionId = `comp-${Date.now()}`,
+ keyframes,
+ stageZoomKeyframes,
+ includeScripts = false,
+ includeStyles = false,
+ } = options;
+
+ const { width, height } = CANVAS_DIMENSIONS[resolution];
+ // Include zoom keyframes in duration calculation
+ const maxZoomTime =
+ stageZoomKeyframes && stageZoomKeyframes.length > 0 ? Math.max(...stageZoomKeyframes.map((kf) => kf.time)) : 0;
+
+ const calculatedDuration =
+ elements.length > 0
+ ? Math.max(...elements.map((el) => el.startTime + el.duration), totalDuration, maxZoomTime)
+ : Math.max(totalDuration, maxZoomTime);
+
+ const sortedElements = sortElements(elements);
+
+ const elementsHtml = sortedElements.map((el) => generateElementHtml(el, keyframes?.[el.id])).join("\n ");
+
+ const customStyles = styles || "";
+
+ // Serialize zoom keyframes to data attribute
+ const zoomKeyframesAttr =
+ stageZoomKeyframes && stageZoomKeyframes.length > 0
+ ? ` data-zoom-keyframes='${JSON.stringify(stageZoomKeyframes).replace(/'/g, "&#39;")}'`
+ : "";
+
+ const { coreCss, customCss, googleFontsLink } = generateHyperframesStyles(sortedElements, resolution, customStyles);
+
+ const gsapScript = includeScripts
+ ? generateGsapTimelineScript(sortedElements, totalDuration, {
+ animations,
+ generateDefaultAnimations,
+ resolution,
+ keyframes,
+ stageZoomKeyframes,
+ })
+ : "";
+
+ const gsapCdnTag = includeScripts ? ` <script src="${GSAP_CDN}"></script>` : "";
+
+ const gsapScriptTag = includeScripts
+ ? ` <script>
+${gsapScript}
+ </script>`
+ : "";
+
+ const styleTags = includeStyles
+ ? [
+ coreCss
+ ? ` <style data-hf-core="true">
+ ${coreCss.split("\n").join("\n ")}
+ </style>`
+ : "",
+ customCss
+ ? ` <style data-hf-custom="true">
+ ${customCss.split("\n").join("\n ")}
+ </style>`
+ : "",
+ ]
+ .filter(Boolean)
+ .join("\n")
+ : "";
+
+ const customStylesAttr = customStyles
+ ? ` data-custom-styles='${JSON.stringify(customStyles).replace(/'/g, "&#39;")}'`
+ : "";
+
+ const resolutionAttr = ` data-resolution="${resolution}"`;
+
+ return `<!DOCTYPE html>
+<html data-composition-id="${compositionId}" data-composition-duration="${calculatedDuration}"${resolutionAttr}${customStylesAttr}>
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ ${includeStyles ? googleFontsLink : ""}
+ ${gsapCdnTag}
+${styleTags ? ` ${styleTags}` : ""}
+</head>
+<body>
+ <div id="stage">
+ <div id="stage-zoom-container"${zoomKeyframesAttr}>
+ ${elementsHtml}
+ </div>
+ </div>
+ ${gsapScriptTag}
+</body>
+</html>`;
+}
+
+function calculateZoomTransform(
+ scale: number,
+ focusX: number,
+ focusY: number,
+ canvasWidth: number,
+ canvasHeight: number,
+): { x: number; y: number } {
+ const centerX = canvasWidth / 2;
+ const centerY = canvasHeight / 2;
+ const x = centerX - focusX * scale;
+ const y = centerY - focusY * scale;
+ return { x, y };
+}
+
+function generateZoomGsapAnimations(
+ zoomKeyframes: StageZoomKeyframe[],
+ canvasWidth: number,
+ canvasHeight: number,
+): string {
+ if (!zoomKeyframes || zoomKeyframes.length === 0) {
+ return "";
+ }
+
+ const sortedKeyframes = [...zoomKeyframes].sort((a, b) => a.time - b.time);
+ const animations: string[] = [];
+
+ animations.push(" // Stage zoom animations");
+
+ for (let i = 0; i < sortedKeyframes.length; i++) {
+ const kf = sortedKeyframes[i];
+ if (!kf) continue;
+ const { x, y } = calculateZoomTransform(
+ kf.zoom.scale,
+ kf.zoom.focusX,
+ kf.zoom.focusY,
+ canvasWidth,
+ canvasHeight,
+ );
+
+ if (i === 0) {
+ animations.push(
+ ` tl.set("#stage-zoom-container", { scale: ${kf.zoom.scale}, x: ${x}, y: ${y} }, ${kf.time});`,
+ );
+ } else {
+ const prevKf = sortedKeyframes[i - 1];
+ if (!prevKf) continue;
+ const duration = kf.time - prevKf.time;
+ const ease = kf.ease ? `, ease: "${kf.ease}"` : "";
+ animations.push(
+ ` tl.to("#stage-zoom-container", { scale: ${kf.zoom.scale}, x: ${x}, y: ${y}, duration: ${duration}${ease} }, ${prevKf.time});`,
+ );
+ }
+ }
+
+ return animations.join("\n");
+}
+
+function generateElementHtml(element: TimelineElement, keyframes?: Keyframe[]): string {
+ const baseAttrs = [
+ `id="${element.id}"`,
+ `data-start="${element.startTime}"`,
+ `data-end="${element.startTime + element.duration}"`,
+ `data-layer="${element.zIndex}"`,
+ `data-name="${element.name}"`,
+ ];
+
+ // Serialize transform properties (x, y, scale, opacity) if non-default
+ if (element.x !== undefined && element.x !== 0) {
+ baseAttrs.push(`data-x="${element.x}"`);
+ }
+ if (element.y !== undefined && element.y !== 0) {
+ baseAttrs.push(`data-y="${element.y}"`);
+ }
+ if (element.scale !== undefined && element.scale !== 1) {
+ baseAttrs.push(`data-scale="${element.scale}"`);
+ }
+ if (element.opacity !== undefined && element.opacity !== 1) {
+ baseAttrs.push(`data-opacity="${element.opacity}"`);
+ }
+
+ // Serialize keyframes to data attribute if present
+ if (keyframes && keyframes.length > 0) {
+ const kfJson = JSON.stringify(keyframes);
+ baseAttrs.push(`data-keyframes='${kfJson.replace(/'/g, "&#39;")}'`);
+ }
+
+ if (isTextElement(element)) {
+ const textAttrs = [...baseAttrs, `data-type="text"`];
+ if (element.color) {
+ textAttrs.push(`data-color="${element.color}"`);
+ }
+ if (element.fontSize) {
+ textAttrs.push(`data-font-size="${element.fontSize}"`);
+ }
+ if (element.fontWeight) {
+ textAttrs.push(`data-font-weight="${element.fontWeight}"`);
+ }
+ if (element.fontFamily) {
+ textAttrs.push(`data-font-family="${element.fontFamily}"`);
+ }
+ if (element.textShadow === false) {
+ textAttrs.push(`data-text-shadow="false"`);
+ }
+ if (element.textOutline) {
+ textAttrs.push(`data-text-outline="true"`);
+ if (element.textOutlineColor) {
+ textAttrs.push(`data-text-outline-color="${element.textOutlineColor}"`);
+ }
+ if (element.textOutlineWidth) {
+ textAttrs.push(`data-text-outline-width="${element.textOutlineWidth}"`);
+ }
+ }
+ if (element.textHighlight) {
+ textAttrs.push(`data-text-highlight="true"`);
+ if (element.textHighlightColor) {
+ textAttrs.push(`data-text-highlight-color="${element.textHighlightColor}"`);
+ }
+ if (element.textHighlightPadding) {
+ textAttrs.push(`data-text-highlight-padding="${element.textHighlightPadding}"`);
+ }
+ if (element.textHighlightRadius) {
+ textAttrs.push(`data-text-highlight-radius="${element.textHighlightRadius}"`);
+ }
+ }
+ const content = element.content || element.name;
+ return `<div ${textAttrs.join(" ")}><div>${content}</div></div>`;
+ }
+
+ if (isCompositionElement(element)) {
+ const compositionAttrs = [
+ ...baseAttrs,
+ `data-type="composition"`,
+ `data-composition-id="${element.compositionId}"`,
+ ];
+ if (element.sourceDuration) {
+ compositionAttrs.push(`data-source-duration="${element.sourceDuration}"`);
+ }
+ if (element.sourceWidth) {
+ compositionAttrs.push(`data-source-width="${element.sourceWidth}"`);
+ }
+ if (element.sourceHeight) {
+ compositionAttrs.push(`data-source-height="${element.sourceHeight}"`);
+ }
+ if (element.variableValues && Object.keys(element.variableValues).length > 0) {
+ const varJson = JSON.stringify(element.variableValues);
+ compositionAttrs.push(`data-variable-values='${varJson.replace(/'/g, "&#39;")}'`);
+ }
+ const attrs = compositionAttrs.join(" ");
+ // Build iframe src with variable values as query params if present
+ // Strip any existing query params first to avoid duplication
+ let iframeSrc = element.src.split("?")[0];
+ if (element.variableValues && Object.keys(element.variableValues).length > 0) {
+ const params = new URLSearchParams();
+ for (const [key, value] of Object.entries(element.variableValues)) {
+ params.set(key, String(value));
+ }
+ iframeSrc = `${iframeSrc}?${params.toString()}`;
+ }
+ // Motion designs are full-screen overlays - always use 100% sizing
+ // The motion design HTML handles its own internal positioning
+ // Wrap iframe in container with click overlay for selection
+ return `<div ${attrs} style="width: 100%; height: 100%;">
+ <iframe src="${iframeSrc}" sandbox="allow-scripts allow-same-origin" style="width: 100%; height: 100%; border: none; pointer-events: none;"></iframe>
+ <div class="composition-click-overlay" style="position: absolute; inset: 0; cursor: pointer;"></div>
+ </div>`;
+ }
+
+ if (isMediaElement(element)) {
+ if (element.mediaStartTime) {
+ baseAttrs.push(`data-media-start="${element.mediaStartTime}"`);
+ }
+ if (element.sourceDuration) {
+ baseAttrs.push(`data-source-duration="${element.sourceDuration}"`);
+ }
+ if (element.isAroll) {
+ baseAttrs.push(`data-aroll="true"`);
+ }
+ if (element.volume !== undefined && element.volume !== 1) {
+ baseAttrs.push(`data-volume="${element.volume}"`);
+ }
+ if (element.type === "video" && element.hasAudio) {
+ baseAttrs.push(`data-has-audio="true"`);
+ }
+ }
+
+ const attrs = baseAttrs.join(" ");
+
+ switch (element.type) {
+ case "video":
+ return `<video ${attrs} src="${element.src}" playsinline></video>`;
+ case "image":
+ return `<img ${attrs} src="${element.src}" alt="${element.name}" />`;
+ case "audio":
+ return `<audio ${attrs} src="${element.src}"></audio>`;
+ default:
+ return "";
+ }
+}
+
+/**
+ * Generate initial position sets for elements.
+ *
+ * Center-based coordinate system with standard CSS origin:
+ * - (0, 0) = top-left corner of the canvas
+ * - (960, 540) = center of canvas (landscape 1920x1080)
+ * - x/y specifies where the element's CENTER goes (not top-left corner)
+ *
+ * Note: xPercent: -50, yPercent: -50 is applied once at player init via
+ * _initializeElementCentering(), so we only set x, y, scale here.
+ * This keeps generated timeline code clean (no repeated xPercent/yPercent).
+ */
+function generateInitialPositionSets(elements: TimelineElement[], keyframes?: Record<string, Keyframe[]>): string {
+ const sets: string[] = [];
+ const timeEpsilon = 0.001;
+
+ for (const el of elements) {
+ const elementKeyframes = keyframes?.[el.id];
+ const hasBaseKeyframe = elementKeyframes?.some(
+ (kf) =>
+ Math.abs(kf.time) <= timeEpsilon &&
+ (kf.properties.x !== undefined || kf.properties.y !== undefined || kf.properties.scale !== undefined),
+ );
+
+ const xVal = el.x ?? 0;
+ const yVal = el.y ?? 0;
+ const scaleVal = isMediaElement(el) ? (el.scale ?? 1) : 1;
+
+ // Audio elements don't need positioning
+ if (el.type === "audio") continue;
+
+ // Composition elements (motion designs) are full-screen overlays
+ // They don't need x/y/scale positioning - the HTML handles internal layout
+ if (isCompositionElement(el)) continue;
+
+ // Skip if element has a base keyframe that will handle positioning
+ if (hasBaseKeyframe) {
+ continue;
+ }
+
+ // Set position and scale (xPercent/yPercent applied at player init)
+ if (scaleVal !== 1) {
+ sets.push(` tl.set("#${el.id}", { x: ${xVal}, y: ${yVal}, scale: ${scaleVal} }, 0);`);
+ } else if (xVal !== 0 || yVal !== 0) {
+ sets.push(` tl.set("#${el.id}", { x: ${xVal}, y: ${yVal} }, 0);`);
+ }
+ }
+
+ return sets.length > 0 ? sets.join("\n") : "";
+}
+
+/**
+ * Generates visibility bookends for ALL elements to ensure they appear/disappear
+ * at the correct times. Elements with keyframes still need visibility bookends
+ * because keyframesToGsapAnimations only handles property animations, not visibility.
+ *
+ * If opacity keyframes exist, the first keyframe defines the base.
+ */
+function generateVisibilityForElementsWithoutKeyframes(
+ elements: TimelineElement[],
+ keyframes?: Record<string, Keyframe[]>,
+): string {
+ const animations: string[] = [];
+
+ for (const el of elements) {
+ const elementKeyframes = keyframes?.[el.id];
+ const opacityKeyframes = elementKeyframes?.filter((kf) => kf.properties.opacity !== undefined) || [];
+ const start = el.startTime;
+ const end = el.startTime + el.duration;
+
+ const safeName = el.name.replace(/[\r\n]+/g, " ");
+ animations.push(` // ${safeName} (visibility)`);
+ animations.push(` tl.set("#${el.id}", { visibility: "hidden" }, 0);`);
+
+ let elementOpacity = el.opacity ?? 1;
+ if (opacityKeyframes.length > 0) {
+ const firstOpacityKeyframe = [...opacityKeyframes].sort((a, b) => a.time - b.time)[0];
+ if (firstOpacityKeyframe?.properties.opacity !== undefined) {
+ elementOpacity = firstOpacityKeyframe.properties.opacity;
+ }
+ }
+ // Only include opacity in visibility bookend if non-default or has opacity keyframes
+ const needsOpacity = elementOpacity !== 1 || opacityKeyframes.length > 0;
+ if (needsOpacity) {
+ animations.push(` tl.set("#${el.id}", { visibility: "visible", opacity: ${elementOpacity} }, ${start});`);
+ } else {
+ animations.push(` tl.set("#${el.id}", { visibility: "visible" }, ${start});`);
+ }
+
+ animations.push(` tl.set("#${el.id}", { visibility: "hidden" }, ${end});`);
+ }
+
+ return animations.length > 0 ? animations.join("\n") : "";
+}
+
+function generateDefaultGsapAnimations(
+ elements: TimelineElement[],
+ totalDuration: number,
+ stageZoomKeyframes?: StageZoomKeyframe[],
+ canvasWidth?: number,
+ canvasHeight?: number,
+): string {
+ if (elements.length === 0 && (!stageZoomKeyframes || stageZoomKeyframes.length === 0)) {
+ return `
+ const tl = gsap.timeline({ paused: true });
+ tl.to({}, { duration: ${totalDuration || 1} });
+ `;
+ }
+
+ const animations: string[] = [];
+
+ // First, set initial positions and scales for elements with x/y offsets or scale
+ const initialPositionSets = generateInitialPositionSets(elements);
+ if (initialPositionSets) {
+ animations.push(initialPositionSets);
+ }
+
+ for (const el of elements) {
+ const start = el.startTime;
+ const end = el.startTime + el.duration;
+
+ const safeName = el.name.replace(/[\r\n]+/g, " ");
+ const elementOpacity = el.opacity ?? 1;
+ animations.push(` // ${safeName}`);
+ animations.push(` tl.set("#${el.id}", { visibility: "hidden" }, 0);`);
+ // Only include opacity if non-default
+ if (elementOpacity !== 1) {
+ animations.push(` tl.set("#${el.id}", { visibility: "visible", opacity: ${elementOpacity} }, ${start});`);
+ } else {
+ animations.push(` tl.set("#${el.id}", { visibility: "visible" }, ${start});`);
+ }
+ animations.push(` tl.set("#${el.id}", { visibility: "hidden" }, ${end});`);
+ }
+
+ const mediaElements = elements.filter((el) => el.type === "video" || el.type === "audio");
+ const mediaSync =
+ mediaElements.length > 0
+ ? `
+ // Sync media playback
+ tl.eventCallback("onUpdate", function() {
+ const time = tl.time();
+ document.querySelectorAll("video[data-start], audio[data-start]").forEach(function(media) {
+ const start = parseFloat(media.dataset.start);
+ const end = parseFloat(media.dataset.end) || Infinity;
+ const mediaTime = time - start;
+ if (time >= start && time < end) {
+ if (Math.abs(media.currentTime - mediaTime) > 0.1) {
+ media.currentTime = mediaTime;
+ }
+ if (media.paused && !tl.paused()) {
+ media.play().catch(function() {});
+ }
+ } else if (!media.paused) {
+ media.pause();
+ }
+ });
+ });`
+ : "";
+
+ // Generate zoom animations if present
+ const zoomAnimations =
+ stageZoomKeyframes && stageZoomKeyframes.length > 0 && canvasWidth && canvasHeight
+ ? "\n" + generateZoomGsapAnimations(stageZoomKeyframes, canvasWidth, canvasHeight)
+ : "";
+
+ return `
+ const tl = gsap.timeline({ paused: true });
+${animations.join("\n")}
+ ${mediaSync}${zoomAnimations}
+ `;
+}
diff --git a/packages/core/src/index.test.ts b/packages/core/src/index.test.ts
new file mode 100644
index 0000000000..4587b5f61f
--- /dev/null
+++ b/packages/core/src/index.test.ts
@@ -0,0 +1,162 @@
+// @vitest-environment node
+import { describe, it, expect } from "vitest";
+import * as core from "./index.js";
+
+describe("@hyperframes/core public API exports", () => {
+ describe("type-related constants and utilities", () => {
+ it("exports CANVAS_DIMENSIONS", () => {
+ expect(core.CANVAS_DIMENSIONS).toBeDefined();
+ expect(core.CANVAS_DIMENSIONS.landscape).toEqual({ width: 1920, height: 1080 });
+ expect(core.CANVAS_DIMENSIONS.portrait).toEqual({ width: 1080, height: 1920 });
+ });
+
+ it("exports TIMELINE_COLORS", () => {
+ expect(core.TIMELINE_COLORS).toBeDefined();
+ expect(core.TIMELINE_COLORS.video).toBeDefined();
+ expect(core.TIMELINE_COLORS.image).toBeDefined();
+ expect(core.TIMELINE_COLORS.text).toBeDefined();
+ expect(core.TIMELINE_COLORS.audio).toBeDefined();
+ expect(core.TIMELINE_COLORS.composition).toBeDefined();
+ });
+
+ it("exports DEFAULT_DURATIONS", () => {
+ expect(core.DEFAULT_DURATIONS).toBeDefined();
+ expect(core.DEFAULT_DURATIONS.video).toBe(5);
+ expect(core.DEFAULT_DURATIONS.text).toBe(2);
+ });
+
+ it("exports type guard functions", () => {
+ expect(typeof core.isTextElement).toBe("function");
+ expect(typeof core.isMediaElement).toBe("function");
+ expect(typeof core.isCompositionElement).toBe("function");
+ });
+
+ it("exports getDefaultStageZoom", () => {
+ expect(typeof core.getDefaultStageZoom).toBe("function");
+ const zoom = core.getDefaultStageZoom("landscape");
+ expect(zoom.scale).toBe(1);
+ expect(zoom.focusX).toBe(960);
+ expect(zoom.focusY).toBe(540);
+ });
+
+ it("exports composition variable type guards", () => {
+ expect(typeof core.isStringVariable).toBe("function");
+ expect(typeof core.isNumberVariable).toBe("function");
+ expect(typeof core.isColorVariable).toBe("function");
+ expect(typeof core.isBooleanVariable).toBe("function");
+ expect(typeof core.isEnumVariable).toBe("function");
+ });
+ });
+
+ describe("template exports", () => {
+ it("exports generateBaseHtml", () => {
+ expect(typeof core.generateBaseHtml).toBe("function");
+ });
+
+ it("exports getStageStyles", () => {
+ expect(typeof core.getStageStyles).toBe("function");
+ });
+
+ it("exports template constants", () => {
+ expect(core.GSAP_CDN).toBeDefined();
+ expect(core.BASE_STYLES).toBeDefined();
+ expect(core.ELEMENT_BASE_STYLES).toBeDefined();
+ expect(core.MEDIA_STYLES).toBeDefined();
+ expect(core.TEXT_STYLES).toBeDefined();
+ expect(core.ZOOM_CONTAINER_STYLES).toBeDefined();
+ });
+ });
+
+ describe("parser exports", () => {
+ it("exports GSAP parser functions", () => {
+ expect(typeof core.parseGsapScript).toBe("function");
+ expect(typeof core.serializeGsapAnimations).toBe("function");
+ expect(typeof core.updateAnimationInScript).toBe("function");
+ expect(typeof core.addAnimationToScript).toBe("function");
+ expect(typeof core.removeAnimationFromScript).toBe("function");
+ expect(typeof core.getAnimationsForElement).toBe("function");
+ expect(typeof core.validateCompositionGsap).toBe("function");
+ expect(typeof core.keyframesToGsapAnimations).toBe("function");
+ expect(typeof core.gsapAnimationsToKeyframes).toBe("function");
+ });
+
+ it("exports GSAP constants", () => {
+ expect(core.SUPPORTED_PROPS).toBeDefined();
+ expect(Array.isArray(core.SUPPORTED_PROPS)).toBe(true);
+ expect(core.SUPPORTED_EASES).toBeDefined();
+ expect(Array.isArray(core.SUPPORTED_EASES)).toBe(true);
+ });
+
+ it("exports HTML parser functions", () => {
+ expect(typeof core.parseHtml).toBe("function");
+ expect(typeof core.updateElementInHtml).toBe("function");
+ expect(typeof core.addElementToHtml).toBe("function");
+ expect(typeof core.removeElementFromHtml).toBe("function");
+ expect(typeof core.validateCompositionHtml).toBe("function");
+ expect(typeof core.extractCompositionMetadata).toBe("function");
+ });
+ });
+
+ describe("generator exports", () => {
+ it("exports hyperframes generator functions", () => {
+ expect(typeof core.generateHyperframesHtml).toBe("function");
+ expect(typeof core.generateGsapTimelineScript).toBe("function");
+ expect(typeof core.generateHyperframesStyles).toBe("function");
+ });
+ });
+
+ describe("compiler exports", () => {
+ it("exports compiler functions", () => {
+ expect(typeof core.compileTimingAttrs).toBe("function");
+ expect(typeof core.injectDurations).toBe("function");
+ expect(typeof core.extractResolvedMedia).toBe("function");
+ expect(typeof core.clampDurations).toBe("function");
+ });
+ });
+
+ describe("lint exports", () => {
+ it("exports lintHyperframeHtml", () => {
+ expect(typeof core.lintHyperframeHtml).toBe("function");
+ });
+ });
+
+ describe("inline-script exports", () => {
+ it("exports hyperframe runtime artifacts", () => {
+ expect(core.HYPERFRAME_RUNTIME_ARTIFACTS).toBeDefined();
+ expect(core.HYPERFRAME_RUNTIME_CONTRACT).toBeDefined();
+ expect(typeof core.loadHyperframeRuntimeSource).toBe("function");
+ });
+
+ it("exports runtime contract constants", () => {
+ expect(core.HYPERFRAME_RUNTIME_GLOBALS).toBeDefined();
+ expect(core.HYPERFRAME_BRIDGE_SOURCES).toBeDefined();
+ expect(core.HYPERFRAME_CONTROL_ACTIONS).toBeDefined();
+ });
+
+ it("exports buildHyperframesRuntimeScript", () => {
+ expect(typeof core.buildHyperframesRuntimeScript).toBe("function");
+ });
+
+ it("exports MEDIA_VISUAL_STYLE_PROPERTIES", () => {
+ expect(core.MEDIA_VISUAL_STYLE_PROPERTIES).toBeDefined();
+ expect(Array.isArray(core.MEDIA_VISUAL_STYLE_PROPERTIES)).toBe(true);
+ expect(core.MEDIA_VISUAL_STYLE_PROPERTIES).toContain("width");
+ expect(core.MEDIA_VISUAL_STYLE_PROPERTIES).toContain("opacity");
+ expect(core.MEDIA_VISUAL_STYLE_PROPERTIES).toContain("transform");
+ });
+
+ it("exports copyMediaVisualStyles", () => {
+ expect(typeof core.copyMediaVisualStyles).toBe("function");
+ });
+
+ it("exports quantizeTimeToFrame", () => {
+ expect(typeof core.quantizeTimeToFrame).toBe("function");
+ });
+ });
+
+ describe("adapter exports", () => {
+ it("exports createGSAPFrameAdapter", () => {
+ expect(typeof core.createGSAPFrameAdapter).toBe("function");
+ });
+ });
+});
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
new file mode 100644
index 0000000000..76172e795a
--- /dev/null
+++ b/packages/core/src/index.ts
@@ -0,0 +1,146 @@
+// Types
+export type {
+ ExecutionMode,
+ Orientation,
+ Asset,
+ TimelineElement,
+ TimelineElementBase,
+ TimelineMediaElement,
+ TimelineTextElement,
+ TimelineCompositionElement,
+ TimelineElementType,
+ MediaElementType,
+ CanvasResolution,
+ MediaFile,
+ CompositionAPI,
+ PlayerAPI,
+ AddElementData,
+ ValidationResult,
+ CompositionAsset,
+ Keyframe,
+ KeyframeProperties,
+ ElementKeyframes,
+ StageZoom,
+ StageZoomKeyframe,
+ CompositionVariableType,
+ CompositionVariableBase,
+ StringVariable,
+ NumberVariable,
+ ColorVariable,
+ BooleanVariable,
+ EnumVariable,
+ CompositionVariable,
+ CompositionSpec,
+ WaveformData,
+} from "./core.types";
+
+export {
+ CANVAS_DIMENSIONS,
+ TIMELINE_COLORS,
+ DEFAULT_DURATIONS,
+ isTextElement,
+ isMediaElement,
+ isCompositionElement,
+ getDefaultStageZoom,
+ isStringVariable,
+ isNumberVariable,
+ isColorVariable,
+ isBooleanVariable,
+ isEnumVariable,
+} from "./core.types";
+
+// Templates
+export { generateBaseHtml, getStageStyles } from "./templates/base";
+export {
+ GSAP_CDN,
+ BASE_STYLES,
+ ELEMENT_BASE_STYLES,
+ MEDIA_STYLES,
+ TEXT_STYLES,
+ ZOOM_CONTAINER_STYLES,
+} from "./templates/constants";
+
+// Parsers
+export type { GsapAnimation, GsapMethod, ParsedGsap } from "./parsers/gsapParser";
+
+export {
+ parseGsapScript,
+ serializeGsapAnimations,
+ updateAnimationInScript,
+ addAnimationToScript,
+ removeAnimationFromScript,
+ getAnimationsForElement,
+ validateCompositionGsap,
+ keyframesToGsapAnimations,
+ gsapAnimationsToKeyframes,
+ SUPPORTED_PROPS,
+ SUPPORTED_EASES,
+} from "./parsers/gsapParser";
+
+export type { ParsedHtml, CompositionMetadata } from "./parsers/htmlParser";
+
+export {
+ parseHtml,
+ updateElementInHtml,
+ addElementToHtml,
+ removeElementFromHtml,
+ validateCompositionHtml,
+ extractCompositionMetadata,
+} from "./parsers/htmlParser";
+
+// Generators
+export type { SerializeOptions } from "./generators/hyperframes";
+
+export {
+ generateHyperframesHtml,
+ generateGsapTimelineScript,
+ generateHyperframesStyles,
+} from "./generators/hyperframes";
+
+// Compiler (timing only — browser-safe, no cheerio/esbuild)
+export type { UnresolvedElement, ResolvedDuration, ResolvedMediaElement, CompilationResult } from "./compiler/timingCompiler";
+
+export { compileTimingAttrs, injectDurations, extractResolvedMedia, clampDurations } from "./compiler/timingCompiler";
+
+// Lint
+export type {
+ HyperframeLintSeverity,
+ HyperframeLintFinding,
+ HyperframeLintResult,
+ HyperframeLinterOptions,
+} from "./lint/types";
+export { lintHyperframeHtml } from "./lint/hyperframeLinter";
+
+// Inline scripts
+export {
+ HYPERFRAME_RUNTIME_ARTIFACTS,
+ HYPERFRAME_RUNTIME_CONTRACT,
+ loadHyperframeRuntimeSource,
+ type HyperframeRuntimeContract,
+} from "./inline-scripts/hyperframe";
+export {
+ HYPERFRAME_RUNTIME_GLOBALS,
+ HYPERFRAME_BRIDGE_SOURCES,
+ HYPERFRAME_CONTROL_ACTIONS,
+ type HyperframeControlAction,
+} from "./inline-scripts/runtimeContract";
+export {
+ buildHyperframesRuntimeScript,
+ type HyperframesRuntimeBuildOptions,
+} from "./inline-scripts/hyperframesRuntime.engine";
+export {
+ MEDIA_VISUAL_STYLE_PROPERTIES,
+ copyMediaVisualStyles,
+ quantizeTimeToFrame,
+ type MediaVisualStyleProperty,
+} from "./inline-scripts/parityContract";
+export type {
+ HyperframePickerApi,
+ HyperframePickerBoundingBox,
+ HyperframePickerElementInfo,
+} from "./inline-scripts/pickerApi";
+
+// Frame adapters
+export type { FrameAdapter, FrameAdapterContext } from "./adapters/types";
+export type { GSAPTimelineLike, CreateGSAPFrameAdapterOptions } from "./adapters/gsap";
+export { createGSAPFrameAdapter } from "./adapters/gsap";
diff --git a/packages/core/src/inline-scripts/hyperframe.ts b/packages/core/src/inline-scripts/hyperframe.ts
new file mode 100644
index 0000000000..6987833390
--- /dev/null
+++ b/packages/core/src/inline-scripts/hyperframe.ts
@@ -0,0 +1,22 @@
+import { buildHyperframesRuntimeScript } from "./hyperframesRuntime.engine";
+import { HYPERFRAME_BRIDGE_SOURCES, HYPERFRAME_RUNTIME_GLOBALS } from "./runtimeContract";
+
+export const HYPERFRAME_RUNTIME_ARTIFACTS = {
+ iife: "hyperframe.runtime.iife.js",
+ esm: "hyperframe.runtime.mjs",
+ manifest: "hyperframe.manifest.json",
+} as const;
+
+export type HyperframeRuntimeContract = {
+ globals: typeof HYPERFRAME_RUNTIME_GLOBALS;
+ messageSources: typeof HYPERFRAME_BRIDGE_SOURCES;
+};
+
+export const HYPERFRAME_RUNTIME_CONTRACT: HyperframeRuntimeContract = {
+ globals: HYPERFRAME_RUNTIME_GLOBALS,
+ messageSources: HYPERFRAME_BRIDGE_SOURCES,
+};
+
+export function loadHyperframeRuntimeSource(): string {
+ return buildHyperframesRuntimeScript();
+}
diff --git a/packages/core/src/inline-scripts/hyperframesRuntime.engine.ts b/packages/core/src/inline-scripts/hyperframesRuntime.engine.ts
new file mode 100644
index 0000000000..cfa3f5ae57
--- /dev/null
+++ b/packages/core/src/inline-scripts/hyperframesRuntime.engine.ts
@@ -0,0 +1,37 @@
+import { buildSync } from "esbuild";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+export type HyperframesRuntimeBuildOptions = {
+ sourceUrl?: string;
+ defaultParityMode?: boolean;
+ minify?: boolean;
+};
+
+function applyDefaultParityMode(script: string, enabled: boolean): string {
+ const parityFlagPattern = /var\s+_parityModeEnabled\s*=\s*(?:true|false)\s*;/;
+ if (!parityFlagPattern.test(script)) return script;
+ return script.replace(parityFlagPattern, `var _parityModeEnabled = ${enabled ? "true" : "false"};`);
+}
+
+export function buildHyperframesRuntimeScript(options: HyperframesRuntimeBuildOptions = {}): string {
+ const entryPath = resolve(dirname(fileURLToPath(import.meta.url)), "../runtime/entry.ts");
+ const result = buildSync({
+ entryPoints: [entryPath],
+ bundle: true,
+ write: false,
+ platform: "browser",
+ format: "iife",
+ target: ["es2020"],
+ minify: options.minify ?? true,
+ legalComments: "none",
+ });
+ let script = result.outputFiles[0]?.text ?? "";
+ if (typeof options.defaultParityMode === "boolean") {
+ script = applyDefaultParityMode(script, options.defaultParityMode);
+ }
+ if (options.sourceUrl && options.sourceUrl.trim()) {
+ script = `${script}\n//# sourceURL=${options.sourceUrl.trim()}`;
+ }
+ return script;
+}
diff --git a/packages/core/src/inline-scripts/parityContract.test.ts b/packages/core/src/inline-scripts/parityContract.test.ts
new file mode 100644
index 0000000000..58da0044e9
--- /dev/null
+++ b/packages/core/src/inline-scripts/parityContract.test.ts
@@ -0,0 +1,57 @@
+import { describe, it, expect } from "vitest";
+import { quantizeTimeToFrame, MEDIA_VISUAL_STYLE_PROPERTIES } from "./parityContract.js";
+
+describe("quantizeTimeToFrame", () => {
+ it("quantizes a time to the nearest frame boundary at 30fps", () => {
+ // 1.5s at 30fps = frame 45 => 45/30 = 1.5
+ expect(quantizeTimeToFrame(1.5, 30)).toBe(1.5);
+ });
+
+ it("floors to the previous frame boundary", () => {
+ // 1.51s at 30fps: floor(1.51*30 + 1e-9) = floor(45.3) = 45 => 45/30 = 1.5
+ expect(quantizeTimeToFrame(1.51, 30)).toBe(1.5);
+ });
+
+ it("handles exact frame boundaries", () => {
+ // 1.0s at 24fps: floor(1.0*24 + 1e-9) = 24 => 24/24 = 1.0
+ expect(quantizeTimeToFrame(1.0, 24)).toBe(1.0);
+ });
+
+ it("returns 0 for zero time", () => {
+ expect(quantizeTimeToFrame(0, 30)).toBe(0);
+ });
+
+ it("returns 0 for negative time", () => {
+ expect(quantizeTimeToFrame(-1, 30)).toBe(0);
+ });
+
+ it("defaults to 30fps for invalid fps", () => {
+ // When fps is invalid, safeFps falls back to 30
+ // quantizeTimeToFrame(1, 0) => floor(1*30+eps)/30 = 1
+ expect(quantizeTimeToFrame(1, 0)).toBe(1);
+ expect(quantizeTimeToFrame(1, NaN)).toBe(1);
+ expect(quantizeTimeToFrame(1, -10)).toBe(1);
+ });
+
+ it("handles NaN time gracefully", () => {
+ expect(quantizeTimeToFrame(NaN, 30)).toBe(0);
+ });
+
+ it("handles 60fps correctly", () => {
+ // 0.5s at 60fps: floor(0.5*60 + 1e-9) = 30 => 30/60 = 0.5
+ expect(quantizeTimeToFrame(0.5, 60)).toBe(0.5);
+ });
+});
+
+describe("MEDIA_VISUAL_STYLE_PROPERTIES", () => {
+ it("is a non-empty readonly array", () => {
+ expect(MEDIA_VISUAL_STYLE_PROPERTIES.length).toBeGreaterThan(0);
+ });
+
+ it("includes core layout properties", () => {
+ expect(MEDIA_VISUAL_STYLE_PROPERTIES).toContain("width");
+ expect(MEDIA_VISUAL_STYLE_PROPERTIES).toContain("height");
+ expect(MEDIA_VISUAL_STYLE_PROPERTIES).toContain("transform");
+ expect(MEDIA_VISUAL_STYLE_PROPERTIES).toContain("opacity");
+ });
+});
diff --git a/packages/core/src/inline-scripts/parityContract.ts b/packages/core/src/inline-scripts/parityContract.ts
new file mode 100644
index 0000000000..a571656560
--- /dev/null
+++ b/packages/core/src/inline-scripts/parityContract.ts
@@ -0,0 +1,50 @@
+export const MEDIA_VISUAL_STYLE_PROPERTIES = [
+ "width",
+ "height",
+ "top",
+ "left",
+ "right",
+ "bottom",
+ "inset",
+ "object-fit",
+ "object-position",
+ "z-index",
+ "opacity",
+ "visibility",
+ "filter",
+ "mix-blend-mode",
+ "backdrop-filter",
+ "border-radius",
+ "overflow",
+ "clip-path",
+ "mask",
+ "mask-image",
+ "mask-size",
+ "mask-position",
+ "mask-repeat",
+ "transform",
+ "transform-origin",
+ "box-sizing",
+] as const;
+
+export type MediaVisualStyleProperty = (typeof MEDIA_VISUAL_STYLE_PROPERTIES)[number];
+
+export function quantizeTimeToFrame(timeSeconds: number, fps: number): number {
+ const safeFps = Number.isFinite(fps) && fps > 0 ? fps : 30;
+ const safeTime = Number.isFinite(timeSeconds) && timeSeconds > 0 ? timeSeconds : 0;
+ const frameIndex = Math.floor(safeTime * safeFps + 1e-9);
+ return frameIndex / safeFps;
+}
+
+export function copyMediaVisualStyles(
+ targetStyle: CSSStyleDeclaration,
+ sourceStyle: CSSStyleDeclaration,
+ properties: readonly string[] = MEDIA_VISUAL_STYLE_PROPERTIES,
+): void {
+ for (const property of properties) {
+ const value = sourceStyle.getPropertyValue(property);
+ if (value) {
+ targetStyle.setProperty(property, value);
+ }
+ }
+}
diff --git a/packages/core/src/inline-scripts/pickerApi.ts b/packages/core/src/inline-scripts/pickerApi.ts
new file mode 100644
index 0000000000..5231bacb4c
--- /dev/null
+++ b/packages/core/src/inline-scripts/pickerApi.ts
@@ -0,0 +1,34 @@
+export type HyperframePickerBoundingBox = {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+};
+
+export type HyperframePickerElementInfo = {
+ id: string | null;
+ tagName: string;
+ selector: string;
+ label: string;
+ boundingBox: HyperframePickerBoundingBox;
+ textContent: string | null;
+ src: string | null;
+ dataAttributes: Record<string, string>;
+};
+
+export type HyperframePickerApi = {
+ enable: () => void;
+ disable: () => void;
+ isActive: () => boolean;
+ getHovered: () => HyperframePickerElementInfo | null;
+ getSelected: () => HyperframePickerElementInfo | null;
+ getCandidatesAtPoint: (clientX: number, clientY: number, limit?: number) => HyperframePickerElementInfo[];
+ pickAtPoint: (clientX: number, clientY: number, index?: number) => HyperframePickerElementInfo | null;
+ pickManyAtPoint: (clientX: number, clientY: number, indexes?: number[]) => HyperframePickerElementInfo[];
+};
+
+declare global {
+ interface Window {
+ __HF_PICKER_API?: HyperframePickerApi;
+ }
+}
diff --git a/packages/core/src/inline-scripts/runtimeContract.ts b/packages/core/src/inline-scripts/runtimeContract.ts
new file mode 100644
index 0000000000..55d0934905
--- /dev/null
+++ b/packages/core/src/inline-scripts/runtimeContract.ts
@@ -0,0 +1,24 @@
+export const HYPERFRAME_RUNTIME_GLOBALS = {
+ player: "__player",
+ playerReady: "__playerReady",
+ renderReady: "__renderReady",
+ timelines: "__timelines",
+ clipManifest: "__clipManifest",
+} as const;
+
+export const HYPERFRAME_BRIDGE_SOURCES = {
+ parent: "hf-parent",
+ preview: "hf-preview",
+} as const;
+
+export const HYPERFRAME_CONTROL_ACTIONS = [
+ "play",
+ "pause",
+ "seek",
+ "set-muted",
+ "set-playback-rate",
+ "enable-pick-mode",
+ "disable-pick-mode",
+] as const;
+
+export type HyperframeControlAction = (typeof HYPERFRAME_CONTROL_ACTIONS)[number];
diff --git a/packages/core/src/lint/hyperframeLinter.test.ts b/packages/core/src/lint/hyperframeLinter.test.ts
new file mode 100644
index 0000000000..3a14dc6914
--- /dev/null
+++ b/packages/core/src/lint/hyperframeLinter.test.ts
@@ -0,0 +1,113 @@
+import { describe, it, expect } from "vitest";
+import { lintHyperframeHtml } from "./hyperframeLinter.js";
+
+describe("lintHyperframeHtml", () => {
+ const validComposition = `
+<html>
+<body>
+ <div id="root" data-composition-id="comp-1" data-width="1920" data-height="1080">
+ <div id="stage"></div>
+ </div>
+ <script src="https://cdn.gsap.com/gsap.min.js"></script>
+ <script>
+ window.__timelines = window.__timelines || {};
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#stage", { opacity: 1, duration: 1 }, 0);
+ window.__timelines["comp-1"] = tl;
+ </script>
+</body>
+</html>`;
+
+ it("reports no errors for a valid composition", () => {
+ const result = lintHyperframeHtml(validComposition);
+ expect(result.ok).toBe(true);
+ expect(result.errorCount).toBe(0);
+ });
+
+ it("reports error when root is missing data-composition-id", () => {
+ const html = `
+<html><body>
+ <div id="root" data-width="1920" data-height="1080"></div>
+ <script>window.__timelines = {};</script>
+</body></html>`;
+ const result = lintHyperframeHtml(html);
+ const finding = result.findings.find((f) => f.code === "root_missing_composition_id");
+ expect(finding).toBeDefined();
+ expect(finding?.severity).toBe("error");
+ });
+
+ it("reports error when root is missing data-width or data-height", () => {
+ const html = `
+<html><body>
+ <div id="root" data-composition-id="c1"></div>
+ <script>window.__timelines = {};</script>
+</body></html>`;
+ const result = lintHyperframeHtml(html);
+ const finding = result.findings.find((f) => f.code === "root_missing_dimensions");
+ expect(finding).toBeDefined();
+ expect(finding?.severity).toBe("error");
+ });
+
+ it("reports error when timeline registry is missing", () => {
+ const html = `
+<html><body>
+ <div id="root" data-composition-id="c1" data-width="1920" data-height="1080"></div>
+ <script>
+ const tl = gsap.timeline({ paused: true });
+ </script>
+</body></html>`;
+ const result = lintHyperframeHtml(html);
+ const finding = result.findings.find((f) => f.code === "missing_timeline_registry");
+ expect(finding).toBeDefined();
+ });
+
+ it("reports error for duplicate media ids", () => {
+ const html = `
+<html><body>
+ <div id="root" data-composition-id="c1" data-width="1920" data-height="1080">
+ <video id="v1" src="a.mp4" data-start="0" data-duration="5"></video>
+ <video id="v1" src="b.mp4" data-start="0" data-duration="3"></video>
+ </div>
+ <script>window.__timelines = {};</script>
+</body></html>`;
+ const result = lintHyperframeHtml(html);
+ const finding = result.findings.find((f) => f.code === "duplicate_media_id");
+ expect(finding).toBeDefined();
+ expect(finding?.severity).toBe("error");
+ expect(finding?.elementId).toBe("v1");
+ });
+
+ it("reports error for composition host missing data-composition-id", () => {
+ const html = `
+<html><body>
+ <div id="root" data-composition-id="c1" data-width="1920" data-height="1080">
+ <div id="host1" data-composition-src="child.html"></div>
+ </div>
+ <script>window.__timelines = {};</script>
+</body></html>`;
+ const result = lintHyperframeHtml(html);
+ const finding = result.findings.find((f) => f.code === "host_missing_composition_id");
+ expect(finding).toBeDefined();
+ });
+
+ it("attaches filePath to findings when option is set", () => {
+ const html = "<html><body><div></div></body></html>";
+ const result = lintHyperframeHtml(html, { filePath: "test.html" });
+ for (const finding of result.findings) {
+ expect(finding.file).toBe("test.html");
+ }
+ });
+
+ it("deduplicates identical findings", () => {
+ // Calling with the same HTML should not produce duplicate entries
+ const html = `
+<html><body>
+ <div id="root"></div>
+ <script>const tl = gsap.timeline();</script>
+</body></html>`;
+ const result = lintHyperframeHtml(html);
+ const codes = result.findings.map((f) => `${f.code}|${f.message}`);
+ const uniqueCodes = [...new Set(codes)];
+ expect(codes.length).toBe(uniqueCodes.length);
+ });
+});
diff --git a/packages/core/src/lint/hyperframeLinter.ts b/packages/core/src/lint/hyperframeLinter.ts
new file mode 100644
index 0000000000..ec34bea61d
--- /dev/null
+++ b/packages/core/src/lint/hyperframeLinter.ts
@@ -0,0 +1,699 @@
+import { parseGsapScript } from "../parsers/gsapParser";
+import type { HyperframeLintFinding, HyperframeLinterOptions, HyperframeLintResult } from "./types";
+
+type OpenTag = {
+ raw: string;
+ name: string;
+ attrs: string;
+ index: number;
+};
+
+type ExtractedBlock = {
+ attrs: string;
+ content: string;
+ raw: string;
+ index: number;
+};
+
+type GsapWindow = {
+ targetSelector: string;
+ position: number;
+ end: number;
+ properties: string[];
+ overwriteAuto: boolean;
+ raw: string;
+};
+
+const TAG_PATTERN = /<([a-z][\w:-]*)(\s[^<>]*?)?>/gi;
+const STYLE_BLOCK_PATTERN = /<style\b([^>]*)>([\s\S]*?)<\/style>/gi;
+const SCRIPT_BLOCK_PATTERN = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
+const COMPOSITION_ID_IN_CSS_PATTERN = /\[data-composition-id=["']([^"']+)["']\]/g;
+const TIMELINE_REGISTRY_INIT_PATTERN =
+ /window\.__timelines\s*=\s*window\.__timelines\s*\|\|\s*\{\}|window\.__timelines\s*=\s*\{\}|window\.__timelines\s*\?\?=\s*\{\}/i;
+const TIMELINE_REGISTRY_ASSIGN_PATTERN = /window\.__timelines\[[^\]]+\]\s*=/i;
+const INVALID_SCRIPT_CLOSE_PATTERN = /<script[^>]*>[\s\S]*?<\s*\/\s*script(?!>)/i;
+const WINDOW_TIMELINE_ASSIGN_PATTERN = /window\.__timelines\[\s*["']([^"']+)["']\s*\]\s*=\s*([A-Za-z_$][\w$]*)/i;
+
+const META_GSAP_KEYS = new Set(["duration", "ease", "repeat", "yoyo", "overwrite", "delay"]);
+
+export function lintHyperframeHtml(html: string, options: HyperframeLinterOptions = {}): HyperframeLintResult {
+ const source = html || "";
+ const filePath = options.filePath;
+ const findings: HyperframeLintFinding[] = [];
+ const seen = new Set<string>();
+
+ const pushFinding = (finding: HyperframeLintFinding) => {
+ const dedupeKey = [
+ finding.code,
+ finding.severity,
+ finding.selector || "",
+ finding.elementId || "",
+ finding.message,
+ ].join("|");
+ if (seen.has(dedupeKey)) {
+ return;
+ }
+ seen.add(dedupeKey);
+ findings.push(filePath ? { ...finding, file: filePath } : finding);
+ };
+
+ const tags = extractOpenTags(source);
+ const styles = extractBlocks(source, STYLE_BLOCK_PATTERN);
+ const scripts = extractBlocks(source, SCRIPT_BLOCK_PATTERN);
+ const compositionIds = collectCompositionIds(tags);
+ const rootTag = findRootTag(source);
+ const rootCompositionId = readAttr(rootTag?.raw || "", "data-composition-id");
+
+ if (!rootTag || !readAttr(rootTag.raw, "data-composition-id")) {
+ pushFinding({
+ code: "root_missing_composition_id",
+ severity: "error",
+ message: "Root composition is missing `data-composition-id`.",
+ elementId: rootTag ? readAttr(rootTag.raw, "id") || undefined : undefined,
+ fixHint: "Add a stable `data-composition-id` to the entry composition wrapper.",
+ snippet: truncateSnippet(rootTag?.raw || ""),
+ });
+ }
+
+ if (!rootTag || !readAttr(rootTag.raw, "data-width") || !readAttr(rootTag.raw, "data-height")) {
+ pushFinding({
+ code: "root_missing_dimensions",
+ severity: "error",
+ message: "Root composition is missing `data-width` or `data-height`.",
+ elementId: rootTag ? readAttr(rootTag.raw, "id") || undefined : undefined,
+ fixHint: "Set numeric `data-width` and `data-height` on the entry composition root.",
+ snippet: truncateSnippet(rootTag?.raw || ""),
+ });
+ }
+
+ if (!TIMELINE_REGISTRY_INIT_PATTERN.test(source) && !TIMELINE_REGISTRY_ASSIGN_PATTERN.test(source)) {
+ pushFinding({
+ code: "missing_timeline_registry",
+ severity: "error",
+ message: "Missing `window.__timelines` registration.",
+ fixHint: "Register each composition timeline on `window.__timelines[compositionId]`.",
+ });
+ }
+
+ if (INVALID_SCRIPT_CLOSE_PATTERN.test(source)) {
+ pushFinding({
+ code: "invalid_inline_script_syntax",
+ severity: "error",
+ message: "Detected malformed inline `<script>` closing syntax.",
+ fixHint: "Close inline scripts with a valid `</script>` tag.",
+ });
+ }
+
+ for (const script of scripts) {
+ const attrs = script.attrs || "";
+ if (/\bsrc\s*=/.test(attrs) || /\btype\s*=\s*["']application\/json["']/.test(attrs)) {
+ continue;
+ }
+ const syntaxError = getInlineScriptSyntaxError(script.content);
+ if (!syntaxError) {
+ continue;
+ }
+ pushFinding({
+ code: "invalid_inline_script_syntax",
+ severity: "error",
+ message: `Inline script has invalid syntax: ${syntaxError}`,
+ fixHint: "Fix the inline script syntax before render verification.",
+ snippet: truncateSnippet(script.content),
+ });
+ }
+
+ for (const tag of tags) {
+ const src = readAttr(tag.raw, "data-composition-src");
+ if (!src) {
+ continue;
+ }
+ const compId = readAttr(tag.raw, "data-composition-id");
+ if (compId) {
+ continue;
+ }
+ pushFinding({
+ code: "host_missing_composition_id",
+ severity: "error",
+ message: `Composition host for "${src}" is missing \`data-composition-id\`.`,
+ elementId: readAttr(tag.raw, "id") || undefined,
+ fixHint: "Set `data-composition-id` on every `data-composition-src` host element.",
+ snippet: truncateSnippet(tag.raw),
+ });
+ }
+
+ const scopedCssCompositionIds = new Set<string>();
+ for (const style of styles) {
+ for (const compId of extractCompositionIdsFromCss(style.content)) {
+ scopedCssCompositionIds.add(compId);
+ }
+ }
+
+ for (const compId of scopedCssCompositionIds) {
+ if (compositionIds.has(compId)) {
+ continue;
+ }
+ pushFinding({
+ code: "scoped_css_missing_wrapper",
+ severity: "warning",
+ message: `Scoped CSS targets composition "${compId}" but no matching wrapper exists in this HTML.`,
+ selector: `[data-composition-id="${compId}"]`,
+ fixHint: "Preserve the matching composition wrapper or align the CSS scope to an existing wrapper.",
+ });
+ }
+
+ const mediaById = new Map<string, OpenTag[]>();
+ const mediaFingerprintCounts = new Map<string, number>();
+ for (const tag of tags) {
+ if (!isMediaTag(tag.name)) {
+ continue;
+ }
+ const elementId = readAttr(tag.raw, "id");
+ if (elementId) {
+ const existing = mediaById.get(elementId) || [];
+ existing.push(tag);
+ mediaById.set(elementId, existing);
+ }
+ const fingerprint = [
+ tag.name,
+ readAttr(tag.raw, "src") || "",
+ readAttr(tag.raw, "data-start") || "",
+ readAttr(tag.raw, "data-duration") || "",
+ ].join("|");
+ mediaFingerprintCounts.set(fingerprint, (mediaFingerprintCounts.get(fingerprint) || 0) + 1);
+ }
+
+ for (const [elementId, mediaTags] of mediaById) {
+ if (mediaTags.length < 2) {
+ continue;
+ }
+ pushFinding({
+ code: "duplicate_media_id",
+ severity: "error",
+ message: `Media id "${elementId}" is defined multiple times.`,
+ elementId,
+ fixHint: "Give each media element a unique id so preview and producer discover the same media graph.",
+ snippet: truncateSnippet(mediaTags[0]?.raw || ""),
+ });
+ }
+
+ for (const [fingerprint, count] of mediaFingerprintCounts) {
+ if (count < 2) {
+ continue;
+ }
+ const [tagName, src, dataStart, dataDuration] = fingerprint.split("|");
+ pushFinding({
+ code: "duplicate_media_discovery_risk",
+ severity: "warning",
+ message: `Detected ${count} matching ${tagName} entries with the same source/start/duration.`,
+ fixHint: "Avoid duplicated media nodes that can be discovered twice during compilation.",
+ snippet: truncateSnippet(`${tagName} src=${src} data-start=${dataStart} data-duration=${dataDuration}`),
+ });
+ }
+
+ const classUsage = countClassUsage(tags);
+ for (const script of scripts) {
+ const localTimelineCompId = readRegisteredTimelineCompositionId(script.content);
+ const gsapWindows = extractGsapWindows(script.content);
+
+ for (let i = 0; i < gsapWindows.length; i++) {
+ const left = gsapWindows[i];
+ if (!left) continue;
+ if (left.end <= left.position) {
+ continue;
+ }
+ for (let j = i + 1; j < gsapWindows.length; j++) {
+ const right = gsapWindows[j];
+ if (!right) continue;
+ if (right.end <= right.position) {
+ continue;
+ }
+ if (left.targetSelector !== right.targetSelector) {
+ continue;
+ }
+ const overlapStart = Math.max(left.position, right.position);
+ const overlapEnd = Math.min(left.end, right.end);
+ if (overlapEnd <= overlapStart) {
+ continue;
+ }
+ if (left.overwriteAuto || right.overwriteAuto) {
+ continue;
+ }
+ const sharedProperties = left.properties.filter((prop) => right.properties.includes(prop));
+ if (sharedProperties.length === 0) {
+ continue;
+ }
+ pushFinding({
+ code: "overlapping_gsap_tweens",
+ severity: "warning",
+ message: `GSAP tweens overlap on "${left.targetSelector}" for ${sharedProperties.join(", ")} between ${overlapStart.toFixed(2)}s and ${overlapEnd.toFixed(2)}s.`,
+ selector: left.targetSelector,
+ fixHint: 'Shorten the earlier tween, move the later tween, or add `overwrite: "auto"`.',
+ snippet: truncateSnippet(`${left.raw}\n${right.raw}`),
+ });
+ }
+ }
+
+ if (!localTimelineCompId || localTimelineCompId === rootCompositionId) {
+ continue;
+ }
+ for (const window of gsapWindows) {
+ if (!isSuspiciousGlobalSelector(window.targetSelector)) {
+ continue;
+ }
+ const className = getSingleClassSelector(window.targetSelector);
+ if (className && (classUsage.get(className) || 0) < 2) {
+ continue;
+ }
+ pushFinding({
+ code: "suspicious_global_gsap_selector",
+ severity: "warning",
+ message: `Timeline "${localTimelineCompId}" uses a global selector "${window.targetSelector}" that may escape composition scope.`,
+ selector: window.targetSelector,
+ fixHint: `Scope the selector like \`[data-composition-id="${localTimelineCompId}"] ${window.targetSelector}\` or use a unique id.`,
+ snippet: truncateSnippet(window.raw),
+ });
+ }
+ }
+
+ // ── Composition pitfall checks ──────────────────────────────────────────
+
+ // #2: Video without muted attribute (audio should come from separate <audio>)
+ for (const tag of tags) {
+ if (tag.name !== "video") continue;
+ const hasMuted = /\bmuted\b/i.test(tag.raw);
+ if (!hasMuted && readAttr(tag.raw, "data-start")) {
+ const elementId = readAttr(tag.raw, "id") || undefined;
+ pushFinding({
+ code: "video_missing_muted",
+ severity: "error",
+ message: `<video${elementId ? ` id="${elementId}"` : ""}> has data-start but is not muted. The framework expects video to be muted with a separate <audio> element for sound.`,
+ elementId,
+ fixHint:
+ "Add the `muted` attribute to the <video> tag and use a separate <audio> element with the same src for audio playback.",
+ snippet: truncateSnippet(tag.raw),
+ });
+ }
+ }
+
+ // #3: Video nested inside a timed element (data-start on ancestor)
+ // Approximation: check if a <video data-start> appears inside another element with data-start
+ // by scanning for video tags whose raw position is between another timed element's open/close
+ const timedTagPositions: Array<{ name: string; start: number; id?: string }> = [];
+ for (const tag of tags) {
+ if (tag.name === "video" || tag.name === "audio") continue;
+ if (readAttr(tag.raw, "data-start")) {
+ timedTagPositions.push({ name: tag.name, start: tag.index, id: readAttr(tag.raw, "id") || undefined });
+ }
+ }
+ for (const tag of tags) {
+ if (tag.name !== "video") continue;
+ if (!readAttr(tag.raw, "data-start")) continue;
+ // Check if any timed non-media element appears before this video in the source
+ // and could be an ancestor (heuristic — not a full DOM parse)
+ for (const parent of timedTagPositions) {
+ if (parent.start < tag.index) {
+ // Check if there's a closing tag for the parent between parent.start and tag.index
+ const parentClosePattern = new RegExp(`</${parent.name}>`, "gi");
+ const between = source.substring(parent.start, tag.index);
+ if (!parentClosePattern.test(between)) {
+ pushFinding({
+ code: "video_nested_in_timed_element",
+ severity: "warning",
+ message: `<video> with data-start appears to be nested inside <${parent.name}${parent.id ? ` id="${parent.id}"` : ""}> which also has data-start. This can break media sync.`,
+ elementId: readAttr(tag.raw, "id") || undefined,
+ fixHint:
+ "Move the <video> to be a direct child of the stage, or remove data-start from the wrapper div (use it as a non-timed visual container).",
+ snippet: truncateSnippet(tag.raw),
+ });
+ break; // Only report once per video
+ }
+ }
+ }
+ }
+
+ // #4: Timed element missing visibility:hidden (no class="clip" or equivalent)
+ for (const tag of tags) {
+ if (tag.name === "audio" || tag.name === "script" || tag.name === "style") continue;
+ if (!readAttr(tag.raw, "data-start")) continue;
+ const classAttr = readAttr(tag.raw, "class") || "";
+ const styleAttr = readAttr(tag.raw, "style") || "";
+ const hasClip = classAttr.split(/\s+/).includes("clip");
+ const hasHiddenStyle = /visibility\s*:\s*hidden/i.test(styleAttr);
+ if (!hasClip && !hasHiddenStyle) {
+ const elementId = readAttr(tag.raw, "id") || undefined;
+ pushFinding({
+ code: "timed_element_missing_visibility_hidden",
+ severity: "warning",
+ message: `<${tag.name}${elementId ? ` id="${elementId}"` : ""}> has data-start but no class="clip" or visibility:hidden. The framework needs elements to start hidden so it can manage their lifecycle.`,
+ elementId,
+ fixHint: 'Add class="clip" to the element (with CSS: .clip { visibility: hidden; }).',
+ snippet: truncateSnippet(tag.raw),
+ });
+ }
+ }
+
+ // #5: Deprecated attribute names
+ for (const tag of tags) {
+ if (readAttr(tag.raw, "data-layer") && !readAttr(tag.raw, "data-track-index")) {
+ const elementId = readAttr(tag.raw, "id") || undefined;
+ pushFinding({
+ code: "deprecated_data_layer",
+ severity: "warning",
+ message: `<${tag.name}${elementId ? ` id="${elementId}"` : ""}> uses data-layer instead of data-track-index.`,
+ elementId,
+ fixHint: "Replace data-layer with data-track-index. The runtime reads data-track-index.",
+ snippet: truncateSnippet(tag.raw),
+ });
+ }
+ if (readAttr(tag.raw, "data-end") && !readAttr(tag.raw, "data-duration")) {
+ const elementId = readAttr(tag.raw, "id") || undefined;
+ pushFinding({
+ code: "deprecated_data_end",
+ severity: "warning",
+ message: `<${tag.name}${elementId ? ` id="${elementId}"` : ""}> uses data-end without data-duration. Use data-duration in source HTML.`,
+ elementId,
+ fixHint:
+ "Replace data-end with data-duration. The compiler generates data-end from data-duration automatically.",
+ snippet: truncateSnippet(tag.raw),
+ });
+ }
+ }
+
+ const errorCount = findings.filter((finding) => finding.severity === "error").length;
+ const warningCount = findings.length - errorCount;
+
+ return {
+ ok: errorCount === 0,
+ errorCount,
+ warningCount,
+ findings,
+ };
+}
+
+function extractOpenTags(source: string): OpenTag[] {
+ const tags: OpenTag[] = [];
+ let match: RegExpExecArray | null;
+ while ((match = TAG_PATTERN.exec(source)) !== null) {
+ const raw = match[0];
+ if (raw.startsWith("</") || raw.startsWith("<!")) {
+ continue;
+ }
+ tags.push({
+ raw,
+ name: (match[1] || "").toLowerCase(),
+ attrs: match[2] || "",
+ index: match.index,
+ });
+ }
+ return tags;
+}
+
+function extractBlocks(source: string, pattern: RegExp): ExtractedBlock[] {
+ const blocks: ExtractedBlock[] = [];
+ let match: RegExpExecArray | null;
+ while ((match = pattern.exec(source)) !== null) {
+ blocks.push({
+ attrs: match[1] || "",
+ content: match[2] || "",
+ raw: match[0],
+ index: match.index,
+ });
+ }
+ return blocks;
+}
+
+function findRootTag(source: string): OpenTag | null {
+ const bodyMatch = source.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i);
+ const bodyContent = bodyMatch ? bodyMatch[1] ?? source : source;
+ const bodyTags = extractOpenTags(bodyContent);
+ for (const tag of bodyTags) {
+ if (["script", "style", "meta", "link", "title"].includes(tag.name)) {
+ continue;
+ }
+ return tag;
+ }
+ return null;
+}
+
+function readAttr(tagSource: string, attr: string): string | null {
+ if (!tagSource) {
+ return null;
+ }
+ const escaped = attr.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const match = tagSource.match(new RegExp(`\\b${escaped}\\s*=\\s*["']([^"']+)["']`, "i"));
+ return match?.[1] || null;
+}
+
+function collectCompositionIds(tags: OpenTag[]): Set<string> {
+ const ids = new Set<string>();
+ for (const tag of tags) {
+ const compId = readAttr(tag.raw, "data-composition-id");
+ if (compId) {
+ ids.add(compId);
+ }
+ }
+ return ids;
+}
+
+function extractCompositionIdsFromCss(css: string): string[] {
+ const ids = new Set<string>();
+ let match: RegExpExecArray | null;
+ while ((match = COMPOSITION_ID_IN_CSS_PATTERN.exec(css)) !== null) {
+ if (match[1]) {
+ ids.add(match[1]);
+ }
+ }
+ return [...ids];
+}
+
+function getInlineScriptSyntaxError(source: string): string | null {
+ if (!source.trim()) {
+ return null;
+ }
+ try {
+ // eslint-disable-next-line no-new-func
+ new Function(source);
+ return null;
+ } catch (error) {
+ if (error instanceof Error) {
+ return error.message;
+ }
+ return String(error);
+ }
+}
+
+function isMediaTag(tagName: string): boolean {
+ return tagName === "video" || tagName === "audio" || tagName === "img";
+}
+
+function countClassUsage(tags: OpenTag[]): Map<string, number> {
+ const counts = new Map<string, number>();
+ for (const tag of tags) {
+ const classAttr = readAttr(tag.raw, "class");
+ if (!classAttr) {
+ continue;
+ }
+ for (const className of classAttr.split(/\s+/).filter(Boolean)) {
+ counts.set(className, (counts.get(className) || 0) + 1);
+ }
+ }
+ return counts;
+}
+
+function readRegisteredTimelineCompositionId(script: string): string | null {
+ const match = script.match(WINDOW_TIMELINE_ASSIGN_PATTERN);
+ return match?.[1] || null;
+}
+
+function extractGsapWindows(script: string): GsapWindow[] {
+ if (!/gsap\.timeline/.test(script)) {
+ return [];
+ }
+
+ const parsed = parseGsapScript(script);
+ if (parsed.animations.length === 0) {
+ return [];
+ }
+
+ const windows: GsapWindow[] = [];
+ const timelineVar = parsed.timelineVar;
+ const methodPattern = new RegExp(`${timelineVar}\\.(set|to|from|fromTo)\\s*\\(([^)]+(?:\\{[^}]*\\}[^)]*)+)\\)`, "g");
+
+ let match: RegExpExecArray | null;
+ let index = 0;
+ while ((match = methodPattern.exec(script)) !== null && index < parsed.animations.length) {
+ const raw = match[0];
+ const meta = parseGsapWindowMeta(match[1] ?? "", match[2] ?? "");
+ const animation = parsed.animations[index];
+ index += 1;
+ if (!animation) {
+ continue;
+ }
+ windows.push({
+ targetSelector: animation.targetSelector,
+ position: animation.position,
+ end: animation.position + meta.effectiveDuration,
+ properties: meta.properties.length > 0 ? meta.properties : Object.keys(animation.properties),
+ overwriteAuto: meta.overwriteAuto,
+ raw,
+ });
+ }
+
+ return windows;
+}
+
+function parseGsapWindowMeta(
+ method: string,
+ argsStr: string,
+): {
+ effectiveDuration: number;
+ properties: string[];
+ overwriteAuto: boolean;
+} {
+ const selectorMatch = argsStr.match(/^\s*["']([^"']+)["']\s*,/);
+ if (!selectorMatch) {
+ return { effectiveDuration: 0, properties: [], overwriteAuto: false };
+ }
+
+ const afterSelector = argsStr.slice(selectorMatch[0].length);
+ let properties: Record<string, string | number> = {};
+ let fromProperties: Record<string, string | number> = {};
+
+ if (method === "fromTo") {
+ const firstBrace = afterSelector.indexOf("{");
+ const firstEnd = findMatchingBrace(afterSelector, firstBrace);
+ if (firstBrace !== -1 && firstEnd !== -1) {
+ fromProperties = parseLooseObjectLiteral(afterSelector.slice(firstBrace, firstEnd + 1));
+ const secondPart = afterSelector.slice(firstEnd + 1);
+ const secondBrace = secondPart.indexOf("{");
+ const secondEnd = findMatchingBrace(secondPart, secondBrace);
+ if (secondBrace !== -1 && secondEnd !== -1) {
+ properties = parseLooseObjectLiteral(secondPart.slice(secondBrace, secondEnd + 1));
+ }
+ }
+ } else {
+ const braceStart = afterSelector.indexOf("{");
+ const braceEnd = findMatchingBrace(afterSelector, braceStart);
+ if (braceStart !== -1 && braceEnd !== -1) {
+ properties = parseLooseObjectLiteral(afterSelector.slice(braceStart, braceEnd + 1));
+ }
+ }
+
+ const duration = numberValue(properties.duration) || 0;
+ const repeat = numberValue(properties.repeat) || 0;
+ const yoyo = stringValue(properties.yoyo) === "true";
+ const cycleCount = repeat > 0 ? repeat + 1 : 1;
+ const effectiveDuration = duration * cycleCount * (yoyo ? 1 : 1);
+ const overwriteAuto = stringValue(properties.overwrite) === "auto";
+
+ const propertyNames = new Set<string>();
+ for (const key of Object.keys(fromProperties)) {
+ if (!META_GSAP_KEYS.has(key)) {
+ propertyNames.add(key);
+ }
+ }
+ for (const key of Object.keys(properties)) {
+ if (!META_GSAP_KEYS.has(key)) {
+ propertyNames.add(key);
+ }
+ }
+
+ return {
+ effectiveDuration: method === "set" ? 0 : effectiveDuration,
+ properties: [...propertyNames],
+ overwriteAuto,
+ };
+}
+
+function parseLooseObjectLiteral(source: string): Record<string, string | number> {
+ const result: Record<string, string | number> = {};
+ const cleaned = source.replace(/^\{|\}$/g, "").trim();
+ if (!cleaned) {
+ return result;
+ }
+
+ const propertyPattern = /(\w+)\s*:\s*("[^"]*"|'[^']*'|true|false|-?[\d.]+|[a-zA-Z_][\w.]*)/g;
+ let match: RegExpExecArray | null;
+ while ((match = propertyPattern.exec(cleaned)) !== null) {
+ const key = match[1];
+ const rawValue = match[2];
+ if (!key || rawValue == null) {
+ continue;
+ }
+ if ((rawValue.startsWith('"') && rawValue.endsWith('"')) || (rawValue.startsWith("'") && rawValue.endsWith("'"))) {
+ result[key] = rawValue.slice(1, -1);
+ continue;
+ }
+ const numeric = Number(rawValue);
+ result[key] = Number.isFinite(numeric) ? numeric : rawValue;
+ }
+ return result;
+}
+
+function findMatchingBrace(source: string, startIndex: number): number {
+ if (startIndex < 0) {
+ return -1;
+ }
+ let depth = 0;
+ for (let i = startIndex; i < source.length; i++) {
+ if (source[i] === "{") {
+ depth += 1;
+ } else if (source[i] === "}") {
+ depth -= 1;
+ if (depth === 0) {
+ return i;
+ }
+ }
+ }
+ return -1;
+}
+
+function numberValue(value: string | number | undefined): number | null {
+ if (typeof value === "number") {
+ return value;
+ }
+ if (typeof value === "string" && value.trim()) {
+ const numeric = Number(value);
+ return Number.isFinite(numeric) ? numeric : null;
+ }
+ return null;
+}
+
+function stringValue(value: string | number | undefined): string | null {
+ if (typeof value === "string") {
+ return value;
+ }
+ if (typeof value === "number") {
+ return String(value);
+ }
+ return null;
+}
+
+function isSuspiciousGlobalSelector(selector: string): boolean {
+ if (!selector) {
+ return false;
+ }
+ if (selector.includes("[data-composition-id=")) {
+ return false;
+ }
+ if (selector.startsWith("#")) {
+ return false;
+ }
+ return selector.startsWith(".") || /^[a-z]/i.test(selector);
+}
+
+function getSingleClassSelector(selector: string): string | null {
+ const match = selector.trim().match(/^\.(?<name>[A-Za-z0-9_-]+)$/);
+ return match?.groups?.name || null;
+}
+
+function truncateSnippet(value: string, maxLength = 220): string | undefined {
+ const normalized = value.replace(/\s+/g, " ").trim();
+ if (!normalized) {
+ return undefined;
+ }
+ if (normalized.length <= maxLength) {
+ return normalized;
+ }
+ return `${normalized.slice(0, maxLength - 3)}...`;
+}
diff --git a/packages/core/src/lint/index.ts b/packages/core/src/lint/index.ts
new file mode 100644
index 0000000000..ec2a3926d0
--- /dev/null
+++ b/packages/core/src/lint/index.ts
@@ -0,0 +1,7 @@
+export type {
+ HyperframeLintSeverity,
+ HyperframeLintFinding,
+ HyperframeLintResult,
+ HyperframeLinterOptions,
+} from "./types";
+export { lintHyperframeHtml } from "./hyperframeLinter";
diff --git a/packages/core/src/lint/types.ts b/packages/core/src/lint/types.ts
new file mode 100644
index 0000000000..a612bcb3e2
--- /dev/null
+++ b/packages/core/src/lint/types.ts
@@ -0,0 +1,23 @@
+export type HyperframeLintSeverity = "error" | "warning";
+
+export type HyperframeLintFinding = {
+ code: string;
+ severity: HyperframeLintSeverity;
+ message: string;
+ file?: string;
+ selector?: string;
+ elementId?: string;
+ fixHint?: string;
+ snippet?: string;
+};
+
+export type HyperframeLintResult = {
+ ok: boolean;
+ errorCount: number;
+ warningCount: number;
+ findings: HyperframeLintFinding[];
+};
+
+export type HyperframeLinterOptions = {
+ filePath?: string;
+};
diff --git a/packages/core/src/parsers/gsapParser.test.ts b/packages/core/src/parsers/gsapParser.test.ts
new file mode 100644
index 0000000000..c5ddd8aa4e
--- /dev/null
+++ b/packages/core/src/parsers/gsapParser.test.ts
@@ -0,0 +1,532 @@
+import { describe, it, expect } from "vitest";
+import {
+ parseGsapScript,
+ gsapAnimationsToKeyframes,
+ SUPPORTED_PROPS,
+ SUPPORTED_EASES,
+ serializeGsapAnimations,
+ validateCompositionGsap,
+ getAnimationsForElement,
+ keyframesToGsapAnimations,
+} from "./gsapParser.js";
+import type { GsapAnimation } from "./gsapParser.js";
+import type { Keyframe } from "../core.types";
+
+describe("parseGsapScript", () => {
+ it("parses a basic timeline with .to()", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#el1", { opacity: 1, duration: 0.5 }, 0);
+ `;
+ const result = parseGsapScript(script);
+
+ expect(result.timelineVar).toBe("tl");
+ expect(result.animations).toHaveLength(1);
+ expect(result.animations[0].method).toBe("to");
+ expect(result.animations[0].targetSelector).toBe("#el1");
+ expect(result.animations[0].properties.opacity).toBe(1);
+ expect(result.animations[0].duration).toBe(0.5);
+ expect(result.animations[0].position).toBe(0);
+ });
+
+ it("parses a timeline with .from()", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.from("#el2", { x: 100, duration: 1 }, 0.5);
+ `;
+ const result = parseGsapScript(script);
+
+ expect(result.animations).toHaveLength(1);
+ expect(result.animations[0].method).toBe("from");
+ expect(result.animations[0].targetSelector).toBe("#el2");
+ expect(result.animations[0].properties.x).toBe(100);
+ expect(result.animations[0].duration).toBe(1);
+ expect(result.animations[0].position).toBe(0.5);
+ });
+
+ it("parses a timeline with .set()", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.set("#el3", { opacity: 0, x: 50 }, 0);
+ `;
+ const result = parseGsapScript(script);
+
+ expect(result.animations).toHaveLength(1);
+ expect(result.animations[0].method).toBe("set");
+ expect(result.animations[0].targetSelector).toBe("#el3");
+ expect(result.animations[0].properties.opacity).toBe(0);
+ expect(result.animations[0].properties.x).toBe(50);
+ expect(result.animations[0].duration).toBeUndefined();
+ });
+
+ it("parses a timeline with .fromTo() and position offset", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.fromTo("#el4", { opacity: 0, x: 100 }, { opacity: 1, x: 200, duration: 1 }, 2);
+ `;
+ const result = parseGsapScript(script);
+
+ expect(result.animations).toHaveLength(1);
+ const anim = result.animations[0];
+ expect(anim.method).toBe("fromTo");
+ expect(anim.targetSelector).toBe("#el4");
+ expect(anim.fromProperties).toBeDefined();
+ expect(anim.fromProperties?.opacity).toBe(0);
+ expect(anim.fromProperties?.x).toBe(100);
+ expect(anim.properties.opacity).toBe(1);
+ expect(anim.properties.x).toBe(200);
+ expect(anim.duration).toBe(1);
+ expect(anim.position).toBe(2);
+ });
+
+ it("parseObjectLiteral does not match negative numbers (known limitation)", () => {
+ // The regex in parseObjectLiteral only matches [\d.]+, not negative numbers.
+ // Negative values like x: -100 won't be parsed by the object literal parser.
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.fromTo("#el5", { opacity: 0, x: -100 }, { opacity: 1, x: 0, duration: 1 }, 0);
+ `;
+ const result = parseGsapScript(script);
+
+ expect(result.animations).toHaveLength(1);
+ const anim = result.animations[0];
+ expect(anim.fromProperties).toBeDefined();
+ expect(anim.fromProperties?.opacity).toBe(0);
+ // -100 is not parseable by the regex, so x won't be in fromProperties
+ expect(anim.fromProperties?.x).toBeUndefined();
+ });
+
+ it("handles an empty script", () => {
+ const result = parseGsapScript("");
+
+ expect(result.animations).toHaveLength(0);
+ expect(result.timelineVar).toBe("tl");
+ expect(result.preamble).toBe("const tl = gsap.timeline({ paused: true });");
+ expect(result.postamble).toBe("");
+ });
+
+ it("extracts preamble correctly", () => {
+ const script = `
+ const myTl = gsap.timeline({ paused: true });
+ myTl.to("#el1", { opacity: 1, duration: 0.5 }, 0);
+ `;
+ const result = parseGsapScript(script);
+
+ expect(result.timelineVar).toBe("myTl");
+ expect(result.preamble).toContain("const myTl = gsap.timeline");
+ });
+
+ it("extracts postamble correctly", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#el1", { opacity: 1, duration: 0.5 }, 0);
+ console.log("done");
+ `;
+ const result = parseGsapScript(script);
+
+ expect(result.postamble).toContain('console.log("done");');
+ });
+
+ it("parses multiple animations", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.set("#el1", { opacity: 0 }, 0);
+ tl.to("#el1", { opacity: 1, duration: 0.5 }, 0);
+ tl.to("#el2", { x: 100, duration: 1 }, 1);
+ `;
+ const result = parseGsapScript(script);
+
+ expect(result.animations).toHaveLength(3);
+ expect(result.animations[0].method).toBe("set");
+ expect(result.animations[1].method).toBe("to");
+ expect(result.animations[2].method).toBe("to");
+ });
+
+ it("filters out unsupported properties from animations", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#el1", { opacity: 1, backgroundColor: "red", x: 50, duration: 0.5 }, 0);
+ `;
+ const result = parseGsapScript(script);
+
+ expect(result.animations[0].properties.opacity).toBe(1);
+ expect(result.animations[0].properties.x).toBe(50);
+ // backgroundColor is not in SUPPORTED_PROPS, so it's filtered out
+ expect(result.animations[0].properties.backgroundColor).toBeUndefined();
+ });
+
+ it("extracts ease from properties", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#el1", { opacity: 1, duration: 1, ease: "power2.out" }, 0);
+ `;
+ const result = parseGsapScript(script);
+
+ expect(result.animations[0].ease).toBe("power2.out");
+ });
+
+ it("uses 'let' or 'var' for timeline declaration", () => {
+ const script = `
+ let timeline = gsap.timeline({ paused: true });
+ timeline.to("#el1", { opacity: 1, duration: 1 }, 0);
+ `;
+ const result = parseGsapScript(script);
+
+ expect(result.timelineVar).toBe("timeline");
+ expect(result.animations).toHaveLength(1);
+ });
+});
+
+describe("gsapAnimationsToKeyframes", () => {
+ it("converts animations to keyframes with element start offset", () => {
+ const animations: GsapAnimation[] = [
+ {
+ id: "anim-1",
+ targetSelector: "#el1",
+ method: "set",
+ position: 2,
+ properties: { x: 100, y: 200 },
+ },
+ {
+ id: "anim-2",
+ targetSelector: "#el1",
+ method: "to",
+ position: 3,
+ properties: { x: 300, y: 400 },
+ duration: 1,
+ ease: "power2.out",
+ },
+ ];
+
+ const keyframes = gsapAnimationsToKeyframes(animations, 2);
+
+ expect(keyframes).toHaveLength(2);
+ // First keyframe: time = 2 - 2 = 0
+ expect(keyframes[0].time).toBe(0);
+ expect(keyframes[0].properties.x).toBe(100);
+ expect(keyframes[0].properties.y).toBe(200);
+ // Second keyframe: time = 3 - 2 = 1
+ expect(keyframes[1].time).toBe(1);
+ expect(keyframes[1].properties.x).toBe(300);
+ expect(keyframes[1].ease).toBe("power2.out");
+ });
+
+ it("filters supported props only", () => {
+ const animations: GsapAnimation[] = [
+ {
+ id: "anim-1",
+ targetSelector: "#el1",
+ method: "to",
+ position: 0,
+ properties: { opacity: 1, x: 50, someUnsupportedProp: "value" } as Record<string, number | string>,
+ duration: 1,
+ },
+ ];
+
+ const keyframes = gsapAnimationsToKeyframes(animations, 0);
+
+ expect(keyframes).toHaveLength(1);
+ expect(keyframes[0].properties.opacity).toBe(1);
+ expect(keyframes[0].properties.x).toBe(50);
+ // String values are skipped (typeof value !== "number" check)
+ expect((keyframes[0].properties as Record<string, unknown>).someUnsupportedProp).toBeUndefined();
+ });
+
+ it("skips base set keyframes at time 0 when skipBaseSet is true", () => {
+ const animations: GsapAnimation[] = [
+ {
+ id: "anim-1",
+ targetSelector: "#el1",
+ method: "set",
+ position: 5,
+ properties: { x: 0, y: 0, scale: 1 },
+ },
+ {
+ id: "anim-2",
+ targetSelector: "#el1",
+ method: "to",
+ position: 6,
+ properties: { x: 100 },
+ duration: 1,
+ },
+ ];
+
+ const keyframes = gsapAnimationsToKeyframes(animations, 5, { skipBaseSet: true });
+
+ // The set at position 5 (time=0) with x=0, y=0, scale=1 (base values) should be skipped
+ expect(keyframes).toHaveLength(1);
+ expect(keyframes[0].id).toBe("anim-2");
+ });
+
+ it("does NOT skip set keyframes when they have non-base values", () => {
+ const animations: GsapAnimation[] = [
+ {
+ id: "anim-1",
+ targetSelector: "#el1",
+ method: "set",
+ position: 5,
+ properties: { x: 100, y: 0 },
+ },
+ ];
+
+ const keyframes = gsapAnimationsToKeyframes(animations, 5, { skipBaseSet: true });
+
+ // x=100 is non-base, so it should NOT be skipped
+ expect(keyframes).toHaveLength(1);
+ expect(keyframes[0].properties.x).toBe(100);
+ });
+
+ it("clamps negative time to zero by default", () => {
+ const animations: GsapAnimation[] = [
+ {
+ id: "anim-1",
+ targetSelector: "#el1",
+ method: "set",
+ position: 0,
+ properties: { opacity: 1 },
+ },
+ ];
+
+ // elementStartTime is 5, so relative time = 0 - 5 = -5
+ const keyframes = gsapAnimationsToKeyframes(animations, 5);
+
+ expect(keyframes[0].time).toBe(0); // Clamped to 0
+ });
+
+ it("adjusts x/y/scale relative to base values", () => {
+ const animations: GsapAnimation[] = [
+ {
+ id: "anim-1",
+ targetSelector: "#el1",
+ method: "to",
+ position: 2,
+ properties: { x: 150, y: 200, scale: 2 },
+ duration: 1,
+ },
+ ];
+
+ const keyframes = gsapAnimationsToKeyframes(animations, 0, {
+ baseX: 50,
+ baseY: 100,
+ baseScale: 2,
+ });
+
+ expect(keyframes[0].properties.x).toBe(100); // 150 - 50
+ expect(keyframes[0].properties.y).toBe(100); // 200 - 100
+ expect(keyframes[0].properties.scale).toBe(1); // 2 / 2
+ });
+});
+
+describe("keyframesToGsapAnimations", () => {
+ it("converts keyframes back to GSAP animations", () => {
+ const keyframes: Keyframe[] = [
+ { id: "kf-1", time: 0, properties: { opacity: 0 } },
+ { id: "kf-2", time: 1, properties: { opacity: 1 }, ease: "power2.out" },
+ ];
+
+ const animations = keyframesToGsapAnimations("el1", keyframes, 2);
+
+ expect(animations).toHaveLength(2);
+ expect(animations[0].method).toBe("set");
+ expect(animations[0].position).toBe(2); // elementStartTime + 0
+ expect(animations[0].properties.opacity).toBe(0);
+ expect(animations[1].method).toBe("to");
+ expect(animations[1].position).toBe(2); // position of prev keyframe
+ expect(animations[1].duration).toBe(1); // kf.time - prevKf.time
+ expect(animations[1].ease).toBe("power2.out");
+ });
+
+ it("applies base x/y/scale offsets", () => {
+ const keyframes: Keyframe[] = [
+ { id: "kf-1", time: 0, properties: { x: 10, y: 20, scale: 2 } },
+ ];
+
+ const animations = keyframesToGsapAnimations("el1", keyframes, 0, {
+ x: 50,
+ y: 100,
+ scale: 0.5,
+ });
+
+ expect(animations[0].properties.x).toBe(60); // baseX + value
+ expect(animations[0].properties.y).toBe(120); // baseY + value
+ expect(animations[0].properties.scale).toBe(1); // baseScale * value
+ });
+});
+
+describe("serializeGsapAnimations", () => {
+ it("serializes animations into a GSAP timeline script", () => {
+ const animations: GsapAnimation[] = [
+ {
+ id: "anim-1",
+ targetSelector: "#el1",
+ method: "set",
+ position: 0,
+ properties: { opacity: 0 },
+ },
+ {
+ id: "anim-2",
+ targetSelector: "#el1",
+ method: "to",
+ position: 0.5,
+ properties: { opacity: 1 },
+ duration: 0.5,
+ ease: "power2.out",
+ },
+ ];
+
+ const result = serializeGsapAnimations(animations);
+
+ expect(result).toContain("const tl = gsap.timeline({ paused: true });");
+ expect(result).toContain('tl.set("#el1"');
+ expect(result).toContain('tl.to("#el1"');
+ expect(result).toContain("opacity: 0");
+ expect(result).toContain("opacity: 1");
+ });
+
+ it("sorts animations by position", () => {
+ const animations: GsapAnimation[] = [
+ {
+ id: "anim-2",
+ targetSelector: "#el1",
+ method: "to",
+ position: 2,
+ properties: { opacity: 1 },
+ duration: 0.5,
+ },
+ {
+ id: "anim-1",
+ targetSelector: "#el1",
+ method: "set",
+ position: 0,
+ properties: { opacity: 0 },
+ },
+ ];
+
+ const result = serializeGsapAnimations(animations);
+
+ const setIdx = result.indexOf("tl.set");
+ const toIdx = result.indexOf("tl.to");
+ expect(setIdx).toBeLessThan(toIdx);
+ });
+
+ it("serializes fromTo animations correctly", () => {
+ const animations: GsapAnimation[] = [
+ {
+ id: "anim-1",
+ targetSelector: "#el1",
+ method: "fromTo",
+ position: 0,
+ properties: { opacity: 1 },
+ fromProperties: { opacity: 0 },
+ duration: 1,
+ },
+ ];
+
+ const result = serializeGsapAnimations(animations);
+ expect(result).toContain('tl.fromTo("#el1"');
+ });
+
+ it("uses custom timeline variable name", () => {
+ const animations: GsapAnimation[] = [
+ {
+ id: "anim-1",
+ targetSelector: "#el1",
+ method: "set",
+ position: 0,
+ properties: { opacity: 0 },
+ },
+ ];
+
+ const result = serializeGsapAnimations(animations, "myTimeline");
+ expect(result).toContain("const myTimeline = gsap.timeline({ paused: true });");
+ expect(result).toContain('myTimeline.set("#el1"');
+ });
+});
+
+describe("validateCompositionGsap", () => {
+ it("returns valid for clean scripts", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#el1", { opacity: 1, duration: 1 }, 0);
+ `;
+ const result = validateCompositionGsap(script);
+ expect(result.valid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it("detects forbidden patterns", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#el1", { opacity: 1, duration: 1, onComplete: function() {} }, 0);
+ setTimeout(function() {}, 100);
+ `;
+ const result = validateCompositionGsap(script);
+ expect(result.valid).toBe(false);
+ expect(result.errors).toContain("onComplete callback not allowed");
+ expect(result.errors).toContain("setTimeout not allowed");
+ });
+
+ it("warns about yoyo and stagger", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.to(".items", { x: 100, stagger: 0.1, yoyo: true, duration: 1 }, 0);
+ `;
+ const result = validateCompositionGsap(script);
+ expect(result.warnings).toContain("yoyo animations may behave unexpectedly when scrubbing");
+ expect(result.warnings).toContain("stagger animations may not serialize correctly");
+ });
+
+ it("detects infinite repeat", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#el1", { opacity: 1, duration: 1, repeat: -1 }, 0);
+ `;
+ const result = validateCompositionGsap(script);
+ expect(result.valid).toBe(false);
+ expect(result.errors).toContain("Infinite repeat (repeat: -1) not allowed");
+ });
+});
+
+describe("getAnimationsForElement", () => {
+ it("filters animations by element id", () => {
+ const animations: GsapAnimation[] = [
+ { id: "a1", targetSelector: "#el1", method: "set", position: 0, properties: { opacity: 0 } },
+ { id: "a2", targetSelector: "#el2", method: "to", position: 0, properties: { opacity: 1 }, duration: 1 },
+ { id: "a3", targetSelector: "#el1", method: "to", position: 1, properties: { opacity: 1 }, duration: 0.5 },
+ ];
+
+ const result = getAnimationsForElement(animations, "el1");
+ expect(result).toHaveLength(2);
+ expect(result.every((a) => a.targetSelector === "#el1")).toBe(true);
+ });
+
+ it("returns empty array when no animations match", () => {
+ const animations: GsapAnimation[] = [
+ { id: "a1", targetSelector: "#el1", method: "set", position: 0, properties: { opacity: 0 } },
+ ];
+
+ const result = getAnimationsForElement(animations, "el99");
+ expect(result).toHaveLength(0);
+ });
+});
+
+describe("SUPPORTED_PROPS", () => {
+ it("includes expected properties", () => {
+ expect(SUPPORTED_PROPS).toContain("opacity");
+ expect(SUPPORTED_PROPS).toContain("x");
+ expect(SUPPORTED_PROPS).toContain("y");
+ expect(SUPPORTED_PROPS).toContain("scale");
+ expect(SUPPORTED_PROPS).toContain("rotation");
+ expect(SUPPORTED_PROPS).toContain("width");
+ expect(SUPPORTED_PROPS).toContain("height");
+ });
+});
+
+describe("SUPPORTED_EASES", () => {
+ it("includes common easing functions", () => {
+ expect(SUPPORTED_EASES).toContain("none");
+ expect(SUPPORTED_EASES).toContain("power2.out");
+ expect(SUPPORTED_EASES).toContain("bounce.out");
+ expect(SUPPORTED_EASES).toContain("elastic.inOut");
+ });
+});
diff --git a/packages/core/src/parsers/gsapParser.ts b/packages/core/src/parsers/gsapParser.ts
new file mode 100644
index 0000000000..6ea0949eb4
--- /dev/null
+++ b/packages/core/src/parsers/gsapParser.ts
@@ -0,0 +1,508 @@
+import type { Keyframe, KeyframeProperties } from "../core.types";
+
+export type GsapMethod = "set" | "to" | "from" | "fromTo";
+
+export interface GsapAnimation {
+ id: string;
+ targetSelector: string;
+ method: GsapMethod;
+ position: number;
+ properties: Record<string, number | string>;
+ fromProperties?: Record<string, number | string>;
+ duration?: number;
+ ease?: string;
+}
+
+export interface ParsedGsap {
+ animations: GsapAnimation[];
+ timelineVar: string;
+ preamble: string;
+ postamble: string;
+}
+
+const GSAP_METHODS = new Set<string>(["set", "to", "from", "fromTo"]);
+
+export const SUPPORTED_PROPS = [
+ "opacity",
+ "visibility",
+ "x",
+ "y",
+ "scale",
+ "scaleX",
+ "scaleY",
+ "rotation",
+ "autoAlpha",
+ "width",
+ "height",
+];
+
+export const SUPPORTED_EASES = [
+ "none",
+ "power1.in",
+ "power1.out",
+ "power1.inOut",
+ "power2.in",
+ "power2.out",
+ "power2.inOut",
+ "power3.in",
+ "power3.out",
+ "power3.inOut",
+ "power4.in",
+ "power4.out",
+ "power4.inOut",
+ "back.in",
+ "back.out",
+ "back.inOut",
+ "elastic.in",
+ "elastic.out",
+ "elastic.inOut",
+ "bounce.in",
+ "bounce.out",
+ "bounce.inOut",
+ "expo.in",
+ "expo.out",
+ "expo.inOut",
+];
+
+function parseObjectLiteral(str: string): Record<string, number | string> {
+ const result: Record<string, number | string> = {};
+
+ const cleaned = str.replace(/^\{|\}$/g, "").trim();
+ if (!cleaned) return result;
+
+ const propRegex = /(\w+)\s*:\s*("[^"]*"|'[^']*'|[\d.]+|[a-zA-Z_][\w.]*)/g;
+ let match;
+
+ while ((match = propRegex.exec(cleaned)) !== null) {
+ const key = match[1] ?? "";
+ let value: string | number = match[2] ?? "";
+
+ if (typeof value === "string") {
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
+ value = value.slice(1, -1);
+ } else if (!isNaN(Number(value))) {
+ value = Number(value);
+ }
+ }
+
+ result[key] = value;
+ }
+
+ return result;
+}
+
+function findMatchingBrace(str: string, startIndex: number): number {
+ let depth = 0;
+ for (let i = startIndex; i < str.length; i++) {
+ if (str[i] === "{") depth++;
+ else if (str[i] === "}") {
+ depth--;
+ if (depth === 0) return i;
+ }
+ }
+ return -1;
+}
+
+export function parseGsapScript(script: string): ParsedGsap {
+ const animations: GsapAnimation[] = [];
+ let idCounter = 0;
+
+ const timelineMatch = script.match(/(?:const|let|var)\s+(\w+)\s*=\s*gsap\.timeline/);
+ const timelineVar = timelineMatch ? timelineMatch[1] ?? "tl" : "tl";
+
+ const preambleMatch = script.match(
+ new RegExp(`^[\\s\\S]*?(?:const|let|var)\\s+${timelineVar}\\s*=\\s*gsap\\.timeline\\s*\\([^)]*\\)\\s*;?`),
+ );
+ const preamble = preambleMatch ? preambleMatch[0] : `const ${timelineVar} = gsap.timeline({ paused: true });`;
+
+ const methodPattern = new RegExp(`${timelineVar}\\.(set|to|from|fromTo)\\s*\\(([^)]+(?:\\{[^}]*\\}[^)]*)+)\\)`, "g");
+
+ let match;
+ while ((match = methodPattern.exec(script)) !== null) {
+ const rawMethod = match[1];
+ if (!rawMethod || !GSAP_METHODS.has(rawMethod)) continue;
+ const method: GsapMethod = rawMethod as GsapMethod;
+ const argsStr = match[2] ?? "";
+
+ const animation = parseGsapCall(method, argsStr, ++idCounter);
+ if (animation) {
+ animations.push(animation);
+ }
+ }
+
+ const lastAnimIdx = script.lastIndexOf(`${timelineVar}.`);
+ let postamble = "";
+ if (lastAnimIdx !== -1) {
+ const afterLastAnim = script.slice(lastAnimIdx);
+ const endOfCall = afterLastAnim.indexOf(";");
+ if (endOfCall !== -1) {
+ postamble = script.slice(lastAnimIdx + endOfCall + 1).trim();
+ }
+ }
+
+ return { animations, timelineVar, preamble, postamble };
+}
+
+function parseGsapCall(method: GsapMethod, argsStr: string, idNum: number): GsapAnimation | null {
+ const selectorMatch = argsStr.match(/^\s*["']([^"']+)["']\s*,/);
+ if (!selectorMatch) return null;
+
+ const targetSelector = selectorMatch[1] ?? "";
+ const afterSelector = argsStr.slice(selectorMatch[0].length);
+
+ let properties: Record<string, number | string> = {};
+ let fromProperties: Record<string, number | string> | undefined;
+ let position = 0;
+
+ if (method === "fromTo") {
+ const firstBrace = afterSelector.indexOf("{");
+ const firstEnd = findMatchingBrace(afterSelector, firstBrace);
+ if (firstBrace === -1 || firstEnd === -1) return null;
+
+ fromProperties = parseObjectLiteral(afterSelector.slice(firstBrace, firstEnd + 1));
+
+ const secondPart = afterSelector.slice(firstEnd + 1);
+ const secondBrace = secondPart.indexOf("{");
+ const secondEnd = findMatchingBrace(secondPart, secondBrace);
+ if (secondBrace === -1 || secondEnd === -1) return null;
+
+ properties = parseObjectLiteral(secondPart.slice(secondBrace, secondEnd + 1));
+
+ const afterProps = secondPart.slice(secondEnd + 1);
+ const posMatch = afterProps.match(/,\s*([\d.]+)/);
+ if (posMatch) position = parseFloat(posMatch[1] ?? "");
+ } else {
+ const braceStart = afterSelector.indexOf("{");
+ const braceEnd = findMatchingBrace(afterSelector, braceStart);
+
+ if (braceStart !== -1 && braceEnd !== -1) {
+ properties = parseObjectLiteral(afterSelector.slice(braceStart, braceEnd + 1));
+
+ const afterProps = afterSelector.slice(braceEnd + 1);
+ const posMatch = afterProps.match(/,\s*([\d.]+)/);
+ if (posMatch) position = parseFloat(posMatch[1] ?? "");
+ }
+ }
+
+ const duration = typeof properties.duration === "number" ? properties.duration : undefined;
+ const ease = typeof properties.ease === "string" ? properties.ease : undefined;
+
+ const filteredProps: Record<string, number | string> = {};
+ for (const [key, value] of Object.entries(properties)) {
+ if (SUPPORTED_PROPS.includes(key)) {
+ filteredProps[key] = value;
+ }
+ }
+
+ let filteredFromProps: Record<string, number | string> | undefined;
+ if (fromProperties) {
+ filteredFromProps = {};
+ for (const [key, value] of Object.entries(fromProperties)) {
+ if (SUPPORTED_PROPS.includes(key)) {
+ filteredFromProps[key] = value;
+ }
+ }
+ }
+
+ return {
+ id: `anim-${idNum}`,
+ targetSelector,
+ method,
+ position,
+ properties: filteredProps,
+ fromProperties: filteredFromProps,
+ duration,
+ ease,
+ };
+}
+
+export function serializeGsapAnimations(
+ animations: GsapAnimation[],
+ timelineVar = "tl",
+ options?: { includeMediaSync?: boolean },
+): string {
+ const sorted = [...animations].sort((a, b) => a.position - b.position);
+
+ const lines = sorted.map((anim) => {
+ const selector = `"${anim.targetSelector}"`;
+
+ const props: Record<string, number | string> = { ...anim.properties };
+ if (anim.duration !== undefined) props.duration = anim.duration;
+ if (anim.ease) props.ease = anim.ease;
+
+ const propsStr = serializeObject(props);
+
+ switch (anim.method) {
+ case "set":
+ return ` ${timelineVar}.set(${selector}, ${propsStr}, ${anim.position});`;
+ case "to":
+ return ` ${timelineVar}.to(${selector}, ${propsStr}, ${anim.position});`;
+ case "from":
+ return ` ${timelineVar}.from(${selector}, ${propsStr}, ${anim.position});`;
+ case "fromTo": {
+ const fromStr = serializeObject(anim.fromProperties || {});
+ return ` ${timelineVar}.fromTo(${selector}, ${fromStr}, ${propsStr}, ${anim.position});`;
+ }
+ }
+ });
+
+ let mediaSync = "";
+ if (options?.includeMediaSync) {
+ mediaSync = `
+ // Sync media playback
+ ${timelineVar}.eventCallback("onUpdate", function() {
+ const time = ${timelineVar}.time();
+ document.querySelectorAll("video[data-start], audio[data-start]").forEach(function(media) {
+ const start = parseFloat(media.dataset.start);
+ const end = parseFloat(media.dataset.end) || Infinity;
+ const mediaTime = time - start;
+ if (time >= start && time < end) {
+ if (Math.abs(media.currentTime - mediaTime) > 0.1) {
+ media.currentTime = mediaTime;
+ }
+ if (media.paused && !${timelineVar}.paused()) {
+ media.play().catch(function() {});
+ }
+ } else if (!media.paused) {
+ media.pause();
+ }
+ });
+ });`;
+ }
+
+ return `
+ const ${timelineVar} = gsap.timeline({ paused: true });
+${lines.join("\n")}${mediaSync}
+ `;
+}
+
+function serializeObject(obj: Record<string, number | string>): string {
+ const entries = Object.entries(obj).map(([key, value]) => {
+ if (typeof value === "string") {
+ return `${key}: "${value}"`;
+ }
+ return `${key}: ${value}`;
+ });
+ return `{ ${entries.join(", ")} }`;
+}
+
+export function updateAnimationInScript(script: string, animationId: string, updates: Partial<GsapAnimation>): string {
+ const parsed = parseGsapScript(script);
+
+ const updated = parsed.animations.map((anim) => {
+ if (anim.id === animationId) {
+ return { ...anim, ...updates };
+ }
+ return anim;
+ });
+
+ return serializeGsapAnimations(updated, parsed.timelineVar);
+}
+
+export function addAnimationToScript(
+ script: string,
+ animation: Omit<GsapAnimation, "id">,
+): { script: string; id: string } {
+ const parsed = parseGsapScript(script);
+
+ const id = `anim-${Date.now()}`;
+ const newAnim: GsapAnimation = { ...animation, id };
+
+ parsed.animations.push(newAnim);
+
+ return {
+ script: serializeGsapAnimations(parsed.animations, parsed.timelineVar),
+ id,
+ };
+}
+
+export function removeAnimationFromScript(script: string, animationId: string): string {
+ const parsed = parseGsapScript(script);
+ const filtered = parsed.animations.filter((a) => a.id !== animationId);
+ return serializeGsapAnimations(filtered, parsed.timelineVar);
+}
+
+export function getAnimationsForElement(animations: GsapAnimation[], elementId: string): GsapAnimation[] {
+ const selector = `#${elementId}`;
+ return animations.filter((a) => a.targetSelector === selector);
+}
+
+export interface ValidationResult {
+ valid: boolean;
+ errors: string[];
+ warnings: string[];
+}
+
+const FORBIDDEN_GSAP_PATTERNS: Array<{ pattern: RegExp; message: string }> = [
+ { pattern: /\.call\s*\(/, message: "call() method not allowed" },
+ {
+ pattern: /\.add\s*\(\s*function/,
+ message: "add(function) not allowed",
+ },
+ {
+ pattern: /\.add\s*\(\s*\(/,
+ message: "add() with arrow function not allowed",
+ },
+ { pattern: /onComplete\s*:/, message: "onComplete callback not allowed" },
+ { pattern: /onStart\s*:/, message: "onStart callback not allowed" },
+ { pattern: /onUpdate\s*:/, message: "onUpdate callback not allowed" },
+ {
+ pattern: /onRepeat\s*:/,
+ message: "onRepeat callback not allowed",
+ },
+ {
+ pattern: /onReverseComplete\s*:/,
+ message: "onReverseComplete callback not allowed",
+ },
+ {
+ pattern: /repeat\s*:\s*-1/,
+ message: "Infinite repeat (repeat: -1) not allowed",
+ },
+ {
+ pattern: /Math\.random\s*\(/,
+ message: "Random values (Math.random) not allowed",
+ },
+ {
+ pattern: /Date\.now\s*\(/,
+ message: "Date-dependent values (Date.now) not allowed",
+ },
+ { pattern: /new\s+Date\s*\(/, message: "Date constructor not allowed" },
+ { pattern: /setTimeout\s*\(/, message: "setTimeout not allowed" },
+ { pattern: /setInterval\s*\(/, message: "setInterval not allowed" },
+ {
+ pattern: /requestAnimationFrame\s*\(/,
+ message: "requestAnimationFrame not allowed",
+ },
+];
+
+export function validateCompositionGsap(script: string): ValidationResult {
+ const errors: string[] = [];
+ const warnings: string[] = [];
+
+ for (const { pattern, message } of FORBIDDEN_GSAP_PATTERNS) {
+ if (pattern.test(script)) {
+ errors.push(message);
+ }
+ }
+
+ if (/yoyo\s*:\s*true/.test(script)) {
+ warnings.push("yoyo animations may behave unexpectedly when scrubbing");
+ }
+
+ if (/stagger\s*:/.test(script)) {
+ warnings.push("stagger animations may not serialize correctly");
+ }
+
+ return {
+ valid: errors.length === 0,
+ errors,
+ warnings,
+ };
+}
+
+export function keyframesToGsapAnimations(
+ elementId: string,
+ keyframes: Keyframe[],
+ elementStartTime: number,
+ base?: { x?: number; y?: number; scale?: number },
+): GsapAnimation[] {
+ const sorted = [...keyframes].sort((a, b) => a.time - b.time);
+ const animations: GsapAnimation[] = [];
+ const baseX = base?.x ?? 0;
+ const baseY = base?.y ?? 0;
+ const baseScale = base?.scale ?? 1;
+
+ sorted.forEach((kf, i) => {
+ const absoluteTime = elementStartTime + kf.time;
+ const isFirst = i === 0;
+
+ const prevKf = i > 0 ? sorted[i - 1] : null;
+ const duration = prevKf ? kf.time - prevKf.time : undefined;
+ const position = prevKf ? elementStartTime + prevKf.time : absoluteTime;
+
+ const properties: Record<string, number | string> = {};
+ for (const [key, value] of Object.entries(kf.properties)) {
+ if (typeof value !== "number") continue;
+ if (key === "x") properties.x = baseX + value;
+ else if (key === "y") properties.y = baseY + value;
+ else if (key === "scale") properties.scale = baseScale * value;
+ else properties[key] = value;
+ }
+
+ animations.push({
+ id: `${elementId}-kf-${kf.id}`,
+ targetSelector: `#${elementId}`,
+ method: isFirst ? "set" : "to",
+ position,
+ properties,
+ duration: isFirst ? undefined : duration,
+ ease: kf.ease,
+ });
+ });
+
+ return animations;
+}
+
+export function gsapAnimationsToKeyframes(
+ animations: GsapAnimation[],
+ elementStartTime: number,
+ options?: {
+ baseX?: number;
+ baseY?: number;
+ baseScale?: number;
+ clampTimeToZero?: boolean;
+ skipBaseSet?: boolean;
+ },
+): Keyframe[] {
+ const validMethods: GsapMethod[] = ["set", "to", "from", "fromTo"];
+ const baseX = options?.baseX ?? 0;
+ const baseY = options?.baseY ?? 0;
+ const baseScale = options?.baseScale ?? 1;
+ const clampTimeToZero = options?.clampTimeToZero ?? true;
+ const skipBaseSet = options?.skipBaseSet ?? false;
+ const baseTimeEpsilon = 0.001;
+ const baseValueEpsilon = 0.00001;
+
+ return animations
+ .filter((a) => validMethods.includes(a.method))
+ .map((a) => {
+ const relativeTimeRaw = a.position - elementStartTime;
+ const time = clampTimeToZero ? Math.max(0, relativeTimeRaw) : relativeTimeRaw;
+
+ const properties: Partial<KeyframeProperties> = {};
+
+ for (const [key, value] of Object.entries(a.properties)) {
+ if (SUPPORTED_PROPS.includes(key) && typeof value === "number") {
+ if (key === "x") {
+ (properties as Record<string, number>).x = value - baseX;
+ } else if (key === "y") {
+ (properties as Record<string, number>).y = value - baseY;
+ } else if (key === "scale") {
+ (properties as Record<string, number>).scale = baseScale !== 0 ? value / baseScale : value;
+ } else {
+ (properties as Record<string, number>)[key] = value;
+ }
+ }
+ }
+
+ if (skipBaseSet && a.method === "set" && Math.abs(time) <= baseTimeEpsilon) {
+ const propKeys = Object.keys(properties);
+ const isOnlyBaseProps = propKeys.every((k) => k === "x" || k === "y" || k === "scale");
+ if (isOnlyBaseProps && propKeys.length > 0) {
+ const hasNonBaseOffset =
+ (properties.x !== undefined && Math.abs(properties.x) > baseValueEpsilon) ||
+ (properties.y !== undefined && Math.abs(properties.y) > baseValueEpsilon) ||
+ (properties.scale !== undefined && Math.abs(properties.scale - 1) > baseValueEpsilon);
+ if (!hasNonBaseOffset) {
+ return null;
+ }
+ }
+ }
+
+ const kf: Keyframe = { id: a.id, time, properties };
+ if (a.ease !== undefined) kf.ease = a.ease;
+ return kf;
+ })
+ .filter((kf): kf is Keyframe => kf !== null)
+ .sort((a, b) => a.time - b.time);
+}
diff --git a/packages/core/src/parsers/htmlParser.test.ts b/packages/core/src/parsers/htmlParser.test.ts
new file mode 100644
index 0000000000..8be4dc2ad0
--- /dev/null
+++ b/packages/core/src/parsers/htmlParser.test.ts
@@ -0,0 +1,525 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { describe, it, expect } from "vitest";
+import { parseHtml, updateElementInHtml, addElementToHtml, removeElementFromHtml, validateCompositionHtml, extractCompositionMetadata } from "./htmlParser.js";
+
+describe("parseHtml", () => {
+ it("extracts elements with data-start and data-end", () => {
+ const html = `
+ <html>
+ <body>
+ <div id="stage">
+ <div id="text1" data-start="0" data-end="5" data-name="Title"><div>Hello World</div></div>
+ <div id="text2" data-start="2" data-end="7" data-name="Subtitle"><div>Sub</div></div>
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ expect(result.elements).toHaveLength(2);
+ expect(result.elements[0].id).toBe("text1");
+ expect(result.elements[0].startTime).toBe(0);
+ expect(result.elements[0].duration).toBe(5);
+ expect(result.elements[0].name).toBe("Title");
+ expect(result.elements[0].type).toBe("text");
+
+ expect(result.elements[1].id).toBe("text2");
+ expect(result.elements[1].startTime).toBe(2);
+ expect(result.elements[1].duration).toBe(5);
+ });
+
+ it("handles nested compositions", () => {
+ const html = `
+ <html>
+ <body>
+ <div id="stage">
+ <div id="comp1" data-start="0" data-end="10" data-type="composition" data-composition-id="abc123">
+ <iframe src="/compositions/abc123"></iframe>
+ </div>
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ expect(result.elements).toHaveLength(1);
+ expect(result.elements[0].type).toBe("composition");
+ expect(result.elements[0].id).toBe("comp1");
+ if (result.elements[0].type === "composition") {
+ expect(result.elements[0].compositionId).toBe("abc123");
+ expect(result.elements[0].src).toBe("/compositions/abc123");
+ }
+ });
+
+ it("extracts media elements (video, audio, img)", () => {
+ const html = `
+ <html>
+ <body>
+ <div id="stage">
+ <video id="vid1" data-start="0" data-end="10" src="video.mp4" data-name="My Video"></video>
+ <audio id="aud1" data-start="0" data-end="5" src="music.mp3" data-name="Music"></audio>
+ <img id="img1" data-start="2" data-end="8" src="photo.jpg" data-name="Photo" />
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ expect(result.elements).toHaveLength(3);
+
+ const video = result.elements.find((e) => e.id === "vid1");
+ expect(video).toBeDefined();
+ expect(video?.type).toBe("video");
+ if (video?.type === "video") {
+ expect(video.src).toBe("video.mp4");
+ }
+
+ const audio = result.elements.find((e) => e.id === "aud1");
+ expect(audio).toBeDefined();
+ expect(audio?.type).toBe("audio");
+
+ const img = result.elements.find((e) => e.id === "img1");
+ expect(img).toBeDefined();
+ expect(img?.type).toBe("image");
+ });
+
+ it("handles missing attributes gracefully", () => {
+ const html = `
+ <html>
+ <body>
+ <div id="stage">
+ <div id="el1" data-start="3"><div>Some text</div></div>
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ expect(result.elements).toHaveLength(1);
+ expect(result.elements[0].startTime).toBe(3);
+ // Default duration is 5 when data-end is missing
+ expect(result.elements[0].duration).toBe(5);
+ });
+
+ it("assigns generated ids when elements have no id", () => {
+ const html = `
+ <html>
+ <body>
+ <div id="stage">
+ <div data-start="0" data-end="5"><div>No ID</div></div>
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ expect(result.elements).toHaveLength(1);
+ expect(result.elements[0].id).toMatch(/^element-\d+$/);
+ });
+
+ it("extracts GSAP script from script tags", () => {
+ const html = `
+ <html>
+ <body>
+ <div id="stage">
+ <div id="text1" data-start="0" data-end="5"><div>Hello</div></div>
+ </div>
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
+ <script>
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#text1", { opacity: 1, duration: 1 }, 0);
+ </script>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ expect(result.gsapScript).not.toBeNull();
+ expect(result.gsapScript).toContain("gsap.timeline");
+ expect(result.gsapScript).toContain('tl.to("#text1"');
+ });
+
+ it("extracts styles from style tags", () => {
+ const html = `
+ <html>
+ <body>
+ <style data-hf-custom="true">
+ .my-class { color: red; }
+ </style>
+ <div id="stage">
+ <div id="text1" data-start="0" data-end="5"><div>Hello</div></div>
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ expect(result.styles).not.toBeNull();
+ expect(result.styles).toContain(".my-class");
+ });
+
+ it("detects landscape resolution from data attribute", () => {
+ const html = `
+ <html data-resolution="landscape">
+ <body>
+ <div id="stage">
+ <div id="text1" data-start="0" data-end="5"><div>Hello</div></div>
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ expect(result.resolution).toBe("landscape");
+ });
+
+ it("detects portrait resolution from data attribute", () => {
+ const html = `
+ <html data-resolution="portrait">
+ <body>
+ <div id="stage">
+ <div id="text1" data-start="0" data-end="5"><div>Hello</div></div>
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ expect(result.resolution).toBe("portrait");
+ });
+
+ it("defaults to portrait when no resolution info is available", () => {
+ const html = `
+ <html>
+ <body>
+ <div id="stage">
+ <div id="text1" data-start="0" data-end="5"><div>Hello</div></div>
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ expect(result.resolution).toBe("portrait");
+ });
+
+ it("extracts x, y, scale, opacity from data attributes", () => {
+ const html = `
+ <html>
+ <body>
+ <div id="stage">
+ <video id="vid1" data-start="0" data-end="5" src="v.mp4" data-x="100" data-y="200" data-scale="1.5" data-opacity="0.8"></video>
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ expect(result.elements[0].x).toBe(100);
+ expect(result.elements[0].y).toBe(200);
+ expect(result.elements[0].scale).toBe(1.5);
+ expect(result.elements[0].opacity).toBe(0.8);
+ });
+
+ it("parses text element properties (color, fontSize, fontWeight, fontFamily)", () => {
+ const html = `
+ <html>
+ <body>
+ <div id="stage">
+ <div id="text1" data-start="0" data-end="5" data-color="red" data-font-size="72" data-font-weight="900" data-font-family="Montserrat"><div>Styled</div></div>
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ const textEl = result.elements[0];
+ expect(textEl.type).toBe("text");
+ if (textEl.type === "text") {
+ expect(textEl.color).toBe("red");
+ expect(textEl.fontSize).toBe(72);
+ expect(textEl.fontWeight).toBe(900);
+ expect(textEl.fontFamily).toBe("Montserrat");
+ }
+ });
+
+ it("parses media element properties (mediaStartTime, sourceDuration, volume)", () => {
+ const html = `
+ <html>
+ <body>
+ <div id="stage">
+ <video id="vid1" data-start="0" data-end="10" src="v.mp4" data-media-start="5" data-source-duration="30" data-volume="0.5" data-has-audio="true"></video>
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ const vid = result.elements[0];
+ expect(vid.type).toBe("video");
+ if (vid.type === "video") {
+ expect(vid.mediaStartTime).toBe(5);
+ expect(vid.sourceDuration).toBe(30);
+ expect(vid.volume).toBe(0.5);
+ expect(vid.hasAudio).toBe(true);
+ }
+ });
+
+ it("extracts data-keyframes attribute", () => {
+ const keyframes = JSON.stringify([
+ { id: "kf1", time: 0, properties: { opacity: 0 } },
+ { id: "kf2", time: 1, properties: { opacity: 1 } },
+ ]);
+ const html = `
+ <html>
+ <body>
+ <div id="stage">
+ <div id="text1" data-start="0" data-end="5" data-keyframes='${keyframes}'><div>Hello</div></div>
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ expect(result.keyframes["text1"]).toBeDefined();
+ expect(result.keyframes["text1"]).toHaveLength(2);
+ expect(result.keyframes["text1"][0].id).toBe("kf1");
+ });
+
+ it("parses stage zoom keyframes", () => {
+ const zoomKeyframes = JSON.stringify([
+ { id: "z1", time: 0, zoom: { scale: 1, focusX: 960, focusY: 540 } },
+ { id: "z2", time: 2, zoom: { scale: 2, focusX: 500, focusY: 300 } },
+ ]);
+ const html = `
+ <html>
+ <body>
+ <div id="stage">
+ <div id="stage-zoom-container" data-zoom-keyframes='${zoomKeyframes}'></div>
+ </div>
+ </body>
+ </html>
+ `;
+ const result = parseHtml(html);
+
+ expect(result.stageZoomKeyframes).toHaveLength(2);
+ expect(result.stageZoomKeyframes[0].zoom.scale).toBe(1);
+ expect(result.stageZoomKeyframes[1].zoom.scale).toBe(2);
+ });
+
+ it("returns empty zoom keyframes when no zoom container exists", () => {
+ const html = `
+ <html>
+ <body><div id="stage"></div></body>
+ </html>
+ `;
+ const result = parseHtml(html);
+ expect(result.stageZoomKeyframes).toHaveLength(0);
+ });
+});
+
+describe("updateElementInHtml", () => {
+ it("updates startTime and duration", () => {
+ const html = `<!DOCTYPE html>
+<html><body>
+ <div id="el1" data-start="0" data-end="5"><div>Hello</div></div>
+</body></html>`;
+
+ const updated = updateElementInHtml(html, "el1", { startTime: 2, duration: 3 });
+
+ expect(updated).toContain('data-start="2"');
+ expect(updated).toContain('data-end="5"'); // data-end gets set to start + duration
+ });
+
+ it("updates element name", () => {
+ const html = `<!DOCTYPE html>
+<html><body>
+ <div id="el1" data-start="0" data-end="5" data-name="Old"><div>Hello</div></div>
+</body></html>`;
+
+ const updated = updateElementInHtml(html, "el1", { name: "New Name" });
+
+ expect(updated).toContain('data-name="New Name"');
+ });
+
+ it("returns original html when element not found", () => {
+ const html = `<!DOCTYPE html>
+<html><body>
+ <div id="el1" data-start="0" data-end="5"><div>Hello</div></div>
+</body></html>`;
+
+ const updated = updateElementInHtml(html, "nonexistent", { name: "Test" });
+
+ expect(updated).toBe(html);
+ });
+});
+
+describe("addElementToHtml", () => {
+ it("adds a new text element to the HTML", () => {
+ const html = `<!DOCTYPE html>
+<html><body>
+ <div id="stage">
+ <div id="stage-zoom-container"></div>
+ </div>
+</body></html>`;
+
+ const { html: updated, id } = addElementToHtml(html, {
+ type: "text",
+ name: "New Text",
+ content: "Hello!",
+ startTime: 1,
+ duration: 3,
+ zIndex: 1,
+ });
+
+ expect(id).toBeDefined();
+ expect(updated).toContain(`id="${id}"`);
+ expect(updated).toContain('data-start="1"');
+ expect(updated).toContain('data-end="4"');
+ expect(updated).toContain("Hello!");
+ });
+
+ it("adds a video element", () => {
+ const html = `<!DOCTYPE html>
+<html><body>
+ <div id="stage">
+ <div id="stage-zoom-container"></div>
+ </div>
+</body></html>`;
+
+ const { html: updated, id } = addElementToHtml(html, {
+ type: "video",
+ name: "My Video",
+ src: "video.mp4",
+ startTime: 0,
+ duration: 10,
+ zIndex: 0,
+ });
+
+ expect(updated).toContain(`id="${id}"`);
+ expect(updated).toContain("video.mp4");
+ });
+});
+
+describe("removeElementFromHtml", () => {
+ it("removes an element by id", () => {
+ const html = `<!DOCTYPE html>
+<html><body>
+ <div id="stage">
+ <div id="el1" data-start="0" data-end="5"><div>Hello</div></div>
+ <div id="el2" data-start="1" data-end="6"><div>World</div></div>
+ </div>
+</body></html>`;
+
+ const updated = removeElementFromHtml(html, "el1");
+
+ expect(updated).not.toContain('id="el1"');
+ expect(updated).toContain('id="el2"');
+ });
+});
+
+describe("validateCompositionHtml", () => {
+ it("returns valid for a well-formed composition", () => {
+ const html = `<!DOCTYPE html>
+<html data-composition-id="comp-1" data-composition-duration="10">
+<body>
+ <div id="stage"></div>
+</body>
+</html>`;
+
+ const result = validateCompositionHtml(html);
+ expect(result.valid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it("reports error for missing composition-id", () => {
+ const html = `<!DOCTYPE html>
+<html data-composition-duration="10">
+<body>
+ <div id="stage"></div>
+</body>
+</html>`;
+
+ const result = validateCompositionHtml(html);
+ expect(result.valid).toBe(false);
+ expect(result.errors).toContain("Missing data-composition-id attribute on <html> element");
+ });
+
+ it("reports error for missing composition-duration", () => {
+ const html = `<!DOCTYPE html>
+<html data-composition-id="comp-1">
+<body>
+ <div id="stage"></div>
+</body>
+</html>`;
+
+ const result = validateCompositionHtml(html);
+ expect(result.valid).toBe(false);
+ expect(result.errors).toContain("Missing data-composition-duration attribute on <html> element");
+ });
+
+ it("reports error for missing #stage", () => {
+ const html = `<!DOCTYPE html>
+<html data-composition-id="comp-1" data-composition-duration="10">
+<body></body>
+</html>`;
+
+ const result = validateCompositionHtml(html);
+ expect(result.valid).toBe(false);
+ expect(result.errors).toContain("Missing #stage element");
+ });
+
+ it("reports error for inline event handlers", () => {
+ const html = `<!DOCTYPE html>
+<html data-composition-id="comp-1" data-composition-duration="10">
+<body>
+ <div id="stage" onclick="alert('hi')"></div>
+</body>
+</html>`;
+
+ const result = validateCompositionHtml(html);
+ expect(result.valid).toBe(false);
+ expect(result.errors).toContain("Inline event handlers (onclick, onload, etc.) not allowed");
+ });
+});
+
+describe("extractCompositionMetadata", () => {
+ it("extracts composition id and duration", () => {
+ const html = `<!DOCTYPE html>
+<html data-composition-id="comp-abc" data-composition-duration="15.5">
+<body></body>
+</html>`;
+
+ const meta = extractCompositionMetadata(html);
+ expect(meta.compositionId).toBe("comp-abc");
+ expect(meta.compositionDuration).toBe(15.5);
+ });
+
+ it("returns null for missing metadata", () => {
+ const html = `<!DOCTYPE html><html><body></body></html>`;
+
+ const meta = extractCompositionMetadata(html);
+ expect(meta.compositionId).toBeNull();
+ expect(meta.compositionDuration).toBeNull();
+ });
+
+ it("extracts composition variables", () => {
+ const variables = JSON.stringify([
+ { id: "title", type: "string", label: "Title", default: "Hello" },
+ { id: "count", type: "number", label: "Count", default: 5 },
+ ]);
+ const html = `<!DOCTYPE html>
+<html data-composition-id="comp-1" data-composition-duration="10" data-composition-variables='${variables}'>
+<body></body>
+</html>`;
+
+ const meta = extractCompositionMetadata(html);
+ expect(meta.variables).toHaveLength(2);
+ expect(meta.variables[0].id).toBe("title");
+ expect(meta.variables[0].type).toBe("string");
+ expect(meta.variables[1].id).toBe("count");
+ expect(meta.variables[1].type).toBe("number");
+ });
+});
diff --git a/packages/core/src/parsers/htmlParser.ts b/packages/core/src/parsers/htmlParser.ts
new file mode 100644
index 0000000000..9cd92e4f23
--- /dev/null
+++ b/packages/core/src/parsers/htmlParser.ts
@@ -0,0 +1,843 @@
+import type {
+ TimelineElement,
+ TimelineElementType,
+ TimelineMediaElement,
+ TimelineTextElement,
+ TimelineCompositionElement,
+ CanvasResolution,
+ Keyframe,
+ KeyframeProperties,
+ StageZoomKeyframe,
+ CompositionVariable,
+} from "../core.types";
+import { CANVAS_DIMENSIONS } from "../core.types";
+import {
+ parseGsapScript,
+ validateCompositionGsap,
+ gsapAnimationsToKeyframes,
+ getAnimationsForElement,
+} from "./gsapParser";
+import type { ValidationResult } from "./gsapParser";
+
+const MEDIA_TYPES = new Set<string>(["video", "image", "audio"]);
+
+export interface ParsedHtml {
+ elements: TimelineElement[];
+ gsapScript: string | null;
+ styles: string | null;
+ resolution: CanvasResolution;
+ keyframes: Record<string, Keyframe[]>;
+ stageZoomKeyframes: StageZoomKeyframe[];
+}
+
+function getElementType(el: Element): TimelineElementType | null {
+ const tag = el.tagName.toLowerCase();
+ if (tag === "video") return "video";
+ if (tag === "img") return "image";
+ if (tag === "audio") return "audio";
+ // Check for explicit data-type attribute first
+ const dataType = el.getAttribute("data-type");
+ if (dataType === "composition") return "composition";
+ if (dataType === "text") return "text";
+ // Fall back to tag-based detection for backwards compatibility
+ if (tag === "div" || tag === "p" || tag === "h1" || tag === "h2" || tag === "h3" || tag === "span") {
+ return "text";
+ }
+ return null;
+}
+
+function getElementName(el: Element): string {
+ const dataName = el.getAttribute("data-name");
+ if (dataName) return dataName;
+
+ const type = getElementType(el);
+ if (type === "text") {
+ const text = el.textContent?.trim().slice(0, 30) || "Text";
+ return text.length === 30 ? text + "..." : text;
+ }
+
+ const src = el.getAttribute("src");
+ if (src) {
+ const filename = src.split("/").pop() || src;
+ return filename.split("?")[0] ?? filename;
+ }
+
+ return el.id || el.className?.toString().split(" ")[0] || "Element";
+}
+
+function getZIndex(el: Element): number {
+ const dataLayer = el.getAttribute("data-layer");
+ if (dataLayer) return parseInt(dataLayer, 10) || 0;
+
+ const style = (el as HTMLElement).style?.zIndex;
+ if (style) return parseInt(style, 10) || 0;
+
+ return 0;
+}
+
+function parseResolutionFromCss(doc: Document, cssText: string | null): CanvasResolution {
+ const stage = doc.getElementById("stage") || doc.querySelector("#stage");
+ if (stage) {
+ const inlineStyle = (stage as HTMLElement).style;
+ if (inlineStyle?.width && inlineStyle?.height) {
+ const w = parseInt(inlineStyle.width, 10);
+ const h = parseInt(inlineStyle.height, 10);
+ if (w && h) {
+ return w > h ? "landscape" : "portrait";
+ }
+ }
+ }
+
+ if (cssText) {
+ const stageMatch = cssText.match(/#stage\s*\{[^}]*width:\s*(\d+)px[^}]*height:\s*(\d+)px[^}]*\}/);
+ if (stageMatch) {
+ const w = parseInt(stageMatch[1] ?? "", 10);
+ const h = parseInt(stageMatch[2] ?? "", 10);
+ return w > h ? "landscape" : "portrait";
+ }
+ const stageMatchReverse = cssText.match(/#stage\s*\{[^}]*height:\s*(\d+)px[^}]*width:\s*(\d+)px[^}]*\}/);
+ if (stageMatchReverse) {
+ const h = parseInt(stageMatchReverse[1] ?? "", 10);
+ const w = parseInt(stageMatchReverse[2] ?? "", 10);
+ return w > h ? "landscape" : "portrait";
+ }
+ }
+
+ return "portrait";
+}
+
+function parseResolutionFromHtml(doc: Document): CanvasResolution | null {
+ const htmlEl = doc.documentElement;
+ const resolutionAttr = htmlEl.getAttribute("data-resolution");
+ if (resolutionAttr === "landscape" || resolutionAttr === "portrait") {
+ return resolutionAttr;
+ }
+
+ const widthAttr = htmlEl.getAttribute("data-composition-width");
+ const heightAttr = htmlEl.getAttribute("data-composition-height");
+ if (widthAttr && heightAttr) {
+ const width = parseInt(widthAttr, 10);
+ const height = parseInt(heightAttr, 10);
+ if (width && height) {
+ return width > height ? "landscape" : "portrait";
+ }
+ }
+
+ return null;
+}
+
+export function parseHtml(html: string): ParsedHtml {
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, "text/html");
+
+ const elements: TimelineElement[] = [];
+ const keyframes: Record<string, Keyframe[]> = {};
+ let idCounter = 0;
+
+ const htmlEl = doc.documentElement;
+ const customStylesAttr = htmlEl.getAttribute("data-custom-styles");
+ let customStyles: string | null = null;
+ if (customStylesAttr) {
+ try {
+ customStyles = JSON.parse(customStylesAttr);
+ } catch {
+ customStyles = customStylesAttr;
+ }
+ }
+
+ const timedElements = doc.querySelectorAll("[data-start]");
+
+ timedElements.forEach((el) => {
+ const type = getElementType(el);
+ if (!type) return;
+
+ const start = parseFloat(el.getAttribute("data-start") || "0");
+ const dataEnd = el.getAttribute("data-end");
+
+ let duration: number;
+ if (dataEnd) {
+ duration = Math.max(0, parseFloat(dataEnd) - start);
+ } else {
+ duration = 5;
+ }
+
+ const id = el.id || `element-${++idCounter}`;
+ const name = getElementName(el);
+ const zIndex = getZIndex(el);
+
+ // Parse data-keyframes attribute if present
+ const keyframesAttr = el.getAttribute("data-keyframes");
+ if (keyframesAttr) {
+ try {
+ const parsedKeyframes = JSON.parse(keyframesAttr);
+ if (Array.isArray(parsedKeyframes) && parsedKeyframes.length > 0) {
+ keyframes[id] = parsedKeyframes;
+ }
+ } catch {
+ // skip invalid keyframes
+ }
+ }
+
+ // Parse transform properties (x, y, scale, opacity)
+ const xAttr = el.getAttribute("data-x");
+ const yAttr = el.getAttribute("data-y");
+ const scaleAttr = el.getAttribute("data-scale");
+ const opacityAttr = el.getAttribute("data-opacity");
+ const x = xAttr ? parseFloat(xAttr) : undefined;
+ const y = yAttr ? parseFloat(yAttr) : undefined;
+ const scale = scaleAttr ? parseFloat(scaleAttr) : undefined;
+ const opacity = opacityAttr ? parseFloat(opacityAttr) : undefined;
+
+ if (type === "text") {
+ const textEl = el.firstElementChild;
+ const content = textEl?.textContent || name;
+ const color = el.getAttribute("data-color") || undefined;
+ const fontSizeAttr = el.getAttribute("data-font-size");
+ const fontSize = fontSizeAttr ? parseInt(fontSizeAttr, 10) : undefined;
+ const fontWeightAttr = el.getAttribute("data-font-weight");
+ const fontWeight = fontWeightAttr ? parseInt(fontWeightAttr, 10) : undefined;
+ const fontFamily = el.getAttribute("data-font-family") || undefined;
+ const textShadowAttr = el.getAttribute("data-text-shadow");
+ const textShadow = textShadowAttr === "false" ? false : undefined;
+
+ // Parse outline properties
+ const textOutlineAttr = el.getAttribute("data-text-outline");
+ const textOutline = textOutlineAttr === "true" ? true : undefined;
+ const textOutlineColor = el.getAttribute("data-text-outline-color") || undefined;
+ const textOutlineWidthAttr = el.getAttribute("data-text-outline-width");
+ const textOutlineWidth = textOutlineWidthAttr ? parseInt(textOutlineWidthAttr, 10) : undefined;
+
+ // Parse highlight properties
+ const textHighlightAttr = el.getAttribute("data-text-highlight");
+ const textHighlight = textHighlightAttr === "true" ? true : undefined;
+ const textHighlightColor = el.getAttribute("data-text-highlight-color") || undefined;
+ const textHighlightPaddingAttr = el.getAttribute("data-text-highlight-padding");
+ const textHighlightPadding = textHighlightPaddingAttr ? parseInt(textHighlightPaddingAttr, 10) : undefined;
+ const textHighlightRadiusAttr = el.getAttribute("data-text-highlight-radius");
+ const textHighlightRadius = textHighlightRadiusAttr ? parseInt(textHighlightRadiusAttr, 10) : undefined;
+
+ const textElement: TimelineTextElement = {
+ id,
+ type: "text",
+ name,
+ content,
+ startTime: start,
+ duration,
+ zIndex,
+ x,
+ y,
+ scale,
+ opacity,
+ color,
+ fontSize,
+ fontWeight,
+ fontFamily,
+ textShadow,
+ textOutline,
+ textOutlineColor,
+ textOutlineWidth,
+ textHighlight,
+ textHighlightColor,
+ textHighlightPadding,
+ textHighlightRadius,
+ };
+ elements.push(textElement);
+ } else if (type === "composition") {
+ // Composition is a div container with iframe inside
+ const iframe = el.querySelector("iframe");
+ const src = iframe?.getAttribute("src") || el.getAttribute("src") || "";
+ const compositionId = el.getAttribute("data-composition-id") || "";
+ const sourceDurationAttr = el.getAttribute("data-source-duration");
+ const sourceDuration = sourceDurationAttr ? parseFloat(sourceDurationAttr) : undefined;
+ const sourceWidthAttr = el.getAttribute("data-source-width");
+ const sourceWidth = sourceWidthAttr ? parseInt(sourceWidthAttr, 10) : undefined;
+ const sourceHeightAttr = el.getAttribute("data-source-height");
+ const sourceHeight = sourceHeightAttr ? parseInt(sourceHeightAttr, 10) : undefined;
+
+ // Parse variable values if present
+ const variableValuesAttr = el.getAttribute("data-variable-values");
+ let variableValues: Record<string, string | number | boolean> | undefined;
+ if (variableValuesAttr) {
+ try {
+ variableValues = JSON.parse(variableValuesAttr);
+ } catch {
+ // skip invalid variable values
+ }
+ }
+
+ const compositionElement: TimelineCompositionElement = {
+ id,
+ type: "composition",
+ name,
+ src,
+ compositionId,
+ startTime: start,
+ duration,
+ zIndex,
+ x,
+ y,
+ scale,
+ opacity,
+ sourceDuration,
+ sourceWidth,
+ sourceHeight,
+ variableValues,
+ };
+ elements.push(compositionElement);
+ } else {
+ if (!MEDIA_TYPES.has(type)) return;
+
+ const src = el.getAttribute("src") || "";
+ const mediaStartTimeAttr = el.getAttribute("data-media-start");
+ const mediaStartTime = mediaStartTimeAttr ? parseFloat(mediaStartTimeAttr) : undefined;
+ const sourceDurationAttr = el.getAttribute("data-source-duration");
+ const sourceDuration = sourceDurationAttr ? parseFloat(sourceDurationAttr) : undefined;
+ const isArollAttr = el.getAttribute("data-aroll");
+ const isAroll = isArollAttr === "true" ? true : undefined;
+ const volumeAttr = el.getAttribute("data-volume");
+ const volume = volumeAttr ? parseFloat(volumeAttr) : undefined;
+ const hasAudioAttr = el.getAttribute("data-has-audio");
+ const hasAudio = hasAudioAttr === "true" ? true : undefined;
+
+ const mediaElement: TimelineMediaElement = {
+ id,
+ type: type as "video" | "image" | "audio",
+ name,
+ src,
+ startTime: start,
+ duration,
+ zIndex,
+ x,
+ y,
+ scale,
+ opacity,
+ mediaStartTime,
+ sourceDuration,
+ isAroll,
+ volume,
+ hasAudio,
+ };
+ elements.push(mediaElement);
+ }
+ });
+
+ const scriptTags = doc.querySelectorAll("script");
+ let gsapScript: string | null = null;
+
+ for (const script of scriptTags) {
+ const src = script.getAttribute("src");
+ if (src && src.includes("gsap")) continue;
+
+ const content = script.textContent?.trim();
+ if (content && (content.includes("gsap") || content.includes("timeline"))) {
+ gsapScript = content;
+ break;
+ }
+ }
+
+ // Extract x/y positions and scale from GSAP script
+ if (gsapScript) {
+ const positionMap = extractPositionsFromGsap(gsapScript);
+ for (const element of elements) {
+ const pos = positionMap.get(element.id);
+ if (pos) {
+ if (pos.x !== undefined) element.x = pos.x;
+ if (pos.y !== undefined) element.y = pos.y;
+ if (
+ pos.scale !== undefined &&
+ (element.type === "video" || element.type === "image" || element.type === "composition")
+ ) {
+ (element as TimelineMediaElement | TimelineCompositionElement).scale = pos.scale;
+ }
+ }
+ }
+ }
+
+ // Normalize keyframes (clamp negative time, convert absolute -> relative if detected)
+ for (const element of elements) {
+ const elementKeyframes = keyframes[element.id];
+ if (!elementKeyframes || elementKeyframes.length === 0) continue;
+
+ const baseX = element.x ?? 0;
+ const baseY = element.y ?? 0;
+ const baseScale =
+ element.type === "video" || element.type === "image" || element.type === "composition"
+ ? ((element as TimelineMediaElement | TimelineCompositionElement).scale ?? 1)
+ : 1;
+
+ keyframes[element.id] = normalizeKeyframes(elementKeyframes, baseX, baseY, baseScale);
+ }
+
+ const styleTags = doc.querySelectorAll("style");
+ const allStyles =
+ Array.from(styleTags)
+ .map((s) => s.textContent?.trim())
+ .filter(Boolean)
+ .join("\n\n") || null;
+
+ const customStyleTags = Array.from(styleTags).filter((s) => s.getAttribute("data-hf-custom") === "true");
+ const customStylesFromTags =
+ customStyleTags
+ .map((s) => s.textContent?.trim())
+ .filter(Boolean)
+ .join("\n\n") || null;
+
+ const styles = customStyles ?? customStylesFromTags ?? null;
+
+ const resolution = parseResolutionFromHtml(doc) ?? parseResolutionFromCss(doc, allStyles);
+
+ // Extract keyframes from GSAP animations for elements that don't have data-keyframes
+ if (gsapScript) {
+ const parsed = parseGsapScript(gsapScript);
+ for (const element of elements) {
+ // Only extract from GSAP if we don't have explicit data-keyframes
+ if (keyframes[element.id]) continue;
+
+ const elementAnimations = getAnimationsForElement(parsed.animations, element.id);
+ if (elementAnimations.length > 0) {
+ const elementKeyframes = gsapAnimationsToKeyframes(elementAnimations, element.startTime, {
+ baseX: element.x ?? 0,
+ baseY: element.y ?? 0,
+ baseScale:
+ element.type === "video" || element.type === "image" || element.type === "composition"
+ ? ((element as TimelineMediaElement | TimelineCompositionElement).scale ?? 1)
+ : 1,
+ clampTimeToZero: true,
+ skipBaseSet: true,
+ });
+ if (elementKeyframes.length > 0) {
+ keyframes[element.id] = elementKeyframes;
+ }
+ }
+ }
+ }
+
+ // Parse stage zoom keyframes from zoom container
+ const stageZoomKeyframes = parseStageZoomKeyframes(doc);
+
+ return {
+ elements,
+ gsapScript,
+ styles,
+ resolution,
+ keyframes,
+ stageZoomKeyframes,
+ };
+}
+
+function parseStageZoomKeyframes(doc: Document): StageZoomKeyframe[] {
+ const zoomContainer = doc.getElementById("stage-zoom-container");
+ if (!zoomContainer) {
+ return [];
+ }
+
+ const zoomKeyframesAttr = zoomContainer.getAttribute("data-zoom-keyframes");
+ if (!zoomKeyframesAttr) {
+ return [];
+ }
+
+ try {
+ const parsed = JSON.parse(zoomKeyframesAttr);
+ if (Array.isArray(parsed)) {
+ return parsed.filter(
+ (kf): kf is StageZoomKeyframe =>
+ typeof kf === "object" &&
+ kf !== null &&
+ typeof kf.id === "string" &&
+ typeof kf.time === "number" &&
+ typeof kf.zoom === "object" &&
+ kf.zoom !== null &&
+ typeof kf.zoom.scale === "number" &&
+ typeof kf.zoom.focusX === "number" &&
+ typeof kf.zoom.focusY === "number",
+ );
+ }
+ } catch {
+ // skip invalid zoom keyframes
+ }
+
+ return [];
+}
+
+/**
+ * Extract x/y positions and scale from GSAP set() calls at position 0
+ * Returns a map of elementId -> { x, y, scale }
+ */
+function extractPositionsFromGsap(script: string): Map<string, { x?: number; y?: number; scale?: number }> {
+ const positionMap = new Map<string, { x?: number; y?: number; scale?: number }>();
+
+ try {
+ const parsed = parseGsapScript(script);
+
+ // Look for set() calls at position 0 with x/y/scale properties
+ for (const anim of parsed.animations) {
+ if (anim.method === "set" && anim.position === 0) {
+ // Extract element ID from selector (e.g., "#element-1" -> "element-1")
+ const selectorMatch = anim.targetSelector.match(/^#(.+)$/);
+ if (!selectorMatch) continue;
+
+ const elementId = selectorMatch[1] ?? "";
+ const x = typeof anim.properties.x === "number" ? anim.properties.x : undefined;
+ const y = typeof anim.properties.y === "number" ? anim.properties.y : undefined;
+ const scale = typeof anim.properties.scale === "number" ? anim.properties.scale : undefined;
+
+ // Only add to map if x, y, or scale is defined and non-default
+ if ((x !== undefined && x !== 0) || (y !== undefined && y !== 0) || (scale !== undefined && scale !== 1)) {
+ const existing = positionMap.get(elementId) || {};
+ positionMap.set(elementId, {
+ x: x !== undefined ? x : existing.x,
+ y: y !== undefined ? y : existing.y,
+ scale: scale !== undefined ? scale : existing.scale,
+ });
+ }
+ }
+ }
+ } catch {
+ // skip GSAP position parsing failure
+ }
+
+ return positionMap;
+}
+
+function normalizeKeyframes(keyframes: Keyframe[], baseX: number, baseY: number, baseScale: number): Keyframe[] {
+ const timeEpsilon = 0.001;
+ const valueEpsilon = 0.00001;
+
+ const hasBaseCheck = (value: number | undefined, base: number): boolean =>
+ value !== undefined && Math.abs(value - base) <= valueEpsilon && Math.abs(base) > valueEpsilon;
+
+ const timeZeroKeyframes = keyframes.filter((kf) => Math.abs(kf.time) <= timeEpsilon);
+
+ const treatAsAbsolute = timeZeroKeyframes.some((kf) => {
+ const props = kf.properties || {};
+ if (
+ hasBaseCheck(props.x, baseX) ||
+ hasBaseCheck(props.y, baseY) ||
+ (baseScale !== 1 && hasBaseCheck(props.scale, baseScale))
+ ) {
+ return true;
+ }
+ return false;
+ });
+
+ return keyframes.map((kf) => {
+ const normalizedProps: Partial<KeyframeProperties> = {};
+ for (const [key, value] of Object.entries(kf.properties || {})) {
+ if (typeof value !== "number") continue;
+ if (treatAsAbsolute && key === "x") {
+ normalizedProps.x = value - baseX;
+ } else if (treatAsAbsolute && key === "y") {
+ normalizedProps.y = value - baseY;
+ } else if (treatAsAbsolute && key === "scale") {
+ normalizedProps.scale = baseScale !== 0 ? value / baseScale : value;
+ } else {
+ (normalizedProps as Record<string, number>)[key] = value;
+ }
+ }
+
+ return {
+ ...kf,
+ time: Math.max(0, kf.time),
+ properties: normalizedProps,
+ };
+ });
+}
+
+export function updateElementInHtml(html: string, elementId: string, updates: Partial<TimelineElement>): string {
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, "text/html");
+
+ const el = doc.getElementById(elementId) || doc.querySelector(`[data-name="${elementId}"]`);
+ if (!el) return html;
+
+ if (updates.startTime !== undefined) {
+ el.setAttribute("data-start", String(updates.startTime));
+ if (el.hasAttribute("data-end") && updates.duration !== undefined) {
+ el.setAttribute("data-end", String(updates.startTime + updates.duration));
+ }
+ }
+
+ if (updates.duration !== undefined) {
+ const start = parseFloat(el.getAttribute("data-start") || "0");
+ el.setAttribute("data-end", String(start + updates.duration));
+ el.removeAttribute("data-duration"); // Clean up legacy
+ }
+
+ if (updates.name !== undefined) {
+ el.setAttribute("data-name", updates.name);
+ }
+
+ if (updates.zIndex !== undefined) {
+ el.setAttribute("data-layer", String(updates.zIndex));
+ }
+
+ // Handle media-specific property
+ if ("src" in updates && updates.src !== undefined) {
+ el.setAttribute("src", updates.src);
+ }
+
+ // Handle text-specific properties
+ if ("content" in updates && updates.content !== undefined) {
+ const textEl = el.firstElementChild;
+ if (textEl) {
+ textEl.textContent = updates.content;
+ }
+ }
+
+ if ("color" in updates && updates.color !== undefined) {
+ el.setAttribute("data-color", updates.color);
+ }
+
+ if ("fontSize" in updates && updates.fontSize !== undefined) {
+ el.setAttribute("data-font-size", String(updates.fontSize));
+ }
+
+ if ("textShadow" in updates) {
+ if (updates.textShadow === false) {
+ el.setAttribute("data-text-shadow", "false");
+ } else {
+ el.removeAttribute("data-text-shadow");
+ }
+ }
+
+ // Handle volume property for audio/video
+ if ("volume" in updates) {
+ if (updates.volume !== undefined && updates.volume !== 1) {
+ el.setAttribute("data-volume", String(updates.volume));
+ } else {
+ el.removeAttribute("data-volume");
+ }
+ }
+
+ // Handle hasAudio property for videos
+ if ("hasAudio" in updates) {
+ if (updates.hasAudio === true) {
+ el.setAttribute("data-has-audio", "true");
+ } else {
+ el.removeAttribute("data-has-audio");
+ }
+ }
+
+ return "<!DOCTYPE html>\n" + doc.documentElement.outerHTML;
+}
+
+export function addElementToHtml(
+ html: string,
+ element: Omit<TimelineElement, "id"> & { id?: string },
+): { html: string; id: string } {
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, "text/html");
+
+ // Prefer zoom container, fall back to stage, then container, then body
+ const container =
+ doc.querySelector("#stage-zoom-container") ||
+ doc.querySelector(".container") ||
+ doc.querySelector("#stage") ||
+ doc.body;
+
+ const id = element.id || `element-${Date.now()}`;
+
+ let newEl: Element;
+
+ switch (element.type) {
+ case "video": {
+ const mediaEl = element as TimelineMediaElement;
+ newEl = doc.createElement("video");
+ newEl.setAttribute("muted", "");
+ newEl.setAttribute("playsinline", "");
+ if (mediaEl.src) newEl.setAttribute("src", mediaEl.src);
+ if (mediaEl.volume !== undefined && mediaEl.volume !== 1) {
+ newEl.setAttribute("data-volume", String(mediaEl.volume));
+ }
+ if (mediaEl.hasAudio) {
+ newEl.setAttribute("data-has-audio", "true");
+ }
+ break;
+ }
+ case "image": {
+ const mediaEl = element as TimelineMediaElement;
+ newEl = doc.createElement("img");
+ if (mediaEl.src) newEl.setAttribute("src", mediaEl.src);
+ newEl.setAttribute("alt", element.name);
+ break;
+ }
+ case "audio": {
+ const mediaEl = element as TimelineMediaElement;
+ newEl = doc.createElement("audio");
+ if (mediaEl.src) newEl.setAttribute("src", mediaEl.src);
+ if (mediaEl.volume !== undefined && mediaEl.volume !== 1) {
+ newEl.setAttribute("data-volume", String(mediaEl.volume));
+ }
+ break;
+ }
+ case "text":
+ default: {
+ const textEl = element as TimelineTextElement;
+ newEl = doc.createElement("div");
+ const textContent = doc.createElement("div");
+ textContent.textContent = textEl.content || element.name;
+ newEl.appendChild(textContent);
+ if (textEl.color) {
+ newEl.setAttribute("data-color", textEl.color);
+ }
+ if (textEl.fontSize) {
+ newEl.setAttribute("data-font-size", String(textEl.fontSize));
+ }
+ break;
+ }
+ }
+
+ newEl.id = id;
+ newEl.setAttribute("data-start", String(element.startTime));
+ newEl.setAttribute("data-end", String(element.startTime + element.duration));
+ newEl.setAttribute("data-layer", String(element.zIndex));
+ newEl.setAttribute("data-name", element.name);
+
+ container.appendChild(newEl);
+
+ return {
+ html: "<!DOCTYPE html>\n" + doc.documentElement.outerHTML,
+ id,
+ };
+}
+
+export function removeElementFromHtml(html: string, elementId: string): string {
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, "text/html");
+
+ const el = doc.getElementById(elementId);
+ if (el) {
+ el.remove();
+ }
+
+ return "<!DOCTYPE html>\n" + doc.documentElement.outerHTML;
+}
+
+export interface CompositionMetadata {
+ compositionId: string | null;
+ compositionDuration: number | null;
+ variables: CompositionVariable[];
+}
+
+export function extractCompositionMetadata(html: string): CompositionMetadata {
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, "text/html");
+ const htmlEl = doc.documentElement;
+
+ const compositionId = htmlEl.getAttribute("data-composition-id");
+ const durationStr = htmlEl.getAttribute("data-composition-duration");
+ const compositionDuration = durationStr ? parseFloat(durationStr) : null;
+
+ const variables = parseCompositionVariables(htmlEl);
+
+ return {
+ compositionId,
+ compositionDuration: compositionDuration && isFinite(compositionDuration) ? compositionDuration : null,
+ variables,
+ };
+}
+
+function parseCompositionVariables(htmlEl: Element): CompositionVariable[] {
+ const variablesAttr = htmlEl.getAttribute("data-composition-variables");
+ if (!variablesAttr) {
+ return [];
+ }
+
+ try {
+ const parsed = JSON.parse(variablesAttr);
+ if (!Array.isArray(parsed)) {
+ return [];
+ }
+
+ return parsed.filter((v): v is CompositionVariable => {
+ if (typeof v !== "object" || v === null) return false;
+ if (typeof v.id !== "string" || typeof v.label !== "string") return false;
+ if (!["string", "number", "color", "boolean", "enum"].includes(v.type)) return false;
+
+ switch (v.type) {
+ case "string":
+ return typeof v.default === "string";
+ case "number":
+ return typeof v.default === "number";
+ case "color":
+ return typeof v.default === "string";
+ case "boolean":
+ return typeof v.default === "boolean";
+ case "enum":
+ return typeof v.default === "string" && Array.isArray(v.options);
+ default:
+ return false;
+ }
+ });
+ } catch {
+ return [];
+ }
+}
+
+export function validateCompositionHtml(html: string): ValidationResult {
+ const errors: string[] = [];
+ const warnings: string[] = [];
+
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, "text/html");
+ const htmlEl = doc.documentElement;
+
+ const compositionId = htmlEl.getAttribute("data-composition-id");
+ if (!compositionId) {
+ errors.push("Missing data-composition-id attribute on <html> element");
+ }
+
+ const durationStr = htmlEl.getAttribute("data-composition-duration");
+ if (!durationStr) {
+ errors.push("Missing data-composition-duration attribute on <html> element");
+ } else {
+ const duration = parseFloat(durationStr);
+ if (!isFinite(duration) || duration <= 0) {
+ errors.push("data-composition-duration must be a positive finite number");
+ }
+ }
+
+ const stage = doc.getElementById("stage");
+ if (!stage) {
+ errors.push("Missing #stage element");
+ }
+
+ if (/\son\w+\s*=/i.test(html)) {
+ errors.push("Inline event handlers (onclick, onload, etc.) not allowed");
+ }
+
+ if (/javascript\s*:/i.test(html)) {
+ errors.push("javascript: URLs not allowed");
+ }
+
+ const scripts = doc.querySelectorAll("script");
+ if (scripts.length > 2) {
+ warnings.push("Multiple script tags detected - only GSAP CDN and main script expected");
+ }
+
+ const gsapScript = extractGsapScript(doc);
+ if (gsapScript) {
+ const gsapValidation = validateCompositionGsap(gsapScript);
+ errors.push(...gsapValidation.errors);
+ warnings.push(...gsapValidation.warnings);
+ }
+
+ return {
+ valid: errors.length === 0,
+ errors,
+ warnings,
+ };
+}
+
+function extractGsapScript(doc: Document): string | null {
+ const scripts = doc.querySelectorAll("script");
+ for (const script of scripts) {
+ const content = script.textContent || "";
+ if (content.includes("gsap.timeline") || content.includes(".set(") || content.includes(".to(")) {
+ return content;
+ }
+ }
+ return null;
+}
+
+export { CANVAS_DIMENSIONS };
diff --git a/packages/core/src/runtime/README.md b/packages/core/src/runtime/README.md
new file mode 100644
index 0000000000..50474311de
--- /dev/null
+++ b/packages/core/src/runtime/README.md
@@ -0,0 +1,58 @@
+# Hyperframe Runtime Engine
+
+This folder owns the runtime that powers preview and producer parity.
+
+## Current Direction
+
+- Runtime source of truth is converging on `hyperframe.ts`.
+- Build produces:
+ - `dist/hyperframe.runtime.iife.js` (browser bootstrap)
+ - `dist/hyperframe.runtime.mjs` (tooling/tests)
+ - `dist/hyperframe.manifest.json` (version + sha256 + artifact map)
+- FE owns iframe runtime injection.
+- BE persists raw generated HTML without injecting runtime scripts.
+- Producer validates pinned runtime checksum from manifest before render.
+
+## Runtime Contract (Stable Surface)
+
+Globals:
+
+- `window.__player`
+- `window.__playerReady`
+- `window.__renderReady`
+- `window.__timelines`
+- `window.__clipManifest`
+
+postMessage:
+
+- parent -> runtime control:
+ - `source: "hf-parent"`
+ - `type: "control"`
+ - actions: `play`, `pause`, `seek`, `set-muted`, `set-playback-rate`, `enable-pick-mode`, `disable-pick-mode`
+- runtime -> parent events:
+ - `source: "hf-preview"`
+ - `type: "state"` and `type: "timeline"`
+
+Determinism baseline:
+
+- `renderSeek` is the producer-canonical seek path.
+- 30fps quantization and readiness gates are correctness requirements.
+
+## Build
+
+```bash
+pnpm -C core build:hyperframes-runtime
+```
+
+## Security Expectations
+
+- Runtime bootstrap URL must be version-pinned and host-allowlisted.
+- Iframe bridge payloads must be schema-validated.
+- Unsafe URL schemes (`javascript:` and unapproved `data:`) are rejected.
+- Fail closed if runtime bootstrap/handshake is not healthy.
+
+## Product Editing Model
+
+- Primary mode: prompt + element picking.
+- Secondary mode: manual precision controls.
+- Avoid timeline-first manual workflows as default product path.
diff --git a/packages/core/src/runtime/adapters/css.test.ts b/packages/core/src/runtime/adapters/css.test.ts
new file mode 100644
index 0000000000..c4611c3460
--- /dev/null
+++ b/packages/core/src/runtime/adapters/css.test.ts
@@ -0,0 +1,99 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { createCssAdapter } from "./css";
+
+describe("css adapter", () => {
+ it("has correct name", () => {
+ expect(createCssAdapter().name).toBe("css");
+ });
+
+ it("discover finds elements with CSS animations", () => {
+ const el = document.createElement("div");
+ el.style.animationName = "fadeIn";
+ el.style.animationDuration = "1s";
+ document.body.appendChild(el);
+
+ const adapter = createCssAdapter();
+ adapter.discover();
+ // discover doesn't crash — that's the main assertion
+ document.body.removeChild(el);
+ });
+
+ it("seek sets animationDelay and pauses", () => {
+ const el = document.createElement("div");
+ el.setAttribute("data-start", "1");
+ el.style.animationName = "slide";
+ el.style.animationDuration = "2s";
+ document.body.appendChild(el);
+
+ // We need to mock getComputedStyle since jsdom doesn't compute animations
+ const origGetComputedStyle = window.getComputedStyle;
+ vi.spyOn(window, "getComputedStyle").mockImplementation((target) => {
+ const real = origGetComputedStyle(target);
+ return {
+ ...real,
+ animationName: target === el ? "slide" : "none",
+ } as CSSStyleDeclaration;
+ });
+
+ const adapter = createCssAdapter();
+ adapter.discover();
+ adapter.seek({ time: 3 });
+
+ expect(el.style.animationPlayState).toBe("paused");
+ // localTime = max(0, 3 - 1) = 2
+ expect(el.style.animationDelay).toBe("-2s");
+
+ document.body.removeChild(el);
+ vi.restoreAllMocks();
+ });
+
+ it("seek uses resolveStartSeconds when provided", () => {
+ const el = document.createElement("div");
+ el.style.animationName = "bounce";
+ document.body.appendChild(el);
+
+ vi.spyOn(window, "getComputedStyle").mockImplementation(() => {
+ return { animationName: "bounce" } as CSSStyleDeclaration;
+ });
+
+ const adapter = createCssAdapter({ resolveStartSeconds: () => 2 });
+ adapter.discover();
+ adapter.seek({ time: 5 });
+
+ expect(el.style.animationPlayState).toBe("paused");
+ // localTime = max(0, 5 - 2) = 3
+ expect(el.style.animationDelay).toBe("-3s");
+
+ document.body.removeChild(el);
+ vi.restoreAllMocks();
+ });
+
+ it("pause restores base play state", () => {
+ const el = document.createElement("div");
+ el.style.animationName = "spin";
+ el.style.animationPlayState = "running";
+ document.body.appendChild(el);
+
+ vi.spyOn(window, "getComputedStyle").mockImplementation(() => {
+ return { animationName: "spin" } as CSSStyleDeclaration;
+ });
+
+ const adapter = createCssAdapter();
+ adapter.discover();
+ adapter.seek({ time: 1 });
+ expect(el.style.animationPlayState).toBe("paused");
+
+ adapter.pause();
+ expect(el.style.animationPlayState).toBe("running");
+
+ document.body.removeChild(el);
+ vi.restoreAllMocks();
+ });
+
+ it("revert clears entries", () => {
+ const adapter = createCssAdapter();
+ adapter.revert!();
+ // Should not crash when seeking after revert
+ expect(() => adapter.seek({ time: 1 })).not.toThrow();
+ });
+});
diff --git a/packages/core/src/runtime/adapters/css.ts b/packages/core/src/runtime/adapters/css.ts
new file mode 100644
index 0000000000..944a9fbf5a
--- /dev/null
+++ b/packages/core/src/runtime/adapters/css.ts
@@ -0,0 +1,51 @@
+import type { RuntimeDeterministicAdapter } from "../types";
+
+export function createCssAdapter(params?: {
+ resolveStartSeconds?: (element: Element) => number;
+}): RuntimeDeterministicAdapter {
+ let entries: Array<{
+ el: HTMLElement;
+ baseDelay: string;
+ basePlayState: string;
+ }> = [];
+
+ return {
+ name: "css",
+ discover: () => {
+ entries = [];
+ const all = document.querySelectorAll("*");
+ for (const rawEl of all) {
+ if (!(rawEl instanceof HTMLElement)) continue;
+ const style = window.getComputedStyle(rawEl);
+ if (!style.animationName || style.animationName === "none") continue;
+ entries.push({
+ el: rawEl,
+ baseDelay: rawEl.style.animationDelay || "",
+ basePlayState: rawEl.style.animationPlayState || "",
+ });
+ }
+ },
+ seek: (ctx) => {
+ const time = Number(ctx.time) || 0;
+ for (const entry of entries) {
+ if (!entry.el.isConnected) continue;
+ const start = params?.resolveStartSeconds
+ ? params.resolveStartSeconds(entry.el)
+ : Number.parseFloat(entry.el.getAttribute("data-start") ?? "0") || 0;
+ const localTime = Math.max(0, time - start);
+ entry.el.style.animationPlayState = "paused";
+ entry.el.style.animationDelay = `-${localTime.toFixed(3)}s`;
+ }
+ },
+ pause: () => {
+ for (const entry of entries) {
+ if (!entry.el.isConnected) continue;
+ entry.el.style.animationPlayState = entry.basePlayState || "paused";
+ if (entry.baseDelay) entry.el.style.animationDelay = entry.baseDelay;
+ }
+ },
+ revert: () => {
+ entries = [];
+ },
+ };
+}
diff --git a/packages/core/src/runtime/adapters/gsap.test.ts b/packages/core/src/runtime/adapters/gsap.test.ts
new file mode 100644
index 0000000000..3cd8ab30b2
--- /dev/null
+++ b/packages/core/src/runtime/adapters/gsap.test.ts
@@ -0,0 +1,78 @@
+import { describe, it, expect, vi } from "vitest";
+import { createGsapAdapter } from "./gsap";
+import type { RuntimeTimelineLike } from "../types";
+
+function createMockTimeline(): RuntimeTimelineLike {
+ return {
+ play: vi.fn(),
+ pause: vi.fn(),
+ seek: vi.fn(),
+ totalTime: vi.fn(),
+ time: vi.fn(() => 0),
+ duration: vi.fn(() => 10),
+ add: vi.fn(),
+ paused: vi.fn(),
+ set: vi.fn(),
+ };
+}
+
+describe("gsap adapter", () => {
+ it("has correct name", () => {
+ const adapter = createGsapAdapter({ getTimeline: () => null });
+ expect(adapter.name).toBe("gsap");
+ });
+
+ it("seek uses totalTime when available", () => {
+ const timeline = createMockTimeline();
+ const adapter = createGsapAdapter({ getTimeline: () => timeline });
+ adapter.seek({ time: 5 });
+ expect(timeline.pause).toHaveBeenCalled();
+ expect(timeline.totalTime).toHaveBeenCalledWith(5, false);
+ expect(timeline.seek).not.toHaveBeenCalled();
+ });
+
+ it("seek falls back to .seek() when totalTime is missing", () => {
+ const timeline = createMockTimeline();
+ (timeline as Record<string, unknown>).totalTime = undefined;
+ const adapter = createGsapAdapter({ getTimeline: () => timeline });
+ adapter.seek({ time: 3 });
+ expect(timeline.pause).toHaveBeenCalled();
+ expect(timeline.seek).toHaveBeenCalledWith(3, false);
+ });
+
+ it("seek clamps negative time to 0", () => {
+ const timeline = createMockTimeline();
+ const adapter = createGsapAdapter({ getTimeline: () => timeline });
+ adapter.seek({ time: -5 });
+ expect(timeline.totalTime).toHaveBeenCalledWith(0, false);
+ });
+
+ it("seek handles NaN time", () => {
+ const timeline = createMockTimeline();
+ const adapter = createGsapAdapter({ getTimeline: () => timeline });
+ adapter.seek({ time: NaN });
+ expect(timeline.totalTime).toHaveBeenCalledWith(0, false);
+ });
+
+ it("seek does nothing without timeline", () => {
+ const adapter = createGsapAdapter({ getTimeline: () => null });
+ expect(() => adapter.seek({ time: 5 })).not.toThrow();
+ });
+
+ it("pause pauses the timeline", () => {
+ const timeline = createMockTimeline();
+ const adapter = createGsapAdapter({ getTimeline: () => timeline });
+ adapter.pause();
+ expect(timeline.pause).toHaveBeenCalled();
+ });
+
+ it("pause does nothing without timeline", () => {
+ const adapter = createGsapAdapter({ getTimeline: () => null });
+ expect(() => adapter.pause()).not.toThrow();
+ });
+
+ it("discover is a no-op", () => {
+ const adapter = createGsapAdapter({ getTimeline: () => null });
+ expect(() => adapter.discover()).not.toThrow();
+ });
+});
diff --git a/packages/core/src/runtime/adapters/gsap.ts b/packages/core/src/runtime/adapters/gsap.ts
new file mode 100644
index 0000000000..b21160f8f5
--- /dev/null
+++ b/packages/core/src/runtime/adapters/gsap.ts
@@ -0,0 +1,28 @@
+import type { RuntimeDeterministicAdapter, RuntimeTimelineLike } from "../types";
+
+type GsapAdapterDeps = {
+ getTimeline: () => RuntimeTimelineLike | null;
+};
+
+export function createGsapAdapter(deps: GsapAdapterDeps): RuntimeDeterministicAdapter {
+ return {
+ name: "gsap",
+ discover: () => {},
+ seek: (ctx) => {
+ const timeline = deps.getTimeline();
+ if (!timeline) return;
+ timeline.pause();
+ const safeTime = Math.max(0, Number(ctx.time) || 0);
+ if (typeof timeline.totalTime === "function") {
+ timeline.totalTime(safeTime, false);
+ } else {
+ timeline.seek(safeTime, false);
+ }
+ },
+ pause: () => {
+ const timeline = deps.getTimeline();
+ if (!timeline) return;
+ timeline.pause();
+ },
+ };
+}
diff --git a/packages/core/src/runtime/adapters/lottie.test.ts b/packages/core/src/runtime/adapters/lottie.test.ts
new file mode 100644
index 0000000000..6c8c12f369
--- /dev/null
+++ b/packages/core/src/runtime/adapters/lottie.test.ts
@@ -0,0 +1,156 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { createLottieAdapter } from "./lottie";
+
+const lottieWindow = window as Window & {
+ lottie?: {
+ loadAnimation: (params: unknown) => unknown;
+ getRegisteredAnimations: () => unknown[];
+ };
+ __hfLottie?: unknown[];
+};
+
+function createLottieWebAnim(opts?: { totalFrames?: number; frameRate?: number }) {
+ return {
+ play: vi.fn(),
+ pause: vi.fn(),
+ stop: vi.fn(),
+ goToAndStop: vi.fn(),
+ goToAndPlay: vi.fn(),
+ totalFrames: opts?.totalFrames ?? 120,
+ frameRate: opts?.frameRate ?? 30,
+ };
+}
+
+function createDotLottiePlayer(opts?: { totalFrames?: number; frameRate?: number; duration?: number }) {
+ return {
+ play: vi.fn(),
+ pause: vi.fn(),
+ totalFrames: opts?.totalFrames ?? 60,
+ frameRate: opts?.frameRate ?? 30,
+ duration: opts?.duration ?? 2,
+ setCurrentRawFrameValue: vi.fn(),
+ seek: vi.fn(),
+ };
+}
+
+describe("lottie adapter", () => {
+ beforeEach(() => {
+ delete lottieWindow.lottie;
+ delete lottieWindow.__hfLottie;
+ });
+
+ afterEach(() => {
+ delete lottieWindow.lottie;
+ delete lottieWindow.__hfLottie;
+ });
+
+ it("has correct name", () => {
+ expect(createLottieAdapter().name).toBe("lottie");
+ });
+
+ describe("discover", () => {
+ it("auto-discovers lottie-web animations", () => {
+ const anim = createLottieWebAnim();
+ lottieWindow.lottie = {
+ loadAnimation: vi.fn(),
+ getRegisteredAnimations: () => [anim],
+ };
+ lottieWindow.__hfLottie = [];
+ const adapter = createLottieAdapter();
+ adapter.discover();
+ expect(lottieWindow.__hfLottie).toContain(anim);
+ });
+
+ it("does not duplicate existing animations", () => {
+ const anim = createLottieWebAnim();
+ lottieWindow.lottie = {
+ loadAnimation: vi.fn(),
+ getRegisteredAnimations: () => [anim],
+ };
+ lottieWindow.__hfLottie = [anim];
+ const adapter = createLottieAdapter();
+ adapter.discover();
+ expect(lottieWindow.__hfLottie).toHaveLength(1);
+ });
+
+ it("handles no global lottie", () => {
+ const adapter = createLottieAdapter();
+ expect(() => adapter.discover()).not.toThrow();
+ });
+ });
+
+ describe("seek", () => {
+ it("seeks lottie-web with goToAndStop in ms", () => {
+ const anim = createLottieWebAnim();
+ lottieWindow.__hfLottie = [anim];
+ const adapter = createLottieAdapter();
+ adapter.seek({ time: 2 });
+ expect(anim.goToAndStop).toHaveBeenCalledWith(2000, false);
+ });
+
+ it("seeks dotlottie-web v2 with setCurrentRawFrameValue", () => {
+ const player = createDotLottiePlayer({ totalFrames: 60, frameRate: 30 });
+ lottieWindow.__hfLottie = [player];
+ const adapter = createLottieAdapter();
+ adapter.seek({ time: 1 });
+ // frame = time * fps = 1 * 30 = 30
+ expect(player.setCurrentRawFrameValue).toHaveBeenCalledWith(30);
+ });
+
+ it("clamps frame to totalFrames - 1", () => {
+ const player = createDotLottiePlayer({ totalFrames: 60, frameRate: 30 });
+ lottieWindow.__hfLottie = [player];
+ const adapter = createLottieAdapter();
+ adapter.seek({ time: 10 }); // frame = 300, but totalFrames = 60
+ expect(player.setCurrentRawFrameValue).toHaveBeenCalledWith(59);
+ });
+
+ it("does nothing with no instances", () => {
+ const adapter = createLottieAdapter();
+ expect(() => adapter.seek({ time: 1 })).not.toThrow();
+ });
+
+ it("clamps negative time to 0", () => {
+ const anim = createLottieWebAnim();
+ lottieWindow.__hfLottie = [anim];
+ const adapter = createLottieAdapter();
+ adapter.seek({ time: -5 });
+ expect(anim.goToAndStop).toHaveBeenCalledWith(0, false);
+ });
+ });
+
+ describe("pause", () => {
+ it("pauses lottie-web animation", () => {
+ const anim = createLottieWebAnim();
+ lottieWindow.__hfLottie = [anim];
+ const adapter = createLottieAdapter();
+ adapter.pause();
+ expect(anim.pause).toHaveBeenCalled();
+ });
+
+ it("pauses dotlottie player", () => {
+ const player = createDotLottiePlayer();
+ lottieWindow.__hfLottie = [player];
+ const adapter = createLottieAdapter();
+ adapter.pause();
+ expect(player.pause).toHaveBeenCalled();
+ });
+ });
+
+ describe("play", () => {
+ it("plays lottie-web animation", () => {
+ const anim = createLottieWebAnim();
+ lottieWindow.__hfLottie = [anim];
+ const adapter = createLottieAdapter();
+ adapter.play!();
+ expect(anim.play).toHaveBeenCalled();
+ });
+ });
+
+ describe("revert", () => {
+ it("does not throw", () => {
+ const adapter = createLottieAdapter();
+ expect(() => adapter.revert!()).not.toThrow();
+ });
+ });
+});
diff --git a/packages/core/src/runtime/adapters/lottie.ts b/packages/core/src/runtime/adapters/lottie.ts
new file mode 100644
index 0000000000..5870d56d6d
--- /dev/null
+++ b/packages/core/src/runtime/adapters/lottie.ts
@@ -0,0 +1,202 @@
+import type { RuntimeDeterministicAdapter } from "../types";
+
+/**
+ * Lottie adapter for HyperFrames
+ *
+ * Supports lottie-web and @lottiefiles/dotlottie-web.
+ *
+ * ## Usage in a composition
+ *
+ * ### lottie-web (classic):
+ * ```html
+ * <script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.12.2/lottie.min.js"></script>
+ * <div id="anim"></div>
+ * <script>
+ * const anim = lottie.loadAnimation({
+ * container: document.getElementById('anim'),
+ * renderer: 'svg',
+ * loop: false,
+ * autoplay: false,
+ * path: 'animation.json',
+ * });
+ * // Register so the adapter can seek it:
+ * window.__hfLottie = window.__hfLottie || [];
+ * window.__hfLottie.push(anim);
+ * </script>
+ * ```
+ *
+ * ### @lottiefiles/dotlottie-web:
+ * ```html
+ * <script src="https://unpkg.com/@lottiefiles/dotlottie-web"></script>
+ * <canvas id="anim"></canvas>
+ * <script>
+ * const player = new DotLottie({
+ * canvas: document.getElementById('anim'),
+ * src: 'animation.lottie',
+ * autoplay: false,
+ * });
+ * window.__hfLottie = window.__hfLottie || [];
+ * window.__hfLottie.push(player);
+ * </script>
+ * ```
+ *
+ * Multiple animations are supported — all are seeked in sync.
+ *
+ * ## Auto-discovery
+ *
+ * The adapter also attempts to auto-discover Lottie animations registered
+ * via the global `lottie` object, so compositions that call
+ * `lottie.loadAnimation(...)` without manually registering still work.
+ */
+export function createLottieAdapter(): RuntimeDeterministicAdapter {
+ return {
+ name: "lottie",
+
+ discover: () => {
+ // Auto-discover animations registered via the global lottie API.
+ // lottie-web exposes registered animations at lottie.getRegisteredAnimations().
+ try {
+ const lottieGlobal = (window as LottieWindow).lottie;
+ if (lottieGlobal && typeof lottieGlobal.getRegisteredAnimations === "function") {
+ const registered = lottieGlobal.getRegisteredAnimations();
+ if (Array.isArray(registered) && registered.length > 0) {
+ const existing = (window as LottieWindow).__hfLottie ?? [];
+ const existingSet = new Set(existing);
+ for (const anim of registered) {
+ if (!existingSet.has(anim)) {
+ existing.push(anim);
+ }
+ }
+ (window as LottieWindow).__hfLottie = existing;
+ }
+ }
+ } catch {
+ // ignore discovery failures
+ }
+ },
+
+ seek: (ctx) => {
+ const time = Math.max(0, Number(ctx.time) || 0);
+ const instances = (window as LottieWindow).__hfLottie;
+ if (!instances || instances.length === 0) return;
+
+ for (const anim of instances) {
+ try {
+ if (isLottieWebAnimation(anim)) {
+ // lottie-web: AnimationItem
+ // goToAndStop(value, isFrame) — isFrame=true means frame number, false means time in ms
+ // We use isFrame=false and pass time in ms for precision.
+ anim.goToAndStop(time * 1000, false);
+ } else if (isDotLottiePlayer(anim)) {
+ // @lottiefiles/dotlottie-web: DotLottie
+ // .seek(frame) — frame is 0-100 percentage OR frame number depending on version
+ // Newer versions use setFrame(frame) or seek(percentage)
+ if (typeof anim.setCurrentRawFrameValue === "function") {
+ // dotlottie-web v2+: direct frame setter
+ const totalFrames = anim.totalFrames ?? 0;
+ const fps = anim.frameRate ?? 30;
+ const frame = time * fps;
+ if (totalFrames > 0) {
+ anim.setCurrentRawFrameValue(Math.min(frame, totalFrames - 1));
+ }
+ } else if (typeof anim.seek === "function") {
+ // dotlottie-web v1: seek(percentage 0-100)
+ const duration = anim.duration ?? 1;
+ const percentage = Math.min(100, (time / duration) * 100);
+ anim.seek(percentage);
+ }
+ }
+ } catch {
+ // ignore per-animation failures — keep going for other instances
+ }
+ }
+ },
+
+ pause: () => {
+ const instances = (window as LottieWindow).__hfLottie;
+ if (!instances || instances.length === 0) return;
+
+ for (const anim of instances) {
+ try {
+ if (isLottieWebAnimation(anim)) {
+ anim.pause();
+ } else if (isDotLottiePlayer(anim)) {
+ anim.pause();
+ }
+ } catch {
+ // ignore
+ }
+ }
+ },
+
+ play: () => {
+ const instances = (window as LottieWindow).__hfLottie;
+ if (!instances || instances.length === 0) return;
+
+ for (const anim of instances) {
+ try {
+ if (isLottieWebAnimation(anim)) {
+ anim.play();
+ } else if (isDotLottiePlayer(anim)) {
+ anim.play();
+ }
+ } catch {
+ // ignore
+ }
+ }
+ },
+
+ revert: () => {
+ // Don't clear __hfLottie — the animation objects are owned by the composition.
+ // Just let them be garbage collected naturally.
+ },
+ };
+}
+
+// ── Type guards ────────────────────────────────────────────────────────────────
+
+function isLottieWebAnimation(anim: unknown): anim is LottieWebAnimation {
+ return typeof anim === "object" && anim !== null && typeof (anim as LottieWebAnimation).goToAndStop === "function";
+}
+
+function isDotLottiePlayer(anim: unknown): anim is DotLottiePlayer {
+ return (
+ typeof anim === "object" &&
+ anim !== null &&
+ typeof (anim as DotLottiePlayer).pause === "function" &&
+ ("totalFrames" in (anim as object) || "duration" in (anim as object))
+ );
+}
+
+// ── Minimal type shapes (no lottie package dependency) ─────────────────────────
+
+interface LottieWebAnimation {
+ play: () => void;
+ pause: () => void;
+ stop: () => void;
+ goToAndStop: (value: number, isFrame: boolean) => void;
+ goToAndPlay: (value: number, isFrame: boolean) => void;
+ totalFrames: number;
+ frameRate: number;
+}
+
+interface LottieWebGlobal {
+ loadAnimation: (params: unknown) => LottieWebAnimation;
+ getRegisteredAnimations: () => LottieWebAnimation[];
+}
+
+interface DotLottiePlayer {
+ play: () => void;
+ pause: () => void;
+ seek?: (percentage: number) => void;
+ setCurrentRawFrameValue?: (frame: number) => void;
+ totalFrames?: number;
+ frameRate?: number;
+ duration?: number;
+}
+
+interface LottieWindow extends Window {
+ lottie?: LottieWebGlobal;
+ /** Compositions register their Lottie animation instances here for the adapter to seek. */
+ __hfLottie?: Array<LottieWebAnimation | DotLottiePlayer>;
+}
diff --git a/packages/core/src/runtime/adapters/three.test.ts b/packages/core/src/runtime/adapters/three.test.ts
new file mode 100644
index 0000000000..ac886f8892
--- /dev/null
+++ b/packages/core/src/runtime/adapters/three.test.ts
@@ -0,0 +1,64 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { createThreeAdapter } from "./three";
+
+const threeWindow = window as Window & { __hfThreeTime?: number };
+
+describe("three adapter", () => {
+ beforeEach(() => {
+ delete threeWindow.__hfThreeTime;
+ });
+
+ it("has correct name", () => {
+ expect(createThreeAdapter().name).toBe("three");
+ });
+
+ it("seek sets __hfThreeTime", () => {
+ const adapter = createThreeAdapter();
+ adapter.seek({ time: 5 });
+ expect(threeWindow.__hfThreeTime).toBe(5);
+ });
+
+ it("seek dispatches hf-seek custom event", () => {
+ const adapter = createThreeAdapter();
+ const handler = vi.fn();
+ window.addEventListener("hf-seek", handler);
+ adapter.seek({ time: 3 });
+ window.removeEventListener("hf-seek", handler);
+ expect(handler).toHaveBeenCalled();
+ const detail = (handler.mock.calls[0][0] as CustomEvent).detail;
+ expect(detail.time).toBe(3);
+ });
+
+ it("seek clamps negative time to 0", () => {
+ const adapter = createThreeAdapter();
+ adapter.seek({ time: -10 });
+ expect(threeWindow.__hfThreeTime).toBe(0);
+ });
+
+ it("pause retains last forced time", () => {
+ const adapter = createThreeAdapter();
+ adapter.seek({ time: 7 });
+ adapter.pause();
+ // Internal state preserved — no crash
+ expect(threeWindow.__hfThreeTime).toBe(7);
+ });
+
+ it("play releases forced time", () => {
+ const adapter = createThreeAdapter();
+ adapter.seek({ time: 7 });
+ adapter.play!();
+ // After play, forced time is released
+ });
+
+ it("revert resets all state", () => {
+ const adapter = createThreeAdapter();
+ adapter.seek({ time: 5 });
+ adapter.revert!();
+ // After revert, forcedTime and lastForcedTime are reset
+ });
+
+ it("discover is a no-op", () => {
+ const adapter = createThreeAdapter();
+ expect(() => adapter.discover()).not.toThrow();
+ });
+});
diff --git a/packages/core/src/runtime/adapters/three.ts b/packages/core/src/runtime/adapters/three.ts
new file mode 100644
index 0000000000..49704e50c8
--- /dev/null
+++ b/packages/core/src/runtime/adapters/three.ts
@@ -0,0 +1,33 @@
+import type { RuntimeDeterministicAdapter } from "../types";
+
+export function createThreeAdapter(): RuntimeDeterministicAdapter {
+ let forcedTime: number | null = null;
+ let lastForcedTime = 0;
+
+ return {
+ name: "three",
+ discover: () => {},
+ seek: (ctx) => {
+ forcedTime = Math.max(0, Number(ctx.time) || 0);
+ lastForcedTime = forcedTime;
+ window.__hfThreeTime = forcedTime;
+ try {
+ window.dispatchEvent(new CustomEvent("hf-seek", { detail: { time: forcedTime } }));
+ } catch {
+ // ignore custom event failures
+ }
+ },
+ pause: () => {
+ if (forcedTime == null) {
+ forcedTime = Math.max(0, lastForcedTime);
+ }
+ },
+ play: () => {
+ forcedTime = null;
+ },
+ revert: () => {
+ forcedTime = null;
+ lastForcedTime = 0;
+ },
+ };
+}
diff --git a/packages/core/src/runtime/adapters/waapi.test.ts b/packages/core/src/runtime/adapters/waapi.test.ts
new file mode 100644
index 0000000000..65b1700e95
--- /dev/null
+++ b/packages/core/src/runtime/adapters/waapi.test.ts
@@ -0,0 +1,72 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { createWaapiAdapter } from "./waapi";
+
+describe("waapi adapter", () => {
+ it("has correct name", () => {
+ expect(createWaapiAdapter().name).toBe("waapi");
+ });
+
+ it("seek pauses and sets currentTime on all animations", () => {
+ const mockAnim = { pause: vi.fn(), currentTime: 0 };
+ (document as any).getAnimations = vi.fn(() => [mockAnim]);
+
+ const adapter = createWaapiAdapter();
+ adapter.seek({ time: 2.5 });
+
+ expect(mockAnim.pause).toHaveBeenCalled();
+ expect(mockAnim.currentTime).toBe(2500); // seconds → ms
+
+ delete (document as any).getAnimations;
+ });
+
+ it("seek clamps negative time to 0", () => {
+ const mockAnim = { pause: vi.fn(), currentTime: 0 };
+ (document as any).getAnimations = vi.fn(() => [mockAnim]);
+
+ const adapter = createWaapiAdapter();
+ adapter.seek({ time: -3 });
+
+ expect(mockAnim.currentTime).toBe(0);
+ delete (document as any).getAnimations;
+ });
+
+ it("pause pauses all animations", () => {
+ const mockAnim = { pause: vi.fn(), currentTime: 0 };
+ (document as any).getAnimations = vi.fn(() => [mockAnim]);
+
+ const adapter = createWaapiAdapter();
+ adapter.pause();
+
+ expect(mockAnim.pause).toHaveBeenCalled();
+ delete (document as any).getAnimations;
+ });
+
+ it("handles missing getAnimations API", () => {
+ const original = document.getAnimations;
+ (document as Record<string, unknown>).getAnimations = undefined;
+
+ const adapter = createWaapiAdapter();
+ expect(() => adapter.seek({ time: 1 })).not.toThrow();
+ expect(() => adapter.pause()).not.toThrow();
+
+ document.getAnimations = original;
+ });
+
+ it("handles animation that throws on pause", () => {
+ const mockAnim = {
+ pause: vi.fn(() => { throw new Error("invalid state"); }),
+ currentTime: 0,
+ };
+ (document as any).getAnimations = vi.fn(() => [mockAnim]);
+
+ const adapter = createWaapiAdapter();
+ expect(() => adapter.seek({ time: 1 })).not.toThrow();
+
+ delete (document as any).getAnimations;
+ });
+
+ it("discover is a no-op", () => {
+ const adapter = createWaapiAdapter();
+ expect(() => adapter.discover()).not.toThrow();
+ });
+});
diff --git a/packages/core/src/runtime/adapters/waapi.ts b/packages/core/src/runtime/adapters/waapi.ts
new file mode 100644
index 0000000000..2df6da072e
--- /dev/null
+++ b/packages/core/src/runtime/adapters/waapi.ts
@@ -0,0 +1,30 @@
+import type { RuntimeDeterministicAdapter } from "../types";
+
+export function createWaapiAdapter(): RuntimeDeterministicAdapter {
+ return {
+ name: "waapi",
+ discover: () => {},
+ seek: (ctx) => {
+ if (!document.getAnimations) return;
+ const timeMs = Math.max(0, (Number(ctx.time) || 0) * 1000);
+ for (const animation of document.getAnimations()) {
+ try {
+ animation.pause();
+ animation.currentTime = timeMs;
+ } catch {
+ // ignore animation edge-cases
+ }
+ }
+ },
+ pause: () => {
+ if (!document.getAnimations) return;
+ for (const animation of document.getAnimations()) {
+ try {
+ animation.pause();
+ } catch {
+ // ignore animation edge-cases
+ }
+ }
+ },
+ };
+}
diff --git a/packages/core/src/runtime/analytics.test.ts b/packages/core/src/runtime/analytics.test.ts
new file mode 100644
index 0000000000..376e0f3452
--- /dev/null
+++ b/packages/core/src/runtime/analytics.test.ts
@@ -0,0 +1,60 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { initRuntimeAnalytics, emitAnalyticsEvent } from "./analytics";
+
+describe("runtime analytics", () => {
+ let postMessage: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ postMessage = vi.fn();
+ // Reset module state by re-init
+ initRuntimeAnalytics(postMessage);
+ });
+
+ it("emits analytics event via postMessage", () => {
+ emitAnalyticsEvent("composition_loaded");
+ expect(postMessage).toHaveBeenCalledWith({
+ source: "hf-preview",
+ type: "analytics",
+ event: "composition_loaded",
+ properties: {},
+ });
+ });
+
+ it("passes properties through", () => {
+ emitAnalyticsEvent("composition_played", { duration: 10, autoplay: true });
+ expect(postMessage).toHaveBeenCalledWith({
+ source: "hf-preview",
+ type: "analytics",
+ event: "composition_played",
+ properties: { duration: 10, autoplay: true },
+ });
+ });
+
+ it("does not throw when postMessage is not set", () => {
+ // Re-init with a function that we'll clear
+ initRuntimeAnalytics(null as unknown as (payload: unknown) => void);
+ expect(() => emitAnalyticsEvent("composition_paused")).not.toThrow();
+ });
+
+ it("does not throw when postMessage throws", () => {
+ postMessage.mockImplementation(() => {
+ throw new Error("channel closed");
+ });
+ expect(() => emitAnalyticsEvent("composition_seeked")).not.toThrow();
+ });
+
+ it("emits all event types", () => {
+ const events = [
+ "composition_loaded",
+ "composition_played",
+ "composition_paused",
+ "composition_seeked",
+ "composition_ended",
+ "element_picked",
+ ] as const;
+ for (const event of events) {
+ emitAnalyticsEvent(event);
+ }
+ expect(postMessage).toHaveBeenCalledTimes(events.length);
+ });
+});
diff --git a/packages/core/src/runtime/analytics.ts b/packages/core/src/runtime/analytics.ts
new file mode 100644
index 0000000000..4d313ddb43
--- /dev/null
+++ b/packages/core/src/runtime/analytics.ts
@@ -0,0 +1,66 @@
+/**
+ * Runtime analytics — vendor-agnostic event emission.
+ *
+ * The runtime emits structured events via postMessage. The host application
+ * decides what to do with them: forward to PostHog, Mixpanel, Amplitude,
+ * a custom logger, or nothing at all.
+ *
+ * For session replay: initialize your analytics SDK (e.g. PostHog) only in
+ * the parent app with `recordCrossOriginIframes: true`. No SDK needs to run
+ * inside this iframe.
+ *
+ * ## Host app integration
+ *
+ * ```javascript
+ * window.addEventListener("message", (e) => {
+ * if (e.data?.source !== "hf-preview" || e.data?.type !== "analytics") return;
+ * const { event, properties } = e.data;
+ *
+ * // PostHog:
+ * posthog.capture(event, properties);
+ * // Mixpanel:
+ * mixpanel.track(event, properties);
+ * // Custom:
+ * myLogger.track(event, properties);
+ * });
+ * ```
+ */
+
+export type RuntimeAnalyticsEvent =
+ | "composition_loaded"
+ | "composition_played"
+ | "composition_paused"
+ | "composition_seeked"
+ | "composition_ended"
+ | "element_picked";
+
+export type RuntimeAnalyticsProperties = Record<string, string | number | boolean | null>;
+
+// Stored reference to the postRuntimeMessage function, set during init.
+// Avoids a circular import between analytics ↔ bridge.
+let _postMessage: ((payload: unknown) => void) | null = null;
+
+export function initRuntimeAnalytics(postMessage: (payload: unknown) => void): void {
+ _postMessage = postMessage;
+}
+
+/**
+ * Emit an analytics event through the bridge.
+ * The host app receives it via postMessage and forwards to its analytics provider.
+ */
+export function emitAnalyticsEvent(
+ event: RuntimeAnalyticsEvent,
+ properties?: RuntimeAnalyticsProperties,
+): void {
+ if (!_postMessage) return;
+ try {
+ _postMessage({
+ source: "hf-preview",
+ type: "analytics",
+ event,
+ properties: properties ?? {},
+ });
+ } catch {
+ // Never let analytics failures affect the runtime
+ }
+}
diff --git a/packages/core/src/runtime/bridge.test.ts b/packages/core/src/runtime/bridge.test.ts
new file mode 100644
index 0000000000..91ddd01204
--- /dev/null
+++ b/packages/core/src/runtime/bridge.test.ts
@@ -0,0 +1,118 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { installRuntimeControlBridge } from "./bridge";
+
+function createMockDeps() {
+ return {
+ onPlay: vi.fn(),
+ onPause: vi.fn(),
+ onSeek: vi.fn(),
+ onSetMuted: vi.fn(),
+ onSetPlaybackRate: vi.fn(),
+ onEnablePickMode: vi.fn(),
+ onDisablePickMode: vi.fn(),
+ };
+}
+
+function makeControlMessage(action: string, extra?: Record<string, unknown>) {
+ return new MessageEvent("message", {
+ data: { source: "hf-parent", type: "control", action, ...extra },
+ });
+}
+
+describe("installRuntimeControlBridge", () => {
+ it("dispatches play command", () => {
+ const deps = createMockDeps();
+ const handler = installRuntimeControlBridge(deps);
+ handler(makeControlMessage("play"));
+ expect(deps.onPlay).toHaveBeenCalledOnce();
+ });
+
+ it("dispatches pause command", () => {
+ const deps = createMockDeps();
+ const handler = installRuntimeControlBridge(deps);
+ handler(makeControlMessage("pause"));
+ expect(deps.onPause).toHaveBeenCalledOnce();
+ });
+
+ it("dispatches seek command with frame and mode", () => {
+ const deps = createMockDeps();
+ const handler = installRuntimeControlBridge(deps);
+ handler(makeControlMessage("seek", { frame: 150, seekMode: "drag" }));
+ expect(deps.onSeek).toHaveBeenCalledWith(150, "drag");
+ });
+
+ it("seek defaults frame to 0 and seekMode to commit", () => {
+ const deps = createMockDeps();
+ const handler = installRuntimeControlBridge(deps);
+ handler(makeControlMessage("seek"));
+ expect(deps.onSeek).toHaveBeenCalledWith(0, "commit");
+ });
+
+ it("dispatches set-muted command", () => {
+ const deps = createMockDeps();
+ const handler = installRuntimeControlBridge(deps);
+ handler(makeControlMessage("set-muted", { muted: true }));
+ expect(deps.onSetMuted).toHaveBeenCalledWith(true);
+ });
+
+ it("dispatches set-playback-rate command", () => {
+ const deps = createMockDeps();
+ const handler = installRuntimeControlBridge(deps);
+ handler(makeControlMessage("set-playback-rate", { playbackRate: 2 }));
+ expect(deps.onSetPlaybackRate).toHaveBeenCalledWith(2);
+ });
+
+ it("defaults playbackRate to 1", () => {
+ const deps = createMockDeps();
+ const handler = installRuntimeControlBridge(deps);
+ handler(makeControlMessage("set-playback-rate"));
+ expect(deps.onSetPlaybackRate).toHaveBeenCalledWith(1);
+ });
+
+ it("dispatches enable-pick-mode", () => {
+ const deps = createMockDeps();
+ const handler = installRuntimeControlBridge(deps);
+ handler(makeControlMessage("enable-pick-mode"));
+ expect(deps.onEnablePickMode).toHaveBeenCalledOnce();
+ });
+
+ it("dispatches disable-pick-mode", () => {
+ const deps = createMockDeps();
+ const handler = installRuntimeControlBridge(deps);
+ handler(makeControlMessage("disable-pick-mode"));
+ expect(deps.onDisablePickMode).toHaveBeenCalledOnce();
+ });
+
+ it("ignores messages from wrong source", () => {
+ const deps = createMockDeps();
+ const handler = installRuntimeControlBridge(deps);
+ handler(new MessageEvent("message", {
+ data: { source: "other", type: "control", action: "play" },
+ }));
+ expect(deps.onPlay).not.toHaveBeenCalled();
+ });
+
+ it("ignores messages with wrong type", () => {
+ const deps = createMockDeps();
+ const handler = installRuntimeControlBridge(deps);
+ handler(new MessageEvent("message", {
+ data: { source: "hf-parent", type: "state", action: "play" },
+ }));
+ expect(deps.onPlay).not.toHaveBeenCalled();
+ });
+
+ it("ignores null data", () => {
+ const deps = createMockDeps();
+ const handler = installRuntimeControlBridge(deps);
+ handler(new MessageEvent("message", { data: null }));
+ expect(deps.onPlay).not.toHaveBeenCalled();
+ });
+
+ it("handles flash-elements command without crashing", () => {
+ const deps = createMockDeps();
+ const handler = installRuntimeControlBridge(deps);
+ expect(() =>
+ handler(makeControlMessage("flash-elements", { selectors: [".test"], duration: 500 }))
+ ).not.toThrow();
+ });
+});
diff --git a/packages/core/src/runtime/bridge.ts b/packages/core/src/runtime/bridge.ts
new file mode 100644
index 0000000000..7afa4a27d1
--- /dev/null
+++ b/packages/core/src/runtime/bridge.ts
@@ -0,0 +1,101 @@
+import type { RuntimeBridgeControlMessage, RuntimeOutboundMessage } from "./types";
+
+type BridgeDeps = {
+ onPlay: () => void;
+ onPause: () => void;
+ onSeek: (frame: number, seekMode: "drag" | "commit") => void;
+ onSetMuted: (muted: boolean) => void;
+ onSetPlaybackRate: (rate: number) => void;
+ onEnablePickMode: () => void;
+ onDisablePickMode: () => void;
+};
+
+export function postRuntimeMessage(payload: RuntimeOutboundMessage): void {
+ try {
+ window.parent.postMessage(payload, "*");
+ } catch {
+ // Ignore cross-frame posting failures.
+ }
+}
+
+export function installRuntimeControlBridge(deps: BridgeDeps): (event: MessageEvent) => void {
+ const handler = (event: MessageEvent) => {
+ const data = event.data as Partial<RuntimeBridgeControlMessage> | null;
+ if (!data || data.source !== "hf-parent" || data.type !== "control") return;
+ const action = data.action;
+ if (action === "play") {
+ deps.onPlay();
+ return;
+ }
+ if (action === "pause") {
+ deps.onPause();
+ return;
+ }
+ if (action === "seek") {
+ deps.onSeek(Number(data.frame ?? 0), data.seekMode ?? "commit");
+ return;
+ }
+ if (action === "set-muted") {
+ deps.onSetMuted(Boolean(data.muted));
+ return;
+ }
+ if (action === "set-playback-rate") {
+ deps.onSetPlaybackRate(Number(data.playbackRate ?? 1));
+ return;
+ }
+ if (action === "enable-pick-mode") {
+ deps.onEnablePickMode();
+ return;
+ }
+ if (action === "disable-pick-mode") {
+ deps.onDisablePickMode();
+ return;
+ }
+ if (action === "flash-elements") {
+ // Briefly highlight elements — used by the chat-canvas bridge
+ // to show what changed after an agent edit
+ const selectors = (data as Record<string, unknown>).selectors as string[] | undefined;
+ const duration = ((data as Record<string, unknown>).duration as number) || 800;
+ if (selectors) {
+ flashElements(selectors, duration);
+ }
+ }
+ };
+ window.addEventListener("message", handler);
+ return handler;
+}
+
+/**
+ * Flash elements — briefly highlight them with a blue outline.
+ * Used by the chat-canvas bridge to show what changed after an agent edit.
+ */
+function flashElements(selectors: string[], duration: number): void {
+ if (!document.getElementById("__hf-flash-styles")) {
+ const style = document.createElement("style");
+ style.id = "__hf-flash-styles";
+ style.textContent = `
+ .__hf-flash {
+ outline: 2px solid rgba(59, 130, 246, 0.6) !important;
+ outline-offset: 2px !important;
+ animation: __hf-flash-pulse ${duration}ms ease-out forwards !important;
+ }
+ @keyframes __hf-flash-pulse {
+ 0% { outline-color: rgba(59, 130, 246, 0.8); }
+ 100% { outline-color: transparent; }
+ }
+ `;
+ document.head.appendChild(style);
+ }
+
+ for (const selector of selectors) {
+ try {
+ const els = document.querySelectorAll(selector);
+ els.forEach((el) => {
+ el.classList.add("__hf-flash");
+ setTimeout(() => el.classList.remove("__hf-flash"), duration);
+ });
+ } catch {
+ // Invalid selector — skip
+ }
+ }
+}
diff --git a/packages/core/src/runtime/compositionLoader.test.ts b/packages/core/src/runtime/compositionLoader.test.ts
new file mode 100644
index 0000000000..19c8430f90
--- /dev/null
+++ b/packages/core/src/runtime/compositionLoader.test.ts
@@ -0,0 +1,224 @@
+import { describe, it, expect, vi, afterEach, beforeAll } from "vitest";
+import { loadExternalCompositions } from "./compositionLoader";
+
+// jsdom doesn't provide CSS.escape
+beforeAll(() => {
+ if (typeof globalThis.CSS === "undefined") {
+ (globalThis as any).CSS = {};
+ }
+ if (typeof CSS.escape !== "function") {
+ CSS.escape = (value: string) => value.replace(/([^\w-])/g, "\\$1");
+ }
+});
+
+describe("loadExternalCompositions", () => {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ document.head.querySelectorAll("style").forEach((s) => s.remove());
+ vi.restoreAllMocks();
+ });
+
+ const defaultParams = {
+ injectedStyles: [] as HTMLStyleElement[],
+ injectedScripts: [] as HTMLScriptElement[],
+ parseDimensionPx: (v: string | null) => (v ? `${v}px` : null),
+ };
+
+ it("does nothing when no composition-src elements exist", async () => {
+ const fetchSpy = vi.spyOn(globalThis, "fetch");
+ await loadExternalCompositions({ ...defaultParams });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("fetches and mounts external composition HTML", async () => {
+ const host = document.createElement("div");
+ host.setAttribute("data-composition-src", "https://example.com/comp.html");
+ host.setAttribute("data-composition-id", "scene-1");
+ document.body.appendChild(host);
+
+ const compositionHtml = `
+ <html><body>
+ <div data-composition-id="scene-1" data-width="1920" data-height="1080">
+ <p>Hello World</p>
+ </div>
+ </body></html>
+ `;
+
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(compositionHtml, { status: 200 })
+ );
+
+ await loadExternalCompositions({ ...defaultParams });
+
+ const mountedParagraph = host.querySelector("p");
+
+ expect(mountedParagraph).toBeTruthy();
+ expect(mountedParagraph?.textContent).toBe("Hello World");
+ });
+
+ it("injects styles into document head", async () => {
+ const host = document.createElement("div");
+ host.setAttribute("data-composition-src", "https://example.com/comp.html");
+ document.body.appendChild(host);
+
+ const compositionHtml = `
+ <html><body>
+ <style>.test { color: red; }</style>
+ <p>Styled</p>
+ </body></html>
+ `;
+
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(compositionHtml, { status: 200 })
+ );
+
+ const injectedStyles: HTMLStyleElement[] = [];
+ await loadExternalCompositions({
+ ...defaultParams,
+ injectedStyles,
+ });
+
+ expect(injectedStyles.length).toBeGreaterThan(0);
+ });
+
+ it("calls onDiagnostic when fetch fails", async () => {
+ const host = document.createElement("div");
+ host.setAttribute("data-composition-src", "https://example.com/broken.html");
+ host.setAttribute("data-composition-id", "broken");
+ document.body.appendChild(host);
+
+ vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("Network error"));
+
+ const onDiagnostic = vi.fn();
+ await loadExternalCompositions({
+ ...defaultParams,
+ onDiagnostic,
+ });
+
+ expect(onDiagnostic).toHaveBeenCalledWith(
+ expect.objectContaining({
+ code: "external_composition_load_failed",
+ details: expect.objectContaining({
+ hostCompositionSrc: "https://example.com/broken.html",
+ errorMessage: "Network error",
+ }),
+ })
+ );
+ });
+
+ it("calls onDiagnostic when HTTP response is not ok", async () => {
+ const host = document.createElement("div");
+ host.setAttribute("data-composition-src", "https://example.com/404.html");
+ document.body.appendChild(host);
+
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response("Not Found", { status: 404 })
+ );
+
+ const onDiagnostic = vi.fn();
+ await loadExternalCompositions({
+ ...defaultParams,
+ onDiagnostic,
+ });
+
+ expect(onDiagnostic).toHaveBeenCalledWith(
+ expect.objectContaining({
+ code: "external_composition_load_failed",
+ })
+ );
+ });
+
+ it("uses local template when available", async () => {
+ const template = document.createElement("template");
+ template.id = "local-comp-template";
+ template.innerHTML = "<p>From template</p>";
+ document.body.appendChild(template);
+
+ const host = document.createElement("div");
+ host.setAttribute("data-composition-src", "https://example.com/comp.html");
+ host.setAttribute("data-composition-id", "local-comp");
+ document.body.appendChild(host);
+
+ const fetchSpy = vi.spyOn(globalThis, "fetch");
+
+ await loadExternalCompositions({ ...defaultParams });
+
+ // Should use local template and not fetch
+ expect(fetchSpy).not.toHaveBeenCalled();
+ expect(host.querySelector("p")?.textContent).toBe("From template");
+ });
+
+ it("skips hosts without data-composition-src value", async () => {
+ const host = document.createElement("div");
+ host.setAttribute("data-composition-src", "");
+ document.body.appendChild(host);
+
+ const fetchSpy = vi.spyOn(globalThis, "fetch");
+ await loadExternalCompositions({ ...defaultParams });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("clears host content before mounting", async () => {
+ const host = document.createElement("div");
+ host.setAttribute("data-composition-src", "https://example.com/comp.html");
+ host.innerHTML = "<span>Old content</span>";
+ document.body.appendChild(host);
+
+ const compositionHtml = `<html><body><p>New</p></body></html>`;
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(compositionHtml, { status: 200 })
+ );
+
+ await loadExternalCompositions({ ...defaultParams });
+ expect(host.querySelector("span")).toBeNull();
+ });
+
+ it("handles inline scripts", async () => {
+ const host = document.createElement("div");
+ host.setAttribute("data-composition-src", "https://example.com/comp.html");
+ document.body.appendChild(host);
+
+ // Only inline scripts (no external src) to avoid waitForExternalScriptLoad timeout
+ const compositionHtml = `
+ <html><body>
+ <script>console.log("inline")</script>
+ <p>With inline script</p>
+ </body></html>
+ `;
+
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(compositionHtml, { status: 200 })
+ );
+
+ const injectedScripts: HTMLScriptElement[] = [];
+ await loadExternalCompositions({
+ ...defaultParams,
+ injectedScripts,
+ });
+
+ expect(injectedScripts.length).toBeGreaterThan(0);
+ expect(injectedScripts[0].textContent).toContain("console.log");
+ });
+
+ it("handles multiple compositions in parallel", async () => {
+ const host1 = document.createElement("div");
+ host1.setAttribute("data-composition-src", "https://example.com/a.html");
+ document.body.appendChild(host1);
+
+ const host2 = document.createElement("div");
+ host2.setAttribute("data-composition-src", "https://example.com/b.html");
+ document.body.appendChild(host2);
+
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
+ const url = typeof input === "string" ? input : (input as Request).url;
+ if (url.includes("a.html")) {
+ return new Response("<html><body><p>A</p></body></html>", { status: 200 });
+ }
+ return new Response("<html><body><p>B</p></body></html>", { status: 200 });
+ });
+
+ await loadExternalCompositions({ ...defaultParams });
+ expect(host1.querySelector("p")?.textContent).toBe("A");
+ expect(host2.querySelector("p")?.textContent).toBe("B");
+ });
+});
diff --git a/packages/core/src/runtime/compositionLoader.ts b/packages/core/src/runtime/compositionLoader.ts
new file mode 100644
index 0000000000..776f2dafe9
--- /dev/null
+++ b/packages/core/src/runtime/compositionLoader.ts
@@ -0,0 +1,267 @@
+type LoadExternalCompositionsParams = {
+ injectedStyles: HTMLStyleElement[];
+ injectedScripts: HTMLScriptElement[];
+ parseDimensionPx: (value: string | null) => string | null;
+ onDiagnostic?: (payload: {
+ code: string;
+ details: Record<string, string | number | boolean | null | string[]>;
+ }) => void;
+};
+
+type PendingScript =
+ | {
+ kind: "inline";
+ content: string;
+ type: string;
+ }
+ | {
+ kind: "external";
+ src: string;
+ type: string;
+ };
+
+const EXTERNAL_SCRIPT_LOAD_TIMEOUT_MS = 8000;
+const BARE_RELATIVE_PATH_RE = /^(?![a-zA-Z][a-zA-Z\d+\-.]*:)(?!\/\/)(?!\/)(?!\.\.?\/).+/;
+
+const waitForExternalScriptLoad = (
+ scriptEl: HTMLScriptElement,
+): Promise<{ status: "load" | "error" | "timeout"; elapsedMs: number }> =>
+ new Promise((resolve) => {
+ let settled = false;
+ const startedAt = Date.now();
+ let timeoutId: number | null = null;
+ const settle = (status: "load" | "error" | "timeout") => {
+ if (settled) return;
+ settled = true;
+ if (timeoutId != null) {
+ window.clearTimeout(timeoutId);
+ }
+ resolve({
+ status,
+ elapsedMs: Math.max(0, Date.now() - startedAt),
+ });
+ };
+ scriptEl.addEventListener("load", () => settle("load"), { once: true });
+ scriptEl.addEventListener("error", () => settle("error"), { once: true });
+ timeoutId = window.setTimeout(() => settle("timeout"), EXTERNAL_SCRIPT_LOAD_TIMEOUT_MS);
+ });
+
+function resetCompositionHost(host: Element) {
+ while (host.firstChild) {
+ host.removeChild(host.firstChild);
+ }
+ host.textContent = "";
+}
+
+function resolveScriptSourceUrl(scriptSrc: string, compositionUrl: URL | null): string {
+ const trimmedSrc = scriptSrc.trim();
+ if (!trimmedSrc) return scriptSrc;
+ try {
+ if (BARE_RELATIVE_PATH_RE.test(trimmedSrc)) {
+ // Composition payloads may use root-relative semantics without a leading slash.
+ return new URL(trimmedSrc, document.baseURI).toString();
+ }
+ if (compositionUrl) {
+ return new URL(trimmedSrc, compositionUrl).toString();
+ }
+ return new URL(trimmedSrc, document.baseURI).toString();
+ } catch {
+ return scriptSrc;
+ }
+}
+
+async function mountCompositionContent(params: {
+ host: Element;
+ hostCompositionId: string | null;
+ hostCompositionSrc: string;
+ sourceNode: ParentNode;
+ hasTemplate: boolean;
+ fallbackBodyInnerHtml: string;
+ compositionUrl: URL | null;
+ injectedStyles: HTMLStyleElement[];
+ injectedScripts: HTMLScriptElement[];
+ parseDimensionPx: (value: string | null) => string | null;
+ onDiagnostic?: (payload: {
+ code: string;
+ details: Record<string, string | number | boolean | null | string[]>;
+ }) => void;
+}): Promise<void> {
+ let innerRoot: Element | null = null;
+ if (params.hostCompositionId) {
+ const candidateRoots = Array.from(params.sourceNode.querySelectorAll<Element>("[data-composition-id]"));
+ innerRoot =
+ candidateRoots.find((candidate) => candidate.getAttribute("data-composition-id") === params.hostCompositionId) ??
+ null;
+ }
+ const contentNode = innerRoot ?? params.sourceNode;
+
+ const styles = Array.from(contentNode.querySelectorAll<HTMLStyleElement>("style"));
+ for (const style of styles) {
+ const clonedStyle = style.cloneNode(true);
+ if (!(clonedStyle instanceof HTMLStyleElement)) continue;
+ document.head.appendChild(clonedStyle);
+ params.injectedStyles.push(clonedStyle);
+ }
+
+ const scripts = Array.from(contentNode.querySelectorAll<HTMLScriptElement>("script"));
+ const scriptPayloads: PendingScript[] = [];
+ for (const script of scripts) {
+ const scriptType = script.getAttribute("type")?.trim() ?? "";
+ const scriptSrc = script.getAttribute("src")?.trim() ?? "";
+ if (scriptSrc) {
+ const resolvedSrc = resolveScriptSourceUrl(scriptSrc, params.compositionUrl);
+ scriptPayloads.push({
+ kind: "external",
+ src: resolvedSrc,
+ type: scriptType,
+ });
+ } else {
+ const scriptText = script.textContent?.trim() ?? "";
+ if (scriptText) {
+ scriptPayloads.push({
+ kind: "inline",
+ content: scriptText,
+ type: scriptType,
+ });
+ }
+ }
+ script.parentNode?.removeChild(script);
+ }
+ const remainingStyles = Array.from(contentNode.querySelectorAll<HTMLStyleElement>("style"));
+ for (const style of remainingStyles) {
+ style.parentNode?.removeChild(style);
+ }
+
+ if (innerRoot) {
+ const imported = document.importNode(innerRoot, true) as HTMLElement;
+ const widthRaw = innerRoot.getAttribute("data-width");
+ const heightRaw = innerRoot.getAttribute("data-height");
+ const widthPx = params.parseDimensionPx(widthRaw);
+ const heightPx = params.parseDimensionPx(heightRaw);
+ imported.style.position = "relative";
+ imported.style.width = widthPx || "100%";
+ imported.style.height = heightPx || "100%";
+ if (widthPx) imported.style.setProperty("--comp-width", widthPx);
+ if (heightPx) imported.style.setProperty("--comp-height", heightPx);
+ if (widthRaw) params.host.setAttribute("data-width", widthRaw);
+ if (heightRaw) params.host.setAttribute("data-height", heightRaw);
+ if (widthPx && params.host instanceof HTMLElement) params.host.style.width = widthPx;
+ if (heightPx && params.host instanceof HTMLElement) params.host.style.height = heightPx;
+ params.host.appendChild(imported);
+ } else if (params.hasTemplate) {
+ params.host.appendChild(document.importNode(contentNode, true));
+ } else {
+ params.host.innerHTML = params.fallbackBodyInnerHtml;
+ }
+
+ for (const scriptPayload of scriptPayloads) {
+ const injectedScript = document.createElement("script");
+ if (scriptPayload.type) {
+ injectedScript.type = scriptPayload.type;
+ }
+ // Preserve deterministic script execution order across injected composition scripts.
+ injectedScript.async = false;
+ if (scriptPayload.kind === "external") {
+ injectedScript.src = scriptPayload.src;
+ } else if (scriptPayload.type.toLowerCase() === "module") {
+ injectedScript.textContent = scriptPayload.content;
+ } else {
+ injectedScript.textContent = `(function(){${scriptPayload.content}})();`;
+ }
+ document.body.appendChild(injectedScript);
+ params.injectedScripts.push(injectedScript);
+ if (scriptPayload.kind === "external") {
+ const loadResult = await waitForExternalScriptLoad(injectedScript);
+ if (loadResult.status !== "load") {
+ params.onDiagnostic?.({
+ code: "external_composition_script_load_issue",
+ details: {
+ hostCompositionId: params.hostCompositionId,
+ hostCompositionSrc: params.hostCompositionSrc,
+ resolvedScriptSrc: scriptPayload.src,
+ loadStatus: loadResult.status,
+ elapsedMs: loadResult.elapsedMs,
+ },
+ });
+ }
+ }
+ }
+}
+
+export async function loadExternalCompositions(params: LoadExternalCompositionsParams): Promise<void> {
+ const hosts = Array.from(document.querySelectorAll("[data-composition-src]"));
+ if (hosts.length === 0) return;
+
+ await Promise.all(
+ hosts.map(async (host) => {
+ const src = host.getAttribute("data-composition-src");
+ if (!src) return;
+ let compositionUrl: URL | null = null;
+ try {
+ compositionUrl = new URL(src, document.baseURI);
+ } catch {
+ compositionUrl = null;
+ }
+ resetCompositionHost(host);
+ try {
+ const hostCompositionId = host.getAttribute("data-composition-id");
+ const localTemplate =
+ hostCompositionId != null
+ ? document.querySelector<HTMLTemplateElement>(`template#${CSS.escape(hostCompositionId)}-template`)
+ : null;
+ if (localTemplate) {
+ await mountCompositionContent({
+ host,
+ hostCompositionId,
+ hostCompositionSrc: src,
+ sourceNode: localTemplate.content,
+ hasTemplate: true,
+ fallbackBodyInnerHtml: "",
+ compositionUrl,
+ injectedStyles: params.injectedStyles,
+ injectedScripts: params.injectedScripts,
+ parseDimensionPx: params.parseDimensionPx,
+ onDiagnostic: params.onDiagnostic,
+ });
+ return;
+ }
+ const response = await fetch(src);
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`);
+ }
+ const html = await response.text();
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, "text/html");
+ const template =
+ (hostCompositionId
+ ? doc.querySelector<HTMLTemplateElement>(`template#${CSS.escape(hostCompositionId)}-template`)
+ : null) ?? doc.querySelector<HTMLTemplateElement>("template");
+ const sourceNode = template ? template.content : doc.body;
+ await mountCompositionContent({
+ host,
+ hostCompositionId,
+ hostCompositionSrc: src,
+ sourceNode,
+ hasTemplate: Boolean(template),
+ fallbackBodyInnerHtml: doc.body.innerHTML,
+ compositionUrl,
+ injectedStyles: params.injectedStyles,
+ injectedScripts: params.injectedScripts,
+ parseDimensionPx: params.parseDimensionPx,
+ onDiagnostic: params.onDiagnostic,
+ });
+ } catch (error) {
+ params.onDiagnostic?.({
+ code: "external_composition_load_failed",
+ details: {
+ hostCompositionId: host.getAttribute("data-composition-id"),
+ hostCompositionSrc: src,
+ errorMessage: error instanceof Error ? error.message : "unknown_error",
+ },
+ });
+ // Keep host empty on load failures to avoid rendering escaped fallback HTML.
+ resetCompositionHost(host);
+ }
+ }),
+ );
+}
diff --git a/packages/core/src/runtime/entry.ts b/packages/core/src/runtime/entry.ts
new file mode 100644
index 0000000000..f71c9effe1
--- /dev/null
+++ b/packages/core/src/runtime/entry.ts
@@ -0,0 +1,24 @@
+import { initSandboxRuntimeModular } from "./init";
+
+type HyperframeWindow = Window & {
+ __hyperframeRuntimeBootstrapped?: boolean;
+};
+
+// Inline composition scripts can run before DOMContentLoaded.
+// Ensure timeline registry exists at script evaluation time.
+(window as HyperframeWindow).__timelines = (window as HyperframeWindow).__timelines || {};
+
+function bootstrapHyperframeRuntime(): void {
+ const win = window as HyperframeWindow;
+ if (win.__hyperframeRuntimeBootstrapped) {
+ return;
+ }
+ win.__hyperframeRuntimeBootstrapped = true;
+ initSandboxRuntimeModular();
+}
+
+if (document.readyState === "loading") {
+ document.addEventListener("DOMContentLoaded", bootstrapHyperframeRuntime, { once: true });
+} else {
+ bootstrapHyperframeRuntime();
+}
diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts
new file mode 100644
index 0000000000..71f18f19d5
--- /dev/null
+++ b/packages/core/src/runtime/init.ts
@@ -0,0 +1,1422 @@
+import { installRuntimeControlBridge, postRuntimeMessage } from "./bridge";
+import { initRuntimeAnalytics, emitAnalyticsEvent } from "./analytics";
+import { createCssAdapter } from "./adapters/css";
+import { createGsapAdapter } from "./adapters/gsap";
+import { createLottieAdapter } from "./adapters/lottie";
+import { createThreeAdapter } from "./adapters/three";
+import { createWaapiAdapter } from "./adapters/waapi";
+import { refreshRuntimeMediaCache, syncRuntimeMedia } from "./media";
+import { createPickerModule } from "./picker";
+import { createRuntimePlayer } from "./player";
+import { createRuntimeState } from "./state";
+import { collectRuntimeTimelinePayload } from "./timeline";
+import { createRuntimeStartTimeResolver } from "./startResolver";
+import { loadExternalCompositions } from "./compositionLoader";
+import type { RuntimeDeterministicAdapter, RuntimeJson, RuntimeTimelineLike } from "./types";
+import type { PlayerAPI } from "../core.types";
+
+export function initSandboxRuntimeModular(): void {
+ const state = createRuntimeState();
+ const runtimeWindow = window as Window & {
+ __hfRuntimeTeardown?: (() => void) | null;
+ };
+ let runtimeErrorListener: ((event: ErrorEvent) => void) | null = null;
+ let runtimeUnhandledRejectionListener: ((event: PromiseRejectionEvent) => void) | null = null;
+ const runtimeCleanupCallbacks: Array<() => void> = [];
+ const postedDiagnosticKeys = new Set<string>();
+ let rootStageDiagnosticRafId: number | null = null;
+ if (typeof runtimeWindow.__hfRuntimeTeardown === "function") {
+ try {
+ runtimeWindow.__hfRuntimeTeardown();
+ } catch {
+ // keep runtime resilient across reinits
+ }
+ }
+ window.__timelines = window.__timelines || {};
+ const registerRuntimeCleanup = (callback: () => void) => {
+ runtimeCleanupCallbacks.push(callback);
+ };
+ const postRuntimeDiagnosticOnce = (code: string, details: Record<string, RuntimeJson>, dedupeKey?: string) => {
+ const key = dedupeKey ?? `${code}:${JSON.stringify(details)}`;
+ if (postedDiagnosticKeys.has(key)) {
+ return;
+ }
+ postedDiagnosticKeys.add(key);
+ postRuntimeMessage({
+ source: "hf-preview",
+ type: "diagnostic",
+ code,
+ details,
+ });
+ };
+ const createPlayerApiCompat = (basePlayer: {
+ _timeline: RuntimeTimelineLike | null;
+ play: () => void;
+ pause: () => void;
+ seek: (timeSeconds: number) => void;
+ getTime: () => number;
+ getDuration: () => number;
+ isPlaying: () => boolean;
+ renderSeek: (timeSeconds: number) => void;
+ }): PlayerAPI => {
+ const defaultStageZoom: ReturnType<PlayerAPI["getStageZoom"]> = {
+ scale: 1,
+ focusX: 960,
+ focusY: 540,
+ };
+ const emptyStageZoomKeyframes: ReturnType<PlayerAPI["getStageZoomKeyframes"]> = [];
+ const emptyVisibleElements: ReturnType<PlayerAPI["getVisibleElements"]> = [];
+ const defaultRenderState: ReturnType<PlayerAPI["getRenderState"]> = {
+ time: basePlayer.getTime(),
+ duration: basePlayer.getDuration(),
+ isPlaying: basePlayer.isPlaying(),
+ renderMode: false,
+ timelineDirty: false,
+ };
+ return {
+ play: basePlayer.play,
+ pause: basePlayer.pause,
+ seek: basePlayer.seek,
+ getTime: basePlayer.getTime,
+ getDuration: basePlayer.getDuration,
+ isPlaying: basePlayer.isPlaying,
+ getMainTimeline: () => null,
+ getElementBounds: () => {},
+ getElementsAtPoint: () => {},
+ setElementPosition: () => {},
+ previewElementPosition: () => {},
+ setElementKeyframes: () => {},
+ setElementScale: () => {},
+ setElementFontSize: () => {},
+ setElementTextContent: () => {},
+ setElementTextColor: () => {},
+ setElementTextShadow: () => {},
+ setElementTextFontWeight: () => {},
+ setElementTextFontFamily: () => {},
+ setElementTextOutline: () => {},
+ setElementTextHighlight: () => {},
+ setElementVolume: () => {},
+ setStageZoom: () => {},
+ getStageZoom: () => defaultStageZoom,
+ setStageZoomKeyframes: () => {},
+ getStageZoomKeyframes: () => emptyStageZoomKeyframes,
+ addElement: () => false,
+ removeElement: () => false,
+ updateElementTiming: () => false,
+ setElementTiming: () => {},
+ updateElementSrc: () => false,
+ updateElementLayer: () => false,
+ updateElementBasePosition: () => false,
+ markTimelineDirty: () => {},
+ isTimelineDirty: () => false,
+ rebuildTimeline: () => {},
+ ensureTimeline: () => {},
+ enableRenderMode: () => {},
+ disableRenderMode: () => {},
+ renderSeek: basePlayer.renderSeek,
+ getElementVisibility: () => ({ visible: false }),
+ getVisibleElements: () => emptyVisibleElements,
+ getRenderState: () => ({
+ ...defaultRenderState,
+ time: basePlayer.getTime(),
+ duration: basePlayer.getDuration(),
+ isPlaying: basePlayer.isPlaying(),
+ }),
+ };
+ };
+
+ const MIN_VALID_TIMELINE_DURATION_SECONDS = 1 / 60;
+ const TIMELINE_FLOOR_COVERAGE_RATIO = 0.75;
+ const LOOP_WRAP_PREVIOUS_TIME_THRESHOLD_SECONDS = 0.75;
+ const LOOP_WRAP_CURRENT_TIME_THRESHOLD_SECONDS = 0.35;
+ const LOOP_GUARD_SEEK_GRACE_PERIOD_MS = 900;
+ const LOOP_GUARD_CONSECUTIVE_WRAP_THRESHOLD = 3;
+ const PLAY_REBIND_HOLD_SECONDS = 2;
+ const METADATA_REBIND_MIN_DURATION_GAIN_SECONDS = 0.05;
+ const METADATA_REBIND_DEBOUNCE_MS = 100;
+ const MAX_DIAGNOSTIC_MESSAGE_LENGTH = 240;
+
+ const normalizeDiagnosticMessage = (value: unknown): string => {
+ if (value instanceof Error) {
+ return value.message || String(value);
+ }
+ if (typeof value === "string") {
+ return value;
+ }
+ try {
+ return JSON.stringify(value);
+ } catch {
+ return String(value ?? "");
+ }
+ };
+
+ const classifyRuntimeScriptFailure = (
+ rawMessage: string,
+ ): {
+ code: string;
+ category: string;
+ } => {
+ const message = rawMessage.toLowerCase();
+ if (message.includes("cannot read properties of null") || message.includes("cannot set properties of null")) {
+ return { code: "runtime_null_dom_access", category: "dom-null-access" };
+ }
+ if (message.includes("failed to execute 'queryselector'")) {
+ return { code: "runtime_invalid_selector", category: "selector-invalid" };
+ }
+ if (message.includes("is not defined")) {
+ return { code: "runtime_reference_missing", category: "reference-missing" };
+ }
+ return { code: "runtime_script_error", category: "script-error" };
+ };
+
+ const parseDimensionPx = (value: string | null): string | null => {
+ if (value == null || value.trim() === "") return null;
+ const parsed = Number.parseFloat(value);
+ if (!Number.isFinite(parsed) || parsed <= 0) return null;
+ return `${parsed}px`;
+ };
+
+ const resolveRootCompositionElement = (): HTMLElement | null => {
+ const mainComp = document.getElementById("main-comp");
+ if (mainComp instanceof HTMLElement && mainComp.hasAttribute("data-composition-id")) {
+ return mainComp;
+ }
+ const explicitRoot = document.querySelector('[data-composition-id][data-root="true"]');
+ if (explicitRoot instanceof HTMLElement) {
+ return explicitRoot;
+ }
+ const compositionNodes = Array.from(document.querySelectorAll("[data-composition-id]")) as HTMLElement[];
+ if (compositionNodes.length === 0) return null;
+ return (
+ compositionNodes.find((node) => !node.parentElement?.closest("[data-composition-id]")) ?? compositionNodes[0]
+ );
+ };
+
+ const applyCompositionSizing = () => {
+ const rootEl = resolveRootCompositionElement();
+ if (!rootEl) return;
+ const forcedWidth = parseDimensionPx(rootEl.getAttribute("data-width"));
+ const forcedHeight = parseDimensionPx(rootEl.getAttribute("data-height"));
+ if (forcedWidth) rootEl.style.width = forcedWidth;
+ if (forcedHeight) rootEl.style.height = forcedHeight;
+ if (forcedWidth) rootEl.style.setProperty("--comp-width", forcedWidth);
+ if (forcedHeight) rootEl.style.setProperty("--comp-height", forcedHeight);
+ };
+
+ const sanitizeCompositionDurationAttributes = () => {
+ const rootEl = resolveRootCompositionElement();
+ const compositionNodes = Array.from(
+ document.querySelectorAll("[data-composition-id][data-duration]"),
+ ) as HTMLElement[];
+ for (const node of compositionNodes) {
+ // Preserve explicit root duration so timeline payload can distinguish
+ // authored finite duration from loop-inflated timeline duration.
+ if (rootEl && node === rootEl) continue;
+ // Non-root compositions derive duration from timeline.
+ node.removeAttribute("data-duration");
+ }
+ };
+
+ const applyClipLayout = () => {
+ const rootEl = resolveRootCompositionElement();
+ if (!rootEl) return;
+ if (!rootEl.style.position) {
+ rootEl.style.position = "relative";
+ }
+ rootEl.style.overflow = "hidden";
+ const rootWidth = parseDimensionPx(rootEl.getAttribute("data-width"));
+ const rootHeight = parseDimensionPx(rootEl.getAttribute("data-height"));
+ if (rootWidth) rootEl.style.width = rootWidth;
+ if (rootHeight) rootEl.style.height = rootHeight;
+ const children = Array.from(rootEl.children) as HTMLElement[];
+ for (const el of children) {
+ const tag = el.tagName.toLowerCase();
+ if (tag === "script" || tag === "style" || tag === "link" || tag === "meta") continue;
+ if (!el.hasAttribute("data-start")) continue;
+ const hasLegacyAnchoredDefaults =
+ (el.style.top === "0px" || el.style.top === "0") &&
+ (el.style.left === "0px" || el.style.left === "0") &&
+ el.style.width === "100%" &&
+ el.style.height === "100%";
+ const hasCenteringTransform = /translate\(\s*-50%\s*,\s*-50%\s*\)/.test(el.style.transform);
+ if (
+ hasLegacyAnchoredDefaults &&
+ hasCenteringTransform &&
+ !el.hasAttribute("data-width") &&
+ !el.hasAttribute("data-height")
+ ) {
+ const previousTop = el.style.top;
+ const previousLeft = el.style.left;
+ const previousWidth = el.style.width;
+ const previousHeight = el.style.height;
+ el.style.top = "";
+ el.style.left = "";
+ el.style.width = "";
+ el.style.height = "";
+ const clearedComputed = window.getComputedStyle(el);
+ const cssProvidesClipLayout =
+ clearedComputed.top !== "auto" ||
+ clearedComputed.bottom !== "auto" ||
+ clearedComputed.left !== "auto" ||
+ clearedComputed.right !== "auto" ||
+ clearedComputed.width !== "0px" ||
+ clearedComputed.height !== "0px";
+ if (!cssProvidesClipLayout) {
+ el.style.top = previousTop;
+ el.style.left = previousLeft;
+ el.style.width = previousWidth;
+ el.style.height = previousHeight;
+ }
+ }
+ const computed = window.getComputedStyle(el);
+ const computedPosition = computed.position;
+ // Root-level timed clips should stack in the same viewport layer.
+ // Relative positioning keeps clips in document flow and can push later
+ // compositions below the viewport (eg. checkerboard-style overlays).
+ const shouldForceAbsolute = computedPosition !== "absolute" && computedPosition !== "fixed";
+ if (shouldForceAbsolute) {
+ el.style.position = "absolute";
+ }
+ const hasExplicitVerticalAnchor =
+ Boolean(el.style.top) || Boolean(el.style.bottom) || computed.top !== "auto" || computed.bottom !== "auto";
+ if (!hasExplicitVerticalAnchor) {
+ el.style.top = "0";
+ }
+ const hasExplicitHorizontalAnchor =
+ Boolean(el.style.left) || Boolean(el.style.right) || computed.left !== "auto" || computed.right !== "auto";
+ if (!hasExplicitHorizontalAnchor) {
+ el.style.left = "0";
+ }
+ if (tag !== "audio") {
+ const forcedWidth = parseDimensionPx(el.getAttribute("data-width"));
+ const forcedHeight = parseDimensionPx(el.getAttribute("data-height"));
+ const hasMeaningfulComputedWidth = computed.width !== "0px" && computed.width !== "auto";
+ const hasMeaningfulComputedHeight = computed.height !== "0px" && computed.height !== "auto";
+ if (forcedWidth) {
+ if (!el.style.width && !hasMeaningfulComputedWidth) {
+ el.style.width = forcedWidth;
+ }
+ } else if (!el.style.width && computed.width === "0px") {
+ el.style.width = "100%";
+ }
+ if (forcedHeight) {
+ if (!el.style.height && !hasMeaningfulComputedHeight) {
+ el.style.height = forcedHeight;
+ }
+ } else if (!el.style.height && computed.height === "0px") {
+ el.style.height = "100%";
+ }
+ }
+ }
+ };
+
+ const resolveStartForElement = (element: Element, fallback = 0): number => {
+ const resolver = createRuntimeStartTimeResolver({
+ timelineRegistry: (window.__timelines ?? {}) as Record<string, RuntimeTimelineLike | undefined>,
+ });
+ return resolver.resolveStartForElement(element, fallback);
+ };
+
+ const resolveDurationForElement = (element: Element): number | null => {
+ const resolver = createRuntimeStartTimeResolver({
+ timelineRegistry: (window.__timelines ?? {}) as Record<string, RuntimeTimelineLike | undefined>,
+ });
+ return resolver.resolveDurationForElement(element);
+ };
+ let externalCompositionsReady = !document.querySelector("[data-composition-src]");
+
+ const getTimelineDurationSeconds = (timeline: RuntimeTimelineLike | null): number | null => {
+ if (!timeline || typeof timeline.duration !== "function") return null;
+ try {
+ const raw = Number(timeline.duration());
+ if (!Number.isFinite(raw)) return null;
+ return Math.max(0, raw);
+ } catch {
+ return null;
+ }
+ };
+
+ const isUsableTimelineDuration = (durationSeconds: number | null): durationSeconds is number =>
+ typeof durationSeconds === "number" &&
+ Number.isFinite(durationSeconds) &&
+ durationSeconds > MIN_VALID_TIMELINE_DURATION_SECONDS;
+
+ type TimelineResolution = {
+ timeline: RuntimeTimelineLike | null;
+ selectedTimelineIds?: string[];
+ selectedDurationSeconds?: number | null;
+ mediaDurationFloorSeconds?: number | null;
+ diagnostics?: {
+ code: string;
+ details: Record<string, string | number | boolean | null | string[]>;
+ };
+ };
+
+ const resolveMediaElementDurationSeconds = (node: HTMLMediaElement): number | null => {
+ const declaredDuration = Number(node.getAttribute("data-duration"));
+ if (Number.isFinite(declaredDuration) && declaredDuration > 0) {
+ return declaredDuration;
+ }
+ const playbackStart = Number(
+ node.getAttribute("data-playback-start") ?? node.getAttribute("data-media-start") ?? "0",
+ );
+ const safePlaybackStart = Number.isFinite(playbackStart) ? Math.max(0, playbackStart) : 0;
+ if (Number.isFinite(node.duration) && node.duration > safePlaybackStart) {
+ return Math.max(0, node.duration - safePlaybackStart);
+ }
+ return null;
+ };
+
+ const resolveMediaWindowDurationSeconds = (): number | null => {
+ const mediaNodes = Array.from(
+ document.querySelectorAll("video[data-start], audio[data-start]"),
+ ) as HTMLMediaElement[];
+ if (mediaNodes.length === 0) return null;
+ let maxWindowEndSeconds = 0;
+ for (const node of mediaNodes) {
+ const start = resolveStartForElement(node, 0);
+ if (!Number.isFinite(start)) continue;
+ const duration = resolveMediaElementDurationSeconds(node);
+ if (duration == null || duration <= MIN_VALID_TIMELINE_DURATION_SECONDS) continue;
+ maxWindowEndSeconds = Math.max(maxWindowEndSeconds, Math.max(0, start) + duration);
+ }
+ return maxWindowEndSeconds > MIN_VALID_TIMELINE_DURATION_SECONDS ? maxWindowEndSeconds : null;
+ };
+
+ const resolveMediaDurationFloorSeconds = (): number | null => {
+ const mediaWindowDuration = resolveMediaWindowDurationSeconds();
+ if (
+ typeof mediaWindowDuration !== "number" ||
+ !Number.isFinite(mediaWindowDuration) ||
+ mediaWindowDuration <= MIN_VALID_TIMELINE_DURATION_SECONDS
+ ) {
+ return null;
+ }
+ return mediaWindowDuration;
+ };
+
+ const resolveMinCandidateDurationSeconds = (mediaDurationFloorSeconds: number | null): number => {
+ if (!isUsableTimelineDuration(mediaDurationFloorSeconds)) {
+ return MIN_VALID_TIMELINE_DURATION_SECONDS;
+ }
+ return Math.max(MIN_VALID_TIMELINE_DURATION_SECONDS, mediaDurationFloorSeconds * TIMELINE_FLOOR_COVERAGE_RATIO);
+ };
+
+ const getSafeTimelineDurationSeconds = (timeline: RuntimeTimelineLike | null, fallback = 0): number => {
+ const timelineDuration = getTimelineDurationSeconds(timeline);
+ const mediaFloor = resolveMediaDurationFloorSeconds();
+ const fallbackDuration = Number.isFinite(fallback) && fallback > MIN_VALID_TIMELINE_DURATION_SECONDS ? fallback : 0;
+ let safeDuration = 0;
+ // Timeline is the source of truth for authored composition duration.
+ if (isUsableTimelineDuration(timelineDuration)) {
+ safeDuration = Math.max(timelineDuration, fallbackDuration);
+ } else if (isUsableTimelineDuration(mediaFloor)) {
+ safeDuration = Math.max(mediaFloor, fallbackDuration);
+ } else {
+ safeDuration = fallbackDuration;
+ }
+ const hardDurationCap = Math.max(1, Number(state.maxTimelineDurationSeconds) || 1800);
+ return safeDuration > 0 ? Math.max(0, Math.min(safeDuration, hardDurationCap)) : 0;
+ };
+
+ const resolveRootTimelineFromDocument = (): TimelineResolution => {
+ const timelines = (window.__timelines ?? {}) as Record<string, RuntimeTimelineLike | undefined>;
+ const startResolver = createRuntimeStartTimeResolver({ timelineRegistry: timelines });
+ const mediaDurationFloorSeconds = resolveMediaDurationFloorSeconds();
+ const minCandidateDurationSeconds = resolveMinCandidateDurationSeconds(mediaDurationFloorSeconds);
+ const resolveCompositionStartSeconds = (compositionId: string): number => {
+ const node = document.querySelector(`[data-composition-id="${CSS.escape(compositionId)}"]`) as Element | null;
+ if (!node) return 0;
+ return startResolver.resolveStartForElement(node, 0);
+ };
+ const createCompositeTimelineFromCandidates = (
+ candidates: Array<{ compositionId: string; timeline: RuntimeTimelineLike; durationSeconds: number }>,
+ ): RuntimeTimelineLike | null => {
+ const gsapApi = window.gsap;
+ if (!gsapApi || typeof gsapApi.timeline !== "function") return null;
+ const compositeTimeline = gsapApi.timeline({ paused: true }) as RuntimeTimelineLike;
+ for (const candidate of candidates) {
+ compositeTimeline.add(candidate.timeline, resolveCompositionStartSeconds(candidate.compositionId));
+ }
+ return compositeTimeline;
+ };
+ const createDurationFloorTimeline = (
+ durationSeconds: number,
+ existingRootTimeline: RuntimeTimelineLike | null,
+ ): RuntimeTimelineLike | null => {
+ if (!isUsableTimelineDuration(durationSeconds)) return null;
+ const gsapApi = window.gsap;
+ if (!gsapApi || typeof gsapApi.timeline !== "function") return null;
+ const fallbackTimeline = gsapApi.timeline({ paused: true }) as RuntimeTimelineLike;
+ if (existingRootTimeline) {
+ try {
+ fallbackTimeline.add(existingRootTimeline, 0);
+ } catch {
+ // keep fallback resilient if root add fails
+ }
+ }
+ const withTween = fallbackTimeline as RuntimeTimelineLike & {
+ to?: (target: object, vars: { duration?: number }) => unknown;
+ };
+ if (typeof withTween.to === "function") {
+ try {
+ withTween.to({}, { duration: durationSeconds });
+ } catch {
+ // no-op; if tween creation fails, caller will discard by unusable duration
+ }
+ }
+ return fallbackTimeline;
+ };
+ const addMissingChildCandidatesToRootTimeline = (
+ rootTimeline: RuntimeTimelineLike,
+ candidates: Array<{ compositionId: string; timeline: RuntimeTimelineLike; durationSeconds: number }>,
+ ): string[] => {
+ const rootWithChildren = rootTimeline as RuntimeTimelineLike & {
+ getChildren?: (...args: unknown[]) => unknown[];
+ };
+ if (typeof rootWithChildren.getChildren !== "function") return [];
+ try {
+ const existingChildren = rootWithChildren.getChildren(true, true, true) ?? [];
+ if (!Array.isArray(existingChildren)) return [];
+ const addedIds: string[] = [];
+ for (const candidate of candidates) {
+ const alreadyIncluded = existingChildren.some((child) => child === candidate.timeline);
+ if (alreadyIncluded) continue;
+ try {
+ const startSec = resolveCompositionStartSeconds(candidate.compositionId);
+ rootTimeline.add(candidate.timeline, startSec);
+ addedIds.push(candidate.compositionId);
+ } catch {
+ // ignore broken child add attempts
+ }
+ }
+ return addedIds;
+ } catch {
+ return [];
+ }
+ };
+ const rootCompositionNode = resolveRootCompositionElement();
+ const rootCompositionId = rootCompositionNode?.getAttribute("data-composition-id") ?? null;
+ if (!rootCompositionId) {
+ return { timeline: null };
+ }
+ const rootTimeline = timelines[rootCompositionId] ?? null;
+ const collectRootChildCandidates = (): Array<{
+ compositionId: string;
+ timeline: RuntimeTimelineLike;
+ durationSeconds: number;
+ }> => {
+ if (!rootCompositionNode) return [];
+ const seen = new Set<string>();
+ const childNodes = Array.from(rootCompositionNode.querySelectorAll("[data-composition-id]"));
+ const candidates: Array<{ compositionId: string; timeline: RuntimeTimelineLike; durationSeconds: number }> = [];
+ for (const childNode of childNodes) {
+ const childId = childNode.getAttribute("data-composition-id");
+ if (!childId || childId === rootCompositionId) continue;
+ if (seen.has(childId)) continue;
+ seen.add(childId);
+ const candidateTimeline = timelines[childId] ?? null;
+ if (!candidateTimeline) continue;
+ if (typeof candidateTimeline.play !== "function" || typeof candidateTimeline.pause !== "function") {
+ continue;
+ }
+ const candidateDuration = getTimelineDurationSeconds(candidateTimeline);
+ candidates.push({
+ compositionId: childId,
+ timeline: candidateTimeline,
+ durationSeconds: candidateDuration ?? 0,
+ });
+ }
+ return candidates;
+ };
+ const rootChildCandidates = collectRootChildCandidates();
+ const ensureChildCandidatesActive = (
+ candidates: Array<{ compositionId: string; timeline: RuntimeTimelineLike; durationSeconds: number }>,
+ ): void => {
+ for (const candidate of candidates) {
+ const timelineWithPaused = candidate.timeline as RuntimeTimelineLike & {
+ paused?: (value?: boolean) => unknown;
+ };
+ if (typeof timelineWithPaused.paused !== "function") continue;
+ try {
+ timelineWithPaused.paused(false);
+ } catch {
+ // keep runtime resilient against timeline API quirks
+ }
+ }
+ };
+ if (rootChildCandidates.length > 0) {
+ ensureChildCandidatesActive(rootChildCandidates);
+ }
+ if (rootTimeline) {
+ const autoNestedChildren =
+ rootChildCandidates.length > 0
+ ? addMissingChildCandidatesToRootTimeline(rootTimeline, rootChildCandidates)
+ : [];
+ // Mark children as bound so the polling loop stops re-resolving
+ if (rootChildCandidates.length > 0 || !document.querySelector("[data-composition-id]:not([data-composition-id='" + rootCompositionId + "'])")) {
+ childrenBound = true;
+ }
+
+ // Force GSAP to render the current frame so child animations show their correct state.
+ // Without this, children added after the root was created may still show initial styles.
+ if (autoNestedChildren.length > 0) {
+ try {
+ const currentTime = rootTimeline.time();
+ rootTimeline.seek(currentTime, false); // false = don't suppress events
+ } catch { /* ignore */ }
+ }
+ const rootDurationSeconds = getTimelineDurationSeconds(rootTimeline);
+ if (!isUsableTimelineDuration(rootDurationSeconds) && rootChildCandidates.length > 0) {
+ const selectedTimelineIds = rootChildCandidates.map((candidate) => candidate.compositionId);
+ const compositeTimeline = createCompositeTimelineFromCandidates(rootChildCandidates);
+ const compositeDurationSeconds = getTimelineDurationSeconds(compositeTimeline);
+ if (compositeTimeline && isUsableTimelineDuration(compositeDurationSeconds)) {
+ return {
+ timeline: compositeTimeline,
+ selectedTimelineIds,
+ selectedDurationSeconds: compositeDurationSeconds,
+ mediaDurationFloorSeconds,
+ diagnostics: {
+ code: "root_timeline_unusable_fallback",
+ details: {
+ rootCompositionId,
+ rootDurationSeconds,
+ fallbackKind: "composite_by_root_children",
+ minCandidateDurationSeconds,
+ selectedDurationSeconds: compositeDurationSeconds,
+ mediaDurationFloorSeconds,
+ selectedTimelineIds,
+ autoNestedChildren,
+ },
+ },
+ };
+ }
+ const durationFloorTimeline = createDurationFloorTimeline(mediaDurationFloorSeconds ?? 0, rootTimeline);
+ const durationFloorSeconds = getTimelineDurationSeconds(durationFloorTimeline);
+ if (durationFloorTimeline && isUsableTimelineDuration(durationFloorSeconds)) {
+ return {
+ timeline: durationFloorTimeline,
+ selectedTimelineIds: [rootCompositionId],
+ selectedDurationSeconds: durationFloorSeconds,
+ mediaDurationFloorSeconds,
+ diagnostics: {
+ code: "root_timeline_unusable_media_floor_fallback",
+ details: {
+ rootCompositionId,
+ rootDurationSeconds,
+ fallbackKind: "media_duration_floor",
+ mediaDurationFloorSeconds,
+ selectedDurationSeconds: durationFloorSeconds,
+ selectedTimelineIds: [rootCompositionId],
+ autoNestedChildren,
+ },
+ },
+ };
+ }
+ }
+ if (!isUsableTimelineDuration(rootDurationSeconds) && rootChildCandidates.length === 0) {
+ const durationFloorTimeline = createDurationFloorTimeline(mediaDurationFloorSeconds ?? 0, rootTimeline);
+ const durationFloorSeconds = getTimelineDurationSeconds(durationFloorTimeline);
+ if (durationFloorTimeline && isUsableTimelineDuration(durationFloorSeconds)) {
+ return {
+ timeline: durationFloorTimeline,
+ selectedTimelineIds: [rootCompositionId],
+ selectedDurationSeconds: durationFloorSeconds,
+ mediaDurationFloorSeconds,
+ diagnostics: {
+ code: "root_timeline_unusable_media_floor_fallback",
+ details: {
+ rootCompositionId,
+ rootDurationSeconds,
+ fallbackKind: "media_duration_floor",
+ mediaDurationFloorSeconds,
+ selectedDurationSeconds: durationFloorSeconds,
+ selectedTimelineIds: [rootCompositionId],
+ },
+ },
+ };
+ }
+ }
+ return {
+ timeline: rootTimeline,
+ selectedTimelineIds: [rootCompositionId],
+ selectedDurationSeconds: rootDurationSeconds,
+ mediaDurationFloorSeconds,
+ diagnostics:
+ autoNestedChildren.length > 0
+ ? {
+ code: "root_timeline_auto_nested_children",
+ details: {
+ rootCompositionId,
+ selectedDurationSeconds: rootDurationSeconds,
+ autoNestedChildren,
+ },
+ }
+ : undefined,
+ };
+ }
+ if (rootChildCandidates.length > 0) {
+ const selectedTimelineIds = rootChildCandidates.map((candidate) => candidate.compositionId);
+ const compositeTimeline = createCompositeTimelineFromCandidates(rootChildCandidates);
+ const compositeDurationSeconds = getTimelineDurationSeconds(compositeTimeline);
+ if (compositeTimeline) {
+ return {
+ timeline: compositeTimeline,
+ selectedTimelineIds,
+ selectedDurationSeconds: compositeDurationSeconds,
+ mediaDurationFloorSeconds,
+ diagnostics: {
+ code: "root_timeline_missing_fallback",
+ details: {
+ rootCompositionId,
+ fallbackKind: "composite_by_root_children",
+ minCandidateDurationSeconds,
+ selectedDurationSeconds: compositeDurationSeconds,
+ mediaDurationFloorSeconds,
+ selectedTimelineIds,
+ },
+ },
+ };
+ }
+ }
+ return { timeline: null };
+ };
+
+ const syncCurrentTimeFromTimeline = () => {
+ const timeline = state.capturedTimeline;
+ if (!timeline || typeof timeline.time !== "function") return;
+ const nextTime = Number(timeline.time());
+ if (!Number.isFinite(nextTime)) return;
+ state.currentTime = Math.max(0, nextTime);
+ };
+
+ // Track whether child composition timelines have been added to the root.
+ // This prevents the polling loop from skipping rebind when TARGET_DURATION
+ // makes the root "usable" before children register. Assumption: child scripts
+ // must register timelines synchronously or in the immediate microtask queue
+ // (setTimeout(0)). Scripts using requestAnimationFrame or longer delays may
+ // not be discovered.
+ let childrenBound = false;
+ const bindRootTimelineIfAvailable = (): boolean => {
+ if (!externalCompositionsReady) return false;
+ const currentTimeline = state.capturedTimeline;
+ const currentDuration = getTimelineDurationSeconds(currentTimeline);
+ const currentTimelineUsable = isUsableTimelineDuration(currentDuration);
+ // Skip rebind ONLY if we already have a usable timeline AND children have been bound.
+ // Without childrenBound check, the TARGET_DURATION spacer makes the timeline "usable"
+ // before child composition timelines are added, causing them to never be discovered.
+ if (currentTimeline && currentTimelineUsable && childrenBound) return false;
+ const resolution = resolveRootTimelineFromDocument();
+ if (!resolution.timeline) return false;
+ if (currentTimeline && currentTimeline === resolution.timeline) {
+ if (typeof currentTimeline.timeScale === "function") {
+ currentTimeline.timeScale(state.playbackRate);
+ }
+ return false;
+ }
+ state.capturedTimeline = resolution.timeline;
+ if (typeof state.capturedTimeline.timeScale === "function") {
+ state.capturedTimeline.timeScale(state.playbackRate);
+ }
+ if (resolution.diagnostics) {
+ postRuntimeMessage({
+ source: "hf-preview",
+ type: "diagnostic",
+ code: resolution.diagnostics.code,
+ details: resolution.diagnostics.details,
+ });
+ }
+ postRuntimeMessage({
+ source: "hf-preview",
+ type: "diagnostic",
+ code: "timeline_bound",
+ details: {
+ selectedTimelineIds: resolution.selectedTimelineIds ?? [],
+ selectedDurationSeconds: resolution.selectedDurationSeconds ?? null,
+ mediaDurationFloorSeconds: resolution.mediaDurationFloorSeconds ?? null,
+ },
+ });
+ return true;
+ };
+
+ const emitRootStageLayoutDiagnostics = () => {
+ const rootNode = resolveRootCompositionElement();
+ if (!(rootNode instanceof HTMLElement)) {
+ return;
+ }
+ const rect = rootNode.getBoundingClientRect();
+ const declaredWidth = Number(rootNode.getAttribute("data-width"));
+ const declaredHeight = Number(rootNode.getAttribute("data-height"));
+ const computedStyle = window.getComputedStyle(rootNode);
+ const hasDeclaredDimensions =
+ Number.isFinite(declaredWidth) && declaredWidth > 0 && Number.isFinite(declaredHeight) && declaredHeight > 0;
+ const looksCollapsed =
+ rect.width <= 0 || rect.height <= 0 || rootNode.clientWidth <= 0 || rootNode.clientHeight <= 0;
+ if (!hasDeclaredDimensions || !looksCollapsed) {
+ return;
+ }
+ postRuntimeDiagnosticOnce(
+ "root_stage_layout_zero",
+ {
+ compositionId: rootNode.getAttribute("data-composition-id") ?? null,
+ declaredWidth,
+ declaredHeight,
+ rectWidth: Math.round(rect.width),
+ rectHeight: Math.round(rect.height),
+ clientWidth: rootNode.clientWidth,
+ clientHeight: rootNode.clientHeight,
+ display: computedStyle.display,
+ visibility: computedStyle.visibility,
+ overflow: computedStyle.overflow,
+ },
+ `root-stage-layout-zero:${rootNode.getAttribute("data-composition-id") ?? "unknown"}`,
+ );
+ };
+
+ const scheduleRootStageLayoutDiagnostics = () => {
+ if (state.tornDown) {
+ return;
+ }
+ if (rootStageDiagnosticRafId != null) {
+ window.cancelAnimationFrame(rootStageDiagnosticRafId);
+ }
+ rootStageDiagnosticRafId = window.requestAnimationFrame(() => {
+ rootStageDiagnosticRafId = null;
+ emitRootStageLayoutDiagnostics();
+ });
+ };
+
+ const installRuntimeErrorDiagnostics = () => {
+ runtimeErrorListener = (event: ErrorEvent) => {
+ const normalized = normalizeDiagnosticMessage(event.error ?? event.message).slice(
+ 0,
+ MAX_DIAGNOSTIC_MESSAGE_LENGTH,
+ );
+ if (!normalized) {
+ return;
+ }
+ const classified = classifyRuntimeScriptFailure(normalized);
+ postRuntimeMessage({
+ source: "hf-preview",
+ type: "diagnostic",
+ code: classified.code,
+ details: {
+ category: classified.category,
+ message: normalized,
+ filename: event.filename || null,
+ line: Number.isFinite(event.lineno) ? event.lineno : null,
+ column: Number.isFinite(event.colno) ? event.colno : null,
+ },
+ });
+ };
+ runtimeUnhandledRejectionListener = (event: PromiseRejectionEvent) => {
+ const normalized = normalizeDiagnosticMessage(event.reason).slice(0, MAX_DIAGNOSTIC_MESSAGE_LENGTH);
+ if (!normalized) {
+ return;
+ }
+ const classified = classifyRuntimeScriptFailure(normalized);
+ postRuntimeMessage({
+ source: "hf-preview",
+ type: "diagnostic",
+ code: `${classified.code}_unhandled_rejection`,
+ details: {
+ category: `${classified.category}-unhandled-rejection`,
+ message: normalized,
+ },
+ });
+ };
+ window.addEventListener("error", runtimeErrorListener);
+ window.addEventListener("unhandledrejection", runtimeUnhandledRejectionListener);
+ };
+
+ const installAssetFailureDiagnostics = () => {
+ const assetNodes = Array.from(document.querySelectorAll("img, video, audio, source, link[rel='stylesheet']"));
+ for (const node of assetNodes) {
+ const onError = () => {
+ if (!(node instanceof Element)) {
+ return;
+ }
+ const tagName = node.tagName.toLowerCase();
+ const assetUrl = node.getAttribute("src") ?? node.getAttribute("href") ?? node.getAttribute("poster") ?? null;
+ const diagnosticCode = tagName === "link" ? "runtime_stylesheet_load_failed" : "runtime_asset_load_failed";
+ postRuntimeDiagnosticOnce(
+ diagnosticCode,
+ {
+ tagName,
+ assetUrl,
+ currentSrc:
+ node instanceof HTMLImageElement || node instanceof HTMLMediaElement ? node.currentSrc || null : null,
+ readyState: node instanceof HTMLMediaElement ? node.readyState : null,
+ networkState: node instanceof HTMLMediaElement ? node.networkState : null,
+ },
+ `${diagnosticCode}:${tagName}:${assetUrl ?? "unknown"}`,
+ );
+ };
+ node.addEventListener("error", onError);
+ registerRuntimeCleanup(() => {
+ node.removeEventListener("error", onError);
+ });
+ }
+
+ const fontSet = document.fonts;
+ if (!fontSet) {
+ return;
+ }
+ void fontSet.ready
+ .then(() => {
+ if (state.tornDown) {
+ return;
+ }
+ const failedFamilies = Array.from(fontSet)
+ .filter((face) => face.status === "error")
+ .map((face) => face.family)
+ .filter((family) => Boolean(family))
+ .slice(0, 10);
+ if (failedFamilies.length === 0) {
+ return;
+ }
+ postRuntimeDiagnosticOnce(
+ "runtime_font_load_issue",
+ {
+ failedFamilies,
+ totalFaces: Array.from(fontSet).length,
+ },
+ `runtime-font-load-issue:${failedFamilies.join("|")}`,
+ );
+ })
+ .catch(() => {
+ // ignore font readiness failures
+ });
+ };
+
+ const rebindTimelineFromResolution = (resolution: TimelineResolution, reason: "loop_guard" | "manual"): boolean => {
+ if (!resolution.timeline) return false;
+ const previousTimeline = state.capturedTimeline;
+ if (previousTimeline && previousTimeline === resolution.timeline) {
+ return false;
+ }
+ const previousTime = Math.max(0, state.currentTime || 0);
+ const wasPlaying = state.isPlaying;
+ state.capturedTimeline = resolution.timeline;
+ if (typeof state.capturedTimeline.timeScale === "function") {
+ state.capturedTimeline.timeScale(state.playbackRate);
+ }
+ try {
+ state.capturedTimeline.pause();
+ state.capturedTimeline.seek(previousTime, false);
+ if (wasPlaying) {
+ state.capturedTimeline.play();
+ }
+ } catch {
+ // keep runtime resilient even if a timeline implementation throws
+ }
+ postRuntimeMessage({
+ source: "hf-preview",
+ type: "diagnostic",
+ code: "timeline_loop_guard_rebind",
+ details: {
+ reason,
+ previousTime,
+ selectedTimelineIds: resolution.selectedTimelineIds ?? [],
+ selectedDurationSeconds: resolution.selectedDurationSeconds ?? null,
+ mediaDurationFloorSeconds: resolution.mediaDurationFloorSeconds ?? null,
+ },
+ });
+ return true;
+ };
+
+ let metadataRebindDebounceTimerId: number | null = null;
+ let metadataRebindApplied = false;
+ const metadataBoundMedia = new Set<HTMLMediaElement>();
+
+ const scheduleMetadataDurationHydration = () => {
+ if (state.tornDown) return;
+ if (metadataRebindDebounceTimerId != null) {
+ window.clearTimeout(metadataRebindDebounceTimerId);
+ }
+ metadataRebindDebounceTimerId = window.setTimeout(() => {
+ if (state.tornDown) return;
+ metadataRebindDebounceTimerId = null;
+ const resolution = resolveRootTimelineFromDocument();
+ if (!resolution.timeline) return;
+ const hasResolvedMediaFloor = isUsableTimelineDuration(resolution.mediaDurationFloorSeconds ?? null);
+ if (!hasResolvedMediaFloor) return;
+ if (!state.capturedTimeline) {
+ if (bindRootTimelineIfAvailable()) {
+ postTimeline();
+ postState(true);
+ }
+ return;
+ }
+ if (metadataRebindApplied) return;
+ const currentDuration = getTimelineDurationSeconds(state.capturedTimeline);
+ const nextDuration = resolution.selectedDurationSeconds ?? getTimelineDurationSeconds(resolution.timeline);
+ const isBetterCandidate =
+ isUsableTimelineDuration(nextDuration) &&
+ (!isUsableTimelineDuration(currentDuration) ||
+ nextDuration >= currentDuration + METADATA_REBIND_MIN_DURATION_GAIN_SECONDS);
+ if (!isBetterCandidate) return;
+ if (rebindTimelineFromResolution(resolution, "manual")) {
+ metadataRebindApplied = true;
+ postRuntimeMessage({
+ source: "hf-preview",
+ type: "diagnostic",
+ code: "timeline_rebind_after_media_metadata",
+ details: {
+ previousDurationSeconds: currentDuration ?? null,
+ selectedDurationSeconds: nextDuration ?? null,
+ selectedTimelineIds: resolution.selectedTimelineIds ?? [],
+ mediaDurationFloorSeconds: resolution.mediaDurationFloorSeconds ?? null,
+ },
+ });
+ postTimeline();
+ postState(true);
+ }
+ }, METADATA_REBIND_DEBOUNCE_MS);
+ };
+
+ const unbindMediaMetadataListeners = () => {
+ for (const mediaEl of metadataBoundMedia) {
+ mediaEl.removeEventListener("loadedmetadata", scheduleMetadataDurationHydration);
+ mediaEl.removeEventListener("durationchange", scheduleMetadataDurationHydration);
+ }
+ metadataBoundMedia.clear();
+ };
+
+ const bindMediaMetadataListeners = () => {
+ if (state.tornDown) return;
+ const mediaEls = Array.from(document.querySelectorAll("video, audio")) as HTMLMediaElement[];
+ for (const mediaEl of mediaEls) {
+ if (metadataBoundMedia.has(mediaEl)) continue;
+ metadataBoundMedia.add(mediaEl);
+ mediaEl.addEventListener("loadedmetadata", scheduleMetadataDurationHydration);
+ mediaEl.addEventListener("durationchange", scheduleMetadataDurationHydration);
+ }
+ };
+
+ const syncMediaForCurrentState = () => {
+ const cache = refreshRuntimeMediaCache({
+ resolveStartSeconds: (element) => resolveStartForElement(element, 0),
+ });
+ syncRuntimeMedia({
+ clips: cache.mediaClips,
+ timeSeconds: state.currentTime,
+ playing: state.isPlaying,
+ playbackRate: state.playbackRate,
+ });
+ const rootCompId = document.querySelector("[data-composition-id]")?.getAttribute("data-composition-id") ?? null;
+ const visibilityNodes = Array.from(document.querySelectorAll("[data-start]"));
+ for (const rawNode of visibilityNodes) {
+ if (!(rawNode instanceof HTMLElement)) continue;
+ const tag = rawNode.tagName.toLowerCase();
+ if (tag === "script" || tag === "style" || tag === "link" || tag === "meta") continue;
+
+ // Skip elements INSIDE sub-compositions — their visibility is managed by GSAP,
+ // not the global time-based adapter. Only manage visibility for:
+ // 1. Composition host elements (have data-composition-id themselves)
+ // 2. Direct children of root composition (audio, etc.)
+ // Skip: elements whose nearest composition ancestor is NOT the root
+ const ownCompId = rawNode.getAttribute("data-composition-id");
+ if (!ownCompId) {
+ // Not a composition host — check if it's inside a sub-composition
+ const parentComp = rawNode.closest("[data-composition-id]");
+ const parentCompId = parentComp?.getAttribute("data-composition-id") ?? null;
+ if (parentCompId && parentCompId !== rootCompId) continue;
+ }
+
+ const start = resolveStartForElement(rawNode, 0);
+ const duration = resolveDurationForElement(rawNode);
+ const end = duration != null && duration > 0 ? start + duration : Number.POSITIVE_INFINITY;
+ // For composition hosts, use the composition timeline's duration to compute end
+ let computedEnd = end;
+ const compId = rawNode.getAttribute("data-composition-id");
+ if (compId && !Number.isFinite(end)) {
+ const compTimeline = (window.__timelines ?? {})[compId];
+ if (compTimeline && typeof compTimeline.duration === "function") {
+ const compDur = compTimeline.duration();
+ if (compDur > 0) computedEnd = start + compDur;
+ }
+ }
+ const isVisibleNow = state.currentTime >= start && (Number.isFinite(computedEnd) ? state.currentTime < computedEnd : true);
+ rawNode.style.visibility = isVisibleNow ? "visible" : "hidden";
+ }
+ };
+
+ const postState = (force: boolean) => {
+ syncCurrentTimeFromTimeline();
+ const frame = Math.max(0, Math.round((state.currentTime || 0) * state.canonicalFps));
+ const now = Date.now();
+ const shouldPost =
+ force ||
+ frame !== state.bridgeLastPostedFrame ||
+ state.isPlaying !== state.bridgeLastPostedPlaying ||
+ state.bridgeMuted !== state.bridgeLastPostedMuted ||
+ now - state.bridgeLastPostedAt >= state.bridgeMaxPostIntervalMs;
+ if (!shouldPost) return;
+ state.bridgeLastPostedFrame = frame;
+ state.bridgeLastPostedPlaying = state.isPlaying;
+ state.bridgeLastPostedMuted = state.bridgeMuted;
+ state.bridgeLastPostedAt = now;
+ postRuntimeMessage({
+ source: "hf-preview",
+ type: "state",
+ frame,
+ isPlaying: state.isPlaying,
+ muted: state.bridgeMuted,
+ playbackRate: state.playbackRate,
+ });
+ };
+
+ const postTimeline = () => {
+ sanitizeCompositionDurationAttributes();
+ applyCompositionSizing();
+ applyClipLayout();
+ // Post resolved stage size so the parent can scale the iframe container
+ const stageSizeRootEl = resolveRootCompositionElement();
+ if (stageSizeRootEl) {
+ const w = parseDimensionPx(stageSizeRootEl.getAttribute("data-width"));
+ const h = parseDimensionPx(stageSizeRootEl.getAttribute("data-height"));
+ const width = w ? parseInt(w, 10) : 0;
+ const height = h ? parseInt(h, 10) : 0;
+ if (width > 0 && height > 0) {
+ postRuntimeMessage({ source: "hf-preview", type: "stage-size", width, height });
+ }
+ }
+ bindRootTimelineIfAvailable();
+ const payload = collectRuntimeTimelinePayload({
+ canonicalFps: state.canonicalFps,
+ maxTimelineDurationSeconds: state.maxTimelineDurationSeconds,
+ });
+ window.__clipManifest = payload;
+ postRuntimeMessage(payload);
+ scheduleRootStageLayoutDiagnostics();
+ };
+
+ const runAdapters = (method: "discover" | "pause" | "play", timeSeconds = 0) => {
+ for (const adapter of state.deterministicAdapters) {
+ try {
+ if (method === "discover") adapter.discover();
+ if (method === "pause") adapter.pause();
+ if (method === "play" && adapter.play) adapter.play();
+ } catch {
+ // keep runtime resilient against adapter-specific failures
+ }
+ if (method === "discover") {
+ try {
+ adapter.seek({ time: timeSeconds });
+ } catch {
+ // ignore seek bootstrap failures
+ }
+ }
+ }
+ };
+
+ if (!externalCompositionsReady) {
+ void loadExternalCompositions({
+ injectedStyles: state.injectedCompStyles,
+ injectedScripts: state.injectedCompScripts,
+ parseDimensionPx,
+ onDiagnostic: ({ code, details }) => {
+ postRuntimeMessage({
+ source: "hf-preview",
+ type: "diagnostic",
+ code,
+ details,
+ });
+ },
+ }).finally(() => {
+ externalCompositionsReady = true;
+ runAdapters("discover", state.currentTime);
+ bindMediaMetadataListeners();
+ installAssetFailureDiagnostics();
+ postTimeline();
+ postState(true);
+ });
+ }
+
+ const picker = createPickerModule({
+ postMessage: (payload) => postRuntimeMessage(payload),
+ });
+ picker.installPickerApi();
+
+ const applyPlaybackRate = (nextRate: number) => {
+ const parsed = Number(nextRate);
+ if (!Number.isFinite(parsed) || parsed <= 0) {
+ state.playbackRate = 1;
+ } else {
+ state.playbackRate = Math.max(0.1, Math.min(5, parsed));
+ }
+ if (state.capturedTimeline && typeof state.capturedTimeline.timeScale === "function") {
+ state.capturedTimeline.timeScale(state.playbackRate);
+ }
+ const mediaEls = document.querySelectorAll("video, audio");
+ for (const el of mediaEls) {
+ if (!(el instanceof HTMLMediaElement)) continue;
+ try {
+ el.playbackRate = state.playbackRate;
+ } catch {
+ // ignore unsupported values
+ }
+ }
+ };
+
+ const player = createRuntimePlayer({
+ getTimeline: () => state.capturedTimeline,
+ setTimeline: (timeline) => {
+ state.capturedTimeline = timeline;
+ },
+ getIsPlaying: () => state.isPlaying,
+ setIsPlaying: (playing) => {
+ state.isPlaying = playing;
+ },
+ getPlaybackRate: () => state.playbackRate,
+ setPlaybackRate: applyPlaybackRate,
+ getCanonicalFps: () => state.canonicalFps,
+ onSyncMedia: (timeSeconds, playing) => {
+ state.currentTime = Math.max(0, Number(timeSeconds) || 0);
+ state.isPlaying = playing;
+ syncMediaForCurrentState();
+ },
+ onStatePost: postState,
+ onDeterministicSeek: (timeSeconds) => {
+ for (const adapter of state.deterministicAdapters) {
+ try {
+ adapter.seek({ time: Number(timeSeconds) || 0 });
+ } catch {
+ // ignore adapter failure
+ }
+ }
+ },
+ onDeterministicPause: () => runAdapters("pause"),
+ onDeterministicPlay: () => runAdapters("play"),
+ onRenderFrameSeek: () => {},
+ onShowNativeVideos: () => {},
+ getSafeDuration: () => getSafeTimelineDurationSeconds(state.capturedTimeline, 0),
+ });
+
+ window.__player = createPlayerApiCompat(player);
+ (window as Window & { __playerReady?: boolean }).__playerReady = true;
+ (window as Window & { __renderReady?: boolean }).__renderReady = true;
+
+ // Wire analytics event emission through the bridge
+ initRuntimeAnalytics(postRuntimeMessage as (payload: unknown) => void);
+ emitAnalyticsEvent("composition_loaded", {
+ duration: player.getDuration(),
+ compositionId: document.querySelector("[data-composition-id]")?.getAttribute("data-composition-id") ?? null,
+ });
+
+ state.controlBridgeHandler = installRuntimeControlBridge({
+ onPlay: () => { player.play(); emitAnalyticsEvent("composition_played", { time: player.getTime() }); },
+ onPause: () => { player.pause(); emitAnalyticsEvent("composition_paused", { time: player.getTime() }); },
+ onSeek: (frame, _seekMode) => {
+ const time = Math.max(0, frame) / state.canonicalFps;
+ player.seek(time);
+ emitAnalyticsEvent("composition_seeked", { time });
+ },
+ onSetMuted: (muted) => {
+ state.bridgeMuted = muted;
+ const mediaEls = document.querySelectorAll("video, audio");
+ for (const el of mediaEls) {
+ if (!(el instanceof HTMLMediaElement)) continue;
+ el.muted = muted;
+ }
+ },
+ onSetPlaybackRate: (rate) => applyPlaybackRate(rate),
+ onEnablePickMode: () => picker.enablePickMode(),
+ onDisablePickMode: () => picker.disablePickMode(),
+ });
+
+ bindRootTimelineIfAvailable();
+ if (state.capturedTimeline) {
+ player._timeline = state.capturedTimeline;
+ }
+
+ // When the bundler inlines compositions, data-composition-src is removed so
+ // loadExternalCompositions() is skipped. But inline scripts registering child
+ // timelines in __timelines haven't executed yet (they run in the browser's next
+ // microtask). Defer a rebinding attempt to catch them.
+ if (externalCompositionsReady) {
+ setTimeout(() => {
+ const prevTimeline = state.capturedTimeline;
+ if (bindRootTimelineIfAvailable() && state.capturedTimeline !== prevTimeline) {
+ player._timeline = state.capturedTimeline;
+ }
+ // Re-run adapters to discover new elements
+ runAdapters("discover", state.currentTime);
+ postTimeline();
+ postState(true);
+ }, 0);
+ }
+
+ state.deterministicAdapters = [
+ createCssAdapter({
+ resolveStartSeconds: (element) => resolveStartForElement(element, 0),
+ }),
+ createWaapiAdapter(),
+ createGsapAdapter({ getTimeline: () => state.capturedTimeline }),
+ createThreeAdapter(),
+ createLottieAdapter(),
+ ] as RuntimeDeterministicAdapter[];
+ installRuntimeErrorDiagnostics();
+ runAdapters("discover");
+ bindMediaMetadataListeners();
+ if (state.timelinePollIntervalId) {
+ clearInterval(state.timelinePollIntervalId);
+ }
+ let timelinePollTick = 0;
+ let lastObservedTimelineTime: number | null = null;
+ let lastExplicitSeekAtMs = 0;
+ let loopGuardRebindTriggered = false;
+ let loopWrapCandidateCount = 0;
+ const markExplicitSeek = () => {
+ lastExplicitSeekAtMs = Date.now();
+ loopGuardRebindTriggered = false;
+ loopWrapCandidateCount = 0;
+ };
+ state.timelinePollIntervalId = setInterval(() => {
+ timelinePollTick += 1;
+ const shouldHoldRebindDuringEarlyPlay =
+ state.isPlaying &&
+ state.capturedTimeline != null &&
+ Math.max(0, state.currentTime || 0) < PLAY_REBIND_HOLD_SECONDS;
+ const timelineBoundThisTick = shouldHoldRebindDuringEarlyPlay ? false : bindRootTimelineIfAvailable();
+ if (state.capturedTimeline && !player._timeline) {
+ player._timeline = state.capturedTimeline;
+ }
+ if (timelineBoundThisTick || timelinePollTick % 20 === 0) {
+ postTimeline();
+ }
+ if (timelinePollTick % 10 === 0) {
+ bindMediaMetadataListeners();
+ }
+ syncCurrentTimeFromTimeline();
+ if (state.isPlaying && state.capturedTimeline) {
+ const currentObserved = Math.max(0, state.currentTime || 0);
+ const previousObserved = lastObservedTimelineTime;
+ const safeDuration = getSafeTimelineDurationSeconds(state.capturedTimeline, 0);
+ if (safeDuration > 0 && currentObserved >= safeDuration) {
+ player.pause();
+ player.seek(safeDuration);
+ lastObservedTimelineTime = safeDuration;
+ loopWrapCandidateCount = 0;
+ postState(true);
+ return;
+ }
+ const isWrapCandidate =
+ previousObserved != null &&
+ previousObserved >= LOOP_WRAP_PREVIOUS_TIME_THRESHOLD_SECONDS &&
+ currentObserved <= LOOP_WRAP_CURRENT_TIME_THRESHOLD_SECONDS;
+ if (isWrapCandidate) {
+ loopWrapCandidateCount += 1;
+ } else {
+ loopWrapCandidateCount = 0;
+ }
+ if (
+ !loopGuardRebindTriggered &&
+ loopWrapCandidateCount >= LOOP_GUARD_CONSECUTIVE_WRAP_THRESHOLD &&
+ Date.now() - lastExplicitSeekAtMs > LOOP_GUARD_SEEK_GRACE_PERIOD_MS
+ ) {
+ const resolution = resolveRootTimelineFromDocument();
+ if (rebindTimelineFromResolution(resolution, "loop_guard")) {
+ loopGuardRebindTriggered = true;
+ loopWrapCandidateCount = 0;
+ }
+ }
+ lastObservedTimelineTime = Math.max(0, state.currentTime || 0);
+ } else {
+ lastObservedTimelineTime = Math.max(0, state.currentTime || 0);
+ }
+ if (state.isPlaying) {
+ syncMediaForCurrentState();
+ }
+ postState(false);
+ }, 50);
+ postTimeline();
+ postState(true);
+
+ const originalSeek = player.seek;
+ player.seek = (timeSeconds: number) => {
+ markExplicitSeek();
+ originalSeek(timeSeconds);
+ };
+ const originalRenderSeek = player.renderSeek;
+ player.renderSeek = (timeSeconds: number) => {
+ markExplicitSeek();
+ originalRenderSeek(timeSeconds);
+ };
+
+ const teardown = () => {
+ if (state.tornDown) return;
+ state.tornDown = true;
+ if (state.timelinePollIntervalId) {
+ clearInterval(state.timelinePollIntervalId);
+ state.timelinePollIntervalId = null;
+ }
+ if (metadataRebindDebounceTimerId != null) {
+ window.clearTimeout(metadataRebindDebounceTimerId);
+ metadataRebindDebounceTimerId = null;
+ }
+ if (rootStageDiagnosticRafId != null) {
+ window.cancelAnimationFrame(rootStageDiagnosticRafId);
+ rootStageDiagnosticRafId = null;
+ }
+ unbindMediaMetadataListeners();
+ if (state.controlBridgeHandler) {
+ window.removeEventListener("message", state.controlBridgeHandler);
+ state.controlBridgeHandler = null;
+ }
+ if (runtimeErrorListener) {
+ window.removeEventListener("error", runtimeErrorListener);
+ runtimeErrorListener = null;
+ }
+ if (runtimeUnhandledRejectionListener) {
+ window.removeEventListener("unhandledrejection", runtimeUnhandledRejectionListener);
+ runtimeUnhandledRejectionListener = null;
+ }
+ if (state.beforeUnloadHandler) {
+ window.removeEventListener("beforeunload", state.beforeUnloadHandler);
+ state.beforeUnloadHandler = null;
+ }
+ picker.disablePickMode();
+ for (const adapter of state.deterministicAdapters) {
+ if (!adapter || typeof adapter.revert !== "function") continue;
+ try {
+ adapter.revert();
+ } catch {
+ // keep runtime resilient against adapter cleanup failures
+ }
+ }
+ state.deterministicAdapters = [];
+ for (const cleanup of runtimeCleanupCallbacks.splice(0)) {
+ try {
+ cleanup();
+ } catch {
+ // ignore cleanup failures
+ }
+ }
+ for (const styleEl of state.injectedCompStyles) {
+ try {
+ styleEl.remove();
+ } catch {
+ // ignore cleanup failures
+ }
+ }
+ state.injectedCompStyles = [];
+ for (const scriptEl of state.injectedCompScripts) {
+ try {
+ scriptEl.remove();
+ } catch {
+ // ignore cleanup failures
+ }
+ }
+ state.injectedCompScripts = [];
+ state.capturedTimeline = null;
+ if (runtimeWindow.__hfRuntimeTeardown === teardown) {
+ runtimeWindow.__hfRuntimeTeardown = null;
+ }
+ };
+ runtimeWindow.__hfRuntimeTeardown = teardown;
+ state.beforeUnloadHandler = teardown;
+ window.addEventListener("beforeunload", state.beforeUnloadHandler);
+}
diff --git a/packages/core/src/runtime/media.test.ts b/packages/core/src/runtime/media.test.ts
new file mode 100644
index 0000000000..fd32fd596d
--- /dev/null
+++ b/packages/core/src/runtime/media.test.ts
@@ -0,0 +1,171 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { refreshRuntimeMediaCache, syncRuntimeMedia } from "./media";
+import type { RuntimeMediaClip } from "./media";
+
+function createVideo(attrs: Record<string, string>): HTMLVideoElement {
+ const el = document.createElement("video");
+ for (const [key, value] of Object.entries(attrs)) {
+ el.setAttribute(key, value);
+ }
+ // jsdom doesn't compute media duration, so we stub it
+ Object.defineProperty(el, "duration", { value: NaN, writable: true, configurable: true });
+ document.body.appendChild(el);
+ return el;
+}
+
+function createAudio(attrs: Record<string, string>): HTMLAudioElement {
+ const el = document.createElement("audio");
+ for (const [key, value] of Object.entries(attrs)) {
+ el.setAttribute(key, value);
+ }
+ Object.defineProperty(el, "duration", { value: NaN, writable: true, configurable: true });
+ document.body.appendChild(el);
+ return el;
+}
+
+describe("refreshRuntimeMediaCache", () => {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ });
+
+ it("finds video elements with data-start", () => {
+ createVideo({ "data-start": "0", "data-duration": "5" });
+ const result = refreshRuntimeMediaCache();
+ expect(result.timedMediaEls).toHaveLength(1);
+ expect(result.mediaClips).toHaveLength(1);
+ expect(result.videoClips).toHaveLength(1);
+ });
+
+ it("finds audio elements with data-start", () => {
+ createAudio({ "data-start": "2", "data-duration": "3" });
+ const result = refreshRuntimeMediaCache();
+ expect(result.timedMediaEls).toHaveLength(1);
+ expect(result.mediaClips).toHaveLength(1);
+ expect(result.videoClips).toHaveLength(0);
+ });
+
+ it("ignores media without data-start", () => {
+ document.body.appendChild(document.createElement("video"));
+ const result = refreshRuntimeMediaCache();
+ expect(result.timedMediaEls).toHaveLength(0);
+ });
+
+ it("calculates clip end from start + duration", () => {
+ createVideo({ "data-start": "2", "data-duration": "3" });
+ const result = refreshRuntimeMediaCache();
+ const clip = result.mediaClips[0];
+ expect(clip.start).toBe(2);
+ expect(clip.duration).toBe(3);
+ expect(clip.end).toBe(5);
+ });
+
+ it("uses media-start offset", () => {
+ createVideo({ "data-start": "0", "data-duration": "5", "data-media-start": "10" });
+ const result = refreshRuntimeMediaCache();
+ expect(result.mediaClips[0].mediaStart).toBe(10);
+ });
+
+ it("parses volume attribute", () => {
+ createVideo({ "data-start": "0", "data-duration": "5", "data-volume": "0.5" });
+ const result = refreshRuntimeMediaCache();
+ expect(result.mediaClips[0].volume).toBe(0.5);
+ });
+
+ it("handles missing volume gracefully", () => {
+ createVideo({ "data-start": "0", "data-duration": "5" });
+ const result = refreshRuntimeMediaCache();
+ expect(result.mediaClips[0].volume).toBeNull();
+ });
+
+ it("maxMediaEnd tracks highest clip end", () => {
+ createVideo({ "data-start": "0", "data-duration": "5" });
+ createVideo({ "data-start": "3", "data-duration": "10" });
+ const result = refreshRuntimeMediaCache();
+ expect(result.maxMediaEnd).toBe(13);
+ });
+
+ it("uses custom resolveStartSeconds", () => {
+ createVideo({ "data-start": "0", "data-duration": "5" });
+ const result = refreshRuntimeMediaCache({ resolveStartSeconds: () => 10 });
+ expect(result.mediaClips[0].start).toBe(10);
+ });
+
+ it("falls back to element.duration when data-duration missing", () => {
+ const el = createVideo({ "data-start": "0" });
+ Object.defineProperty(el, "duration", { value: 8, writable: true });
+ const result = refreshRuntimeMediaCache();
+ expect(result.mediaClips[0].duration).toBe(8);
+ });
+});
+
+describe("syncRuntimeMedia", () => {
+ function createMockClip(overrides?: Partial<RuntimeMediaClip>): RuntimeMediaClip {
+ const el = document.createElement("video") as HTMLVideoElement;
+ document.body.appendChild(el);
+ Object.defineProperty(el, "paused", { value: true, writable: true, configurable: true });
+ el.play = vi.fn(() => Promise.resolve());
+ el.pause = vi.fn();
+ Object.defineProperty(el, "currentTime", { value: 0, writable: true, configurable: true });
+ Object.defineProperty(el, "playbackRate", { value: 1, writable: true, configurable: true });
+ return {
+ el,
+ start: 0,
+ mediaStart: 0,
+ duration: 10,
+ end: 10,
+ volume: null,
+ ...overrides,
+ };
+ }
+
+ afterEach(() => {
+ document.body.innerHTML = "";
+ });
+
+ it("plays active clip when playing", () => {
+ const clip = createMockClip({ start: 0, end: 10 });
+ syncRuntimeMedia({ clips: [clip], timeSeconds: 5, playing: true, playbackRate: 1 });
+ expect(clip.el.play).toHaveBeenCalled();
+ });
+
+ it("pauses active clip when not playing", () => {
+ const clip = createMockClip({ start: 0, end: 10 });
+ Object.defineProperty(clip.el, "paused", { value: false, writable: true });
+ syncRuntimeMedia({ clips: [clip], timeSeconds: 5, playing: false, playbackRate: 1 });
+ expect(clip.el.pause).toHaveBeenCalled();
+ });
+
+ it("pauses inactive clip", () => {
+ const clip = createMockClip({ start: 5, end: 10 });
+ Object.defineProperty(clip.el, "paused", { value: false, writable: true });
+ syncRuntimeMedia({ clips: [clip], timeSeconds: 2, playing: true, playbackRate: 1 });
+ expect(clip.el.pause).toHaveBeenCalled();
+ });
+
+ it("sets volume when clip has volume", () => {
+ const clip = createMockClip({ start: 0, end: 10, volume: 0.7 });
+ syncRuntimeMedia({ clips: [clip], timeSeconds: 5, playing: false, playbackRate: 1 });
+ expect(clip.el.volume).toBe(0.7);
+ });
+
+ it("seeks when currentTime drifts > 0.3s", () => {
+ const clip = createMockClip({ start: 0, end: 10, mediaStart: 0 });
+ Object.defineProperty(clip.el, "currentTime", { value: 0, writable: true });
+ syncRuntimeMedia({ clips: [clip], timeSeconds: 5, playing: false, playbackRate: 1 });
+ expect(clip.el.currentTime).toBe(5);
+ });
+
+ it("does not seek when currentTime is close enough", () => {
+ const clip = createMockClip({ start: 0, end: 10, mediaStart: 0 });
+ Object.defineProperty(clip.el, "currentTime", { value: 5.1, writable: true });
+ const original = clip.el.currentTime;
+ syncRuntimeMedia({ clips: [clip], timeSeconds: 5, playing: false, playbackRate: 1 });
+ expect(clip.el.currentTime).toBe(original);
+ });
+
+ it("sets playbackRate", () => {
+ const clip = createMockClip({ start: 0, end: 10 });
+ syncRuntimeMedia({ clips: [clip], timeSeconds: 5, playing: true, playbackRate: 2 });
+ expect(clip.el.playbackRate).toBe(2);
+ });
+});
diff --git a/packages/core/src/runtime/media.ts b/packages/core/src/runtime/media.ts
new file mode 100644
index 0000000000..9e2d47d9c0
--- /dev/null
+++ b/packages/core/src/runtime/media.ts
@@ -0,0 +1,83 @@
+export type RuntimeMediaClip = {
+ el: HTMLVideoElement | HTMLAudioElement;
+ start: number;
+ mediaStart: number;
+ duration: number;
+ end: number;
+ volume: number | null;
+};
+
+export function refreshRuntimeMediaCache(params?: { resolveStartSeconds?: (element: Element) => number }): {
+ timedMediaEls: Array<HTMLVideoElement | HTMLAudioElement>;
+ mediaClips: RuntimeMediaClip[];
+ videoClips: RuntimeMediaClip[];
+ maxMediaEnd: number;
+} {
+ const mediaEls = Array.from(document.querySelectorAll("video[data-start], audio[data-start]")) as Array<
+ HTMLVideoElement | HTMLAudioElement
+ >;
+ const mediaClips: RuntimeMediaClip[] = [];
+ const videoClips: RuntimeMediaClip[] = [];
+ let maxMediaEnd = 0;
+ for (const el of mediaEls) {
+ const start = params?.resolveStartSeconds
+ ? params.resolveStartSeconds(el)
+ : Number.parseFloat(el.dataset.start ?? "0");
+ if (!Number.isFinite(start)) continue;
+ const mediaStart = Number.parseFloat(el.dataset.playbackStart ?? el.dataset.mediaStart ?? "0") || 0;
+ let duration = Number.parseFloat(el.dataset.duration ?? "");
+ if ((!Number.isFinite(duration) || duration <= 0) && Number.isFinite(el.duration) && el.duration > 0) {
+ duration = Math.max(0, el.duration - mediaStart);
+ }
+ const end = Number.isFinite(duration) && duration > 0 ? start + duration : Number.POSITIVE_INFINITY;
+ const volumeRaw = Number.parseFloat(el.dataset.volume ?? "");
+ const clip: RuntimeMediaClip = {
+ el,
+ start,
+ mediaStart,
+ duration: Number.isFinite(duration) && duration > 0 ? duration : Number.POSITIVE_INFINITY,
+ end,
+ volume: Number.isFinite(volumeRaw) ? volumeRaw : null,
+ };
+ mediaClips.push(clip);
+ if (el.tagName === "VIDEO") videoClips.push(clip);
+ if (Number.isFinite(end)) maxMediaEnd = Math.max(maxMediaEnd, end);
+ }
+ return { timedMediaEls: mediaEls, mediaClips, videoClips, maxMediaEnd };
+}
+
+export function syncRuntimeMedia(params: {
+ clips: RuntimeMediaClip[];
+ timeSeconds: number;
+ playing: boolean;
+ playbackRate: number;
+}): void {
+ for (const clip of params.clips) {
+ const { el } = clip;
+ if (!el.isConnected) continue;
+ const relTime = params.timeSeconds - clip.start + clip.mediaStart;
+ const isActive = params.timeSeconds >= clip.start && params.timeSeconds < clip.end && relTime >= 0;
+ if (isActive) {
+ if (clip.volume != null) el.volume = clip.volume;
+ try {
+ el.playbackRate = params.playbackRate;
+ } catch {
+ // ignore unsupported playbackRate
+ }
+ if (Math.abs((el.currentTime || 0) - relTime) > 0.3) {
+ try {
+ el.currentTime = relTime;
+ } catch {
+ // ignore browser seek restrictions
+ }
+ }
+ if (params.playing && el.paused) {
+ void el.play().catch(() => {});
+ } else if (!params.playing && !el.paused) {
+ el.pause();
+ }
+ continue;
+ }
+ if (!el.paused) el.pause();
+ }
+}
diff --git a/packages/core/src/runtime/picker.test.ts b/packages/core/src/runtime/picker.test.ts
new file mode 100644
index 0000000000..d5b0d58af8
--- /dev/null
+++ b/packages/core/src/runtime/picker.test.ts
@@ -0,0 +1,153 @@
+import { describe, it, expect, vi, afterEach } from "vitest";
+import { createPickerModule } from "./picker";
+
+function createMockPostMessage() {
+ return vi.fn();
+}
+
+describe("createPickerModule", () => {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ document.head.querySelectorAll("style").forEach(s => s.remove());
+ document.body.classList.remove("__hf-pick-active");
+ });
+
+ it("returns enablePickMode, disablePickMode, installPickerApi", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ expect(typeof picker.enablePickMode).toBe("function");
+ expect(typeof picker.disablePickMode).toBe("function");
+ expect(typeof picker.installPickerApi).toBe("function");
+ });
+
+ describe("enablePickMode / disablePickMode", () => {
+ it("adds and removes pick-active class on body", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.enablePickMode();
+ expect(document.body.classList.contains("__hf-pick-active")).toBe(true);
+
+ picker.disablePickMode();
+ expect(document.body.classList.contains("__hf-pick-active")).toBe(false);
+ });
+
+ it("injects and removes style element", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.enablePickMode();
+ const styles = document.head.querySelectorAll("style");
+ const hasPickStyle = Array.from(styles).some(s =>
+ s.textContent?.includes("__hf-pick-highlight")
+ );
+ expect(hasPickStyle).toBe(true);
+
+ picker.disablePickMode();
+ const stylesAfter = document.head.querySelectorAll("style");
+ const hasPickStyleAfter = Array.from(stylesAfter).some(s =>
+ s.textContent?.includes("__hf-pick-highlight")
+ );
+ expect(hasPickStyleAfter).toBe(false);
+ });
+
+ it("enabling twice is idempotent", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.enablePickMode();
+ picker.enablePickMode();
+ expect(document.body.classList.contains("__hf-pick-active")).toBe(true);
+ });
+
+ it("disabling when not active is safe", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ expect(() => picker.disablePickMode()).not.toThrow();
+ });
+ });
+
+ describe("installPickerApi", () => {
+ it("installs __HF_PICKER_API on window", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.installPickerApi();
+ const api = (window as any).__HF_PICKER_API;
+ expect(api).toBeDefined();
+ expect(typeof api.enable).toBe("function");
+ expect(typeof api.disable).toBe("function");
+ expect(typeof api.isActive).toBe("function");
+ expect(typeof api.getHovered).toBe("function");
+ expect(typeof api.getSelected).toBe("function");
+ expect(typeof api.getCandidatesAtPoint).toBe("function");
+ expect(typeof api.pickAtPoint).toBe("function");
+ expect(typeof api.pickManyAtPoint).toBe("function");
+ });
+
+ it("isActive returns pick mode state", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.installPickerApi();
+ const api = (window as any).__HF_PICKER_API;
+
+ expect(api.isActive()).toBe(false);
+ picker.enablePickMode();
+ expect(api.isActive()).toBe(true);
+ picker.disablePickMode();
+ expect(api.isActive()).toBe(false);
+ });
+
+ it("getCandidatesAtPoint returns empty for invalid coords", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.installPickerApi();
+ const api = (window as any).__HF_PICKER_API;
+ expect(api.getCandidatesAtPoint(NaN, NaN)).toEqual([]);
+ expect(api.getCandidatesAtPoint(Infinity, 0)).toEqual([]);
+ });
+
+ it("pickAtPoint returns null for invalid coords", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.installPickerApi();
+ const api = (window as any).__HF_PICKER_API;
+ expect(api.pickAtPoint(NaN, NaN)).toBeNull();
+ });
+
+ it("pickManyAtPoint returns empty for invalid coords", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.installPickerApi();
+ const api = (window as any).__HF_PICKER_API;
+ expect(api.pickManyAtPoint(NaN, NaN)).toEqual([]);
+ });
+
+ it("getHovered returns null initially", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.installPickerApi();
+ const api = (window as any).__HF_PICKER_API;
+ expect(api.getHovered()).toBeNull();
+ });
+
+ it("getSelected returns null initially", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.installPickerApi();
+ const api = (window as any).__HF_PICKER_API;
+ expect(api.getSelected()).toBeNull();
+ });
+ });
+
+ describe("escape key handler", () => {
+ it("disables pick mode and posts cancel message on Escape", () => {
+ const postMessage = createMockPostMessage();
+ const picker = createPickerModule({ postMessage });
+ picker.enablePickMode();
+
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
+
+ expect(document.body.classList.contains("__hf-pick-active")).toBe(false);
+ expect(postMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ source: "hf-preview",
+ type: "pick-mode-cancelled",
+ })
+ );
+ });
+
+ it("ignores non-Escape keys", () => {
+ const postMessage = createMockPostMessage();
+ const picker = createPickerModule({ postMessage });
+ picker.enablePickMode();
+
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ expect(document.body.classList.contains("__hf-pick-active")).toBe(true);
+ });
+ });
+});
diff --git a/packages/core/src/runtime/picker.ts b/packages/core/src/runtime/picker.ts
new file mode 100644
index 0000000000..f45cb76d9a
--- /dev/null
+++ b/packages/core/src/runtime/picker.ts
@@ -0,0 +1,257 @@
+import type { RuntimeJson, RuntimeOutboundMessage, RuntimePickerElementInfo } from "./types";
+
+type PickerModuleDeps = {
+ postMessage: (payload: RuntimeOutboundMessage) => void;
+};
+
+export type PickerModule = {
+ enablePickMode: () => void;
+ disablePickMode: () => void;
+ installPickerApi: () => void;
+};
+
+export function createPickerModule(deps: PickerModuleDeps): PickerModule {
+ let pickModeActive = false;
+ let pickModeHighlightEl: Element | null = null;
+ let pickModeStyleEl: HTMLStyleElement | null = null;
+ let pickLastHoveredInfo: RuntimePickerElementInfo | null = null;
+ let pickLastSelectedInfo: RuntimePickerElementInfo | null = null;
+
+ function emitPickerRuntimeEvent(eventName: string, detail: RuntimeJson): void {
+ try {
+ window.dispatchEvent(new CustomEvent(eventName, { detail }));
+ } catch {
+ // no-op in unsupported contexts
+ }
+ }
+
+ function setLastHoveredInfo(info: RuntimePickerElementInfo | null): void {
+ pickLastHoveredInfo = info;
+ emitPickerRuntimeEvent("hyperframe:picker:hovered", {
+ elementInfo: pickLastHoveredInfo,
+ isPickMode: pickModeActive,
+ timestamp: Date.now(),
+ });
+ }
+
+ function setLastSelectedInfo(info: RuntimePickerElementInfo | null): void {
+ pickLastSelectedInfo = info;
+ emitPickerRuntimeEvent("hyperframe:picker:selected", {
+ elementInfo: pickLastSelectedInfo,
+ isPickMode: pickModeActive,
+ timestamp: Date.now(),
+ });
+ }
+
+ function isPickableElement(el: Element | null): el is Element {
+ if (!el || el === document.body || el === document.documentElement) return false;
+ const tag = el.tagName.toLowerCase();
+ if (tag === "script" || tag === "style" || tag === "link" || tag === "meta") return false;
+ if (el.classList.contains("__hf-pick-highlight")) return false;
+ return true;
+ }
+
+ function buildElementSelector(el: Element): string {
+ const htmlEl = el as HTMLElement;
+ if (htmlEl.id) return `#${htmlEl.id}`;
+ const compositionId = el.getAttribute("data-composition-id");
+ if (compositionId) return `[data-composition-id="${compositionId}"]`;
+ const compositionSrc = el.getAttribute("data-composition-src");
+ if (compositionSrc) return `[data-composition-src="${compositionSrc}"]`;
+ const track = el.getAttribute("data-track-index");
+ if (track) return `[data-track-index="${track}"]`;
+ const tag = el.tagName.toLowerCase();
+ const parent = el.parentElement;
+ if (!parent) return tag;
+ const siblings = parent.querySelectorAll(`:scope > ${tag}`);
+ if (siblings.length === 1) return tag;
+ for (let i = 0; i < siblings.length; i += 1) {
+ if (siblings[i] === el) return `${tag}:nth-of-type(${i + 1})`;
+ }
+ return tag;
+ }
+
+ function buildElementLabel(el: Element): string {
+ const tag = el.tagName.toLowerCase();
+ const text = (el.textContent ?? "").trim().replace(/\s+/g, " ");
+ const trimLabel = (value: string, maxChars: number) =>
+ value.length > maxChars ? `${value.slice(0, maxChars - 1)}…` : value;
+ if (tag === "h1" || tag === "h2" || tag === "h3") return "Heading";
+ if (tag === "p" || tag === "span" || tag === "div") return text.length > 0 ? trimLabel(text, 56) : "Text";
+ if (tag === "img") return "Image";
+ if (tag === "video") return "Video";
+ if (tag === "audio") return "Audio";
+ if (tag === "svg") return "Shape";
+ if (el.getAttribute("data-composition-src")) return "Composition";
+ if (tag === "section") return "Section";
+ return `${tag.charAt(0).toUpperCase()}${tag.slice(1)}`;
+ }
+
+ function getPickCandidatesFromPoint(clientX: number, clientY: number, limit?: number): Element[] {
+ const maxCandidates = typeof limit === "number" && limit > 0 ? limit : 8;
+ let raw: Element[] = [];
+ if (document.elementsFromPoint) {
+ raw = document.elementsFromPoint(clientX, clientY);
+ } else if (document.elementFromPoint) {
+ const single = document.elementFromPoint(clientX, clientY);
+ raw = single ? [single] : [];
+ }
+ const dedupe: Record<string, true> = {};
+ const candidates: Element[] = [];
+ for (let i = 0; i < raw.length; i += 1) {
+ const node = raw[i];
+ if (!isPickableElement(node)) continue;
+ const key = `${node.tagName}::${(node as HTMLElement).id || ""}::${i}`;
+ if (dedupe[key]) continue;
+ dedupe[key] = true;
+ candidates.push(node);
+ if (candidates.length >= maxCandidates) break;
+ }
+ return candidates;
+ }
+
+ function extractElementInfo(el: Element): RuntimePickerElementInfo {
+ const rect = el.getBoundingClientRect();
+ const dataAttributes: Record<string, string> = {};
+ for (let i = 0; i < el.attributes.length; i += 1) {
+ const attr = el.attributes[i];
+ if (attr.name.startsWith("data-")) {
+ dataAttributes[attr.name] = attr.value;
+ }
+ }
+ const htmlEl = el as HTMLElement;
+ return {
+ id: htmlEl.id || null,
+ tagName: el.tagName.toLowerCase(),
+ selector: buildElementSelector(el),
+ label: buildElementLabel(el),
+ boundingBox: { x: rect.left, y: rect.top, width: rect.width, height: rect.height },
+ textContent: el.textContent ? el.textContent.trim().slice(0, 200) : null,
+ src: el.getAttribute("src") || el.getAttribute("data-composition-src") || null,
+ dataAttributes,
+ };
+ }
+
+ function getPickInfosFromPoint(clientX: number, clientY: number, limit?: number): RuntimePickerElementInfo[] {
+ return getPickCandidatesFromPoint(clientX, clientY, limit).map(extractElementInfo);
+ }
+
+ function onPickMouseMove(event: MouseEvent): void {
+ if (!pickModeActive) return;
+ const candidates = getPickCandidatesFromPoint(event.clientX, event.clientY, 1);
+ const target = candidates[0] ?? (event.target instanceof Element ? event.target : null);
+ if (!isPickableElement(target)) return;
+ if (pickModeHighlightEl === target) return;
+ if (pickModeHighlightEl) {
+ pickModeHighlightEl.classList.remove("__hf-pick-highlight");
+ }
+ pickModeHighlightEl = target;
+ target.classList.add("__hf-pick-highlight");
+ const info = extractElementInfo(target);
+ setLastHoveredInfo(info);
+ deps.postMessage({ source: "hf-preview", type: "element-hovered", elementInfo: info });
+ }
+
+ function onPickClick(event: MouseEvent): void {
+ if (!pickModeActive) return;
+ event.preventDefault();
+ event.stopPropagation();
+ event.stopImmediatePropagation();
+ const infos = getPickInfosFromPoint(event.clientX, event.clientY, 8);
+ if (infos.length === 0) return;
+ setLastHoveredInfo(infos[0] ?? null);
+ deps.postMessage({
+ source: "hf-preview",
+ type: "element-pick-candidates",
+ candidates: infos,
+ selectedIndex: 0,
+ point: { x: event.clientX, y: event.clientY },
+ });
+ }
+
+ function onPickKeyDown(event: KeyboardEvent): void {
+ if (event.key !== "Escape") return;
+ disablePickMode();
+ deps.postMessage({ source: "hf-preview", type: "pick-mode-cancelled" });
+ }
+
+ function enablePickMode(): void {
+ if (pickModeActive) return;
+ pickModeActive = true;
+ pickModeStyleEl = document.createElement("style");
+ pickModeStyleEl.textContent = [
+ ".__hf-pick-highlight { outline: 2px solid #4f8cf7 !important; outline-offset: 2px; cursor: crosshair !important; }",
+ ".__hf-pick-active * { cursor: crosshair !important; }",
+ ].join("\n");
+ document.head.appendChild(pickModeStyleEl);
+ document.body.classList.add("__hf-pick-active");
+ document.addEventListener("mousemove", onPickMouseMove, true);
+ document.addEventListener("click", onPickClick, true);
+ document.addEventListener("keydown", onPickKeyDown, true);
+ emitPickerRuntimeEvent("hyperframe:picker:mode", { isPickMode: true, timestamp: Date.now() });
+ }
+
+ function disablePickMode(): void {
+ if (!pickModeActive) return;
+ pickModeActive = false;
+ if (pickModeHighlightEl) {
+ pickModeHighlightEl.classList.remove("__hf-pick-highlight");
+ pickModeHighlightEl = null;
+ }
+ if (pickModeStyleEl) {
+ pickModeStyleEl.remove();
+ pickModeStyleEl = null;
+ }
+ document.body.classList.remove("__hf-pick-active");
+ document.removeEventListener("mousemove", onPickMouseMove, true);
+ document.removeEventListener("click", onPickClick, true);
+ document.removeEventListener("keydown", onPickKeyDown, true);
+ emitPickerRuntimeEvent("hyperframe:picker:mode", { isPickMode: false, timestamp: Date.now() });
+ }
+
+ function installPickerApi(): void {
+ window.__HF_PICKER_API = {
+ enable: enablePickMode,
+ disable: disablePickMode,
+ isActive: () => pickModeActive,
+ getHovered: () => pickLastHoveredInfo,
+ getSelected: () => pickLastSelectedInfo,
+ getCandidatesAtPoint: (clientX, clientY, limit) =>
+ Number.isFinite(clientX) && Number.isFinite(clientY) ? getPickInfosFromPoint(clientX, clientY, limit) : [],
+ pickAtPoint: (clientX, clientY, index) => {
+ if (!Number.isFinite(clientX) || !Number.isFinite(clientY)) return null;
+ const infos = getPickInfosFromPoint(clientX, clientY, 8);
+ if (!infos.length) return null;
+ const safeIndex = Math.max(0, Math.min(infos.length - 1, Number(index ?? 0)));
+ const selected = infos[safeIndex] ?? null;
+ if (!selected) return null;
+ setLastSelectedInfo(selected);
+ deps.postMessage({ source: "hf-preview", type: "element-picked", elementInfo: selected });
+ disablePickMode();
+ return selected;
+ },
+ pickManyAtPoint: (clientX, clientY, indexes) => {
+ if (!Number.isFinite(clientX) || !Number.isFinite(clientY)) return [];
+ const infos = getPickInfosFromPoint(clientX, clientY, 8);
+ if (!infos.length) return [];
+ const selected: RuntimePickerElementInfo[] = [];
+ const rawIndexes = Array.isArray(indexes) ? indexes : [0];
+ for (const rawIndex of rawIndexes) {
+ const idx = Math.max(0, Math.min(infos.length - 1, Math.floor(Number(rawIndex))));
+ const info = infos[idx];
+ if (!info) continue;
+ const duplicate = selected.some((item) => item.selector === info.selector && item.tagName === info.tagName);
+ if (!duplicate) selected.push(info);
+ }
+ if (!selected.length) return [];
+ setLastSelectedInfo(selected[0] ?? null);
+ deps.postMessage({ source: "hf-preview", type: "element-picked-many", elementInfos: selected });
+ disablePickMode();
+ return selected;
+ },
+ };
+ emitPickerRuntimeEvent("hyperframe:picker:api-ready", { hasApi: true, timestamp: Date.now() });
+ }
+
+ return { enablePickMode, disablePickMode, installPickerApi };
+}
diff --git a/packages/core/src/runtime/player.test.ts b/packages/core/src/runtime/player.test.ts
new file mode 100644
index 0000000000..14453585ee
--- /dev/null
+++ b/packages/core/src/runtime/player.test.ts
@@ -0,0 +1,213 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { createRuntimePlayer } from "./player";
+import type { RuntimeTimelineLike } from "./types";
+
+function createMockTimeline(opts?: { time?: number; duration?: number }): RuntimeTimelineLike {
+ const state = { time: opts?.time ?? 0, duration: opts?.duration ?? 10, paused: false };
+ return {
+ play: vi.fn(() => { state.paused = false; }),
+ pause: vi.fn(() => { state.paused = true; }),
+ seek: vi.fn((t: number) => { state.time = t; }),
+ totalTime: vi.fn((t: number) => { state.time = t; }),
+ time: vi.fn(() => state.time),
+ duration: vi.fn(() => state.duration),
+ add: vi.fn(),
+ paused: vi.fn((p?: boolean) => { if (p !== undefined) state.paused = p; }),
+ timeScale: vi.fn(),
+ set: vi.fn(),
+ };
+}
+
+function createMockDeps(timeline?: RuntimeTimelineLike | null) {
+ let isPlaying = false;
+ let playbackRate = 1;
+ return {
+ getTimeline: vi.fn(() => timeline ?? null),
+ setTimeline: vi.fn(),
+ getIsPlaying: vi.fn(() => isPlaying),
+ setIsPlaying: vi.fn((v: boolean) => { isPlaying = v; }),
+ getPlaybackRate: vi.fn(() => playbackRate),
+ setPlaybackRate: vi.fn((v: number) => { playbackRate = v; }),
+ getCanonicalFps: vi.fn(() => 30),
+ onSyncMedia: vi.fn(),
+ onStatePost: vi.fn(),
+ onDeterministicSeek: vi.fn(),
+ onDeterministicPause: vi.fn(),
+ onDeterministicPlay: vi.fn(),
+ onRenderFrameSeek: vi.fn(),
+ onShowNativeVideos: vi.fn(),
+ getSafeDuration: vi.fn(() => 10),
+ };
+}
+
+describe("createRuntimePlayer", () => {
+ describe("play", () => {
+ it("does nothing without a timeline", () => {
+ const deps = createMockDeps(null);
+ const player = createRuntimePlayer(deps);
+ player.play();
+ expect(deps.setIsPlaying).not.toHaveBeenCalled();
+ });
+
+ it("does nothing if already playing", () => {
+ const timeline = createMockTimeline();
+ const deps = createMockDeps(timeline);
+ deps.getIsPlaying.mockReturnValue(true);
+ const player = createRuntimePlayer(deps);
+ player.play();
+ expect(timeline.play).not.toHaveBeenCalled();
+ });
+
+ it("plays the timeline and updates state", () => {
+ const timeline = createMockTimeline({ time: 2, duration: 10 });
+ const deps = createMockDeps(timeline);
+ const player = createRuntimePlayer(deps);
+ player.play();
+ expect(timeline.play).toHaveBeenCalled();
+ expect(deps.setIsPlaying).toHaveBeenCalledWith(true);
+ expect(deps.onDeterministicPlay).toHaveBeenCalled();
+ expect(deps.onShowNativeVideos).toHaveBeenCalled();
+ expect(deps.onStatePost).toHaveBeenCalledWith(true);
+ });
+
+ it("resets to 0 when at end of timeline", () => {
+ const timeline = createMockTimeline({ time: 10, duration: 10 });
+ const deps = createMockDeps(timeline);
+ deps.getSafeDuration.mockReturnValue(10);
+ const player = createRuntimePlayer(deps);
+ player.play();
+ expect(timeline.seek).toHaveBeenCalledWith(0, false);
+ expect(deps.onDeterministicSeek).toHaveBeenCalledWith(0);
+ });
+
+ it("sets timeScale to playbackRate", () => {
+ const timeline = createMockTimeline({ time: 0, duration: 10 });
+ const deps = createMockDeps(timeline);
+ deps.getPlaybackRate.mockReturnValue(2);
+ const player = createRuntimePlayer(deps);
+ player.play();
+ expect(timeline.timeScale).toHaveBeenCalledWith(2);
+ });
+ });
+
+ describe("pause", () => {
+ it("does nothing without a timeline", () => {
+ const deps = createMockDeps(null);
+ const player = createRuntimePlayer(deps);
+ player.pause();
+ expect(deps.setIsPlaying).not.toHaveBeenCalled();
+ });
+
+ it("pauses the timeline and syncs media", () => {
+ const timeline = createMockTimeline({ time: 5 });
+ const deps = createMockDeps(timeline);
+ const player = createRuntimePlayer(deps);
+ player.pause();
+ expect(timeline.pause).toHaveBeenCalled();
+ expect(deps.setIsPlaying).toHaveBeenCalledWith(false);
+ expect(deps.onDeterministicSeek).toHaveBeenCalledWith(5);
+ expect(deps.onDeterministicPause).toHaveBeenCalled();
+ expect(deps.onSyncMedia).toHaveBeenCalledWith(5, false);
+ expect(deps.onRenderFrameSeek).toHaveBeenCalledWith(5);
+ expect(deps.onStatePost).toHaveBeenCalledWith(true);
+ });
+ });
+
+ describe("seek", () => {
+ it("does nothing without a timeline", () => {
+ const deps = createMockDeps(null);
+ const player = createRuntimePlayer(deps);
+ player.seek(5);
+ expect(deps.onDeterministicSeek).not.toHaveBeenCalled();
+ });
+
+ it("seeks to quantized time and pauses", () => {
+ const timeline = createMockTimeline({ duration: 10 });
+ const deps = createMockDeps(timeline);
+ const player = createRuntimePlayer(deps);
+ player.seek(3);
+ expect(timeline.pause).toHaveBeenCalled();
+ expect(timeline.totalTime).toHaveBeenCalled();
+ expect(deps.setIsPlaying).toHaveBeenCalledWith(false);
+ expect(deps.onSyncMedia).toHaveBeenCalled();
+ expect(deps.onStatePost).toHaveBeenCalledWith(true);
+ });
+
+ it("clamps negative time to 0", () => {
+ const timeline = createMockTimeline({ duration: 10 });
+ const deps = createMockDeps(timeline);
+ const player = createRuntimePlayer(deps);
+ player.seek(-5);
+ expect(deps.onDeterministicSeek).toHaveBeenCalledWith(0);
+ });
+
+ it("handles NaN time", () => {
+ const timeline = createMockTimeline({ duration: 10 });
+ const deps = createMockDeps(timeline);
+ const player = createRuntimePlayer(deps);
+ player.seek(NaN);
+ expect(deps.onDeterministicSeek).toHaveBeenCalledWith(0);
+ });
+ });
+
+ describe("renderSeek", () => {
+ it("seeks deterministically for render pipeline", () => {
+ const timeline = createMockTimeline({ duration: 10 });
+ const deps = createMockDeps(timeline);
+ const player = createRuntimePlayer(deps);
+ player.renderSeek(5);
+ expect(timeline.pause).toHaveBeenCalled();
+ expect(deps.setIsPlaying).toHaveBeenCalledWith(false);
+ expect(deps.onRenderFrameSeek).toHaveBeenCalled();
+ });
+ });
+
+ describe("getters", () => {
+ it("getTime returns timeline time", () => {
+ const timeline = createMockTimeline({ time: 7.5 });
+ const deps = createMockDeps(timeline);
+ const player = createRuntimePlayer(deps);
+ expect(player.getTime()).toBe(7.5);
+ });
+
+ it("getDuration returns timeline duration", () => {
+ const timeline = createMockTimeline({ duration: 30 });
+ const deps = createMockDeps(timeline);
+ const player = createRuntimePlayer(deps);
+ expect(player.getDuration()).toBe(30);
+ });
+
+ it("getTime returns 0 without timeline", () => {
+ const deps = createMockDeps(null);
+ const player = createRuntimePlayer(deps);
+ expect(player.getTime()).toBe(0);
+ });
+
+ it("getDuration returns 0 without timeline", () => {
+ const deps = createMockDeps(null);
+ const player = createRuntimePlayer(deps);
+ expect(player.getDuration()).toBe(0);
+ });
+
+ it("isPlaying delegates to deps", () => {
+ const deps = createMockDeps(null);
+ deps.getIsPlaying.mockReturnValue(true);
+ const player = createRuntimePlayer(deps);
+ expect(player.isPlaying()).toBe(true);
+ });
+
+ it("setPlaybackRate delegates to deps", () => {
+ const deps = createMockDeps(null);
+ const player = createRuntimePlayer(deps);
+ player.setPlaybackRate(1.5);
+ expect(deps.setPlaybackRate).toHaveBeenCalledWith(1.5);
+ });
+
+ it("getPlaybackRate delegates to deps", () => {
+ const deps = createMockDeps(null);
+ deps.getPlaybackRate.mockReturnValue(2);
+ const player = createRuntimePlayer(deps);
+ expect(player.getPlaybackRate()).toBe(2);
+ });
+ });
+});
diff --git a/packages/core/src/runtime/player.ts b/packages/core/src/runtime/player.ts
new file mode 100644
index 0000000000..7fcc381221
--- /dev/null
+++ b/packages/core/src/runtime/player.ts
@@ -0,0 +1,103 @@
+import type { RuntimePlayer, RuntimeTimelineLike } from "./types";
+import { quantizeTimeToFrame } from "../inline-scripts/parityContract";
+
+type PlayerDeps = {
+ getTimeline: () => RuntimeTimelineLike | null;
+ setTimeline: (timeline: RuntimeTimelineLike | null) => void;
+ getIsPlaying: () => boolean;
+ setIsPlaying: (playing: boolean) => void;
+ getPlaybackRate: () => number;
+ setPlaybackRate: (rate: number) => void;
+ getCanonicalFps: () => number;
+ onSyncMedia: (timeSeconds: number, playing: boolean) => void;
+ onStatePost: (force: boolean) => void;
+ onDeterministicSeek: (timeSeconds: number) => void;
+ onDeterministicPause: () => void;
+ onDeterministicPlay: () => void;
+ onRenderFrameSeek: (timeSeconds: number) => void;
+ onShowNativeVideos: () => void;
+ getSafeDuration?: () => number;
+};
+
+function seekTimelineDeterministically(
+ timeline: RuntimeTimelineLike,
+ timeSeconds: number,
+ canonicalFps: number,
+): number {
+ const quantized = quantizeTimeToFrame(timeSeconds, canonicalFps);
+ timeline.pause();
+ if (typeof timeline.totalTime === "function") {
+ timeline.totalTime(quantized, false);
+ } else {
+ timeline.seek(quantized, false);
+ }
+ return quantized;
+}
+
+export function createRuntimePlayer(deps: PlayerDeps): RuntimePlayer {
+ return {
+ _timeline: null,
+ play: () => {
+ const timeline = deps.getTimeline();
+ if (!timeline || deps.getIsPlaying()) return;
+ const safeDuration = Math.max(0, Number(deps.getSafeDuration?.() ?? timeline.duration() ?? 0) || 0);
+ if (safeDuration > 0) {
+ const currentTime = Math.max(0, Number(timeline.time()) || 0);
+ if (currentTime >= safeDuration) {
+ timeline.pause();
+ timeline.seek(0, false);
+ deps.onDeterministicSeek(0);
+ deps.setIsPlaying(false);
+ deps.onSyncMedia(0, false);
+ deps.onRenderFrameSeek(0);
+ }
+ }
+ if (typeof timeline.timeScale === "function") {
+ timeline.timeScale(deps.getPlaybackRate());
+ }
+ timeline.play();
+ deps.onDeterministicPlay();
+ deps.setIsPlaying(true);
+ deps.onShowNativeVideos();
+ deps.onStatePost(true);
+ },
+ pause: () => {
+ const timeline = deps.getTimeline();
+ if (!timeline) return;
+ timeline.pause();
+ const time = Math.max(0, Number(timeline.time()) || 0);
+ deps.onDeterministicSeek(time);
+ deps.onDeterministicPause();
+ deps.setIsPlaying(false);
+ deps.onSyncMedia(time, false);
+ deps.onRenderFrameSeek(time);
+ deps.onStatePost(true);
+ },
+ seek: (timeSeconds: number) => {
+ const timeline = deps.getTimeline();
+ if (!timeline) return;
+ const safeTime = Math.max(0, Number(timeSeconds) || 0);
+ const quantized = seekTimelineDeterministically(timeline, safeTime, deps.getCanonicalFps());
+ deps.onDeterministicSeek(quantized);
+ deps.setIsPlaying(false);
+ deps.onSyncMedia(quantized, false);
+ deps.onRenderFrameSeek(quantized);
+ deps.onStatePost(true);
+ },
+ renderSeek: (timeSeconds: number) => {
+ const timeline = deps.getTimeline();
+ if (!timeline) return;
+ const quantized = seekTimelineDeterministically(timeline, timeSeconds, deps.getCanonicalFps());
+ deps.onDeterministicSeek(quantized);
+ deps.setIsPlaying(false);
+ deps.onSyncMedia(quantized, false);
+ deps.onRenderFrameSeek(quantized);
+ deps.onStatePost(true);
+ },
+ getTime: () => Number(deps.getTimeline()?.time() ?? 0),
+ getDuration: () => Number(deps.getTimeline()?.duration() ?? 0),
+ isPlaying: () => deps.getIsPlaying(),
+ setPlaybackRate: (rate: number) => deps.setPlaybackRate(rate),
+ getPlaybackRate: () => deps.getPlaybackRate(),
+ };
+}
diff --git a/packages/core/src/runtime/startResolver.test.ts b/packages/core/src/runtime/startResolver.test.ts
new file mode 100644
index 0000000000..8843073359
--- /dev/null
+++ b/packages/core/src/runtime/startResolver.test.ts
@@ -0,0 +1,225 @@
+import { describe, it, expect, afterEach, beforeAll } from "vitest";
+import { createRuntimeStartTimeResolver } from "./startResolver";
+
+// jsdom doesn't provide CSS.escape — polyfill it
+beforeAll(() => {
+ if (typeof globalThis.CSS === "undefined") {
+ (globalThis as any).CSS = {};
+ }
+ if (typeof CSS.escape !== "function") {
+ CSS.escape = (value: string) =>
+ value.replace(/([^\w-])/g, "\\$1");
+ }
+});
+
+describe("createRuntimeStartTimeResolver", () => {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ });
+
+ describe("resolveStartForElement", () => {
+ it("resolves absolute numeric data-start", () => {
+ const el = document.createElement("div");
+ el.setAttribute("data-start", "5");
+ document.body.appendChild(el);
+ const resolver = createRuntimeStartTimeResolver({});
+ expect(resolver.resolveStartForElement(el)).toBe(5);
+ });
+
+ it("resolves zero start", () => {
+ const el = document.createElement("div");
+ el.setAttribute("data-start", "0");
+ document.body.appendChild(el);
+ const resolver = createRuntimeStartTimeResolver({});
+ expect(resolver.resolveStartForElement(el)).toBe(0);
+ });
+
+ it("returns fallback when no data-start", () => {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ const resolver = createRuntimeStartTimeResolver({});
+ expect(resolver.resolveStartForElement(el, 3)).toBe(3);
+ });
+
+ it("resolves reference to another element (after end)", () => {
+ const a = document.createElement("div");
+ a.id = "scene-1";
+ a.setAttribute("data-start", "2");
+ a.setAttribute("data-duration", "3");
+ document.body.appendChild(a);
+
+ const b = document.createElement("div");
+ b.setAttribute("data-start", "scene-1");
+ document.body.appendChild(b);
+
+ const resolver = createRuntimeStartTimeResolver({});
+ // scene-1 starts at 2, duration 3, so b starts at 2+3 = 5
+ expect(resolver.resolveStartForElement(b)).toBe(5);
+ });
+
+ it("resolves reference with positive offset", () => {
+ const a = document.createElement("div");
+ a.id = "intro";
+ a.setAttribute("data-start", "0");
+ a.setAttribute("data-duration", "5");
+ document.body.appendChild(a);
+
+ const b = document.createElement("div");
+ b.setAttribute("data-start", "intro + 2");
+ document.body.appendChild(b);
+
+ const resolver = createRuntimeStartTimeResolver({});
+ // intro ends at 5, offset +2 → 7
+ expect(resolver.resolveStartForElement(b)).toBe(7);
+ });
+
+ it("resolves reference with negative offset", () => {
+ const a = document.createElement("div");
+ a.id = "scene-a";
+ a.setAttribute("data-start", "0");
+ a.setAttribute("data-duration", "10");
+ document.body.appendChild(a);
+
+ const b = document.createElement("div");
+ b.setAttribute("data-start", "scene-a - 3");
+ document.body.appendChild(b);
+
+ const resolver = createRuntimeStartTimeResolver({});
+ // scene-a ends at 10, offset -3 → 7
+ expect(resolver.resolveStartForElement(b)).toBe(7);
+ });
+
+ it("clamps resolved start to 0", () => {
+ const a = document.createElement("div");
+ a.id = "clip";
+ a.setAttribute("data-start", "1");
+ a.setAttribute("data-duration", "2");
+ document.body.appendChild(a);
+
+ const b = document.createElement("div");
+ b.setAttribute("data-start", "clip - 100");
+ document.body.appendChild(b);
+
+ const resolver = createRuntimeStartTimeResolver({});
+ expect(resolver.resolveStartForElement(b)).toBe(0);
+ });
+
+ it("handles circular references gracefully", () => {
+ const a = document.createElement("div");
+ a.id = "a";
+ a.setAttribute("data-start", "b");
+ document.body.appendChild(a);
+
+ const b = document.createElement("div");
+ b.id = "b";
+ b.setAttribute("data-start", "a");
+ document.body.appendChild(b);
+
+ const resolver = createRuntimeStartTimeResolver({});
+ // Should not infinite loop — returns fallback
+ expect(resolver.resolveStartForElement(a)).toBeGreaterThanOrEqual(0);
+ expect(resolver.resolveStartForElement(b)).toBeGreaterThanOrEqual(0);
+ });
+
+ it("uses data-composition-id selector for lookup", () => {
+ const comp = document.createElement("div");
+ comp.setAttribute("data-composition-id", "hero");
+ comp.setAttribute("data-start", "0");
+ comp.setAttribute("data-duration", "5");
+ document.body.appendChild(comp);
+
+ const after = document.createElement("div");
+ after.setAttribute("data-start", "hero");
+ document.body.appendChild(after);
+
+ const resolver = createRuntimeStartTimeResolver({});
+ expect(resolver.resolveStartForElement(after)).toBe(5);
+ });
+
+ it("returns fallback when reference target not found", () => {
+ const el = document.createElement("div");
+ el.setAttribute("data-start", "nonexistent");
+ document.body.appendChild(el);
+
+ const resolver = createRuntimeStartTimeResolver({});
+ expect(resolver.resolveStartForElement(el, 0)).toBe(0);
+ });
+
+ it("caches resolved values (second call is same result)", () => {
+ const el = document.createElement("div");
+ el.setAttribute("data-start", "3.5");
+ document.body.appendChild(el);
+
+ const resolver = createRuntimeStartTimeResolver({});
+ const first = resolver.resolveStartForElement(el);
+ const second = resolver.resolveStartForElement(el);
+ expect(first).toBe(second);
+ expect(first).toBe(3.5);
+ });
+ });
+
+ describe("resolveDurationForElement", () => {
+ it("resolves explicit data-duration", () => {
+ const el = document.createElement("div");
+ el.setAttribute("data-duration", "7");
+ document.body.appendChild(el);
+
+ const resolver = createRuntimeStartTimeResolver({});
+ expect(resolver.resolveDurationForElement(el)).toBe(7);
+ });
+
+ it("resolves from data-end minus start", () => {
+ const el = document.createElement("div");
+ el.setAttribute("data-start", "2");
+ el.setAttribute("data-end", "8");
+ document.body.appendChild(el);
+
+ const resolver = createRuntimeStartTimeResolver({});
+ expect(resolver.resolveDurationForElement(el)).toBe(6);
+ });
+
+ it("returns null when no duration info available", () => {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+
+ const resolver = createRuntimeStartTimeResolver({});
+ expect(resolver.resolveDurationForElement(el)).toBeNull();
+ });
+
+ it("resolves from timeline registry for compositions", () => {
+ const el = document.createElement("div");
+ el.setAttribute("data-composition-id", "comp-1");
+ document.body.appendChild(el);
+
+ const mockTimeline = { duration: () => 12, time: () => 0, play: () => {}, pause: () => {}, seek: () => {}, add: () => {}, paused: () => {}, set: () => {} };
+ const resolver = createRuntimeStartTimeResolver({
+ timelineRegistry: { "comp-1": mockTimeline as any },
+ });
+ expect(resolver.resolveDurationForElement(el)).toBe(12);
+ });
+
+ it("prefers data-duration over timeline registry", () => {
+ const el = document.createElement("div");
+ el.setAttribute("data-composition-id", "comp-1");
+ el.setAttribute("data-duration", "5");
+ document.body.appendChild(el);
+
+ const mockTimeline = { duration: () => 12, time: () => 0, play: () => {}, pause: () => {}, seek: () => {}, add: () => {}, paused: () => {}, set: () => {} };
+ const resolver = createRuntimeStartTimeResolver({
+ timelineRegistry: { "comp-1": mockTimeline as any },
+ });
+ expect(resolver.resolveDurationForElement(el)).toBe(5);
+ });
+
+ it("caches duration results", () => {
+ const el = document.createElement("div");
+ el.setAttribute("data-duration", "4");
+ document.body.appendChild(el);
+
+ const resolver = createRuntimeStartTimeResolver({});
+ const first = resolver.resolveDurationForElement(el);
+ const second = resolver.resolveDurationForElement(el);
+ expect(first).toBe(second);
+ });
+ });
+});
diff --git a/packages/core/src/runtime/startResolver.ts b/packages/core/src/runtime/startResolver.ts
new file mode 100644
index 0000000000..620a984a90
--- /dev/null
+++ b/packages/core/src/runtime/startResolver.ts
@@ -0,0 +1,151 @@
+import type { RuntimeTimelineLike } from "./types";
+
+type ReferenceExpression =
+ | {
+ kind: "absolute";
+ value: number;
+ }
+ | {
+ kind: "reference";
+ refId: string;
+ offset: number;
+ };
+
+function parseNumeric(value: string | null | undefined): number | null {
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : null;
+}
+
+function parseStartExpression(raw: string | null | undefined): ReferenceExpression | null {
+ const normalized = (raw ?? "").trim();
+ if (!normalized) return null;
+ const absolute = parseNumeric(normalized);
+ if (absolute != null) {
+ return { kind: "absolute", value: absolute };
+ }
+ const referenceMatch = normalized.match(/^([A-Za-z0-9_.:-]+)(?:\s*([+-])\s*([0-9]*\.?[0-9]+))?$/);
+ if (!referenceMatch) return null;
+ const refId = (referenceMatch[1] ?? "").trim();
+ if (!refId) return null;
+ const sign = referenceMatch[2] ?? "+";
+ const offsetRaw = referenceMatch[3] ?? "0";
+ const parsedOffset = Number.parseFloat(offsetRaw);
+ const offsetMagnitude = Number.isFinite(parsedOffset) ? Math.max(0, parsedOffset) : 0;
+ const offset = sign === "-" ? -offsetMagnitude : offsetMagnitude;
+ return { kind: "reference", refId, offset };
+}
+
+export function createRuntimeStartTimeResolver(params: {
+ timelineRegistry?: Record<string, RuntimeTimelineLike | undefined>;
+}): {
+ resolveStartForElement: (element: Element, fallback?: number) => number;
+ resolveDurationForElement: (element: Element) => number | null;
+} {
+ const timelineRegistry = params.timelineRegistry ?? {};
+ const startCache = new WeakMap<Element, number | null>();
+ const durationCache = new WeakMap<Element, number | null>();
+ const visiting = new Set<Element>();
+
+ const findReferenceTarget = (refId: string): Element | null => {
+ const byId = document.getElementById(refId);
+ if (byId) return byId;
+ return (document.querySelector(`[data-composition-id="${CSS.escape(refId)}"]`) as Element | null) ?? null;
+ };
+
+ const resolveDurationForElement = (element: Element): number | null => {
+ const cached = durationCache.get(element);
+ if (cached !== undefined) return cached;
+ let resolved: number | null = null;
+ const durationAttr = parseNumeric(element.getAttribute("data-duration"));
+ if (durationAttr != null && durationAttr > 0) {
+ resolved = durationAttr;
+ }
+ if (resolved == null || resolved <= 0) {
+ const endAttr = parseNumeric(element.getAttribute("data-end"));
+ if (endAttr != null) {
+ const start = resolveStartForElementInternal(element, 0);
+ const delta = endAttr - start;
+ if (Number.isFinite(delta) && delta > 0) {
+ resolved = delta;
+ }
+ }
+ }
+ if ((resolved == null || resolved <= 0) && element instanceof HTMLMediaElement) {
+ const playbackStart =
+ parseNumeric(element.getAttribute("data-playback-start")) ??
+ parseNumeric(element.getAttribute("data-media-start")) ??
+ 0;
+ if (Number.isFinite(element.duration) && element.duration > playbackStart) {
+ resolved = element.duration - playbackStart;
+ }
+ }
+ if (resolved == null || resolved <= 0) {
+ const compositionId = element.getAttribute("data-composition-id");
+ if (compositionId) {
+ const timeline = timelineRegistry[compositionId] ?? null;
+ if (timeline && typeof timeline.duration === "function") {
+ try {
+ const timelineDuration = Number(timeline.duration());
+ if (Number.isFinite(timelineDuration) && timelineDuration > 0) {
+ resolved = timelineDuration;
+ }
+ } catch {
+ // ignore broken timeline impls
+ }
+ }
+ }
+ }
+ if (resolved != null && Number.isFinite(resolved) && resolved > 0) {
+ durationCache.set(element, resolved);
+ return resolved;
+ }
+ durationCache.set(element, null);
+ return null;
+ };
+
+ const resolveStartForElementInternal = (element: Element, fallback: number): number => {
+ const cached = startCache.get(element);
+ if (cached !== undefined) {
+ return cached == null ? fallback : cached;
+ }
+ if (visiting.has(element)) {
+ return fallback;
+ }
+ visiting.add(element);
+ try {
+ const expression = parseStartExpression(element.getAttribute("data-start"));
+ if (!expression) {
+ startCache.set(element, fallback);
+ return fallback;
+ }
+ if (expression.kind === "absolute") {
+ const absolute = Math.max(0, expression.value);
+ startCache.set(element, absolute);
+ return absolute;
+ }
+ const target = findReferenceTarget(expression.refId);
+ if (!target) {
+ startCache.set(element, fallback);
+ return fallback;
+ }
+ const targetStart = resolveStartForElementInternal(target, 0);
+ const targetDuration = resolveDurationForElement(target);
+ if (targetDuration == null || targetDuration <= 0) {
+ const unresolved = Math.max(0, targetStart + expression.offset);
+ startCache.set(element, unresolved);
+ return unresolved;
+ }
+ const resolved = Math.max(0, targetStart + targetDuration + expression.offset);
+ startCache.set(element, resolved);
+ return resolved;
+ } finally {
+ visiting.delete(element);
+ }
+ };
+
+ return {
+ resolveStartForElement: (element: Element, fallback = 0) =>
+ resolveStartForElementInternal(element, Math.max(0, fallback)),
+ resolveDurationForElement: (element: Element) => resolveDurationForElement(element),
+ };
+}
diff --git a/packages/core/src/runtime/state.test.ts b/packages/core/src/runtime/state.test.ts
new file mode 100644
index 0000000000..b470dda04c
--- /dev/null
+++ b/packages/core/src/runtime/state.test.ts
@@ -0,0 +1,58 @@
+import { describe, it, expect } from "vitest";
+import { createRuntimeState } from "./state";
+
+describe("createRuntimeState", () => {
+ it("returns a fresh state with correct defaults", () => {
+ const state = createRuntimeState();
+ expect(state.isPlaying).toBe(false);
+ expect(state.currentTime).toBe(0);
+ expect(state.canonicalFps).toBe(30);
+ expect(state.playbackRate).toBe(1);
+ expect(state.bridgeMuted).toBe(false);
+ expect(state.capturedTimeline).toBeNull();
+ expect(state.rafId).toBeNull();
+ expect(state.tornDown).toBe(false);
+ expect(state.maxTimelineDurationSeconds).toBe(1800);
+ expect(state.parityModeEnabled).toBe(true);
+ });
+
+ it("returns independent instances", () => {
+ const a = createRuntimeState();
+ const b = createRuntimeState();
+ a.isPlaying = true;
+ a.currentTime = 5;
+ expect(b.isPlaying).toBe(false);
+ expect(b.currentTime).toBe(0);
+ });
+
+ it("bridge state defaults are correct", () => {
+ const state = createRuntimeState();
+ expect(state.bridgeLastPostedFrame).toBe(-1);
+ expect(state.bridgeLastPostedAt).toBe(0);
+ expect(state.bridgeLastPostedPlaying).toBe(false);
+ expect(state.bridgeLastPostedMuted).toBe(false);
+ expect(state.bridgeMaxPostIntervalMs).toBe(80);
+ });
+
+ it("cached arrays start empty", () => {
+ const state = createRuntimeState();
+ expect(state.cachedTimedMediaEls).toEqual([]);
+ expect(state.cachedMediaClips).toEqual([]);
+ expect(state.cachedVideoClips).toEqual([]);
+ expect(state.injectedCompStyles).toEqual([]);
+ expect(state.injectedCompScripts).toEqual([]);
+ expect(state.deterministicAdapters).toEqual([]);
+ });
+
+ it("state is mutable", () => {
+ const state = createRuntimeState();
+ state.isPlaying = true;
+ state.currentTime = 12.5;
+ state.canonicalFps = 60;
+ state.tornDown = true;
+ expect(state.isPlaying).toBe(true);
+ expect(state.currentTime).toBe(12.5);
+ expect(state.canonicalFps).toBe(60);
+ expect(state.tornDown).toBe(true);
+ });
+});
diff --git a/packages/core/src/runtime/state.ts b/packages/core/src/runtime/state.ts
new file mode 100644
index 0000000000..15c8b163f1
--- /dev/null
+++ b/packages/core/src/runtime/state.ts
@@ -0,0 +1,66 @@
+import type { RuntimeDeterministicAdapter, RuntimeTimelineLike } from "./types";
+import type { RuntimeMediaClip } from "./media";
+
+export type RuntimeState = {
+ capturedTimeline: RuntimeTimelineLike | null;
+ isPlaying: boolean;
+ rafId: number | null;
+ currentTime: number;
+ deterministicAdapters: RuntimeDeterministicAdapter[];
+ parityModeEnabled: boolean;
+ canonicalFps: number;
+ bridgeMuted: boolean;
+ playbackRate: number;
+ bridgeLastPostedFrame: number;
+ bridgeLastPostedAt: number;
+ bridgeLastPostedPlaying: boolean;
+ bridgeLastPostedMuted: boolean;
+ bridgeMaxPostIntervalMs: number;
+ timelinePollIntervalId: ReturnType<typeof setInterval> | null;
+ controlBridgeHandler: ((event: MessageEvent) => void) | null;
+ clampDurationLoggedRaw: number | null;
+ beforeUnloadHandler: (() => void) | null;
+ domReadyHandler: (() => void) | null;
+ injectedCompStyles: HTMLStyleElement[];
+ injectedCompScripts: HTMLScriptElement[];
+ cachedTimedMediaEls: Array<HTMLVideoElement | HTMLAudioElement>;
+ cachedMediaClips: RuntimeMediaClip[];
+ cachedVideoClips: RuntimeMediaClip[];
+ cachedMediaTimelineDurationSeconds: number;
+ tornDown: boolean;
+ maxTimelineDurationSeconds: number;
+ nativeVisualWatchdogTick: number;
+};
+
+export function createRuntimeState(): RuntimeState {
+ return {
+ capturedTimeline: null,
+ isPlaying: false,
+ rafId: null,
+ currentTime: 0,
+ deterministicAdapters: [],
+ parityModeEnabled: true,
+ canonicalFps: 30,
+ bridgeMuted: false,
+ playbackRate: 1,
+ bridgeLastPostedFrame: -1,
+ bridgeLastPostedAt: 0,
+ bridgeLastPostedPlaying: false,
+ bridgeLastPostedMuted: false,
+ bridgeMaxPostIntervalMs: 80,
+ timelinePollIntervalId: null,
+ controlBridgeHandler: null,
+ clampDurationLoggedRaw: null,
+ beforeUnloadHandler: null,
+ domReadyHandler: null,
+ injectedCompStyles: [],
+ injectedCompScripts: [],
+ cachedTimedMediaEls: [],
+ cachedMediaClips: [],
+ cachedVideoClips: [],
+ cachedMediaTimelineDurationSeconds: 0,
+ tornDown: false,
+ maxTimelineDurationSeconds: 1800,
+ nativeVisualWatchdogTick: 0,
+ };
+}
diff --git a/packages/core/src/runtime/timeline.test.ts b/packages/core/src/runtime/timeline.test.ts
new file mode 100644
index 0000000000..238e3eb21c
--- /dev/null
+++ b/packages/core/src/runtime/timeline.test.ts
@@ -0,0 +1,276 @@
+import { describe, it, expect, afterEach } from "vitest";
+import { collectRuntimeTimelinePayload } from "./timeline";
+
+describe("collectRuntimeTimelinePayload", () => {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ delete (window as any).__timelines;
+ });
+
+ const defaultParams = { canonicalFps: 30, maxTimelineDurationSeconds: 1800 };
+
+ it("returns minimal payload for empty document", () => {
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.source).toBe("hf-preview");
+ expect(result.type).toBe("timeline");
+ expect(result.clips).toEqual([]);
+ expect(result.scenes).toEqual([]);
+ expect(result.durationInFrames).toBeGreaterThanOrEqual(1);
+ expect(result.compositionWidth).toBe(1920);
+ expect(result.compositionHeight).toBe(1080);
+ });
+
+ it("collects clips from elements with data-start and data-duration", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "10");
+ document.body.appendChild(root);
+
+ const clip = document.createElement("div");
+ clip.id = "text-1";
+ clip.setAttribute("data-start", "1");
+ clip.setAttribute("data-duration", "3");
+ clip.setAttribute("data-track-index", "0");
+ root.appendChild(clip);
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.clips).toHaveLength(1);
+ expect(result.clips[0].id).toBe("text-1");
+ expect(result.clips[0].start).toBe(1);
+ expect(result.clips[0].duration).toBe(3);
+ expect(result.clips[0].kind).toBe("element");
+ });
+
+ it("identifies video clips by tag", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "10");
+ document.body.appendChild(root);
+
+ const video = document.createElement("video");
+ video.id = "v1";
+ video.setAttribute("data-start", "0");
+ video.setAttribute("data-duration", "5");
+ root.appendChild(video);
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.clips[0].kind).toBe("video");
+ });
+
+ it("identifies audio clips by tag", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "10");
+ document.body.appendChild(root);
+
+ const audio = document.createElement("audio");
+ audio.id = "a1";
+ audio.setAttribute("data-start", "0");
+ audio.setAttribute("data-duration", "5");
+ root.appendChild(audio);
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.clips[0].kind).toBe("audio");
+ });
+
+ it("identifies image clips by tag", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "10");
+ document.body.appendChild(root);
+
+ const img = document.createElement("img");
+ img.id = "img1";
+ img.setAttribute("data-start", "0");
+ img.setAttribute("data-duration", "5");
+ root.appendChild(img);
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.clips[0].kind).toBe("image");
+ });
+
+ it("identifies composition clips", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "20");
+ document.body.appendChild(root);
+
+ const comp = document.createElement("div");
+ comp.id = "scene-1";
+ comp.setAttribute("data-composition-id", "scene-1");
+ comp.setAttribute("data-start", "0");
+ comp.setAttribute("data-duration", "10");
+ root.appendChild(comp);
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.clips[0].kind).toBe("composition");
+ });
+
+ it("collects scenes from composition nodes", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "20");
+ document.body.appendChild(root);
+
+ const scene = document.createElement("div");
+ scene.setAttribute("data-composition-id", "scene-intro");
+ scene.setAttribute("data-start", "0");
+ scene.setAttribute("data-duration", "10");
+ scene.setAttribute("data-label", "Intro");
+ root.appendChild(scene);
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.scenes).toHaveLength(1);
+ expect(result.scenes[0].id).toBe("scene-intro");
+ expect(result.scenes[0].label).toBe("Intro");
+ expect(result.scenes[0].start).toBe(0);
+ expect(result.scenes[0].duration).toBe(10);
+ });
+
+ it("skips caption and ambient compositions from scenes", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "20");
+ document.body.appendChild(root);
+
+ const caption = document.createElement("div");
+ caption.setAttribute("data-composition-id", "caption-1");
+ caption.setAttribute("data-start", "0");
+ caption.setAttribute("data-duration", "5");
+ root.appendChild(caption);
+
+ const ambient = document.createElement("div");
+ ambient.setAttribute("data-composition-id", "ambient-bg");
+ ambient.setAttribute("data-start", "0");
+ ambient.setAttribute("data-duration", "5");
+ root.appendChild(ambient);
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.scenes).toHaveLength(0);
+ });
+
+ it("reads composition dimensions from root", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-width", "3840");
+ root.setAttribute("data-height", "2160");
+ root.setAttribute("data-duration", "5");
+ document.body.appendChild(root);
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.compositionWidth).toBe(3840);
+ expect(result.compositionHeight).toBe(2160);
+ });
+
+ it("defaults composition dimensions to 1920x1080", () => {
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.compositionWidth).toBe(1920);
+ expect(result.compositionHeight).toBe(1080);
+ });
+
+ it("computes durationInFrames from max clip end", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "10");
+ document.body.appendChild(root);
+
+ const clip = document.createElement("div");
+ clip.setAttribute("data-start", "0");
+ clip.setAttribute("data-duration", "10");
+ root.appendChild(clip);
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.durationInFrames).toBe(300); // 10s * 30fps
+ });
+
+ it("clamps duration to maxTimelineDurationSeconds", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "5000");
+ document.body.appendChild(root);
+
+ const clip = document.createElement("div");
+ clip.setAttribute("data-start", "0");
+ clip.setAttribute("data-duration", "5000");
+ root.appendChild(clip);
+
+ const result = collectRuntimeTimelinePayload({ canonicalFps: 30, maxTimelineDurationSeconds: 60 });
+ expect(result.durationInFrames).toBeLessThanOrEqual(60 * 30);
+ });
+
+ it("skips script/style/meta nodes", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "10");
+ document.body.appendChild(root);
+
+ const script = document.createElement("script");
+ script.setAttribute("data-start", "0");
+ script.setAttribute("data-duration", "5");
+ root.appendChild(script);
+
+ const style = document.createElement("style");
+ style.setAttribute("data-start", "0");
+ style.setAttribute("data-duration", "5");
+ root.appendChild(style);
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.clips).toHaveLength(0);
+ });
+
+ it("resolves asset URLs from src attribute", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "10");
+ document.body.appendChild(root);
+
+ const img = document.createElement("img");
+ img.id = "hero";
+ img.setAttribute("src", "https://example.com/hero.jpg");
+ img.setAttribute("data-start", "0");
+ img.setAttribute("data-duration", "5");
+ root.appendChild(img);
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.clips[0].assetUrl).toBe("https://example.com/hero.jpg");
+ });
+
+ it("uses label from data-timeline-label", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "10");
+ document.body.appendChild(root);
+
+ const clip = document.createElement("div");
+ clip.id = "clip-1";
+ clip.setAttribute("data-start", "0");
+ clip.setAttribute("data-duration", "5");
+ clip.setAttribute("data-timeline-label", "Hero Shot");
+ root.appendChild(clip);
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.clips[0].label).toBe("Hero Shot");
+ });
+
+ it("handles timeline registry for composition duration", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ document.body.appendChild(root);
+
+ const comp = document.createElement("div");
+ comp.setAttribute("data-composition-id", "scene-1");
+ comp.setAttribute("data-start", "0");
+ root.appendChild(comp);
+
+ (window as any).__timelines = {
+ "main": { duration: () => 15, time: () => 0, play: () => {}, pause: () => {}, seek: () => {}, add: () => {}, paused: () => {}, set: () => {} },
+ "scene-1": { duration: () => 8, time: () => 0, play: () => {}, pause: () => {}, seek: () => {}, add: () => {}, paused: () => {}, set: () => {} },
+ };
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ // scene-1 should get duration 8 from timeline registry
+ const sceneClip = result.clips.find(c => c.compositionId === "scene-1");
+ expect(sceneClip).toBeDefined();
+ expect(sceneClip?.duration).toBe(8);
+ });
+});
diff --git a/packages/core/src/runtime/timeline.ts b/packages/core/src/runtime/timeline.ts
new file mode 100644
index 0000000000..5fce145a86
--- /dev/null
+++ b/packages/core/src/runtime/timeline.ts
@@ -0,0 +1,280 @@
+import type { RuntimeTimelineClip, RuntimeTimelineMessage, RuntimeTimelineScene, RuntimeTimelineLike } from "./types";
+import { createRuntimeStartTimeResolver } from "./startResolver";
+
+function parseNum(value: string | null | undefined): number | null {
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : null;
+}
+
+function toAbsoluteAssetUrl(rawValue: string | null | undefined): string | null {
+ const raw = String(rawValue ?? "").trim();
+ if (!raw) return null;
+ const lowered = raw.toLowerCase();
+ if (lowered.startsWith("data:") || lowered.startsWith("javascript:")) return null;
+ try {
+ return new URL(raw, document.baseURI).toString();
+ } catch {
+ return raw;
+ }
+}
+
+function resolveNodeAssetUrl(node: Element): string | null {
+ const src = node.getAttribute("src") ?? node.getAttribute("data-src");
+ if (src) return toAbsoluteAssetUrl(src);
+ const compositionSrc = node.getAttribute("data-composition-src");
+ if (compositionSrc) return toAbsoluteAssetUrl(compositionSrc);
+ const mediaDescendant = node.querySelector("img[src], video[src], audio[src], source[src]");
+ if (!mediaDescendant) return null;
+ return toAbsoluteAssetUrl(mediaDescendant.getAttribute("src"));
+}
+
+export function collectRuntimeTimelinePayload(params: {
+ canonicalFps: number;
+ maxTimelineDurationSeconds: number;
+}): RuntimeTimelineMessage {
+ const runtimeWindow = window as Window & {
+ __timelines?: Record<string, RuntimeTimelineLike | undefined>;
+ };
+ const timelineRegistry = runtimeWindow.__timelines ?? {};
+ const startResolver = createRuntimeStartTimeResolver({
+ timelineRegistry,
+ });
+ const resolveTimelineDurationSeconds = (compositionId: string | null): number | null => {
+ if (!compositionId) return null;
+ const timeline = timelineRegistry[compositionId] ?? null;
+ if (!timeline || typeof timeline.duration !== "function") return null;
+ try {
+ const duration = Number(timeline.duration());
+ return Number.isFinite(duration) && duration > 0 ? duration : null;
+ } catch {
+ return null;
+ }
+ };
+ const resolveMediaElementDurationSeconds = (mediaEl: HTMLVideoElement | HTMLAudioElement): number | null => {
+ const declaredDuration = parseNum(mediaEl.getAttribute("data-duration"));
+ if (declaredDuration != null && declaredDuration > 0) {
+ return declaredDuration;
+ }
+ const playbackStart =
+ parseNum(mediaEl.getAttribute("data-playback-start")) ?? parseNum(mediaEl.getAttribute("data-media-start")) ?? 0;
+ if (Number.isFinite(mediaEl.duration) && mediaEl.duration > playbackStart) {
+ return Math.max(0, mediaEl.duration - playbackStart);
+ }
+ return null;
+ };
+ const resolveMediaWindowEndSeconds = (): number | null => {
+ const mediaNodes = Array.from(document.querySelectorAll("video[data-start], audio[data-start]")) as Array<
+ HTMLVideoElement | HTMLAudioElement
+ >;
+ if (mediaNodes.length === 0) return null;
+ let maxWindowEndSeconds = 0;
+ for (const mediaNode of mediaNodes) {
+ const start = startResolver.resolveStartForElement(mediaNode, 0);
+ if (!Number.isFinite(start)) continue;
+ const duration = resolveMediaElementDurationSeconds(mediaNode);
+ if (duration == null || duration <= 0) continue;
+ maxWindowEndSeconds = Math.max(maxWindowEndSeconds, Math.max(0, start) + duration);
+ }
+ return maxWindowEndSeconds > 0 ? maxWindowEndSeconds : null;
+ };
+ const isSceneLikeCompositionId = (compositionId: string): boolean => {
+ const normalized = compositionId.trim().toLowerCase();
+ if (!normalized || normalized === "main") return false;
+ if (normalized.includes("caption")) return false;
+ if (normalized.includes("ambient")) return false;
+ return true;
+ };
+ const resolveNearestCompositionContext = (
+ node: Element,
+ root: Element | null,
+ ): {
+ parentCompositionId: string | null;
+ compositionAncestors: string[];
+ inheritedStart: number | null;
+ inheritedDuration: number | null;
+ } => {
+ const ancestors: string[] = [];
+ let inheritedStart: number | null = null;
+ let inheritedDuration: number | null = null;
+ let parentCompositionId: string | null = null;
+ let cursor = node.parentElement;
+ while (cursor) {
+ const compositionId = cursor.getAttribute("data-composition-id");
+ if (compositionId) {
+ ancestors.push(compositionId);
+ if (!parentCompositionId && cursor !== root) {
+ parentCompositionId = compositionId;
+ }
+ if (inheritedStart == null) {
+ inheritedStart = startResolver.resolveStartForElement(cursor, 0);
+ }
+ if (inheritedDuration == null) {
+ inheritedDuration = parseNum(cursor.getAttribute("data-duration")) ?? null;
+ }
+ }
+ cursor = cursor.parentElement;
+ }
+ return {
+ parentCompositionId,
+ compositionAncestors: ancestors.reverse(),
+ inheritedStart,
+ inheritedDuration,
+ };
+ };
+
+ const root = document.querySelector("[data-composition-id]") as Element | null;
+ const rootCompositionId = root?.getAttribute("data-composition-id") ?? null;
+ const rootCompositionStart = root ? startResolver.resolveStartForElement(root, 0) : 0;
+ const mediaWindowEnd = resolveMediaWindowEndSeconds();
+ const mediaWindowDuration =
+ mediaWindowEnd != null ? Math.max(0, mediaWindowEnd - Math.max(0, rootCompositionStart)) : null;
+ const rootDurationFromTimeline = resolveTimelineDurationSeconds(rootCompositionId);
+ const rootDurationFromAttr = parseNum(root?.getAttribute("data-duration"));
+ const timelineDurationCandidate =
+ typeof rootDurationFromTimeline === "number" &&
+ Number.isFinite(rootDurationFromTimeline) &&
+ rootDurationFromTimeline > 0
+ ? rootDurationFromTimeline
+ : null;
+ const attrDurationCandidate =
+ typeof rootDurationFromAttr === "number" && Number.isFinite(rootDurationFromAttr) && rootDurationFromAttr > 0
+ ? rootDurationFromAttr
+ : null;
+ const mediaWindowDurationCandidate =
+ typeof mediaWindowDuration === "number" && Number.isFinite(mediaWindowDuration) && mediaWindowDuration > 0
+ ? mediaWindowDuration
+ : null;
+ const timelineLooksLoopInflated =
+ timelineDurationCandidate != null &&
+ mediaWindowDurationCandidate != null &&
+ timelineDurationCandidate > mediaWindowDurationCandidate + 1;
+ // Prefer explicit authored root duration first.
+ // If absent, guard against loop-inflated GSAP durations by trusting finite media window.
+ const preferredRootDuration =
+ attrDurationCandidate ??
+ (timelineLooksLoopInflated
+ ? mediaWindowDurationCandidate
+ : (timelineDurationCandidate ?? mediaWindowDurationCandidate));
+ const rootCompositionDuration =
+ preferredRootDuration != null ? Math.min(preferredRootDuration, params.maxTimelineDurationSeconds) : null;
+ const rootCompositionEnd = rootCompositionDuration != null ? rootCompositionStart + rootCompositionDuration : null;
+ const timelineWindowEnd =
+ rootCompositionEnd ??
+ (typeof mediaWindowEnd === "number" && Number.isFinite(mediaWindowEnd) && mediaWindowEnd > 0
+ ? mediaWindowEnd
+ : null);
+ const clampDurationToRootWindow = (start: number, duration: number): number => {
+ if (!Number.isFinite(duration) || duration <= 0) return 0;
+ if (timelineWindowEnd == null || !Number.isFinite(timelineWindowEnd)) return duration;
+ if (!Number.isFinite(start) || start >= timelineWindowEnd) return 0;
+ return Math.max(0, Math.min(duration, timelineWindowEnd - start));
+ };
+ const compositionNodes = Array.from(document.querySelectorAll("[data-composition-id]"));
+ const clips: RuntimeTimelineClip[] = [];
+ const scenes: RuntimeTimelineScene[] = [];
+ const nodes = Array.from(document.querySelectorAll("*"));
+ let maxEnd = 0;
+ for (let i = 0; i < nodes.length; i += 1) {
+ const node = nodes[i];
+ if (node === root) continue;
+ if (["SCRIPT", "STYLE", "LINK", "META", "TEMPLATE", "NOSCRIPT"].includes(node.tagName)) continue;
+ const compositionContext = resolveNearestCompositionContext(node, root);
+ const start = startResolver.resolveStartForElement(node, compositionContext.inheritedStart ?? 0);
+ const nodeCompositionId = node.getAttribute("data-composition-id");
+ let duration = parseNum(node.getAttribute("data-duration"));
+ if ((duration == null || duration <= 0) && nodeCompositionId && nodeCompositionId !== rootCompositionId) {
+ duration = resolveTimelineDurationSeconds(nodeCompositionId);
+ }
+ if ((duration == null || duration <= 0) && node instanceof HTMLMediaElement) {
+ const mediaStart =
+ parseNum(node.getAttribute("data-playback-start")) ?? parseNum(node.getAttribute("data-media-start")) ?? 0;
+ if (Number.isFinite(node.duration) && node.duration > 0) {
+ duration = Math.max(0, node.duration - mediaStart);
+ }
+ }
+ if (duration == null || duration <= 0) {
+ const inheritedDuration = compositionContext.inheritedDuration;
+ if (inheritedDuration != null && inheritedDuration > 0) {
+ const inheritedStart = compositionContext.inheritedStart ?? 0;
+ const inheritedEnd = inheritedStart + inheritedDuration;
+ duration = Math.max(0, inheritedEnd - start);
+ }
+ }
+ if (duration == null || duration <= 0) continue;
+ duration = clampDurationToRootWindow(start, duration);
+ if (duration <= 0) continue;
+ const end = start + duration;
+ maxEnd = Math.max(maxEnd, end);
+ const tag = node.tagName.toLowerCase();
+ const kind: RuntimeTimelineClip["kind"] =
+ nodeCompositionId && nodeCompositionId !== rootCompositionId
+ ? "composition"
+ : tag === "video"
+ ? "video"
+ : tag === "audio"
+ ? "audio"
+ : tag === "img"
+ ? "image"
+ : "element";
+ clips.push({
+ id: (node as HTMLElement).id || `__node__index_${i}`,
+ label:
+ node.getAttribute("data-timeline-label") ??
+ node.getAttribute("data-label") ??
+ node.getAttribute("aria-label") ??
+ (node as HTMLElement).id ??
+ (node as HTMLElement).className?.split(" ")[0] ??
+ kind,
+ start,
+ duration,
+ track:
+ Number.parseInt(node.getAttribute("data-track-index") ?? node.getAttribute("data-track") ?? String(i), 10) || 0,
+ kind,
+ tagName: tag,
+ compositionId: node.getAttribute("data-composition-id"),
+ compositionAncestors: compositionContext.compositionAncestors,
+ parentCompositionId: compositionContext.parentCompositionId,
+ nodePath: null,
+ compositionSrc: toAbsoluteAssetUrl(node.getAttribute("data-composition-src")),
+ assetUrl: resolveNodeAssetUrl(node),
+ timelineRole: node.getAttribute("data-timeline-role"),
+ timelineLabel: node.getAttribute("data-timeline-label"),
+ timelineGroup: node.getAttribute("data-timeline-group"),
+ timelinePriority: parseNum(node.getAttribute("data-timeline-priority")),
+ });
+ }
+ for (const compositionNode of compositionNodes) {
+ if (compositionNode === root) continue;
+ const compositionId = compositionNode.getAttribute("data-composition-id");
+ if (!compositionId || !isSceneLikeCompositionId(compositionId)) continue;
+ const start = startResolver.resolveStartForElement(compositionNode, 0);
+ const durationFromAttr = parseNum(compositionNode.getAttribute("data-duration"));
+ const durationFromTimeline = resolveTimelineDurationSeconds(compositionId);
+ const duration = durationFromAttr && durationFromAttr > 0 ? durationFromAttr : durationFromTimeline;
+ if (duration == null || duration <= 0) continue;
+ const clampedDuration = clampDurationToRootWindow(start, duration);
+ if (clampedDuration <= 0) continue;
+ scenes.push({
+ id: compositionId,
+ label: compositionNode.getAttribute("data-label") ?? compositionId,
+ start,
+ duration: clampedDuration,
+ thumbnailUrl: toAbsoluteAssetUrl(compositionNode.getAttribute("data-thumbnail-url")),
+ avatarName: null,
+ });
+ }
+ const safeDuration = Math.max(1, Math.min(maxEnd || 1, params.maxTimelineDurationSeconds));
+ const shouldEmitNonDeterministicInf = timelineLooksLoopInflated && attrDurationCandidate == null;
+ const durationInFrames = shouldEmitNonDeterministicInf
+ ? Number.POSITIVE_INFINITY
+ : Math.max(1, Math.round(safeDuration * Math.max(1, params.canonicalFps)));
+ return {
+ source: "hf-preview",
+ type: "timeline",
+ durationInFrames,
+ clips,
+ scenes,
+ compositionWidth: parseNum(root?.getAttribute("data-width")) ?? 1920,
+ compositionHeight: parseNum(root?.getAttribute("data-height")) ?? 1080,
+ };
+}
diff --git a/packages/core/src/runtime/types.ts b/packages/core/src/runtime/types.ts
new file mode 100644
index 0000000000..7cfcf8a9e9
--- /dev/null
+++ b/packages/core/src/runtime/types.ts
@@ -0,0 +1,203 @@
+export type RuntimeJson = string | number | boolean | null | RuntimeJson[] | { [key: string]: RuntimeJson };
+
+export type RuntimeBridgeControlAction =
+ | "play"
+ | "pause"
+ | "seek"
+ | "set-muted"
+ | "set-playback-rate"
+ | "enable-pick-mode"
+ | "disable-pick-mode"
+ | "flash-elements";
+
+export type RuntimeBridgeControlMessage = {
+ source: "hf-parent";
+ type: "control";
+ action: RuntimeBridgeControlAction;
+ frame?: number;
+ muted?: boolean;
+ playbackRate?: number;
+ seekMode?: "drag" | "commit";
+};
+
+export type RuntimeStateMessage = {
+ source: "hf-preview";
+ type: "state";
+ frame: number;
+ isPlaying: boolean;
+ muted: boolean;
+ playbackRate: number;
+};
+
+export type RuntimeTimelineClip = {
+ id: string | null;
+ label: string;
+ start: number;
+ duration: number;
+ track: number;
+ kind: "video" | "audio" | "image" | "element" | "composition";
+ tagName: string | null;
+ compositionId: string | null;
+ compositionAncestors: string[];
+ parentCompositionId: string | null;
+ nodePath: string | null;
+ compositionSrc: string | null;
+ assetUrl: string | null;
+ timelineRole: string | null;
+ timelineLabel: string | null;
+ timelineGroup: string | null;
+ timelinePriority: number | null;
+};
+
+export type RuntimeTimelineScene = {
+ id: string;
+ label: string;
+ start: number;
+ duration: number;
+ thumbnailUrl: string | null;
+ avatarName: string | null;
+};
+
+export type RuntimeTimelineMessage = {
+ source: "hf-preview";
+ type: "timeline";
+ durationInFrames: number;
+ clips: RuntimeTimelineClip[];
+ scenes: RuntimeTimelineScene[];
+ compositionWidth: number;
+ compositionHeight: number;
+};
+
+export type RuntimeDiagnosticMessage = {
+ source: "hf-preview";
+ type: "diagnostic";
+ code: string;
+ details: Record<string, RuntimeJson>;
+};
+
+export type RuntimePickerBoundingBox = {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+};
+
+export type RuntimePickerElementInfo = {
+ id: string | null;
+ tagName: string;
+ selector: string;
+ label: string;
+ boundingBox: RuntimePickerBoundingBox;
+ textContent: string | null;
+ src: string | null;
+ dataAttributes: Record<string, string>;
+};
+
+export type RuntimePickerHoveredMessage = {
+ source: "hf-preview";
+ type: "element-hovered";
+ elementInfo: RuntimePickerElementInfo;
+};
+
+export type RuntimePickerCandidatesMessage = {
+ source: "hf-preview";
+ type: "element-pick-candidates";
+ candidates: RuntimePickerElementInfo[];
+ selectedIndex: number;
+ point: { x: number; y: number };
+};
+
+export type RuntimePickerPickedMessage = {
+ source: "hf-preview";
+ type: "element-picked";
+ elementInfo: RuntimePickerElementInfo;
+};
+
+export type RuntimePickerPickedManyMessage = {
+ source: "hf-preview";
+ type: "element-picked-many";
+ elementInfos: RuntimePickerElementInfo[];
+};
+
+export type RuntimePickerCancelledMessage = {
+ source: "hf-preview";
+ type: "pick-mode-cancelled";
+};
+
+export type RuntimeStageSizeMessage = {
+ source: "hf-preview";
+ type: "stage-size";
+ width: number;
+ height: number;
+};
+
+/**
+ * Analytics events emitted by the runtime.
+ *
+ * The host app receives these via postMessage and forwards to its analytics
+ * provider (PostHog, Mixpanel, Amplitude, custom logging, etc.).
+ * No analytics SDK runs inside this iframe.
+ */
+export type RuntimeAnalyticsMessage = {
+ source: "hf-preview";
+ type: "analytics";
+ event:
+ | "composition_loaded"
+ | "composition_played"
+ | "composition_paused"
+ | "composition_seeked"
+ | "composition_ended"
+ | "element_picked";
+ properties: Record<string, string | number | boolean | null>;
+};
+
+export type RuntimeOutboundMessage =
+ | RuntimeStateMessage
+ | RuntimeTimelineMessage
+ | RuntimeDiagnosticMessage
+ | RuntimePickerHoveredMessage
+ | RuntimePickerCandidatesMessage
+ | RuntimePickerPickedMessage
+ | RuntimePickerPickedManyMessage
+ | RuntimePickerCancelledMessage
+ | RuntimeStageSizeMessage
+ | RuntimeAnalyticsMessage;
+
+export type RuntimePlayer = {
+ _timeline: RuntimeTimelineLike | null;
+ play: () => void;
+ pause: () => void;
+ seek: (timeSeconds: number) => void;
+ renderSeek: (timeSeconds: number) => void;
+ getTime: () => number;
+ getDuration: () => number;
+ isPlaying: () => boolean;
+ setPlaybackRate: (rate: number) => void;
+ getPlaybackRate: () => number;
+};
+
+export type RuntimeTimelineLike = {
+ play: () => void;
+ pause: () => void;
+ seek: (timeSeconds: number, suppressEvents?: boolean) => void;
+ totalTime?: (timeSeconds: number, suppressEvents?: boolean) => void;
+ time: () => number;
+ duration: () => number;
+ add: (timeline: RuntimeTimelineLike, startAtSeconds: number) => void;
+ paused: (paused?: boolean) => void;
+ timeScale?: (rate: number) => void;
+ set: (target: RuntimeGsapSetTarget, vars: RuntimeGsapSetVars, atSeconds?: number) => void;
+};
+
+export type RuntimeDeterministicAdapter = {
+ name: string;
+ discover: () => void;
+ seek: (ctx: { time: number }) => void;
+ pause: () => void;
+ play?: () => void;
+ revert?: () => void;
+};
+
+export type RuntimeGsapSetTarget = string | Element | Element[] | null;
+
+export type RuntimeGsapSetVars = Record<string, string | number | boolean | null | undefined>;
diff --git a/packages/core/src/runtime/window.d.ts b/packages/core/src/runtime/window.d.ts
new file mode 100644
index 0000000000..cf9b105558
--- /dev/null
+++ b/packages/core/src/runtime/window.d.ts
@@ -0,0 +1,66 @@
+import type { RuntimeTimelineMessage, RuntimeTimelineLike } from "./types";
+import type { HyperframePickerApi } from "../inline-scripts/pickerApi";
+import type { PlayerAPI } from "../core.types";
+
+type ThreeClockLike = {
+ elapsedTime: number;
+ oldTime: number;
+ startTime: number;
+ getElapsedTime: () => number;
+ getDelta: () => number;
+};
+
+type ThreeAnimationMixerLike = {
+ setTime?: (time: number) => void;
+ update: (deltaTime: number) => ThreeAnimationMixerLike;
+};
+
+type ThreeLike = {
+ Clock?: {
+ prototype: ThreeClockLike;
+ };
+ AnimationMixer?: {
+ prototype: ThreeAnimationMixerLike;
+ };
+};
+
+declare global {
+ interface Window {
+ __timelines: Record<string, RuntimeTimelineLike>;
+ __player?: PlayerAPI;
+ __clipManifest?: RuntimeTimelineMessage;
+ __playerReady?: boolean;
+ __renderReady?: boolean;
+ __HF_PARITY_MODE?: boolean;
+ __HF_FPS?: number;
+ __HF_MAX_DURATION_SEC?: number;
+ __hfThreeTime?: number;
+ __HF_PICKER_API?: HyperframePickerApi;
+ gsap?: {
+ timeline: (params?: { paused?: boolean }) => RuntimeTimelineLike;
+ ticker?: {
+ tick: () => void;
+ };
+ };
+ THREE?: ThreeLike;
+ /**
+ * Global lottie-web instance (set by including the lottie.min.js script).
+ * The adapter uses `lottie.getRegisteredAnimations()` for auto-discovery.
+ */
+ lottie?: {
+ loadAnimation: (params: unknown) => unknown;
+ getRegisteredAnimations: () => unknown[];
+ };
+ /**
+ * Lottie animation instances registered by compositions.
+ * The adapter seeks all instances when the player is seeked.
+ *
+ * Push your animation instance here after calling `lottie.loadAnimation()`:
+ * window.__hfLottie = window.__hfLottie || [];
+ * window.__hfLottie.push(anim);
+ */
+ __hfLottie?: unknown[];
+ }
+}
+
+export {};
diff --git a/packages/core/src/templates/base.test.ts b/packages/core/src/templates/base.test.ts
new file mode 100644
index 0000000000..ec1b6b9fc9
--- /dev/null
+++ b/packages/core/src/templates/base.test.ts
@@ -0,0 +1,114 @@
+import { describe, it, expect } from "vitest";
+import { generateBaseHtml, getStageStyles } from "./base.js";
+import {
+ GSAP_CDN,
+ BASE_STYLES,
+ ELEMENT_BASE_STYLES,
+ MEDIA_STYLES,
+ TEXT_STYLES,
+ ZOOM_CONTAINER_STYLES,
+} from "./constants.js";
+
+describe("generateBaseHtml", () => {
+ it("generates valid HTML structure with DOCTYPE", () => {
+ const html = generateBaseHtml();
+ expect(html).toContain("<!DOCTYPE html>");
+ expect(html).toContain("<html");
+ expect(html).toContain("</html>");
+ expect(html).toContain("<head>");
+ expect(html).toContain("</head>");
+ expect(html).toContain("<body>");
+ expect(html).toContain("</body>");
+ });
+
+ it("includes #stage element", () => {
+ const html = generateBaseHtml();
+ expect(html).toContain('id="stage"');
+ });
+
+ it("includes #stage-zoom-container element", () => {
+ const html = generateBaseHtml();
+ expect(html).toContain('id="stage-zoom-container"');
+ });
+
+ it("defaults to portrait resolution", () => {
+ const html = generateBaseHtml();
+ expect(html).toContain('data-resolution="portrait"');
+ });
+
+ it("accepts landscape resolution", () => {
+ const html = generateBaseHtml("landscape");
+ expect(html).toContain('data-resolution="landscape"');
+ });
+
+ it("accepts portrait resolution explicitly", () => {
+ const html = generateBaseHtml("portrait");
+ expect(html).toContain('data-resolution="portrait"');
+ });
+
+ it("includes meta charset and viewport", () => {
+ const html = generateBaseHtml();
+ expect(html).toContain('charset="UTF-8"');
+ expect(html).toContain('name="viewport"');
+ });
+});
+
+describe("getStageStyles", () => {
+ it("returns landscape stage styles (1920x1080)", () => {
+ const styles = getStageStyles("landscape");
+ expect(styles).toContain("width: 1920px");
+ expect(styles).toContain("height: 1080px");
+ expect(styles).toContain("position: relative");
+ expect(styles).toContain("overflow: hidden");
+ });
+
+ it("returns portrait stage styles (1080x1920)", () => {
+ const styles = getStageStyles("portrait");
+ expect(styles).toContain("width: 1080px");
+ expect(styles).toContain("height: 1920px");
+ });
+
+ it("defaults to portrait", () => {
+ const styles = getStageStyles();
+ expect(styles).toContain("width: 1080px");
+ expect(styles).toContain("height: 1920px");
+ });
+});
+
+describe("constants", () => {
+ it("GSAP_CDN is a valid URL", () => {
+ expect(GSAP_CDN).toMatch(/^https:\/\//);
+ expect(GSAP_CDN).toContain("gsap");
+ expect(GSAP_CDN).toContain(".min.js");
+ });
+
+ it("BASE_STYLES contains reset styles", () => {
+ expect(BASE_STYLES).toContain("margin: 0");
+ expect(BASE_STYLES).toContain("padding: 0");
+ expect(BASE_STYLES).toContain("box-sizing: border-box");
+ });
+
+ it("ELEMENT_BASE_STYLES includes position and visibility", () => {
+ expect(ELEMENT_BASE_STYLES).toContain("position: absolute");
+ expect(ELEMENT_BASE_STYLES).toContain("visibility: hidden");
+ });
+
+ it("MEDIA_STYLES includes object-fit", () => {
+ expect(MEDIA_STYLES).toContain("object-fit: contain");
+ expect(MEDIA_STYLES).toContain("width: 100%");
+ expect(MEDIA_STYLES).toContain("height: 100%");
+ });
+
+ it("TEXT_STYLES includes font and alignment", () => {
+ expect(TEXT_STYLES).toContain("font-size: 48px");
+ expect(TEXT_STYLES).toContain("font-weight: bold");
+ expect(TEXT_STYLES).toContain("color: white");
+ expect(TEXT_STYLES).toContain("display: flex");
+ });
+
+ it("ZOOM_CONTAINER_STYLES includes transform-origin", () => {
+ expect(ZOOM_CONTAINER_STYLES).toContain("transform-origin: 0 0");
+ expect(ZOOM_CONTAINER_STYLES).toContain("position: absolute");
+ expect(ZOOM_CONTAINER_STYLES).toContain("inset: 0");
+ });
+});
diff --git a/packages/core/src/templates/base.ts b/packages/core/src/templates/base.ts
new file mode 100644
index 0000000000..7e909d98da
--- /dev/null
+++ b/packages/core/src/templates/base.ts
@@ -0,0 +1,21 @@
+import { CANVAS_DIMENSIONS, type CanvasResolution } from "../core.types";
+
+export function generateBaseHtml(resolution: CanvasResolution = "portrait"): string {
+ return `<!DOCTYPE html>
+<html data-resolution="${resolution}">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+</head>
+<body>
+ <div id="stage">
+ <div id="stage-zoom-container"></div>
+ </div>
+</body>
+</html>`;
+}
+
+export function getStageStyles(resolution: CanvasResolution = "portrait"): string {
+ const { width, height } = CANVAS_DIMENSIONS[resolution];
+ return `position: relative; width: ${width}px; height: ${height}px; overflow: hidden; background: #000;`;
+}
diff --git a/packages/core/src/templates/constants.ts b/packages/core/src/templates/constants.ts
new file mode 100644
index 0000000000..eabb04fbb1
--- /dev/null
+++ b/packages/core/src/templates/constants.ts
@@ -0,0 +1,12 @@
+export const GSAP_CDN = "https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js";
+
+export const BASE_STYLES = `* { margin: 0; padding: 0; box-sizing: border-box; }
+html, body { width: 100%; height: 100%; overflow: hidden; background: #000; display: flex; align-items: center; justify-content: center; }`;
+
+export const ELEMENT_BASE_STYLES = `position: absolute; visibility: hidden;`;
+
+export const MEDIA_STYLES = `width: 100%; height: 100%; object-fit: contain;`;
+
+export const TEXT_STYLES = `display: flex; align-items: center; justify-content: center; font-family: system-ui, -apple-system, sans-serif; font-size: 48px; font-weight: bold; color: white; text-shadow: 2px 2px 4px rgba(0,0,0,0.8); width: 100%; height: 100%;`;
+
+export const ZOOM_CONTAINER_STYLES = `position: absolute; inset: 0; transform-origin: 0 0;`;
diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json
new file mode 100644
index 0000000000..e6c2b5a440
--- /dev/null
+++ b/packages/core/tsconfig.json
@@ -0,0 +1,18 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true,
+ "outDir": "./dist",
+ "rootDir": "./src"
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules", "dist", "src/tests", "src/runtime", "**/*.test.ts"]
+}
diff --git a/packages/core/vitest.config.ts b/packages/core/vitest.config.ts
new file mode 100644
index 0000000000..58fade59e5
--- /dev/null
+++ b/packages/core/vitest.config.ts
@@ -0,0 +1,27 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: ["src/**/*.test.ts"],
+ environment: "jsdom",
+ coverage: {
+ provider: "v8",
+ include: ["src/runtime/**/*.ts"],
+ exclude: [
+ "src/runtime/**/*.test.ts",
+ "src/runtime/types.ts",
+ "src/runtime/window.d.ts",
+ "src/runtime/entry.ts",
+ "src/runtime/init.ts",
+ "src/runtime/README.md",
+ ],
+ thresholds: {
+ // Enforced in CI — these are floor values, not targets
+ statements: 75,
+ branches: 70,
+ functions: 80,
+ lines: 75,
+ },
+ },
+ },
+});
diff --git a/packages/engine/package.json b/packages/engine/package.json
new file mode 100644
index 0000000000..eb6b1ee80d
--- /dev/null
+++ b/packages/engine/package.json
@@ -0,0 +1,30 @@
+{
+ "name": "@hyperframes/engine",
+ "version": "0.1.0",
+ "description": "Seekable web page to video rendering engine (Puppeteer + FFmpeg)",
+ "type": "module",
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "scripts": {
+ "build": "tsc",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@hono/node-server": "^1.13.0",
+ "@hyperframes/core": "workspace:*",
+ "hono": "^4.6.0",
+ "linkedom": "^0.18.12",
+ "puppeteer": "^24.0.0",
+ "puppeteer-core": "^24.39.1"
+ },
+ "devDependencies": {
+ "@types/node": "^22.10.1",
+ "typescript": "^5.7.2"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+}
diff --git a/packages/engine/src/cdp-headless-experimental.d.ts b/packages/engine/src/cdp-headless-experimental.d.ts
new file mode 100644
index 0000000000..271da171a6
--- /dev/null
+++ b/packages/engine/src/cdp-headless-experimental.d.ts
@@ -0,0 +1,54 @@
+/**
+ * Type augmentation for Chrome's HeadlessExperimental CDP domain.
+ *
+ * Puppeteer's CDPSession.send() is typed against devtools-protocol's
+ * ProtocolMapping.Commands, which does not include HeadlessExperimental.
+ * This module augmentation adds proper types so we can call these methods
+ * without unsafe `as any` casts.
+ */
+
+/** Parameters for HeadlessExperimental.beginFrame */
+interface HeadlessExperimentalBeginFrameRequest {
+ /** Timestamp in milliseconds since epoch for the frame */
+ frameTimeTicks: number;
+ /** Interval in milliseconds between frames */
+ interval: number;
+ /** If true, do not produce display updates (warmup mode) */
+ noDisplayUpdates?: boolean;
+ /** Optional screenshot configuration */
+ screenshot?: {
+ format: "jpeg" | "png";
+ quality?: number;
+ optimizeForSpeed?: boolean;
+ };
+}
+
+/** Response from HeadlessExperimental.beginFrame */
+interface HeadlessExperimentalBeginFrameResponse {
+ /** Whether the compositor reported visual damage */
+ hasDamage: boolean;
+ /** Base64-encoded screenshot data (present only when screenshot was requested and hasDamage is true) */
+ screenshotData?: string;
+}
+
+export {};
+
+declare module "devtools-protocol/types/protocol-mapping.js" {
+ // Merge into the existing ProtocolMapping namespace
+ export namespace ProtocolMapping {
+ interface Commands {
+ "HeadlessExperimental.enable": {
+ paramsType: [];
+ returnType: void;
+ };
+ "HeadlessExperimental.disable": {
+ paramsType: [];
+ returnType: void;
+ };
+ "HeadlessExperimental.beginFrame": {
+ paramsType: [HeadlessExperimentalBeginFrameRequest];
+ returnType: HeadlessExperimentalBeginFrameResponse;
+ };
+ }
+ }
+}
diff --git a/packages/engine/src/config.test.ts b/packages/engine/src/config.test.ts
new file mode 100644
index 0000000000..ce26ae8473
--- /dev/null
+++ b/packages/engine/src/config.test.ts
@@ -0,0 +1,95 @@
+import { describe, it, expect, beforeEach, afterEach } from "vitest";
+import { resolveConfig, DEFAULT_CONFIG } from "./config.js";
+
+describe("resolveConfig", () => {
+ const savedEnv = new Map<string, string | undefined>();
+
+ function setEnv(key: string, value: string) {
+ savedEnv.set(key, process.env[key]);
+ process.env[key] = value;
+ }
+
+ beforeEach(() => {
+ savedEnv.clear();
+ });
+
+ afterEach(() => {
+ for (const [key, value] of savedEnv) {
+ if (value === undefined) {
+ delete process.env[key];
+ } else {
+ process.env[key] = value;
+ }
+ }
+ });
+
+ it("returns defaults when no overrides or env vars are set", () => {
+ const config = resolveConfig();
+ expect(config.fps).toBe(30);
+ expect(config.quality).toBe("standard");
+ expect(config.format).toBe("jpeg");
+ expect(config.jpegQuality).toBe(80);
+ expect(config.debug).toBe(false);
+ });
+
+ it("applies explicit overrides over defaults", () => {
+ const config = resolveConfig({ fps: 60, debug: true });
+ expect(config.fps).toBe(60);
+ expect(config.debug).toBe(true);
+ // Non-overridden fields remain at defaults
+ expect(config.quality).toBe("standard");
+ });
+
+ it("reads numeric env vars with PRODUCER_ prefix", () => {
+ setEnv("PRODUCER_MAX_WORKERS", "4");
+ setEnv("PRODUCER_CORES_PER_WORKER", "3");
+
+ const config = resolveConfig();
+ expect(config.concurrency).toBe(4);
+ expect(config.coresPerWorker).toBe(3);
+ });
+
+ it("reads boolean env vars (true/false strings)", () => {
+ setEnv("PRODUCER_DISABLE_GPU", "true");
+ setEnv("PRODUCER_ENABLE_BROWSER_POOL", "true");
+
+ const config = resolveConfig();
+ expect(config.disableGpu).toBe(true);
+ expect(config.enableBrowserPool).toBe(true);
+ });
+
+ it("treats non-'true' boolean env vars as false", () => {
+ setEnv("PRODUCER_DISABLE_GPU", "yes");
+
+ const config = resolveConfig();
+ expect(config.disableGpu).toBe(false);
+ });
+
+ it("explicit overrides take precedence over env vars", () => {
+ setEnv("PRODUCER_CORES_PER_WORKER", "5");
+
+ const config = resolveConfig({ coresPerWorker: 8 });
+ expect(config.coresPerWorker).toBe(8);
+ });
+
+ it("falls back to defaults for invalid numeric env vars", () => {
+ setEnv("PRODUCER_CORES_PER_WORKER", "not-a-number");
+
+ const config = resolveConfig();
+ expect(config.coresPerWorker).toBe(DEFAULT_CONFIG.coresPerWorker);
+ });
+
+ it("clamps chunkSizeFrames to minimum of 120", () => {
+ setEnv("PRODUCER_CHUNK_SIZE_FRAMES", "50");
+
+ const config = resolveConfig();
+ expect(config.chunkSizeFrames).toBe(120);
+ });
+
+ it("clamps frameDataUriCacheLimit to minimum of 32", () => {
+ setEnv("PRODUCER_FRAME_DATA_URI_CACHE_LIMIT", "10");
+
+ const config = resolveConfig();
+ expect(config.frameDataUriCacheLimit).toBe(32);
+ });
+});
diff --git a/packages/engine/src/config.ts b/packages/engine/src/config.ts
new file mode 100644
index 0000000000..9813e53e7f
--- /dev/null
+++ b/packages/engine/src/config.ts
@@ -0,0 +1,176 @@
+/**
+ * Engine Configuration
+ *
+ * Typed configuration for the rendering pipeline. Replaces the PRODUCER_*
+ * env var sprawl with a structured interface. Env vars still work as
+ * fallbacks for backward compatibility during migration.
+ */
+
+/**
+ * Full engine configuration. All fields are wired through the config
+ * object; env vars serve as backward-compatible fallbacks resolved
+ * in `resolveConfig()`.
+ */
+export interface EngineConfig {
+ // ── Rendering ────────────────────────────────────────────────────────
+ fps: 24 | 30 | 60;
+ quality: "draft" | "standard" | "high";
+ format: "jpeg" | "png";
+ jpegQuality: number;
+
+ // ── Parallelism ──────────────────────────────────────────────────────
+ /** Max worker count. "auto" uses CPU-based heuristic. */
+ concurrency: number | "auto";
+ /** CPU cores allocated per worker. */
+ coresPerWorker: number;
+ /** Minimum frames before parallel workers are used. */
+ minParallelFrames: number;
+ /** Frame count threshold for "large render" heuristics. */
+ largeRenderThreshold: number;
+
+ // ── Browser ──────────────────────────────────────────────────────────
+ chromePath?: string;
+ disableGpu: boolean;
+ enableBrowserPool: boolean;
+ browserTimeout: number;
+ protocolTimeout: number;
+ /** Expected Chromium major version (optional validation). */
+ expectedChromiumMajor?: number;
+ /** Force screenshot capture mode (skip BeginFrame even on Linux). */
+ forceScreenshot: boolean;
+
+ // ── Encoding ─────────────────────────────────────────────────────────
+ enableChunkedEncode: boolean;
+ chunkSizeFrames: number;
+ enableStreamingEncode: boolean;
+
+ // ── FFmpeg timeouts ──────────────────────────────────────────────────
+ /** Timeout for FFmpeg frame encoding (ms). Default: 600_000 */
+ ffmpegEncodeTimeout: number;
+ /** Timeout for FFmpeg mux/faststart processes (ms). Default: 300_000 */
+ ffmpegProcessTimeout: number;
+ /** Timeout for FFmpeg streaming encode (ms). Default: 600_000 */
+ ffmpegStreamingTimeout: number;
+
+ // ── Media ────────────────────────────────────────────────────────────
+ audioGain: number;
+ frameDataUriCacheLimit: number;
+
+ // ── Timeouts ─────────────────────────────────────────────────────────
+ playerReadyTimeout: number;
+ renderReadyTimeout: number;
+
+ // ── Runtime ──────────────────────────────────────────────────────────
+ /** Verify Hyperframe runtime SHA256 checksums. */
+ verifyRuntime: boolean;
+ /** Custom manifest path for Hyperframe runtime. */
+ runtimeManifestPath?: string;
+
+ // ── Debug ────────────────────────────────────────────────────────────
+ debug: boolean;
+}
+
+/** Default configuration — sensible for Hyperframes compositions. */
+export const DEFAULT_CONFIG: EngineConfig = {
+ fps: 30,
+ quality: "standard",
+ format: "jpeg",
+ jpegQuality: 80,
+
+ concurrency: "auto",
+ coresPerWorker: 2.5,
+ minParallelFrames: 120,
+ largeRenderThreshold: 1000,
+
+ disableGpu: false,
+ enableBrowserPool: false,
+ browserTimeout: 120_000,
+ protocolTimeout: 300_000,
+ forceScreenshot: false,
+
+ enableChunkedEncode: false,
+ chunkSizeFrames: 360,
+ enableStreamingEncode: false,
+
+ ffmpegEncodeTimeout: 600_000,
+ ffmpegProcessTimeout: 300_000,
+ ffmpegStreamingTimeout: 600_000,
+
+ audioGain: 1.35,
+ frameDataUriCacheLimit: 256,
+
+ playerReadyTimeout: 45_000,
+ renderReadyTimeout: 15_000,
+
+ verifyRuntime: true,
+
+ debug: false,
+};
+
+/**
+ * Resolve configuration by merging: defaults ← env vars ← explicit overrides.
+ * Env vars provide backward compatibility during migration; explicit config
+ * takes precedence over everything.
+ */
+export function resolveConfig(overrides?: Partial<EngineConfig>): EngineConfig {
+ const env = (key: string): string | undefined => process.env[key];
+ const envNum = (key: string, fallback: number): number => {
+ const raw = env(key);
+ if (raw === undefined || raw === "") return fallback;
+ const n = Number(raw);
+ return Number.isFinite(n) ? n : fallback;
+ };
+ const envBool = (key: string, fallback: boolean): boolean => {
+ const raw = env(key);
+ if (raw === undefined) return fallback;
+ return raw === "true";
+ };
+
+ // Env-var layer (backward compat)
+ const fromEnv: Partial<EngineConfig> = {
+ concurrency: env("PRODUCER_MAX_WORKERS") ? Number(env("PRODUCER_MAX_WORKERS")) : undefined,
+ coresPerWorker: envNum("PRODUCER_CORES_PER_WORKER", DEFAULT_CONFIG.coresPerWorker),
+ minParallelFrames: envNum("PRODUCER_MIN_PARALLEL_FRAMES", DEFAULT_CONFIG.minParallelFrames),
+ largeRenderThreshold: envNum("PRODUCER_LARGE_RENDER_THRESHOLD", DEFAULT_CONFIG.largeRenderThreshold),
+
+ chromePath: env("PRODUCER_HEADLESS_SHELL_PATH"),
+ disableGpu: envBool("PRODUCER_DISABLE_GPU", DEFAULT_CONFIG.disableGpu),
+ enableBrowserPool: envBool("PRODUCER_ENABLE_BROWSER_POOL", DEFAULT_CONFIG.enableBrowserPool),
+ browserTimeout: envNum("PRODUCER_PUPPETEER_LAUNCH_TIMEOUT_MS", DEFAULT_CONFIG.browserTimeout),
+ protocolTimeout: envNum("PRODUCER_PUPPETEER_PROTOCOL_TIMEOUT_MS", DEFAULT_CONFIG.protocolTimeout),
+ expectedChromiumMajor: env("PRODUCER_EXPECTED_CHROMIUM_MAJOR")
+ ? Number(env("PRODUCER_EXPECTED_CHROMIUM_MAJOR"))
+ : undefined,
+
+ forceScreenshot: envBool("PRODUCER_FORCE_SCREENSHOT", DEFAULT_CONFIG.forceScreenshot),
+
+ enableChunkedEncode: envBool("PRODUCER_ENABLE_CHUNKED_ENCODE", DEFAULT_CONFIG.enableChunkedEncode),
+ chunkSizeFrames: Math.max(120, envNum("PRODUCER_CHUNK_SIZE_FRAMES", DEFAULT_CONFIG.chunkSizeFrames)),
+ enableStreamingEncode: envBool("PRODUCER_ENABLE_STREAMING_ENCODE", DEFAULT_CONFIG.enableStreamingEncode),
+
+ ffmpegEncodeTimeout: envNum("FFMPEG_ENCODE_TIMEOUT_MS", DEFAULT_CONFIG.ffmpegEncodeTimeout),
+ ffmpegProcessTimeout: envNum("FFMPEG_PROCESS_TIMEOUT_MS", DEFAULT_CONFIG.ffmpegProcessTimeout),
+ ffmpegStreamingTimeout: envNum("FFMPEG_STREAMING_TIMEOUT_MS", DEFAULT_CONFIG.ffmpegStreamingTimeout),
+
+ audioGain: envNum("PRODUCER_AUDIO_GAIN", DEFAULT_CONFIG.audioGain),
+ frameDataUriCacheLimit: Math.max(
+ 32,
+ envNum("PRODUCER_FRAME_DATA_URI_CACHE_LIMIT", DEFAULT_CONFIG.frameDataUriCacheLimit),
+ ),
+
+ playerReadyTimeout: envNum("PRODUCER_PLAYER_READY_TIMEOUT_MS", DEFAULT_CONFIG.playerReadyTimeout),
+ renderReadyTimeout: envNum("PRODUCER_RENDER_READY_TIMEOUT_MS", DEFAULT_CONFIG.renderReadyTimeout),
+
+ verifyRuntime: env("PRODUCER_VERIFY_HYPERFRAME_RUNTIME") !== "false",
+ runtimeManifestPath: env("PRODUCER_HYPERFRAME_MANIFEST_PATH"),
+ };
+
+ // Remove undefined values so they don't override defaults
+ const cleanEnv = Object.fromEntries(Object.entries(fromEnv).filter(([, v]) => v !== undefined));
+
+ return {
+ ...DEFAULT_CONFIG,
+ ...cleanEnv,
+ ...overrides,
+ };
+}
diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.ts
new file mode 100644
index 0000000000..18d327138c
--- /dev/null
+++ b/packages/engine/src/index.ts
@@ -0,0 +1,154 @@
+/**
+ * @hyperframes/engine
+ *
+ * Seekable web page to video rendering engine.
+ * Framework-agnostic: works with GSAP, Lottie, Three.js, CSS animations,
+ * or any web content that implements the window.__hf seek protocol.
+ *
+ * ## Error Convention
+ *
+ * Engine services use three error strategies depending on the operation type:
+ *
+ * - **Orchestration services throw on failure.** Browser launch, session init,
+ * frame capture, and CDP operations propagate errors as thrown exceptions.
+ * Callers are expected to catch and handle (e.g. frameCapture, browserManager,
+ * screenshotService, videoFrameExtractor.extractVideoFramesRange).
+ *
+ * - **FFmpeg process wrappers return `{ success, error? }` result objects.**
+ * Encoding, muxing, audio mixing, and streaming encode operations never reject.
+ * They resolve with a result that includes `success: boolean` and an optional
+ * `error` string (e.g. chunkEncoder, audioMixer, streamingEncoder).
+ *
+ * - **Cleanup and teardown functions never throw.** Browser close, session close,
+ * temp directory removal, and resource release swallow errors via `.catch(() => {})`
+ * to avoid masking the original failure (e.g. releaseBrowser, closeCaptureSession,
+ * FrameLookupTable.cleanup).
+ *
+ * - **Optional lookups return `T | undefined` or `T | null`.**
+ * Functions that may legitimately find nothing (resolveHeadlessShellPath,
+ * getFrameAtTime, detectGpuEncoder) return a nullable value instead of throwing.
+ *
+ */
+
+// ── Protocol types ─────────────────────────────────────────────────────────────
+export type {
+ HfProtocol,
+ HfMediaElement,
+ CaptureOptions,
+ CaptureResult,
+ CaptureBufferResult,
+ CapturePerfSummary,
+} from "./types.js";
+
+// ── Configuration ──────────────────────────────────────────────────────────────
+export { resolveConfig, DEFAULT_CONFIG, type EngineConfig } from "./config.js";
+
+// ── Browser management ─────────────────────────────────────────────────────────
+export {
+ acquireBrowser,
+ releaseBrowser,
+ resolveHeadlessShellPath,
+ buildChromeArgs,
+ ENABLE_BROWSER_POOL,
+ type BuildChromeArgsOptions,
+ type CaptureMode,
+ type AcquiredBrowser,
+} from "./services/browserManager.js";
+
+// ── Frame capture pipeline ──────────────────────────────────────────────────────
+export {
+ createCaptureSession,
+ initializeSession,
+ closeCaptureSession,
+ captureFrame,
+ captureFrameToBuffer,
+ getCompositionDuration,
+ getCapturePerfSummary,
+ prepareCaptureSessionForReuse,
+ type CaptureSession,
+ type BeforeCaptureHook,
+} from "./services/frameCapture.js";
+
+// ── Screenshot (BeginFrame) ─────────────────────────────────────────────────────
+export {
+ beginFrameCapture,
+ pageScreenshotCapture,
+ getCdpSession,
+ injectVideoFramesBatch,
+ syncVideoFrameVisibility,
+ cdpSessionCache,
+ type BeginFrameResult,
+} from "./services/screenshotService.js";
+
+// ── Encoding ───────────────────────────────────────────────────────────────────
+export {
+ encodeFramesFromDir,
+ encodeFramesChunkedConcat,
+ muxVideoWithAudio,
+ applyFaststart,
+ detectGpuEncoder,
+ ENCODER_PRESETS,
+ type GpuEncoder,
+} from "./services/chunkEncoder.js";
+export type {
+ EncoderOptions,
+ EncodeResult,
+ MuxResult,
+} from "./services/chunkEncoder.types.js";
+
+export {
+ spawnStreamingEncoder,
+ createFrameReorderBuffer,
+ type StreamingEncoder,
+ type StreamingEncoderOptions,
+ type StreamingEncoderResult,
+ type FrameReorderBuffer,
+} from "./services/streamingEncoder.js";
+
+// ── Media processing ───────────────────────────────────────────────────────────
+export {
+ parseVideoElements,
+ extractVideoFramesRange,
+ extractAllVideoFrames,
+ getFrameAtTime,
+ createFrameLookupTable,
+ FrameLookupTable,
+ type VideoElement,
+ type ExtractedFrames,
+ type ExtractionOptions,
+ type ExtractionResult,
+} from "./services/videoFrameExtractor.js";
+
+export { createVideoFrameInjector } from "./services/videoFrameInjector.js";
+
+export {
+ parseAudioElements,
+ processCompositionAudio,
+} from "./services/audioMixer.js";
+export type {
+ AudioElement,
+ AudioTrack,
+ MixResult,
+} from "./services/audioMixer.types.js";
+
+// ── Parallel rendering ─────────────────────────────────────────────────────────
+export {
+ calculateOptimalWorkers,
+ distributeFrames,
+ executeParallelCapture,
+ mergeWorkerFrames,
+ getSystemResources,
+ type WorkerTask,
+ type WorkerResult,
+ type ParallelProgress,
+} from "./services/parallelCoordinator.js";
+
+// ── File server ────────────────────────────────────────────────────────────────
+export { createFileServer, type FileServerOptions, type FileServerHandle } from "./services/fileServer.js";
+
+// ── Utilities ──────────────────────────────────────────────────────────────────
+export { quantizeTimeToFrame, MEDIA_VISUAL_STYLE_PROPERTIES } from "@hyperframes/core";
+
+export { extractVideoMetadata, extractAudioMetadata, type VideoMetadata, type AudioMetadata } from "./utils/ffprobe.js";
+
+export { downloadToTemp, isHttpUrl } from "./utils/urlDownloader.js";
diff --git a/packages/engine/src/services/audioMixer.ts b/packages/engine/src/services/audioMixer.ts
new file mode 100644
index 0000000000..67c73e8660
--- /dev/null
+++ b/packages/engine/src/services/audioMixer.ts
@@ -0,0 +1,392 @@
+/**
+ * Audio Mixer Service
+ *
+ * Processes and mixes audio tracks using FFmpeg.
+ */
+
+import { existsSync, mkdirSync, rmSync } from "fs";
+import { join, dirname } from "path";
+import { parseHTML } from "linkedom";
+import { extractAudioMetadata } from "../utils/ffprobe.js";
+import { downloadToTemp, isHttpUrl } from "../utils/urlDownloader.js";
+import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";
+import { runFfmpeg } from "../utils/runFfmpeg.js";
+import type { AudioElement, AudioTrack, MixResult } from "./audioMixer.types.js";
+
+export type { AudioElement, AudioTrack, MixResult } from "./audioMixer.types.js";
+
+interface ExtractResult {
+ success: boolean;
+ outputPath: string;
+ durationMs: number;
+ error?: string;
+}
+
+export function parseAudioElements(html: string): AudioElement[] {
+ const elements: AudioElement[] = [];
+ const { document } = parseHTML(html);
+
+ // Parse <audio> elements
+ const audioEls = document.querySelectorAll("audio[id][src]");
+ for (const el of audioEls) {
+ const id = el.getAttribute("id");
+ const src = el.getAttribute("src");
+ if (!id || !src) continue;
+
+ const startAttr = el.getAttribute("data-start");
+ const endAttr = el.getAttribute("data-end");
+ const mediaStartAttr = el.getAttribute("data-media-start");
+ const layerAttr = el.getAttribute("data-layer");
+ const volumeAttr = el.getAttribute("data-volume");
+
+ elements.push({
+ id,
+ src,
+ start: startAttr ? parseFloat(startAttr) : 0,
+ end: endAttr ? parseFloat(endAttr) : 0,
+ mediaStart: mediaStartAttr ? parseFloat(mediaStartAttr) : 0,
+ layer: layerAttr ? parseInt(layerAttr) : 0,
+ volume: volumeAttr ? parseFloat(volumeAttr) : 1.0,
+ type: "audio",
+ });
+ }
+
+ // Parse <video> elements with data-has-audio="true"
+ const videoEls = document.querySelectorAll('video[id][src][data-has-audio="true"]');
+ for (const el of videoEls) {
+ const id = el.getAttribute("id");
+ const src = el.getAttribute("src");
+ if (!id || !src) continue;
+
+ const startAttr = el.getAttribute("data-start");
+ const endAttr = el.getAttribute("data-end");
+ const mediaStartAttr = el.getAttribute("data-media-start");
+ const layerAttr = el.getAttribute("data-layer");
+ const volumeAttr = el.getAttribute("data-volume");
+
+ elements.push({
+ id: `${id}-audio`,
+ src,
+ start: startAttr ? parseFloat(startAttr) : 0,
+ end: endAttr ? parseFloat(endAttr) : 0,
+ mediaStart: mediaStartAttr ? parseFloat(mediaStartAttr) : 0,
+ layer: layerAttr ? parseInt(layerAttr) : 0,
+ volume: volumeAttr ? parseFloat(volumeAttr) : 1.0,
+ type: "video",
+ });
+ }
+
+ return elements;
+}
+
+async function extractAudioFromVideo(
+ videoPath: string,
+ outputPath: string,
+ options?: { startTime?: number; duration?: number },
+ signal?: AbortSignal,
+ config?: Partial<Pick<EngineConfig, "ffmpegProcessTimeout">>,
+): Promise<ExtractResult> {
+ const ffmpegProcessTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;
+ const outputDir = dirname(outputPath);
+ if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
+
+ const args: string[] = ["-i", videoPath];
+ if (options?.startTime !== undefined) args.push("-ss", String(options.startTime));
+ if (options?.duration !== undefined) args.push("-t", String(options.duration));
+ args.push("-vn", "-acodec", "pcm_s16le", "-ar", "48000", "-ac", "2", "-y", outputPath);
+
+ const result = await runFfmpeg(args, { signal, timeout: ffmpegProcessTimeout });
+
+ if (signal?.aborted) {
+ return { success: false, outputPath, durationMs: result.durationMs, error: "Audio extract cancelled" };
+ }
+ if (!result.success) {
+ return {
+ success: false,
+ outputPath,
+ durationMs: result.durationMs,
+ error: result.exitCode !== null ? `FFmpeg exited with code ${result.exitCode}` : result.stderr,
+ };
+ }
+ return { success: true, outputPath, durationMs: result.durationMs };
+}
+
+async function prepareAudioTrack(
+ srcPath: string,
+ outputPath: string,
+ mediaStart: number,
+ duration: number,
+ signal?: AbortSignal,
+ config?: Partial<Pick<EngineConfig, "ffmpegProcessTimeout">>,
+): Promise<ExtractResult> {
+ const ffmpegProcessTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;
+ const outputDir = dirname(outputPath);
+ if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
+
+ const args = [
+ "-ss",
+ String(mediaStart),
+ "-t",
+ String(duration),
+ "-i",
+ srcPath,
+ "-acodec",
+ "pcm_s16le",
+ "-ar",
+ "48000",
+ "-ac",
+ "2",
+ "-y",
+ outputPath,
+ ];
+
+ const result = await runFfmpeg(args, { signal, timeout: ffmpegProcessTimeout });
+
+ if (signal?.aborted) {
+ return { success: false, outputPath, durationMs: result.durationMs, error: "Audio prepare cancelled" };
+ }
+ return {
+ success: result.success,
+ outputPath,
+ durationMs: result.durationMs,
+ error: !result.success
+ ? result.exitCode !== null
+ ? `FFmpeg exited with code ${result.exitCode}: ${result.stderr.slice(-200)}`
+ : result.stderr
+ : undefined,
+ };
+}
+
+async function generateSilence(
+ outputPath: string,
+ duration: number,
+ signal?: AbortSignal,
+ config?: Partial<Pick<EngineConfig, "ffmpegProcessTimeout">>,
+): Promise<ExtractResult> {
+ const ffmpegProcessTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;
+ const outputDir = dirname(outputPath);
+ if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
+
+ const args = [
+ "-f",
+ "lavfi",
+ "-i",
+ "anullsrc=r=48000:cl=stereo",
+ "-t",
+ String(duration),
+ "-acodec",
+ "pcm_s16le",
+ "-y",
+ outputPath,
+ ];
+
+ const result = await runFfmpeg(args, { signal, timeout: ffmpegProcessTimeout });
+
+ if (signal?.aborted) {
+ return { success: false, outputPath, durationMs: result.durationMs, error: "Silence generation cancelled" };
+ }
+ return {
+ success: result.success,
+ outputPath,
+ durationMs: result.durationMs,
+ error: !result.success
+ ? result.exitCode !== null
+ ? `FFmpeg exited with code ${result.exitCode}`
+ : result.stderr
+ : undefined,
+ };
+}
+
+async function mixAudioTracks(
+ tracks: AudioTrack[],
+ outputPath: string,
+ totalDuration: number,
+ signal?: AbortSignal,
+ config?: Partial<Pick<EngineConfig, "ffmpegProcessTimeout" | "audioGain">>,
+): Promise<MixResult> {
+ const ffmpegProcessTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;
+ const masterOutputGain = config?.audioGain ?? DEFAULT_CONFIG.audioGain;
+
+ if (tracks.length === 0) {
+ const result = await generateSilence(outputPath, totalDuration, signal, config);
+ return {
+ success: result.success,
+ outputPath,
+ durationMs: result.durationMs,
+ tracksProcessed: 0,
+ error: result.error,
+ };
+ }
+
+ const outputDir = dirname(outputPath);
+ if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
+
+ const inputs: string[] = [];
+ const filterParts: string[] = [];
+
+ tracks.forEach((track, i) => {
+ inputs.push("-i", track.srcPath);
+ const delayMs = Math.round(track.start * 1000);
+ const trimDuration = track.end - track.start;
+ filterParts.push(
+ `[${i}:a]atrim=0:${trimDuration},volume=${track.volume},adelay=${delayMs}|${delayMs},apad=whole_dur=${totalDuration}[a${i}]`,
+ );
+ });
+
+ const mixInputs = tracks.map((_, i) => `[a${i}]`).join("");
+ const weights = tracks.map(() => "1").join(" ");
+ const mixFilter = `${mixInputs}amix=inputs=${tracks.length}:duration=longest:dropout_transition=0:normalize=0:weights='${weights}'[mixed]`;
+ const postMixGainFilter = `[mixed]volume=${masterOutputGain}[out]`;
+ const fullFilter = [...filterParts, mixFilter, postMixGainFilter].join(";");
+
+ const args = [
+ ...inputs,
+ "-filter_complex",
+ fullFilter,
+ "-map",
+ "[out]",
+ "-acodec",
+ "aac",
+ "-b:a",
+ "192k",
+ "-t",
+ String(totalDuration),
+ "-y",
+ outputPath,
+ ];
+
+ const result = await runFfmpeg(args, { signal, timeout: ffmpegProcessTimeout });
+
+ if (signal?.aborted) {
+ return {
+ success: false,
+ outputPath,
+ durationMs: result.durationMs,
+ tracksProcessed: 0,
+ error: "Audio mix cancelled",
+ };
+ }
+ if (!result.success) {
+ return {
+ success: false,
+ outputPath,
+ durationMs: result.durationMs,
+ tracksProcessed: 0,
+ error: result.exitCode !== null ? `FFmpeg exited with code ${result.exitCode}` : result.stderr,
+ };
+ }
+ return { success: true, outputPath, durationMs: result.durationMs, tracksProcessed: tracks.length };
+}
+
+export async function processCompositionAudio(
+ elements: AudioElement[],
+ baseDir: string,
+ workDir: string,
+ outputPath: string,
+ totalDuration: number,
+ signal?: AbortSignal,
+ config?: Partial<Pick<EngineConfig, "ffmpegProcessTimeout" | "audioGain">>,
+): Promise<MixResult> {
+ const startMs = Date.now();
+ const tracks: AudioTrack[] = [];
+ const errors: string[] = [];
+
+ if (!existsSync(workDir)) mkdirSync(workDir, { recursive: true });
+
+ await Promise.all(
+ elements.map(async (element) => {
+ if (signal?.aborted) {
+ errors.push(`Cancelled: ${element.id}`);
+ return;
+ }
+ try {
+ let srcPath = element.src;
+ if (!srcPath.startsWith("/") && !isHttpUrl(srcPath)) {
+ srcPath = join(baseDir, srcPath);
+ }
+
+ if (isHttpUrl(srcPath)) {
+ try {
+ srcPath = await downloadToTemp(srcPath, workDir);
+ } catch (err: unknown) {
+ errors.push(`Download failed: ${element.id} — ${err instanceof Error ? err.message : String(err)}`);
+ return;
+ }
+ }
+
+ if (!existsSync(srcPath)) {
+ errors.push(`Source not found: ${element.id}`);
+ return;
+ }
+
+ // Fallback: if no duration was specified, probe the actual file
+ if (element.end - element.start <= 0) {
+ const metadata = await extractAudioMetadata(srcPath);
+ const effectiveDuration = metadata.durationSeconds - element.mediaStart;
+ element.end = element.start + (effectiveDuration > 0 ? effectiveDuration : metadata.durationSeconds);
+ }
+
+ let audioSrcPath = srcPath;
+ if (element.type === "video") {
+ const extractedPath = join(workDir, `${element.id}-extracted.wav`);
+ const extractResult = await extractAudioFromVideo(
+ srcPath,
+ extractedPath,
+ {
+ startTime: element.mediaStart,
+ duration: element.end - element.start,
+ },
+ signal,
+ config,
+ );
+ if (!extractResult.success) {
+ errors.push(`Extract failed: ${element.id}`);
+ return;
+ }
+ audioSrcPath = extractedPath;
+ } else {
+ const trimmedPath = join(workDir, `${element.id}-trimmed.wav`);
+ const prepResult = await prepareAudioTrack(
+ srcPath,
+ trimmedPath,
+ element.mediaStart,
+ element.end - element.start,
+ signal,
+ config,
+ );
+ if (!prepResult.success) {
+ errors.push(`Prepare failed: ${element.id}`);
+ return;
+ }
+ audioSrcPath = trimmedPath;
+ }
+
+ tracks.push({
+ id: element.id,
+ srcPath: audioSrcPath,
+ start: element.start,
+ end: element.end,
+ mediaStart: element.mediaStart,
+ duration: element.end - element.start,
+ volume: element.volume || 1.0,
+ });
+ } catch (err: unknown) {
+ errors.push(`Error: ${element.id} — ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }),
+ );
+
+ const mixResult = await mixAudioTracks(tracks, outputPath, totalDuration, signal, config);
+
+ try {
+ rmSync(workDir, { recursive: true, force: true });
+ } catch {
+ /* ignore */
+ }
+
+ return {
+ ...mixResult,
+ durationMs: Date.now() - startMs,
+ error: errors.length > 0 ? `Warnings: ${errors.join(", ")}` : mixResult.error,
+ };
+}
diff --git a/packages/engine/src/services/audioMixer.types.ts b/packages/engine/src/services/audioMixer.types.ts
new file mode 100644
index 0000000000..cdad893409
--- /dev/null
+++ b/packages/engine/src/services/audioMixer.types.ts
@@ -0,0 +1,28 @@
+export interface AudioElement {
+ id: string;
+ src: string;
+ start: number;
+ end: number;
+ mediaStart: number;
+ layer: number;
+ volume?: number;
+ type: "audio" | "video";
+}
+
+export interface AudioTrack {
+ id: string;
+ srcPath: string;
+ start: number;
+ end: number;
+ mediaStart: number;
+ duration: number;
+ volume: number;
+}
+
+export interface MixResult {
+ success: boolean;
+ outputPath: string;
+ durationMs: number;
+ tracksProcessed: number;
+ error?: string;
+}
diff --git a/packages/engine/src/services/browserManager.ts b/packages/engine/src/services/browserManager.ts
new file mode 100644
index 0000000000..c8998f2c82
--- /dev/null
+++ b/packages/engine/src/services/browserManager.ts
@@ -0,0 +1,219 @@
+/**
+ * Browser Manager
+ *
+ * Manages Puppeteer browser lifecycle: Chrome executable resolution,
+ * launch args, pooled browser acquisition/release.
+ */
+
+import type { Browser, PuppeteerNode } from "puppeteer-core";
+import { existsSync, readdirSync } from "fs";
+import { join } from "path";
+import { homedir } from "os";
+import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";
+
+let _puppeteer: PuppeteerNode | undefined;
+
+async function getPuppeteer(): Promise<PuppeteerNode> {
+ if (_puppeteer) return _puppeteer;
+ try {
+ const mod = await import("puppeteer" as string);
+ _puppeteer = mod.default;
+ } catch {
+ const mod = await import("puppeteer-core");
+ _puppeteer = mod.default;
+ }
+ if (!_puppeteer) throw new Error("Neither puppeteer nor puppeteer-core found");
+ return _puppeteer;
+}
+
+// "beginframe" = atomic compositor control via HeadlessExperimental.beginFrame (Linux only)
+// "screenshot" = renderSeek + Page.captureScreenshot (all platforms)
+export type CaptureMode = "beginframe" | "screenshot";
+
+export interface AcquiredBrowser {
+ browser: Browser;
+ captureMode: CaptureMode;
+}
+
+/**
+ * Resolve chrome-headless-shell binary for deterministic BeginFrame rendering.
+ * Checks config.chromePath, then PRODUCER_HEADLESS_SHELL_PATH env var,
+ * then scans Puppeteer's managed cache at ~/.cache/puppeteer/chrome-headless-shell/.
+ */
+export function resolveHeadlessShellPath(config?: Partial<Pick<EngineConfig, "chromePath">>): string | undefined {
+ if (config?.chromePath) {
+ return config.chromePath;
+ }
+ if (process.env.PRODUCER_HEADLESS_SHELL_PATH) {
+ return process.env.PRODUCER_HEADLESS_SHELL_PATH;
+ }
+ const baseDir = join(homedir(), ".cache", "puppeteer", "chrome-headless-shell");
+ if (!existsSync(baseDir)) return undefined;
+ try {
+ const versions = readdirSync(baseDir).sort().reverse(); // newest first
+ for (const version of versions) {
+ const candidates = [
+ join(baseDir, version, "chrome-headless-shell-linux64", "chrome-headless-shell"),
+ join(baseDir, version, "chrome-headless-shell-mac-arm64", "chrome-headless-shell"),
+ join(baseDir, version, "chrome-headless-shell-mac-x64", "chrome-headless-shell"),
+ join(baseDir, version, "chrome-headless-shell-win64", "chrome-headless-shell.exe"),
+ ];
+ for (const binary of candidates) {
+ if (existsSync(binary)) return binary;
+ }
+ }
+ } catch {
+ // ignore
+ }
+ return undefined;
+}
+
+let pooledBrowser: Browser | null = null;
+let pooledBrowserRefCount = 0;
+let pooledCaptureMode: CaptureMode = "screenshot";
+
+// Preserve the producer-era export so re-export shims keep the same public API.
+export const ENABLE_BROWSER_POOL = DEFAULT_CONFIG.enableBrowserPool;
+
+export async function acquireBrowser(
+ chromeArgs: string[],
+ config?: Partial<
+ Pick<EngineConfig, "browserTimeout" | "protocolTimeout" | "enableBrowserPool" | "chromePath" | "forceScreenshot">
+ >,
+): Promise<AcquiredBrowser> {
+ const enablePool = config?.enableBrowserPool ?? DEFAULT_CONFIG.enableBrowserPool;
+
+ if (enablePool && pooledBrowser) {
+ pooledBrowserRefCount += 1;
+ return { browser: pooledBrowser, captureMode: pooledCaptureMode };
+ }
+
+ // Config chromePath overrides env var / auto-detection.
+ const headlessShell = resolveHeadlessShellPath(config);
+
+ // BeginFrame requires chrome-headless-shell AND Linux (crashes on macOS/Windows).
+ const isLinux = process.platform === "linux";
+ const forceScreenshot = config?.forceScreenshot ?? DEFAULT_CONFIG.forceScreenshot;
+ let captureMode: CaptureMode;
+ let executablePath: string | undefined;
+
+ if (headlessShell && isLinux && !forceScreenshot) {
+ captureMode = "beginframe";
+ executablePath = headlessShell;
+ } else {
+ // Screenshot mode with renderSeek: works on all platforms.
+ captureMode = "screenshot";
+ if (headlessShell && !isLinux) {
+ executablePath = headlessShell;
+ } else {
+ executablePath = undefined; // Puppeteer uses its bundled Chromium
+ }
+ }
+
+ const ppt = await getPuppeteer();
+ const browser = await ppt.launch({
+ headless: true,
+ args: chromeArgs,
+ defaultViewport: null,
+ executablePath,
+ timeout: config?.browserTimeout ?? DEFAULT_CONFIG.browserTimeout,
+ protocolTimeout: config?.protocolTimeout ?? DEFAULT_CONFIG.protocolTimeout,
+ });
+ if (enablePool) {
+ pooledBrowser = browser;
+ pooledBrowserRefCount = 1;
+ pooledCaptureMode = captureMode;
+ }
+ return { browser, captureMode };
+}
+
+export async function releaseBrowser(
+ browser: Browser,
+ config?: Partial<Pick<EngineConfig, "enableBrowserPool">>,
+): Promise<void> {
+ const enablePool = config?.enableBrowserPool ?? DEFAULT_CONFIG.enableBrowserPool;
+ if (!enablePool) {
+ await browser.close().catch(() => {});
+ return;
+ }
+ if (pooledBrowser && pooledBrowser === browser) {
+ pooledBrowserRefCount = Math.max(0, pooledBrowserRefCount - 1);
+ if (pooledBrowserRefCount === 0) {
+ await browser.close().catch(() => {});
+ pooledBrowser = null;
+ }
+ return;
+ }
+ await browser.close().catch(() => {});
+}
+
+export interface BuildChromeArgsOptions {
+ width: number;
+ height: number;
+ captureMode?: CaptureMode;
+}
+
+export function buildChromeArgs(
+ options: BuildChromeArgsOptions,
+ config?: Partial<Pick<EngineConfig, "disableGpu" | "chromePath">>,
+): string[] {
+ // Chrome flags tuned for headless rendering performance.
+ // Based on Remotion's open-browser.ts flags with additions for our use case.
+ const chromeArgs = [
+ "--no-sandbox",
+ "--disable-setuid-sandbox",
+ "--disable-dev-shm-usage",
+ "--enable-webgl",
+ "--ignore-gpu-blocklist",
+ "--use-gl=angle",
+ "--use-angle=swiftshader",
+ "--font-render-hinting=none",
+ "--force-color-profile=srgb",
+ `--window-size=${options.width},${options.height}`,
+ // Remotion perf flags — prevent Chrome from throttling background tabs/timers
+ "--disable-background-timer-throttling",
+ "--disable-backgrounding-occluded-windows",
+ "--disable-renderer-backgrounding",
+ "--disable-background-media-suspend",
+ // Reduce overhead from unused Chrome features
+ "--disable-breakpad",
+ "--disable-component-extensions-with-background-pages",
+ "--disable-default-apps",
+ "--disable-extensions",
+ "--disable-hang-monitor",
+ "--disable-ipc-flooding-protection",
+ "--disable-popup-blocking",
+ "--disable-sync",
+ "--disable-component-update",
+ "--disable-domain-reliability",
+ "--disable-print-preview",
+ "--no-pings",
+ "--no-zygote",
+ // Memory
+ "--force-gpu-mem-available-mb=4096",
+ "--disk-cache-size=268435456",
+ // Disable features that add overhead
+ "--disable-features=AudioServiceOutOfProcess,IsolateOrigins,site-per-process,Translate,BackForwardCache,IntensiveWakeUpThrottling",
+ ];
+
+ // BeginFrame flags — only when using chrome-headless-shell on Linux
+ if (options.captureMode !== "screenshot") {
+ chromeArgs.push(
+ "--deterministic-mode",
+ "--enable-begin-frame-control",
+ "--disable-new-content-rendering-timeout",
+ "--run-all-compositor-stages-before-draw",
+ "--disable-threaded-animation",
+ "--disable-threaded-scrolling",
+ "--disable-checker-imaging",
+ "--disable-image-animation-resync",
+ "--enable-surface-synchronization",
+ );
+ }
+
+ const gpuDisabled = config?.disableGpu ?? DEFAULT_CONFIG.disableGpu;
+ if (gpuDisabled) {
+ chromeArgs.push("--disable-gpu");
+ }
+ return chromeArgs;
+}
diff --git a/packages/engine/src/services/chunkEncoder.test.ts b/packages/engine/src/services/chunkEncoder.test.ts
new file mode 100644
index 0000000000..1628292c2e
--- /dev/null
+++ b/packages/engine/src/services/chunkEncoder.test.ts
@@ -0,0 +1,27 @@
+import { describe, it, expect } from "vitest";
+import { ENCODER_PRESETS } from "./chunkEncoder.js";
+
+describe("ENCODER_PRESETS", () => {
+ it("has draft, standard, and high presets", () => {
+ expect(ENCODER_PRESETS).toHaveProperty("draft");
+ expect(ENCODER_PRESETS).toHaveProperty("standard");
+ expect(ENCODER_PRESETS).toHaveProperty("high");
+ });
+
+ it("draft uses ultrafast preset with high CRF", () => {
+ expect(ENCODER_PRESETS.draft.preset).toBe("ultrafast");
+ expect(ENCODER_PRESETS.draft.quality).toBeGreaterThan(ENCODER_PRESETS.standard.quality);
+ expect(ENCODER_PRESETS.draft.codec).toBe("h264");
+ });
+
+ it("high uses slow preset with low CRF for better quality", () => {
+ expect(ENCODER_PRESETS.high.preset).toBe("slow");
+ expect(ENCODER_PRESETS.high.quality).toBeLessThan(ENCODER_PRESETS.standard.quality);
+ expect(ENCODER_PRESETS.high.codec).toBe("h264");
+ });
+
+ it("standard sits between draft and high in quality", () => {
+ expect(ENCODER_PRESETS.standard.quality).toBeGreaterThan(ENCODER_PRESETS.high.quality);
+ expect(ENCODER_PRESETS.standard.quality).toBeLessThan(ENCODER_PRESETS.draft.quality);
+ });
+});
diff --git a/packages/engine/src/services/chunkEncoder.ts b/packages/engine/src/services/chunkEncoder.ts
new file mode 100644
index 0000000000..bfb285b195
--- /dev/null
+++ b/packages/engine/src/services/chunkEncoder.ts
@@ -0,0 +1,399 @@
+/**
+ * Chunk Encoder Service
+ *
+ * Encodes captured frames into video using FFmpeg.
+ * Supports CPU (libx264) and GPU encoding.
+ */
+
+import { spawn } from "child_process";
+import { existsSync, mkdirSync, readdirSync, statSync, writeFileSync } from "fs";
+import { join, dirname } from "path";
+import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";
+import { type GpuEncoder, getCachedGpuEncoder, getGpuEncoderName } from "../utils/gpuEncoder.js";
+import { runFfmpeg } from "../utils/runFfmpeg.js";
+import type { EncoderOptions, EncodeResult, MuxResult } from "./chunkEncoder.types.js";
+
+export type { EncoderOptions, EncodeResult, MuxResult } from "./chunkEncoder.types.js";
+
+export const ENCODER_PRESETS = {
+ draft: { preset: "ultrafast", quality: 28, codec: "h264" as const },
+ standard: { preset: "medium", quality: 23, codec: "h264" as const },
+ high: { preset: "slow", quality: 18, codec: "h264" as const },
+};
+
+// Re-export GPU utilities so existing consumers that import from chunkEncoder still work.
+export { detectGpuEncoder, type GpuEncoder } from "../utils/gpuEncoder.js";
+
+function buildEncoderArgs(
+ options: EncoderOptions,
+ inputArgs: string[],
+ outputPath: string,
+ gpuEncoder: GpuEncoder = null,
+): string[] {
+ const {
+ fps,
+ codec = "h264",
+ preset = "medium",
+ quality = 23,
+ bitrate,
+ pixelFormat = "yuv420p",
+ useGpu = false,
+ } = options;
+
+ const args: string[] = [...inputArgs, "-r", String(fps)];
+ const shouldUseGpu = useGpu && gpuEncoder !== null;
+
+ if (codec === "h264" || codec === "h265") {
+ if (shouldUseGpu) {
+ const encoderName = getGpuEncoderName(gpuEncoder, codec);
+ args.push("-c:v", encoderName);
+
+ switch (gpuEncoder) {
+ case "nvenc":
+ args.push("-preset", preset);
+ if (bitrate) args.push("-b:v", bitrate);
+ else args.push("-cq", String(quality));
+ break;
+ case "videotoolbox":
+ if (bitrate) args.push("-b:v", bitrate);
+ else {
+ const vtQuality = Math.max(0, Math.min(100, 100 - quality * 2));
+ args.push("-q:v", String(vtQuality));
+ }
+ args.push("-allow_sw", "1");
+ break;
+ case "vaapi":
+ args.unshift("-vaapi_device", "/dev/dri/renderD128");
+ args.push("-vf", "format=nv12,hwupload");
+ if (bitrate) args.push("-b:v", bitrate);
+ else args.push("-qp", String(quality));
+ break;
+ case "qsv":
+ args.push("-preset", preset);
+ if (bitrate) args.push("-b:v", bitrate);
+ else args.push("-global_quality", String(quality));
+ break;
+ }
+ } else {
+ const encoderName = codec === "h264" ? "libx264" : "libx265";
+ args.push("-c:v", encoderName, "-preset", preset);
+ if (bitrate) args.push("-b:v", bitrate);
+ else args.push("-crf", String(quality));
+ }
+ } else if (codec === "vp9") {
+ args.push("-c:v", "libvpx-vp9", "-b:v", bitrate || "0", "-crf", String(quality));
+ args.push("-deadline", preset === "ultrafast" ? "realtime" : "good");
+ } else if (codec === "prores") {
+ args.push("-c:v", "prores_ks", "-profile:v", preset, "-vendor", "apl0");
+ return [...args, "-y", outputPath];
+ }
+
+ if (gpuEncoder !== "vaapi") {
+ args.push("-pix_fmt", pixelFormat);
+ }
+
+ args.push("-y", outputPath);
+ return args;
+}
+
+export async function encodeFramesFromDir(
+ framesDir: string,
+ framePattern: string,
+ outputPath: string,
+ options: EncoderOptions,
+ signal?: AbortSignal,
+ config?: Partial<Pick<EngineConfig, "ffmpegEncodeTimeout">>,
+): Promise<EncodeResult> {
+ const startTime = Date.now();
+
+ const outputDir = dirname(outputPath);
+ if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
+
+ const files = readdirSync(framesDir).filter((f) => f.match(/\.(jpg|jpeg|png)$/i));
+ const frameCount = files.length;
+
+ if (frameCount === 0) {
+ return {
+ success: false,
+ outputPath,
+ durationMs: Date.now() - startTime,
+ framesEncoded: 0,
+ fileSize: 0,
+ error: "[FFmpeg] No frame files found in directory",
+ };
+ }
+
+ let gpuEncoder: GpuEncoder = null;
+ if (options.useGpu) {
+ gpuEncoder = await getCachedGpuEncoder();
+ }
+
+ const inputPath = join(framesDir, framePattern);
+ const inputArgs = ["-framerate", String(options.fps), "-i", inputPath];
+ const args = buildEncoderArgs(options, inputArgs, outputPath, gpuEncoder);
+
+ return new Promise((resolve) => {
+ const ffmpeg = spawn("ffmpeg", args);
+ let stderr = "";
+ const onAbort = () => {
+ ffmpeg.kill("SIGTERM");
+ };
+ if (signal) {
+ if (signal.aborted) {
+ ffmpeg.kill("SIGTERM");
+ } else {
+ signal.addEventListener("abort", onAbort, { once: true });
+ }
+ }
+
+ const encodeTimeout = config?.ffmpegEncodeTimeout ?? DEFAULT_CONFIG.ffmpegEncodeTimeout;
+ const timer = setTimeout(() => {
+ ffmpeg.kill("SIGTERM");
+ }, encodeTimeout);
+
+ ffmpeg.stderr.on("data", (data) => {
+ stderr += data.toString();
+ });
+
+ ffmpeg.on("close", (code) => {
+ clearTimeout(timer);
+ if (signal) signal.removeEventListener("abort", onAbort);
+ const durationMs = Date.now() - startTime;
+ if (signal?.aborted) {
+ resolve({
+ success: false,
+ outputPath,
+ durationMs,
+ framesEncoded: 0,
+ fileSize: 0,
+ error: "FFmpeg encode cancelled",
+ });
+ return;
+ }
+
+ if (code !== 0) {
+ resolve({
+ success: false,
+ outputPath,
+ durationMs,
+ framesEncoded: 0,
+ fileSize: 0,
+ error: `FFmpeg exited with code ${code}`,
+ });
+ return;
+ }
+
+ const fileSize = existsSync(outputPath) ? statSync(outputPath).size : 0;
+ resolve({ success: true, outputPath, durationMs, framesEncoded: frameCount, fileSize });
+ });
+
+ ffmpeg.on("error", (err) => {
+ clearTimeout(timer);
+ if (signal) signal.removeEventListener("abort", onAbort);
+ resolve({
+ success: false,
+ outputPath,
+ durationMs: Date.now() - startTime,
+ framesEncoded: 0,
+ fileSize: 0,
+ error: `[FFmpeg] ${err.message}`,
+ });
+ });
+ });
+}
+
+export async function encodeFramesChunkedConcat(
+ framesDir: string,
+ framePattern: string,
+ outputPath: string,
+ options: EncoderOptions,
+ chunkSizeFrames: number,
+ signal?: AbortSignal,
+): Promise<EncodeResult> {
+ const start = Date.now();
+ const files = readdirSync(framesDir)
+ .filter((f) => f.match(/\.(jpg|jpeg|png)$/i))
+ .sort();
+ if (files.length === 0) {
+ return {
+ success: false,
+ outputPath,
+ durationMs: Date.now() - start,
+ framesEncoded: 0,
+ fileSize: 0,
+ error: "[FFmpeg] No frame files found in directory",
+ };
+ }
+ const chunkSize = Math.max(30, Math.floor(chunkSizeFrames));
+ const chunkCount = Math.ceil(files.length / chunkSize);
+ const chunkDir = join(dirname(outputPath), "chunk-encode");
+ if (!existsSync(chunkDir)) mkdirSync(chunkDir, { recursive: true });
+ const chunkPaths: string[] = [];
+
+ for (let i = 0; i < chunkCount; i++) {
+ if (signal?.aborted) {
+ return {
+ success: false,
+ outputPath,
+ durationMs: Date.now() - start,
+ framesEncoded: 0,
+ fileSize: 0,
+ error: "Chunked encode cancelled",
+ };
+ }
+ const startNumber = i * chunkSize;
+ const framesInChunk = Math.min(chunkSize, files.length - startNumber);
+ const chunkPath = join(chunkDir, `chunk_${String(i).padStart(4, "0")}.mp4`);
+ const inputPath = join(framesDir, framePattern);
+ const inputArgs = [
+ "-framerate",
+ String(options.fps),
+ "-start_number",
+ String(startNumber),
+ "-i",
+ inputPath,
+ "-frames:v",
+ String(framesInChunk),
+ ];
+ let gpuEncoder: GpuEncoder = null;
+ if (options.useGpu) gpuEncoder = await getCachedGpuEncoder();
+ const args = buildEncoderArgs(options, inputArgs, chunkPath, gpuEncoder);
+ const chunkResult = await new Promise<{ success: boolean; error?: string }>((resolve) => {
+ const ffmpeg = spawn("ffmpeg", args);
+ let stderr = "";
+ ffmpeg.stderr.on("data", (d) => {
+ stderr += d.toString();
+ });
+ ffmpeg.on("close", (code) => {
+ if (code === 0) resolve({ success: true });
+ else resolve({ success: false, error: `Chunk ${i} encode failed: ${stderr.slice(-400)}` });
+ });
+ ffmpeg.on("error", (err) => {
+ resolve({ success: false, error: `Chunk ${i} encode error: ${err.message}` });
+ });
+ });
+ if (!chunkResult.success) {
+ return {
+ success: false,
+ outputPath,
+ durationMs: Date.now() - start,
+ framesEncoded: 0,
+ fileSize: 0,
+ error: chunkResult.error,
+ };
+ }
+ chunkPaths.push(chunkPath);
+ }
+
+ const concatListPath = join(chunkDir, "concat-list.txt");
+ const concatInput = chunkPaths.map((path) => `file '${path.replace(/'/g, "'\\''")}'`).join("\n");
+ writeFileSync(concatListPath, concatInput, "utf-8");
+
+ const concatArgs = ["-f", "concat", "-safe", "0", "-i", concatListPath, "-c", "copy", "-y", outputPath];
+ const concatResult = await new Promise<{ success: boolean; error?: string }>((resolve) => {
+ const ffmpeg = spawn("ffmpeg", concatArgs);
+ let stderr = "";
+ ffmpeg.stderr.on("data", (d) => {
+ stderr += d.toString();
+ });
+ ffmpeg.on("close", (code) => {
+ if (code === 0) resolve({ success: true });
+ else resolve({ success: false, error: `Chunk concat failed: ${stderr.slice(-400)}` });
+ });
+ ffmpeg.on("error", (err) => {
+ resolve({ success: false, error: `Chunk concat error: ${err.message}` });
+ });
+ });
+
+ if (!concatResult.success) {
+ return {
+ success: false,
+ outputPath,
+ durationMs: Date.now() - start,
+ framesEncoded: 0,
+ fileSize: 0,
+ error: concatResult.error,
+ };
+ }
+
+ const fileSize = existsSync(outputPath) ? statSync(outputPath).size : 0;
+ return {
+ success: true,
+ outputPath,
+ durationMs: Date.now() - start,
+ framesEncoded: files.length,
+ fileSize,
+ };
+}
+
+export async function muxVideoWithAudio(
+ videoPath: string,
+ audioPath: string,
+ outputPath: string,
+ signal?: AbortSignal,
+ config?: Partial<Pick<EngineConfig, "ffmpegProcessTimeout">>,
+): Promise<MuxResult> {
+ const outputDir = dirname(outputPath);
+ if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
+
+ const args = [
+ "-i",
+ videoPath,
+ "-i",
+ audioPath,
+ "-c:v",
+ "copy",
+ "-c:a",
+ "aac",
+ "-b:a",
+ "192k",
+ "-shortest",
+ "-movflags",
+ "+faststart",
+ "-y",
+ outputPath,
+ ];
+
+ const processTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;
+ const result = await runFfmpeg(args, { signal, timeout: processTimeout });
+
+ if (signal?.aborted) {
+ return { success: false, outputPath, durationMs: result.durationMs, error: "FFmpeg mux cancelled" };
+ }
+ return {
+ success: result.success,
+ outputPath,
+ durationMs: result.durationMs,
+ error: !result.success
+ ? result.exitCode !== null
+ ? `FFmpeg exited with code ${result.exitCode}`
+ : `[FFmpeg] ${result.stderr}`
+ : undefined,
+ };
+}
+
+export async function applyFaststart(
+ inputPath: string,
+ outputPath: string,
+ signal?: AbortSignal,
+ config?: Partial<Pick<EngineConfig, "ffmpegProcessTimeout">>,
+): Promise<MuxResult> {
+ const args = ["-i", inputPath, "-c", "copy", "-movflags", "+faststart", "-y", outputPath];
+
+ const processTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;
+ const result = await runFfmpeg(args, { signal, timeout: processTimeout });
+
+ if (signal?.aborted) {
+ return { success: false, outputPath, durationMs: result.durationMs, error: "FFmpeg faststart cancelled" };
+ }
+ return {
+ success: result.success,
+ outputPath,
+ durationMs: result.durationMs,
+ error: !result.success
+ ? result.exitCode !== null
+ ? `FFmpeg exited with code ${result.exitCode}`
+ : `[FFmpeg] ${result.stderr}`
+ : undefined,
+ };
+}
diff --git a/packages/engine/src/services/chunkEncoder.types.ts b/packages/engine/src/services/chunkEncoder.types.ts
new file mode 100644
index 0000000000..9d36b4294e
--- /dev/null
+++ b/packages/engine/src/services/chunkEncoder.types.ts
@@ -0,0 +1,27 @@
+export interface EncoderOptions {
+ fps: number;
+ width: number;
+ height: number;
+ codec?: "h264" | "h265" | "vp9" | "prores";
+ preset?: string;
+ quality?: number;
+ bitrate?: string;
+ pixelFormat?: string;
+ useGpu?: boolean;
+}
+
+export interface EncodeResult {
+ success: boolean;
+ outputPath: string;
+ durationMs: number;
+ framesEncoded: number;
+ fileSize: number;
+ error?: string;
+}
+
+export interface MuxResult {
+ success: boolean;
+ outputPath: string;
+ durationMs: number;
+ error?: string;
+}
diff --git a/packages/engine/src/services/fileServer.ts b/packages/engine/src/services/fileServer.ts
new file mode 100644
index 0000000000..f57558e932
--- /dev/null
+++ b/packages/engine/src/services/fileServer.ts
@@ -0,0 +1,175 @@
+/**
+ * File Server
+ *
+ * Lightweight HTTP server that serves a project directory to headless Chrome.
+ * Optionally injects scripts into index.html on-the-fly (e.g. runtime, bridge).
+ * Framework-agnostic — the caller decides what scripts to inject.
+ */
+
+import { Hono } from "hono";
+import { serve } from "@hono/node-server";
+import { readFileSync, existsSync, statSync } from "node:fs";
+import { join, extname } from "node:path";
+
+const MIME_TYPES: Record<string, string> = {
+ ".html": "text/html; charset=utf-8",
+ ".css": "text/css; charset=utf-8",
+ ".js": "application/javascript; charset=utf-8",
+ ".json": "application/json; charset=utf-8",
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".svg": "image/svg+xml",
+ ".webp": "image/webp",
+ ".mp4": "video/mp4",
+ ".webm": "video/webm",
+ ".mp3": "audio/mpeg",
+ ".wav": "audio/wav",
+ ".ogg": "audio/ogg",
+ ".aac": "audio/aac",
+ ".woff": "font/woff",
+ ".woff2": "font/woff2",
+ ".ttf": "font/ttf",
+ ".otf": "font/otf",
+};
+
+function stripEmbeddedRuntimeScripts(html: string): string {
+ if (!html) return html;
+ const scriptRe = /<script\b[^>]*>[\s\S]*?<\/script>/gi;
+ const runtimeSrcMarkers = [
+ "hyperframe.runtime.iife.js",
+ "hyperframes-runtime.modular.inline.js",
+ "data-hyperframes-preview-runtime",
+ ];
+ const runtimeInlineMarkers = [
+ "__hyperframeRuntimeBootstrapped",
+ "__hyperframeRuntime",
+ "__hyperframeRuntimeTeardown",
+ "window.__player =",
+ "window.__playerReady",
+ "window.__renderReady",
+ ];
+
+ const shouldStrip = (block: string): boolean => {
+ const lowered = block.toLowerCase();
+ for (const marker of runtimeSrcMarkers) {
+ if (lowered.includes(marker.toLowerCase())) {
+ return true;
+ }
+ }
+ for (const marker of runtimeInlineMarkers) {
+ if (block.includes(marker)) {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ return html.replace(scriptRe, (block) => (shouldStrip(block) ? "" : block));
+}
+
+function injectScriptsIntoHtml(
+ html: string,
+ headScripts: string[],
+ bodyScripts: string[],
+ stripEmbedded: boolean,
+): string {
+ if (stripEmbedded) {
+ html = stripEmbeddedRuntimeScripts(html);
+ }
+
+ if (headScripts.length > 0) {
+ const headTags = headScripts.map((src) => `<script>${src}</script>`).join("\n");
+ if (html.includes("</head>")) {
+ html = html.replace("</head>", () => `${headTags}\n</head>`);
+ } else if (html.includes("<body")) {
+ html = html.replace("<body", () => `${headTags}\n<body`);
+ } else {
+ html = headTags + "\n" + html;
+ }
+ }
+
+ if (bodyScripts.length > 0) {
+ const bodyTags = bodyScripts.map((src) => `<script>${src}</script>`).join("\n");
+ if (html.includes("</body>")) {
+ html = html.replace("</body>", () => `${bodyTags}\n</body>`);
+ } else {
+ html = html + "\n" + bodyTags;
+ }
+ }
+
+ return html;
+}
+
+export interface FileServerOptions {
+ projectDir: string;
+ compiledDir?: string;
+ port?: number;
+ /** Scripts injected into <head> of index.html. Default: none. */
+ headScripts?: string[];
+ /** Scripts injected before </body> of index.html. Default: none. */
+ bodyScripts?: string[];
+ /** Strip embedded runtime scripts from HTML before injection. Default: true. */
+ stripEmbeddedRuntime?: boolean;
+}
+
+export interface FileServerHandle {
+ url: string;
+ port: number;
+ close: () => void;
+}
+
+export function createFileServer(options: FileServerOptions): Promise<FileServerHandle> {
+ const { projectDir, compiledDir, port = 0, stripEmbeddedRuntime = true } = options;
+
+ const headScripts = options.headScripts ?? [];
+ const bodyScripts = options.bodyScripts ?? [];
+
+ const app = new Hono();
+
+ app.get("/*", (c) => {
+ let requestPath = c.req.path;
+ if (requestPath === "/") requestPath = "/index.html";
+
+ // Remove leading slash
+ const relativePath = requestPath.replace(/^\//, "");
+ const compiledPath = compiledDir ? join(compiledDir, relativePath) : null;
+ const hasCompiledFile = Boolean(compiledPath && existsSync(compiledPath) && statSync(compiledPath).isFile());
+ const filePath = hasCompiledFile ? (compiledPath as string) : join(projectDir, relativePath);
+
+ if (!existsSync(filePath) || !statSync(filePath).isFile()) {
+ return c.text("Not found", 404);
+ }
+
+ const ext = extname(filePath).toLowerCase();
+ const contentType = MIME_TYPES[ext] || "application/octet-stream";
+
+ if (ext === ".html") {
+ const rawHtml = readFileSync(filePath, "utf-8");
+ const html =
+ relativePath === "index.html"
+ ? injectScriptsIntoHtml(rawHtml, headScripts, bodyScripts, stripEmbeddedRuntime)
+ : rawHtml;
+ return c.text(html, 200, { "Content-Type": contentType });
+ }
+
+ const content = readFileSync(filePath);
+ return new Response(content, {
+ status: 200,
+ headers: { "Content-Type": contentType },
+ });
+ });
+
+ return new Promise((resolve) => {
+ const server = serve({ fetch: app.fetch, port }, (info) => {
+ const actualPort = info.port;
+ const url = `http://localhost:${actualPort}`;
+ resolve({
+ url,
+ port: actualPort,
+ close: () => server.close(),
+ });
+ });
+ });
+}
diff --git a/packages/engine/src/services/frameCapture.ts b/packages/engine/src/services/frameCapture.ts
new file mode 100644
index 0000000000..f78629a3a4
--- /dev/null
+++ b/packages/engine/src/services/frameCapture.ts
@@ -0,0 +1,452 @@
+/**
+ * Frame Capture Service
+ *
+ * Uses Puppeteer to capture frames from any web page implementing the
+ * window.__hf seek protocol. Navigates to a file server URL, waits for
+ * the page to expose window.__hf, then captures frames deterministically
+ * via Chrome's BeginFrame API or Page.captureScreenshot fallback.
+ */
+
+import { type Browser, type Page, type Viewport, type ConsoleMessage } from "puppeteer-core";
+import { existsSync, mkdirSync, writeFileSync } from "fs";
+import { join } from "path";
+import { quantizeTimeToFrame } from "@hyperframes/core";
+
+// ── Extracted modules ───────────────────────────────────────────────────────
+import {
+ acquireBrowser,
+ releaseBrowser,
+ buildChromeArgs,
+ resolveHeadlessShellPath,
+ type CaptureMode,
+} from "./browserManager.js";
+import { beginFrameCapture, getCdpSession, pageScreenshotCapture } from "./screenshotService.js";
+import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";
+import type { CaptureOptions, CaptureResult, CaptureBufferResult, CapturePerfSummary } from "../types.js";
+
+export type { CaptureOptions, CaptureResult, CaptureBufferResult, CapturePerfSummary };
+
+/** Called after seeking, before screenshot. Use for video frame injection or other pre-capture work. */
+export type BeforeCaptureHook = (page: Page, time: number) => Promise<void>;
+
+export interface CaptureSession {
+ browser: Browser;
+ page: Page;
+ options: CaptureOptions;
+ serverUrl: string;
+ outputDir: string;
+ onBeforeCapture: BeforeCaptureHook | null;
+ isInitialized: boolean;
+ browserConsoleBuffer: string[];
+ capturePerf: {
+ frames: number;
+ seekMs: number;
+ beforeCaptureMs: number;
+ screenshotMs: number;
+ totalMs: number;
+ };
+ captureMode: CaptureMode;
+ // BeginFrame state
+ beginFrameTimeTicks: number;
+ beginFrameIntervalMs: number;
+ beginFrameHasDamageCount: number;
+ beginFrameNoDamageCount: number;
+ /** Optional producer config — when set, overrides module-level env var constants. */
+ config?: Partial<EngineConfig>;
+}
+
+// Circular buffer for browser console messages dumped on render failure diagnostics.
+// Complex compositions produce 100+ messages; 50 was too small to capture relevant errors.
+const BROWSER_CONSOLE_BUFFER_SIZE = 200;
+
+export async function createCaptureSession(
+ serverUrl: string,
+ outputDir: string,
+ options: CaptureOptions,
+ onBeforeCapture: BeforeCaptureHook | null = null,
+ config?: Partial<EngineConfig>,
+): Promise<CaptureSession> {
+ if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
+
+ // Determine capture mode before building args — BeginFrame flags only apply on Linux
+ const headlessShell = resolveHeadlessShellPath(config);
+ const isLinux = process.platform === "linux";
+ const forceScreenshot = config?.forceScreenshot ?? DEFAULT_CONFIG.forceScreenshot;
+ const preMode: CaptureMode = headlessShell && isLinux && !forceScreenshot ? "beginframe" : "screenshot";
+ const chromeArgs = buildChromeArgs({ width: options.width, height: options.height, captureMode: preMode }, config);
+
+ const { browser, captureMode } = await acquireBrowser(chromeArgs, config);
+
+ const page = await browser.newPage();
+ const browserVersion = await browser.version();
+ const expectedMajor = config?.expectedChromiumMajor;
+ if (Number.isFinite(expectedMajor)) {
+ const actualChromiumMajor = Number.parseInt((browserVersion.match(/(\d+)\./) || [])[1] || "", 10);
+ if (Number.isFinite(actualChromiumMajor) && actualChromiumMajor !== expectedMajor) {
+ throw new Error(
+ `[FrameCapture] Chromium major mismatch expected=${expectedMajor} actual=${actualChromiumMajor} raw=${browserVersion}`,
+ );
+ }
+ }
+ const viewport: Viewport = {
+ width: options.width,
+ height: options.height,
+ deviceScaleFactor: options.deviceScaleFactor || 1,
+ };
+ await page.setViewport(viewport);
+
+ return {
+ browser,
+ page,
+ options,
+ serverUrl,
+ outputDir,
+ onBeforeCapture,
+ isInitialized: false,
+ browserConsoleBuffer: [],
+ capturePerf: {
+ frames: 0,
+ seekMs: 0,
+ beforeCaptureMs: 0,
+ screenshotMs: 0,
+ totalMs: 0,
+ },
+ captureMode,
+ beginFrameTimeTicks: 0,
+ beginFrameIntervalMs: 1000 / Math.max(1, options.fps),
+ beginFrameHasDamageCount: 0,
+ beginFrameNoDamageCount: 0,
+ config,
+ };
+}
+
+export async function initializeSession(session: CaptureSession): Promise<void> {
+ const { page, serverUrl, options } = session;
+
+ // Forward browser console to host with [Browser] prefix
+ page.on("console", (msg: ConsoleMessage) => {
+ const type = msg.type();
+ const text = msg.text();
+ const prefix = type === "error" ? "[Browser:ERROR]" : type === "warn" ? "[Browser:WARN]" : "[Browser]";
+ console.log(`${prefix} ${text}`);
+
+ session.browserConsoleBuffer.push(`${prefix} ${text}`);
+ if (session.browserConsoleBuffer.length > BROWSER_CONSOLE_BUFFER_SIZE) {
+ session.browserConsoleBuffer.shift();
+ }
+ });
+
+ page.on("pageerror", (err) => {
+ const text = `[Browser:PAGEERROR] ${err instanceof Error ? err.message : String(err)}`;
+ console.error(text);
+ session.browserConsoleBuffer.push(text);
+ if (session.browserConsoleBuffer.length > BROWSER_CONSOLE_BUFFER_SIZE) {
+ session.browserConsoleBuffer.shift();
+ }
+ });
+
+ // Navigate to the file server
+ const url = `${serverUrl}/index.html`;
+ if (session.captureMode === "screenshot") {
+ // Screenshot mode: standard navigation, rAF works normally
+ await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60000 });
+
+ const pageReadyTimeout = session.config?.playerReadyTimeout ?? DEFAULT_CONFIG.playerReadyTimeout;
+ await page.waitForFunction(
+ `!!(window.__hf && typeof window.__hf.seek === "function" && window.__hf.duration > 0)`,
+ { timeout: pageReadyTimeout },
+ );
+
+ // Wait for all video elements to have loaded metadata (dimensions + duration)
+ // Without this, frame 0 captures videos at their 300x150 default size
+ await page.waitForFunction(
+ `document.querySelectorAll("video").length === 0 || Array.from(document.querySelectorAll("video")).every(v => v.readyState >= 1)`,
+ { timeout: pageReadyTimeout },
+ );
+
+ await page.evaluate(`document.fonts?.ready`);
+
+ session.isInitialized = true;
+ return;
+ }
+
+ // In BeginFrame mode, Chrome's event loop is paused until we issue frames.
+ // Start a warmup loop to drive rAF/setTimeout callbacks during page load.
+ let warmupRunning = true;
+ let warmupTicks = 0;
+ let warmupFrameTime = 0;
+ const warmupIntervalMs = 33; // ~30fps
+ let warmupClient: import("puppeteer-core").CDPSession | null = null;
+
+ const warmupLoop = async () => {
+ try {
+ warmupClient = await getCdpSession(page);
+ await warmupClient.send("HeadlessExperimental.enable");
+ } catch {
+ /* page not ready yet */
+ }
+
+ while (warmupRunning) {
+ if (warmupClient) {
+ try {
+ await warmupClient.send("HeadlessExperimental.beginFrame", {
+ frameTimeTicks: warmupFrameTime,
+ interval: warmupIntervalMs,
+ noDisplayUpdates: true,
+ });
+ warmupFrameTime += warmupIntervalMs;
+ warmupTicks++;
+ } catch {
+ /* ignore warmup errors */
+ }
+ }
+ await new Promise((r) => setTimeout(r, warmupIntervalMs));
+ }
+ };
+ warmupLoop().catch(() => {});
+
+ await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60000 });
+
+ // Poll for window.__hf readiness using manual evaluate loop (waitForFunction
+ // uses rAF polling internally, which won't fire in beginFrame mode).
+ const pageReadyTimeout = session.config?.playerReadyTimeout ?? DEFAULT_CONFIG.playerReadyTimeout;
+ const pollDeadline = Date.now() + pageReadyTimeout;
+ while (Date.now() < pollDeadline) {
+ const ready = await page.evaluate(
+ `!!(window.__hf && typeof window.__hf.seek === "function" && window.__hf.duration > 0)`,
+ );
+ if (ready) break;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ const pageReady = await page.evaluate(
+ `!!(window.__hf && typeof window.__hf.seek === "function" && window.__hf.duration > 0)`,
+ );
+ if (!pageReady) {
+ warmupRunning = false;
+ throw new Error(
+ `[FrameCapture] window.__hf not ready after ${pageReadyTimeout}ms. Page must expose window.__hf = { duration, seek }.`,
+ );
+ }
+
+ // Wait for all video elements to have loaded metadata (dimensions + duration).
+ // Without this, frame 0 captures videos at their 300x150 default size.
+ const videoDeadline = Date.now() + (session.config?.playerReadyTimeout ?? DEFAULT_CONFIG.playerReadyTimeout);
+ while (Date.now() < videoDeadline) {
+ const videosReady = await page.evaluate(
+ `document.querySelectorAll("video").length === 0 || Array.from(document.querySelectorAll("video")).every(v => v.readyState >= 1)`,
+ );
+ if (videosReady) break;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+
+ // Font check (no rAF dependency — uses fonts.ready API directly)
+ await page.evaluate(`document.fonts?.ready`);
+
+ // Stop warmup
+ warmupRunning = false;
+
+ // Set base frame time ticks past warmup range
+ session.beginFrameTimeTicks = (warmupTicks + 10) * session.beginFrameIntervalMs;
+
+ session.isInitialized = true;
+}
+
+async function captureFrameErrorDiagnostics(
+ session: CaptureSession,
+ frameIndex: number,
+ time: number,
+ error: Error,
+): Promise<string | null> {
+ try {
+ const diagnosticsDir = join(session.outputDir, "diagnostics");
+ if (!existsSync(diagnosticsDir)) mkdirSync(diagnosticsDir, { recursive: true });
+ const base = join(diagnosticsDir, `frame-error-${frameIndex}`);
+ await session.page.screenshot({ path: `${base}.png`, type: "png", fullPage: true });
+ const html = await session.page.content();
+ writeFileSync(`${base}.html`, html, "utf-8");
+ writeFileSync(
+ `${base}.json`,
+ JSON.stringify(
+ {
+ frameIndex,
+ time,
+ error: error.message,
+ stack: error.stack,
+ browserConsoleTail: session.browserConsoleBuffer.slice(-30),
+ },
+ null,
+ 2,
+ ),
+ "utf-8",
+ );
+ return `${base}.json`;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Internal helper: seek timeline and inject video frames.
+ * Shared by captureFrame (disk) and captureFrameToBuffer (buffer).
+ * Returns timing breakdown for perf tracking.
+ */
+async function prepareFrameForCapture(
+ session: CaptureSession,
+ frameIndex: number,
+ time: number,
+): Promise<{
+ quantizedTime: number;
+ seekMs: number;
+ beforeCaptureMs: number;
+}> {
+ const { page, options } = session;
+
+ if (!session.isInitialized) {
+ throw new Error("[FrameCapture] Session not initialized");
+ }
+
+ const quantizedTime = quantizeTimeToFrame(time, options.fps);
+
+ const seekStart = Date.now();
+ // Seek via the __hf protocol. The page's seek() implementation handles
+ // all framework-specific logic (GSAP stepping, CSS animation sync, etc.)
+ await page.evaluate((t: number) => {
+ if (window.__hf && typeof window.__hf.seek === "function") {
+ window.__hf.seek(t);
+ }
+ }, quantizedTime);
+ const seekMs = Date.now() - seekStart;
+
+ // Before-capture hook (e.g. video frame injection)
+ const beforeCaptureStart = Date.now();
+ if (session.onBeforeCapture) {
+ await session.onBeforeCapture(page, quantizedTime);
+ }
+ const beforeCaptureMs = Date.now() - beforeCaptureStart;
+
+ return { quantizedTime, seekMs, beforeCaptureMs };
+}
+
+/**
+ * Internal core: prepare, screenshot, and track perf.
+ * Shared by captureFrame (disk) and captureFrameToBuffer (buffer).
+ * Returns the screenshot buffer, quantized time, and total capture time.
+ */
+async function captureFrameCore(
+ session: CaptureSession,
+ frameIndex: number,
+ time: number,
+): Promise<{ buffer: Buffer; quantizedTime: number; captureTimeMs: number }> {
+ const { page, options } = session;
+ const startTime = Date.now();
+
+ try {
+ const { quantizedTime, seekMs, beforeCaptureMs } = await prepareFrameForCapture(session, frameIndex, time);
+
+ const screenshotStart = Date.now();
+ let screenshotBuffer: Buffer;
+
+ if (session.captureMode === "beginframe") {
+ const frameTimeTicks = session.beginFrameTimeTicks + frameIndex * session.beginFrameIntervalMs;
+ const result = await beginFrameCapture(page, options, frameTimeTicks, session.beginFrameIntervalMs);
+ if (result.hasDamage) session.beginFrameHasDamageCount++;
+ else session.beginFrameNoDamageCount++;
+ screenshotBuffer = result.buffer;
+ } else {
+ screenshotBuffer = await pageScreenshotCapture(page, options);
+ }
+
+ const screenshotMs = Date.now() - screenshotStart;
+ const captureTimeMs = Date.now() - startTime;
+
+ session.capturePerf.frames += 1;
+ session.capturePerf.seekMs += seekMs;
+ session.capturePerf.beforeCaptureMs += beforeCaptureMs;
+ session.capturePerf.screenshotMs += screenshotMs;
+ session.capturePerf.totalMs += captureTimeMs;
+
+ return { buffer: screenshotBuffer, quantizedTime, captureTimeMs };
+ } catch (captureError) {
+ if (session.isInitialized) {
+ await captureFrameErrorDiagnostics(
+ session,
+ frameIndex,
+ time,
+ captureError instanceof Error ? captureError : new Error(String(captureError)),
+ );
+ }
+ throw captureError;
+ }
+}
+
+export async function captureFrame(session: CaptureSession, frameIndex: number, time: number): Promise<CaptureResult> {
+ const { options, outputDir } = session;
+ const { buffer, quantizedTime, captureTimeMs } = await captureFrameCore(session, frameIndex, time);
+
+ const ext = options.format === "png" ? "png" : "jpg";
+ const frameName = `frame_${String(frameIndex).padStart(6, "0")}.${ext}`;
+ const framePath = join(outputDir, frameName);
+ writeFileSync(framePath, buffer);
+
+ return { frameIndex, time: quantizedTime, path: framePath, captureTimeMs };
+}
+
+/**
+ * Capture a frame and return the screenshot as a Buffer instead of writing to disk.
+ * Used by the streaming encode pipeline to pipe frames directly to FFmpeg stdin.
+ */
+export async function captureFrameToBuffer(
+ session: CaptureSession,
+ frameIndex: number,
+ time: number,
+): Promise<CaptureBufferResult> {
+ const { buffer, captureTimeMs } = await captureFrameCore(session, frameIndex, time);
+
+ return { buffer, captureTimeMs };
+}
+
+export async function closeCaptureSession(session: CaptureSession): Promise<void> {
+ if (session.page) await session.page.close().catch(() => {});
+ if (session.browser) await releaseBrowser(session.browser, session.config);
+ session.isInitialized = false;
+}
+
+export function prepareCaptureSessionForReuse(
+ session: CaptureSession,
+ outputDir: string,
+ onBeforeCapture: BeforeCaptureHook | null,
+): void {
+ if (!existsSync(outputDir)) {
+ mkdirSync(outputDir, { recursive: true });
+ }
+ session.outputDir = outputDir;
+ session.onBeforeCapture = onBeforeCapture;
+ session.capturePerf = {
+ frames: 0,
+ seekMs: 0,
+ beforeCaptureMs: 0,
+ screenshotMs: 0,
+ totalMs: 0,
+ };
+ session.beginFrameHasDamageCount = 0;
+ session.beginFrameNoDamageCount = 0;
+}
+
+export async function getCompositionDuration(session: CaptureSession): Promise<number> {
+ if (!session.isInitialized) throw new Error("[FrameCapture] Session not initialized");
+
+ return session.page.evaluate(() => {
+ return window.__hf?.duration ?? 0;
+ });
+}
+
+export function getCapturePerfSummary(session: CaptureSession): CapturePerfSummary {
+ const frames = Math.max(1, session.capturePerf.frames);
+ return {
+ frames: session.capturePerf.frames,
+ avgTotalMs: Math.round(session.capturePerf.totalMs / frames),
+ avgSeekMs: Math.round(session.capturePerf.seekMs / frames),
+ avgBeforeCaptureMs: Math.round(session.capturePerf.beforeCaptureMs / frames),
+ avgScreenshotMs: Math.round(session.capturePerf.screenshotMs / frames),
+ };
+}
diff --git a/packages/engine/src/services/parallelCoordinator.test.ts b/packages/engine/src/services/parallelCoordinator.test.ts
new file mode 100644
index 0000000000..cddcc5721a
--- /dev/null
+++ b/packages/engine/src/services/parallelCoordinator.test.ts
@@ -0,0 +1,44 @@
+import { describe, it, expect } from "vitest";
+import { distributeFrames } from "./parallelCoordinator.js";
+
+describe("distributeFrames", () => {
+ it("distributes frames evenly across workers", () => {
+ const tasks = distributeFrames(100, 4, "/tmp/work");
+ expect(tasks).toHaveLength(4);
+
+ // First worker: frames 0-24
+ expect(tasks[0]?.startFrame).toBe(0);
+ expect(tasks[0]?.endFrame).toBe(25);
+
+ // Last worker: frames 75-99
+ expect(tasks[3]?.startFrame).toBe(75);
+ expect(tasks[3]?.endFrame).toBe(100);
+ });
+
+ it("handles single worker", () => {
+ const tasks = distributeFrames(50, 1, "/tmp/work");
+ expect(tasks).toHaveLength(1);
+ expect(tasks[0]?.startFrame).toBe(0);
+ expect(tasks[0]?.endFrame).toBe(50);
+ });
+
+ it("does not create empty tasks when workers exceed frames", () => {
+ const tasks = distributeFrames(3, 10, "/tmp/work");
+ // Can't have more tasks than frames
+ expect(tasks.length).toBeLessThanOrEqual(3);
+ // All frames are covered
+ const totalFrames = tasks.reduce((sum, t) => sum + (t.endFrame - t.startFrame), 0);
+ expect(totalFrames).toBe(3);
+ });
+
+ it("assigns worker output directories", () => {
+ const tasks = distributeFrames(60, 2, "/tmp/my-work");
+ expect(tasks[0]?.outputDir).toContain("worker-0");
+ expect(tasks[1]?.outputDir).toContain("worker-1");
+ });
+
+ it("assigns sequential worker IDs", () => {
+ const tasks = distributeFrames(100, 3, "/tmp/work");
+ expect(tasks.map((t) => t.workerId)).toEqual([0, 1, 2]);
+ });
+});
diff --git a/packages/engine/src/services/parallelCoordinator.ts b/packages/engine/src/services/parallelCoordinator.ts
new file mode 100644
index 0000000000..14d8ee5a7b
--- /dev/null
+++ b/packages/engine/src/services/parallelCoordinator.ts
@@ -0,0 +1,293 @@
+/**
+ * Parallel Coordinator Service
+ *
+ * Coordinates parallel frame capture across multiple Puppeteer sessions.
+ * Auto-detects optimal worker count based on CPU/memory.
+ */
+
+import { cpus, freemem, totalmem } from "os";
+import { existsSync, mkdirSync, readdirSync } from "fs";
+import { copyFile, rename } from "fs/promises";
+import { join } from "path";
+
+import {
+ createCaptureSession,
+ initializeSession,
+ closeCaptureSession,
+ captureFrame,
+ captureFrameToBuffer,
+ getCapturePerfSummary,
+ type CaptureSession,
+ type CaptureOptions,
+ type CapturePerfSummary,
+ type BeforeCaptureHook,
+} from "./frameCapture.js";
+import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";
+
+export interface WorkerTask {
+ workerId: number;
+ startFrame: number;
+ endFrame: number;
+ outputDir: string;
+}
+
+export interface WorkerResult {
+ workerId: number;
+ framesCaptured: number;
+ startFrame: number;
+ endFrame: number;
+ durationMs: number;
+ perf?: CapturePerfSummary;
+ error?: string;
+}
+
+export interface ParallelProgress {
+ totalFrames: number;
+ capturedFrames: number;
+ activeWorkers: number;
+ workerProgress: Map<number, number>;
+}
+
+const MEMORY_PER_WORKER_MB = 256;
+const MIN_WORKERS = 1;
+const ABSOLUTE_MAX_WORKERS = 10;
+const DEFAULT_SAFE_MAX_WORKERS = 6;
+const MIN_FRAMES_PER_WORKER = 30;
+
+export function calculateOptimalWorkers(
+ totalFrames: number,
+ requested?: number,
+ config?: Partial<Pick<EngineConfig, "concurrency" | "coresPerWorker" | "minParallelFrames" | "largeRenderThreshold">>,
+): number {
+ // Resolve effective values: config overrides → DEFAULT_CONFIG fallback.
+ const effectiveMaxWorkers = (() => {
+ const concurrency = config?.concurrency ?? DEFAULT_CONFIG.concurrency;
+ if (concurrency !== "auto") {
+ return Math.max(MIN_WORKERS, Math.min(ABSOLUTE_MAX_WORKERS, Math.floor(concurrency)));
+ }
+ return DEFAULT_SAFE_MAX_WORKERS;
+ })();
+ const effectiveCoresPerWorker = config?.coresPerWorker ?? DEFAULT_CONFIG.coresPerWorker;
+ const effectiveMinParallelFrames = config?.minParallelFrames ?? DEFAULT_CONFIG.minParallelFrames;
+ const effectiveLargeRenderThreshold = config?.largeRenderThreshold ?? DEFAULT_CONFIG.largeRenderThreshold;
+
+ if (requested !== undefined) {
+ return Math.max(MIN_WORKERS, Math.min(effectiveMaxWorkers, requested));
+ }
+
+ if (totalFrames < MIN_FRAMES_PER_WORKER * 2) return 1;
+
+ const cpuCount = cpus().length;
+ const cpuBasedWorkers = Math.max(1, cpuCount - 2);
+
+ // Use total memory instead of free memory — macOS reports misleadingly low
+ // freemem() because it aggressively caches files in "inactive" memory that
+ // is immediately reclaimable.
+ const totalMemoryMB = Math.round(totalmem() / (1024 * 1024));
+ const memoryBasedWorkers = Math.max(1, Math.floor((totalMemoryMB * 0.5) / MEMORY_PER_WORKER_MB));
+
+ const frameBasedWorkers = Math.floor(totalFrames / MIN_FRAMES_PER_WORKER);
+
+ const optimal = Math.min(cpuBasedWorkers, memoryBasedWorkers, frameBasedWorkers);
+ const minWorkersForJob = totalFrames >= effectiveMinParallelFrames ? 2 : MIN_WORKERS;
+ let finalWorkers = Math.max(minWorkersForJob, Math.min(effectiveMaxWorkers, optimal));
+
+ // Adaptive scaling: cap workers for large renders to prevent CPU contention.
+ // Each Chrome process (with SwiftShader) is CPU-heavy; too many on a long
+ // render causes protocol timeouts from compositor starvation.
+ // Scale proportionally to CPU count: ~3 cores per worker (benchmarked).
+ // 8 cores → 2 workers, 16 cores → 5 workers, 32 cores → 10 workers.
+ if (totalFrames >= effectiveLargeRenderThreshold) {
+ const cpuScaledMax = Math.max(2, Math.floor(cpuCount / effectiveCoresPerWorker));
+ if (finalWorkers > cpuScaledMax) {
+ finalWorkers = cpuScaledMax;
+ }
+ }
+
+ return finalWorkers;
+}
+
+export function distributeFrames(totalFrames: number, workerCount: number, workDir: string): WorkerTask[] {
+ const tasks: WorkerTask[] = [];
+ const framesPerWorker = Math.ceil(totalFrames / workerCount);
+
+ for (let i = 0; i < workerCount; i++) {
+ const startFrame = i * framesPerWorker;
+ const endFrame = Math.min((i + 1) * framesPerWorker, totalFrames);
+ if (startFrame >= totalFrames) break;
+
+ tasks.push({
+ workerId: i,
+ startFrame,
+ endFrame,
+ outputDir: join(workDir, `worker-${i}`),
+ });
+ }
+
+ return tasks;
+}
+
+async function executeWorkerTask(
+ task: WorkerTask,
+ serverUrl: string,
+ captureOptions: CaptureOptions,
+ createBeforeCaptureHook: () => BeforeCaptureHook | null,
+ signal?: AbortSignal,
+ onFrameCaptured?: (workerId: number, frameIndex: number) => void,
+ onFrameBuffer?: (frameIndex: number, buffer: Buffer) => Promise<void>,
+ config?: Partial<EngineConfig>,
+): Promise<WorkerResult> {
+ const startTime = Date.now();
+ let framesCaptured = 0;
+
+ if (!existsSync(task.outputDir)) mkdirSync(task.outputDir, { recursive: true });
+
+ let session: CaptureSession | null = null;
+ let perf: CapturePerfSummary | undefined;
+
+ try {
+ session = await createCaptureSession(serverUrl, task.outputDir, captureOptions, createBeforeCaptureHook(), config);
+ await initializeSession(session);
+
+ for (let i = task.startFrame; i < task.endFrame; i++) {
+ if (signal?.aborted) {
+ throw new Error("Parallel worker cancelled");
+ }
+ const time = i / captureOptions.fps;
+
+ if (onFrameBuffer) {
+ // Streaming mode: capture to buffer and invoke callback
+ const { buffer } = await captureFrameToBuffer(session, i, time);
+ await onFrameBuffer(i, buffer);
+ } else {
+ // Disk mode: capture to file
+ await captureFrame(session, i, time);
+ }
+ framesCaptured++;
+
+ if (onFrameCaptured) onFrameCaptured(task.workerId, i);
+ }
+
+ perf = getCapturePerfSummary(session);
+ return {
+ workerId: task.workerId,
+ framesCaptured,
+ startFrame: task.startFrame,
+ endFrame: task.endFrame,
+ durationMs: Date.now() - startTime,
+ perf,
+ };
+ } catch (error) {
+ const errMsg = error instanceof Error ? error.message : String(error);
+ return {
+ workerId: task.workerId,
+ framesCaptured,
+ startFrame: task.startFrame,
+ endFrame: task.endFrame,
+ durationMs: Date.now() - startTime,
+ perf,
+ error: errMsg,
+ };
+ } finally {
+ if (session) await closeCaptureSession(session).catch(() => {});
+ }
+}
+
+export async function executeParallelCapture(
+ serverUrl: string,
+ workDir: string,
+ tasks: WorkerTask[],
+ captureOptions: CaptureOptions,
+ createBeforeCaptureHook: () => BeforeCaptureHook | null,
+ signal?: AbortSignal,
+ onProgress?: (progress: ParallelProgress) => void,
+ onFrameBuffer?: (frameIndex: number, buffer: Buffer) => Promise<void>,
+ config?: Partial<EngineConfig>,
+): Promise<WorkerResult[]> {
+ const totalFrames = tasks.reduce((sum, t) => sum + (t.endFrame - t.startFrame), 0);
+ const workerProgress = new Map<number, number>();
+
+ for (const task of tasks) workerProgress.set(task.workerId, 0);
+
+ const onFrameCaptured = (workerId: number, _frameIndex: number) => {
+ const current = workerProgress.get(workerId) || 0;
+ workerProgress.set(workerId, current + 1);
+
+ if (onProgress) {
+ const capturedFrames = Array.from(workerProgress.values()).reduce((a, b) => a + b, 0);
+ onProgress({
+ totalFrames,
+ capturedFrames,
+ activeWorkers: tasks.length,
+ workerProgress: new Map(workerProgress),
+ });
+ }
+ };
+
+ const results = await Promise.all(
+ tasks.map((task) =>
+ executeWorkerTask(
+ task,
+ serverUrl,
+ captureOptions,
+ createBeforeCaptureHook,
+ signal,
+ onFrameCaptured,
+ onFrameBuffer,
+ config,
+ ),
+ ),
+ );
+
+ const errors = results.filter((r) => r.error);
+ if (errors.length > 0) {
+ const errorMessages = errors.map((e) => `Worker ${e.workerId}: ${e.error}`).join("; ");
+ throw new Error(`[Parallel] Capture failed: ${errorMessages}`);
+ }
+
+ return results;
+}
+
+export async function mergeWorkerFrames(workDir: string, tasks: WorkerTask[], outputDir: string): Promise<number> {
+ if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
+
+ let totalFrames = 0;
+ const sortedTasks = [...tasks].sort((a, b) => a.startFrame - b.startFrame);
+
+ for (const task of sortedTasks) {
+ if (!existsSync(task.outputDir)) {
+ continue;
+ }
+
+ const files = readdirSync(task.outputDir)
+ .filter((f) => f.startsWith("frame_") && (f.endsWith(".jpg") || f.endsWith(".png")))
+ .sort();
+ const copyTasks = files.map(async (file) => {
+ const sourcePath = join(task.outputDir, file);
+ const targetPath = join(outputDir, file);
+ try {
+ await rename(sourcePath, targetPath);
+ } catch {
+ await copyFile(sourcePath, targetPath);
+ }
+ });
+ await Promise.all(copyTasks);
+ totalFrames += files.length;
+ }
+
+ return totalFrames;
+}
+
+export function getSystemResources(): {
+ cpuCores: number;
+ totalMemoryMB: number;
+ freeMemoryMB: number;
+ recommendedWorkers: number;
+} {
+ return {
+ cpuCores: cpus().length,
+ totalMemoryMB: Math.round(totalmem() / (1024 * 1024)),
+ freeMemoryMB: Math.round(freemem() / (1024 * 1024)),
+ recommendedWorkers: calculateOptimalWorkers(1000),
+ };
+}
diff --git a/packages/engine/src/services/screenshotService.ts b/packages/engine/src/services/screenshotService.ts
new file mode 100644
index 0000000000..c51c32f264
--- /dev/null
+++ b/packages/engine/src/services/screenshotService.ts
@@ -0,0 +1,222 @@
+/**
+ * Screenshot Service
+ *
+ * BeginFrame-based deterministic screenshot capture and video frame injection.
+ */
+
+import { type Page } from "puppeteer-core";
+import { type CaptureOptions } from "../types.js";
+import { MEDIA_VISUAL_STYLE_PROPERTIES } from "@hyperframes/core";
+
+export const cdpSessionCache = new WeakMap<Page, import("puppeteer-core").CDPSession>();
+
+export async function getCdpSession(page: Page): Promise<import("puppeteer-core").CDPSession> {
+ let client = cdpSessionCache.get(page);
+ if (!client) {
+ client = await page.createCDPSession();
+ cdpSessionCache.set(page, client);
+ }
+ return client;
+}
+
+/**
+ * BeginFrame result with screenshot data and damage detection.
+ */
+export interface BeginFrameResult {
+ buffer: Buffer;
+ hasDamage: boolean;
+}
+
+/**
+ * Capture a frame using HeadlessExperimental.beginFrame.
+ *
+ * This is an atomic operation: one CDP call runs a single layout-paint-composite
+ * cycle and returns the screenshot + hasDamage boolean. Replaces the separate
+ * settle → screenshot pipeline with a single deterministic render cycle.
+ *
+ * Requires chrome-headless-shell with --enable-begin-frame-control and
+ * --deterministic-mode flags.
+ */
+// Cache the last valid screenshot buffer per page for hasDamage=false frames.
+// When Chrome reports no visual change, we reuse the previous frame rather than
+// attempting Page.captureScreenshot (which times out in beginFrame mode since
+// the compositor is paused).
+const lastFrameCache = new WeakMap<Page, Buffer>();
+
+export async function beginFrameCapture(
+ page: Page,
+ options: CaptureOptions,
+ frameTimeTicks: number,
+ interval: number,
+): Promise<BeginFrameResult> {
+ const client = await getCdpSession(page);
+
+ const format = options.format === "png" ? "png" : "jpeg";
+ const result = await client.send("HeadlessExperimental.beginFrame", {
+ frameTimeTicks,
+ interval,
+ screenshot: {
+ format,
+ quality: format === "jpeg" ? (options.quality ?? 80) : undefined,
+ optimizeForSpeed: true,
+ },
+ });
+
+ let buffer: Buffer;
+ if (result.screenshotData) {
+ buffer = Buffer.from(result.screenshotData, "base64");
+ lastFrameCache.set(page, buffer);
+ } else {
+ // hasDamage=false — nothing changed visually. Reuse the last frame.
+ const cached = lastFrameCache.get(page);
+ if (cached) {
+ buffer = cached;
+ } else {
+ // No cached frame yet (shouldn't happen — frame 0 always has damage).
+ // Issue another beginFrame with a tiny time advance to force a composite.
+ const retry = await client.send("HeadlessExperimental.beginFrame", {
+ frameTimeTicks: frameTimeTicks + 0.001,
+ interval,
+ screenshot: {
+ format,
+ quality: format === "jpeg" ? (options.quality ?? 80) : undefined,
+ optimizeForSpeed: true,
+ },
+ });
+ buffer = retry.screenshotData ? Buffer.from(retry.screenshotData, "base64") : Buffer.alloc(0);
+ if (buffer.length > 0) lastFrameCache.set(page, buffer);
+ }
+ }
+
+ return {
+ buffer,
+ hasDamage: result.hasDamage,
+ };
+}
+
+/**
+ * Capture a screenshot using standard Page.captureScreenshot CDP call.
+ * Fallback for environments where BeginFrame is unavailable (macOS, Windows).
+ */
+export async function pageScreenshotCapture(page: Page, options: CaptureOptions): Promise<Buffer> {
+ const client = await getCdpSession(page);
+ const format = options.format === "png" ? "png" : "jpeg";
+ const result = await client.send("Page.captureScreenshot", {
+ format,
+ quality: format === "jpeg" ? (options.quality ?? 80) : undefined,
+ optimizeForSpeed: true,
+ });
+ return Buffer.from(result.data, "base64");
+}
+
+export async function injectVideoFramesBatch(
+ page: Page,
+ updates: Array<{ videoId: string; dataUri: string }>,
+): Promise<void> {
+ if (updates.length === 0) return;
+ await page.evaluate(
+ async (items: Array<{ videoId: string; dataUri: string }>, visualProperties: string[]) => {
+ const pendingDecodes: Array<Promise<void>> = [];
+ for (const item of items) {
+ const video = document.getElementById(item.videoId) as HTMLVideoElement | null;
+ if (!video) continue;
+
+ let img = video.nextElementSibling as HTMLImageElement | null;
+ const isNewImage = !img || !img.classList.contains("__render_frame__");
+ const computedStyle = window.getComputedStyle(video);
+ const computedOpacity = parseFloat(computedStyle.opacity) || 1;
+ const sourceIsStatic = !computedStyle.position || computedStyle.position === "static";
+
+ if (isNewImage) {
+ img = document.createElement("img");
+ img.classList.add("__render_frame__");
+ img.id = `__render_frame_${item.videoId}__`;
+ img.style.pointerEvents = "none";
+ video.parentNode?.insertBefore(img, video.nextSibling);
+ }
+ if (!img) continue;
+
+ if (!sourceIsStatic) {
+ img.style.position = computedStyle.position;
+ img.style.width = computedStyle.width;
+ img.style.height = computedStyle.height;
+ img.style.top = computedStyle.top;
+ img.style.left = computedStyle.left;
+ img.style.right = computedStyle.right;
+ img.style.bottom = computedStyle.bottom;
+ img.style.inset = computedStyle.inset;
+ } else {
+ const videoRect = video.getBoundingClientRect();
+ const offsetLeft = Number.isFinite(video.offsetLeft) ? video.offsetLeft : 0;
+ const offsetTop = Number.isFinite(video.offsetTop) ? video.offsetTop : 0;
+ const offsetWidth = video.offsetWidth > 0 ? video.offsetWidth : videoRect.width;
+ const offsetHeight = video.offsetHeight > 0 ? video.offsetHeight : videoRect.height;
+ img.style.position = "absolute";
+ img.style.inset = "auto";
+ img.style.left = `${offsetLeft}px`;
+ img.style.top = `${offsetTop}px`;
+ img.style.right = "auto";
+ img.style.bottom = "auto";
+ img.style.width = `${offsetWidth}px`;
+ img.style.height = `${offsetHeight}px`;
+ }
+ img.style.objectFit = computedStyle.objectFit;
+ img.style.objectPosition = computedStyle.objectPosition;
+ img.style.zIndex = computedStyle.zIndex;
+
+ for (const property of visualProperties) {
+ if (
+ sourceIsStatic &&
+ (property === "top" ||
+ property === "left" ||
+ property === "right" ||
+ property === "bottom" ||
+ property === "inset")
+ ) {
+ continue;
+ }
+ const value = computedStyle.getPropertyValue(property);
+ if (value) {
+ img.style.setProperty(property, value);
+ }
+ }
+ img.decoding = "sync";
+ img.src = item.dataUri;
+ pendingDecodes.push(
+ img
+ .decode()
+ .catch(() => undefined)
+ .then(() => undefined),
+ );
+ img.style.opacity = String(computedOpacity);
+ img.style.visibility = "visible";
+ video.style.setProperty("visibility", "hidden", "important");
+ video.style.setProperty("opacity", "0", "important");
+ video.style.setProperty("pointer-events", "none", "important");
+ }
+ if (pendingDecodes.length > 0) {
+ await Promise.all(pendingDecodes);
+ }
+ },
+ updates,
+ [...MEDIA_VISUAL_STYLE_PROPERTIES],
+ );
+}
+
+export async function syncVideoFrameVisibility(page: Page, activeVideoIds: string[]): Promise<void> {
+ await page.evaluate((ids: string[]) => {
+ const active = new Set(ids);
+ const videos = Array.from(document.querySelectorAll("video[data-start]")) as HTMLVideoElement[];
+ for (const video of videos) {
+ if (active.has(video.id)) continue;
+ video.style.removeProperty("display");
+ video.style.setProperty("visibility", "hidden", "important");
+ video.style.setProperty("opacity", "0", "important");
+ video.style.setProperty("pointer-events", "none", "important");
+ const img = video.nextElementSibling as HTMLElement | null;
+ if (img && img.classList.contains("__render_frame__")) {
+ img.style.visibility = "hidden";
+ }
+ }
+ }, activeVideoIds);
+}
diff --git a/packages/engine/src/services/streamingEncoder.ts b/packages/engine/src/services/streamingEncoder.ts
new file mode 100644
index 0000000000..0a3e9fe651
--- /dev/null
+++ b/packages/engine/src/services/streamingEncoder.ts
@@ -0,0 +1,308 @@
+/**
+ * Streaming Encoder Service
+ *
+ * Pipes frame screenshot buffers directly to FFmpeg's stdin instead of writing
+ * them to disk and reading them back in a separate encode stage. Follows the
+ * Remotion pattern of image2pipe → FFmpeg.
+ *
+ * Two building blocks:
+ * 1. Frame reorder buffer – ensures out-of-order parallel workers feed
+ * frames to FFmpeg stdin in sequential order.
+ * 2. Streaming FFmpeg encoder – spawns FFmpeg with `-f image2pipe` and
+ * exposes a `writeFrame(buffer)` + `close()` API.
+ */
+
+import { spawn, type ChildProcess } from "child_process";
+import { existsSync, mkdirSync, statSync } from "fs";
+import { dirname } from "path";
+
+import { type GpuEncoder, getCachedGpuEncoder, getGpuEncoderName } from "../utils/gpuEncoder.js";
+import { type EncoderOptions } from "./chunkEncoder.types.js";
+import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";
+
+// Re-export EncoderOptions so callers can reference the type via this module.
+export type { EncoderOptions } from "./chunkEncoder.types.js";
+
+// ---------------------------------------------------------------------------
+// 1. Frame reorder buffer (based on Remotion's ensure-frames-in-order.ts)
+// ---------------------------------------------------------------------------
+
+export interface FrameReorderBuffer {
+ waitForFrame: (frame: number) => Promise<void>;
+ advanceTo: (frame: number) => void;
+ waitForAllDone: () => Promise<void>;
+}
+
+export function createFrameReorderBuffer(startFrame: number, endFrame: number): FrameReorderBuffer {
+ let nextFrame = startFrame;
+ let waiters: Array<{ frame: number; resolve: () => void }> = [];
+
+ const resolveWaiters = () => {
+ for (const waiter of waiters.slice()) {
+ if (waiter.frame === nextFrame) {
+ waiter.resolve();
+ waiters = waiters.filter((w) => w !== waiter);
+ }
+ }
+ };
+
+ return {
+ waitForFrame: (frame: number) =>
+ new Promise<void>((resolve) => {
+ waiters.push({ frame, resolve });
+ resolveWaiters();
+ }),
+ advanceTo: (frame: number) => {
+ nextFrame = frame;
+ resolveWaiters();
+ },
+ waitForAllDone: () =>
+ new Promise<void>((resolve) => {
+ waiters.push({ frame: endFrame, resolve });
+ resolveWaiters();
+ }),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// 2. Streaming FFmpeg encoder
+// ---------------------------------------------------------------------------
+
+export interface StreamingEncoderOptions {
+ fps: number;
+ width: number;
+ height: number;
+ codec?: "h264" | "h265" | "vp9" | "prores";
+ preset?: string;
+ quality?: number;
+ bitrate?: string;
+ pixelFormat?: string;
+ useGpu?: boolean;
+ imageFormat?: "jpeg" | "png";
+}
+
+export interface StreamingEncoderResult {
+ success: boolean;
+ durationMs: number;
+ fileSize: number;
+ error?: string;
+}
+
+export interface StreamingEncoder {
+ writeFrame: (buffer: Buffer) => boolean;
+ close: () => Promise<StreamingEncoderResult>;
+ getExitStatus: () => "running" | "success" | "error";
+}
+
+/**
+ * Build FFmpeg args for streaming (image2pipe) input.
+ * Reuses the same codec/quality/GPU logic as chunkEncoder's buildEncoderArgs
+ * but with `-f image2pipe` instead of `-i <pattern>`.
+ */
+function buildStreamingArgs(
+ options: StreamingEncoderOptions,
+ outputPath: string,
+ gpuEncoder: GpuEncoder = null,
+): string[] {
+ const {
+ fps,
+ codec = "h264",
+ preset = "medium",
+ quality = 23,
+ bitrate,
+ pixelFormat = "yuv420p",
+ useGpu = false,
+ imageFormat = "jpeg",
+ } = options;
+
+ // Input args: pipe from stdin
+ const inputCodec = imageFormat === "png" ? "png" : "mjpeg";
+ const args: string[] = [
+ "-f",
+ "image2pipe",
+ "-vcodec",
+ inputCodec,
+ "-framerate",
+ String(fps),
+ "-i",
+ "-",
+ "-r",
+ String(fps),
+ ];
+
+ const shouldUseGpu = useGpu && gpuEncoder !== null;
+
+ if (codec === "h264" || codec === "h265") {
+ if (shouldUseGpu) {
+ const encoderName = getGpuEncoderName(gpuEncoder, codec);
+ args.push("-c:v", encoderName);
+
+ switch (gpuEncoder) {
+ case "nvenc":
+ args.push("-preset", preset);
+ if (bitrate) args.push("-b:v", bitrate);
+ else args.push("-cq", String(quality));
+ break;
+ case "videotoolbox":
+ if (bitrate) args.push("-b:v", bitrate);
+ else {
+ const vtQuality = Math.max(0, Math.min(100, 100 - quality * 2));
+ args.push("-q:v", String(vtQuality));
+ }
+ args.push("-allow_sw", "1");
+ break;
+ case "vaapi":
+ args.unshift("-vaapi_device", "/dev/dri/renderD128");
+ args.push("-vf", "format=nv12,hwupload");
+ if (bitrate) args.push("-b:v", bitrate);
+ else args.push("-qp", String(quality));
+ break;
+ case "qsv":
+ args.push("-preset", preset);
+ if (bitrate) args.push("-b:v", bitrate);
+ else args.push("-global_quality", String(quality));
+ break;
+ }
+ } else {
+ const encoderName = codec === "h264" ? "libx264" : "libx265";
+ args.push("-c:v", encoderName, "-preset", preset);
+ if (bitrate) args.push("-b:v", bitrate);
+ else args.push("-crf", String(quality));
+ }
+ } else if (codec === "vp9") {
+ args.push("-c:v", "libvpx-vp9", "-b:v", bitrate || "0", "-crf", String(quality));
+ args.push("-deadline", preset === "ultrafast" ? "realtime" : "good");
+ } else if (codec === "prores") {
+ args.push("-c:v", "prores_ks", "-profile:v", preset, "-vendor", "apl0");
+ return [...args, "-y", outputPath];
+ }
+
+ if (gpuEncoder !== "vaapi") {
+ args.push("-pix_fmt", pixelFormat);
+ }
+
+ args.push("-y", outputPath);
+ return args;
+}
+
+/**
+ * Spawn a streaming FFmpeg encoder that accepts frame buffers on stdin.
+ */
+export async function spawnStreamingEncoder(
+ outputPath: string,
+ options: StreamingEncoderOptions,
+ signal?: AbortSignal,
+ config?: Partial<Pick<EngineConfig, "ffmpegStreamingTimeout">>,
+): Promise<StreamingEncoder> {
+ const outputDir = dirname(outputPath);
+ if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
+
+ let gpuEncoder: GpuEncoder = null;
+ if (options.useGpu) {
+ gpuEncoder = await getCachedGpuEncoder();
+ }
+
+ const args = buildStreamingArgs(options, outputPath, gpuEncoder);
+
+ const startTime = Date.now();
+ const ffmpeg: ChildProcess = spawn("ffmpeg", args, {
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+
+ let exitStatus: "running" | "success" | "error" = "running";
+ let stderr = "";
+ let exitCode: number | null = null;
+ let exitPromiseResolve: ((value: void) => void) | null = null;
+ const exitPromise = new Promise<void>((resolve) => (exitPromiseResolve = resolve));
+
+ // Track stderr for progress and error messages
+ ffmpeg.stderr?.on("data", (data: Buffer) => {
+ stderr += data.toString();
+ });
+
+ ffmpeg.on("close", (code: number | null) => {
+ exitCode = code;
+ exitStatus = code === 0 ? "success" : "error";
+ exitPromiseResolve?.();
+ });
+
+ ffmpeg.on("error", (err: Error) => {
+ exitStatus = "error";
+ stderr += `\nProcess error: ${err.message}`;
+ exitPromiseResolve?.();
+ });
+
+ // Handle abort signal
+ const onAbort = () => {
+ if (exitStatus === "running") {
+ ffmpeg.kill("SIGTERM");
+ }
+ };
+ if (signal) {
+ if (signal.aborted) {
+ ffmpeg.kill("SIGTERM");
+ } else {
+ signal.addEventListener("abort", onAbort, { once: true });
+ }
+ }
+
+ // Timeout safety
+ const streamingTimeout = config?.ffmpegStreamingTimeout ?? DEFAULT_CONFIG.ffmpegStreamingTimeout;
+ const timer = setTimeout(() => {
+ if (exitStatus === "running") {
+ ffmpeg.kill("SIGTERM");
+ }
+ }, streamingTimeout);
+
+ const encoder: StreamingEncoder = {
+ writeFrame: (buffer: Buffer): boolean => {
+ if (exitStatus !== "running" || !ffmpeg.stdin || ffmpeg.stdin.destroyed) {
+ return false;
+ }
+ return ffmpeg.stdin.write(buffer);
+ },
+
+ close: async (): Promise<StreamingEncoderResult> => {
+ clearTimeout(timer);
+ if (signal) signal.removeEventListener("abort", onAbort);
+
+ // Close stdin to signal end of input
+ if (ffmpeg.stdin && !ffmpeg.stdin.destroyed) {
+ await new Promise<void>((resolve) => {
+ ffmpeg.stdin!.end(() => resolve());
+ });
+ }
+
+ // Wait for FFmpeg to finish
+ await exitPromise;
+
+ const durationMs = Date.now() - startTime;
+
+ if (signal?.aborted) {
+ return {
+ success: false,
+ durationMs,
+ fileSize: 0,
+ error: "Streaming encode cancelled",
+ };
+ }
+
+ if (exitCode !== 0) {
+ return {
+ success: false,
+ durationMs,
+ fileSize: 0,
+ error: `FFmpeg exited with code ${exitCode}`,
+ };
+ }
+
+ const fileSize = existsSync(outputPath) ? statSync(outputPath).size : 0;
+
+ return { success: true, durationMs, fileSize };
+ },
+
+ getExitStatus: () => exitStatus,
+ };
+
+ return encoder;
+}
diff --git a/packages/engine/src/services/videoFrameExtractor.ts b/packages/engine/src/services/videoFrameExtractor.ts
new file mode 100644
index 0000000000..4d65582810
--- /dev/null
+++ b/packages/engine/src/services/videoFrameExtractor.ts
@@ -0,0 +1,395 @@
+/**
+ * Video Frame Extractor Service
+ *
+ * Pre-extracts video frames using FFmpeg for frame-accurate rendering.
+ * Videos are replaced with <img> elements during capture.
+ */
+
+import { spawn } from "child_process";
+import { existsSync, mkdirSync, readdirSync, rmSync } from "fs";
+import { join } from "path";
+import { parseHTML } from "linkedom";
+import { extractVideoMetadata, type VideoMetadata } from "../utils/ffprobe.js";
+import { downloadToTemp, isHttpUrl } from "../utils/urlDownloader.js";
+import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";
+
+export interface VideoElement {
+ id: string;
+ src: string;
+ start: number;
+ end: number;
+ mediaStart: number;
+ hasAudio: boolean;
+}
+
+export interface ExtractedFrames {
+ videoId: string;
+ srcPath: string;
+ outputDir: string;
+ framePattern: string;
+ fps: number;
+ totalFrames: number;
+ metadata: VideoMetadata;
+ framePaths: Map<number, string>;
+}
+
+export interface ExtractionOptions {
+ fps: number;
+ outputDir: string;
+ quality?: number;
+ format?: "jpg" | "png";
+}
+
+export interface ExtractionResult {
+ success: boolean;
+ extracted: ExtractedFrames[];
+ errors: Array<{ videoId: string; error: string }>;
+ totalFramesExtracted: number;
+ durationMs: number;
+}
+
+export function parseVideoElements(html: string): VideoElement[] {
+ const videos: VideoElement[] = [];
+ const { document } = parseHTML(html);
+
+ const videoEls = document.querySelectorAll("video[id][src]");
+ for (const el of videoEls) {
+ const id = el.getAttribute("id");
+ const src = el.getAttribute("src");
+ if (!id || !src) continue;
+
+ const startAttr = el.getAttribute("data-start");
+ const endAttr = el.getAttribute("data-end");
+ const mediaStartAttr = el.getAttribute("data-media-start");
+ const hasAudioAttr = el.getAttribute("data-has-audio");
+
+ videos.push({
+ id,
+ src,
+ start: startAttr ? parseFloat(startAttr) : 0,
+ end: endAttr ? parseFloat(endAttr) : 0,
+ mediaStart: mediaStartAttr ? parseFloat(mediaStartAttr) : 0,
+ hasAudio: hasAudioAttr === "true",
+ });
+ }
+
+ return videos;
+}
+
+export async function extractVideoFramesRange(
+ videoPath: string,
+ videoId: string,
+ startTime: number,
+ duration: number,
+ options: ExtractionOptions,
+ signal?: AbortSignal,
+ config?: Partial<Pick<EngineConfig, "ffmpegProcessTimeout">>,
+): Promise<ExtractedFrames> {
+ const ffmpegProcessTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;
+ const { fps, outputDir, quality = 95, format = "jpg" } = options;
+
+ const videoOutputDir = join(outputDir, videoId);
+ if (!existsSync(videoOutputDir)) mkdirSync(videoOutputDir, { recursive: true });
+
+ const metadata = await extractVideoMetadata(videoPath);
+ const framePattern = `frame_%05d.${format}`;
+ const outputPattern = join(videoOutputDir, framePattern);
+
+ const args: string[] = [
+ "-ss",
+ String(startTime),
+ "-i",
+ videoPath,
+ "-t",
+ String(duration),
+ "-vf",
+ `fps=${fps}`,
+ "-q:v",
+ format === "jpg" ? String(Math.ceil((100 - quality) / 3)) : "0",
+ ];
+ if (format === "png") args.push("-compression_level", "6");
+ args.push("-y", outputPattern);
+
+ return new Promise((resolve, reject) => {
+ const ffmpeg = spawn("ffmpeg", args);
+ let stderr = "";
+ const onAbort = () => {
+ ffmpeg.kill("SIGTERM");
+ };
+ if (signal) {
+ if (signal.aborted) {
+ ffmpeg.kill("SIGTERM");
+ } else {
+ signal.addEventListener("abort", onAbort, { once: true });
+ }
+ }
+
+ const timer = setTimeout(() => {
+ ffmpeg.kill("SIGTERM");
+ }, ffmpegProcessTimeout);
+
+ ffmpeg.stderr.on("data", (data) => {
+ stderr += data.toString();
+ });
+
+ ffmpeg.on("close", (code) => {
+ clearTimeout(timer);
+ if (signal) signal.removeEventListener("abort", onAbort);
+ if (signal?.aborted) {
+ reject(new Error("Video frame extraction cancelled"));
+ return;
+ }
+ if (code !== 0) {
+ reject(new Error(`FFmpeg exited with code ${code}: ${stderr.slice(-500)}`));
+ return;
+ }
+
+ const framePaths = new Map<number, string>();
+ const files = readdirSync(videoOutputDir)
+ .filter((f) => f.startsWith("frame_") && f.endsWith(`.${format}`))
+ .sort();
+ files.forEach((file, index) => {
+ framePaths.set(index, join(videoOutputDir, file));
+ });
+
+ resolve({
+ videoId,
+ srcPath: videoPath,
+ outputDir: videoOutputDir,
+ framePattern,
+ fps,
+ totalFrames: framePaths.size,
+ metadata,
+ framePaths,
+ });
+ });
+
+ ffmpeg.on("error", (err) => {
+ clearTimeout(timer);
+ if (signal) signal.removeEventListener("abort", onAbort);
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
+ reject(new Error("[FFmpeg] ffmpeg not found"));
+ } else {
+ reject(err);
+ }
+ });
+ });
+}
+
+export async function extractAllVideoFrames(
+ videos: VideoElement[],
+ baseDir: string,
+ options: ExtractionOptions,
+ signal?: AbortSignal,
+ config?: Partial<Pick<EngineConfig, "ffmpegProcessTimeout">>,
+): Promise<ExtractionResult> {
+ const startTime = Date.now();
+ const extracted: ExtractedFrames[] = [];
+ const errors: Array<{ videoId: string; error: string }> = [];
+ let totalFramesExtracted = 0;
+
+ // Process videos in parallel for better performance
+ const results = await Promise.all(
+ videos.map(async (video) => {
+ if (signal?.aborted) {
+ throw new Error("Video frame extraction cancelled");
+ }
+ try {
+ let videoPath = video.src;
+ if (!videoPath.startsWith("/") && !isHttpUrl(videoPath)) {
+ videoPath = join(baseDir, videoPath);
+ }
+
+ if (isHttpUrl(videoPath)) {
+ const downloadDir = join(options.outputDir, "_downloads");
+ mkdirSync(downloadDir, { recursive: true });
+ videoPath = await downloadToTemp(videoPath, downloadDir);
+ }
+
+ if (!existsSync(videoPath)) {
+ return { error: { videoId: video.id, error: `Video file not found: ${videoPath}` } };
+ }
+
+ let videoDuration = video.end - video.start;
+
+ // Fallback: if no data-duration/data-end was specified, probe the actual file
+ if (videoDuration <= 0) {
+ const metadata = await extractVideoMetadata(videoPath);
+ const sourceDuration = metadata.durationSeconds - video.mediaStart;
+ videoDuration = sourceDuration > 0 ? sourceDuration : metadata.durationSeconds;
+ video.end = video.start + videoDuration;
+ }
+
+ const result = await extractVideoFramesRange(
+ videoPath,
+ video.id,
+ video.mediaStart,
+ videoDuration,
+ options,
+ signal,
+ config,
+ );
+
+ return { result };
+ } catch (err) {
+ return {
+ error: {
+ videoId: video.id,
+ error: err instanceof Error ? err.message : String(err),
+ },
+ };
+ }
+ }),
+ );
+
+ // Collect results and errors
+ for (const item of results) {
+ if ("error" in item && item.error) {
+ errors.push(item.error);
+ } else if ("result" in item) {
+ extracted.push(item.result);
+ totalFramesExtracted += item.result.totalFrames;
+ }
+ }
+
+ return { success: errors.length === 0, extracted, errors, totalFramesExtracted, durationMs: Date.now() - startTime };
+}
+
+export function getFrameAtTime(extracted: ExtractedFrames, globalTime: number, videoStart: number): string | null {
+ const localTime = globalTime - videoStart;
+ if (localTime < 0) return null;
+ const frameIndex = Math.floor(localTime * extracted.fps);
+ if (frameIndex < 0 || frameIndex >= extracted.totalFrames) return null;
+ return extracted.framePaths.get(frameIndex) || null;
+}
+
+export class FrameLookupTable {
+ private videos: Map<
+ string,
+ {
+ extracted: ExtractedFrames;
+ start: number;
+ end: number;
+ mediaStart: number;
+ }
+ > = new Map();
+ private orderedVideos: Array<{
+ videoId: string;
+ extracted: ExtractedFrames;
+ start: number;
+ end: number;
+ mediaStart: number;
+ }> = [];
+ private activeVideoIds: Set<string> = new Set();
+ private startCursor = 0;
+ private lastTime: number | null = null;
+
+ addVideo(extracted: ExtractedFrames, start: number, end: number, mediaStart: number): void {
+ this.videos.set(extracted.videoId, { extracted, start, end, mediaStart });
+ this.orderedVideos = Array.from(this.videos.entries())
+ .map(([videoId, video]) => ({ videoId, ...video }))
+ .sort((a, b) => a.start - b.start);
+ this.resetActiveState();
+ }
+
+ getFrame(videoId: string, globalTime: number): string | null {
+ const video = this.videos.get(videoId);
+ if (!video) return null;
+ if (globalTime < video.start || globalTime >= video.end) return null;
+ return getFrameAtTime(video.extracted, globalTime, video.start);
+ }
+
+ private resetActiveState(): void {
+ this.activeVideoIds.clear();
+ this.startCursor = 0;
+ this.lastTime = null;
+ }
+
+ private refreshActiveSet(globalTime: number): void {
+ if (this.lastTime == null || globalTime < this.lastTime) {
+ this.activeVideoIds.clear();
+ this.startCursor = 0;
+ for (const entry of this.orderedVideos) {
+ if (entry.start <= globalTime && globalTime < entry.end) {
+ this.activeVideoIds.add(entry.videoId);
+ }
+ if (entry.start <= globalTime) {
+ this.startCursor += 1;
+ } else {
+ break;
+ }
+ }
+ this.lastTime = globalTime;
+ return;
+ }
+
+ while (this.startCursor < this.orderedVideos.length) {
+ const candidate = this.orderedVideos[this.startCursor];
+ if (!candidate) break;
+ if (candidate.start > globalTime) {
+ break;
+ }
+ if (globalTime < candidate.end) {
+ this.activeVideoIds.add(candidate.videoId);
+ }
+ this.startCursor += 1;
+ }
+
+ for (const videoId of Array.from(this.activeVideoIds)) {
+ const video = this.videos.get(videoId);
+ if (!video || globalTime < video.start || globalTime >= video.end) {
+ this.activeVideoIds.delete(videoId);
+ }
+ }
+ this.lastTime = globalTime;
+ }
+
+ getActiveFramePayloads(globalTime: number): Map<string, { framePath: string; frameIndex: number }> {
+ const frames = new Map<string, { framePath: string; frameIndex: number }>();
+ this.refreshActiveSet(globalTime);
+ for (const videoId of this.activeVideoIds) {
+ const video = this.videos.get(videoId);
+ if (!video) continue;
+ const localTime = globalTime - video.start;
+ const frameIndex = Math.floor(localTime * video.extracted.fps);
+ if (frameIndex < 0 || frameIndex >= video.extracted.totalFrames) continue;
+ const framePath = video.extracted.framePaths.get(frameIndex);
+ if (!framePath) continue;
+ frames.set(videoId, { framePath, frameIndex });
+ }
+ return frames;
+ }
+
+ getActiveFrames(globalTime: number): Map<string, string> {
+ const payloads = this.getActiveFramePayloads(globalTime);
+ const frames = new Map<string, string>();
+ for (const [videoId, payload] of payloads) {
+ frames.set(videoId, payload.framePath);
+ }
+ return frames;
+ }
+
+ cleanup(): void {
+ for (const video of this.videos.values()) {
+ if (existsSync(video.extracted.outputDir)) {
+ rmSync(video.extracted.outputDir, { recursive: true, force: true });
+ }
+ }
+ this.videos.clear();
+ this.orderedVideos = [];
+ this.resetActiveState();
+ }
+}
+
+export function createFrameLookupTable(videos: VideoElement[], extracted: ExtractedFrames[]): FrameLookupTable {
+ const table = new FrameLookupTable();
+ const extractedMap = new Map<string, ExtractedFrames>();
+ for (const ext of extracted) extractedMap.set(ext.videoId, ext);
+
+ for (const video of videos) {
+ const ext = extractedMap.get(video.id);
+ if (ext) table.addVideo(ext, video.start, video.end, video.mediaStart);
+ }
+
+ return table;
+}
diff --git a/packages/engine/src/services/videoFrameInjector.ts b/packages/engine/src/services/videoFrameInjector.ts
new file mode 100644
index 0000000000..c31eb9b445
--- /dev/null
+++ b/packages/engine/src/services/videoFrameInjector.ts
@@ -0,0 +1,113 @@
+/**
+ * Video Frame Injector
+ *
+ * Creates a BeforeCaptureHook that replaces native <video> elements with
+ * pre-extracted frame images during rendering. This is the Hyperframes-specific
+ * video handling strategy — OSS users with different video pipelines can
+ * provide their own hook or skip video injection entirely.
+ */
+
+import { type Page } from "puppeteer-core";
+import { promises as fs } from "fs";
+import { type FrameLookupTable } from "./videoFrameExtractor.js";
+import { injectVideoFramesBatch, syncVideoFrameVisibility } from "./screenshotService.js";
+import { type BeforeCaptureHook } from "./frameCapture.js";
+import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";
+
+function createFrameDataUriCache(cacheLimit: number) {
+ const cache = new Map<string, string>();
+ const inFlight = new Map<string, Promise<string>>();
+
+ function remember(framePath: string, dataUri: string): string {
+ if (cache.has(framePath)) {
+ cache.delete(framePath);
+ }
+ cache.set(framePath, dataUri);
+ if (cache.size > cacheLimit) {
+ const oldestKey = cache.keys().next().value;
+ if (oldestKey) {
+ cache.delete(oldestKey);
+ }
+ }
+ return dataUri;
+ }
+
+ async function get(framePath: string): Promise<string> {
+ const cached = cache.get(framePath);
+ if (cached) {
+ remember(framePath, cached);
+ return cached;
+ }
+
+ const existing = inFlight.get(framePath);
+ if (existing) {
+ return existing;
+ }
+
+ const pending = fs
+ .readFile(framePath)
+ .then((frameData) => {
+ const mimeType = framePath.endsWith(".png") ? "image/png" : "image/jpeg";
+ const dataUri = `data:${mimeType};base64,${frameData.toString("base64")}`;
+ return remember(framePath, dataUri);
+ })
+ .finally(() => {
+ inFlight.delete(framePath);
+ });
+ inFlight.set(framePath, pending);
+ return pending;
+ }
+
+ return { get };
+}
+
+/**
+ * Creates a BeforeCaptureHook that injects pre-extracted video frames
+ * into the page, replacing native <video> elements with frame images.
+ */
+export function createVideoFrameInjector(
+ frameLookup: FrameLookupTable | null,
+ config?: Partial<Pick<EngineConfig, "frameDataUriCacheLimit">>,
+): BeforeCaptureHook | null {
+ if (!frameLookup) return null;
+
+ const cacheLimit = Math.max(32, config?.frameDataUriCacheLimit ?? DEFAULT_CONFIG.frameDataUriCacheLimit);
+ const frameCache = createFrameDataUriCache(cacheLimit);
+ const lastInjectedFrameByVideo = new Map<string, number>();
+
+ return async (page: Page, time: number) => {
+ const activePayloads = frameLookup.getActiveFramePayloads(time);
+
+ const updates: Array<{ videoId: string; dataUri: string; frameIndex: number }> = [];
+ const activeIds = new Set<string>();
+ if (activePayloads.size > 0) {
+ const pendingReads: Array<Promise<{ videoId: string; dataUri: string; frameIndex: number }>> = [];
+ for (const [videoId, payload] of activePayloads) {
+ activeIds.add(videoId);
+ const lastFrameIndex = lastInjectedFrameByVideo.get(videoId);
+ if (lastFrameIndex === payload.frameIndex) continue;
+ pendingReads.push(
+ frameCache.get(payload.framePath).then((dataUri) => ({ videoId, dataUri, frameIndex: payload.frameIndex })),
+ );
+ }
+ updates.push(...(await Promise.all(pendingReads)));
+ }
+
+ for (const videoId of Array.from(lastInjectedFrameByVideo.keys())) {
+ if (!activeIds.has(videoId)) {
+ lastInjectedFrameByVideo.delete(videoId);
+ }
+ }
+
+ await syncVideoFrameVisibility(page, Array.from(activeIds));
+ if (updates.length > 0) {
+ await injectVideoFramesBatch(
+ page,
+ updates.map((u) => ({ videoId: u.videoId, dataUri: u.dataUri })),
+ );
+ for (const update of updates) {
+ lastInjectedFrameByVideo.set(update.videoId, update.frameIndex);
+ }
+ }
+ };
+}
diff --git a/packages/engine/src/types.ts b/packages/engine/src/types.ts
new file mode 100644
index 0000000000..a27c77f70a
--- /dev/null
+++ b/packages/engine/src/types.ts
@@ -0,0 +1,91 @@
+/**
+ * @hyperframes/engine — Protocol Types
+ *
+ * The engine's page contract. Any web page that wants to be rendered
+ * as video must expose `window.__hf` implementing the HfProtocol interface.
+ */
+
+// ── Seek Protocol ──────────────────────────────────────────────────────────────
+
+/**
+ * Declares a media element the engine should handle.
+ *
+ * Headless Chrome in BeginFrame mode cannot play <video> or produce audio.
+ * The engine pre-extracts video frames and audio tracks from declared media
+ * elements and handles injection/mixing automatically.
+ */
+export interface HfMediaElement {
+ /** DOM id of the <video> or <audio> element */
+ elementId: string;
+ /** Source file path or URL */
+ src: string;
+ /** When in the composition this element appears (seconds) */
+ startTime: number;
+ /** When in the composition this element disappears (seconds) */
+ endTime: number;
+ /** Offset into the source file (seconds, default: 0) */
+ mediaOffset?: number;
+ /** Audio volume 0-1 (default: 1) */
+ volume?: number;
+ /** Whether this element has audio that should be extracted */
+ hasAudio?: boolean;
+}
+
+/**
+ * The seek protocol. The only contract between the engine and a page.
+ *
+ * The engine reads `duration` to calculate total frames, calls `seek(time)`
+ * before each frame capture, and uses `media` (if provided) to handle
+ * video frame injection and audio mixing.
+ *
+ * The engine does NOT care what animation framework drives the page.
+ * GSAP, Framer Motion, CSS animations, Three.js — anything works as long
+ * as `seek()` produces deterministic visual output for a given time.
+ */
+export interface HfProtocol {
+ /** Total duration of the composition in seconds */
+ duration: number;
+ /** Seek to a specific time. Must produce deterministic visual output. */
+ seek(time: number): void;
+ /** Optional: media elements the engine should handle */
+ media?: HfMediaElement[];
+}
+
+// ── Capture Types ──────────────────────────────────────────────────────────────
+
+export interface CaptureOptions {
+ width: number;
+ height: number;
+ fps: number;
+ format?: "jpeg" | "png";
+ quality?: number;
+ deviceScaleFactor?: number;
+}
+
+export interface CaptureResult {
+ frameIndex: number;
+ time: number;
+ path: string;
+ captureTimeMs: number;
+}
+
+export interface CaptureBufferResult {
+ buffer: Buffer;
+ captureTimeMs: number;
+}
+
+export interface CapturePerfSummary {
+ frames: number;
+ avgTotalMs: number;
+ avgSeekMs: number;
+ avgBeforeCaptureMs: number;
+ avgScreenshotMs: number;
+}
+
+// ── Global Augmentation ────────────────────────────────────────────────────────
+
+declare global {
+ interface Window {
+ __hf?: HfProtocol;
+ }
+}
diff --git a/packages/engine/src/utils/ffprobe.ts b/packages/engine/src/utils/ffprobe.ts
new file mode 100644
index 0000000000..aae63f1aa6
--- /dev/null
+++ b/packages/engine/src/utils/ffprobe.ts
@@ -0,0 +1,192 @@
+import { spawn } from "child_process";
+
+const videoMetadataCache = new Map<string, Promise<VideoMetadata>>();
+const audioMetadataCache = new Map<string, Promise<AudioMetadata>>();
+
+export interface VideoMetadata {
+ durationSeconds: number;
+ width: number;
+ height: number;
+ fps: number;
+ videoCodec: string;
+ hasAudio: boolean;
+}
+
+export interface AudioMetadata {
+ durationSeconds: number;
+ sampleRate: number;
+ channels: number;
+ audioCodec: string;
+ bitrate?: number;
+}
+
+interface FFProbeStream {
+ codec_type: string;
+ codec_name?: string;
+ width?: number;
+ height?: number;
+ r_frame_rate?: string;
+ avg_frame_rate?: string;
+ sample_rate?: string;
+ channels?: number;
+}
+
+interface FFProbeFormat {
+ duration?: string;
+ bit_rate?: string;
+}
+
+interface FFProbeOutput {
+ streams: FFProbeStream[];
+ format: FFProbeFormat;
+}
+
+function parseFrameRate(frameRateStr: string | undefined): number {
+ if (!frameRateStr) return 0;
+ const parts = frameRateStr.split("/");
+ if (parts.length === 2) {
+ const num = parseFloat(parts[0] ?? "");
+ const den = parseFloat(parts[1] ?? "");
+ if (den !== 0) return Math.round((num / den) * 100) / 100;
+ }
+ return parseFloat(frameRateStr) || 0;
+}
+
+export async function extractVideoMetadata(filePath: string): Promise<VideoMetadata> {
+ const cached = videoMetadataCache.get(filePath);
+ if (cached) {
+ return cached;
+ }
+
+ const probePromise = new Promise<VideoMetadata>((resolve, reject) => {
+ const args = ["-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", filePath];
+
+ const ffprobe = spawn("ffprobe", args);
+ let stdout = "";
+ let stderr = "";
+
+ ffprobe.stdout.on("data", (data) => {
+ stdout += data.toString();
+ });
+ ffprobe.stderr.on("data", (data) => {
+ stderr += data.toString();
+ });
+
+ ffprobe.on("close", (code) => {
+ if (code !== 0) {
+ reject(new Error(`[FFmpeg] ffprobe exited with code ${code}: ${stderr}`));
+ return;
+ }
+
+ try {
+ const output: FFProbeOutput = JSON.parse(stdout);
+ const videoStream = output.streams.find((s) => s.codec_type === "video");
+ if (!videoStream) {
+ reject(new Error("[FFmpeg] No video stream found"));
+ return;
+ }
+
+ const hasAudio = output.streams.some((s) => s.codec_type === "audio");
+ const fps = parseFrameRate(videoStream.avg_frame_rate) || parseFrameRate(videoStream.r_frame_rate);
+ const durationSeconds = output.format.duration ? parseFloat(output.format.duration) : 0;
+
+ const metadata: VideoMetadata = {
+ durationSeconds,
+ width: videoStream.width || 0,
+ height: videoStream.height || 0,
+ fps,
+ videoCodec: videoStream.codec_name || "unknown",
+ hasAudio,
+ };
+ resolve(metadata);
+ } catch (parseError: unknown) {
+ reject(new Error(`[FFmpeg] Failed to parse ffprobe output: ${parseError instanceof Error ? parseError.message : parseError}`));
+ }
+ });
+
+ ffprobe.on("error", (err) => {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
+ reject(new Error("[FFmpeg] ffprobe not found. Please install FFmpeg."));
+ } else {
+ reject(err);
+ }
+ });
+ });
+ videoMetadataCache.set(filePath, probePromise);
+ probePromise.catch(() => {
+ if (videoMetadataCache.get(filePath) === probePromise) {
+ videoMetadataCache.delete(filePath);
+ }
+ });
+ return probePromise;
+}
+
+export async function extractAudioMetadata(filePath: string): Promise<AudioMetadata> {
+ const cached = audioMetadataCache.get(filePath);
+ if (cached) {
+ return cached;
+ }
+
+ const probePromise = new Promise<AudioMetadata>((resolve, reject) => {
+ const args = ["-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", filePath];
+
+ const ffprobe = spawn("ffprobe", args);
+ let stdout = "";
+ let stderr = "";
+
+ ffprobe.stdout.on("data", (data) => {
+ stdout += data.toString();
+ });
+ ffprobe.stderr.on("data", (data) => {
+ stderr += data.toString();
+ });
+
+ ffprobe.on("close", (code) => {
+ if (code !== 0) {
+ reject(new Error(`[FFmpeg] ffprobe exited with code ${code}: ${stderr}`));
+ return;
+ }
+
+ try {
+ const output: FFProbeOutput = JSON.parse(stdout);
+ const audioStream = output.streams.find((s) => s.codec_type === "audio");
+ if (!audioStream) {
+ reject(new Error("[FFmpeg] No audio stream found"));
+ return;
+ }
+
+ const durationSeconds = output.format.duration ? parseFloat(output.format.duration) : 0;
+
+ const metadata: AudioMetadata = {
+ durationSeconds,
+ sampleRate: audioStream.sample_rate ? parseInt(audioStream.sample_rate) : 44100,
+ channels: audioStream.channels || 2,
+ audioCodec: audioStream.codec_name || "unknown",
+ bitrate: output.format.bit_rate ? parseInt(output.format.bit_rate) : undefined,
+ };
+ resolve(metadata);
+ } catch (parseError: unknown) {
+ reject(
+ new Error(
+ `[FFmpeg] Failed to parse ffprobe output: ${parseError instanceof Error ? parseError.message : parseError}`,
+ ),
+ );
+ }
+ });
+
+ ffprobe.on("error", (err) => {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
+ reject(new Error("[FFmpeg] ffprobe not found. Please install FFmpeg."));
+ } else {
+ reject(err);
+ }
+ });
+ });
+ audioMetadataCache.set(filePath, probePromise);
+ probePromise.catch(() => {
+ if (audioMetadataCache.get(filePath) === probePromise) {
+ audioMetadataCache.delete(filePath);
+ }
+ });
+ return probePromise;
+}
diff --git a/packages/engine/src/utils/gpuEncoder.ts b/packages/engine/src/utils/gpuEncoder.ts
new file mode 100644
index 0000000000..709f65b8d3
--- /dev/null
+++ b/packages/engine/src/utils/gpuEncoder.ts
@@ -0,0 +1,58 @@
+/**
+ * GPU Encoder Detection
+ *
+ * Shared GPU encoder detection and naming utilities used by both
+ * chunkEncoder and streamingEncoder services.
+ */
+
+import { spawn } from "child_process";
+
+export type GpuEncoder = "nvenc" | "videotoolbox" | "vaapi" | "qsv" | null;
+
+export async function detectGpuEncoder(): Promise<GpuEncoder> {
+ return new Promise((resolve) => {
+ const ffmpeg = spawn("ffmpeg", ["-encoders"], {
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ let stdout = "";
+
+ ffmpeg.stdout.on("data", (data) => {
+ stdout += data.toString();
+ });
+
+ ffmpeg.on("close", () => {
+ if (stdout.includes("h264_nvenc")) resolve("nvenc");
+ else if (stdout.includes("h264_videotoolbox")) resolve("videotoolbox");
+ else if (stdout.includes("h264_vaapi")) resolve("vaapi");
+ else if (stdout.includes("h264_qsv")) resolve("qsv");
+ else resolve(null);
+ });
+
+ ffmpeg.on("error", () => resolve(null));
+ });
+}
+
+let cachedGpuEncoder: GpuEncoder | undefined = undefined;
+
+export async function getCachedGpuEncoder(): Promise<GpuEncoder> {
+ if (cachedGpuEncoder === undefined) {
+ cachedGpuEncoder = await detectGpuEncoder();
+ }
+ return cachedGpuEncoder;
+}
+
+export function getGpuEncoderName(encoder: GpuEncoder, codec: "h264" | "h265"): string {
+ if (!encoder) return codec === "h264" ? "libx264" : "libx265";
+ switch (encoder) {
+ case "nvenc":
+ return codec === "h264" ? "h264_nvenc" : "hevc_nvenc";
+ case "videotoolbox":
+ return codec === "h264" ? "h264_videotoolbox" : "hevc_videotoolbox";
+ case "vaapi":
+ return codec === "h264" ? "h264_vaapi" : "hevc_vaapi";
+ case "qsv":
+ return codec === "h264" ? "h264_qsv" : "hevc_qsv";
+ default:
+ return codec === "h264" ? "libx264" : "libx265";
+ }
+}
diff --git a/packages/engine/src/utils/parityContract.ts b/packages/engine/src/utils/parityContract.ts
new file mode 100644
index 0000000000..0cf159f08f
--- /dev/null
+++ b/packages/engine/src/utils/parityContract.ts
@@ -0,0 +1,35 @@
+export const MEDIA_VISUAL_STYLE_PROPERTIES = [
+ "width",
+ "height",
+ "top",
+ "left",
+ "right",
+ "bottom",
+ "inset",
+ "object-fit",
+ "object-position",
+ "z-index",
+ "opacity",
+ "visibility",
+ "filter",
+ "mix-blend-mode",
+ "backdrop-filter",
+ "border-radius",
+ "overflow",
+ "clip-path",
+ "mask",
+ "mask-image",
+ "mask-size",
+ "mask-position",
+ "mask-repeat",
+ "transform",
+ "transform-origin",
+ "box-sizing",
+] as const;
+
+export function quantizeTimeToFrame(timeSeconds: number, fps: number): number {
+ const safeFps = Number.isFinite(fps) && fps > 0 ? fps : 30;
+ const safeTime = Number.isFinite(timeSeconds) && timeSeconds > 0 ? timeSeconds : 0;
+ const frameIndex = Math.floor(safeTime * safeFps + 1e-9);
+ return frameIndex / safeFps;
+}
diff --git a/packages/engine/src/utils/runFfmpeg.ts b/packages/engine/src/utils/runFfmpeg.ts
new file mode 100644
index 0000000000..82610b591f
--- /dev/null
+++ b/packages/engine/src/utils/runFfmpeg.ts
@@ -0,0 +1,81 @@
+/**
+ * Shared FFmpeg process runner.
+ *
+ * Extracts the repeated spawn-stderr-timeout-abort-close-error pattern
+ * that appears across audioMixer and chunkEncoder into a single helper.
+ */
+
+import { spawn } from "child_process";
+
+export interface RunFfmpegOptions {
+ signal?: AbortSignal;
+ timeout?: number;
+ onStderr?: (line: string) => void;
+}
+
+export interface RunFfmpegResult {
+ success: boolean;
+ exitCode: number | null;
+ stderr: string;
+ durationMs: number;
+}
+
+const DEFAULT_TIMEOUT = 300_000;
+
+export async function runFfmpeg(args: string[], opts?: RunFfmpegOptions): Promise<RunFfmpegResult> {
+ const startMs = Date.now();
+ const signal = opts?.signal;
+ const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;
+ const onStderr = opts?.onStderr;
+
+ return new Promise<RunFfmpegResult>((resolve) => {
+ const ffmpeg = spawn("ffmpeg", args);
+ let stderr = "";
+
+ const onAbort = () => {
+ ffmpeg.kill("SIGTERM");
+ };
+
+ if (signal) {
+ if (signal.aborted) {
+ ffmpeg.kill("SIGTERM");
+ } else {
+ signal.addEventListener("abort", onAbort, { once: true });
+ }
+ }
+
+ const timer = setTimeout(() => {
+ ffmpeg.kill("SIGTERM");
+ }, timeout);
+
+ ffmpeg.stderr.on("data", (data: Buffer) => {
+ const chunk = data.toString();
+ stderr += chunk;
+ if (onStderr) {
+ onStderr(chunk);
+ }
+ });
+
+ ffmpeg.on("close", (code) => {
+ clearTimeout(timer);
+ if (signal) signal.removeEventListener("abort", onAbort);
+ resolve({
+ success: !signal?.aborted && code === 0,
+ exitCode: code,
+ stderr,
+ durationMs: Date.now() - startMs,
+ });
+ });
+
+ ffmpeg.on("error", (err) => {
+ clearTimeout(timer);
+ if (signal) signal.removeEventListener("abort", onAbort);
+ resolve({
+ success: false,
+ exitCode: null,
+ stderr: err.message,
+ durationMs: Date.now() - startMs,
+ });
+ });
+ });
+}
diff --git a/packages/engine/src/utils/urlDownloader.ts b/packages/engine/src/utils/urlDownloader.ts
new file mode 100644
index 0000000000..d02993ebb3
--- /dev/null
+++ b/packages/engine/src/utils/urlDownloader.ts
@@ -0,0 +1,78 @@
+import { createWriteStream, existsSync, mkdirSync } from "fs";
+import { createHash } from "crypto";
+import { join, extname } from "path";
+import { Readable } from "stream";
+import { finished } from "stream/promises";
+
+const downloadPathCache = new Map<string, string>();
+const inFlightDownloads = new Map<string, Promise<string>>();
+
+function getFilenameFromUrl(url: string): string {
+ const hash = createHash("md5").update(url).digest("hex").slice(0, 12);
+ const urlObj = new URL(url);
+ const ext = extname(urlObj.pathname) || ".mp4";
+ return `download_${hash}${ext}`;
+}
+
+export async function downloadToTemp(url: string, destDir: string, timeoutMs: number = 300000): Promise<string> {
+ const cachedPath = downloadPathCache.get(url);
+ if (cachedPath && existsSync(cachedPath)) {
+ return cachedPath;
+ }
+ const inFlight = inFlightDownloads.get(url);
+ if (inFlight) {
+ return inFlight;
+ }
+
+ if (!existsSync(destDir)) {
+ mkdirSync(destDir, { recursive: true });
+ }
+
+ const filename = getFilenameFromUrl(url);
+ const localPath = join(destDir, filename);
+
+ if (existsSync(localPath)) {
+ downloadPathCache.set(url, localPath);
+ return localPath;
+ }
+
+ const downloadPromise = (async () => {
+ try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
+
+ const response = await fetch(url, { signal: controller.signal });
+ clearTimeout(timeoutId);
+
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ }
+
+ if (!response.body) {
+ throw new Error("Response body is empty");
+ }
+
+ const fileStream = createWriteStream(localPath);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const readableStream = Readable.fromWeb(response.body as any);
+ await finished(readableStream.pipe(fileStream));
+
+ downloadPathCache.set(url, localPath);
+ return localPath;
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ if (message.includes("aborted")) {
+ throw new Error(`[URLDownloader] Download timeout after ${timeoutMs / 1000}s: ${url}`);
+ }
+ throw new Error(`[URLDownloader] Download failed: ${message}`);
+ } finally {
+ inFlightDownloads.delete(url);
+ }
+ })();
+ inFlightDownloads.set(url, downloadPromise);
+ return downloadPromise;
+}
+
+export function isHttpUrl(path: string): boolean {
+ return path.startsWith("http://") || path.startsWith("https://");
+}
diff --git a/packages/engine/tsconfig.json b/packages/engine/tsconfig.json
new file mode 100644
index 0000000000..d672cb2b7c
--- /dev/null
+++ b/packages/engine/tsconfig.json
@@ -0,0 +1,18 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "esModuleInterop": true,
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "skipLibCheck": true,
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/packages/engine/vitest.config.ts b/packages/engine/vitest.config.ts
new file mode 100644
index 0000000000..ae847ff6d9
--- /dev/null
+++ b/packages/engine/vitest.config.ts
@@ -0,0 +1,7 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: ["src/**/*.test.ts"],
+ },
+});
diff --git a/packages/producer/build.mjs b/packages/producer/build.mjs
new file mode 100644
index 0000000000..acbbd3506c
--- /dev/null
+++ b/packages/producer/build.mjs
@@ -0,0 +1,60 @@
+#!/usr/bin/env node
+/**
+ * Build script for @hyperframes/producer (public OSS package)
+ *
+ * Bundles src/server.ts → dist/public-server.js (standalone server).
+ */
+
+import { build } from "esbuild";
+import { mkdirSync, rmSync } from "fs";
+import { resolve, dirname } from "path";
+import { fileURLToPath } from "url";
+
+rmSync("dist", { recursive: true, force: true });
+mkdirSync("dist", { recursive: true });
+
+const scriptDir = dirname(fileURLToPath(import.meta.url));
+
+const workspaceAliasPlugin = {
+ name: "workspace-alias",
+ setup(build) {
+ build.onResolve({ filter: /^@hyperframes\/engine$/ }, () => ({
+ path: resolve(scriptDir, "../engine/src/index.ts"),
+ }));
+ build.onResolve({ filter: /^@hyperframes\/core$/ }, () => ({
+ path: resolve(scriptDir, "../core/src/index.ts"),
+ }));
+ build.onResolve({ filter: /^@hyperframes\/core\/lint$/ }, () => ({
+ path: resolve(scriptDir, "../core/src/lint/index.ts"),
+ }));
+ },
+};
+
+await Promise.all([
+ build({
+ bundle: true,
+ platform: "node",
+ target: "node22",
+ format: "esm",
+ external: ["puppeteer", "esbuild"],
+ plugins: [workspaceAliasPlugin],
+ minify: false,
+ sourcemap: true,
+ entryPoints: ["src/index.ts"],
+ outfile: "dist/index.js",
+ }),
+ build({
+ bundle: true,
+ platform: "node",
+ target: "node22",
+ format: "esm",
+ external: ["puppeteer", "esbuild"],
+ plugins: [workspaceAliasPlugin],
+ minify: false,
+ sourcemap: true,
+ entryPoints: ["src/server.ts"],
+ outfile: "dist/public-server.js",
+ }),
+]);
+
+console.log("[Build] Complete: dist/index.js, dist/public-server.js");
diff --git a/packages/producer/package.json b/packages/producer/package.json
new file mode 100644
index 0000000000..aae1f72b60
--- /dev/null
+++ b/packages/producer/package.json
@@ -0,0 +1,67 @@
+{
+ "name": "@hyperframes/producer",
+ "version": "0.1.0",
+ "description": "HTML-to-video rendering engine using Chrome's BeginFrame API",
+ "type": "module",
+ "main": "dist/index.js",
+ "types": "dist/index.d.ts",
+ "exports": {
+ ".": {
+ "import": "./dist/index.js",
+ "types": "./dist/index.d.ts"
+ },
+ "./server": {
+ "import": "./dist/public-server.js"
+ }
+ },
+ "files": [
+ "dist/"
+ ],
+ "publishConfig": {
+ "access": "public",
+ "registry": "https://registry.npmjs.org/"
+ },
+ "engines": {
+ "node": ">=22"
+ },
+ "scripts": {
+ "build": "pnpm -w build:hyperframes-runtime:modular && node build.mjs",
+ "typecheck": "tsc --noEmit",
+ "parity:check": "tsx src/parity-harness.ts",
+ "parity:fixtures": "tsx src/parity-fixtures.ts",
+ "parity:fixtures:ci": "tsx src/parity-fixtures.ts",
+ "parity:check:ci": "tsx src/parity-harness.ts --preview-url \"http://127.0.0.1:4173/minimal-wysiwyg.html\" --producer-url \"http://127.0.0.1:4173/minimal-wysiwyg.html?mode=producer\" --checkpoints \"0,0.5,1,1.5\" --allow-mismatch-ratio 0 --emulate-producer-swap true --artifacts-dir \".debug/parity-harness-ci\"",
+ "perf:gate": "tsx src/perf-gate.ts",
+ "check:runtime-conformance": "tsx src/runtime-conformance.ts",
+ "benchmark": "tsx src/benchmark.ts",
+ "test": "tsx src/regression-harness.ts",
+ "test:update": "tsx src/regression-harness.ts --update",
+ "prepublishOnly": "pnpm build"
+ },
+ "dependencies": {
+ "@hyperframes/core": "workspace:*",
+ "@hyperframes/engine": "workspace:*",
+ "@fontsource/archivo-black": "^5.2.8",
+ "@fontsource/eb-garamond": "^5.2.7",
+ "@fontsource/ibm-plex-mono": "^5.2.7",
+ "@fontsource/inter": "^5.2.8",
+ "@fontsource/jetbrains-mono": "^5.2.8",
+ "@fontsource/league-gothic": "^5.2.8",
+ "@fontsource/montserrat": "^5.2.8",
+ "@fontsource/nunito": "^5.2.7",
+ "@fontsource/oswald": "^5.2.8",
+ "@fontsource/outfit": "^5.2.8",
+ "@fontsource/space-mono": "^5.2.9",
+ "@hono/node-server": "^1.13.0",
+ "hono": "^4.6.0",
+ "linkedom": "^0.18.12",
+ "puppeteer": "^24.0.0",
+ "puppeteer-core": "^24.39.1"
+ },
+ "devDependencies": {
+ "@types/node": "^22.10.1",
+ "esbuild": "^0.27.2",
+ "tsx": "^4.7.0",
+ "typescript": "^5.7.2"
+ }
+}
diff --git a/packages/producer/src/benchmark.ts b/packages/producer/src/benchmark.ts
new file mode 100644
index 0000000000..d672f42aff
--- /dev/null
+++ b/packages/producer/src/benchmark.ts
@@ -0,0 +1,237 @@
+#!/usr/bin/env tsx
+/**
+ * Render Benchmark
+ *
+ * Runs each test fixture multiple times and records per-stage timing.
+ * Results are saved to producer/tests/perf/benchmark-results.json.
+ *
+ * Usage:
+ * pnpm benchmark # 3 runs per fixture (default)
+ * pnpm benchmark -- --runs 5 # 5 runs per fixture
+ * pnpm benchmark -- --only chat # single fixture
+ * pnpm benchmark -- --exclude-tags slow
+ */
+
+import { readdirSync, readFileSync, writeFileSync, existsSync, mkdirSync, cpSync, rmSync } from "node:fs";
+import { join, resolve, dirname } from "node:path";
+import { tmpdir } from "node:os";
+import { fileURLToPath } from "node:url";
+import { createRenderJob, executeRenderJob, type RenderPerfSummary } from "./services/renderOrchestrator.js";
+
+const scriptDir = dirname(fileURLToPath(import.meta.url));
+const testsDir = resolve(scriptDir, "../tests");
+const perfDir = resolve(testsDir, "perf");
+
+interface TestMeta {
+ name: string;
+ tags?: string[];
+ renderConfig: { fps: 24 | 30 | 60 };
+}
+
+interface BenchmarkRun {
+ run: number;
+ perfSummary: RenderPerfSummary;
+}
+
+interface FixtureResult {
+ fixture: string;
+ name: string;
+ runs: BenchmarkRun[];
+ averages: {
+ totalElapsedMs: number;
+ captureAvgMs: number | null;
+ stages: Record<string, number>;
+ };
+}
+
+interface BenchmarkResults {
+ timestamp: string;
+ platform: string;
+ nodeVersion: string;
+ runsPerFixture: number;
+ fixtures: FixtureResult[];
+}
+
+function parseArgs(): { runs: number; only: string | null; excludeTags: string[] } {
+ let runs = 3;
+ let only: string | null = null;
+ const excludeTags: string[] = [];
+
+ for (let i = 2; i < process.argv.length; i++) {
+ if (process.argv[i] === "--runs" && process.argv[i + 1]) {
+ i++;
+ runs = parseInt(process.argv[i] ?? "", 10);
+ } else if (process.argv[i] === "--only" && process.argv[i + 1]) {
+ i++;
+ only = process.argv[i] ?? null;
+ } else if (process.argv[i] === "--exclude-tags" && process.argv[i + 1]) {
+ i++;
+ excludeTags.push(...(process.argv[i] ?? "").split(","));
+ }
+ }
+
+ return { runs, only, excludeTags };
+}
+
+function discoverFixtures(only: string | null, excludeTags: string[]): Array<{ id: string; dir: string; meta: TestMeta }> {
+ const fixtures: Array<{ id: string; dir: string; meta: TestMeta }> = [];
+
+ for (const entry of readdirSync(testsDir)) {
+ if (entry === "perf" || entry === "parity") continue;
+ const dir = join(testsDir, entry);
+ const metaPath = join(dir, "meta.json");
+ const srcDir = join(dir, "src");
+ if (!existsSync(metaPath) || !existsSync(join(srcDir, "index.html"))) continue;
+
+ if (only && entry !== only) continue;
+
+ const meta: TestMeta = JSON.parse(readFileSync(metaPath, "utf-8"));
+ if (excludeTags.length > 0 && meta.tags?.some((t) => excludeTags.includes(t))) continue;
+
+ fixtures.push({ id: entry, dir, meta });
+ }
+
+ return fixtures;
+}
+
+function avg(nums: number[]): number {
+ if (nums.length === 0) return 0;
+ return Math.round(nums.reduce((a, b) => a + b, 0) / nums.length);
+}
+
+async function runBenchmark(): Promise<void> {
+ const { runs, only, excludeTags } = parseArgs();
+ const fixtures = discoverFixtures(only, excludeTags);
+
+ if (fixtures.length === 0) {
+ console.error("No fixtures found");
+ process.exit(1);
+ }
+
+ console.log(`\n🏁 Benchmark: ${fixtures.length} fixture(s) × ${runs} run(s)\n`);
+
+ const results: FixtureResult[] = [];
+
+ for (const fixture of fixtures) {
+ console.log(`\n━━━ ${fixture.meta.name} (${fixture.id}) ━━━`);
+ const fixtureRuns: BenchmarkRun[] = [];
+
+ for (let r = 0; r < runs; r++) {
+ console.log(` Run ${r + 1}/${runs}...`);
+
+ // Copy src to temp dir for isolation
+ const tmpRoot = join(tmpdir(), `benchmark-${fixture.id}-${Date.now()}`);
+ mkdirSync(tmpRoot, { recursive: true });
+ cpSync(join(fixture.dir, "src"), join(tmpRoot, "src"), { recursive: true });
+
+ const projectDir = join(tmpRoot, "src");
+ const outputPath = join(tmpRoot, "output.mp4");
+
+ const job = createRenderJob({
+ fps: fixture.meta.renderConfig.fps,
+ quality: "high",
+ debug: false,
+ });
+
+ try {
+ await executeRenderJob(job, projectDir, outputPath);
+ } catch (err) {
+ console.error(` ❌ Run ${r + 1} failed: ${err instanceof Error ? err.message : err}`);
+ continue;
+ } finally {
+ try { rmSync(tmpRoot, { recursive: true, force: true }); } catch {}
+ }
+
+ if (job.perfSummary) {
+ fixtureRuns.push({ run: r + 1, perfSummary: job.perfSummary });
+ const ps = job.perfSummary;
+ console.log(` ✓ ${ps.totalElapsedMs}ms total | capture avg ${ps.captureAvgMs ?? "?"}ms/frame | ${ps.totalFrames} frames`);
+ }
+ }
+
+ if (fixtureRuns.length === 0) {
+ console.log(` ⚠ No successful runs`);
+ continue;
+ }
+
+ // Compute averages
+ const allStageKeys = new Set<string>();
+ for (const run of fixtureRuns) {
+ for (const key of Object.keys(run.perfSummary.stages)) {
+ allStageKeys.add(key);
+ }
+ }
+
+ const avgStages: Record<string, number> = {};
+ for (const key of allStageKeys) {
+ avgStages[key] = avg(fixtureRuns.map((r) => r.perfSummary.stages[key] ?? 0));
+ }
+
+ const fixtureResult: FixtureResult = {
+ fixture: fixture.id,
+ name: fixture.meta.name,
+ runs: fixtureRuns,
+ averages: {
+ totalElapsedMs: avg(fixtureRuns.map((r) => r.perfSummary.totalElapsedMs)),
+ captureAvgMs: avg(fixtureRuns.filter((r) => r.perfSummary.captureAvgMs != null).map((r) => r.perfSummary.captureAvgMs!)) || null,
+ stages: avgStages,
+ },
+ };
+
+ results.push(fixtureResult);
+
+ console.log(`\n Average: ${fixtureResult.averages.totalElapsedMs}ms total`);
+ for (const [stage, ms] of Object.entries(fixtureResult.averages.stages)) {
+ const pct = Math.round((ms / fixtureResult.averages.totalElapsedMs) * 100);
+ console.log(` ${stage}: ${ms}ms (${pct}%)`);
+ }
+ }
+
+ // Save results
+ const benchmarkResults: BenchmarkResults = {
+ timestamp: new Date().toISOString(),
+ platform: `${process.platform} ${process.arch}`,
+ nodeVersion: process.version,
+ runsPerFixture: runs,
+ fixtures: results,
+ };
+
+ if (!existsSync(perfDir)) mkdirSync(perfDir, { recursive: true });
+ const outputPath = join(perfDir, "benchmark-results.json");
+ writeFileSync(outputPath, JSON.stringify(benchmarkResults, null, 2), "utf-8");
+
+ // Print summary table
+ console.log("\n\n📊 BENCHMARK SUMMARY");
+ console.log("═".repeat(80));
+ console.log(
+ "Fixture".padEnd(25) +
+ "Total".padStart(10) +
+ "Compile".padStart(10) +
+ "Extract".padStart(10) +
+ "Audio".padStart(10) +
+ "Capture".padStart(10) +
+ "Encode".padStart(10)
+ );
+ console.log("─".repeat(80));
+
+ for (const f of results) {
+ const s = f.averages.stages;
+ console.log(
+ f.fixture.padEnd(25) +
+ `${f.averages.totalElapsedMs}ms`.padStart(10) +
+ `${s.compileMs ?? "-"}ms`.padStart(10) +
+ `${s.videoExtractMs ?? "-"}ms`.padStart(10) +
+ `${s.audioProcessMs ?? "-"}ms`.padStart(10) +
+ `${s.captureMs ?? "-"}ms`.padStart(10) +
+ `${s.encodeMs ?? "-"}ms`.padStart(10)
+ );
+ }
+
+ console.log("═".repeat(80));
+ console.log(`\nResults saved to: ${outputPath}`);
+}
+
+runBenchmark().catch((err) => {
+ console.error("Benchmark failed:", err);
+ process.exit(1);
+});
diff --git a/packages/producer/src/config.ts b/packages/producer/src/config.ts
new file mode 100644
index 0000000000..4d58c6e320
--- /dev/null
+++ b/packages/producer/src/config.ts
@@ -0,0 +1,10 @@
+/**
+ * Re-exported from @hyperframes/engine with ProducerConfig alias.
+ * @see engine/src/config.ts for implementation.
+ */
+export {
+ type EngineConfig,
+ type EngineConfig as ProducerConfig,
+ DEFAULT_CONFIG,
+ resolveConfig,
+} from "@hyperframes/engine";
diff --git a/packages/producer/src/index.ts b/packages/producer/src/index.ts
new file mode 100644
index 0000000000..f27825ab52
--- /dev/null
+++ b/packages/producer/src/index.ts
@@ -0,0 +1,84 @@
+/**
+ * @hyperframes/producer
+ *
+ * Generic HTML-to-video rendering engine using Chrome's BeginFrame API.
+ * Framework-agnostic: works with GSAP, Lottie, Three.js, CSS animations,
+ * or any web content via configurable page contracts and hooks.
+ */
+
+// ── Main rendering pipeline ─────────────────────────────────────────────────
+export {
+ createRenderJob,
+ executeRenderJob,
+ RenderCancelledError,
+ type RenderConfig,
+ type RenderJob,
+ type RenderStatus,
+ type RenderPerfSummary,
+ type ProgressCallback,
+} from "./services/renderOrchestrator.js";
+
+// ── Frame capture (lower-level) ─────────────────────────────────────────────
+export {
+ createCaptureSession,
+ initializeSession,
+ closeCaptureSession,
+ captureFrame,
+ captureFrameToBuffer,
+ getCompositionDuration,
+ getCapturePerfSummary,
+ prepareCaptureSessionForReuse,
+ type CaptureOptions,
+ type CaptureSession,
+ type CaptureResult,
+ type CapturePerfSummary,
+ type BeforeCaptureHook,
+} from "./services/frameCapture.js";
+
+// ── File server ─────────────────────────────────────────────────────────────
+export {
+ createFileServer,
+ type FileServerOptions,
+ type FileServerHandle,
+} from "./services/fileServer.js";
+
+// ── Video frame injection (Hyperframes-specific hook) ───────────────────────
+export { createVideoFrameInjector } from "./services/videoFrameInjector.js";
+
+// ── Configuration ───────────────────────────────────────────────────────────
+export {
+ resolveConfig,
+ DEFAULT_CONFIG,
+ type ProducerConfig,
+} from "./config.js";
+
+// ── Logger ──────────────────────────────────────────────────────────────────
+export {
+ type ProducerLogger,
+ type LogLevel,
+ createConsoleLogger,
+ defaultLogger,
+} from "./logger.js";
+
+// ── Server ──────────────────────────────────────────────────────────────────
+export {
+ createRenderHandlers,
+ createProducerApp,
+ startServer,
+ type HandlerOptions,
+ type ServerOptions,
+ type RenderHandlers,
+} from "./server.js";
+
+// ── Utilities ───────────────────────────────────────────────────────────────
+export { quantizeTimeToFrame } from "./utils/parityContract.js";
+export {
+ resolveRenderPaths,
+ type RenderPaths,
+} from "./utils/paths.js";
+
+export {
+ prepareHyperframeLintBody,
+ runHyperframeLint,
+ type PreparedHyperframeLintInput,
+} from "./services/hyperframeLint.js";
diff --git a/packages/producer/src/logger.ts b/packages/producer/src/logger.ts
new file mode 100644
index 0000000000..0fd56fd62d
--- /dev/null
+++ b/packages/producer/src/logger.ts
@@ -0,0 +1,67 @@
+/**
+ * Pluggable Producer Logger
+ *
+ * Lightweight pluggable logger with zero dependencies.
+ * Default implementation writes to console with level filtering.
+ *
+ * Users can provide their own logger (e.g. Winston, Pino) by
+ * implementing the ProducerLogger interface.
+ */
+
+export type LogLevel = "error" | "warn" | "info" | "debug";
+
+export interface ProducerLogger {
+ error(message: string, meta?: Record<string, unknown>): void;
+ warn(message: string, meta?: Record<string, unknown>): void;
+ info(message: string, meta?: Record<string, unknown>): void;
+ debug(message: string, meta?: Record<string, unknown>): void;
+}
+
+const LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {
+ error: 0,
+ warn: 1,
+ info: 2,
+ debug: 3,
+};
+
+/**
+ * Create a console-based logger with level filtering.
+ *
+ * Messages at or below the configured level are printed;
+ * everything else is silently dropped.
+ */
+export function createConsoleLogger(level: LogLevel = "info"): ProducerLogger {
+ const threshold = LOG_LEVEL_PRIORITY[level];
+
+ const shouldLog = (msgLevel: LogLevel): boolean =>
+ LOG_LEVEL_PRIORITY[msgLevel] <= threshold;
+
+ const formatMeta = (meta?: Record<string, unknown>): string =>
+ meta ? ` ${JSON.stringify(meta)}` : "";
+
+ return {
+ error(message, meta) {
+ if (shouldLog("error")) {
+ console.error(`[ERROR] ${message}${formatMeta(meta)}`);
+ }
+ },
+ warn(message, meta) {
+ if (shouldLog("warn")) {
+ console.warn(`[WARN] ${message}${formatMeta(meta)}`);
+ }
+ },
+ info(message, meta) {
+ if (shouldLog("info")) {
+ console.log(`[INFO] ${message}${formatMeta(meta)}`);
+ }
+ },
+ debug(message, meta) {
+ if (shouldLog("debug")) {
+ console.log(`[DEBUG] ${message}${formatMeta(meta)}`);
+ }
+ },
+ };
+}
+
+/** Default logger singleton (level: "info"). */
+export const defaultLogger: ProducerLogger = createConsoleLogger("info");
diff --git a/packages/producer/src/parity-harness.ts b/packages/producer/src/parity-harness.ts
new file mode 100644
index 0000000000..f7053eb447
--- /dev/null
+++ b/packages/producer/src/parity-harness.ts
@@ -0,0 +1,390 @@
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, writeFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import process from "node:process";
+import { spawnSync } from "node:child_process";
+import puppeteer, { type Page } from "puppeteer-core";
+import { MEDIA_VISUAL_STYLE_PROPERTIES, quantizeTimeToFrame } from "./utils/parityContract.js";
+
+type ParityHarnessOptions = {
+ previewUrl: string;
+ producerUrl: string;
+ width: number;
+ height: number;
+ fps: number;
+ checkpoints: number[];
+ allowMismatchRatio: number;
+ artifactsDir: string;
+ emulateProducerSwap: boolean;
+};
+
+function parseNumberArg(value: string | undefined, fallback: number): number {
+ if (!value) return fallback;
+ const parsed = Number(value);
+ if (!Number.isFinite(parsed)) return fallback;
+ return parsed;
+}
+
+function parseArgs(argv: string[]): ParityHarnessOptions {
+ const args = new Map<string, string>();
+ for (let i = 2; i < argv.length; i += 1) {
+ const token = argv[i];
+ if (!token || !token.startsWith("--")) continue;
+ const key = token.slice(2);
+ const next = argv[i + 1];
+ if (!next || next.startsWith("--")) {
+ args.set(key, "true");
+ continue;
+ }
+ args.set(key, next);
+ i += 1;
+ }
+
+ const previewUrl = args.get("preview-url") || "";
+ const producerUrl = args.get("producer-url") || "";
+ if (!previewUrl || !producerUrl) {
+ throw new Error(
+ 'Missing required args. Usage: --preview-url "<url>" --producer-url "<url>" [--checkpoints "0,1,2"] [--fps 30] [--width 1920] [--height 1080] [--allow-mismatch-ratio 0]'
+ );
+ }
+
+ const checkpointsRaw = args.get("checkpoints") || "0,1,2,3,5";
+ const checkpoints = checkpointsRaw
+ .split(",")
+ .map((value) => Number(value.trim()))
+ .filter((value) => Number.isFinite(value) && value >= 0);
+ if (checkpoints.length === 0) {
+ throw new Error("No valid checkpoints provided.");
+ }
+
+ return {
+ previewUrl,
+ producerUrl,
+ width: parseNumberArg(args.get("width"), 1920),
+ height: parseNumberArg(args.get("height"), 1080),
+ fps: parseNumberArg(args.get("fps"), 30),
+ checkpoints,
+ allowMismatchRatio: Math.max(
+ 0,
+ Math.min(1, parseNumberArg(args.get("allow-mismatch-ratio"), 0))
+ ),
+ artifactsDir: resolve(args.get("artifacts-dir") || ".debug/parity-harness"),
+ emulateProducerSwap:
+ (args.get("emulate-producer-swap") || "false").toLowerCase() === "true",
+ };
+}
+
+async function waitForParityReady(page: Page): Promise<void> {
+ await page.waitForFunction(
+ () => {
+ const win = window as unknown as { __playerReady?: boolean; __renderReady?: boolean };
+ return Boolean(win.__playerReady && win.__renderReady);
+ },
+ { timeout: 30_000 }
+ );
+ await page.evaluate(() => document.fonts.ready);
+}
+
+function ensureDir(path: string): void {
+ if (!existsSync(path)) {
+ mkdirSync(path, { recursive: true });
+ }
+}
+
+function writeBinary(path: string, data: Buffer): void {
+ ensureDir(dirname(path));
+ writeFileSync(path, data);
+}
+
+function writeJson(path: string, data: unknown): void {
+ ensureDir(dirname(path));
+ writeFileSync(path, JSON.stringify(data, null, 2), "utf-8");
+}
+
+function writeImageDiff(basePath: string, comparePath: string, outputPath: string): void {
+ const ffmpeg = spawnSync(
+ "ffmpeg",
+ [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-y",
+ "-i",
+ basePath,
+ "-i",
+ comparePath,
+ "-filter_complex",
+ "[0:v][1:v]blend=all_mode=difference",
+ outputPath,
+ ],
+ { stdio: "pipe" },
+ );
+ if (ffmpeg.status !== 0) {
+ const stderr = (ffmpeg.stderr || Buffer.from("")).toString("utf-8");
+ throw new Error(`ffmpeg diff failed: ${stderr}`);
+ }
+}
+
+async function captureStyleSnapshot(page: Page): Promise<Record<string, unknown>> {
+ return page.evaluate((properties: string[]) => {
+ const targets = Array.from(
+ document.querySelectorAll("video[data-start], img.__render_frame__, img.__preview_render_frame__, img.__parity_render_frame__"),
+ ) as HTMLElement[];
+ return {
+ location: window.location.href,
+ viewport: {
+ width: window.innerWidth,
+ height: window.innerHeight,
+ dpr: window.devicePixelRatio,
+ },
+ media: targets.map((el) => {
+ const style = window.getComputedStyle(el);
+ const values: Record<string, string> = {};
+ for (const property of properties) {
+ values[property] = style.getPropertyValue(property);
+ }
+ return {
+ id: el.id || null,
+ tagName: el.tagName.toLowerCase(),
+ className: el.className || null,
+ values,
+ };
+ }),
+ };
+ }, [...MEDIA_VISUAL_STYLE_PROPERTIES]);
+}
+
+async function emulateProducerVideoSwap(page: Page): Promise<void> {
+ await page.evaluate((properties: string[]) => {
+ const videos = Array.from(document.querySelectorAll("video[data-start]")) as HTMLVideoElement[];
+ for (const video of videos) {
+ let img = video.nextElementSibling as HTMLImageElement | null;
+ if (!img || !img.classList.contains("__parity_render_frame__")) {
+ img = document.createElement("img");
+ img.className = "__parity_render_frame__";
+ video.parentNode?.insertBefore(img, video.nextSibling);
+ }
+
+ const style = window.getComputedStyle(video);
+ const sourceIsStatic = !style.position || style.position === "static";
+ if (!sourceIsStatic) {
+ img.style.position = style.position;
+ img.style.top = style.top;
+ img.style.left = style.left;
+ img.style.right = style.right;
+ img.style.bottom = style.bottom;
+ } else {
+ img.style.position = "absolute";
+ img.style.top = "0px";
+ img.style.left = "0px";
+ img.style.right = "0px";
+ img.style.bottom = "0px";
+ }
+ for (const property of properties) {
+ if (
+ sourceIsStatic &&
+ (property === "top" ||
+ property === "left" ||
+ property === "right" ||
+ property === "bottom" ||
+ property === "inset")
+ ) {
+ continue;
+ }
+ const value = style.getPropertyValue(property);
+ if (value) {
+ img.style.setProperty(property, value);
+ }
+ }
+ img.style.pointerEvents = "none";
+ img.style.visibility = "visible";
+
+ try {
+ const width = Math.max(2, video.videoWidth || video.clientWidth || 2);
+ const height = Math.max(2, video.videoHeight || video.clientHeight || 2);
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext("2d", { alpha: false });
+ if (!ctx) {
+ continue;
+ }
+ ctx.drawImage(video, 0, 0, width, height);
+ img.src = canvas.toDataURL("image/png");
+ video.style.setProperty("visibility", "hidden", "important");
+ video.style.setProperty("opacity", "0", "important");
+ } catch {
+ video.style.removeProperty("visibility");
+ video.style.removeProperty("opacity");
+ }
+ }
+ }, [...MEDIA_VISUAL_STYLE_PROPERTIES]);
+}
+
+async function captureCheckpoint(
+ page: Page,
+ checkpointSec: number,
+ fps: number,
+ emulateProducerSwap: boolean,
+): Promise<Buffer> {
+ const quantized = quantizeTimeToFrame(checkpointSec, fps);
+ await page.evaluate(
+ ({ time, targetFps }) => {
+ const win = window as unknown as {
+ __player?: { renderSeek?(t: number): void; seek?(t: number): void };
+ gsap?: { ticker?: { tick(): void } };
+ };
+ const player = win.__player;
+ if (!player) return;
+ const safe = Math.max(0, Number(time) || 0);
+ const frame = Math.floor(safe * targetFps + 1e-9);
+ const quantized = frame / targetFps;
+ if (typeof player.renderSeek === "function") {
+ player.renderSeek(quantized);
+ } else if (typeof player.seek === "function") {
+ player.seek(quantized);
+ }
+ if (win.gsap?.ticker?.tick) {
+ win.gsap.ticker.tick();
+ }
+ },
+ { time: quantized, targetFps: fps },
+ );
+ if (emulateProducerSwap) {
+ await emulateProducerVideoSwap(page);
+ }
+ await page.evaluate(
+ () =>
+ new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))
+ );
+ return (await page.screenshot({ type: "png" })) as Buffer;
+}
+
+function sha256(data: Buffer): string {
+ return createHash("sha256").update(data).digest("hex");
+}
+
+async function run(): Promise<void> {
+ const options = parseArgs(process.argv);
+ console.log(`[ParityHarness] options=${JSON.stringify(options)}`);
+ ensureDir(options.artifactsDir);
+
+ const browser = await puppeteer.launch({
+ headless: true,
+ defaultViewport: {
+ width: options.width,
+ height: options.height,
+ deviceScaleFactor: 1,
+ },
+ args: [
+ "--no-sandbox",
+ "--disable-setuid-sandbox",
+ "--disable-dev-shm-usage",
+ "--disable-accelerated-2d-canvas",
+ "--enable-webgl",
+ "--ignore-gpu-blocklist",
+ "--use-gl=angle",
+ "--use-angle=swiftshader",
+ "--font-render-hinting=none",
+ "--force-color-profile=srgb",
+ `--window-size=${options.width},${options.height}`,
+ ],
+ });
+
+ try {
+ const previewPage = await browser.newPage();
+ const producerPage = await browser.newPage();
+
+ await Promise.all([
+ previewPage.goto(options.previewUrl, { waitUntil: ["load", "networkidle2"], timeout: 60_000 }),
+ producerPage.goto(options.producerUrl, { waitUntil: ["load", "networkidle2"], timeout: 60_000 }),
+ ]);
+ await Promise.all([waitForParityReady(previewPage), waitForParityReady(producerPage)]);
+
+ let mismatches = 0;
+ const results: Array<{
+ checkpointSec: number;
+ previewHash: string;
+ producerHash: string;
+ match: boolean;
+ previewImagePath: string;
+ producerImagePath: string;
+ diffImagePath: string | null;
+ previewStylesPath: string;
+ producerStylesPath: string;
+ }> = [];
+
+ for (const checkpointSec of options.checkpoints) {
+ const checkpointKey = checkpointSec.toFixed(3).replace(/\./g, "_");
+ const artifactDir = join(options.artifactsDir, `checkpoint_${checkpointKey}s`);
+ ensureDir(artifactDir);
+ const [previewBuffer, producerBuffer] = await Promise.all([
+ captureCheckpoint(previewPage, checkpointSec, options.fps, false),
+ captureCheckpoint(
+ producerPage,
+ checkpointSec,
+ options.fps,
+ options.emulateProducerSwap,
+ ),
+ ]);
+ const previewHash = sha256(previewBuffer);
+ const producerHash = sha256(producerBuffer);
+ const match = previewHash === producerHash;
+ if (!match) mismatches += 1;
+ const previewImagePath = join(artifactDir, "preview.png");
+ const producerImagePath = join(artifactDir, "producer.png");
+ const diffImagePath = match ? null : join(artifactDir, "diff.png");
+ writeBinary(previewImagePath, previewBuffer);
+ writeBinary(producerImagePath, producerBuffer);
+ if (diffImagePath) {
+ writeImageDiff(previewImagePath, producerImagePath, diffImagePath);
+ }
+ const [previewStyles, producerStyles] = await Promise.all([
+ captureStyleSnapshot(previewPage),
+ captureStyleSnapshot(producerPage),
+ ]);
+ const previewStylesPath = join(artifactDir, "preview-styles.json");
+ const producerStylesPath = join(artifactDir, "producer-styles.json");
+ writeJson(previewStylesPath, previewStyles);
+ writeJson(producerStylesPath, producerStyles);
+ const row = {
+ checkpointSec,
+ previewHash,
+ producerHash,
+ match,
+ previewImagePath,
+ producerImagePath,
+ diffImagePath,
+ previewStylesPath,
+ producerStylesPath,
+ };
+ results.push(row);
+ console.log(`[ParityHarness] checkpoint=${JSON.stringify(row)}`);
+ }
+
+ const total = results.length;
+ const mismatchRatio = total > 0 ? mismatches / total : 0;
+ const summary = {
+ totalCheckpoints: total,
+ mismatches,
+ mismatchRatio,
+ allowMismatchRatio: options.allowMismatchRatio,
+ pass: mismatchRatio <= options.allowMismatchRatio,
+ artifactsDir: options.artifactsDir,
+ };
+ writeJson(join(options.artifactsDir, "summary.json"), { summary, results });
+ console.log(`[ParityHarness] summary=${JSON.stringify(summary)}`);
+
+ if (!summary.pass) {
+ process.exitCode = 1;
+ }
+ } finally {
+ await browser.close();
+ }
+}
+
+void run().catch((error) => {
+ const message = error instanceof Error ? error.message : String(error);
+ console.error(`[ParityHarness] fatal=${JSON.stringify({ message })}`);
+ process.exitCode = 1;
+});
diff --git a/packages/producer/src/perf-gate.ts b/packages/producer/src/perf-gate.ts
new file mode 100644
index 0000000000..f5dd13dcf9
--- /dev/null
+++ b/packages/producer/src/perf-gate.ts
@@ -0,0 +1,27 @@
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+
+type PerfBaseline = {
+ parityFixtureMaxMs: number;
+ allowedRegressionRatio: number;
+};
+
+function main(): void {
+ const baselinePath = resolve(
+ process.env.PRODUCER_PERF_BASELINE_PATH || "producer/tests/perf/baseline.json",
+ );
+ const measuredMs = Number(process.env.PRODUCER_PARITY_ELAPSED_MS || "");
+ if (!Number.isFinite(measuredMs) || measuredMs <= 0) {
+ throw new Error("Missing PRODUCER_PARITY_ELAPSED_MS for perf gate");
+ }
+ const baselineRaw = readFileSync(baselinePath, "utf-8");
+ const baseline = JSON.parse(baselineRaw) as PerfBaseline;
+ const maxMs = Math.round(baseline.parityFixtureMaxMs * (1 + baseline.allowedRegressionRatio));
+ const payload = { baselinePath, measuredMs, parityFixtureMaxMs: baseline.parityFixtureMaxMs, maxMs };
+ console.log(`[PerfGate] ${JSON.stringify(payload)}`);
+ if (measuredMs > maxMs) {
+ throw new Error(`[PerfGate] Regression detected measured=${measuredMs}ms max=${maxMs}ms`);
+ }
+}
+
+main();
diff --git a/packages/producer/src/regression-harness.ts b/packages/producer/src/regression-harness.ts
new file mode 100644
index 0000000000..3d5cb3523b
--- /dev/null
+++ b/packages/producer/src/regression-harness.ts
@@ -0,0 +1,887 @@
+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, copyFileSync, rmSync, statSync, cpSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, resolve, join } from "node:path";
+import { spawnSync } from "node:child_process";
+import { fileURLToPath } from "node:url";
+import process from "node:process";
+import { createRenderJob, executeRenderJob } from "./services/renderOrchestrator.js";
+import { compileForRender } from "./services/htmlCompiler.js";
+import { validateCompilation } from "./services/compilationTester.js";
+import { extractVideoMetadata } from "./utils/ffprobe.js";
+
+// ── Types ────────────────────────────────────────────────────────────────────
+
+type TestMetadata = {
+ name: string;
+ description: string;
+ tags: string[];
+ minPsnr: number;
+ maxFrameFailures: number;
+ minAudioCorrelation: number;
+ maxAudioLagWindows: number;
+ renderConfig: {
+ fps: 24 | 30 | 60;
+ workers?: number; // Optional: auto-calculates if omitted
+ };
+};
+
+type TestSuite = {
+ id: string;
+ dir: string;
+ srcDir: string;
+ meta: TestMetadata;
+};
+
+type CliOptions = {
+ testNames: string[];
+ excludeTags: string[];
+ update: boolean;
+ sequential: boolean;
+ keepTemp: boolean;
+};
+
+type TestResult = {
+ suite: TestSuite;
+ passed: boolean;
+ compilation?: {
+ passed: boolean;
+ errors: string[];
+ warnings: string[];
+ };
+ visual?: {
+ passed: boolean;
+ failedFrames: number;
+ checkpoints: Array<{ time: number; psnr: number; passed: boolean }>;
+ };
+ audio?: {
+ passed: boolean;
+ correlation: number;
+ lagWindows: number;
+ };
+ renderedOutputPath?: string;
+};
+
+// ── Utilities ────────────────────────────────────────────────────────────────
+
+/**
+ * Pretty-print logger for human-readable output alongside JSON events
+ */
+function logPretty(message: string, emoji = "•") {
+ console.error(`${emoji} ${message}`);
+}
+
+function formatDuration(ms: number): string {
+ if (ms < 1000) return `${ms}ms`;
+ if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
+ const minutes = Math.floor(ms / 60000);
+ const seconds = Math.floor((ms % 60000) / 1000);
+ return `${minutes}m ${seconds}s`;
+}
+
+function parseArgs(argv: string[]): CliOptions {
+ const testNames: string[] = [];
+ const excludeTags: string[] = [];
+ let update = false;
+ let sequential = false;
+ let keepTemp = false;
+
+ for (let i = 2; i < argv.length; i += 1) {
+ const token = argv[i];
+ if (!token) continue;
+ if (token === "--update") {
+ update = true;
+ } else if (token === "--sequential") {
+ sequential = true;
+ } else if (token === "--keep-temp") {
+ keepTemp = true;
+ } else if (token === "--exclude-tags" && i + 1 < argv.length) {
+ i += 1;
+ const tagArg = argv[i];
+ if (tagArg) excludeTags.push(...tagArg.split(","));
+ } else if (!token.startsWith("--")) {
+ testNames.push(token);
+ }
+ }
+
+ return { testNames, excludeTags, update, sequential, keepTemp };
+}
+
+function validateMetadata(meta: unknown): TestMetadata {
+ if (typeof meta !== "object" || meta === null) {
+ throw new Error("meta.json must be a JSON object");
+ }
+ const m = meta as Record<string, unknown>;
+ if (typeof m.name !== "string" || !m.name) {
+ throw new Error("meta.json: 'name' must be a non-empty string");
+ }
+ if (typeof m.description !== "string") {
+ throw new Error("meta.json: 'description' must be a string");
+ }
+ if (!Array.isArray(m.tags)) {
+ throw new Error("meta.json: 'tags' must be an array");
+ }
+ if (typeof m.minPsnr !== "number" || m.minPsnr < 0) {
+ throw new Error("meta.json: 'minPsnr' must be a non-negative number");
+ }
+ if (typeof m.maxFrameFailures !== "number" || m.maxFrameFailures < 0) {
+ throw new Error("meta.json: 'maxFrameFailures' must be a non-negative number");
+ }
+ if (typeof m.minAudioCorrelation !== "number" || m.minAudioCorrelation < 0 || m.minAudioCorrelation > 1) {
+ throw new Error("meta.json: 'minAudioCorrelation' must be between 0 and 1");
+ }
+ if (typeof m.maxAudioLagWindows !== "number" || m.maxAudioLagWindows < 1) {
+ throw new Error("meta.json: 'maxAudioLagWindows' must be >= 1");
+ }
+ if (!m.renderConfig || typeof m.renderConfig !== "object") {
+ throw new Error("meta.json: 'renderConfig' must be an object");
+ }
+ const rc = m.renderConfig as Record<string, unknown>;
+ if (![24, 30, 60].includes(rc.fps as number)) {
+ throw new Error("meta.json: 'renderConfig.fps' must be 24, 30, or 60");
+ }
+ if (rc.workers !== undefined) {
+ if (typeof rc.workers !== "number" || rc.workers < 1) {
+ throw new Error("meta.json: 'renderConfig.workers' must be >= 1 (or omit to auto-calculate)");
+ }
+ }
+
+ return m as TestMetadata;
+}
+
+function discoverTestSuites(testsDir: string, filterNames: string[], excludeTags: string[] = []): TestSuite[] {
+ if (!existsSync(testsDir)) {
+ throw new Error(`Tests directory not found: ${testsDir}`);
+ }
+
+ const entries = readdirSync(testsDir);
+ const suites: TestSuite[] = [];
+
+ for (const entry of entries) {
+ const dir = join(testsDir, entry);
+ if (!statSync(dir).isDirectory()) continue;
+ if (entry === "node_modules" || entry.startsWith(".")) continue;
+
+ // If filter is specified, skip non-matching tests
+ if (filterNames.length > 0 && !filterNames.includes(entry)) {
+ continue;
+ }
+
+ const srcDir = join(dir, "src");
+ const metaPath = join(dir, "meta.json");
+
+ // Validate structure
+ if (!existsSync(srcDir) || !statSync(srcDir).isDirectory()) {
+ console.warn(`⚠️ Skipping ${entry}: missing src/ directory`);
+ continue;
+ }
+ if (!existsSync(join(srcDir, "index.html"))) {
+ console.warn(`⚠️ Skipping ${entry}: missing src/index.html`);
+ continue;
+ }
+ if (!existsSync(metaPath)) {
+ console.warn(`⚠️ Skipping ${entry}: missing meta.json`);
+ continue;
+ }
+
+ // Parse and validate meta.json
+ let meta: TestMetadata;
+ try {
+ const metaRaw = JSON.parse(readFileSync(metaPath, "utf-8"));
+ meta = validateMetadata(metaRaw);
+ } catch (error) {
+ console.warn(`⚠️ Skipping ${entry}: invalid meta.json - ${error instanceof Error ? error.message : String(error)}`);
+ continue;
+ }
+
+ // Skip tests with excluded tags
+ if (excludeTags.length > 0 && meta.tags.some(t => excludeTags.includes(t))) {
+ logPretty(`Skipping ${entry}: excluded by tags [${meta.tags.filter(t => excludeTags.includes(t)).join(", ")}]`, "⏭️");
+ continue;
+ }
+
+ suites.push({
+ id: entry,
+ dir,
+ srcDir,
+ meta,
+ });
+ }
+
+ return suites;
+}
+
+// ── FFmpeg Utilities ─────────────────────────────────────────────────────────
+
+function runFfmpeg(args: string[], label: string): { stdout: Buffer; stderr: string } {
+ const result = spawnSync("ffmpeg", args, {
+ stdio: ["ignore", "pipe", "pipe"],
+ maxBuffer: 256 * 1024 * 1024,
+ encoding: "buffer",
+ });
+ const stderr = result.stderr.toString("utf-8");
+ if (result.status !== 0) {
+ throw new Error(`${label} failed: ${stderr}`);
+ }
+ return { stdout: result.stdout, stderr };
+}
+
+function extractFrameAsImage(
+ videoPath: string,
+ timeSeconds: number,
+ outputPath: string,
+ fps: number,
+): void {
+ const frameIndex = Math.max(0, Math.round(timeSeconds * fps));
+ runFfmpeg(
+ [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-i",
+ videoPath,
+ "-vf",
+ `select='eq(n\\,${frameIndex})'`,
+ "-frames:v",
+ "1",
+ "-y",
+ outputPath,
+ ],
+ `Frame extraction at ${timeSeconds}s`
+ );
+}
+
+function psnrAtCheckpoint(
+ renderedVideo: string,
+ snapshotVideo: string,
+ checkpointSec: number,
+ fps: number,
+): number {
+ const frameIndex = Math.max(0, Math.round(checkpointSec * fps));
+ const filter = `[0:v]select='eq(n\\,${frameIndex})',setpts=PTS-STARTPTS[rv];[1:v]select='eq(n\\,${frameIndex})',setpts=PTS-STARTPTS[gv];[rv][gv]psnr`;
+ const args = [
+ "-hide_banner",
+ "-loglevel",
+ "info",
+ "-i",
+ renderedVideo,
+ "-i",
+ snapshotVideo,
+ "-filter_complex",
+ filter,
+ "-frames:v",
+ "1",
+ "-f",
+ "null",
+ "-",
+ ];
+ const { stderr } = runFfmpeg(args, `Frame PSNR at ${checkpointSec}s`);
+ const match = stderr.match(/average:\s*([^\s]+)/i);
+ if (!match) {
+ throw new Error(`Unable to parse PSNR output at ${checkpointSec}s`);
+ }
+ const rawValue = (match[1] ?? "").trim().toLowerCase();
+ if (rawValue === "inf" || rawValue === "infinite") {
+ return Number.POSITIVE_INFINITY;
+ }
+ const parsedValue = Number(rawValue);
+ if (!Number.isFinite(parsedValue)) {
+ throw new Error(`Invalid PSNR value at ${checkpointSec}s: ${match[1]}`);
+ }
+ return parsedValue;
+}
+
+function extractMonoPcm16(videoPath: string): Int16Array {
+ const { stdout } = runFfmpeg(
+ [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-i",
+ videoPath,
+ "-vn",
+ "-ac",
+ "1",
+ "-ar",
+ "16000",
+ "-f",
+ "s16le",
+ "-",
+ ],
+ `Audio extraction (${videoPath})`,
+ );
+ if (stdout.byteLength < 2) {
+ return new Int16Array(0);
+ }
+ return new Int16Array(stdout.buffer, stdout.byteOffset, Math.floor(stdout.byteLength / 2));
+}
+
+function buildRmsEnvelope(samples: Int16Array, windowSize = 2048, hopSize = 1024): number[] {
+ if (samples.length < windowSize) return [];
+ const envelope: number[] = [];
+ for (let start = 0; start + windowSize <= samples.length; start += hopSize) {
+ let energy = 0;
+ for (let i = 0; i < windowSize; i += 1) {
+ const normalized = (samples[start + i] ?? 0) / 32768;
+ energy += normalized * normalized;
+ }
+ envelope.push(Math.sqrt(energy / windowSize));
+ }
+ return envelope;
+}
+
+function correlationAtLag(a: number[], b: number[], lag: number): number {
+ const startA = Math.max(0, lag);
+ const startB = Math.max(0, -lag);
+ const length = Math.min(a.length - startA, b.length - startB);
+ if (length <= 32) return -1;
+
+ let meanA = 0;
+ let meanB = 0;
+ for (let i = 0; i < length; i += 1) {
+ meanA += a[startA + i] ?? 0;
+ meanB += b[startB + i] ?? 0;
+ }
+ meanA /= length;
+ meanB /= length;
+
+ let numerator = 0;
+ let denA = 0;
+ let denB = 0;
+ for (let i = 0; i < length; i += 1) {
+ const da = (a[startA + i] ?? 0) - meanA;
+ const db = (b[startB + i] ?? 0) - meanB;
+ numerator += da * db;
+ denA += da * da;
+ denB += db * db;
+ }
+ if (denA <= 1e-12 || denB <= 1e-12) return -1;
+ return numerator / Math.sqrt(denA * denB);
+}
+
+function bestEnvelopeCorrelation(
+ rendered: number[],
+ snapshot: number[],
+ maxLagWindows: number,
+): { correlation: number; lagWindows: number } {
+ let best = -1;
+ let bestLag = 0;
+ for (let lag = -maxLagWindows; lag <= maxLagWindows; lag += 1) {
+ const corr = correlationAtLag(rendered, snapshot, lag);
+ if (corr > best) {
+ best = corr;
+ bestLag = lag;
+ }
+ }
+ return { correlation: best, lagWindows: bestLag };
+}
+
+// ── Failure Reporting ────────────────────────────────────────────────────────
+
+function saveFailureDetails(
+ suite: TestSuite,
+ result: TestResult,
+ renderedVideoPath: string,
+ snapshotVideoPath: string,
+ compiledHtml?: string,
+ snapshotHtml?: string,
+): void {
+ const failuresDir = join(suite.dir, "failures");
+ if (!existsSync(failuresDir)) {
+ mkdirSync(failuresDir, { recursive: true });
+ }
+
+ // Save compilation failures
+ if (result.compilation && !result.compilation.passed) {
+ if (compiledHtml && snapshotHtml) {
+ writeFileSync(join(failuresDir, "actual.html"), compiledHtml, "utf-8");
+ writeFileSync(join(failuresDir, "expected.html"), snapshotHtml, "utf-8");
+
+ const diffSummary = [
+ "=== COMPILATION FAILURE ===",
+ "",
+ "Errors:",
+ ...result.compilation.errors.map(e => ` - ${e}`),
+ "",
+ "Files saved for comparison:",
+ ` - actual.html (what was compiled)`,
+ ` - expected.html (golden snapshot)`,
+ "",
+ "To compare:",
+ ` diff failures/expected.html failures/actual.html`,
+ "",
+ ].join("\n");
+
+ writeFileSync(join(failuresDir, "compilation-diff.txt"), diffSummary, "utf-8");
+ logPretty(`Saved compilation failure details to ${failuresDir}/`, "💾");
+ }
+ }
+
+ // Save visual failures
+ if (result.visual && !result.visual.passed && result.visual.checkpoints.length > 0) {
+ const failedCheckpoints = result.visual.checkpoints.filter(c => !c.passed);
+
+ const visualReport = {
+ summary: {
+ totalCheckpoints: result.visual.checkpoints.length,
+ failedCheckpoints: failedCheckpoints.length,
+ threshold: suite.meta.minPsnr,
+ },
+ failedFrames: failedCheckpoints.map(c => ({
+ time: c.time,
+ psnr: c.psnr,
+ belowThresholdBy: suite.meta.minPsnr - c.psnr,
+ })),
+ };
+
+ writeFileSync(
+ join(failuresDir, "visual-failures.json"),
+ JSON.stringify(visualReport, null, 2),
+ "utf-8"
+ );
+
+ // Extract images for first 10 failed frames
+ const framesToExtract = failedCheckpoints.slice(0, 10);
+ if (framesToExtract.length > 0) {
+ const framesDir = join(failuresDir, "frames");
+ if (!existsSync(framesDir)) {
+ mkdirSync(framesDir, { recursive: true });
+ }
+
+ logPretty(`Extracting ${framesToExtract.length} failed frames...`, "📸");
+
+ for (const checkpoint of framesToExtract) {
+ const timeStr = checkpoint.time.toFixed(2).replace(".", "_");
+ try {
+ extractFrameAsImage(
+ renderedVideoPath,
+ checkpoint.time,
+ join(framesDir, `actual_${timeStr}s.png`),
+ suite.meta.renderConfig.fps
+ );
+ extractFrameAsImage(
+ snapshotVideoPath,
+ checkpoint.time,
+ join(framesDir, `expected_${timeStr}s.png`),
+ suite.meta.renderConfig.fps
+ );
+ } catch (error) {
+ logPretty(` Warning: Could not extract frame at ${checkpoint.time}s`, "⚠️");
+ }
+ }
+ }
+
+ logPretty(`Saved visual failure details to ${failuresDir}/`, "💾");
+ }
+
+ // Save audio failures
+ if (result.audio && !result.audio.passed) {
+ const audioReport = {
+ summary: {
+ correlation: result.audio.correlation,
+ lagWindows: result.audio.lagWindows,
+ threshold: suite.meta.minAudioCorrelation,
+ maxLagWindows: suite.meta.maxAudioLagWindows,
+ },
+ analysis: {
+ correlationBelowThreshold: result.audio.correlation < suite.meta.minAudioCorrelation,
+ lagExceedsLimit: Math.abs(result.audio.lagWindows) > suite.meta.maxAudioLagWindows,
+ },
+ };
+
+ writeFileSync(
+ join(failuresDir, "audio-failures.json"),
+ JSON.stringify(audioReport, null, 2),
+ "utf-8"
+ );
+
+ logPretty(`Saved audio failure details to ${failuresDir}/`, "💾");
+ }
+}
+
+// ── Test Execution ───────────────────────────────────────────────────────────
+
+async function runTestSuite(
+ suite: TestSuite,
+ options: {
+ update: boolean;
+ keepTemp: boolean;
+ }
+): Promise<TestResult> {
+ // Use predictable temp location: /tmp/hyperframes-tests/{test-id}/
+ const testsRoot = join(tmpdir(), "hyperframes-tests");
+ if (!existsSync(testsRoot)) {
+ mkdirSync(testsRoot, { recursive: true });
+ }
+
+ const tempRoot = join(testsRoot, suite.id);
+ if (existsSync(tempRoot)) {
+ rmSync(tempRoot, { recursive: true, force: true });
+ }
+ mkdirSync(tempRoot, { recursive: true });
+
+ const tempDownloadDir = join(tempRoot, "downloads");
+ const renderedOutputPath = join(tempRoot, "output.mp4");
+
+ // Snapshot files stored in test's output/ directory
+ const snapshotDir = join(suite.dir, "output");
+ const snapshotCompiledPath = join(snapshotDir, "compiled.html");
+ const snapshotVideoPath = join(snapshotDir, "output.mp4");
+
+ console.log(JSON.stringify({ event: "test_start", suite: suite.id, name: suite.meta.name }));
+ logPretty(`Running test: ${suite.meta.name}`, "🧪");
+
+ const result: TestResult = { suite, passed: false };
+ let compiledHtml: string | undefined;
+ let snapshotHtml: string | undefined;
+
+ try {
+ // STEP 1: Compile HTML
+ console.log(JSON.stringify({ event: "compilation_start", suite: suite.id }));
+ logPretty("Compiling composition...", "⚙️");
+
+ const inputHtmlPath = join(suite.srcDir, "index.html");
+ if (!existsSync(inputHtmlPath)) {
+ throw new Error(`Input HTML not found: ${inputHtmlPath}`);
+ }
+
+ const compiled = await compileForRender(suite.srcDir, inputHtmlPath, tempDownloadDir);
+ compiledHtml = compiled.html;
+
+ // Update mode: save snapshot and pass
+ if (options.update) {
+ if (!existsSync(snapshotDir)) {
+ mkdirSync(snapshotDir, { recursive: true });
+ }
+ writeFileSync(snapshotCompiledPath, compiled.html, "utf-8");
+ console.log(JSON.stringify({ event: "snapshot_updated", suite: suite.id, file: "output/compiled.html" }));
+ result.compilation = { passed: true, errors: [], warnings: [] };
+ } else {
+ // Test mode: compare against snapshot
+ if (!existsSync(snapshotCompiledPath)) {
+ throw new Error(`Snapshot not found: ${snapshotCompiledPath}. Run with --update to create it.`);
+ }
+
+ snapshotHtml = readFileSync(snapshotCompiledPath, "utf-8");
+ const validation = validateCompilation(compiled.html, snapshotHtml);
+
+ result.compilation = {
+ passed: validation.passed,
+ errors: validation.errors,
+ warnings: validation.warnings,
+ };
+
+ console.log(JSON.stringify({
+ event: "compilation_complete",
+ suite: suite.id,
+ passed: validation.passed,
+ errors: validation.errors.length,
+ warnings: validation.warnings.length,
+ }));
+
+ if (!validation.passed) {
+ console.error(JSON.stringify({
+ event: "compilation_failed",
+ suite: suite.id,
+ errors: validation.errors,
+ }));
+ result.passed = false;
+ return result;
+ }
+ }
+
+ // STEP 2: Render video
+ console.log(JSON.stringify({ event: "rendering_start", suite: suite.id }));
+ logPretty("Rendering video...", "🎬");
+
+ const tempSrcDir = join(tempRoot, "src");
+ cpSync(suite.srcDir, tempSrcDir, { recursive: true });
+
+ const job = createRenderJob({
+ fps: suite.meta.renderConfig.fps,
+ quality: "high", // Always use max quality for tests
+ workers: suite.meta.renderConfig.workers,
+ useGpu: false,
+ debug: false,
+ });
+
+ await executeRenderJob(job, tempSrcDir, renderedOutputPath);
+
+ console.log(JSON.stringify({ event: "rendering_complete", suite: suite.id }));
+ logPretty("Render complete! Starting quality validation...", "✓");
+
+ // Update mode: save snapshot and pass
+ if (options.update) {
+ if (!existsSync(snapshotDir)) {
+ mkdirSync(snapshotDir, { recursive: true });
+ }
+ copyFileSync(renderedOutputPath, snapshotVideoPath);
+ console.log(JSON.stringify({ event: "snapshot_updated", suite: suite.id, file: "output/output.mp4" }));
+ result.visual = { passed: true, failedFrames: 0, checkpoints: [] };
+ result.audio = { passed: true, correlation: 1, lagWindows: 0 };
+ result.passed = true;
+ return result;
+ }
+
+ // Test mode: compare against snapshot
+ if (!existsSync(snapshotVideoPath)) {
+ throw new Error(`Snapshot not found: ${snapshotVideoPath}. Run with --update to create it.`);
+ }
+
+ // Visual comparison (100 frames, 1 per 1% of video duration)
+ logPretty("Comparing visual quality (100 checkpoints)...", "🔍");
+ const videoMetadata = await extractVideoMetadata(renderedOutputPath);
+ const videoDuration = videoMetadata.durationSeconds;
+
+ const visualCheckpoints: Array<{ time: number; psnr: number; passed: boolean }> = [];
+ for (let i = 0; i < 100; i++) {
+ const time = (videoDuration * i) / 100;
+ const psnr = psnrAtCheckpoint(renderedOutputPath, snapshotVideoPath, time, suite.meta.renderConfig.fps);
+ visualCheckpoints.push({
+ time,
+ psnr,
+ passed: psnr >= suite.meta.minPsnr,
+ });
+
+ // Progress indicator every 20 checkpoints
+ if ((i + 1) % 20 === 0) {
+ logPretty(` Progress: ${i + 1}/100 checkpoints`, " ");
+ }
+ }
+
+ const failedFrames = visualCheckpoints.filter((c) => !c.passed).length;
+ const visualPassed = failedFrames <= suite.meta.maxFrameFailures;
+
+ result.visual = {
+ passed: visualPassed,
+ failedFrames,
+ checkpoints: visualCheckpoints,
+ };
+
+ console.log(JSON.stringify({
+ event: "visual_comparison_complete",
+ suite: suite.id,
+ passed: visualPassed,
+ failedFrames,
+ checkpoints: visualCheckpoints,
+ }));
+
+ if (visualPassed) {
+ logPretty(`Visual quality: PASSED (${failedFrames} failed frames, threshold: ${suite.meta.maxFrameFailures})`, "✓");
+ } else {
+ logPretty(`Visual quality: FAILED (${failedFrames} failed frames, threshold: ${suite.meta.maxFrameFailures})`, "✗");
+ }
+
+ // Audio comparison
+ logPretty("Comparing audio quality...", "🔊");
+ const renderedAudio = extractMonoPcm16(renderedOutputPath);
+ const snapshotAudio = extractMonoPcm16(snapshotVideoPath);
+
+ let audioPassed = true;
+ let audioCorrelation = 1;
+ let audioLagWindows = 0;
+
+ if (renderedAudio.length > 0 && snapshotAudio.length > 0) {
+ const renderedEnvelope = buildRmsEnvelope(renderedAudio);
+ const snapshotEnvelope = buildRmsEnvelope(snapshotAudio);
+ const audio = bestEnvelopeCorrelation(renderedEnvelope, snapshotEnvelope, suite.meta.maxAudioLagWindows);
+ audioCorrelation = audio.correlation;
+ audioLagWindows = audio.lagWindows;
+ audioPassed = audio.correlation >= suite.meta.minAudioCorrelation;
+ }
+
+ result.audio = {
+ passed: audioPassed,
+ correlation: audioCorrelation,
+ lagWindows: audioLagWindows,
+ };
+
+ console.log(JSON.stringify({
+ event: "audio_comparison_complete",
+ suite: suite.id,
+ passed: audioPassed,
+ correlation: audioCorrelation,
+ lagWindows: audioLagWindows,
+ }));
+
+ if (audioPassed) {
+ logPretty(`Audio quality: PASSED (correlation: ${audioCorrelation.toFixed(3)}, lag: ${audioLagWindows})`, "✓");
+ } else {
+ logPretty(`Audio quality: FAILED (correlation: ${audioCorrelation.toFixed(3)}, threshold: ${suite.meta.minAudioCorrelation})`, "✗");
+ }
+
+ // Overall test passes if all checks passed
+ result.passed = result.compilation!.passed && visualPassed && audioPassed;
+ result.renderedOutputPath = options.keepTemp ? renderedOutputPath : undefined;
+
+ if (result.passed) {
+ logPretty(`Test PASSED: ${suite.meta.name}`, "✅");
+ } else {
+ logPretty(`Test FAILED: ${suite.meta.name}`, "❌");
+ }
+
+ return result;
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ result.passed = false;
+
+ console.error(JSON.stringify({
+ event: "test_error",
+ suite: suite.id,
+ error: errorMessage,
+ }));
+
+ return result;
+ } finally {
+ // Save failure details before cleanup
+ if (!result.passed && !options.update) {
+ try {
+ saveFailureDetails(
+ suite,
+ result,
+ renderedOutputPath,
+ snapshotVideoPath,
+ compiledHtml,
+ snapshotHtml
+ );
+ } catch (error) {
+ logPretty(`Warning: Could not save failure details: ${error instanceof Error ? error.message : String(error)}`, "⚠️");
+ }
+ }
+
+ // Clean up temp directory
+ if (!options.keepTemp) {
+ rmSync(tempRoot, { recursive: true, force: true });
+ } else {
+ console.log(JSON.stringify({ event: "temp_preserved", suite: suite.id, path: tempRoot }));
+ }
+ }
+}
+
+// ── Main ─────────────────────────────────────────────────────────────────────
+
+async function run(): Promise<void> {
+ const options = parseArgs(process.argv);
+ const moduleDir = dirname(fileURLToPath(import.meta.url));
+ const producerRoot = resolve(moduleDir, "..");
+ const testsDir = join(producerRoot, "tests");
+
+ const suites = discoverTestSuites(testsDir, options.testNames, options.excludeTags);
+
+ if (suites.length === 0) {
+ if (options.testNames.length > 0) {
+ throw new Error(`No test suites found matching: ${options.testNames.join(", ")}`);
+ }
+ throw new Error(`No test suites found in ${testsDir}`);
+ }
+
+ console.log(JSON.stringify({
+ event: "test_suite_start",
+ totalSuites: suites.length,
+ parallel: !options.sequential
+ }));
+
+ logPretty(`Starting ${suites.length} test suite(s) - ${options.sequential ? "sequential" : "parallel"} mode`, "🚀");
+
+ let results: TestResult[] = [];
+
+ if (options.sequential) {
+ // Sequential execution
+ for (const suite of suites) {
+ try {
+ const result = await runTestSuite(suite, options);
+ results.push(result);
+ } catch (error) {
+ console.error(JSON.stringify({
+ event: "test_failed",
+ suite: suite.id,
+ error: error instanceof Error ? error.message : String(error),
+ }));
+ process.exitCode = 1;
+ }
+ }
+ } else {
+ // Parallel execution (default)
+ const settledResults = await Promise.allSettled(
+ suites.map(suite => runTestSuite(suite, options))
+ );
+
+ results = settledResults.map((settled, index) => {
+ const matchingSuite = suites[index];
+ if (settled.status === "fulfilled") {
+ return settled.value;
+ } else {
+ console.error(JSON.stringify({
+ event: "test_failed",
+ suite: matchingSuite?.id ?? "unknown",
+ error: settled.reason instanceof Error ? settled.reason.message : String(settled.reason),
+ }));
+ process.exitCode = 1;
+ if (!matchingSuite) {
+ throw new Error(`No matching suite at index ${index}`);
+ }
+ return {
+ suite: matchingSuite,
+ passed: false,
+ };
+ }
+ });
+ }
+
+ // Summary
+ if (options.update) {
+ console.log(JSON.stringify({
+ event: "snapshots_updated",
+ total: results.length,
+ }));
+ logPretty(`Updated ${results.length} snapshot(s)`, "📸");
+ } else {
+ const passed = results.filter((r) => r.passed).length;
+ const failed = results.filter((r) => !r.passed).length;
+ const failedAtCompilation = results.filter((r) => r.compilation && !r.compilation.passed).length;
+ const failedAtVisual = results.filter((r) => r.visual && !r.visual.passed).length;
+ const failedAtAudio = results.filter((r) => r.audio && !r.audio.passed).length;
+
+ console.log(JSON.stringify({
+ event: "test_suite_summary",
+ total: results.length,
+ passed,
+ failed,
+ failedAtCompilation,
+ failedAtVisual,
+ failedAtAudio,
+ results: results.map((r) => ({
+ suite: r.suite.id,
+ name: r.suite.meta.name,
+ passed: r.passed,
+ compilation: r.compilation?.passed,
+ visual: r.visual?.passed,
+ audio: r.audio?.passed,
+ })),
+ }));
+
+ // Pretty summary
+ logPretty("═══════════════════════════════════════", "");
+ logPretty(`Test Suite Summary`, "📊");
+ logPretty(`Total: ${results.length} | Passed: ${passed} | Failed: ${failed}`, "");
+ if (failed > 0) {
+ logPretty(` Failed at compilation: ${failedAtCompilation}`, "");
+ logPretty(` Failed at visual: ${failedAtVisual}`, "");
+ logPretty(` Failed at audio: ${failedAtAudio}`, "");
+ }
+ logPretty("═══════════════════════════════════════", "");
+
+ if (failed > 0) {
+ process.exitCode = 1;
+ }
+ }
+}
+
+void run().catch((error) => {
+ console.error(
+ JSON.stringify({
+ event: "test_suite_fatal",
+ message: error instanceof Error ? error.message : String(error),
+ }),
+ );
+ process.exitCode = 1;
+});
diff --git a/packages/producer/src/runtime-conformance.ts b/packages/producer/src/runtime-conformance.ts
new file mode 100644
index 0000000000..5c875d28b7
--- /dev/null
+++ b/packages/producer/src/runtime-conformance.ts
@@ -0,0 +1,45 @@
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import {
+ getVerifiedHyperframeRuntimeSource,
+ resolveHyperframeManifestPath,
+} from "./services/hyperframeRuntimeLoader.js";
+
+function assert(condition: unknown, message: string): void {
+ if (!condition) {
+ throw new Error(message);
+ }
+}
+
+const manifestPath = resolveHyperframeManifestPath();
+const manifestRaw = readFileSync(manifestPath, "utf8");
+const manifest = JSON.parse(manifestRaw) as {
+ sha256?: string;
+ artifacts?: { iife?: string };
+};
+
+const verifiedSource = getVerifiedHyperframeRuntimeSource();
+const sourceSha = createHash("sha256").update(verifiedSource, "utf8").digest("hex");
+assert(sourceSha === manifest.sha256, "Verified runtime hash does not match manifest sha256");
+
+const servicesDir = resolve(fileURLToPath(new URL("./services", import.meta.url)));
+const fileServerSource = readFileSync(resolve(servicesDir, "fileServer.ts"), "utf8");
+assert(
+ fileServerSource.includes("getVerifiedHyperframeRuntimeSource"),
+ "Producer file server must inject runtime via getVerifiedHyperframeRuntimeSource"
+);
+assert(
+ !fileServerSource.includes("loadHyperframeRuntimeSource"),
+ "Producer file server must not inject runtime via loadHyperframeRuntimeSource"
+);
+
+console.log(
+ JSON.stringify({
+ event: "producer_runtime_conformance_ok",
+ manifestPath,
+ runtimeSha256: sourceSha,
+ })
+);
+
diff --git a/packages/producer/src/server.ts b/packages/producer/src/server.ts
new file mode 100644
index 0000000000..e975be84c8
--- /dev/null
+++ b/packages/producer/src/server.ts
@@ -0,0 +1,492 @@
+#!/usr/bin/env node
+/**
+ * @hyperframes/producer — Public Server
+ *
+ * Clean HTTP API for rendering HTML compositions to video.
+ *
+ * Routes:
+ * POST /render — blocking render, returns JSON
+ * POST /render/stream — SSE streaming render with progress
+ * POST /lint — blocking Hyperframe lint
+ * GET /health — health check
+ * GET /outputs/:token — download rendered MP4
+ */
+
+import { existsSync, mkdirSync, statSync, mkdtempSync, writeFileSync, rmSync, createReadStream } from "node:fs";
+import { resolve, dirname, join } from "node:path";
+import { tmpdir } from "node:os";
+import { parseArgs } from "node:util";
+import crypto from "node:crypto";
+import { Hono, type Context } from "hono";
+import { streamSSE } from "hono/streaming";
+import { serve } from "@hono/node-server";
+import {
+ RenderCancelledError,
+ createRenderJob,
+ executeRenderJob,
+} from "./services/renderOrchestrator.js";
+import { prepareHyperframeLintBody, runHyperframeLint } from "./services/hyperframeLint.js";
+import { resolveRenderPaths } from "./utils/paths.js";
+import { defaultLogger, type ProducerLogger } from "./logger.js";
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+export interface HandlerOptions {
+ /** Custom logger. Defaults to console-based defaultLogger. */
+ logger?: ProducerLogger;
+ /** Extract or generate a request ID. Defaults to x-request-id header or random UUID. */
+ getRequestId?: (c: Context) => string;
+ /** Directory for rendered output files. Defaults to PRODUCER_RENDERS_DIR or /tmp. */
+ rendersDir?: string;
+ /** Prefix for output URLs in responses. Default: "/outputs". */
+ outputUrlPrefix?: string;
+ /** TTL for output artifact download tokens (ms). Default: 15 minutes. */
+ artifactTtlMs?: number;
+}
+
+export interface ServerOptions extends HandlerOptions {
+ /** Port to listen on. Default: 9847. */
+ port?: number;
+}
+
+// ---------------------------------------------------------------------------
+// Shared validation helpers
+// ---------------------------------------------------------------------------
+interface RenderInput {
+ projectDir: string;
+ outputPath?: string | null;
+ fps: 24 | 30 | 60;
+ quality: "draft" | "standard" | "high";
+ workers?: number;
+ useGpu: boolean;
+ debug: boolean;
+}
+
+interface PreparedRenderInput {
+ input: RenderInput;
+ cleanupProjectDir?: string;
+}
+
+function parseRenderOptions(body: Record<string, unknown>): Omit<RenderInput, "projectDir"> {
+ const fps = ([24, 30, 60].includes(body.fps as number) ? body.fps : 30) as 24 | 30 | 60;
+ const quality = (["draft", "standard", "high"].includes(body.quality as string) ? body.quality : "high") as "draft" | "standard" | "high";
+ const workers = typeof body.workers === "number" ? body.workers : undefined;
+ const useGpu = body.gpu === true;
+ const debug = body.debug === true;
+ const outputPath =
+ typeof body.outputPath === "string" && body.outputPath.trim().length > 0
+ ? body.outputPath
+ : typeof body.output === "string" && body.output.trim().length > 0
+ ? body.output
+ : null;
+
+ return { outputPath, fps, quality, workers, useGpu, debug };
+}
+
+async function prepareRenderBody(body: Record<string, unknown>): Promise<{ prepared: PreparedRenderInput } | { error: string }> {
+ const options = parseRenderOptions(body);
+ const projectDir = typeof body.projectDir === "string" ? body.projectDir : undefined;
+ if (projectDir) {
+ const absProjectDir = resolve(projectDir);
+ if (!existsSync(absProjectDir) || !statSync(absProjectDir).isDirectory()) {
+ return { error: `Project directory not found: ${absProjectDir}` };
+ }
+ if (!existsSync(resolve(absProjectDir, "index.html"))) {
+ return { error: `No index.html in project directory: ${absProjectDir}` };
+ }
+ return { prepared: { input: { projectDir: absProjectDir, ...options } } };
+ }
+
+ const previewUrl = typeof body.previewUrl === "string" ? body.previewUrl.trim() : "";
+ const inlineHtml = typeof body.html === "string" ? body.html : "";
+ if (!previewUrl && !inlineHtml) {
+ return { error: "Missing render source: provide projectDir, previewUrl, or html" };
+ }
+
+ let htmlContent = inlineHtml;
+ if (!htmlContent) {
+ try {
+ const response = await fetch(previewUrl, { method: "GET" });
+ if (!response.ok) {
+ return { error: `Failed to fetch previewUrl: ${response.status} ${response.statusText}` };
+ }
+ htmlContent = await response.text();
+ } catch (error) {
+ return { error: `Failed to fetch previewUrl: ${error instanceof Error ? error.message : String(error)}` };
+ }
+ }
+
+ const tempRoot = process.env.PRODUCER_TMP_PROJECT_DIR || tmpdir();
+ const tempProjectDir = mkdtempSync(join(tempRoot, "producer-project-"));
+ writeFileSync(join(tempProjectDir, "index.html"), htmlContent, "utf-8");
+ return {
+ prepared: {
+ input: {
+ projectDir: tempProjectDir,
+ ...options,
+ },
+ cleanupProjectDir: tempProjectDir,
+ },
+ };
+}
+
+function resolveOutputPath(projectDir: string, outputCandidate: string | null | undefined, rendersDir: string, log: ProducerLogger): string {
+ try {
+ return resolveRenderPaths(projectDir, outputCandidate, rendersDir).absoluteOutputPath;
+ } catch (error) {
+ const fallbackPath = resolve(rendersDir, `producer-fallback-${Date.now()}.mp4`);
+ log.warn("Failed to resolve output path, using fallback", {
+ fallback: fallbackPath,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return fallbackPath;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Output artifact management
+// ---------------------------------------------------------------------------
+interface OutputArtifact {
+ path: string;
+ expiresAtMs: number;
+}
+
+function createArtifactStore(ttlMs: number) {
+ const artifacts = new Map<string, OutputArtifact>();
+
+ const cleanup = setInterval(() => {
+ const now = Date.now();
+ for (const [token, artifact] of artifacts.entries()) {
+ if (artifact.expiresAtMs <= now) {
+ artifacts.delete(token);
+ }
+ }
+ }, 60_000);
+ cleanup.unref();
+
+ return {
+ register(path: string): string {
+ const token = crypto.randomUUID();
+ artifacts.set(token, { path, expiresAtMs: Date.now() + ttlMs });
+ return token;
+ },
+ get(token: string): OutputArtifact | undefined {
+ return artifacts.get(token);
+ },
+ delete(token: string) {
+ artifacts.delete(token);
+ },
+ };
+}
+
+function cleanupTempDir(dir: string | undefined, log: ProducerLogger): void {
+ if (!dir) return;
+ try {
+ rmSync(dir, { recursive: true, force: true });
+ } catch (error) {
+ log.warn("Failed to cleanup temp project dir", {
+ cleanupProjectDir: dir,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Handler factory
+// ---------------------------------------------------------------------------
+export interface RenderHandlers {
+ render: (c: Context) => Promise<Response>;
+ renderStream: (c: Context) => Response | Promise<Response>;
+ lint: (c: Context) => Promise<Response>;
+ health: (c: Context) => Response;
+ outputs: (c: Context) => Response;
+}
+
+/**
+ * Create route handler functions for the producer server.
+ *
+ * These can be mounted on any Hono app at any path prefix.
+ */
+export function createRenderHandlers(options: HandlerOptions = {}): RenderHandlers {
+ const log = options.logger ?? defaultLogger;
+ const getRequestId = options.getRequestId ?? ((c: Context) => c.req.header("x-request-id") || crypto.randomUUID());
+ const outputUrlPrefix = options.outputUrlPrefix ?? "/outputs";
+ const rendersDir = options.rendersDir ?? process.env.PRODUCER_RENDERS_DIR ?? "/tmp";
+ const artifactTtlMs = options.artifactTtlMs ?? Number(process.env.PRODUCER_OUTPUT_ARTIFACT_TTL_MS || 15 * 60 * 1000);
+ const store = createArtifactStore(artifactTtlMs);
+ const startTime = Date.now();
+
+ const health = (c: Context): Response =>
+ c.json({ status: "ok", uptime: Math.floor((Date.now() - startTime) / 1000), timestamp: new Date().toISOString() });
+
+ const lint = async (c: Context): Promise<Response> => {
+ const requestId = getRequestId(c);
+
+ let body: Record<string, unknown>;
+ try {
+ body = await c.req.json();
+ } catch {
+ return c.json({ success: false, requestId, error: "Invalid JSON body" }, 400);
+ }
+
+ const preparedResult = prepareHyperframeLintBody(body);
+ if ("error" in preparedResult) {
+ return c.json({ success: false, requestId, error: preparedResult.error }, 400);
+ }
+
+ const result = runHyperframeLint(preparedResult.prepared);
+ log.info("lint completed", {
+ requestId,
+ entryFile: preparedResult.prepared.entryFile,
+ source: preparedResult.prepared.source,
+ errorCount: result.errorCount,
+ warningCount: result.warningCount,
+ });
+
+ return c.json({
+ success: true,
+ requestId,
+ entryFile: preparedResult.prepared.entryFile,
+ source: preparedResult.prepared.source,
+ result,
+ });
+ };
+
+ const render = async (c: Context): Promise<Response> => {
+ const requestId = getRequestId(c);
+ const t0 = Date.now();
+
+ let body: Record<string, unknown>;
+ try {
+ body = await c.req.json();
+ } catch {
+ return c.json({ success: false, requestId, error: "Invalid JSON body" }, 400);
+ }
+
+ const preparedResult = await prepareRenderBody(body);
+ if ("error" in preparedResult) {
+ return c.json({ success: false, requestId, error: preparedResult.error }, 400);
+ }
+
+ const { input, cleanupProjectDir } = preparedResult.prepared;
+ const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
+ const outputDir = dirname(absoluteOutputPath);
+ if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
+
+ log.info("render started", { requestId, projectDir: input.projectDir, fps: input.fps, quality: input.quality });
+
+ const job = createRenderJob({ fps: input.fps, quality: input.quality, workers: input.workers, useGpu: input.useGpu, debug: input.debug, logger: log });
+
+ let lastLoggedPct = -10;
+ try {
+ await executeRenderJob(job, input.projectDir, absoluteOutputPath, async (j, message) => {
+ const pct = Math.floor(j.progress * 100);
+ if (pct >= lastLoggedPct + 10) {
+ lastLoggedPct = pct;
+ log.info(`render progress ${pct}%`, { requestId, stage: j.currentStage, message });
+ }
+ });
+
+ const fileSize = existsSync(absoluteOutputPath) ? statSync(absoluteOutputPath).size : 0;
+ const durationMs = Date.now() - t0;
+ const outputToken = store.register(absoluteOutputPath);
+ const outputUrl = `${outputUrlPrefix}/${outputToken}`;
+ log.info("render completed", { requestId, durationMs, fileSize, perf: job.perfSummary ?? null });
+
+ return c.json({ success: true, requestId, outputPath: absoluteOutputPath, outputToken, outputUrl, fileSize, durationMs, videoDurationSeconds: job.duration ?? null, perf: job.perfSummary ?? null });
+ } catch (error) {
+ const durationMs = Date.now() - t0;
+ const errorMsg = error instanceof Error ? error.message : String(error);
+ log.error("render failed", { requestId, durationMs, error: errorMsg, stage: job.currentStage });
+ return c.json({ success: false, requestId, error: errorMsg, stage: job.currentStage, durationMs, errorDetails: job.errorDetails ?? null }, 500);
+ } finally {
+ cleanupTempDir(cleanupProjectDir, log);
+ }
+ };
+
+ const renderStream = (c: Context) => {
+ return streamSSE(c, async (stream) => {
+ const requestId = getRequestId(c);
+ const t0 = Date.now();
+
+ let body: Record<string, unknown>;
+ try {
+ body = await c.req.json();
+ } catch {
+ await stream.writeSSE({ data: JSON.stringify({ type: "error", requestId, error: "Invalid JSON body", stage: "validation" }) });
+ return;
+ }
+
+ const preparedResult = await prepareRenderBody(body);
+ if ("error" in preparedResult) {
+ await stream.writeSSE({ data: JSON.stringify({ type: "error", requestId, error: preparedResult.error, stage: "validation" }) });
+ return;
+ }
+
+ const { input, cleanupProjectDir } = preparedResult.prepared;
+ const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
+ const outputDir = dirname(absoluteOutputPath);
+ if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
+
+ log.info("render-stream started", { requestId, projectDir: input.projectDir });
+
+ const job = createRenderJob({ fps: input.fps, quality: input.quality, workers: input.workers, useGpu: input.useGpu, debug: input.debug, logger: log });
+ const abortController = new AbortController();
+ const onRequestAbort = () => abortController.abort(new RenderCancelledError("request_aborted"));
+ c.req.raw.signal.addEventListener("abort", onRequestAbort, { once: true });
+
+ try {
+ await executeRenderJob(job, input.projectDir, absoluteOutputPath, async (j, message) => {
+ await stream.writeSSE({
+ data: JSON.stringify({
+ type: "progress",
+ requestId,
+ stage: j.currentStage,
+ progress: j.progress,
+ framesRendered: j.framesRendered ?? 0,
+ totalFrames: j.totalFrames ?? 0,
+ message,
+ }),
+ });
+ }, abortController.signal);
+
+ const fileSize = existsSync(absoluteOutputPath) ? statSync(absoluteOutputPath).size : 0;
+ const outputToken = store.register(absoluteOutputPath);
+ const outputUrl = `${outputUrlPrefix}/${outputToken}`;
+ log.info("render-stream completed", { requestId, fileSize, perf: job.perfSummary ?? null });
+ await stream.writeSSE({
+ data: JSON.stringify({ type: "complete", requestId, outputPath: absoluteOutputPath, outputToken, outputUrl, fileSize, videoDurationSeconds: job.duration ?? null, perf: job.perfSummary ?? null }),
+ });
+ } catch (error) {
+ if (error instanceof RenderCancelledError) {
+ await stream.writeSSE({
+ data: JSON.stringify({
+ type: "cancelled",
+ requestId,
+ stage: job.currentStage,
+ message: error.message,
+ }),
+ });
+ return;
+ }
+ const errorMsg = error instanceof Error ? error.message : String(error);
+ const elapsedMs = Date.now() - t0;
+ log.error("render-stream failed", { requestId, elapsedMs, error: errorMsg, stage: job.currentStage });
+ await stream.writeSSE({
+ data: JSON.stringify({
+ type: "error",
+ requestId,
+ error: errorMsg,
+ stage: job.currentStage,
+ elapsedMs,
+ errorDetails: job.errorDetails ?? null,
+ }),
+ });
+ } finally {
+ c.req.raw.signal.removeEventListener("abort", onRequestAbort);
+ cleanupTempDir(cleanupProjectDir, log);
+ }
+ });
+ };
+
+ const outputs = (c: Context): Response => {
+ const token = c.req.param("token");
+ const artifact = store.get(token);
+ if (!artifact) {
+ return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
+ }
+ if (!existsSync(artifact.path)) {
+ store.delete(token);
+ return c.json({ success: false, error: "Output artifact file missing" }, 404);
+ }
+ const stats = statSync(artifact.path);
+ return new Response(createReadStream(artifact.path) as unknown as ReadableStream, {
+ headers: {
+ "content-type": "video/mp4",
+ "content-length": String(stats.size),
+ "cache-control": "no-store",
+ },
+ });
+ };
+
+ return { render, renderStream, lint, health, outputs };
+}
+
+// ---------------------------------------------------------------------------
+// Public app factory
+// ---------------------------------------------------------------------------
+
+/**
+ * Create a Hono app with clean public routes for OSS use.
+ */
+export function createProducerApp(options: HandlerOptions = {}): Hono {
+ const app = new Hono();
+ const handlers = createRenderHandlers(options);
+
+ app.get("/health", handlers.health);
+ app.post("/render", handlers.render);
+ app.post("/render/stream", handlers.renderStream);
+ app.post("/lint", handlers.lint);
+ app.get("/outputs/:token", handlers.outputs);
+
+ return app;
+}
+
+// ---------------------------------------------------------------------------
+// Standalone server
+// ---------------------------------------------------------------------------
+
+/**
+ * Start the producer HTTP server with graceful shutdown.
+ */
+export function startServer(options: ServerOptions = {}) {
+ const port = options.port ?? parseInt(process.env.PRODUCER_PORT ?? "9847", 10);
+ const log = options.logger ?? defaultLogger;
+ const app = createProducerApp(options);
+
+ const server = serve({ fetch: app.fetch, port }, () => {
+ log.info(`Listening on http://localhost:${port}`);
+ });
+
+ // Disable timeouts for long renders
+ server.setTimeout(0);
+ (server as unknown as import("node:http").Server).requestTimeout = 0;
+ (server as unknown as import("node:http").Server).keepAliveTimeout = 0;
+
+ function shutdown(signal: string) {
+ log.info(`Received ${signal}, shutting down`);
+ server.close(() => {
+ log.info("Server closed");
+ process.exit(0);
+ });
+ setTimeout(() => {
+ log.warn("Forced exit after 30s timeout");
+ process.exit(1);
+ }, 30_000).unref();
+ }
+
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
+ process.on("SIGINT", () => shutdown("SIGINT"));
+
+ return server;
+}
+
+// ---------------------------------------------------------------------------
+// Self-executable: node dist/public-server.js
+// ---------------------------------------------------------------------------
+// Only auto-start when this file is the explicit entry point.
+// In esbuild bundles, import.meta.url is shared across inlined modules,
+// so we check argv[1] against known public server filenames.
+const entryScript = process.argv[1] ? resolve(process.argv[1]) : "";
+const isPublicServerEntry = entryScript.endsWith("/public-server.js") ||
+ entryScript.endsWith("/src/server.ts");
+
+if (isPublicServerEntry) {
+ const { values } = parseArgs({
+ options: {
+ port: { type: "string", short: "p", default: process.env.PRODUCER_PORT ?? "9847" },
+ },
+ });
+ startServer({ port: parseInt(values.port as string, 10) });
+}
diff --git a/packages/producer/src/services/audioExtractor.ts b/packages/producer/src/services/audioExtractor.ts
new file mode 100644
index 0000000000..3cb86f5faf
--- /dev/null
+++ b/packages/producer/src/services/audioExtractor.ts
@@ -0,0 +1,324 @@
+/**
+ * Audio Extractor Service
+ *
+ * Extracts audio from media elements in the composition HTML,
+ * applies timeline positioning, and mixes into a single audio track.
+ */
+
+import { spawn } from "node:child_process";
+import { existsSync, mkdirSync, rmSync, readFileSync } from "node:fs";
+import { join, dirname } from "node:path";
+
+export interface AudioElement {
+ id: string;
+ src: string;
+ start: number;
+ duration: number;
+ mediaStart: number;
+ volume: number;
+ tagName: "audio" | "video";
+}
+
+export interface AudioTrack {
+ id: string;
+ srcPath: string;
+ start: number;
+ duration: number;
+ mediaStart: number;
+ volume: number;
+}
+
+/**
+ * Parse audio/video elements from HTML to find media with audio.
+ */
+export function parseAudioElements(html: string): AudioElement[] {
+ const elements: AudioElement[] = [];
+
+ // Match <audio> and <video> elements with data-start
+ const mediaRegex = /<(audio|video)\s[^>]*data-start=["']([^"']+)["'][^>]*>/gi;
+ let match;
+
+ while ((match = mediaRegex.exec(html)) !== null) {
+ const fullTag = match[0];
+ const tagName = (match[1] ?? "").toLowerCase() as "audio" | "video";
+ const start = parseFloat(match[2] ?? "");
+
+ const idMatch = fullTag.match(/id=["']([^"']+)["']/);
+ const srcMatch = fullTag.match(/src=["']([^"']+)["']/);
+ if (!srcMatch) continue;
+
+ const durationMatch = fullTag.match(/data-duration=["']([^"']+)["']/);
+ const endMatch = fullTag.match(/data-end=["']([^"']+)["']/);
+ const mediaStartMatch = fullTag.match(
+ /data-media-start=["']([^"']+)["']/
+ );
+ const volumeMatch = fullTag.match(/data-volume=["']([^"']+)["']/);
+ const parsedVolume = volumeMatch ? parseFloat(volumeMatch[1] ?? "") : 1.0;
+ const safeVolume = Number.isFinite(parsedVolume) ? parsedVolume : 1.0;
+ const durationFromDuration = durationMatch
+ ? parseFloat(durationMatch[1] ?? "")
+ : NaN;
+ const end = endMatch ? parseFloat(endMatch[1] ?? "") : NaN;
+ const duration =
+ !isNaN(durationFromDuration) && durationFromDuration > 0
+ ? durationFromDuration
+ : !isNaN(end) && end > start
+ ? end - start
+ : 0;
+
+ elements.push({
+ id: idMatch?.[1] || `media-${elements.length}`,
+ src: srcMatch[1] ?? "",
+ start: isNaN(start) ? 0 : start,
+ duration,
+ mediaStart: mediaStartMatch ? parseFloat(mediaStartMatch[1] ?? "") : 0,
+ volume: safeVolume,
+ tagName,
+ });
+ }
+
+ return elements;
+}
+
+/**
+ * Run an FFmpeg command and return a promise.
+ */
+function runFFmpeg(args: string[]): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const ffmpeg = spawn("ffmpeg", args);
+ let stderr = "";
+
+ ffmpeg.stderr.on("data", (data) => {
+ stderr += data.toString();
+ });
+
+ ffmpeg.on("close", (code) => {
+ if (code === 0) {
+ resolve();
+ } else {
+ reject(
+ new Error(`FFmpeg failed (code ${code}): ${stderr.slice(-500)}`)
+ );
+ }
+ });
+
+ ffmpeg.on("error", (err) => {
+ reject(err);
+ });
+ });
+}
+
+/**
+ * Extract audio from a single media file.
+ */
+async function extractAudioTrack(
+ srcPath: string,
+ outputPath: string,
+ playbackStart: number,
+ duration: number
+): Promise<boolean> {
+ const outputDir = dirname(outputPath);
+ if (!existsSync(outputDir)) {
+ mkdirSync(outputDir, { recursive: true });
+ }
+
+ const args: string[] = [];
+
+ if (playbackStart > 0) {
+ args.push("-ss", String(playbackStart));
+ }
+
+ if (duration > 0) {
+ args.push("-t", String(duration));
+ }
+
+ args.push(
+ "-i",
+ srcPath,
+ "-vn",
+ "-acodec",
+ "pcm_s16le",
+ "-ar",
+ "48000",
+ "-ac",
+ "2",
+ "-y",
+ outputPath
+ );
+
+ try {
+ await runFFmpeg(args);
+ return true;
+ } catch (err) {
+ console.warn(
+ `[AudioExtractor] Failed to extract audio from ${srcPath}: ${
+ err instanceof Error ? err.message : err
+ }`
+ );
+ return false;
+ }
+}
+
+/**
+ * Generate a silence audio file.
+ */
+async function generateSilence(
+ outputPath: string,
+ duration: number
+): Promise<void> {
+ const outputDir = dirname(outputPath);
+ if (!existsSync(outputDir)) {
+ mkdirSync(outputDir, { recursive: true });
+ }
+
+ await runFFmpeg([
+ "-f",
+ "lavfi",
+ "-i",
+ "anullsrc=r=48000:cl=stereo",
+ "-t",
+ String(duration),
+ "-acodec",
+ "pcm_s16le",
+ "-y",
+ outputPath,
+ ]);
+}
+
+/**
+ * Mix multiple audio tracks with timeline positioning.
+ */
+async function mixTracks(
+ tracks: AudioTrack[],
+ outputPath: string,
+ totalDuration: number
+): Promise<void> {
+ if (tracks.length === 0) {
+ await generateSilence(outputPath, totalDuration);
+ return;
+ }
+
+ const outputDir = dirname(outputPath);
+ if (!existsSync(outputDir)) {
+ mkdirSync(outputDir, { recursive: true });
+ }
+
+ const inputs: string[] = [];
+ const filterParts: string[] = [];
+
+ tracks.forEach((track, i) => {
+ inputs.push("-i", track.srcPath);
+
+ const delayMs = Math.round(track.start * 1000);
+ const trimDuration = track.duration > 0 ? track.duration : totalDuration;
+
+ filterParts.push(
+ `[${i}:a]atrim=0:${trimDuration},volume=${track.volume},adelay=${delayMs}|${delayMs},apad=whole_dur=${totalDuration}[a${i}]`
+ );
+ });
+
+ const mixInputs = tracks.map((_, i) => `[a${i}]`).join("");
+ const mixFilter = `${mixInputs}amix=inputs=${tracks.length}:duration=longest:normalize=0[out]`;
+ const fullFilter = [...filterParts, mixFilter].join(";");
+
+ const args = [
+ ...inputs,
+ "-filter_complex",
+ fullFilter,
+ "-map",
+ "[out]",
+ "-acodec",
+ "aac",
+ "-b:a",
+ "192k",
+ "-t",
+ String(totalDuration),
+ "-y",
+ outputPath,
+ ];
+
+ await runFFmpeg(args);
+}
+
+/**
+ * Process all audio for a composition.
+ *
+ * @param htmlPath - Path to the composition HTML (for parsing media elements)
+ * @param projectDir - Base directory for resolving relative media paths
+ * @param workDir - Temporary working directory for intermediate files
+ * @param outputPath - Final mixed audio output path
+ * @param totalDuration - Total composition duration in seconds
+ * @returns true if audio was produced, false if no audio elements found
+ */
+export async function processAudio(
+ htmlPath: string,
+ projectDir: string,
+ workDir: string,
+ outputPath: string,
+ totalDuration: number
+): Promise<boolean> {
+ const html = readFileSync(htmlPath, "utf-8");
+ const elements = parseAudioElements(html);
+
+ if (elements.length === 0) {
+ console.log("[AudioExtractor] No audio elements found");
+ return false;
+ }
+
+ console.log(
+ `[AudioExtractor] Processing ${elements.length} audio element(s)...`
+ );
+
+ if (!existsSync(workDir)) {
+ mkdirSync(workDir, { recursive: true });
+ }
+
+ const tracks: AudioTrack[] = [];
+
+ for (const element of elements) {
+ // Resolve source path relative to project directory
+ let srcPath = element.src;
+ if (!srcPath.startsWith("/") && !srcPath.startsWith("http")) {
+ srcPath = join(projectDir, srcPath);
+ }
+
+ if (!existsSync(srcPath)) {
+ console.warn(`[AudioExtractor] Source not found: ${srcPath}`);
+ continue;
+ }
+
+ const extractedPath = join(workDir, `${element.id}-extracted.wav`);
+ const success = await extractAudioTrack(
+ srcPath,
+ extractedPath,
+ element.mediaStart,
+ element.duration
+ );
+
+ if (success) {
+ tracks.push({
+ id: element.id,
+ srcPath: extractedPath,
+ start: element.start,
+ duration: element.duration,
+ mediaStart: element.mediaStart,
+ volume: element.volume,
+ });
+ }
+ }
+
+ console.log(
+ `[AudioExtractor] Mixing ${tracks.length} track(s) into final audio...`
+ );
+ await mixTracks(tracks, outputPath, totalDuration);
+
+ // Clean up work directory
+ try {
+ rmSync(workDir, { recursive: true, force: true });
+ } catch {
+ // Ignore cleanup errors
+ }
+
+ console.log("[AudioExtractor] Audio processing complete");
+ return true;
+}
diff --git a/packages/producer/src/services/audioMixer.ts b/packages/producer/src/services/audioMixer.ts
new file mode 100644
index 0000000000..12b310769c
--- /dev/null
+++ b/packages/producer/src/services/audioMixer.ts
@@ -0,0 +1,11 @@
+/**
+ * Re-exported from @hyperframes/engine.
+ * @see engine/src/services/audioMixer.ts for implementation.
+ */
+export {
+ parseAudioElements,
+ processCompositionAudio,
+ type AudioElement,
+ type AudioTrack,
+ type MixResult,
+} from "@hyperframes/engine";
diff --git a/packages/producer/src/services/browserManager.ts b/packages/producer/src/services/browserManager.ts
new file mode 100644
index 0000000000..b0c76112ee
--- /dev/null
+++ b/packages/producer/src/services/browserManager.ts
@@ -0,0 +1,14 @@
+/**
+ * Re-exported from @hyperframes/engine.
+ * @see engine/src/services/browserManager.ts for implementation.
+ */
+export {
+ acquireBrowser,
+ releaseBrowser,
+ resolveHeadlessShellPath,
+ buildChromeArgs,
+ ENABLE_BROWSER_POOL,
+ type BuildChromeArgsOptions,
+ type CaptureMode,
+ type AcquiredBrowser,
+} from "@hyperframes/engine";
diff --git a/packages/producer/src/services/chunkEncoder.ts b/packages/producer/src/services/chunkEncoder.ts
new file mode 100644
index 0000000000..87ce12a4be
--- /dev/null
+++ b/packages/producer/src/services/chunkEncoder.ts
@@ -0,0 +1,16 @@
+/**
+ * Re-exported from @hyperframes/engine.
+ * @see engine/src/services/chunkEncoder.ts for implementation.
+ */
+export {
+ encodeFramesFromDir,
+ encodeFramesChunkedConcat,
+ muxVideoWithAudio,
+ applyFaststart,
+ detectGpuEncoder,
+ ENCODER_PRESETS,
+ type EncoderOptions,
+ type EncodeResult,
+ type MuxResult,
+ type GpuEncoder,
+} from "@hyperframes/engine";
diff --git a/packages/producer/src/services/compilationRunner.ts b/packages/producer/src/services/compilationRunner.ts
new file mode 100644
index 0000000000..fa2ea2e0d3
--- /dev/null
+++ b/packages/producer/src/services/compilationRunner.ts
@@ -0,0 +1,157 @@
+/**
+ * Compilation Test Runner
+ *
+ * Orchestrates compilation tests: compiles input HTML, compares to golden files.
+ */
+
+import { readFileSync, writeFileSync, existsSync, mkdtempSync, rmSync, mkdirSync } from "fs";
+import { join } from "path";
+import { tmpdir } from "os";
+import { compileForRender } from "./htmlCompiler.js";
+import {
+ validateCompilation,
+ type CompilationValidationResult,
+} from "./compilationTester.js";
+
+export interface CompilationTestResult {
+ testId: string;
+ passed: boolean;
+ validation: CompilationValidationResult;
+ compilationTimeMs: number;
+ compiledHtmlPath?: string; // For --keep-temp
+}
+
+interface TestSuite {
+ id: string;
+ dir: string;
+ srcDir: string;
+ goldenMp4: string;
+ meta: Record<string, unknown>;
+}
+
+/**
+ * Run compilation test for a test suite.
+ * Compiles src/index.html and compares against compiled.html golden file.
+ */
+export async function runCompilationTest(
+ suite: TestSuite,
+ keepTemp: boolean
+): Promise<CompilationTestResult> {
+ const startTime = Date.now();
+
+ // Create temp directory for downloads (if HTML has HTTP URLs)
+ const tempDir = mkdtempSync(join(tmpdir(), `compile-test-${suite.id}-`));
+
+ try {
+ // Compile the input HTML
+ const inputHtmlPath = join(suite.srcDir, "index.html");
+ if (!existsSync(inputHtmlPath)) {
+ throw new Error(`Input HTML not found: ${inputHtmlPath}`);
+ }
+
+ const compiled = await compileForRender(
+ suite.srcDir,
+ inputHtmlPath,
+ tempDir
+ );
+
+ const actualHtml = compiled.html;
+
+ // Load golden compiled HTML
+ const goldenPath = join(suite.dir, "output", "compiled.html");
+ if (!existsSync(goldenPath)) {
+ throw new Error(`Golden compiled.html not found: ${goldenPath}`);
+ }
+
+ const goldenHtml = readFileSync(goldenPath, "utf-8");
+
+ // Validate
+ const validation = validateCompilation(actualHtml, goldenHtml);
+
+ const compilationTimeMs = Date.now() - startTime;
+
+ // Save compiled HTML if --keep-temp
+ let compiledHtmlPath: string | undefined;
+ if (keepTemp) {
+ compiledHtmlPath = join(tempDir, "compiled.html");
+ writeFileSync(compiledHtmlPath, actualHtml, "utf-8");
+ }
+
+ return {
+ testId: suite.id,
+ passed: validation.passed,
+ validation,
+ compilationTimeMs,
+ compiledHtmlPath,
+ };
+ } catch (error) {
+ const compilationTimeMs = Date.now() - startTime;
+ const errorMessage =
+ error instanceof Error ? error.message : String(error);
+
+ return {
+ testId: suite.id,
+ passed: false,
+ validation: {
+ passed: false,
+ actualElements: [],
+ goldenElements: [],
+ errors: [`Compilation failed: ${errorMessage}`],
+ warnings: [],
+ },
+ compilationTimeMs,
+ };
+ } finally {
+ // Cleanup temp directory unless --keep-temp
+ if (!keepTemp && existsSync(tempDir)) {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ }
+}
+
+/**
+ * Generate or update compiled.html golden file for a test suite.
+ * Compiles src/index.html and writes to compiled.html.
+ */
+export async function updateCompiledGolden(
+ suite: TestSuite
+): Promise<void> {
+ console.log(`[${suite.id}] Updating compiled.html golden file...`);
+
+ // Create temp directory for downloads
+ const tempDir = mkdtempSync(join(tmpdir(), `update-golden-${suite.id}-`));
+
+ try {
+ const inputHtmlPath = join(suite.srcDir, "index.html");
+ if (!existsSync(inputHtmlPath)) {
+ throw new Error(`Input HTML not found: ${inputHtmlPath}`);
+ }
+
+ // Compile the input HTML
+ const compiled = await compileForRender(
+ suite.srcDir,
+ inputHtmlPath,
+ tempDir
+ );
+
+ // Write to output/compiled.html
+ const outputDir = join(suite.dir, "output");
+ if (!existsSync(outputDir)) {
+ mkdirSync(outputDir, { recursive: true });
+ }
+ const goldenPath = join(outputDir, "compiled.html");
+ writeFileSync(goldenPath, compiled.html, "utf-8");
+
+ console.log(`[${suite.id}] ✓ Updated output/compiled.html (${compiled.videos.length} video(s), ${compiled.audios.length} audio(s))`);
+ } catch (error) {
+ const errorMessage =
+ error instanceof Error ? error.message : String(error);
+ console.error(`[${suite.id}] ✗ Failed to update compiled.html: ${errorMessage}`);
+ throw error;
+ } finally {
+ // Cleanup temp directory
+ if (existsSync(tempDir)) {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ }
+}
diff --git a/packages/producer/src/services/compilationTester.ts b/packages/producer/src/services/compilationTester.ts
new file mode 100644
index 0000000000..833de4784d
--- /dev/null
+++ b/packages/producer/src/services/compilationTester.ts
@@ -0,0 +1,355 @@
+/**
+ * Compilation Testing Service
+ *
+ * Validates that HTML compilation produces correct timing attributes.
+ * Compares compiled HTML against golden files using semantic attribute matching.
+ */
+
+import { parseHTML } from "linkedom";
+
+export interface CompiledElement {
+ id: string;
+ tagName: "video" | "audio" | "div";
+ src?: string;
+ dataStart: number;
+ dataEnd: number | null;
+ dataDuration: number | null;
+ dataHasAudio?: boolean;
+ dataMediaStart?: number;
+ compositionSrc?: string;
+}
+
+export interface CompilationValidationResult {
+ passed: boolean;
+ actualElements: CompiledElement[];
+ goldenElements: CompiledElement[];
+ errors: string[];
+ warnings: string[];
+}
+
+type CompositionStructure = {
+ id: string;
+ selfCompositionId: string | null;
+ descendantCompositionIds: string[];
+};
+
+const EPSILON = 0.001; // Tolerance for floating-point timing comparisons
+
+/**
+ * Parse HTML and extract all elements with timing attributes.
+ * Includes <video>, <audio>, and <div data-composition-src>.
+ */
+export function extractTimedElements(html: string): CompiledElement[] {
+ const elements: CompiledElement[] = [];
+
+ // Extract video elements
+ const videoRegex = /<video[^>]*>/gi;
+ let match;
+
+ while ((match = videoRegex.exec(html)) !== null) {
+ const fullTag = match[0];
+ const idMatch = fullTag.match(/id=["']([^"']+)["']/);
+ if (!idMatch) continue;
+
+ const srcMatch = fullTag.match(/src=["']([^"']+)["']/);
+ const startMatch = fullTag.match(/data-start=["']([^"']+)["']/);
+ const endMatch = fullTag.match(/data-end=["']([^"']+)["']/);
+ const durationMatch = fullTag.match(/data-duration=["']([^"']+)["']/);
+ const mediaStartMatch = fullTag.match(/data-media-start=["']([^"']+)["']/);
+ const hasAudioMatch = fullTag.match(/data-has-audio=["']([^"']+)["']/);
+
+ elements.push({
+ id: idMatch[1] ?? "",
+ tagName: "video",
+ src: srcMatch?.[1],
+ dataStart: startMatch ? parseFloat(startMatch[1] ?? "") : 0,
+ dataEnd: endMatch ? parseFloat(endMatch[1] ?? "") : null,
+ dataDuration: durationMatch ? parseFloat(durationMatch[1] ?? "") : null,
+ dataMediaStart: mediaStartMatch ? parseFloat(mediaStartMatch[1] ?? "") : undefined,
+ dataHasAudio: hasAudioMatch ? hasAudioMatch[1] === "true" : undefined,
+ });
+ }
+
+ // Extract audio elements
+ const audioRegex = /<audio[^>]*>/gi;
+ while ((match = audioRegex.exec(html)) !== null) {
+ const fullTag = match[0];
+ const idMatch = fullTag.match(/id=["']([^"']+)["']/);
+ if (!idMatch) continue;
+
+ const srcMatch = fullTag.match(/src=["']([^"']+)["']/);
+ const startMatch = fullTag.match(/data-start=["']([^"']+)["']/);
+ const endMatch = fullTag.match(/data-end=["']([^"']+)["']/);
+ const durationMatch = fullTag.match(/data-duration=["']([^"']+)["']/);
+ const mediaStartMatch = fullTag.match(/data-media-start=["']([^"']+)["']/);
+
+ elements.push({
+ id: idMatch[1] ?? "",
+ tagName: "audio",
+ src: srcMatch?.[1],
+ dataStart: startMatch ? parseFloat(startMatch[1] ?? "") : 0,
+ dataEnd: endMatch ? parseFloat(endMatch[1] ?? "") : null,
+ dataDuration: durationMatch ? parseFloat(durationMatch[1] ?? "") : null,
+ dataMediaStart: mediaStartMatch ? parseFloat(mediaStartMatch[1] ?? "") : undefined,
+ });
+ }
+
+ // Extract composition elements (div with data-composition-src)
+ const compRegex = /<div[^>]*data-composition-src[^>]*>/gi;
+ while ((match = compRegex.exec(html)) !== null) {
+ const fullTag = match[0];
+ const idMatch = fullTag.match(/id=["']([^"']+)["']/);
+ if (!idMatch) continue;
+
+ const compositionSrcMatch = fullTag.match(/data-composition-src=["']([^"']+)["']/);
+ const startMatch = fullTag.match(/data-start=["']([^"']+)["']/);
+ const endMatch = fullTag.match(/data-end=["']([^"']+)["']/);
+ const durationMatch = fullTag.match(/data-duration=["']([^"']+)["']/);
+
+ elements.push({
+ id: idMatch[1] ?? "",
+ tagName: "div",
+ compositionSrc: compositionSrcMatch?.[1],
+ dataStart: startMatch ? parseFloat(startMatch[1] ?? "") : 0,
+ dataEnd: endMatch ? parseFloat(endMatch[1] ?? "") : null,
+ dataDuration: durationMatch ? parseFloat(durationMatch[1] ?? "") : null,
+ });
+ }
+
+ return elements;
+}
+
+function extractCompositionStructures(html: string): CompositionStructure[] {
+ const { document } = parseHTML(html);
+ const elements = Array.from(document.querySelectorAll<HTMLElement>("[id]"));
+
+ return elements.map((element) => {
+ const descendantCompositionIds = Array.from(
+ element.querySelectorAll<HTMLElement>("[data-composition-id]"),
+ )
+ .filter((candidate) => candidate !== element)
+ .map((candidate) => candidate.getAttribute("data-composition-id") || "")
+ .filter(Boolean)
+ .sort();
+
+ return {
+ id: element.id,
+ selfCompositionId: element.getAttribute("data-composition-id"),
+ descendantCompositionIds,
+ };
+ });
+}
+
+/**
+ * Validate a single element's timing attributes.
+ * Returns array of error messages (empty if valid).
+ */
+function validateElementTiming(element: CompiledElement, label: string): string[] {
+ const errors: string[] = [];
+
+ // For video and audio, require data-end and data-duration
+ if (element.tagName === "video" || element.tagName === "audio") {
+ if (element.dataEnd === null) {
+ errors.push(`${label} [${element.id}]: missing data-end attribute`);
+ }
+ if (element.dataDuration === null) {
+ errors.push(`${label} [${element.id}]: missing data-duration attribute`);
+ }
+
+ // Check timing math: data-end should equal data-start + data-duration
+ if (element.dataEnd !== null && element.dataDuration !== null) {
+ const computed = element.dataStart + element.dataDuration;
+ if (Math.abs(element.dataEnd - computed) > EPSILON) {
+ errors.push(
+ `${label} [${element.id}]: data-end (${element.dataEnd}) != data-start (${element.dataStart}) + data-duration (${element.dataDuration}) = ${computed}`
+ );
+ }
+ }
+ }
+
+ // Video-specific: require data-has-audio
+ if (element.tagName === "video" && element.dataHasAudio === undefined) {
+ errors.push(`${label} [${element.id}]: missing data-has-audio attribute`);
+ }
+
+ return errors;
+}
+
+/**
+ * Compare two elements and return differences.
+ * Compares timing attributes with epsilon tolerance.
+ */
+function compareElements(
+ actual: CompiledElement,
+ golden: CompiledElement
+): string[] {
+ const errors: string[] = [];
+
+ // Compare tag names
+ if (actual.tagName !== golden.tagName) {
+ errors.push(
+ `[${actual.id}]: tagName mismatch (actual: ${actual.tagName}, golden: ${golden.tagName})`
+ );
+ return errors; // Don't continue if tag mismatch
+ }
+
+ // Compare data-start (should be exact)
+ if (Math.abs(actual.dataStart - golden.dataStart) > EPSILON) {
+ errors.push(
+ `[${actual.id}]: data-start mismatch (actual: ${actual.dataStart}, golden: ${golden.dataStart})`
+ );
+ }
+
+ // Compare data-end with epsilon tolerance
+ if (golden.dataEnd !== null) {
+ if (actual.dataEnd === null) {
+ errors.push(`[${actual.id}]: missing data-end (golden has: ${golden.dataEnd})`);
+ } else if (Math.abs(actual.dataEnd - golden.dataEnd) > EPSILON) {
+ errors.push(
+ `[${actual.id}]: data-end mismatch (actual: ${actual.dataEnd}, golden: ${golden.dataEnd})`
+ );
+ }
+ }
+
+ // Compare data-duration with epsilon tolerance
+ if (golden.dataDuration !== null) {
+ if (actual.dataDuration === null) {
+ errors.push(
+ `[${actual.id}]: missing data-duration (golden has: ${golden.dataDuration})`
+ );
+ } else if (Math.abs(actual.dataDuration - golden.dataDuration) > EPSILON) {
+ errors.push(
+ `[${actual.id}]: data-duration mismatch (actual: ${actual.dataDuration}, golden: ${golden.dataDuration})`
+ );
+ }
+ }
+
+ // Compare data-has-audio (video only)
+ if (actual.tagName === "video") {
+ if (actual.dataHasAudio !== golden.dataHasAudio) {
+ errors.push(
+ `[${actual.id}]: data-has-audio mismatch (actual: ${actual.dataHasAudio}, golden: ${golden.dataHasAudio})`
+ );
+ }
+ }
+
+ // Compare composition-src (composition only)
+ if (actual.tagName === "div" && actual.compositionSrc !== golden.compositionSrc) {
+ errors.push(
+ `[${actual.id}]: data-composition-src mismatch (actual: ${actual.compositionSrc}, golden: ${golden.compositionSrc})`
+ );
+ }
+
+ return errors;
+}
+
+/**
+ * Validate compiled HTML against golden HTML.
+ * Returns detailed validation result with errors and warnings.
+ */
+export function validateCompilation(
+ actualHtml: string,
+ goldenHtml: string
+): CompilationValidationResult {
+ const actualElements = extractTimedElements(actualHtml);
+ const goldenElements = extractTimedElements(goldenHtml);
+ const actualStructures = extractCompositionStructures(actualHtml);
+ const goldenStructures = extractCompositionStructures(goldenHtml);
+
+ const errors: string[] = [];
+ const warnings: string[] = [];
+
+ // Validate actual element timings
+ for (const element of actualElements) {
+ const timingErrors = validateElementTiming(element, "actual");
+ errors.push(...timingErrors);
+ }
+
+ // Validate golden element timings (sanity check)
+ for (const element of goldenElements) {
+ const timingErrors = validateElementTiming(element, "golden");
+ if (timingErrors.length > 0) {
+ warnings.push(
+ `Golden file has invalid timing: ${timingErrors.join(", ")}`
+ );
+ }
+ }
+
+ // Create maps for comparison
+ const actualMap = new Map<string, CompiledElement>();
+ const goldenMap = new Map<string, CompiledElement>();
+ const actualStructureMap = new Map<string, CompositionStructure>();
+ const goldenStructureMap = new Map<string, CompositionStructure>();
+
+ for (const el of actualElements) {
+ actualMap.set(el.id, el);
+ }
+
+ for (const el of goldenElements) {
+ goldenMap.set(el.id, el);
+ }
+
+ for (const structure of actualStructures) {
+ actualStructureMap.set(structure.id, structure);
+ }
+
+ for (const structure of goldenStructures) {
+ goldenStructureMap.set(structure.id, structure);
+ }
+
+ // Check for missing elements (in golden but not in actual)
+ for (const [id, goldenEl] of goldenMap) {
+ if (!actualMap.has(id)) {
+ errors.push(
+ `Missing element [${id}] (present in golden, not in actual)`
+ );
+ }
+ }
+
+ // Check for extra elements (in actual but not in golden)
+ for (const [id, actualEl] of actualMap) {
+ if (!goldenMap.has(id)) {
+ warnings.push(
+ `Extra element [${id}] <${actualEl.tagName}> (present in actual, not in golden)`
+ );
+ }
+ }
+
+ // Compare matching elements
+ for (const [id, actualEl] of actualMap) {
+ const goldenEl = goldenMap.get(id);
+ if (!goldenEl) continue;
+
+ const compareErrors = compareElements(actualEl, goldenEl);
+ errors.push(...compareErrors);
+ }
+
+ for (const [id, goldenStructure] of goldenStructureMap) {
+ const actualStructure = actualStructureMap.get(id);
+ if (!actualStructure) continue;
+
+ if (actualStructure.selfCompositionId !== goldenStructure.selfCompositionId) {
+ errors.push(
+ `[${id}]: data-composition-id mismatch (actual: ${actualStructure.selfCompositionId ?? "null"}, golden: ${goldenStructure.selfCompositionId ?? "null"})`,
+ );
+ }
+
+ const actualDescendants = actualStructure.descendantCompositionIds.join(",");
+ const goldenDescendants = goldenStructure.descendantCompositionIds.join(",");
+ if (actualDescendants !== goldenDescendants) {
+ errors.push(
+ `[${id}]: descendant composition ids mismatch (actual: ${actualDescendants || "none"}, golden: ${goldenDescendants || "none"})`,
+ );
+ }
+ }
+
+ const passed = errors.length === 0;
+
+ return {
+ passed,
+ actualElements,
+ goldenElements,
+ errors,
+ warnings,
+ };
+}
diff --git a/packages/producer/src/services/deterministicFonts.ts b/packages/producer/src/services/deterministicFonts.ts
new file mode 100644
index 0000000000..c7b8e4ae68
--- /dev/null
+++ b/packages/producer/src/services/deterministicFonts.ts
@@ -0,0 +1,309 @@
+import { readdirSync, readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { createRequire } from "node:module";
+import { parseHTML } from "linkedom";
+
+const require = createRequire(import.meta.url);
+
+type FontFaceSpec = {
+ weight: string;
+ style?: "normal" | "italic";
+};
+
+type CanonicalFontSpec = {
+ packageName: string;
+ faces: FontFaceSpec[];
+};
+
+const GENERIC_FAMILIES = new Set([
+ "sans-serif",
+ "serif",
+ "monospace",
+ "cursive",
+ "fantasy",
+ "system-ui",
+ "ui-sans-serif",
+ "ui-serif",
+ "ui-monospace",
+ "emoji",
+ "math",
+ "fangsong",
+ "-apple-system",
+ "blinkmacsystemfont",
+]);
+
+const CANONICAL_FONTS: Record<string, CanonicalFontSpec> = {
+ inter: {
+ packageName: "@fontsource/inter",
+ faces: [
+ { weight: "400" },
+ { weight: "700" },
+ { weight: "900" },
+ ],
+ },
+ montserrat: {
+ packageName: "@fontsource/montserrat",
+ faces: [
+ { weight: "400" },
+ { weight: "700" },
+ { weight: "900" },
+ ],
+ },
+ outfit: {
+ packageName: "@fontsource/outfit",
+ faces: [
+ { weight: "400" },
+ { weight: "700" },
+ { weight: "900" },
+ ],
+ },
+ nunito: {
+ packageName: "@fontsource/nunito",
+ faces: [
+ { weight: "400" },
+ { weight: "700" },
+ { weight: "900" },
+ ],
+ },
+ oswald: {
+ packageName: "@fontsource/oswald",
+ faces: [
+ { weight: "400" },
+ { weight: "700" },
+ ],
+ },
+ "league-gothic": {
+ packageName: "@fontsource/league-gothic",
+ faces: [{ weight: "400" }],
+ },
+ "archivo-black": {
+ packageName: "@fontsource/archivo-black",
+ faces: [{ weight: "400" }],
+ },
+ "space-mono": {
+ packageName: "@fontsource/space-mono",
+ faces: [
+ { weight: "400" },
+ { weight: "700" },
+ ],
+ },
+ "ibm-plex-mono": {
+ packageName: "@fontsource/ibm-plex-mono",
+ faces: [
+ { weight: "400" },
+ { weight: "700" },
+ ],
+ },
+ "jetbrains-mono": {
+ packageName: "@fontsource/jetbrains-mono",
+ faces: [
+ { weight: "400" },
+ { weight: "700" },
+ ],
+ },
+ "eb-garamond": {
+ packageName: "@fontsource/eb-garamond",
+ faces: [
+ { weight: "400" },
+ { weight: "700" },
+ ],
+ },
+};
+
+const FONT_ALIASES: Record<string, keyof typeof CANONICAL_FONTS> = {
+ inter: "inter",
+ "helvetica neue": "inter",
+ helvetica: "inter",
+ arial: "inter",
+ "helvetica bold": "inter",
+ montserrat: "montserrat",
+ futura: "montserrat",
+ "din alternate": "montserrat",
+ "arial black": "montserrat",
+ outfit: "outfit",
+ nunito: "nunito",
+ oswald: "oswald",
+ "bebas neue": "league-gothic",
+ "league gothic": "league-gothic",
+ "archivo black": "archivo-black",
+ "space mono": "space-mono",
+ "ibm plex mono": "ibm-plex-mono",
+ "jetbrains mono": "jetbrains-mono",
+ "courier new": "jetbrains-mono",
+ courier: "jetbrains-mono",
+ "eb garamond": "eb-garamond",
+ garamond: "eb-garamond",
+};
+
+const PACKAGE_ROOT_CACHE = new Map<string, string>();
+const FONT_DATA_URI_CACHE = new Map<string, string>();
+
+function normalizeFamilyName(family: string): string {
+ return family.trim().replace(/^['"]|['"]$/g, "").trim().toLowerCase();
+}
+
+function packageRoot(packageName: string): string {
+ const cached = PACKAGE_ROOT_CACHE.get(packageName);
+ if (cached) {
+ return cached;
+ }
+
+ const packageJsonPath = require.resolve(`${packageName}/package.json`);
+ const root = dirname(packageJsonPath);
+ PACKAGE_ROOT_CACHE.set(packageName, root);
+ return root;
+}
+
+function resolveFontFile(packageName: string, weight: string, style: "normal" | "italic" = "normal"): string {
+ const root = packageRoot(packageName);
+ const filesDir = join(root, "files");
+ const slug = packageName.replace("@fontsource/", "");
+ const files = readdirSync(filesDir);
+
+ const exact = `${slug}-latin-${weight}-${style}.woff2`;
+ if (files.includes(exact)) {
+ return join(filesDir, exact);
+ }
+
+ const relaxed = files.find((file) => {
+ return file.endsWith(`-${weight}-${style}.woff2`) && file.includes("-latin-");
+ });
+ if (relaxed) {
+ return join(filesDir, relaxed);
+ }
+
+ throw new Error(`No deterministic font asset found for ${packageName} weight=${weight} style=${style}`);
+}
+
+function fontDataUri(packageName: string, weight: string, style: "normal" | "italic" = "normal"): string {
+ const key = `${packageName}:${weight}:${style}`;
+ const cached = FONT_DATA_URI_CACHE.get(key);
+ if (cached) {
+ return cached;
+ }
+
+ const fontPath = resolveFontFile(packageName, weight, style);
+ const content = readFileSync(fontPath);
+ const uri = `data:font/woff2;base64,${content.toString("base64")}`;
+ FONT_DATA_URI_CACHE.set(key, uri);
+ return uri;
+}
+
+function extractExistingFontFaces(html: string): Set<string> {
+ const families = new Set<string>();
+ const fontFaceRegex = /@font-face\s*\{[\s\S]*?font-family\s*:\s*([^;]+);[\s\S]*?\}/gi;
+ for (const match of html.matchAll(fontFaceRegex)) {
+ const raw = match[1] || "";
+ const normalized = normalizeFamilyName(raw);
+ if (normalized) {
+ families.add(normalized);
+ }
+ }
+ return families;
+}
+
+function extractRequestedFontFamilies(html: string): Map<string, string> {
+ const requested = new Map<string, string>();
+ const addFamilyList = (value: string) => {
+ for (const family of value.split(",")) {
+ const originalCase = family.trim().replace(/^['"]|['"]$/g, "").trim();
+ const normalized = originalCase.toLowerCase();
+ if (!normalized || GENERIC_FAMILIES.has(normalized)) {
+ continue;
+ }
+ if (!requested.has(normalized)) {
+ requested.set(normalized, originalCase);
+ }
+ }
+ };
+
+ const fontFamilyRegex = /font-family\s*:\s*([^;}{]+)[;}]?/gi;
+ for (const match of html.matchAll(fontFamilyRegex)) {
+ addFamilyList(match[1] || "");
+ }
+
+ const dataFontFamilyRegex = /data-font-family=["']([^"']+)["']/gi;
+ for (const match of html.matchAll(dataFontFamilyRegex)) {
+ addFamilyList(match[1] || "");
+ }
+
+ return requested;
+}
+
+function buildFontFaceCss(requestedFamilies: Map<string, string>): { css: string; unresolved: string[] } {
+ const rules: string[] = [];
+ const unresolved: string[] = [];
+
+ for (const [normalizedFamily, originalCaseFamily] of requestedFamilies) {
+ const canonicalKey = FONT_ALIASES[normalizedFamily];
+ if (!canonicalKey) {
+ unresolved.push(originalCaseFamily);
+ continue;
+ }
+
+ const canonical = CANONICAL_FONTS[canonicalKey];
+ if (!canonical) continue;
+ for (const face of canonical.faces) {
+ const style = face.style || "normal";
+ const src = fontDataUri(canonical.packageName, face.weight, style);
+ rules.push(
+ [
+ "@font-face {",
+ ` font-family: "${originalCaseFamily}";`,
+ ` src: url("${src}") format("woff2");`,
+ ` font-style: ${style};`,
+ ` font-weight: ${face.weight};`,
+ " font-display: block;",
+ "}",
+ ].join("\n"),
+ );
+ }
+ }
+
+ return {
+ css: rules.join("\n\n").trim(),
+ unresolved: unresolved.sort(),
+ };
+}
+
+export function injectDeterministicFontFaces(html: string): string {
+ const existingFaces = extractExistingFontFaces(html);
+ const requestedFamilies = extractRequestedFontFamilies(html);
+ const pendingFamilies = new Map<string, string>();
+
+ for (const [normalizedFamily, originalCaseFamily] of requestedFamilies) {
+ if (!existingFaces.has(normalizedFamily)) {
+ pendingFamilies.set(normalizedFamily, originalCaseFamily);
+ }
+ }
+
+ if (pendingFamilies.size === 0) {
+ return html;
+ }
+
+ const { css, unresolved } = buildFontFaceCss(pendingFamilies);
+ if (!css) {
+ if (unresolved.length > 0) {
+ console.warn(`[Compiler] No deterministic font mapping for: ${unresolved.join(", ")}`);
+ }
+ return html;
+ }
+
+ const { document } = parseHTML(html);
+ const head = document.querySelector("head");
+ if (!head) {
+ return html;
+ }
+
+ const styleEl = document.createElement("style");
+ styleEl.setAttribute("data-hyperframes-deterministic-fonts", "true");
+ styleEl.textContent = css;
+ head.insertBefore(styleEl, head.firstChild);
+
+ console.log(`[Compiler] Injected deterministic @font-face rules for ${pendingFamilies.size - unresolved.length} requested font families`);
+ if (unresolved.length > 0) {
+ console.warn(`[Compiler] Unresolved font families left dynamic: ${unresolved.join(", ")}`);
+ }
+
+ return document.toString();
+}
diff --git a/packages/producer/src/services/fileServer.ts b/packages/producer/src/services/fileServer.ts
new file mode 100644
index 0000000000..f4f0dfbfe4
--- /dev/null
+++ b/packages/producer/src/services/fileServer.ts
@@ -0,0 +1,326 @@
+/**
+ * File Server for Render Mode
+ *
+ * Lightweight HTTP server that serves the project directory inside Docker.
+ * Key responsibility: inject the verified Hyperframe runtime + render mode extension
+ * into index.html on-the-fly, so Puppeteer can load the composition with
+ * all relative URLs (compositions, CSS, JS, assets) resolving correctly.
+ */
+
+import { Hono } from "hono";
+import { serve } from "@hono/node-server";
+import { readFileSync, existsSync, statSync } from "node:fs";
+import { join, extname } from "node:path";
+import { getVerifiedHyperframeRuntimeSource } from "./hyperframeRuntimeLoader.js";
+
+const MIME_TYPES: Record<string, string> = {
+ ".html": "text/html; charset=utf-8",
+ ".css": "text/css; charset=utf-8",
+ ".js": "application/javascript; charset=utf-8",
+ ".json": "application/json; charset=utf-8",
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".svg": "image/svg+xml",
+ ".webp": "image/webp",
+ ".mp4": "video/mp4",
+ ".webm": "video/webm",
+ ".mp3": "audio/mpeg",
+ ".wav": "audio/wav",
+ ".ogg": "audio/ogg",
+ ".aac": "audio/aac",
+ ".woff": "font/woff",
+ ".woff2": "font/woff2",
+ ".ttf": "font/ttf",
+ ".otf": "font/otf",
+};
+
+/**
+ * Render mode extension -- adds renderSeek() for frame-accurate seeking
+ * without media sync (videos are replaced with frame images during render).
+ */
+const RENDER_SEEK_MODE =
+ process.env.PRODUCER_RUNTIME_RENDER_SEEK_MODE === "strict-boundary"
+ ? "strict-boundary"
+ : "preview-phase";
+const RENDER_SEEK_DIAGNOSTICS = process.env.PRODUCER_DEBUG_SEEK_DIAGNOSTICS === "true";
+const RENDER_SEEK_STEP = Math.max(1 / 600, Number(process.env.PRODUCER_RENDER_SEEK_STEP || 1 / 120));
+const RENDER_SEEK_OFFSET_FRACTION = Math.max(
+ 0,
+ Math.min(0.95, Number(process.env.PRODUCER_RUNTIME_RENDER_SEEK_OFFSET_FRACTION || 0.5)),
+);
+
+const RENDER_MODE_SCRIPT = `(function() {
+ var __seekMode = ${JSON.stringify(RENDER_SEEK_MODE)};
+ var __seekDiagnostics = ${RENDER_SEEK_DIAGNOSTICS ? "true" : "false"};
+ var __seekStep = ${RENDER_SEEK_STEP};
+ var __seekOffsetFraction = ${RENDER_SEEK_OFFSET_FRACTION};
+ window.__HF_EXPORT_RENDER_SEEK_CONFIG = {
+ mode: __seekMode,
+ diagnostics: __seekDiagnostics,
+ step: __seekStep,
+ offsetFraction: __seekOffsetFraction,
+ owner: "runtime",
+ };
+ function installMediaFallbackPlayer() {
+ if (document.querySelector('[data-composition-id]')) return false;
+ var mediaEls = Array.from(document.querySelectorAll('video, audio'));
+ if (!mediaEls.length) return false;
+
+ var isPlaying = false;
+ var currentTime = 0;
+ function fallbackDuration() {
+ var maxDuration = 0;
+ for (var i = 0; i < mediaEls.length; i++) {
+ var d = Number(mediaEls[i].duration);
+ if (isFinite(d) && d > maxDuration) maxDuration = d;
+ }
+ return Math.max(0, maxDuration);
+ }
+ function syncFallbackMedia(time, playing) {
+ for (var i = 0; i < mediaEls.length; i++) {
+ var media = mediaEls[i];
+ var existing = Number(media.currentTime) || 0;
+ if (Math.abs(existing - time) > 0.3) {
+ try { media.currentTime = time; } catch (e) {}
+ }
+ if (playing) {
+ if (media.paused) {
+ media.play().catch(function() {});
+ }
+ } else if (!media.paused) {
+ media.pause();
+ }
+ }
+ }
+
+ var basePlayer = window.__player && typeof window.__player === 'object' ? window.__player : {};
+ window.__player = {
+ ...basePlayer,
+ _timeline: null,
+ play: function() {
+ isPlaying = true;
+ syncFallbackMedia(currentTime, true);
+ },
+ pause: function() {
+ isPlaying = false;
+ syncFallbackMedia(currentTime, false);
+ },
+ seek: function(time) {
+ var safeTime = Math.max(0, Number(time) || 0);
+ currentTime = safeTime;
+ isPlaying = false;
+ syncFallbackMedia(safeTime, false);
+ },
+ renderSeek: function(time) {
+ var safeTime = Math.max(0, Number(time) || 0);
+ currentTime = safeTime;
+ isPlaying = false;
+ syncFallbackMedia(safeTime, false);
+ },
+ getTime: function() {
+ var primary = mediaEls[0];
+ if (!primary) return currentTime;
+ var t = Number(primary.currentTime);
+ return isFinite(t) ? t : currentTime;
+ },
+ getDuration: function() {
+ return fallbackDuration();
+ },
+ isPlaying: function() {
+ return isPlaying;
+ },
+ };
+ window.__playerReady = true;
+ window.__renderReady = true;
+ return true;
+ }
+
+ function waitForPlayer() {
+ var hasComposition = Boolean(document.querySelector('[data-composition-id]'));
+ if (hasComposition) {
+ if (window.__player && typeof window.__player.renderSeek === "function") {
+ window.__playerReady = true;
+ window.__renderReady = true;
+ return;
+ }
+ setTimeout(waitForPlayer, 50);
+ return;
+ }
+ if (installMediaFallbackPlayer()) {
+ return;
+ }
+ setTimeout(waitForPlayer, 50);
+ }
+ waitForPlayer();
+})();`;
+
+/**
+ * Bridge script: maps window.__player (Hyperframe runtime) → window.__hf (engine protocol).
+ * Injected after RENDER_MODE_SCRIPT so the engine's frameCapture can find window.__hf.
+ */
+const HF_BRIDGE_SCRIPT = `(function() {
+ function bridge() {
+ var p = window.__player;
+ if (!p || typeof p.renderSeek !== "function" || typeof p.getDuration !== "function") {
+ return false;
+ }
+ window.__hf = {
+ get duration() { return p.getDuration(); },
+ seek: function(t) { p.renderSeek(t); },
+ };
+ return true;
+ }
+ if (bridge()) return;
+ var iv = setInterval(function() {
+ if (bridge()) clearInterval(iv);
+ }, 50);
+})();`;
+
+function stripEmbeddedRuntimeScripts(html: string): string {
+ if (!html) return html;
+ const scriptRe = /<script\b[^>]*>[\s\S]*?<\/script>/gi;
+ const runtimeSrcMarkers = [
+ "hyperframe.runtime.iife.js",
+ "hyperframe-runtime.modular-runtime.inline.js",
+ "data-hyperframes-preview-runtime",
+ ];
+ const runtimeInlineMarkers = [
+ "__hyperframeRuntimeBootstrapped",
+ "__hyperframeRuntime",
+ "__hyperframeRuntimeTeardown",
+ "window.__player =",
+ "window.__playerReady",
+ "window.__renderReady",
+ ];
+
+ const shouldStrip = (block: string): boolean => {
+ const lowered = block.toLowerCase();
+ for (const marker of runtimeSrcMarkers) {
+ if (lowered.includes(marker.toLowerCase())) {
+ return true;
+ }
+ }
+ for (const marker of runtimeInlineMarkers) {
+ if (block.includes(marker)) {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ return html.replace(scriptRe, (block) => (shouldStrip(block) ? "" : block));
+}
+
+function injectScriptsIntoHtml(
+ html: string,
+ headScripts: string[],
+ bodyScripts: string[],
+ stripEmbedded: boolean,
+): string {
+ if (stripEmbedded) {
+ html = stripEmbeddedRuntimeScripts(html);
+ }
+
+ if (headScripts.length > 0) {
+ const headTags = headScripts.map((src) => `<script>${src}</script>`).join("\n");
+ if (html.includes("</head>")) {
+ // Use function replacement to avoid $& interpolation in runtime source
+ html = html.replace("</head>", () => `${headTags}\n</head>`);
+ } else if (html.includes("<body")) {
+ html = html.replace("<body", () => `${headTags}\n<body`);
+ } else {
+ html = headTags + "\n" + html;
+ }
+ }
+
+ if (bodyScripts.length > 0) {
+ const bodyTags = bodyScripts.map((src) => `<script>${src}</script>`).join("\n");
+ if (html.includes("</body>")) {
+ // Use function replacement to avoid $& interpolation in runtime source
+ html = html.replace("</body>", () => `${bodyTags}\n</body>`);
+ } else {
+ html = html + "\n" + bodyTags;
+ }
+ }
+
+ return html;
+}
+
+export interface FileServerOptions {
+ projectDir: string;
+ compiledDir?: string;
+ port?: number;
+ /** Scripts injected into <head> of index.html. Default: verified Hyperframe runtime. */
+ headScripts?: string[];
+ /** Scripts injected before </body> of index.html. Default: render mode extension. */
+ bodyScripts?: string[];
+ /** Strip embedded runtime scripts from HTML before injection. Default: true. */
+ stripEmbeddedRuntime?: boolean;
+}
+
+export interface FileServerHandle {
+ url: string;
+ port: number;
+ close: () => void;
+}
+
+export function createFileServer(options: FileServerOptions): Promise<FileServerHandle> {
+ const { projectDir, compiledDir, port = 0, stripEmbeddedRuntime = true } = options;
+
+ // Default scripts: Hyperframe runtime in <head>, render mode in </body>
+ const headScripts = options.headScripts ?? [getVerifiedHyperframeRuntimeSource()];
+ const bodyScripts = options.bodyScripts ?? [RENDER_MODE_SCRIPT, HF_BRIDGE_SCRIPT];
+
+
+ const app = new Hono();
+
+ app.get("/*", (c) => {
+ let requestPath = c.req.path;
+ if (requestPath === "/") requestPath = "/index.html";
+
+ // Remove leading slash
+ const relativePath = requestPath.replace(/^\//, "");
+ const compiledPath = compiledDir ? join(compiledDir, relativePath) : null;
+ const hasCompiledFile = Boolean(
+ compiledPath && existsSync(compiledPath) && statSync(compiledPath).isFile()
+ );
+ const filePath = hasCompiledFile ? (compiledPath as string) : join(projectDir, relativePath);
+
+ if (!existsSync(filePath) || !statSync(filePath).isFile()) {
+ return c.text("Not found", 404);
+ }
+
+ const ext = extname(filePath).toLowerCase();
+ const contentType = MIME_TYPES[ext] || "application/octet-stream";
+
+ if (ext === ".html") {
+ const rawHtml = readFileSync(filePath, "utf-8");
+ const isIndex = relativePath === "index.html";
+ const html = isIndex
+ ? injectScriptsIntoHtml(rawHtml, headScripts, bodyScripts, stripEmbeddedRuntime)
+ : rawHtml;
+ return c.text(html, 200, { "Content-Type": contentType });
+ }
+
+ const content = readFileSync(filePath);
+ return new Response(content, {
+ status: 200,
+ headers: { "Content-Type": contentType },
+ });
+ });
+
+ return new Promise((resolve) => {
+ const server = serve({ fetch: app.fetch, port }, (info) => {
+ const actualPort = info.port;
+ const url = `http://localhost:${actualPort}`;
+
+ resolve({
+ url,
+ port: actualPort,
+ close: () => server.close(),
+ });
+ });
+ });
+}
diff --git a/packages/producer/src/services/frameCapture.ts b/packages/producer/src/services/frameCapture.ts
new file mode 100644
index 0000000000..784b89d933
--- /dev/null
+++ b/packages/producer/src/services/frameCapture.ts
@@ -0,0 +1,20 @@
+/**
+ * Re-exported from @hyperframes/engine.
+ * @see engine/src/services/frameCapture.ts for implementation.
+ */
+export {
+ createCaptureSession,
+ initializeSession,
+ closeCaptureSession,
+ captureFrame,
+ captureFrameToBuffer,
+ getCompositionDuration,
+ getCapturePerfSummary,
+ prepareCaptureSessionForReuse,
+ type CaptureOptions,
+ type CaptureResult,
+ type CaptureBufferResult,
+ type CapturePerfSummary,
+ type CaptureSession,
+ type BeforeCaptureHook,
+} from "@hyperframes/engine";
diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts
new file mode 100644
index 0000000000..88b261b46c
--- /dev/null
+++ b/packages/producer/src/services/htmlCompiler.ts
@@ -0,0 +1,805 @@
+/**
+ * HTML Compiler for Producer
+ *
+ * Two-phase compilation that guarantees every media element has data-end:
+ * 1. Static pass via core's compileTimingAttrs() (data-start + data-duration → data-end)
+ * 2. ffprobe resolution for elements without data-duration
+ *
+ * Also handles sub-compositions referenced via data-composition-src,
+ * recursively extracting nested media from sub-sub-compositions.
+ */
+
+import { readFileSync, existsSync, mkdirSync } from "fs";
+import { join, dirname, resolve } from "path";
+import { parseHTML } from "linkedom";
+import {
+ compileTimingAttrs,
+ injectDurations,
+ extractResolvedMedia,
+ clampDurations,
+ type ResolvedDuration,
+ type UnresolvedElement,
+} from "@hyperframes/core";
+import { extractVideoMetadata, extractAudioMetadata } from "../utils/ffprobe.js";
+import { parseVideoElements, type VideoElement, parseAudioElements, type AudioElement } from "@hyperframes/engine";
+import { downloadToTemp, isHttpUrl } from "../utils/urlDownloader.js";
+import type { Page } from "puppeteer-core";
+import { injectDeterministicFontFaces } from "./deterministicFonts.js";
+
+export interface CompiledComposition {
+ html: string;
+ subCompositions: Map<string, string>;
+ videos: VideoElement[];
+ audios: AudioElement[];
+ unresolvedCompositions: UnresolvedElement[];
+ width: number;
+ height: number;
+ staticDuration: number;
+}
+
+function dedupeElementsById<T extends { id: string }>(elements: T[]): T[] {
+ const deduped = new Map<string, T>();
+ for (const element of elements) {
+ deduped.set(element.id, element);
+ }
+ return Array.from(deduped.values());
+}
+
+async function resolveMediaDuration(
+ src: string,
+ mediaStart: number,
+ baseDir: string,
+ downloadDir: string,
+ tagName: string
+): Promise<{ duration: number; resolvedPath: string }> {
+ let filePath = src;
+
+ if (isHttpUrl(src)) {
+ if (!existsSync(downloadDir)) mkdirSync(downloadDir, { recursive: true });
+ filePath = await downloadToTemp(src, downloadDir);
+ } else if (!filePath.startsWith("/")) {
+ filePath = join(baseDir, filePath);
+ }
+
+ if (!existsSync(filePath)) {
+ return { duration: 0, resolvedPath: filePath };
+ }
+
+ const metadata = tagName === "video"
+ ? await extractVideoMetadata(filePath)
+ : await extractAudioMetadata(filePath);
+
+ const fileDuration = metadata.durationSeconds;
+ const effectiveDuration = fileDuration - mediaStart;
+ const duration = effectiveDuration > 0 ? effectiveDuration : fileDuration;
+
+ return { duration, resolvedPath: filePath };
+}
+
+/**
+ * Compile a single HTML file: static pass + ffprobe for unresolved media.
+ * Returns compiled HTML and any unresolved composition elements that need browser resolution.
+ */
+async function compileHtmlFile(
+ html: string,
+ baseDir: string,
+ downloadDir: string
+): Promise<{ html: string; unresolvedCompositions: UnresolvedElement[] }> {
+ const { html: staticCompiled, unresolved } = compileTimingAttrs(html);
+
+ const mediaUnresolved = unresolved.filter(
+ (el) => (el.tagName === "video" || el.tagName === "audio") && el.src
+ );
+
+ const unresolvedCompositions = unresolved.filter(
+ (el) => el.tagName === "div"
+ );
+
+ // Phase 1: Resolve missing durations (parallel ffprobe)
+ const resolvedResults = await Promise.all(
+ mediaUnresolved.map((el) =>
+ resolveMediaDuration(el.src!, el.mediaStart, baseDir, downloadDir, el.tagName)
+ .then(({ duration }) => ({ id: el.id, duration }))
+ )
+ );
+ const resolutions: ResolvedDuration[] = resolvedResults.filter((r) => r.duration > 0);
+
+ let compiledHtml = resolutions.length > 0
+ ? injectDurations(staticCompiled, resolutions)
+ : staticCompiled;
+
+ // Phase 2: Validate pre-resolved media — clamp data-duration to actual source duration (parallel ffprobe)
+ const preResolved = extractResolvedMedia(compiledHtml);
+ const clampResults = await Promise.all(
+ preResolved
+ .filter((el) => !!el.src)
+ .map(async (el) => {
+ const { duration: maxDuration } = await resolveMediaDuration(
+ el.src!, el.mediaStart, baseDir, downloadDir, el.tagName
+ );
+ return { id: el.id, duration: el.duration, maxDuration, src: el.src! };
+ })
+ );
+ const clampList: ResolvedDuration[] = [];
+ for (const r of clampResults) {
+ if (r.maxDuration > 0 && r.duration > r.maxDuration) {
+ clampList.push({ id: r.id, duration: r.maxDuration });
+ }
+ }
+
+ if (clampList.length > 0) {
+ compiledHtml = clampDurations(compiledHtml, clampList);
+ }
+
+ return { html: compiledHtml, unresolvedCompositions };
+}
+
+/**
+ * Parse sub-compositions referenced via data-composition-src.
+ * Reads each file, compiles it, extracts video/audio, adjusts timing offsets.
+ * Recurses into nested sub-compositions with accumulated offsets.
+ */
+async function parseSubCompositions(
+ html: string,
+ projectDir: string,
+ downloadDir: string,
+ parentOffset: number = 0,
+ parentEnd: number = Infinity,
+ visited: Set<string> = new Set()
+): Promise<{
+ videos: VideoElement[];
+ audios: AudioElement[];
+ subCompositions: Map<string, string>;
+}> {
+ const videos: VideoElement[] = [];
+ const audios: AudioElement[] = [];
+ const subCompositions = new Map<string, string>();
+
+ const { document } = parseHTML(html);
+ const compEls = document.querySelectorAll("[data-composition-src]");
+
+ // Build work items, filtering out invalid/circular entries synchronously
+ const workItems: Array<{
+ srcPath: string;
+ absoluteStart: number;
+ absoluteEnd: number;
+ filePath: string;
+ rawSubHtml: string;
+ nestedVisited: Set<string>;
+ }> = [];
+
+ for (const el of compEls) {
+ const srcPath = el.getAttribute("data-composition-src");
+ if (!srcPath) continue;
+
+ const elStart = parseFloat(el.getAttribute("data-start") || "0");
+ const elEndRaw = el.getAttribute("data-end");
+ const elEnd = elEndRaw ? parseFloat(elEndRaw) : Infinity;
+
+ const absoluteStart = parentOffset + elStart;
+ const absoluteEnd = Math.min(
+ parentEnd,
+ isFinite(elEnd) ? parentOffset + elEnd : Infinity
+ );
+
+ const filePath = resolve(projectDir, srcPath);
+
+ // Circular reference guard
+ if (visited.has(filePath)) {
+ continue;
+ }
+
+ if (!existsSync(filePath)) {
+ continue;
+ }
+
+ const rawSubHtml = readFileSync(filePath, "utf-8");
+ const nestedVisited = new Set(visited);
+ nestedVisited.add(filePath);
+
+ workItems.push({ srcPath, absoluteStart, absoluteEnd, filePath, rawSubHtml, nestedVisited });
+ }
+
+ // Parallelize file compilation + recursive parsing
+ const results = await Promise.all(
+ workItems.map(async (item) => {
+ const { html: compiledSub } = await compileHtmlFile(item.rawSubHtml, dirname(item.filePath), downloadDir);
+
+ const nested = await parseSubCompositions(
+ compiledSub, projectDir, downloadDir,
+ item.absoluteStart, item.absoluteEnd, item.nestedVisited
+ );
+
+ const subVideos = parseVideoElements(compiledSub);
+ const subAudios = parseAudioElements(compiledSub);
+
+ return { srcPath: item.srcPath, compiledSub, nested, subVideos, subAudios, absoluteStart: item.absoluteStart, absoluteEnd: item.absoluteEnd };
+ })
+ );
+
+ // Merge results
+ for (const r of results) {
+ subCompositions.set(r.srcPath, r.compiledSub);
+
+ for (const [key, value] of r.nested.subCompositions) {
+ subCompositions.set(key, value);
+ }
+ videos.push(...r.nested.videos);
+ audios.push(...r.nested.audios);
+
+ for (const v of r.subVideos) {
+ v.start += r.absoluteStart;
+ v.end += r.absoluteStart;
+ if (v.end > r.absoluteEnd) {
+ v.end = r.absoluteEnd;
+ }
+ if (v.start < r.absoluteEnd) {
+ videos.push(v);
+ }
+ }
+
+ for (const a of r.subAudios) {
+ a.start += r.absoluteStart;
+ a.end += r.absoluteStart;
+ if (a.end > r.absoluteEnd) {
+ a.end = r.absoluteEnd;
+ }
+ if (a.start < r.absoluteEnd) {
+ audios.push(a);
+ }
+ }
+
+ if (r.subVideos.length > 0 || r.subAudios.length > 0 || r.nested.videos.length > 0 || r.nested.audios.length > 0) {
+ }
+ }
+
+ return { videos, audios, subCompositions };
+}
+
+/**
+ * Extract CSS `@import url(...)` rules that load external stylesheets (e.g. Google Fonts)
+ * from inline `<style>` blocks and promote them to `<link rel="stylesheet">` +
+ * `<link rel="preload">` in `<head>`.
+ *
+ * This moves font discovery from the CSS cascade to the document parser level so
+ * Chromium's `load` event and `networkidle2` correctly track them, preventing
+ * font-swap artifacts during frame capture.
+ */
+function promoteCssImportsToLinkTags(html: string): string {
+ const { document } = parseHTML(html);
+ const head = document.querySelector("head");
+ if (!head) return html;
+
+ const importRe = /@import\s+url\(\s*['"]?([^'")\s]+)['"]?\s*\)\s*;?/gi;
+ const seenUrls = new Set<string>();
+ const styleEls = document.querySelectorAll("style");
+
+ for (const styleEl of styleEls) {
+ const original = styleEl.textContent || "";
+ let modified = original;
+ let match: RegExpExecArray | null;
+ importRe.lastIndex = 0;
+ while ((match = importRe.exec(original)) !== null) {
+ const url = match[1] ?? "";
+ if (!url.startsWith("http://") && !url.startsWith("https://")) continue;
+ if (seenUrls.has(url)) {
+ modified = modified.replace(match[0], "");
+ continue;
+ }
+ seenUrls.add(url);
+ modified = modified.replace(match[0], "");
+
+ const preload = document.createElement("link");
+ preload.setAttribute("rel", "preload");
+ preload.setAttribute("href", url);
+ preload.setAttribute("as", "style");
+ head.appendChild(preload);
+
+ const link = document.createElement("link");
+ link.setAttribute("rel", "stylesheet");
+ link.setAttribute("href", url);
+ head.appendChild(link);
+ }
+ if (modified !== original) {
+ styleEl.textContent = modified;
+ }
+ }
+
+ return document.toString();
+}
+
+/**
+ * Merge all `<head>` `<style>` blocks into a single tag with `@import` rules
+ * at the top, and merge all inline `<body>` `<script>` blocks into one at the
+ * end of `<body>`.
+ *
+ * Mirrors the bundler's `coalesceHeadStylesAndBodyScripts` to guarantee
+ * identical CSS cascade order and script execution order between preview and
+ * export, preventing font-loading and animation-ordering regressions.
+ */
+
+/**
+ * Scope CSS rules to a specific composition by prepending each selector
+ * with `[data-composition-id="<id>"]`. This prevents class name collisions
+ * when multiple sub-compositions use the same class names (e.g. ".content").
+ *
+ * Handles:
+ * - Regular rules: `.foo { }` → `[data-composition-id="x"] .foo { }`
+ * - @media and other at-rules: preserved, inner selectors are scoped
+ * - @import, @font-face, @keyframes: left unscoped (global by nature)
+ */
+function scopeCssToComposition(css: string, compositionId: string): string {
+ const scope = `[data-composition-id="${compositionId}"]`;
+ // Split on top-level rule boundaries. Simple regex approach:
+ // scope each selector in rule blocks while preserving at-rules.
+ return css.replace(
+ /([^{}@]+)\{/g,
+ (match, selectors: string) => {
+ const trimmed = selectors.trim();
+ // Skip @-rule headers (they don't have selectors to scope)
+ if (trimmed.startsWith("@")) return match;
+ // Skip if already scoped to this composition
+ if (trimmed.includes(`data-composition-id="${compositionId}"`)) return match;
+ // Scope each comma-separated selector
+ const scoped = trimmed
+ .split(",")
+ .map((s: string) => {
+ const sel = s.trim();
+ if (!sel) return sel;
+ // Don't scope :root, html, body, or * alone — they're global
+ if (/^(html|body|:root|\*)$/i.test(sel)) return sel;
+ return `${scope} ${sel}`;
+ })
+ .join(", ");
+ return `${scoped} {`;
+ },
+ );
+}
+
+function coalesceHeadStylesAndBodyScripts(html: string): string {
+ const { document } = parseHTML(html);
+ const head = document.querySelector("head");
+ const body = document.querySelector("body");
+ if (!head) return html;
+
+ const styleEls = Array.from(head.querySelectorAll("style"));
+ if (styleEls.length > 1) {
+ const importRe = /@import\s+url\([^)]*\)\s*;|@import\s+["'][^"']+["']\s*;/gi;
+ const imports: string[] = [];
+ const cssParts: string[] = [];
+ const seenImports = new Set<string>();
+
+ for (const el of styleEls) {
+ const raw = (el.textContent || "").trim();
+ if (!raw) continue;
+ const nonImportCss = raw.replace(importRe, (match) => {
+ const cleaned = match.trim();
+ if (!seenImports.has(cleaned)) {
+ seenImports.add(cleaned);
+ imports.push(cleaned);
+ }
+ return "";
+ });
+ const trimmedCss = nonImportCss.trim();
+ if (trimmedCss) cssParts.push(trimmedCss);
+ }
+
+ const mergedCss = [...imports, ...cssParts].join("\n\n").trim();
+ if (mergedCss) {
+ const firstStyleEl = styleEls[0];
+ if (firstStyleEl) firstStyleEl.textContent = mergedCss;
+ for (let i = 1; i < styleEls.length; i++) {
+ const el = styleEls[i];
+ if (el) el.remove();
+ }
+ }
+ }
+
+ if (body) {
+ const bodyScripts = Array.from(body.querySelectorAll("script")).filter((el) => {
+ const src = (el.getAttribute("src") || "").trim();
+ if (src) return false;
+ const type = (el.getAttribute("type") || "").trim().toLowerCase();
+ return !type || type === "text/javascript" || type === "application/javascript";
+ });
+ if (bodyScripts.length > 0) {
+ const mergedJs = bodyScripts
+ .map((el) => (el.textContent || "").trim())
+ .filter(Boolean)
+ .join("\n;\n")
+ .trim();
+ for (const el of bodyScripts) {
+ el.remove();
+ }
+ if (mergedJs) {
+ const script = document.createElement("script");
+ script.textContent = mergedJs;
+ body.appendChild(script);
+ }
+ }
+ }
+
+ return document.toString();
+}
+
+/**
+ * Inline sub-composition HTML into the main document, mirroring what the
+ * bundler's step 6 does. For each host element with `data-composition-src`:
+ * - Resolve the composition HTML from the pre-compiled map or disk
+ * - Extract <template> (or <body>) content
+ * - Move composition <style> to <head>, <script> to end of <body>
+ * - Replace host innerHTML with composition children
+ * - Remove data-composition-src so the runtime skips async fetching
+ */
+function inlineSubCompositions(
+ html: string,
+ subCompositions: Map<string, string>,
+ projectDir: string
+): string {
+ const { document } = parseHTML(html);
+ const head = document.querySelector("head");
+ const body = document.querySelector("body");
+ const hosts = document.querySelectorAll("[data-composition-src]");
+
+ if (!hosts.length) return html;
+
+ const collectedStyles: string[] = [];
+ const collectedScripts: string[] = [];
+
+ for (const host of hosts) {
+ const srcPath = host.getAttribute("data-composition-src");
+ if (!srcPath) continue;
+
+ let compHtml = subCompositions.get(srcPath) || null;
+ if (!compHtml) {
+ const filePath = resolve(projectDir, srcPath);
+ if (existsSync(filePath)) {
+ compHtml = readFileSync(filePath, "utf-8");
+ }
+ }
+ if (!compHtml) {
+ continue;
+ }
+
+ const compDoc = parseHTML(compHtml).document;
+ const compId = host.getAttribute("data-composition-id");
+
+ const templateEl = compDoc.querySelector("template");
+ const bodyEl = compDoc.querySelector("body");
+ const contentHtml = templateEl
+ ? (templateEl.innerHTML || "")
+ : bodyEl
+ ? (bodyEl.innerHTML || "")
+ : compDoc.toString();
+
+ const contentDoc = parseHTML(contentHtml).document;
+
+ const innerRoot = compId
+ ? contentDoc.querySelector(`[data-composition-id="${compId}"]`)
+ : contentDoc.querySelector("[data-composition-id]");
+ const inferredCompId = innerRoot?.getAttribute("data-composition-id")?.trim() || null;
+
+ for (const styleEl of contentDoc.querySelectorAll("style")) {
+ const css = styleEl.textContent || "";
+ const scopeId = compId || inferredCompId;
+ if (scopeId && css.trim()) {
+ // Scope sub-composition styles to their composition ID to prevent
+ // CSS class collisions when multiple compositions use the same
+ // class names (e.g. ".content"). This matches preview behavior
+ // where each composition's styles are naturally scoped.
+ collectedStyles.push(scopeCssToComposition(css, scopeId));
+ } else {
+ collectedStyles.push(css);
+ }
+ styleEl.remove();
+ }
+
+ for (const scriptEl of contentDoc.querySelectorAll("script")) {
+ const src = (scriptEl.getAttribute("src") || "").trim();
+ if (src) continue;
+ const content = (scriptEl.textContent || "").trim();
+ if (content) {
+ const scriptMountCompId = compId || inferredCompId || "";
+ const compIdLiteral = JSON.stringify(scriptMountCompId);
+ collectedScripts.push(`(function(){
+ var __compId = ${compIdLiteral};
+ var __run = function() {
+ try {
+ ${content}
+ } catch (_err) {
+ console.error("[Compiler] Composition script failed", __compId, _err);
+ }
+ };
+ if (!__compId) { __run(); return; }
+ var __selector = '[data-composition-id="' + (__compId + '').replace(/"/g, '\\\\"') + '"]';
+ var __attempt = 0;
+ var __tryRun = function() {
+ if (document.querySelector(__selector)) { __run(); return; }
+ if (++__attempt >= 8) { __run(); return; }
+ requestAnimationFrame(__tryRun);
+ };
+ __tryRun();
+})()`);
+ }
+ scriptEl.remove();
+ }
+
+ if (innerRoot) {
+ const innerW = innerRoot.getAttribute("data-width");
+ const innerH = innerRoot.getAttribute("data-height");
+ if (innerW && !host.getAttribute("data-width")) host.setAttribute("data-width", innerW);
+ if (innerH && !host.getAttribute("data-height")) host.setAttribute("data-height", innerH);
+ innerRoot.querySelectorAll("style, script").forEach((el) => el.remove());
+ if (!compId && inferredCompId) {
+ host.innerHTML = innerRoot.outerHTML || "";
+ } else {
+ host.innerHTML = innerRoot.innerHTML || "";
+ }
+ } else {
+ contentDoc.querySelectorAll("style, script").forEach((el) => el.remove());
+ host.innerHTML = contentDoc.toString();
+ }
+
+ host.removeAttribute("data-composition-src");
+
+ // Set explicit pixel dimensions on the host element so children using
+ // width/height: 100% resolve correctly. The runtime does this
+ // automatically but compiled HTML needs it inline.
+ const hostW = host.getAttribute("data-width");
+ const hostH = host.getAttribute("data-height");
+ if (hostW && hostH) {
+ const existing = host.getAttribute("style") || "";
+ const needsWidth = !existing.includes("width");
+ const needsHeight = !existing.includes("height");
+ const needsPosition = !existing.includes("position");
+ const additions = [
+ needsPosition ? "position:relative" : "",
+ needsWidth ? `width:${hostW}px` : "",
+ needsHeight ? `height:${hostH}px` : "",
+ ].filter(Boolean).join(";");
+ if (additions) {
+ host.setAttribute("style", existing ? `${existing};${additions}` : additions);
+ }
+ }
+
+ }
+
+ if (collectedStyles.length && head) {
+ const styleEl = document.createElement("style");
+ styleEl.textContent = collectedStyles.join("\n\n");
+ head.appendChild(styleEl);
+ }
+
+ if (collectedScripts.length && body) {
+ const scriptEl = document.createElement("script");
+ scriptEl.textContent = collectedScripts.join("\n;\n");
+ body.appendChild(scriptEl);
+ }
+
+ return document.toString();
+}
+
+/**
+ * Full compilation pipeline for the producer.
+ *
+ * Returns everything the orchestrator needs: compiled HTML, all media elements,
+ * dimensions, and static duration.
+ */
+export async function compileForRender(
+ projectDir: string,
+ htmlPath: string,
+ downloadDir: string
+): Promise<CompiledComposition> {
+
+ const rawHtml = readFileSync(htmlPath, "utf-8");
+ const { html: compiledHtml, unresolvedCompositions } = await compileHtmlFile(rawHtml, projectDir, downloadDir);
+
+ // Parse sub-compositions first (extracts media + compiled HTML for each)
+ const { videos: subVideos, audios: subAudios, subCompositions } =
+ await parseSubCompositions(compiledHtml, projectDir, downloadDir);
+
+ // Inline sub-compositions into the main HTML so the runtime takes the same
+ // synchronous code path as the bundled preview (no async fetch of
+ // data-composition-src). This mirrors what htmlBundler.ts does for preview.
+ const inlinedHtml = inlineSubCompositions(compiledHtml, subCompositions, projectDir);
+
+ const html = injectDeterministicFontFaces(
+ coalesceHeadStylesAndBodyScripts(promoteCssImportsToLinkTags(inlinedHtml)),
+ );
+
+ // Parse main HTML elements
+ const mainVideos = parseVideoElements(html);
+ const mainAudios = parseAudioElements(html);
+
+ const videos = dedupeElementsById([...subVideos, ...mainVideos]);
+ const audios = dedupeElementsById([...subAudios, ...mainAudios]);
+
+ // Read dimensions from root composition element using DOM parser
+ const { document } = parseHTML(html);
+ const rootEl = document.querySelector("[data-composition-id]");
+
+ const width = rootEl
+ ? parseInt(rootEl.getAttribute("data-width") || "1080", 10)
+ : 1080;
+ const height = rootEl
+ ? parseInt(rootEl.getAttribute("data-height") || "1920", 10)
+ : 1920;
+
+ // Static duration (may be 0 if set at runtime by GSAP)
+ const staticDuration = rootEl
+ ? parseFloat(
+ rootEl.getAttribute("data-duration")
+ || rootEl.getAttribute("data-composition-duration")
+ || "0",
+ )
+ : 0;
+
+
+ return { html, subCompositions, videos, audios, unresolvedCompositions, width, height, staticDuration };
+}
+
+/**
+ * Discover media elements from the browser DOM after JavaScript has run.
+ * This catches videos/audios whose `src` is set dynamically via JS
+ * (e.g. `document.getElementById("pip-video").src = URL`), which the
+ * static regex parsers miss because the HTML has `src=""`.
+ */
+export interface BrowserMediaElement {
+ id: string;
+ tagName: "video" | "audio";
+ src: string;
+ start: number;
+ end: number;
+ duration: number;
+ mediaStart: number;
+ hasAudio: boolean;
+ volume: number;
+}
+
+export async function discoverMediaFromBrowser(
+ page: Page
+): Promise<BrowserMediaElement[]> {
+
+ const elements = await page.evaluate(() => {
+ const results: {
+ id: string;
+ tagName: string;
+ src: string;
+ start: number;
+ end: number;
+ duration: number;
+ mediaStart: number;
+ hasAudio: boolean;
+ volume: number;
+ }[] = [];
+
+ const mediaEls = document.querySelectorAll("video[data-start], audio[data-start]");
+ mediaEls.forEach((el) => {
+ const htmlEl = el as HTMLVideoElement | HTMLAudioElement;
+ const id = htmlEl.id;
+ if (!id) return;
+
+ const src = htmlEl.src || htmlEl.getAttribute("src") || "";
+ const start = parseFloat(htmlEl.getAttribute("data-start") || "0");
+ const end = parseFloat(htmlEl.getAttribute("data-end") || "0");
+ const duration = parseFloat(htmlEl.getAttribute("data-duration") || "0");
+ const mediaStart = parseFloat(htmlEl.getAttribute("data-media-start") || "0");
+ const hasAudio = htmlEl.getAttribute("data-has-audio") === "true";
+ const volume = parseFloat(htmlEl.getAttribute("data-volume") || "1");
+
+ results.push({
+ id,
+ tagName: htmlEl.tagName.toLowerCase(),
+ src,
+ start,
+ end,
+ duration,
+ mediaStart,
+ hasAudio,
+ volume,
+ });
+ });
+
+ return results;
+ });
+
+ return elements as BrowserMediaElement[];
+}
+
+/**
+ * Resolve composition durations via Puppeteer by querying window.__timelines.
+ * The page must already have the interceptor loaded and timelines registered.
+ */
+export async function resolveCompositionDurations(
+ page: Page,
+ unresolved: UnresolvedElement[]
+): Promise<ResolvedDuration[]> {
+ if (unresolved.length === 0) return [];
+
+
+ const ids = unresolved.map(el => el.id);
+
+ const results = await page.evaluate((compIds: string[]) => {
+ const win = window as unknown as { __timelines?: Record<string, { duration(): number }> };
+ const timelines = win.__timelines || {};
+ const resolved: { id: string; duration: number; source: string }[] = [];
+
+ for (const id of compIds) {
+ // Try window.__timelines[id].duration() first (GSAP timeline)
+ const tl = timelines[id];
+ if (tl && typeof tl.duration === "function") {
+ const dur = tl.duration();
+ if (dur > 0) {
+ resolved.push({ id, duration: dur, source: "__timelines" });
+ continue;
+ }
+ }
+
+ // Fallback: check for authored duration on the element itself
+ const el = document.getElementById(id);
+ if (el) {
+ const compDurAttr = el.getAttribute("data-duration") || el.getAttribute("data-composition-duration");
+ if (compDurAttr) {
+ const dur = parseFloat(compDurAttr);
+ if (dur > 0) {
+ resolved.push({ id, duration: dur, source: "data-duration" });
+ continue;
+ }
+ }
+ }
+
+ resolved.push({ id, duration: 0, source: "unresolved" });
+ }
+
+ return resolved;
+ }, ids);
+
+ const resolutions: ResolvedDuration[] = [];
+ for (const r of results) {
+ if (r.duration > 0) {
+ resolutions.push({ id: r.id, duration: r.duration });
+ }
+ }
+
+ return resolutions;
+}
+
+/**
+ * Re-compile after composition durations are resolved.
+ * Injects durations into the HTML and re-parses sub-composition media with proper bounds.
+ */
+export async function recompileWithResolutions(
+ compiled: CompiledComposition,
+ resolutions: ResolvedDuration[],
+ projectDir: string,
+ downloadDir: string
+): Promise<CompiledComposition> {
+ if (resolutions.length === 0) return compiled;
+
+
+ const html = injectDurations(compiled.html, resolutions);
+
+ // Re-parse sub-compositions with the updated parent bounds
+ const { videos: subVideos, audios: subAudios, subCompositions } =
+ await parseSubCompositions(html, projectDir, downloadDir);
+
+ const mainVideos = parseVideoElements(html);
+ const mainAudios = parseAudioElements(html);
+
+ const videos = dedupeElementsById([...subVideos, ...mainVideos]);
+ const audios = dedupeElementsById([...subAudios, ...mainAudios]);
+
+ const remaining = compiled.unresolvedCompositions.filter(
+ c => !resolutions.some(r => r.id === c.id)
+ );
+
+
+ return {
+ ...compiled,
+ html,
+ subCompositions,
+ videos,
+ audios,
+ unresolvedCompositions: remaining,
+ };
+}
diff --git a/packages/producer/src/services/hyperframeLint.ts b/packages/producer/src/services/hyperframeLint.ts
new file mode 100644
index 0000000000..ee5b3e18c6
--- /dev/null
+++ b/packages/producer/src/services/hyperframeLint.ts
@@ -0,0 +1,111 @@
+import { existsSync, readFileSync, statSync } from "node:fs";
+import { resolve, join } from "node:path";
+import { lintHyperframeHtml, type HyperframeLintResult } from "@hyperframes/core/lint";
+
+export interface PreparedHyperframeLintInput {
+ entryFile: string;
+ html: string;
+ source: "projectDir" | "files" | "html";
+}
+
+function isStringRecord(value: unknown): value is Record<string, string> {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ return false;
+ }
+ return Object.values(value).every((item) => typeof item === "string");
+}
+
+function pickEntryFile(files: Record<string, string>, preferredEntryFile?: string): string | null {
+ const candidates: string[] = [];
+ if (preferredEntryFile) {
+ candidates.push(preferredEntryFile);
+ }
+ candidates.push("index.html", "src/index.html");
+
+ for (const candidate of candidates) {
+ const value = files[candidate];
+ if (typeof value === "string" && value.length > 0) {
+ return candidate;
+ }
+ }
+
+ for (const [fileName, content] of Object.entries(files)) {
+ if (fileName.toLowerCase().endsWith(".html") && content.length > 0) {
+ return fileName;
+ }
+ }
+
+ return null;
+}
+
+function readProjectEntryFile(projectDir: string, preferredEntryFile?: string): PreparedHyperframeLintInput | { error: string } {
+ const absProjectDir = resolve(projectDir);
+ if (!existsSync(absProjectDir) || !statSync(absProjectDir).isDirectory()) {
+ return { error: `Project directory not found: ${absProjectDir}` };
+ }
+
+ const entryCandidates = [preferredEntryFile, "index.html", "src/index.html"].filter(
+ (value): value is string => typeof value === "string" && value.trim().length > 0,
+ );
+
+ for (const entryFile of entryCandidates) {
+ const absoluteEntryPath = resolve(absProjectDir, entryFile);
+ if (!absoluteEntryPath.startsWith(absProjectDir)) {
+ return { error: `Entry file must stay inside project directory: ${entryFile}` };
+ }
+ if (existsSync(absoluteEntryPath) && statSync(absoluteEntryPath).isFile()) {
+ return {
+ entryFile,
+ html: readFileSync(absoluteEntryPath, "utf-8"),
+ source: "projectDir",
+ };
+ }
+ }
+
+ return { error: `No HTML entry file found in project directory: ${join(absProjectDir, preferredEntryFile || "index.html")}` };
+}
+
+export function prepareHyperframeLintBody(
+ body: Record<string, unknown>,
+): { prepared: PreparedHyperframeLintInput } | { error: string } {
+ const requestedEntryFile =
+ typeof body.entryFile === "string" && body.entryFile.trim().length > 0 ? body.entryFile.trim() : undefined;
+
+ if (typeof body.projectDir === "string" && body.projectDir.trim().length > 0) {
+ const prepared = readProjectEntryFile(body.projectDir, requestedEntryFile);
+ if ("error" in prepared) {
+ return prepared;
+ }
+ return { prepared };
+ }
+
+ if (isStringRecord(body.files)) {
+ const entryFile = pickEntryFile(body.files, requestedEntryFile);
+ if (!entryFile) {
+ return { error: "No HTML entry file found in files payload" };
+ }
+ return {
+ prepared: {
+ entryFile,
+ html: body.files[entryFile] ?? "",
+ source: "files",
+ },
+ };
+ }
+
+ if (typeof body.html === "string") {
+ return {
+ prepared: {
+ entryFile: requestedEntryFile || "index.html",
+ html: body.html,
+ source: "html",
+ },
+ };
+ }
+
+ return { error: "Missing lint source: provide projectDir, files, or html" };
+}
+
+export function runHyperframeLint(prepared: PreparedHyperframeLintInput): HyperframeLintResult {
+ return lintHyperframeHtml(prepared.html, { filePath: prepared.entryFile });
+}
diff --git a/packages/producer/src/services/hyperframeRuntimeLoader.ts b/packages/producer/src/services/hyperframeRuntimeLoader.ts
new file mode 100644
index 0000000000..3c0c115bd1
--- /dev/null
+++ b/packages/producer/src/services/hyperframeRuntimeLoader.ts
@@ -0,0 +1,85 @@
+import { createHash } from "node:crypto";
+import { existsSync, readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const PRODUCER_DIR = dirname(fileURLToPath(import.meta.url));
+const MODULE_RELATIVE_MANIFEST_PATH = resolve(
+ PRODUCER_DIR,
+ "../../../core/dist/hyperframe.manifest.json"
+);
+const CWD_RELATIVE_MANIFEST_PATHS = [
+ resolve(process.cwd(), "../core/dist/hyperframe.manifest.json"),
+ resolve(process.cwd(), "core/dist/hyperframe.manifest.json"),
+];
+
+type HyperframeRuntimeManifest = {
+ sha256?: string;
+ artifacts?: {
+ iife?: string;
+ };
+};
+
+export type ResolvedHyperframeRuntime = {
+ manifestPath: string;
+ runtimePath: string;
+ expectedSha256: string;
+ actualSha256: string;
+ runtimeSource: string;
+};
+
+export function resolveHyperframeManifestPath(): string {
+ if (process.env.PRODUCER_HYPERFRAME_MANIFEST_PATH) {
+ return process.env.PRODUCER_HYPERFRAME_MANIFEST_PATH;
+ }
+ const candidates = [...CWD_RELATIVE_MANIFEST_PATHS, MODULE_RELATIVE_MANIFEST_PATH];
+ for (const candidate of candidates) {
+ if (existsSync(candidate)) {
+ return candidate;
+ }
+ }
+ return MODULE_RELATIVE_MANIFEST_PATH;
+}
+
+export function getVerifiedHyperframeRuntimeSource(): string {
+ return resolveVerifiedHyperframeRuntime().runtimeSource;
+}
+
+export function resolveVerifiedHyperframeRuntime(): ResolvedHyperframeRuntime {
+ const manifestPath = resolveHyperframeManifestPath();
+ if (!existsSync(manifestPath)) {
+ throw new Error(
+ `[HyperframeRuntimeLoader] Missing manifest at ${manifestPath}. Build core runtime artifacts before rendering.`
+ );
+ }
+
+ const manifestRaw = readFileSync(manifestPath, "utf8");
+ const manifest = JSON.parse(manifestRaw) as HyperframeRuntimeManifest;
+ const runtimeFileName = manifest.artifacts?.iife;
+ if (!runtimeFileName || !manifest.sha256) {
+ throw new Error(
+ `[HyperframeRuntimeLoader] Invalid manifest at ${manifestPath}; missing iife artifact or sha256.`
+ );
+ }
+
+ const runtimePath = resolve(dirname(manifestPath), runtimeFileName);
+ if (!existsSync(runtimePath)) {
+ throw new Error(`[HyperframeRuntimeLoader] Missing runtime artifact at ${runtimePath}.`);
+ }
+
+ const runtimeSource = readFileSync(runtimePath, "utf8");
+ const runtimeSha = createHash("sha256").update(runtimeSource, "utf8").digest("hex");
+ if (runtimeSha !== manifest.sha256) {
+ throw new Error(
+ `[HyperframeRuntimeLoader] Runtime checksum mismatch. expected=${manifest.sha256} actual=${runtimeSha}`
+ );
+ }
+ return {
+ manifestPath,
+ runtimePath,
+ expectedSha256: manifest.sha256,
+ actualSha256: runtimeSha,
+ runtimeSource,
+ };
+}
+
diff --git a/packages/producer/src/services/parallelCoordinator.ts b/packages/producer/src/services/parallelCoordinator.ts
new file mode 100644
index 0000000000..7f61b4b7dd
--- /dev/null
+++ b/packages/producer/src/services/parallelCoordinator.ts
@@ -0,0 +1,14 @@
+/**
+ * Re-exported from @hyperframes/engine.
+ * @see engine/src/services/parallelCoordinator.ts for implementation.
+ */
+export {
+ calculateOptimalWorkers,
+ distributeFrames,
+ executeParallelCapture,
+ mergeWorkerFrames,
+ getSystemResources,
+ type WorkerTask,
+ type WorkerResult,
+ type ParallelProgress,
+} from "@hyperframes/engine";
diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.ts
new file mode 100644
index 0000000000..d179e0da45
--- /dev/null
+++ b/packages/producer/src/services/renderOrchestrator.ts
@@ -0,0 +1,944 @@
+/**
+ * Render Orchestrator Service
+ *
+ * Coordinates the entire video rendering pipeline:
+ * 1. Parse composition metadata
+ * 2. Pre-extract video frames
+ * 3. Pre-process audio tracks
+ * 4. Parallel frame capture
+ * 5. Video encoding
+ * 6. Final assembly (audio mux + faststart)
+ *
+ * Heavy observability: every stage logs timing, errors include
+ * full context, and failures produce a diagnostic summary.
+ */
+
+import { existsSync, mkdirSync, rmSync, writeFileSync, copyFileSync, appendFileSync } from "fs";
+import {
+ type EngineConfig as ProducerConfig,
+ resolveConfig,
+ extractAllVideoFrames,
+ createFrameLookupTable,
+ type VideoElement,
+ FrameLookupTable,
+ createCaptureSession,
+ initializeSession,
+ closeCaptureSession,
+ captureFrame,
+ captureFrameToBuffer,
+ getCompositionDuration,
+ prepareCaptureSessionForReuse,
+ type CaptureOptions,
+ type CaptureSession,
+ createVideoFrameInjector,
+ encodeFramesFromDir,
+ encodeFramesChunkedConcat,
+ muxVideoWithAudio,
+ applyFaststart,
+ ENCODER_PRESETS,
+ processCompositionAudio,
+ type AudioElement,
+ calculateOptimalWorkers,
+ distributeFrames,
+ executeParallelCapture,
+ mergeWorkerFrames,
+ spawnStreamingEncoder,
+ createFrameReorderBuffer,
+ type StreamingEncoder,
+} from "@hyperframes/engine";
+import { join, dirname, resolve } from "path";
+import { randomUUID } from "crypto";
+import { freemem } from "os";
+import { fileURLToPath } from "url";
+import { createFileServer, type FileServerHandle } from "./fileServer.js";
+import { compileForRender, resolveCompositionDurations, recompileWithResolutions, discoverMediaFromBrowser, type CompiledComposition } from "./htmlCompiler.js";
+import { defaultLogger, type ProducerLogger } from "../logger.js";
+
+/**
+ * Wrap a cleanup operation so it never throws, but logs any failure.
+ */
+async function safeCleanup(label: string, fn: () => Promise<void> | void, log: ProducerLogger = defaultLogger): Promise<void> {
+ try {
+ await fn();
+ } catch (err) {
+ log.debug(`Cleanup failed (${label})`, { error: err instanceof Error ? err.message : String(err) });
+ }
+}
+
+export type RenderStatus =
+ | "queued"
+ | "preprocessing"
+ | "rendering"
+ | "encoding"
+ | "assembling"
+ | "complete"
+ | "failed"
+ | "cancelled";
+
+export interface RenderConfig {
+ fps: 24 | 30 | 60;
+ quality: "draft" | "standard" | "high";
+ workers?: number;
+ useGpu?: boolean;
+ debug?: boolean;
+ /** Full producer config. When provided, env vars are not read. */
+ producerConfig?: ProducerConfig;
+ /** Custom logger. Defaults to console-based defaultLogger. */
+ logger?: ProducerLogger;
+}
+
+export interface RenderPerfSummary {
+ renderId: string;
+ totalElapsedMs: number;
+ fps: number;
+ quality: string;
+ workers: number;
+ chunkedEncode: boolean;
+ chunkSizeFrames: number | null;
+ compositionDurationSeconds: number;
+ totalFrames: number;
+ resolution: { width: number; height: number };
+ videoCount: number;
+ audioCount: number;
+ stages: Record<string, number>;
+ captureAvgMs?: number;
+ capturePeakMs?: number;
+}
+
+export interface RenderJob {
+ id: string;
+ config: RenderConfig;
+ status: RenderStatus;
+ progress: number;
+ currentStage: string;
+ createdAt: Date;
+ startedAt?: Date;
+ completedAt?: Date;
+ error?: string;
+ outputPath?: string;
+ duration?: number;
+ totalFrames?: number;
+ framesRendered?: number;
+ perfSummary?: RenderPerfSummary;
+ failedStage?: string;
+ errorDetails?: {
+ message: string;
+ stack?: string;
+ elapsedMs: number;
+ freeMemoryMB: number;
+ browserConsoleTail?: string[];
+ perfStages?: Record<string, number>;
+ };
+}
+
+export type ProgressCallback = (job: RenderJob, message: string) => void;
+
+export class RenderCancelledError extends Error {
+ reason: "user_cancelled" | "timeout" | "aborted";
+ constructor(message: string = "render_cancelled", reason: "user_cancelled" | "timeout" | "aborted" = "aborted") {
+ super(message);
+ this.name = "RenderCancelledError";
+ this.reason = reason;
+ }
+}
+
+export interface CompositionMetadata {
+ duration: number;
+ videos: VideoElement[];
+ audios: AudioElement[];
+ width: number;
+ height: number;
+}
+
+function updateJobStatus(
+ job: RenderJob,
+ status: RenderStatus,
+ stage: string,
+ progress: number,
+ onProgress?: ProgressCallback
+): void {
+ job.status = status;
+ job.currentStage = stage;
+ job.progress = progress;
+ if (status === "failed" || status === "complete") job.completedAt = new Date();
+ if (onProgress) onProgress(job, stage);
+}
+
+function installDebugLogger(logPath: string, log: ProducerLogger = defaultLogger): () => void {
+ const origLog = console.log;
+ const origError = console.error;
+ const origWarn = console.warn;
+
+ const write = (prefix: string, args: unknown[]) => {
+ const ts = new Date().toISOString();
+ const line = `[${ts}] ${prefix} ${args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ")}\n`;
+ try { appendFileSync(logPath, line); } catch (err) {
+ log.debug("Debug log write failed", { logPath, error: err instanceof Error ? err.message : String(err) });
+ }
+ };
+
+ console.log = (...args: unknown[]) => { write("LOG", args); origLog(...args); };
+ console.error = (...args: unknown[]) => { write("ERR", args); origError(...args); };
+ console.warn = (...args: unknown[]) => { write("WRN", args); origWarn(...args); };
+
+ return () => {
+ console.log = origLog;
+ console.error = origError;
+ console.warn = origWarn;
+ };
+}
+
+/**
+ * Write compiled HTML and sub-compositions to the work directory.
+ */
+function writeCompiledArtifacts(compiled: CompiledComposition, workDir: string, includeSummary: boolean): void {
+ const compileDir = join(workDir, "compiled");
+ mkdirSync(compileDir, { recursive: true });
+
+ writeFileSync(join(compileDir, "index.html"), compiled.html, "utf-8");
+
+ for (const [srcPath, html] of compiled.subCompositions) {
+ const outPath = join(compileDir, srcPath);
+ mkdirSync(dirname(outPath), { recursive: true });
+ writeFileSync(outPath, html, "utf-8");
+ }
+
+ if (includeSummary) {
+ const summary = {
+ width: compiled.width,
+ height: compiled.height,
+ staticDuration: compiled.staticDuration,
+ videos: compiled.videos.map((v) => ({
+ id: v.id, src: v.src, start: v.start, end: v.end, mediaStart: v.mediaStart,
+ })),
+ audios: compiled.audios.map((a) => ({
+ id: a.id, src: a.src, start: a.start, end: a.end, mediaStart: a.mediaStart,
+ })),
+ subCompositions: Array.from(compiled.subCompositions.keys()),
+ };
+ writeFileSync(join(compileDir, "summary.json"), JSON.stringify(summary, null, 2), "utf-8");
+ }
+}
+
+export function createRenderJob(config: RenderConfig): RenderJob {
+ return {
+ id: randomUUID(),
+ config,
+ status: "queued",
+ progress: 0,
+ currentStage: "Queued",
+ createdAt: new Date(),
+ };
+}
+
+/**
+ * Main render pipeline
+ */
+export async function executeRenderJob(
+ job: RenderJob,
+ projectDir: string,
+ outputPath: string,
+ onProgress?: ProgressCallback,
+ abortSignal?: AbortSignal,
+): Promise<void> {
+ const moduleDir = dirname(fileURLToPath(import.meta.url));
+ const producerRoot = process.env.PRODUCER_RENDERS_DIR
+ ? resolve(process.env.PRODUCER_RENDERS_DIR, "..")
+ : resolve(moduleDir, "../..");
+ const debugDir = join(producerRoot, ".debug");
+ const workDir = job.config.debug
+ ? join(debugDir, job.id)
+ : join(dirname(outputPath), `work-${job.id}`);
+ const pipelineStart = Date.now();
+ const log = job.config.logger ?? defaultLogger;
+ let fileServer: FileServerHandle | null = null;
+ let probeSession: CaptureSession | null = null;
+ let lastBrowserConsole: string[] = [];
+ let restoreLogger: (() => void) | null = null;
+ const perfStages: Record<string, number> = {};
+ const perfOutputPath = join(workDir, "perf-summary.json");
+ const cfg = job.config.producerConfig ?? resolveConfig();
+ const enableChunkedEncode = cfg.enableChunkedEncode;
+ const chunkedEncodeSize = cfg.chunkSizeFrames;
+ const enableStreamingEncode = cfg.enableStreamingEncode;
+
+ try {
+ const assertNotAborted = () => {
+ if (abortSignal?.aborted) {
+ throw new RenderCancelledError("render_cancelled");
+ }
+ };
+
+ job.startedAt = new Date();
+ assertNotAborted();
+ if (!existsSync(workDir)) mkdirSync(workDir, { recursive: true });
+
+ if (job.config.debug) {
+ const logPath = join(workDir, "render.log");
+ restoreLogger = installDebugLogger(logPath, log);
+ }
+
+ const htmlPath = join(projectDir, "index.html");
+ assertNotAborted();
+
+ // ── Stage 1: Compile ─────────────────────────────────────────────────
+ const stage1Start = Date.now();
+ updateJobStatus(job, "preprocessing", "Compiling composition", 5, onProgress);
+
+ const compileStart = Date.now();
+ let compiled = await compileForRender(projectDir, htmlPath, join(workDir, "downloads"));
+ assertNotAborted();
+ perfStages.compileOnlyMs = Date.now() - compileStart;
+ writeCompiledArtifacts(compiled, workDir, Boolean(job.config.debug));
+
+ const composition: CompositionMetadata = {
+ duration: compiled.staticDuration,
+ videos: compiled.videos,
+ audios: compiled.audios,
+ width: compiled.width,
+ height: compiled.height,
+ };
+ const { width, height } = composition;
+
+ const probeStart = Date.now();
+ const needsBrowser = composition.duration <= 0 || compiled.unresolvedCompositions.length > 0;
+
+ if (needsBrowser) {
+ const reasons = [];
+ if (composition.duration <= 0) reasons.push("root duration unknown");
+ if (compiled.unresolvedCompositions.length > 0) reasons.push(`${compiled.unresolvedCompositions.length} unresolved composition(s)`);
+
+ fileServer = await createFileServer({ projectDir, compiledDir: join(workDir, "compiled"), port: 0 });
+ assertNotAborted();
+
+ const captureOpts: CaptureOptions = { width, height, fps: job.config.fps, format: "jpeg", quality: 80 };
+ probeSession = await createCaptureSession(fileServer.url, join(workDir, "probe"), captureOpts, null, cfg);
+ await initializeSession(probeSession);
+ assertNotAborted();
+ lastBrowserConsole = probeSession.browserConsoleBuffer;
+
+ // Discover root composition duration
+ if (composition.duration <= 0) {
+ const discoveredDuration = await getCompositionDuration(probeSession);
+ assertNotAborted();
+ composition.duration = discoveredDuration;
+ }
+
+ // Resolve unresolved composition durations via window.__timelines
+ if (compiled.unresolvedCompositions.length > 0) {
+ const resolutions = await resolveCompositionDurations(probeSession.page, compiled.unresolvedCompositions);
+ assertNotAborted();
+ if (resolutions.length > 0) {
+ compiled = await recompileWithResolutions(compiled, resolutions, projectDir, join(workDir, "downloads"));
+ assertNotAborted();
+ // Update composition metadata with re-parsed media
+ composition.videos = compiled.videos;
+ composition.audios = compiled.audios;
+ writeCompiledArtifacts(compiled, workDir, Boolean(job.config.debug));
+ }
+ }
+
+ // Discover media elements from browser DOM (catches dynamically-set src)
+ const browserMedia = await discoverMediaFromBrowser(probeSession.page);
+ assertNotAborted();
+ if (browserMedia.length > 0) {
+ const existingVideoIds = new Set(composition.videos.map(v => v.id));
+ const existingAudioIds = new Set(composition.audios.map(a => a.id));
+
+ for (const el of browserMedia) {
+ if (!el.src || el.src === "about:blank") continue;
+
+ // Convert absolute localhost URLs back to relative paths
+ let src = el.src;
+ if (fileServer && src.startsWith(fileServer.url)) {
+ src = src.slice(fileServer.url.length).replace(/^\//, "");
+ }
+
+ if (el.tagName === "video") {
+ if (existingVideoIds.has(el.id)) {
+ // Reconcile to browser/runtime media metadata (runtime src can differ from static HTML).
+ const existing = composition.videos.find(v => v.id === el.id);
+ if (existing) {
+ if (existing.src !== src) {
+ existing.src = src;
+ }
+ if (el.end > 0 && (existing.end <= 0 || Math.abs(existing.end - el.end) > 0.0001)) {
+ existing.end = el.end;
+ }
+ if (el.mediaStart > 0 && (existing.mediaStart <= 0 || Math.abs(existing.mediaStart - el.mediaStart) > 0.0001)) {
+ existing.mediaStart = el.mediaStart;
+ }
+ if (el.hasAudio && !existing.hasAudio) {
+ existing.hasAudio = true;
+ }
+ }
+ } else {
+ // New video discovered from browser
+ composition.videos.push({
+ id: el.id,
+ src,
+ start: el.start,
+ end: el.end,
+ mediaStart: el.mediaStart,
+ hasAudio: el.hasAudio,
+ });
+ existingVideoIds.add(el.id);
+ }
+ } else if (el.tagName === "audio") {
+ if (existingAudioIds.has(el.id)) {
+ const existing = composition.audios.find(a => a.id === el.id);
+ if (existing) {
+ if (existing.src !== src) {
+ existing.src = src;
+ }
+ if (el.end > 0 && (existing.end <= 0 || Math.abs(existing.end - el.end) > 0.0001)) {
+ existing.end = el.end;
+ }
+ if (el.mediaStart > 0 && (existing.mediaStart <= 0 || Math.abs(existing.mediaStart - el.mediaStart) > 0.0001)) {
+ existing.mediaStart = el.mediaStart;
+ }
+ if (el.volume > 0 && Math.abs((existing.volume ?? 1) - el.volume) > 0.0001) {
+ existing.volume = el.volume;
+ }
+ }
+ } else {
+ composition.audios.push({
+ id: el.id,
+ src,
+ start: el.start,
+ end: el.end,
+ mediaStart: el.mediaStart,
+ layer: 0,
+ volume: el.volume,
+ type: "audio",
+ });
+ existingAudioIds.add(el.id);
+ }
+ }
+ }
+ }
+ }
+ perfStages.browserProbeMs = Date.now() - probeStart;
+
+ job.duration = composition.duration;
+ job.totalFrames = Math.ceil(composition.duration * job.config.fps);
+
+ if (job.duration <= 0) {
+ throw new Error("Invalid composition duration: " + job.duration + ". Check that GSAP timelines are registered.");
+ }
+
+ perfStages.compileMs = Date.now() - stage1Start;
+
+ // ── Stage 2: Video frame extraction ─────────────────────────────────
+ const stage2Start = Date.now();
+ updateJobStatus(job, "preprocessing", "Extracting video frames", 10, onProgress);
+
+ let frameLookup: FrameLookupTable | null = null;
+
+ if (composition.videos.length > 0) {
+
+ const extractionResult = await extractAllVideoFrames(
+ composition.videos,
+ projectDir,
+ { fps: job.config.fps, outputDir: join(workDir, "video-frames") },
+ abortSignal,
+ );
+ assertNotAborted();
+
+ if (extractionResult.extracted.length > 0) {
+ frameLookup = createFrameLookupTable(
+ composition.videos,
+ extractionResult.extracted,
+ );
+ }
+
+ perfStages.videoExtractMs = Date.now() - stage2Start;
+
+ // Auto-detect audio from video files via ffprobe metadata
+ const existingAudioSrcs = new Set(composition.audios.map(a => a.src));
+ for (const ext of extractionResult.extracted) {
+ if (ext.metadata.hasAudio) {
+ const video = composition.videos.find(v => v.id === ext.videoId);
+ if (video && !existingAudioSrcs.has(video.src)) {
+ composition.audios.push({
+ id: `${video.id}-audio`,
+ src: video.src,
+ start: video.start,
+ end: video.end,
+ mediaStart: video.mediaStart,
+ layer: 0,
+ volume: 1.0,
+ type: "video",
+ });
+ existingAudioSrcs.add(video.src);
+ }
+ }
+ }
+ } else {
+ perfStages.videoExtractMs = Date.now() - stage2Start;
+ }
+
+ // ── Stage 3: Audio processing ───────────────────────────────────────
+ const stage3Start = Date.now();
+ updateJobStatus(job, "preprocessing", "Processing audio tracks", 20, onProgress);
+
+ const audioOutputPath = join(workDir, "audio.aac");
+ let hasAudio = false;
+
+ if (composition.audios.length > 0) {
+
+ const audioResult = await processCompositionAudio(
+ composition.audios,
+ projectDir,
+ join(workDir, "audio-work"),
+ audioOutputPath,
+ job.duration,
+ abortSignal,
+ );
+ assertNotAborted();
+
+ hasAudio = audioResult.success;
+ perfStages.audioProcessMs = Date.now() - stage3Start;
+ } else {
+ perfStages.audioProcessMs = Date.now() - stage3Start;
+ }
+
+ // ── Stage 4: Frame capture ──────────────────────────────────────────
+ const stage4Start = Date.now();
+ updateJobStatus(job, "rendering", "Starting frame capture", 25, onProgress);
+
+ // Start file server (may already be running from duration discovery)
+ if (!fileServer) {
+ fileServer = await createFileServer({ projectDir, compiledDir: join(workDir, "compiled"), port: 0 });
+ assertNotAborted();
+ }
+
+ const framesDir = join(workDir, "captured-frames");
+ if (!existsSync(framesDir)) mkdirSync(framesDir, { recursive: true });
+
+ const captureOptions: CaptureOptions = {
+ width,
+ height,
+ fps: job.config.fps,
+ format: "jpeg",
+ quality: job.config.quality === "draft" ? 80 : 95,
+ };
+
+ const workerCount = calculateOptimalWorkers(job.totalFrames!, job.config.workers, cfg);
+
+ const videoOnlyPath = join(workDir, "video-only.mp4");
+ const preset = ENCODER_PRESETS[job.config.quality];
+
+
+ job.framesRendered = 0;
+
+ // Streaming encode mode: pipe frame buffers directly to FFmpeg stdin,
+ // skipping disk writes and the separate Stage 5 encode step.
+ let streamingEncoder: StreamingEncoder | null = null;
+
+ if (enableStreamingEncode) {
+ streamingEncoder = await spawnStreamingEncoder(
+ videoOnlyPath,
+ {
+ fps: job.config.fps,
+ width,
+ height,
+ codec: preset.codec,
+ preset: preset.preset,
+ quality: preset.quality,
+ useGpu: job.config.useGpu,
+ imageFormat: captureOptions.format || "jpeg",
+ },
+ abortSignal,
+ );
+ assertNotAborted();
+ }
+
+ if (enableStreamingEncode && streamingEncoder) {
+ // ── Streaming capture + encode (Stage 4 absorbs Stage 5) ──────────
+ const reorderBuffer = createFrameReorderBuffer(0, job.totalFrames!);
+ const currentEncoder = streamingEncoder;
+
+ if (workerCount > 1) {
+ // Parallel capture → streaming encode
+ const tasks = distributeFrames(job.totalFrames, workerCount, workDir);
+
+ const onFrameBuffer = async (frameIndex: number, buffer: Buffer): Promise<void> => {
+ await reorderBuffer.waitForFrame(frameIndex);
+ currentEncoder.writeFrame(buffer);
+ reorderBuffer.advanceTo(frameIndex + 1);
+ };
+
+ await executeParallelCapture(
+ fileServer.url,
+ workDir,
+ tasks,
+ captureOptions,
+ () => createVideoFrameInjector(frameLookup),
+ abortSignal,
+ (progress) => {
+ job.framesRendered = progress.capturedFrames;
+ const frameProgress = progress.capturedFrames / progress.totalFrames;
+ const progressPct = 25 + frameProgress * 55;
+
+ if (
+ progress.capturedFrames % 30 === 0 ||
+ progress.capturedFrames === progress.totalFrames
+ ) {
+ updateJobStatus(
+ job,
+ "rendering",
+ `Streaming frame ${progress.capturedFrames}/${progress.totalFrames} (${workerCount} workers)`,
+ Math.round(progressPct),
+ onProgress
+ );
+ }
+ },
+ onFrameBuffer,
+ cfg,
+ );
+
+ if (probeSession) {
+ lastBrowserConsole = probeSession.browserConsoleBuffer;
+ await closeCaptureSession(probeSession);
+ probeSession = null;
+ }
+ } else {
+ // Sequential capture → streaming encode
+
+ const videoInjector = createVideoFrameInjector(frameLookup);
+ const session = probeSession ?? await createCaptureSession(
+ fileServer.url,
+ framesDir,
+ captureOptions,
+ videoInjector,
+ cfg,
+ );
+ if (probeSession) {
+ prepareCaptureSessionForReuse(session, framesDir, videoInjector);
+ probeSession = null;
+ }
+
+ try {
+ if (!session.isInitialized) {
+ await initializeSession(session);
+ }
+ assertNotAborted();
+ lastBrowserConsole = session.browserConsoleBuffer;
+
+ for (let i = 0; i < job.totalFrames!; i++) {
+ assertNotAborted();
+ const time = i / job.config.fps;
+ const { buffer } = await captureFrameToBuffer(session, i, time);
+ await reorderBuffer.waitForFrame(i);
+ currentEncoder.writeFrame(buffer);
+ reorderBuffer.advanceTo(i + 1);
+ job.framesRendered = i + 1;
+
+ const frameProgress = (i + 1) / job.totalFrames!;
+ const progress = 25 + frameProgress * 55;
+
+ updateJobStatus(
+ job,
+ "rendering",
+ `Streaming frame ${i + 1}/${job.totalFrames}`,
+ Math.round(progress),
+ onProgress
+ );
+ }
+ } finally {
+ lastBrowserConsole = session.browserConsoleBuffer;
+ await closeCaptureSession(session);
+ }
+ }
+
+ // Close encoder and get result
+ const encodeResult = await currentEncoder.close();
+ assertNotAborted();
+
+ if (!encodeResult.success) {
+ throw new Error(`Streaming encode failed: ${encodeResult.error}`);
+ }
+
+ perfStages.captureMs = Date.now() - stage4Start;
+ perfStages.encodeMs = encodeResult.durationMs; // Overlapped with capture
+ } else {
+ // ── Disk-based capture (original flow) ────────────────────────────
+ if (workerCount > 1) {
+ // Parallel capture
+ const tasks = distributeFrames(job.totalFrames, workerCount, workDir);
+
+ await executeParallelCapture(
+ fileServer.url,
+ workDir,
+ tasks,
+ captureOptions,
+ () => createVideoFrameInjector(frameLookup),
+ abortSignal,
+ (progress) => {
+ job.framesRendered = progress.capturedFrames;
+ const frameProgress = progress.capturedFrames / progress.totalFrames;
+ const progressPct = 25 + frameProgress * 45;
+
+ if (
+ progress.capturedFrames % 30 === 0 ||
+ progress.capturedFrames === progress.totalFrames
+ ) {
+ updateJobStatus(
+ job,
+ "rendering",
+ `Capturing frame ${progress.capturedFrames}/${progress.totalFrames} (${workerCount} workers)`,
+ Math.round(progressPct),
+ onProgress
+ );
+ }
+ },
+ undefined,
+ cfg,
+ );
+
+ await mergeWorkerFrames(workDir, tasks, framesDir);
+ if (probeSession) {
+ lastBrowserConsole = probeSession.browserConsoleBuffer;
+ await closeCaptureSession(probeSession);
+ probeSession = null;
+ }
+ } else {
+ // Sequential capture
+
+ const videoInjector = createVideoFrameInjector(frameLookup);
+ const session = probeSession ?? await createCaptureSession(
+ fileServer.url,
+ framesDir,
+ captureOptions,
+ videoInjector,
+ cfg,
+ );
+ if (probeSession) {
+ prepareCaptureSessionForReuse(session, framesDir, videoInjector);
+ probeSession = null;
+ }
+
+ try {
+ if (!session.isInitialized) {
+ await initializeSession(session);
+ }
+ assertNotAborted();
+ lastBrowserConsole = session.browserConsoleBuffer;
+
+ for (let i = 0; i < job.totalFrames; i++) {
+ assertNotAborted();
+ const time = i / job.config.fps;
+ await captureFrame(session, i, time);
+ job.framesRendered = i + 1;
+
+ const frameProgress = (i + 1) / job.totalFrames;
+ const progress = 25 + frameProgress * 45;
+
+ updateJobStatus(
+ job,
+ "rendering",
+ `Capturing frame ${i + 1}/${job.totalFrames}`,
+ Math.round(progress),
+ onProgress
+ );
+ }
+ } finally {
+ lastBrowserConsole = session.browserConsoleBuffer;
+ await closeCaptureSession(session);
+ }
+ }
+
+ perfStages.captureMs = Date.now() - stage4Start;
+
+ // ── Stage 5: Encode ─────────────────────────────────────────────────
+ const stage5Start = Date.now();
+ updateJobStatus(job, "encoding", "Encoding video", 75, onProgress);
+
+ const encodeResult = enableChunkedEncode
+ ? await encodeFramesChunkedConcat(
+ framesDir,
+ "frame_%06d.jpg",
+ videoOnlyPath,
+ {
+ fps: job.config.fps,
+ width,
+ height,
+ codec: preset.codec,
+ preset: preset.preset,
+ quality: preset.quality,
+ useGpu: job.config.useGpu,
+ },
+ chunkedEncodeSize,
+ abortSignal,
+ )
+ : await encodeFramesFromDir(
+ framesDir,
+ "frame_%06d.jpg",
+ videoOnlyPath,
+ {
+ fps: job.config.fps,
+ width,
+ height,
+ codec: preset.codec,
+ preset: preset.preset,
+ quality: preset.quality,
+ useGpu: job.config.useGpu,
+ },
+ abortSignal,
+ );
+ assertNotAborted();
+
+ if (!encodeResult.success) {
+ throw new Error(`Encoding failed: ${encodeResult.error}`);
+ }
+
+ perfStages.encodeMs = Date.now() - stage5Start;
+ }
+
+ if (probeSession !== null) {
+ const remainingProbeSession: CaptureSession = probeSession;
+ lastBrowserConsole = remainingProbeSession.browserConsoleBuffer;
+ await closeCaptureSession(remainingProbeSession);
+ probeSession = null;
+ }
+
+ if (frameLookup) frameLookup.cleanup();
+
+ // Stop file server
+ fileServer.close();
+ fileServer = null;
+
+ // ── Stage 6: Assemble ───────────────────────────────────────────────
+ const stage6Start = Date.now();
+ updateJobStatus(job, "assembling", "Assembling final video", 90, onProgress);
+
+ if (hasAudio) {
+ const muxResult = await muxVideoWithAudio(
+ videoOnlyPath,
+ audioOutputPath,
+ outputPath,
+ abortSignal,
+ );
+ assertNotAborted();
+ if (!muxResult.success) {
+ throw new Error(`Audio muxing failed: ${muxResult.error}`);
+ }
+ } else {
+ const faststartResult = await applyFaststart(videoOnlyPath, outputPath, abortSignal);
+ assertNotAborted();
+ if (!faststartResult.success) {
+ throw new Error(`Faststart failed: ${faststartResult.error}`);
+ }
+ }
+
+ perfStages.assembleMs = Date.now() - stage6Start;
+
+ // ── Complete ─────────────────────────────────────────────────────────
+ job.outputPath = outputPath;
+ updateJobStatus(job, "complete", "Render complete", 100, onProgress);
+
+ const totalElapsed = Date.now() - pipelineStart;
+
+ const perfSummary: RenderPerfSummary = {
+ renderId: job.id,
+ totalElapsedMs: totalElapsed,
+ fps: job.config.fps,
+ quality: job.config.quality,
+ workers: workerCount,
+ chunkedEncode: enableChunkedEncode,
+ chunkSizeFrames: enableChunkedEncode ? chunkedEncodeSize : null,
+ compositionDurationSeconds: composition.duration,
+ totalFrames: job.totalFrames!,
+ resolution: { width, height },
+ videoCount: composition.videos.length,
+ audioCount: composition.audios.length,
+ stages: perfStages,
+ captureAvgMs: job.totalFrames! > 0 ? Math.round((perfStages.captureMs ?? 0) / job.totalFrames!) : undefined,
+ };
+ job.perfSummary = perfSummary;
+ if (job.config.debug) {
+ try {
+ writeFileSync(perfOutputPath, JSON.stringify(perfSummary, null, 2), "utf-8");
+ } catch (err) {
+ log.debug("Failed to write perf summary", { perfOutputPath, error: err instanceof Error ? err.message : String(err) });
+ }
+ }
+
+ // ── Cleanup ─────────────────────────────────────────────────────────
+ if (job.config.debug) {
+ // Copy output MP4 into debug dir for easy access
+ if (existsSync(outputPath)) {
+ const debugOutput = join(workDir, "output.mp4");
+ copyFileSync(outputPath, debugOutput);
+ }
+ } else {
+ await safeCleanup("remove workDir", () => { rmSync(workDir, { recursive: true, force: true }); }, log);
+ }
+
+ if (restoreLogger) restoreLogger();
+ } catch (error) {
+ if (error instanceof RenderCancelledError || abortSignal?.aborted) {
+ job.error = error instanceof Error ? error.message : "render_cancelled";
+ updateJobStatus(job, "cancelled", "Render cancelled", job.progress, onProgress);
+ if (fileServer) {
+ await safeCleanup("close file server (cancel)", () => { fileServer.close(); }, log);
+ }
+ if (probeSession) {
+ const session = probeSession;
+ await safeCleanup("close probe session (cancel)", () => closeCaptureSession(session), log);
+ }
+ if (!job.config.debug) {
+ await safeCleanup("remove workDir (cancel)", () => {
+ rmSync(workDir, { recursive: true, force: true });
+ }, log);
+ }
+ if (restoreLogger) restoreLogger();
+ throw error instanceof RenderCancelledError ? error : new RenderCancelledError("render_cancelled");
+ }
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ const errorStack = error instanceof Error ? error.stack : undefined;
+ job.error = errorMessage;
+ updateJobStatus(
+ job,
+ "failed",
+ `Failed: ${errorMessage}`,
+ job.progress,
+ onProgress
+ );
+
+ // Diagnostic summary
+ const elapsed = Date.now() - pipelineStart;
+ const freeMemMB = Math.round(freemem() / (1024 * 1024));
+
+ // Populate structured error details for downstream consumers (SSE, sync response)
+ job.failedStage = job.currentStage;
+ job.errorDetails = {
+ message: errorMessage,
+ stack: errorStack,
+ elapsedMs: elapsed,
+ freeMemoryMB: freeMemMB,
+ browserConsoleTail: lastBrowserConsole.length > 0 ? lastBrowserConsole.slice(-30) : undefined,
+ perfStages: Object.keys(perfStages).length > 0 ? { ...perfStages } : undefined,
+ };
+
+
+ // Cleanup
+ if (fileServer) {
+ await safeCleanup("close file server (error)", () => { fileServer.close(); }, log);
+ }
+ if (probeSession) {
+ const session = probeSession;
+ await safeCleanup("close probe session (error)", () => closeCaptureSession(session), log);
+ }
+
+ if (!job.config.debug) {
+ await safeCleanup("remove workDir (error)", () => {
+ if (existsSync(workDir)) rmSync(workDir, { recursive: true, force: true });
+ }, log);
+ }
+
+ if (restoreLogger) restoreLogger();
+ throw error;
+ }
+}
diff --git a/packages/producer/src/services/screenshotService.ts b/packages/producer/src/services/screenshotService.ts
new file mode 100644
index 0000000000..a00cf3e2b9
--- /dev/null
+++ b/packages/producer/src/services/screenshotService.ts
@@ -0,0 +1,13 @@
+/**
+ * Re-exported from @hyperframes/engine.
+ * @see engine/src/services/screenshotService.ts for implementation.
+ */
+export {
+ beginFrameCapture,
+ pageScreenshotCapture,
+ getCdpSession,
+ injectVideoFramesBatch,
+ syncVideoFrameVisibility,
+ cdpSessionCache,
+ type BeginFrameResult,
+} from "@hyperframes/engine";
diff --git a/packages/producer/src/services/streamingEncoder.ts b/packages/producer/src/services/streamingEncoder.ts
new file mode 100644
index 0000000000..653c0b135b
--- /dev/null
+++ b/packages/producer/src/services/streamingEncoder.ts
@@ -0,0 +1,12 @@
+/**
+ * Re-exported from @hyperframes/engine.
+ * @see engine/src/services/streamingEncoder.ts for implementation.
+ */
+export {
+ spawnStreamingEncoder,
+ createFrameReorderBuffer,
+ type StreamingEncoder,
+ type StreamingEncoderOptions,
+ type StreamingEncoderResult,
+ type FrameReorderBuffer,
+} from "@hyperframes/engine";
diff --git a/packages/producer/src/services/timingCompiler.ts b/packages/producer/src/services/timingCompiler.ts
new file mode 100644
index 0000000000..40611d4225
--- /dev/null
+++ b/packages/producer/src/services/timingCompiler.ts
@@ -0,0 +1,212 @@
+/**
+ * Producer-local timing compiler helpers.
+ * Keep this aligned with core timing compiler behavior.
+ */
+
+export interface UnresolvedElement {
+ id: string;
+ tagName: string;
+ src?: string;
+ start: number;
+ end?: number;
+ duration?: number;
+ mediaStart: number;
+ compositionSrc?: string;
+}
+
+export interface ResolvedDuration {
+ id: string;
+ duration: number;
+}
+
+export interface ResolvedMediaElement {
+ id: string;
+ tagName: string;
+ src?: string;
+ start: number;
+ duration: number;
+ mediaStart: number;
+}
+
+export interface CompilationResult {
+ html: string;
+ unresolved: UnresolvedElement[];
+}
+
+function getAttr(tag: string, attr: string): string | null {
+ const match = tag.match(new RegExp(`${attr}=["']([^"']+)["']`));
+ return match ? match[1] ?? null : null;
+}
+
+function hasAttr(tag: string, attr: string): boolean {
+ return new RegExp(`${attr}=["']`).test(tag);
+}
+
+function injectAttr(tag: string, attr: string, value: string): string {
+ return tag.replace(/>$/, ` ${attr}="${value}">`);
+}
+
+function compileTag(tag: string, isVideo: boolean): { tag: string; unresolved: UnresolvedElement | null } {
+ let result = tag;
+ let unresolved: UnresolvedElement | null = null;
+ const id = getAttr(result, "id");
+ const startStr = getAttr(result, "data-start");
+ const start = startStr !== null ? parseFloat(startStr) : 0;
+ const mediaStartStr = getAttr(result, "data-media-start");
+ const mediaStart = mediaStartStr ? parseFloat(mediaStartStr) : 0;
+
+ if (!hasAttr(result, "data-end")) {
+ const durationStr = getAttr(result, "data-duration");
+ if (durationStr !== null) {
+ result = injectAttr(result, "data-end", String(start + parseFloat(durationStr)));
+ } else if (id) {
+ unresolved = {
+ id,
+ tagName: isVideo ? "video" : "audio",
+ src: getAttr(result, "src") ?? undefined,
+ start,
+ mediaStart,
+ };
+ }
+ }
+
+ if (isVideo && !hasAttr(result, "data-has-audio")) {
+ result = injectAttr(result, "data-has-audio", "true");
+ }
+
+ return { tag: result, unresolved };
+}
+
+export function compileTimingAttrs(html: string): CompilationResult {
+ const unresolved: UnresolvedElement[] = [];
+
+ html = html.replace(/<video[^>]*>/gi, (match) => {
+ const { tag, unresolved: u } = compileTag(match, true);
+ if (u) {
+ unresolved.push(u);
+ }
+ return tag;
+ });
+
+ html = html.replace(/<audio[^>]*>/gi, (match) => {
+ const { tag, unresolved: u } = compileTag(match, false);
+ if (u) {
+ unresolved.push(u);
+ }
+ return tag;
+ });
+
+ html.replace(/<(?:div|section)[^>]*>/gi, (match) => {
+ if (!hasAttr(match, "data-start")) {
+ return match;
+ }
+ if (hasAttr(match, "data-end") || hasAttr(match, "data-duration")) {
+ return match;
+ }
+ const id = getAttr(match, "id");
+ if (id) {
+ const startStr = getAttr(match, "data-start");
+ const compositionSrc = getAttr(match, "data-composition-src");
+ unresolved.push({
+ id,
+ tagName: "div",
+ start: startStr ? parseFloat(startStr) : 0,
+ mediaStart: 0,
+ compositionSrc: compositionSrc ?? undefined,
+ });
+ }
+ return match;
+ });
+
+ return { html, unresolved };
+}
+
+function escapeRegex(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+export function injectDurations(html: string, resolutions: ResolvedDuration[]): string {
+ for (const { id, duration } of resolutions) {
+ const idPattern = new RegExp(`(<[^>]*id=["']${escapeRegex(id)}["'][^>]*>)`, "gi");
+ html = html.replace(idPattern, (tag) => {
+ let result = tag;
+ if (!hasAttr(result, "data-duration")) {
+ result = injectAttr(result, "data-duration", String(duration));
+ }
+ if (!hasAttr(result, "data-end")) {
+ const startStr = getAttr(result, "data-start");
+ const start = startStr ? parseFloat(startStr) : 0;
+ result = injectAttr(result, "data-end", String(start + duration));
+ }
+ return result;
+ });
+ }
+ return html;
+}
+
+/**
+ * Extract video/audio elements that already have data-duration set.
+ * Used by callers to validate declared durations against actual source durations.
+ */
+export function extractResolvedMedia(html: string): ResolvedMediaElement[] {
+ const resolved: ResolvedMediaElement[] = [];
+
+ const mediaRegex = /<(?:video|audio)[^>]*>/gi;
+ let match: RegExpExecArray | null;
+ while ((match = mediaRegex.exec(html)) !== null) {
+ const tag = match[0];
+ const id = getAttr(tag, "id");
+ const durationStr = getAttr(tag, "data-duration");
+ if (!id || durationStr === null) continue;
+
+ const duration = parseFloat(durationStr);
+ if (!Number.isFinite(duration) || duration <= 0) continue;
+
+ const isVideo = /^<video/i.test(tag);
+ const startStr = getAttr(tag, "data-start");
+ const mediaStartStr = getAttr(tag, "data-media-start");
+
+ resolved.push({
+ id,
+ tagName: isVideo ? "video" : "audio",
+ src: getAttr(tag, "src") ?? undefined,
+ start: startStr !== null ? parseFloat(startStr) : 0,
+ duration,
+ mediaStart: mediaStartStr ? parseFloat(mediaStartStr) : 0,
+ });
+ }
+
+ return resolved;
+}
+
+/**
+ * Clamp existing data-duration and data-end on media elements.
+ * For each resolution, replaces the declared duration with the clamped value
+ * and recomputes data-end accordingly.
+ */
+export function clampDurations(html: string, clamps: ResolvedDuration[]): string {
+ for (const { id, duration } of clamps) {
+ const idPattern = new RegExp(`(<[^>]*id=["']${escapeRegex(id)}["'][^>]*>)`, "gi");
+
+ html = html.replace(idPattern, (tag) => {
+ // Replace data-duration value
+ tag = tag.replace(
+ /data-duration=["'][^"']*["']/,
+ `data-duration="${duration}"`
+ );
+
+ // Recompute data-end from data-start + clamped duration
+ const startStr = getAttr(tag, "data-start");
+ const start = startStr ? parseFloat(startStr) : 0;
+ tag = tag.replace(
+ /data-end=["'][^"']*["']/,
+ `data-end="${start + duration}"`
+ );
+
+ return tag;
+ });
+ }
+
+ return html;
+}
+
diff --git a/packages/producer/src/services/videoFrameExtractor.ts b/packages/producer/src/services/videoFrameExtractor.ts
new file mode 100644
index 0000000000..224e3b6eda
--- /dev/null
+++ b/packages/producer/src/services/videoFrameExtractor.ts
@@ -0,0 +1,16 @@
+/**
+ * Re-exported from @hyperframes/engine.
+ * @see engine/src/services/videoFrameExtractor.ts for implementation.
+ */
+export {
+ parseVideoElements,
+ extractVideoFramesRange,
+ extractAllVideoFrames,
+ getFrameAtTime,
+ createFrameLookupTable,
+ FrameLookupTable,
+ type VideoElement,
+ type ExtractedFrames,
+ type ExtractionOptions,
+ type ExtractionResult,
+} from "@hyperframes/engine";
diff --git a/packages/producer/src/services/videoFrameInjector.ts b/packages/producer/src/services/videoFrameInjector.ts
new file mode 100644
index 0000000000..df9c367862
--- /dev/null
+++ b/packages/producer/src/services/videoFrameInjector.ts
@@ -0,0 +1,5 @@
+/**
+ * Re-exported from @hyperframes/engine.
+ * @see engine/src/services/videoFrameInjector.ts for implementation.
+ */
+export { createVideoFrameInjector } from "@hyperframes/engine";
diff --git a/packages/producer/src/utils/ffprobe.ts b/packages/producer/src/utils/ffprobe.ts
new file mode 100644
index 0000000000..b356bac010
--- /dev/null
+++ b/packages/producer/src/utils/ffprobe.ts
@@ -0,0 +1,10 @@
+/**
+ * Re-exported from @hyperframes/engine.
+ * @see engine/src/utils/ffprobe.ts for implementation.
+ */
+export {
+ extractVideoMetadata,
+ extractAudioMetadata,
+ type VideoMetadata,
+ type AudioMetadata,
+} from "@hyperframes/engine";
diff --git a/packages/producer/src/utils/parityContract.ts b/packages/producer/src/utils/parityContract.ts
new file mode 100644
index 0000000000..e9fba2ab0b
--- /dev/null
+++ b/packages/producer/src/utils/parityContract.ts
@@ -0,0 +1,8 @@
+/**
+ * Re-exported from @hyperframes/engine.
+ * @see engine/src/utils/parityContract.ts for implementation.
+ */
+export {
+ quantizeTimeToFrame,
+ MEDIA_VISUAL_STYLE_PROPERTIES,
+} from "@hyperframes/engine";
diff --git a/packages/producer/src/utils/paths.ts b/packages/producer/src/utils/paths.ts
new file mode 100644
index 0000000000..0ec61d7b09
--- /dev/null
+++ b/packages/producer/src/utils/paths.ts
@@ -0,0 +1,27 @@
+/**
+ * Path resolution utilities for the render pipeline.
+ */
+
+import { resolve, basename, join } from "node:path";
+
+export interface RenderPaths {
+ absoluteProjectDir: string;
+ absoluteOutputPath: string;
+}
+
+const DEFAULT_RENDERS_DIR = process.env.PRODUCER_RENDERS_DIR
+ ?? resolve(new URL(import.meta.url).pathname, "../../..", "renders");
+
+export function resolveRenderPaths(
+ projectDir: string,
+ outputPath: string | null | undefined,
+ rendersDir: string = DEFAULT_RENDERS_DIR
+): RenderPaths {
+ const absoluteProjectDir = resolve(projectDir);
+ const projectName = basename(absoluteProjectDir);
+ const resolvedOutputPath =
+ outputPath ?? join(rendersDir, `${projectName}.mp4`);
+ const absoluteOutputPath = resolve(resolvedOutputPath);
+
+ return { absoluteProjectDir, absoluteOutputPath };
+}
diff --git a/packages/producer/src/utils/urlDownloader.ts b/packages/producer/src/utils/urlDownloader.ts
new file mode 100644
index 0000000000..23061139e4
--- /dev/null
+++ b/packages/producer/src/utils/urlDownloader.ts
@@ -0,0 +1,8 @@
+/**
+ * Re-exported from @hyperframes/engine.
+ * @see engine/src/utils/urlDownloader.ts for implementation.
+ */
+export {
+ downloadToTemp,
+ isHttpUrl,
+} from "@hyperframes/engine";
diff --git a/packages/producer/tests/chat/meta.json b/packages/producer/tests/chat/meta.json
new file mode 100644
index 0000000000..153ab258eb
--- /dev/null
+++ b/packages/producer/tests/chat/meta.json
@@ -0,0 +1,15 @@
+{
+ "name": "Chat Interface",
+ "description": "Tests chat interface composition with animations",
+ "tags": ["chat", "ui", "animations"],
+
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/chat/src/code_review.md b/packages/producer/tests/chat/src/code_review.md
new file mode 100644
index 0000000000..fe6bc69bf4
--- /dev/null
+++ b/packages/producer/tests/chat/src/code_review.md
@@ -0,0 +1,69 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 2
+- Critical issues: 1
+- Overall compliance status: NEEDS_WORK
+
+## Critical Issues
+
+### Empty Tweens for Duration
+- **File**: index.html:26
+- **File**: compositions/typography.html:224
+- **Violation**: `masterTL.to({}, { duration: 15 });` and `tl.to({}, { duration: 15 });`
+- **Schema Rule**: "NEVER create empty tweens like `tl.to({}, { duration: N })` just to set duration — use `data-duration` instead"
+- **Impact**: This is a direct violation of the schema's duration management rules. While it might work in some environments, it bypasses the framework's declarative duration system and can lead to rendering inconsistencies or failures in the server-side renderer.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track-index`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - no relative timing used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+### index.html
+**Status**: HAS_ISSUES
+
+**Issues Found**:
+- **Line 26**: Uses empty tween `masterTL.to({}, { duration: 15 });` to set duration. Should use `data-duration="15"` on the `#main` div (line 11) instead.
+
+### compositions/typography.html
+**Status**: HAS_ISSUES
+
+**Issues Found**:
+- **Line 224**: Uses empty tween `tl.to({}, { duration: 15 });` to set duration. Should use `data-duration="15"` on the composition root div (line 2) instead.
+- **Line 156**: `const sceneEl = document.querySelector(scene.id);` - While not a strict violation, it's better to scope queries to the composition root to avoid conflicts if multiple instances of the same composition are loaded.
+
+## Recommended Fixes
+
+### Fix 1: Declarative Duration in index.html
+Replace the empty tween with `data-duration` on the element.
+
+```html
+<!-- Change line 11 -->
+<div id="main" data-composition-id="main-comp" data-width="1080" data-height="1920" data-start="0" data-duration="15">
+
+<!-- Remove line 26 -->
+<!-- masterTL.to({}, { duration: 15 }); -->
+```
+
+### Fix 2: Declarative Duration in typography.html
+Replace the empty tween with `data-duration` on the element.
+
+```html
+<!-- Change line 2 -->
+<div data-composition-id="typography" data-width="1080" data-height="1920" data-duration="15">
+
+<!-- Remove line 224 -->
+<!-- tl.to({}, { duration: 15 }); -->
+```
diff --git a/packages/producer/tests/chat/src/compositions/typography.html b/packages/producer/tests/chat/src/compositions/typography.html
new file mode 100644
index 0000000000..c8ac94220f
--- /dev/null
+++ b/packages/producer/tests/chat/src/compositions/typography.html
@@ -0,0 +1,226 @@
+<template id="typography-template">
+ <div data-composition-id="typography" data-width="1080" data-height="1920" data-duration="15">
+ <div class="text-container">
+ <div id="scene-1" class="phrase">
+ <span class="word">TEXT</span>
+ <span class="word">ANIMATION</span>
+ </div>
+ <div id="scene-2" class="phrase">
+ <span class="word">WHAT</span>
+ <span class="word">DO</span>
+ <span class="word">YOU</span>
+ <span class="word">WANT</span>
+ <span class="word">TO</span>
+ <span class="word">WRITE?</span>
+ </div>
+ <div id="scene-3" class="phrase">
+ <span class="word">EVERYTHING</span>
+ <span class="word">YOU</span>
+ <span class="word">WANT,</span>
+ </div>
+ <div id="scene-4" class="phrase">
+ <span class="word">STANDING</span>
+ <span class="word">IN</span>
+ <span class="word">FRONT</span>
+ <span class="word">OF</span>
+ <span class="word">YOU.</span>
+ </div>
+ <div id="scene-5" class="phrase">
+ <span class="word">VERY</span>
+ <span class="word">EASY,</span>
+ </div>
+ <div id="scene-6" class="phrase">
+ <span class="word">AND</span>
+ <span class="word">FAST.</span>
+ </div>
+ <div id="scene-7" class="phrase">
+ <span class="word">SIT</span>
+ <span class="word">BACK</span>
+ <span class="word">AND</span>
+ <span class="word">RELAX</span>
+ <span class="cursor">|</span>
+ </div>
+ <div id="scene-8" class="phrase">
+ <span class="word">WHAT</span>
+ <span class="word">YOU</span>
+ <span class="word">ARE</span>
+ <span class="word">LOOKING</span>
+ <span class="word">FOR?</span>
+ </div>
+ <div id="scene-9" class="phrase">
+ <span class="word">THERE</span>
+ <span class="word">YOU</span>
+ <span class="word">HAVE</span>
+ <span class="word">IT!</span>
+ </div>
+ <div id="scene-10" class="phrase thank-you">
+ <span class="word">THANK</span>
+ <span class="word">YOU</span>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="typography"] .text-container {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ flex-direction: column;
+ color: white;
+ text-align: center;
+ }
+
+ [data-composition-id="typography"] .phrase {
+ font-size: 100px;
+ font-weight: 500;
+ opacity: 0;
+ position: absolute;
+ text-transform: uppercase;
+ letter-spacing: -2px;
+ width: 90%;
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 20px;
+ }
+
+ [data-composition-id="typography"] .word {
+ opacity: 0;
+ display: inline-block;
+ }
+
+ [data-composition-id="typography"] .glitch-overlay {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ mix-blend-mode: screen;
+ opacity: 0;
+ }
+
+ [data-composition-id="typography"] .chromatic {
+ color: #ff00ff;
+ transform: translateX(5px);
+ }
+
+ [data-composition-id="typography"] .chromatic-2 {
+ color: #00ffff;
+ transform: translateX(-5px);
+ }
+
+ [data-composition-id="typography"] .cursor {
+ opacity: 0;
+ margin-left: 10px;
+ }
+
+ [data-composition-id="typography"] .thank-you {
+ font-size: 150px;
+ background: linear-gradient(90deg, #00f2fe 0%, #4facfe 100%);
+ -webkit-background-clip: text;
+ -webkit-text-fill-color: transparent;
+ }
+
+ /* Glitch Effect Classes */
+ .glitch-flicker {
+ animation: flicker 0.1s infinite;
+ }
+
+ @keyframes flicker {
+ 0% { opacity: 0.5; transform: skew(2deg); }
+ 50% { opacity: 1; transform: skew(-2deg); }
+ 100% { opacity: 0.8; transform: skew(0deg); }
+ }
+ </style>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+
+ const scenes = [
+ { id: "#scene-1", start: 0.5, duration: 1.2 },
+ { id: "#scene-2", start: 2.0, duration: 1.8 },
+ { id: "#scene-3", start: 4.0, duration: 1.0 },
+ { id: "#scene-4", start: 5.2, duration: 1.5 },
+ { id: "#scene-5", start: 7.0, duration: 0.8 },
+ { id: "#scene-6", start: 8.0, duration: 0.8 },
+ { id: "#scene-7", start: 9.0, duration: 1.8 },
+ { id: "#scene-8", start: 11.0, duration: 1.5 },
+ { id: "#scene-9", start: 12.8, duration: 1.0 },
+ { id: "#scene-10", start: 14.0, duration: 1.0 }
+ ];
+
+ scenes.forEach((scene, index) => {
+ const startTime = scene.start;
+ const sceneEl = document.querySelector(scene.id);
+ const words = sceneEl.querySelectorAll(".word");
+
+ // Show scene container
+ tl.set(scene.id, { opacity: 1 }, startTime);
+
+ // Word by word appearance
+ words.forEach((word, wIndex) => {
+ const wordStart = startTime + (wIndex * 0.2);
+
+ // Creative Animation Variations
+ if (index % 3 === 0) {
+ // Fly-in from sides
+ const xOffset = wIndex % 2 === 0 ? -500 : 500;
+ tl.fromTo(word, { opacity: 0, x: xOffset, scale: 0.5 }, { opacity: 1, x: 0, scale: 1, duration: 0.4, ease: "back.out(1.7)" }, wordStart);
+ } else if (index % 3 === 1) {
+ // Fade-in with scale and rotation
+ tl.fromTo(word, { opacity: 0, scale: 0, rotation: -45 }, { opacity: 1, scale: 1, rotation: 0, duration: 0.5, ease: "elastic.out(1, 0.5)" }, wordStart);
+ } else {
+ // Pop-In & Flicker (Original)
+ tl.set(word, { opacity: 1, scale: 1.5 }, wordStart);
+ tl.to(word, { scale: 1, duration: 0.1, ease: "power4.out" }, wordStart);
+ }
+
+ // Glitch/Chromatic Aberration & Horizontal Displacement on major beats
+ tl.to(scene.id, {
+ x: (wIndex % 2 === 0 ? 15 : -15),
+ skewX: (wIndex % 2 === 0 ? 5 : -5),
+ duration: 0.05,
+ repeat: 1,
+ yoyo: true,
+ ease: "none"
+ }, wordStart);
+
+ // Color flash for specific words (purple, cyan, teal)
+ if (word.textContent.includes("ANIMATION") || word.textContent.includes("WRITE") || word.textContent.includes("FAST") || word.textContent.includes("EASY")) {
+ tl.to(word, { color: "#a855f7", duration: 0.1, repeat: 1, yoyo: true }, wordStart);
+ }
+ });
+
+ // Typewriter Cursor for Scene 7
+ if (scene.id === "#scene-7") {
+ const cursor = sceneEl.querySelector(".cursor");
+ tl.set(cursor, { opacity: 1 }, startTime + (words.length * 0.2));
+ tl.to(cursor, { opacity: 0, duration: 0.4, repeat: 3, yoyo: true, ease: "steps(1)" }, startTime + (words.length * 0.2));
+ }
+
+ // Outro: Whole line disappears
+ tl.set(scene.id, { opacity: 0 }, startTime + scene.duration);
+ });
+
+ // Special Outro for Thank You
+ tl.to("#scene-10", {
+ filter: "hue-rotate(360deg) drop-shadow(0 0 30px rgba(0, 255, 255, 1))",
+ scale: 1.2,
+ duration: 1.0,
+ ease: "power1.inOut"
+ }, 14.0);
+
+ tl.to("#scene-10 .word", {
+ opacity: 0,
+ y: -50,
+ stagger: 0.1,
+ duration: 0.5,
+ ease: "power2.in"
+ }, 14.5);
+
+ window.__timelines["typography"] = tl;
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/chat/src/index.html b/packages/producer/tests/chat/src/index.html
new file mode 100644
index 0000000000..21fb072f1a
--- /dev/null
+++ b/packages/producer/tests/chat/src/index.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Kinetic Typography Sequence</title>
+ <link rel="stylesheet" href="style.css">
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+</head>
+<body>
+ <div id="main" data-composition-id="main-comp" data-width="1080" data-height="1920" data-start="0" data-duration="15">
+ <!-- Audio Asset -->
+ <audio id="bg-music" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/f87f97d4_0c49f6fa95224cc3bd4f5ea3a0d937c5.wav" data-start="0" data-duration="15" data-track-index="0"></audio>
+
+ <!-- Typography Composition -->
+ <div id="typography-layer"
+ data-composition-id="typography"
+ data-composition-src="compositions/typography.html"
+ data-start="0"
+ data-track-index="1">
+ </div>
+ </div>
+
+ <script>
+ const masterTL = gsap.timeline({ paused: true });
+ window.__timelines["main-comp"] = masterTL;
+ </script>
+</body>
+</html>
diff --git a/packages/producer/tests/chat/src/style.css b/packages/producer/tests/chat/src/style.css
new file mode 100644
index 0000000000..5045fe1743
--- /dev/null
+++ b/packages/producer/tests/chat/src/style.css
@@ -0,0 +1,24 @@
+* {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+}
+
+html, body {
+ width: 100vw;
+ height: 100vh;
+ overflow: hidden;
+ background-color: #000;
+ font-family: 'Montserrat', sans-serif;
+}
+
+@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@500;900&display=swap');
+
+#main {
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+}
diff --git a/packages/producer/tests/dogs-captions/meta.json b/packages/producer/tests/dogs-captions/meta.json
new file mode 100644
index 0000000000..2b61ede09c
--- /dev/null
+++ b/packages/producer/tests/dogs-captions/meta.json
@@ -0,0 +1,15 @@
+{
+ "name": "Dogs with Captions",
+ "description": "Tests video composition with captions and animations",
+ "tags": ["video", "captions", "animations", "slow"],
+
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/dogs-captions/src/compositions/captions.html b/packages/producer/tests/dogs-captions/src/compositions/captions.html
new file mode 100644
index 0000000000..644de435fb
--- /dev/null
+++ b/packages/producer/tests/dogs-captions/src/compositions/captions.html
@@ -0,0 +1,119 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1080" data-height="1920">
+ <div id="captions-container"></div>
+
+ <style>
+ [data-composition-id="captions"] {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ display: flex;
+ justify-content: center;
+ align-items: flex-end;
+ padding-bottom: 400px; /* Position in lower third */
+ pointer-events: none;
+ }
+
+ #captions-container {
+ width: 900px;
+ text-align: center;
+ font-family: 'Arial', sans-serif; /* Fallback to system sans-serif */
+ font-weight: 900;
+ font-size: 72px;
+ color: white;
+ text-shadow: 4px 4px 8px rgba(0, 0, 0, 0.8);
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ }
+
+ .word {
+ margin: 0 10px;
+ opacity: 0;
+ display: inline-block;
+ }
+
+ .highlight {
+ color: #ffff00; /* Yellow highlight */
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'Dogs', 'start': 0.08, 'end': 0.44}, {'text': 'sleep', 'start': 0.52, 'end': 0.78}, {'text': 'in', 'start': 0.86, 'end': 0.93}, {'text': 'their', 'start': 0.98, 'end': 1.08}, {'text': 'humans', 'start': 1.14, 'end': 1.56}, {'text': 'bed', 'start': 1.66, 'end': 1.92}, {'text': 'for', 'start': 1.96, 'end': 2.05}, {'text': 'three', 'start': 2.18, 'end': 2.5}, {'text': 'powerful', 'start': 2.68, 'end': 3.11}, {'text': 'reasons', 'start': 3.16, 'end': 3.84}, {'text': 'And', 'start': 3.849, 'end': 3.94}, {'text': 'if', 'start': 4.0, 'end': 4.08}, {'text': 'you', 'start': 4.12, 'end': 4.26}, {'text': 'dont', 'start': 4.3, 'end': 4.47}, {'text': 'understand', 'start': 4.54, 'end': 5.06}, {'text': 'these', 'start': 5.12, 'end': 5.62}, {'text': 'youre', 'start': 5.66, 'end': 5.78}, {'text': 'probably', 'start': 5.82, 'end': 6.26}, {'text': 'missing', 'start': 6.32, 'end': 6.62}, {'text': 'the', 'start': 6.66, 'end': 6.8}, {'text': 'biggest', 'start': 6.84, 'end': 7.11}, {'text': 'danger', 'start': 7.22, 'end': 7.6}, {'text': 'hiding', 'start': 7.64, 'end': 7.96}, {'text': 'right', 'start': 8.0, 'end': 8.14}, {'text': 'under', 'start': 8.18, 'end': 8.38}, {'text': 'your', 'start': 8.42, 'end': 8.52}, {'text': 'nose', 'start': 8.56, 'end': 9.28}, {'text': 'First', 'start': 9.36, 'end': 9.98}, {'text': 'for', 'start': 10.02, 'end': 10.17}, {'text': 'your', 'start': 10.2, 'end': 10.32}, {'text': 'dog', 'start': 10.33, 'end': 10.78}, {'text': 'youre', 'start': 10.82, 'end': 10.92}, {'text': 'not', 'start': 10.93, 'end': 11.19}, {'text': 'their', 'start': 11.22, 'end': 11.36}, {'text': 'owner', 'start': 11.42, 'end': 11.93}, {'text': 'Youre', 'start': 11.98, 'end': 12.14}, {'text': 'their', 'start': 12.15, 'end': 12.3}, {'text': 'entire', 'start': 12.36, 'end': 12.94}, {'text': 'universe', 'start': 13.02, 'end': 13.89}, {'text': 'Sleeping', 'start': 13.9, 'end': 14.35}, {'text': 'beside', 'start': 14.4, 'end': 14.88}, {'text': 'you', 'start': 14.94, 'end': 15.04}, {'text': 'is', 'start': 15.1, 'end': 15.23}, {'text': 'the', 'start': 15.26, 'end': 15.34}, {'text': 'closest', 'start': 15.4, 'end': 15.86}, {'text': 'they', 'start': 15.9, 'end': 16.0}, {'text': 'ever', 'start': 16.059, 'end': 16.309}, {'text': 'feel', 'start': 16.34, 'end': 16.64}, {'text': 'to', 'start': 16.66, 'end': 16.8}, {'text': 'safety', 'start': 16.84, 'end': 17.73}, {'text': 'family', 'start': 17.78, 'end': 18.41}, {'text': 'and', 'start': 18.44, 'end': 18.55}, {'text': 'home', 'start': 18.68, 'end': 19.27}, {'text': 'That', 'start': 19.3, 'end': 19.45}, {'text': 'quiet', 'start': 19.5, 'end': 19.88}, {'text': 'nudge', 'start': 19.94, 'end': 20.2}, {'text': 'at', 'start': 20.24, 'end': 20.34}, {'text': 'night', 'start': 20.36, 'end': 20.96}, {'text': 'thats', 'start': 20.98, 'end': 21.24}, {'text': 'them', 'start': 21.25, 'end': 21.48}, {'text': 'saying', 'start': 21.56, 'end': 22.22}, {'text': '"Where', 'start': 22.23, 'end': 22.44}, {'text': 'you', 'start': 22.5, 'end': 22.6}, {'text': 'are', 'start': 22.7, 'end': 23.22}, {'text': 'thats', 'start': 23.26, 'end': 23.48}, {'text': 'where', 'start': 23.52, 'end': 23.64}, {'text': 'I', 'start': 23.76, 'end': 23.82}, {'text': 'belong"', 'start': 23.86, 'end': 24.7}, {'text': 'Second', 'start': 24.78, 'end': 25.48}, {'text': 'your', 'start': 25.54, 'end': 25.63}, {'text': 'warmth', 'start': 25.76, 'end': 26.36}, {'text': 'your', 'start': 26.4, 'end': 26.58}, {'text': 'scent', 'start': 26.64, 'end': 27.2}, {'text': 'your', 'start': 27.26, 'end': 27.39}, {'text': 'breathing', 'start': 27.42, 'end': 28.06}, {'text': 'your', 'start': 28.1, 'end': 28.23}, {'text': 'presence', 'start': 28.26, 'end': 28.68}, {'text': 'literally', 'start': 28.8, 'end': 29.18}, {'text': 'tell', 'start': 29.22, 'end': 29.4}, {'text': 'their', 'start': 29.42, 'end': 29.56}, {'text': 'nervous', 'start': 29.62, 'end': 29.94}, {'text': 'system', 'start': 29.98, 'end': 30.38}, {'text': '"Stand', 'start': 30.39, 'end': 30.74}, {'text': 'down', 'start': 30.8, 'end': 31.22}, {'text': 'Youre', 'start': 31.26, 'end': 31.4}, {'text': 'safe', 'start': 31.48, 'end': 31.74}, {'text': 'now"', 'start': 31.84, 'end': 32.4}, {'text': 'Thats', 'start': 32.42, 'end': 32.68}, {'text': 'why', 'start': 32.74, 'end': 32.88}, {'text': 'the', 'start': 32.92, 'end': 33.0}, {'text': 'moment', 'start': 33.04, 'end': 33.32}, {'text': 'you', 'start': 33.36, 'end': 33.44}, {'text': 'lie', 'start': 33.5, 'end': 33.65}, {'text': 'down', 'start': 33.74, 'end': 34.04}, {'text': 'your', 'start': 34.08, 'end': 34.24}, {'text': 'bed', 'start': 34.26, 'end': 34.46}, {'text': 'becomes', 'start': 34.54, 'end': 34.91}, {'text': 'the', 'start': 34.94, 'end': 35.0}, {'text': 'most', 'start': 35.06, 'end': 35.269}, {'text': 'valuable', 'start': 35.3, 'end': 35.74}, {'text': 'place', 'start': 35.78, 'end': 36.04}, {'text': 'in', 'start': 36.08, 'end': 36.17}, {'text': 'the', 'start': 36.2, 'end': 36.26}, {'text': 'house', 'start': 36.32, 'end': 36.99}, {'text': 'But', 'start': 37.0, 'end': 37.129}, {'text': 'heres', 'start': 37.18, 'end': 37.4}, {'text': 'the', 'start': 37.44, 'end': 37.54}, {'text': 'part', 'start': 37.58, 'end': 37.78}, {'text': 'most', 'start': 38.0, 'end': 38.25}, {'text': 'people', 'start': 38.26, 'end': 38.58}, {'text': 'dont', 'start': 38.62, 'end': 38.83}, {'text': 'realize', 'start': 38.86, 'end': 39.47}, {'text': 'Even', 'start': 39.52, 'end': 39.73}, {'text': 'in', 'start': 39.78, 'end': 39.86}, {'text': 'deep', 'start': 39.94, 'end': 40.129}, {'text': 'sleep', 'start': 40.26, 'end': 40.56}, {'text': 'dogs', 'start': 40.629, 'end': 40.9}, {'text': 'stay', 'start': 40.96, 'end': 41.16}, {'text': 'half-alert', 'start': 41.2, 'end': 41.84}, {'text': 'Their', 'start': 41.86, 'end': 42.04}, {'text': 'brain', 'start': 42.06, 'end': 42.32}, {'text': 'is', 'start': 42.34, 'end': 42.52}, {'text': 'wired', 'start': 42.58, 'end': 42.9}, {'text': 'to', 'start': 42.98, 'end': 43.04}, {'text': 'protect', 'start': 43.1, 'end': 43.54}, {'text': 'you', 'start': 43.6, 'end': 43.76}, {'text': 'If', 'start': 43.78, 'end': 43.9}, {'text': 'anything', 'start': 43.94, 'end': 44.28}, {'text': 'felt', 'start': 44.42, 'end': 44.64}, {'text': 'off', 'start': 44.68, 'end': 44.88}, {'text': 'a', 'start': 44.9, 'end': 44.96}, {'text': 'noise', 'start': 45.04, 'end': 45.44}, {'text': 'a', 'start': 45.46, 'end': 45.52}, {'text': 'movement', 'start': 45.62, 'end': 46.08}, {'text': 'a', 'start': 46.12, 'end': 46.22}, {'text': 'change', 'start': 46.3, 'end': 46.64}, {'text': 'in', 'start': 46.68, 'end': 46.76}, {'text': 'your', 'start': 46.8, 'end': 46.92}, {'text': 'breathing', 'start': 46.96, 'end': 47.72}, {'text': 'your', 'start': 47.76, 'end': 47.84}, {'text': 'dog', 'start': 47.92, 'end': 48.18}, {'text': 'would', 'start': 48.22, 'end': 48.34}, {'text': 'wake', 'start': 48.4, 'end': 48.58}, {'text': 'up', 'start': 48.64, 'end': 48.76}, {'text': 'before', 'start': 48.78, 'end': 49.08}, {'text': 'you', 'start': 49.12, 'end': 49.18}, {'text': 'ever', 'start': 49.22, 'end': 49.44}, {'text': 'did', 'start': 49.48, 'end': 50.06}, {'text': 'Thats', 'start': 50.08, 'end': 50.3}, {'text': 'the', 'start': 50.34, 'end': 50.4}, {'text': 'level', 'start': 50.52, 'end': 50.72}, {'text': 'of', 'start': 50.8, 'end': 50.88}, {'text': 'loyalty', 'start': 50.94, 'end': 51.42}, {'text': 'were', 'start': 51.5, 'end': 51.62}, {'text': 'talking', 'start': 51.64, 'end': 52.04}, {'text': 'about', 'start': 52.08, 'end': 52.38}, {'text': 'And', 'start': 52.4, 'end': 52.5}, {'text': 'this', 'start': 52.54, 'end': 52.66}, {'text': 'is', 'start': 52.72, 'end': 52.82}, {'text': 'exactly', 'start': 52.86, 'end': 53.46}, {'text': 'why', 'start': 53.56, 'end': 53.83}, {'text': 'the', 'start': 54.02, 'end': 54.1}, {'text': 'next', 'start': 54.16, 'end': 54.34}, {'text': 'part', 'start': 54.46, 'end': 54.72}, {'text': 'matters', 'start': 54.96, 'end': 55.28}, {'text': 'so', 'start': 55.36, 'end': 55.46}, {'text': 'much', 'start': 55.56, 'end': 55.78}, {'text': 'because', 'start': 55.84, 'end': 56.12}, {'text': 'dogs', 'start': 56.18, 'end': 56.46}, {'text': 'give', 'start': 56.54, 'end': 56.66}, {'text': 'us', 'start': 56.7, 'end': 56.88}, {'text': 'unfiltered', 'start': 56.94, 'end': 57.54}, {'text': 'love', 'start': 57.6, 'end': 58.14}, {'text': 'but', 'start': 58.18, 'end': 58.3}, {'text': 'they', 'start': 58.32, 'end': 58.48}, {'text': 'hide', 'start': 58.54, 'end': 58.82}, {'text': 'their', 'start': 58.84, 'end': 59.019}, {'text': 'pain', 'start': 59.08, 'end': 59.64}, {'text': 'They', 'start': 59.66, 'end': 59.76}, {'text': 'dont', 'start': 59.8, 'end': 60.02}, {'text': 'complain', 'start': 60.06, 'end': 60.88}, {'text': 'They', 'start': 60.9, 'end': 61.01}, {'text': 'dont', 'start': 61.06, 'end': 61.3}, {'text': 'tell', 'start': 61.31, 'end': 61.56}, {'text': 'you', 'start': 61.68, 'end': 61.9}, {'text': 'when', 'start': 61.91, 'end': 62.14}, {'text': 'something', 'start': 62.22, 'end': 62.54}, {'text': 'is', 'start': 62.6, 'end': 62.74}, {'text': 'wrong', 'start': 62.76, 'end': 63.12}, {'text': 'They', 'start': 63.14, 'end': 63.22}, {'text': 'just', 'start': 63.34, 'end': 63.56}, {'text': 'keep', 'start': 63.62, 'end': 63.82}, {'text': 'loving', 'start': 63.88, 'end': 64.18}, {'text': 'you', 'start': 64.28, 'end': 64.739}, {'text': 'even', 'start': 64.819, 'end': 65.06}, {'text': 'while', 'start': 65.099, 'end': 65.26}, {'text': 'their', 'start': 65.3, 'end': 65.459}, {'text': 'body', 'start': 65.5, 'end': 65.82}, {'text': 'is', 'start': 65.88, 'end': 66.0}, {'text': 'taking', 'start': 66.04, 'end': 66.35}, {'text': 'damage', 'start': 66.46, 'end': 67.08}, {'text': 'And', 'start': 67.1, 'end': 67.2}, {'text': 'one', 'start': 67.26, 'end': 67.36}, {'text': 'of', 'start': 67.4, 'end': 67.46}, {'text': 'the', 'start': 67.5, 'end': 67.6}, {'text': 'biggest', 'start': 67.62, 'end': 67.96}, {'text': 'hidden', 'start': 68.0, 'end': 68.22}, {'text': 'threats', 'start': 68.34, 'end': 68.74}, {'text': 'doesnt', 'start': 68.94, 'end': 69.28}, {'text': 'come', 'start': 69.34, 'end': 69.66}, {'text': 'from', 'start': 69.7, 'end': 69.85}, {'text': 'where', 'start': 69.88, 'end': 70.04}, {'text': 'most', 'start': 70.1, 'end': 70.36}, {'text': 'people', 'start': 70.38, 'end': 70.7}, {'text': 'think', 'start': 70.74, 'end': 71.1}, {'text': 'It', 'start': 71.14, 'end': 71.24}, {'text': 'comes', 'start': 71.3, 'end': 71.53}, {'text': 'from', 'start': 71.58, 'end': 71.74}, {'text': 'what', 'start': 71.8, 'end': 71.89}, {'text': 'we', 'start': 72.0, 'end': 72.16}, {'text': 'spray', 'start': 72.24, 'end': 72.62}, {'text': 'on', 'start': 72.7, 'end': 72.84}, {'text': 'them', 'start': 72.88, 'end': 73.26}, {'text': 'Most', 'start': 73.32, 'end': 73.58}, {'text': 'flea', 'start': 73.7, 'end': 73.88}, {'text': 'and', 'start': 73.92, 'end': 74.0}, {'text': 'tick', 'start': 74.1, 'end': 74.26}, {'text': 'products', 'start': 74.34, 'end': 74.72}, {'text': 'rely', 'start': 74.78, 'end': 75.04}, {'text': 'on', 'start': 75.08, 'end': 75.18}, {'text': 'harsh', 'start': 75.22, 'end': 75.44}, {'text': 'chemicals', 'start': 75.54, 'end': 76.12}, {'text': 'neurotoxins', 'start': 76.2, 'end': 77.08}, {'text': 'pesticides', 'start': 77.12, 'end': 78.1}, {'text': 'stuff', 'start': 78.22, 'end': 78.42}, {'text': 'designed', 'start': 78.48, 'end': 78.96}, {'text': 'to', 'start': 79.0, 'end': 79.06}, {'text': 'kill', 'start': 79.16, 'end': 79.34}, {'text': 'living', 'start': 79.4, 'end': 79.66}, {'text': 'organisms', 'start': 79.72, 'end': 80.34}, {'text': 'on', 'start': 80.4, 'end': 80.56}, {'text': 'contact', 'start': 80.6, 'end': 81.62}, {'text': 'And', 'start': 81.64, 'end': 81.74}, {'text': 'over', 'start': 81.8, 'end': 81.94}, {'text': 'time', 'start': 82.06, 'end': 82.62}, {'text': 'those', 'start': 82.66, 'end': 82.86}, {'text': 'chemicals', 'start': 82.9, 'end': 83.35}, {'text': 'dont', 'start': 83.44, 'end': 83.62}, {'text': 'just', 'start': 83.68, 'end': 83.86}, {'text': 'disappear', 'start': 83.9, 'end': 84.82}, {'text': 'They', 'start': 84.86, 'end': 84.96}, {'text': 'get', 'start': 85.0, 'end': 85.1}, {'text': 'absorbed', 'start': 85.16, 'end': 85.64}, {'text': 'through', 'start': 85.68, 'end': 85.86}, {'text': 'the', 'start': 85.92, 'end': 86.02}, {'text': 'skin', 'start': 86.08, 'end': 86.68}, {'text': 'inhaled', 'start': 86.78, 'end': 87.28}, {'text': 'and', 'start': 87.32, 'end': 87.45}, {'text': 'stored', 'start': 87.54, 'end': 87.8}, {'text': 'in', 'start': 87.84, 'end': 87.92}, {'text': 'the', 'start': 87.94, 'end': 88.04}, {'text': 'body', 'start': 88.06, 'end': 88.98}, {'text': 'Slowly', 'start': 89.04, 'end': 89.81}, {'text': 'quietly', 'start': 89.86, 'end': 90.64}, {'text': 'they', 'start': 90.7, 'end': 90.83}, {'text': 'can', 'start': 90.84, 'end': 90.95}, {'text': 'impact', 'start': 91.0, 'end': 91.36}, {'text': 'the', 'start': 91.42, 'end': 91.54}, {'text': 'liver', 'start': 91.56, 'end': 92.16}, {'text': 'breathing', 'start': 92.18, 'end': 92.98}, {'text': 'the', 'start': 92.99, 'end': 93.08}, {'text': 'nervous', 'start': 93.14, 'end': 93.38}, {'text': 'system', 'start': 93.48, 'end': 94.14}, {'text': 'hormones', 'start': 94.24, 'end': 95.28}, {'text': 'and', 'start': 95.32, 'end': 95.39}, {'text': 'even', 'start': 95.46, 'end': 95.74}, {'text': 'shorten', 'start': 95.82, 'end': 96.2}, {'text': 'lifespan', 'start': 96.32, 'end': 97.26}, {'text': 'And', 'start': 97.28, 'end': 97.38}, {'text': 'youd', 'start': 97.42, 'end': 97.54}, {'text': 'never', 'start': 97.58, 'end': 97.8}, {'text': 'notice', 'start': 97.86, 'end': 98.14}, {'text': 'it', 'start': 98.2, 'end': 98.28}, {'text': 'happening', 'start': 98.32, 'end': 99.1}, {'text': 'because', 'start': 99.14, 'end': 99.52}, {'text': 'dogs', 'start': 99.56, 'end': 99.94}, {'text': 'dont', 'start': 99.96, 'end': 100.16}, {'text': 'show', 'start': 100.2, 'end': 100.4}, {'text': 'pain', 'start': 100.46, 'end': 100.7}, {'text': 'the', 'start': 100.74, 'end': 100.8}, {'text': 'way', 'start': 100.84, 'end': 101.0}, {'text': 'humans', 'start': 101.06, 'end': 101.39}, {'text': 'do', 'start': 101.4, 'end': 101.98}, {'text': 'So', 'start': 102.04, 'end': 102.12}, {'text': 'whats', 'start': 102.24, 'end': 102.48}, {'text': 'the', 'start': 102.49, 'end': 102.61}, {'text': 'safer', 'start': 102.68, 'end': 103.06}, {'text': 'option', 'start': 103.14, 'end': 103.8}, {'text': 'Not', 'start': 103.84, 'end': 104.04}, {'text': 'leaving', 'start': 104.08, 'end': 104.36}, {'text': 'your', 'start': 104.4, 'end': 104.48}, {'text': 'dog', 'start': 104.56, 'end': 104.78}, {'text': 'unprotected', 'start': 104.86, 'end': 105.82}, {'text': 'because', 'start': 105.86, 'end': 106.12}, {'text': 'fleas', 'start': 106.22, 'end': 106.5}, {'text': 'and', 'start': 106.52, 'end': 106.6}, {'text': 'ticks', 'start': 106.7, 'end': 107.0}, {'text': 'absolutely', 'start': 107.1, 'end': 107.64}, {'text': 'carry', 'start': 107.7, 'end': 107.96}, {'text': 'parasites', 'start': 108.02, 'end': 108.56}, {'text': 'and', 'start': 108.58, 'end': 108.67}, {'text': 'disease', 'start': 108.72, 'end': 109.54}, {'text': 'but', 'start': 109.58, 'end': 109.68}, {'text': 'also', 'start': 109.76, 'end': 110.16}, {'text': 'not', 'start': 110.3, 'end': 110.539}, {'text': 'flooding', 'start': 110.64, 'end': 110.96}, {'text': 'your', 'start': 111.0, 'end': 111.1}, {'text': 'dogs', 'start': 111.14, 'end': 111.48}, {'text': 'body', 'start': 111.52, 'end': 111.78}, {'text': 'with', 'start': 111.9, 'end': 112.05}, {'text': 'chemicals', 'start': 112.08, 'end': 112.58}, {'text': 'just', 'start': 112.64, 'end': 112.78}, {'text': 'to', 'start': 112.8, 'end': 112.93}, {'text': 'solve', 'start': 112.96, 'end': 113.24}, {'text': 'one', 'start': 113.34, 'end': 113.5}, {'text': 'problem', 'start': 113.52, 'end': 114.05}, {'text': 'The', 'start': 114.05, 'end': 114.16}, {'text': 'smarter', 'start': 114.24, 'end': 114.58}, {'text': 'choice', 'start': 114.62, 'end': 114.94}, {'text': 'is', 'start': 115.0, 'end': 115.15}, {'text': 'natural', 'start': 115.18, 'end': 115.55}, {'text': 'protection', 'start': 115.56, 'end': 116.13}, {'text': 'that', 'start': 116.18, 'end': 116.3}, {'text': 'repels', 'start': 116.32, 'end': 116.82}, {'text': 'pests', 'start': 116.86, 'end': 117.23}, {'text': 'without', 'start': 117.26, 'end': 117.59}, {'text': 'compromising', 'start': 117.62, 'end': 118.31}, {'text': 'health', 'start': 118.36, 'end': 118.88}, {'text': 'Thats', 'start': 118.94, 'end': 119.14}, {'text': 'why', 'start': 119.18, 'end': 119.29}, {'text': 'I', 'start': 119.29, 'end': 119.42}, {'text': 'recommend', 'start': 119.48, 'end': 119.9}, {'text': 'a', 'start': 119.94, 'end': 120.02}, {'text': 'natural', 'start': 120.04, 'end': 120.57}, {'text': 'essential', 'start': 120.6, 'end': 121.21}, {'text': 'oil-based', 'start': 121.26, 'end': 121.9}, {'text': 'flea', 'start': 121.94, 'end': 122.16}, {'text': 'spray', 'start': 122.2, 'end': 122.54}, {'text': 'instead', 'start': 122.86, 'end': 123.14}, {'text': 'of', 'start': 123.18, 'end': 123.26}, {'text': 'chemical', 'start': 123.28, 'end': 123.64}, {'text': 'treatments', 'start': 123.74, 'end': 124.54}, {'text': 'Protect', 'start': 124.56, 'end': 124.9}, {'text': 'your', 'start': 124.94, 'end': 125.02}, {'text': 'dog', 'start': 125.08, 'end': 125.48}, {'text': 'but', 'start': 125.52, 'end': 125.6}, {'text': 'dont', 'start': 125.66, 'end': 125.9}, {'text': 'poison', 'start': 125.96, 'end': 126.26}, {'text': 'them', 'start': 126.28, 'end': 126.4}, {'text': 'in', 'start': 126.46, 'end': 126.5}, {'text': 'the', 'start': 126.54, 'end': 126.62}, {'text': 'process', 'start': 126.66, 'end': 127.66}, {'text': 'And', 'start': 127.7, 'end': 127.8}, {'text': 'for', 'start': 127.84, 'end': 127.94}, {'text': 'anyone', 'start': 128.0, 'end': 128.24}, {'text': 'watching', 'start': 128.32, 'end': 128.66}, {'text': 'this', 'start': 128.72, 'end': 128.88}, {'text': 'online', 'start': 129.08, 'end': 129.94}, {'text': 'Bug', 'start': 129.979, 'end': 130.16}, {'text': 'MD', 'start': 130.28, 'end': 130.58}, {'text': 'Flea', 'start': 130.699, 'end': 130.94}, {'text': '&', 'start': 131.0, 'end': 131.06}, {'text': 'Tick', 'start': 131.18, 'end': 131.52}, {'text': 'is', 'start': 131.58, 'end': 131.66}, {'text': 'available', 'start': 131.7, 'end': 132.16}, {'text': 'on', 'start': 132.18, 'end': 132.34}, {'text': 'Amazon', 'start': 132.36, 'end': 133.26}, {'text': 'And', 'start': 133.269, 'end': 133.36}, {'text': 'Ive', 'start': 133.42, 'end': 133.52}, {'text': 'also', 'start': 133.58, 'end': 133.84}, {'text': 'linked', 'start': 133.86, 'end': 134.1}, {'text': 'it', 'start': 134.14, 'end': 134.22}, {'text': 'in', 'start': 134.3, 'end': 134.36}, {'text': 'my', 'start': 134.4, 'end': 134.5}, {'text': 'Instagram', 'start': 134.56, 'end': 134.98}, {'text': 'profile', 'start': 135.06, 'end': 135.74}, {'text': 'If', 'start': 135.82, 'end': 135.88}, {'text': 'youre', 'start': 135.9, 'end': 136.0}, {'text': 'watching', 'start': 136.06, 'end': 136.34}, {'text': 'online', 'start': 136.4, 'end': 136.84}, {'text': 'and', 'start': 136.92, 'end': 137.04}, {'text': 'want', 'start': 137.12, 'end': 137.3}, {'text': 'my', 'start': 137.36, 'end': 137.5}, {'text': 'exact', 'start': 137.54, 'end': 138.12}, {'text': 'natural', 'start': 138.4, 'end': 138.769}, {'text': 'flea', 'start': 138.88, 'end': 139.08}, {'text': 'spray', 'start': 139.14, 'end': 139.38}, {'text': 'recipe', 'start': 139.46, 'end': 140.08}, {'text': 'comment', 'start': 140.14, 'end': 140.48}, {'text': 'fleas', 'start': 140.56, 'end': 141.04}, {'text': 'and', 'start': 141.1, 'end': 141.18}, {'text': 'Ill', 'start': 141.22, 'end': 141.359}, {'text': 'send', 'start': 141.42, 'end': 141.6}, {'text': 'it', 'start': 141.64, 'end': 141.72}, {'text': 'to', 'start': 141.78, 'end': 141.88}, {'text': 'you', 'start': 141.94, 'end': 142.32}];
+ const container = document.getElementById('captions-container');
+ const tl = gsap.timeline({ paused: true });
+
+ if (!TRANSCRIPT || TRANSCRIPT.length === 0) {
+ window.__timelines["captions"] = tl;
+ return;
+ }
+
+ // Group words into chunks of 3-5 words for better readability
+ const chunks = [];
+ let currentChunk = [];
+ for (let i = 0; i < TRANSCRIPT.length; i++) {
+ currentChunk.push(TRANSCRIPT[i]);
+ if (currentChunk.length >= 4 || i === TRANSCRIPT.length - 1) {
+ chunks.push([...currentChunk]);
+ currentChunk = [];
+ }
+ }
+
+ chunks.forEach((chunk, chunkIndex) => {
+ const chunkStartTime = chunk[0].start;
+ const chunkEndTime = chunk[chunk.length - 1].end;
+
+ // Create a div for this chunk
+ const chunkDiv = document.createElement('div');
+ chunkDiv.className = 'chunk';
+ chunkDiv.style.position = 'absolute';
+ chunkDiv.style.opacity = 0;
+ chunkDiv.style.width = '100%';
+ chunkDiv.style.display = 'flex';
+ chunkDiv.style.flexWrap = 'wrap';
+ chunkDiv.style.justifyContent = 'center';
+ container.appendChild(chunkDiv);
+
+ // Show chunk
+ tl.to(chunkDiv, { opacity: 1, duration: 0.1 }, chunkStartTime);
+
+ chunk.forEach((wordData, wordIndex) => {
+ const wordSpan = document.createElement('span');
+ wordSpan.className = 'word';
+ wordSpan.innerText = wordData.text.toUpperCase();
+ chunkDiv.appendChild(wordSpan);
+
+ // Animate word appearance
+ tl.to(wordSpan, {
+ opacity: 1,
+ scale: 1.1,
+ duration: 0.1
+ }, wordData.start);
+
+ // Highlight current word
+ tl.to(wordSpan, {
+ color: '#ffff00',
+ duration: 0.05
+ }, wordData.start);
+
+ // Remove highlight when next word starts or chunk ends
+ const nextTime = (wordIndex < chunk.length - 1) ? chunk[wordIndex + 1].start : chunkEndTime;
+ tl.to(wordSpan, {
+ color: '#ffffff',
+ scale: 1.0,
+ duration: 0.05
+ }, nextTime);
+ });
+
+ // Hide chunk
+ tl.to(chunkDiv, { opacity: 0, duration: 0.1 }, chunkEndTime);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/dogs-captions/src/index.html b/packages/producer/tests/dogs-captions/src/index.html
new file mode 100644
index 0000000000..e368bdea3f
--- /dev/null
+++ b/packages/producer/tests/dogs-captions/src/index.html
@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Dog Safety Video with Captions</title>
+ <link rel="stylesheet" href="style.css">
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+</head>
+<body>
+ <div id="main" data-composition-id="main-comp" data-start="0" data-width="1080" data-height="1920">
+ <!-- Main Video -->
+ <video id="video-1"
+ data-start="0"
+ data-duration="142.36"
+ data-track-index="0"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/12ca139c_8bf35a3b61b84ab69251ad5091e4c69b.mp4"
+ crossorigin="anonymous">
+ </video>
+
+ <!-- Captions Composition -->
+ <div id="captions-comp"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="144.36"
+ data-track-index="1">
+ </div>
+
+ <script src="script.js"></script>
+ </div>
+</body>
+</html>
diff --git a/packages/producer/tests/dogs-captions/src/script.js b/packages/producer/tests/dogs-captions/src/script.js
new file mode 100644
index 0000000000..4464616c40
--- /dev/null
+++ b/packages/producer/tests/dogs-captions/src/script.js
@@ -0,0 +1,2 @@
+const tl = gsap.timeline({ paused: true });
+window.__timelines["main-comp"] = tl;
diff --git a/packages/producer/tests/dogs-captions/src/style.css b/packages/producer/tests/dogs-captions/src/style.css
new file mode 100644
index 0000000000..f6da388d3f
--- /dev/null
+++ b/packages/producer/tests/dogs-captions/src/style.css
@@ -0,0 +1,24 @@
+* {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+}
+
+html, body {
+ width: 100vw;
+ height: 100vh;
+ overflow: hidden;
+ background-color: black;
+}
+
+#main {
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+}
+
+video {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
diff --git a/packages/producer/tests/font-variant-numeric/meta.json b/packages/producer/tests/font-variant-numeric/meta.json
new file mode 100644
index 0000000000..847516344d
--- /dev/null
+++ b/packages/producer/tests/font-variant-numeric/meta.json
@@ -0,0 +1,15 @@
+{
+ "name": "Font Variant Numeric",
+ "description": "Tests that font-variant-numeric: tabular-nums does not crash the layout stability gate's document.fonts.check() call",
+ "tags": ["fonts", "css", "layout-stability"],
+
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+
+ "renderConfig": {
+ "fps": 24
+ }
+}
diff --git a/packages/producer/tests/font-variant-numeric/src/index.html b/packages/producer/tests/font-variant-numeric/src/index.html
new file mode 100644
index 0000000000..3abff5aa13
--- /dev/null
+++ b/packages/producer/tests/font-variant-numeric/src/index.html
@@ -0,0 +1,77 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8"/>
+<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
+<title>Font Variant Numeric Test</title>
+<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+<style>
+ @import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap');
+
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1080px;
+ height: 1920px;
+ background: #0F172A;
+ overflow: hidden;
+ font-family: 'Space Mono', monospace;
+ }
+
+ #main-comp {
+ position: relative;
+ width: 1080px;
+ height: 1920px;
+ }
+
+ .counter {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ font-family: 'Space Mono', monospace;
+ font-size: 120px;
+ font-weight: 700;
+ color: #6366F1;
+ /* This is the CSS property that was crashing document.fonts.check() */
+ font-variant-numeric: tabular-nums;
+ }
+
+ .label {
+ position: absolute;
+ top: 35%;
+ left: 50%;
+ transform: translateX(-50%);
+ font-size: 24px;
+ letter-spacing: 4px;
+ color: #94A3B8;
+ text-transform: uppercase;
+ }
+</style>
+</head>
+<body>
+<div id="main-comp" data-composition-id="main-comp" data-width="1080" data-height="1920" data-start="0" data-duration="3">
+ <div class="label">COUNTER</div>
+ <div class="counter" id="counter-value">0000</div>
+ <!-- Silent audio to satisfy regression harness audio comparison -->
+ <audio id="silence" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/f87f97d4_0c49f6fa95224cc3bd4f5ea3a0d937c5.wav" data-start="0" data-duration="3" data-volume="0" data-track-index="0"></audio>
+</div>
+
+<script>
+ const tl = gsap.timeline({ paused: true });
+ window.__timelines = window.__timelines || {};
+ window.__timelines["main-comp"] = tl;
+
+ const counterEl = document.getElementById("counter-value");
+ const obj = { val: 0 };
+ tl.to(obj, {
+ val: 9999,
+ duration: 3,
+ ease: "none",
+ onUpdate: () => {
+ counterEl.textContent = String(Math.round(obj.val)).padStart(4, "0");
+ }
+ });
+</script>
+</body>
+</html>
diff --git a/packages/producer/tests/many-cuts/meta.json b/packages/producer/tests/many-cuts/meta.json
new file mode 100644
index 0000000000..df1ace4d19
--- /dev/null
+++ b/packages/producer/tests/many-cuts/meta.json
@@ -0,0 +1,15 @@
+{
+ "name": "Magic Cut - Many Rapid Transitions",
+ "description": "Tests composition with rapid text transitions and synchronized audio clicks",
+ "tags": ["animations", "audio", "timing", "cuts", "transitions"],
+
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/many-cuts/src/code_review.md b/packages/producer/tests/many-cuts/src/code_review.md
new file mode 100644
index 0000000000..025d1753d2
--- /dev/null
+++ b/packages/producer/tests/many-cuts/src/code_review.md
@@ -0,0 +1,49 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 3
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None. The composition follows the HyperFrame schema correctly.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track-index`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - absolute timing used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files (N/A - single composition)
+- [x] Composition files use `<template>` tags (N/A - root composition)
+- [x] External compositions loaded via `data-composition-src` (N/A)
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+### index.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. The root composition is correctly defined with `data-composition-id`, `data-width`, `data-height`, `data-start`, and `data-track-index`.
+- Audio clips are correctly defined with `id`, `data-start`, `data-duration`, and `data-track-index`.
+- Tracks are used correctly to avoid overlap for audio clips.
+
+### script.js
+**Status**: COMPLIANT
+
+**Issues Found**:
+- **Determinism**: The script uses a deterministic approach for particle generation (lines 47, 51) instead of `Math.random()`. This is excellent and follows the "CRITICAL: Deterministic Behavior Required" rule.
+- **Timeline Registration**: The timeline is correctly registered in `window.__timelines["magic-cut-intro"]`.
+- **Framework Alignment**: The script focuses on visual animations (opacity, scale, particles) and does not attempt to control audio playback or clip lifecycle, which is correct.
+
+### style.css
+**Status**: COMPLIANT
+
+**Issues Found**:
+- The dimensions match the requested Portrait (9:16) orientation (1080x1920).
+- Layout is handled via CSS, which is the correct approach.
diff --git a/packages/producer/tests/many-cuts/src/index.html b/packages/producer/tests/many-cuts/src/index.html
new file mode 100644
index 0000000000..9f80f19902
--- /dev/null
+++ b/packages/producer/tests/many-cuts/src/index.html
@@ -0,0 +1,47 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Magic Cut Intro</title>
+ <link rel="stylesheet" href="style.css">
+ <link href="https://fonts.googleapis.com/css2?family=Bangers&family=Lobster&family=Montserrat:wght@900&family=Playfair+Display:ital,wght@1,900&family=Press+Start+2P&family=Syncopate:wght@700&display=swap" rel="stylesheet">
+</head>
+<body>
+ <div id="container" data-composition-id="magic-cut-intro" data-width="1080" data-height="1920" data-start="0" data-duration="5.6" data-track-index="1">
+ <div class="text-variant" id="v1">Magic Cut</div>
+ <div class="text-variant" id="v2">Magic Cut</div>
+ <div class="text-variant" id="v3">Magic Cut</div>
+ <div class="text-variant" id="v4">Magic Cut</div>
+ <div class="text-variant" id="v5">Magic Cut</div>
+ <div class="text-variant" id="v6">Magic Cut</div>
+ <div class="text-variant" id="v7">Magic Cut</div>
+ <div class="text-variant" id="v8">Magic Cut</div>
+ <div class="text-variant" id="v9">Magic Cut</div>
+ <div class="text-variant" id="v10">Magic Cut</div>
+ <div class="text-variant" id="v11">Magic Cut</div>
+ <div class="text-variant" id="v12">Magic Cut</div>
+ <div class="text-variant" id="v13">Magic Cut</div>
+ <div id="final-message">Meet your Editing Agent</div>
+ <div id="particles-container"></div>
+
+ <!-- 9 Audio clicks synced with first 9 cuts -->
+ <audio id="click1" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52be8a19_b6ad2cf680444264933b185ff8295074.mp3" data-start="0" data-duration="0.2" data-track-index="2" crossorigin="anonymous"></audio>
+ <audio id="click2" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52be8a19_b6ad2cf680444264933b185ff8295074.mp3" data-start="0.2" data-duration="0.2" data-track-index="3" crossorigin="anonymous"></audio>
+ <audio id="click3" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52be8a19_b6ad2cf680444264933b185ff8295074.mp3" data-start="0.4" data-duration="0.2" data-track-index="4" crossorigin="anonymous"></audio>
+ <audio id="click4" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52be8a19_b6ad2cf680444264933b185ff8295074.mp3" data-start="0.6" data-duration="0.2" data-track-index="5" crossorigin="anonymous"></audio>
+ <audio id="click5" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52be8a19_b6ad2cf680444264933b185ff8295074.mp3" data-start="0.8" data-duration="0.2" data-track-index="6" crossorigin="anonymous"></audio>
+ <audio id="click6" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52be8a19_b6ad2cf680444264933b185ff8295074.mp3" data-start="1.0" data-duration="0.2" data-track-index="7" crossorigin="anonymous"></audio>
+ <audio id="click7" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52be8a19_b6ad2cf680444264933b185ff8295074.mp3" data-start="1.2" data-duration="0.2" data-track-index="8" crossorigin="anonymous"></audio>
+ <audio id="click8" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52be8a19_b6ad2cf680444264933b185ff8295074.mp3" data-start="1.4" data-duration="0.2" data-track-index="9" crossorigin="anonymous"></audio>
+ <audio id="click9" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52be8a19_b6ad2cf680444264933b185ff8295074.mp3" data-start="1.6" data-duration="0.2" data-track-index="10" crossorigin="anonymous"></audio>
+ <audio id="click10" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52be8a19_b6ad2cf680444264933b185ff8295074.mp3" data-start="1.8" data-duration="0.2" data-track-index="11" crossorigin="anonymous"></audio>
+ <audio id="click11" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52be8a19_b6ad2cf680444264933b185ff8295074.mp3" data-start="2.0" data-duration="0.2" data-track-index="12" crossorigin="anonymous"></audio>
+ <audio id="click12" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52be8a19_b6ad2cf680444264933b185ff8295074.mp3" data-start="2.2" data-duration="0.2" data-track-index="13" crossorigin="anonymous"></audio>
+ <audio id="click13" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52be8a19_b6ad2cf680444264933b185ff8295074.mp3" data-start="2.4" data-duration="0.2" data-track-index="14" crossorigin="anonymous"></audio>
+ <audio id="epic-boom" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/02937d93_65b31a3a3d1f4568b0516b66343245d6.mp3" data-start="2.6" data-duration="3.0" data-track-index="15" crossorigin="anonymous"></audio>
+ </div>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <script src="script.js"></script>
+</body>
+</html>
\ No newline at end of file
diff --git a/packages/producer/tests/many-cuts/src/script.js b/packages/producer/tests/many-cuts/src/script.js
new file mode 100644
index 0000000000..063f3f0dec
--- /dev/null
+++ b/packages/producer/tests/many-cuts/src/script.js
@@ -0,0 +1,78 @@
+const masterTL = gsap.timeline({ paused: true });
+
+const variants = ['#v1', '#v2', '#v3', '#v4', '#v5', '#v6', '#v7', '#v8', '#v9', '#v10', '#v11', '#v12', '#v13'];
+const cutDuration = 0.2;
+
+variants.forEach((selector, index) => {
+ // Show current variant
+ masterTL.set(selector, {
+ opacity: 1
+ }, index * cutDuration);
+
+ // Hide previous variant
+ if (index > 0) {
+ masterTL.set(variants[index - 1], {
+ opacity: 0
+ }, index * cutDuration);
+ }
+});
+
+const finalStartTime = variants.length * cutDuration; // 2.6s
+
+// Hide last variant
+masterTL.set(variants[variants.length - 1], {
+ opacity: 0
+}, finalStartTime);
+
+// Show final message with epic effect
+masterTL.to('#final-message', {
+ opacity: 1,
+ scale: 1,
+ duration: 0.8,
+ ease: "elastic.out(1, 0.5)"
+}, finalStartTime);
+
+// Explosion Particles
+const particlesContainer = document.getElementById('particles-container');
+const particleCount = 120; // Increased count
+const colors = ['#FFD700', '#FF4500', '#FF69B4', '#00FFFF', '#FFF', '#ADFF2F', '#FF8C00'];
+
+for (let i = 0; i < particleCount; i++) {
+ const particle = document.createElement('div');
+ particle.className = 'particle';
+ particlesContainer.appendChild(particle);
+
+ const angle = (i / particleCount) * Math.PI * 2;
+ // Deterministic "randomness" using modulo and index
+ const velocity = 400 + 600 * ((i * 7) % 10 / 10); // Increased velocity for bigger explosion
+ const x = Math.cos(angle) * velocity;
+ const y = Math.sin(angle) * velocity;
+ const color = colors[i % colors.length];
+ const size = 8 + 12 * ((i * 3) % 5 / 5); // Varied sizes
+
+ masterTL.set(particle, {
+ x: 540,
+ y: 960,
+ width: size,
+ height: size,
+ xPercent: -50,
+ yPercent: -50,
+ backgroundColor: color,
+ opacity: 1,
+ scale: 1
+ }, finalStartTime);
+
+ masterTL.to(particle, {
+ x: 540 + x,
+ y: 960 + y,
+ opacity: 0,
+ scale: 0,
+ rotation: (i % 2 === 0 ? 360 : -360), // Add some rotation
+ duration: 2.0, // Longer duration for bigger feel
+ ease: "power3.out"
+ }, finalStartTime);
+}
+
+// Register the timeline
+window.__timelines = window.__timelines || {};
+window.__timelines["magic-cut-intro"] = masterTL;
diff --git a/packages/producer/tests/many-cuts/src/style.css b/packages/producer/tests/many-cuts/src/style.css
new file mode 100644
index 0000000000..1c48f2b8f7
--- /dev/null
+++ b/packages/producer/tests/many-cuts/src/style.css
@@ -0,0 +1,147 @@
+* {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+}
+
+html, body {
+ width: 1080px;
+ height: 1920px;
+ overflow: hidden;
+ background-color: #000; /* Black */
+}
+
+#container {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ position: relative;
+}
+
+.text-variant {
+ position: absolute;
+ width: 100%;
+ left: 0;
+ top: 50%;
+ transform: translateY(-50%);
+ text-align: center;
+ opacity: 0;
+ font-size: 120px;
+ text-transform: uppercase;
+ padding: 20px;
+}
+
+#v1 {
+ font-family: 'Montserrat', sans-serif;
+ color: #FFF;
+ font-weight: 900;
+}
+
+#v2 {
+ font-family: 'Bangers', cursive;
+ color: #FFD700; /* Gold */
+}
+
+#v3 {
+ font-family: 'Press Start 2P', cursive;
+ color: #00FF00; /* Neon Green */
+ font-size: 80px;
+}
+
+#v4 {
+ font-family: 'Lobster', cursive;
+ color: #FF69B4; /* Hot Pink */
+ text-transform: none;
+}
+
+#v5 {
+ font-family: 'Syncopate', sans-serif;
+ color: #00FFFF; /* Cyan */
+ font-weight: 700;
+}
+
+#v6 {
+ font-family: 'Playfair Display', serif;
+ color: #FF4500; /* OrangeRed */
+ font-style: italic;
+}
+
+#v7 {
+ font-family: 'Montserrat', sans-serif;
+ color: #ADFF2F; /* GreenYellow */
+ font-weight: 300;
+}
+
+#v8 {
+ font-family: 'Bangers', cursive;
+ color: #DA70D6; /* Orchid */
+}
+
+#v9 {
+ font-family: 'Press Start 2P', cursive;
+ color: #F0E68C; /* Khaki */
+ font-size: 80px;
+}
+
+#v10 {
+ font-family: 'Lobster', cursive;
+ color: #7FFFD4; /* Aquamarine */
+ text-transform: none;
+}
+
+#v11 {
+ font-family: 'Syncopate', sans-serif;
+ color: #FFB6C1; /* LightPink */
+ font-weight: 700;
+}
+
+#v12 {
+ font-family: 'Playfair Display', serif;
+ color: #E0FFFF; /* LightCyan */
+ font-style: normal;
+ font-weight: 900;
+}
+
+#v13 {
+ font-family: 'Montserrat', sans-serif;
+ color: #FFA500; /* Orange */
+ font-weight: 900;
+}
+
+#final-message {
+ position: absolute;
+ width: 100%;
+ left: 0;
+ top: 50%;
+ transform: translateY(-50%) scale(0.8);
+ text-align: center;
+ opacity: 0;
+ font-size: 120px; /* Bigger */
+ font-family: 'Montserrat', sans-serif;
+ color: #FFF;
+ font-weight: 900;
+ padding: 40px;
+ letter-spacing: -2px;
+ z-index: 10;
+}
+
+#particles-container {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ left: 0;
+ top: 0;
+ pointer-events: none;
+}
+
+.particle {
+ position: absolute;
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ opacity: 0;
+ left: 0;
+ top: 0;
+}
\ No newline at end of file
diff --git a/packages/producer/tests/missing-host-comp-id/meta.json b/packages/producer/tests/missing-host-comp-id/meta.json
new file mode 100644
index 0000000000..648000b42d
--- /dev/null
+++ b/packages/producer/tests/missing-host-comp-id/meta.json
@@ -0,0 +1,12 @@
+{
+ "name": "Missing Host Composition Id",
+ "description": "Ensures producer preserves scoped composition wrappers when hosts omit data-composition-id",
+ "tags": ["composition", "scoped-css", "producer"],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 24
+ }
+}
diff --git a/packages/producer/tests/missing-host-comp-id/src/compositions/scoped-text.html b/packages/producer/tests/missing-host-comp-id/src/compositions/scoped-text.html
new file mode 100644
index 0000000000..a28e639358
--- /dev/null
+++ b/packages/producer/tests/missing-host-comp-id/src/compositions/scoped-text.html
@@ -0,0 +1,36 @@
+<template id="scoped-text-template">
+ <div
+ data-composition-id="scoped-text"
+ data-width="1080"
+ data-height="1920"
+ data-duration="3"
+ >
+ <div class="label">Scoped Text Should Stay Styled</div>
+
+ <style>
+ [data-composition-id="scoped-text"] {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: rgb(12, 12, 12);
+ }
+
+ [data-composition-id="scoped-text"] .label {
+ color: rgb(255, 214, 10);
+ font-family: Helvetica, Arial, sans-serif;
+ font-size: 88px;
+ font-weight: 700;
+ letter-spacing: -0.04em;
+ }
+ </style>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+ tl.to({}, { duration: 3 });
+ window.__timelines = window.__timelines || {};
+ window.__timelines["scoped-text"] = tl;
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/missing-host-comp-id/src/index.html b/packages/producer/tests/missing-host-comp-id/src/index.html
new file mode 100644
index 0000000000..0c858195da
--- /dev/null
+++ b/packages/producer/tests/missing-host-comp-id/src/index.html
@@ -0,0 +1,40 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Missing Host Composition Id</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+</head>
+<body>
+ <div
+ id="main-comp"
+ data-composition-id="master"
+ data-width="1080"
+ data-height="1920"
+ data-duration="3"
+ >
+ <audio
+ id="silence-track"
+ src="silence.wav"
+ data-start="0"
+ data-duration="3"
+ data-track-index="0"
+ ></audio>
+ <div
+ id="scoped-text-host"
+ data-composition-src="compositions/scoped-text.html"
+ data-start="0"
+ data-duration="3"
+ data-track-index="1"
+ ></div>
+ </div>
+
+ <script>
+ const masterTl = gsap.timeline({ paused: true });
+ masterTl.to({}, { duration: 3 });
+ window.__timelines = window.__timelines || {};
+ window.__timelines["master"] = masterTl;
+ </script>
+</body>
+</html>
diff --git a/packages/producer/tests/missing-host-comp-id/src/silence.wav b/packages/producer/tests/missing-host-comp-id/src/silence.wav
new file mode 100644
index 0000000000..b9113c424a
Binary files /dev/null and b/packages/producer/tests/missing-host-comp-id/src/silence.wav differ
diff --git a/packages/producer/tests/parity/README.md b/packages/producer/tests/parity/README.md
new file mode 100644
index 0000000000..465fa5a582
--- /dev/null
+++ b/packages/producer/tests/parity/README.md
@@ -0,0 +1,25 @@
+# Producer Parity Fixtures
+
+Fixtures used by `src/parity-harness.ts`.
+
+- `fixtures/minimal-wysiwyg.html`: CI-safe fixture with deterministic animation.
+- `fixtures/good-preview-bad-producer.json`: checkpoint metadata for the known border-radius parity regression.
+
+## Local run example
+
+```bash
+cd producer/tests/parity/fixtures
+python3 -m http.server 4173
+```
+
+Then in another terminal:
+
+```bash
+cd producer
+pnpm parity:check \
+ --preview-url "http://127.0.0.1:4173/minimal-wysiwyg.html" \
+ --producer-url "http://127.0.0.1:4173/minimal-wysiwyg.html?mode=producer" \
+ --checkpoints "0,0.5,1,1.5" \
+ --allow-mismatch-ratio 0 \
+ --emulate-producer-swap true
+```
diff --git a/packages/producer/tests/parity/fixtures/minimal-wysiwyg.html b/packages/producer/tests/parity/fixtures/minimal-wysiwyg.html
new file mode 100644
index 0000000000..559efac8c0
--- /dev/null
+++ b/packages/producer/tests/parity/fixtures/minimal-wysiwyg.html
@@ -0,0 +1,71 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Parity Fixture</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <script
+ data-hyperframes-preview-runtime="1"
+ src=""
+ ></script>
+ <style>
+ html,
+ body {
+ margin: 0;
+ width: 640px;
+ height: 360px;
+ overflow: hidden;
+ background: #0f172a;
+ }
+
+ #root {
+ width: 640px;
+ height: 360px;
+ position: relative;
+ overflow: hidden;
+ }
+
+ #animated-card {
+ position: absolute;
+ top: 80px;
+ left: 180px;
+ width: 280px;
+ height: 200px;
+ border-radius: 0px;
+ background: linear-gradient(135deg, #06b6d4, #6366f1);
+ }
+ </style>
+ </head>
+ <body>
+ <div
+ id="root"
+ data-composition-id="main-video"
+ data-width="640"
+ data-height="360"
+ data-duration="2"
+ data-fps="30"
+ >
+ <div id="animated-card" data-start="0"></div>
+ </div>
+ <script>
+ (function () {
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#animated-card", {
+ borderRadius: "48px",
+ x: 50,
+ duration: 1,
+ ease: "none",
+ });
+ tl.to("#animated-card", {
+ borderRadius: "12px",
+ x: 0,
+ duration: 1,
+ ease: "none",
+ });
+ window.__timelines = window.__timelines || {};
+ window.__timelines["main-video"] = tl;
+ })();
+ </script>
+ </body>
+</html>
diff --git a/packages/producer/tests/perf/baseline.json b/packages/producer/tests/perf/baseline.json
new file mode 100644
index 0000000000..557b92b117
--- /dev/null
+++ b/packages/producer/tests/perf/baseline.json
@@ -0,0 +1,4 @@
+{
+ "parityFixtureMaxMs": 90000,
+ "allowedRegressionRatio": 0.15
+}
diff --git a/packages/producer/tests/perf/benchmark-results.json b/packages/producer/tests/perf/benchmark-results.json
new file mode 100644
index 0000000000..5bd0d994cd
--- /dev/null
+++ b/packages/producer/tests/perf/benchmark-results.json
@@ -0,0 +1,59 @@
+{
+ "timestamp": "2026-03-11T01:22:09.852Z",
+ "platform": "linux x64",
+ "nodeVersion": "v22.17.0",
+ "runsPerFixture": 1,
+ "fixtures": [
+ {
+ "fixture": "missing-host-comp-id",
+ "name": "Missing Host Composition Id",
+ "runs": [
+ {
+ "run": 1,
+ "perfSummary": {
+ "renderId": "0afc2d13-2bc0-4eda-9134-1efeb6a15908",
+ "totalElapsedMs": 5620,
+ "fps": 24,
+ "quality": "high",
+ "workers": 2,
+ "chunkedEncode": false,
+ "chunkSizeFrames": null,
+ "compositionDurationSeconds": 3,
+ "totalFrames": 72,
+ "resolution": {
+ "width": 1080,
+ "height": 1920
+ },
+ "videoCount": 0,
+ "audioCount": 1,
+ "stages": {
+ "compileOnlyMs": 29,
+ "browserProbeMs": 0,
+ "compileMs": 30,
+ "videoExtractMs": 0,
+ "audioProcessMs": 136,
+ "captureMs": 4832,
+ "encodeMs": 528,
+ "assembleMs": 94
+ },
+ "captureAvgMs": 67
+ }
+ }
+ ],
+ "averages": {
+ "totalElapsedMs": 5620,
+ "captureAvgMs": 67,
+ "stages": {
+ "compileOnlyMs": 29,
+ "browserProbeMs": 0,
+ "compileMs": 30,
+ "videoExtractMs": 0,
+ "audioProcessMs": 136,
+ "captureMs": 4832,
+ "encodeMs": 528,
+ "assembleMs": 94
+ }
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/packages/producer/tests/style-1-prod/meta.json b/packages/producer/tests/style-1-prod/meta.json
new file mode 100644
index 0000000000..4bdb2813bc
--- /dev/null
+++ b/packages/producer/tests/style-1-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-1-prod",
+ "description": "Regression fixture imported from normalized style pack style-1-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "landscape"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-1-prod/src/code_review.md b/packages/producer/tests/style-1-prod/src/code_review.md
new file mode 100644
index 0000000000..790883f4aa
--- /dev/null
+++ b/packages/producer/tests/style-1-prod/src/code_review.md
@@ -0,0 +1,63 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 3
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None. The compositions follow the deterministic requirements and essential timeline registration rules.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images used)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - absolute timing used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+## File Reviews
+
+### index.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Correctly defines the root composition `main-video`.
+- Uses `data-width="1920"` and `data-height="1080"` as requested for Landscape orientation.
+- Properly registers `window.__timelines["main-video"]`.
+- Loads sub-compositions using `data-composition-src`.
+- Primitive clips (`video`, `audio`) have required `id`, `data-start`, and `data-track`.
+- Track assignments are clean: Track 0 (BG), Track 1 (Video), Track 2 (Graphics), Track 3 (Captions), Track 4 (Audio).
+
+### compositions/captions.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Uses `<template>` tag correctly.
+- Root element has `data-composition-id`, `data-width`, `data-height`, and `data-duration`.
+- Script is deterministic, using a fixed `TRANSCRIPT` array.
+- Correctly registers `window.__timelines["captions"]`.
+- Note: The `data-composition-id` in the HTML is `captions`, and the script registers `captions`. In `index.html`, the container has `data-composition-id="captions-comp"`. The framework typically matches the registration to the ID of the element being instantiated. Since the template root has `data-composition-id="captions"`, this is the ID that should be registered.
+
+### compositions/graphics.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Uses `<template>` tag correctly.
+- Root element has `data-composition-id`, `data-width`, `data-height`, and `data-duration`.
+- Animations are deterministic GSAP tweens.
+- Correctly registers `window.__timelines["graphics-comp"]`.
+- Layout is well-coordinated with the A-roll positioning defined in the master timeline.
+
+## Recommendations
+- **Consistency**: In `index.html`, the captions container uses `data-composition-id="captions-comp"`, but the template inside `captions.html` uses `data-composition-id="captions"`. While the framework handles the swap during instantiation, keeping these IDs identical (e.g., both `captions`) improves maintainability.
+- **Deterministic Logic**: The use of `(function() { ... })()` in sub-compositions is a good practice for scoping.
diff --git a/packages/producer/tests/style-1-prod/src/compositions/captions.html b/packages/producer/tests/style-1-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..7906503af9
--- /dev/null
+++ b/packages/producer/tests/style-1-prod/src/compositions/captions.html
@@ -0,0 +1,94 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1920" data-height="1080" data-duration="17">
+ <div id="captions-container"></div>
+
+ <style>
+ [data-composition-id="captions"] {
+ width: 1920px;
+ height: 1080px;
+ position: relative; /* Changed from flex to absolute positioning for precision */
+ pointer-events: none;
+ background: transparent;
+ }
+
+ [data-composition-id="captions"] #captions-container {
+ position: absolute;
+ bottom: 54px; /* 5% of 1080px */
+ left: 0;
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ }
+
+ [data-composition-id="captions"] .caption-line {
+ position: absolute;
+ bottom: 0;
+ /* No left: 50% here, we rely on the container's flex centering */
+ background-color: #000000; /* Dark solid background strip */
+ color: #FFFFFF; /* White */
+ font-family: 'Futura', 'DIN Alternate', 'Arial Black', sans-serif;
+ font-weight: 900;
+ font-size: 56px;
+ padding: 15px 40px;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ opacity: 0;
+ white-space: nowrap;
+ display: inline-block;
+ z-index: 100;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.86, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics,', 'start': 3.579, 'end': 4.599}, {'text': 'sixty-two', 'start': 4.679, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.079, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.42}, {'text': 'look', 'start': 10.519, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want,', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.859}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Editor', 'start': 15.079, 'end': 15.42}, {'text': 'Agent.', 'start': 15.619, 'end': 16.02}];
+ const container = document.getElementById('captions-container');
+ const tl = gsap.timeline({ paused: true });
+
+ const lines = [];
+ let currentLine = [];
+
+ TRANSCRIPT.forEach((word, index) => {
+ currentLine.push(word);
+ if (currentLine.length === 5 || index === TRANSCRIPT.length - 1) {
+ lines.push({
+ words: [...currentLine],
+ text: currentLine.map(w => w.text).join(' ').toUpperCase()
+ });
+ currentLine = [];
+ }
+ });
+
+ lines.forEach((line, index) => {
+ const startTime = line.words[0].start;
+ const endTime = line.words[line.words.length - 1].end;
+
+ const lineEl = document.createElement('div');
+ lineEl.className = 'caption-line';
+ lineEl.textContent = line.text;
+ container.appendChild(lineEl);
+
+ // Center the line element relative to the container
+ gsap.set(lineEl, { left: '50%', xPercent: -50 });
+
+ tl.to(lineEl, {
+ opacity: 1,
+ y: -20,
+ duration: 0.2,
+ ease: 'power2.out'
+ }, startTime);
+
+ tl.to(lineEl, {
+ opacity: 0,
+ y: -40,
+ duration: 0.1,
+ ease: 'power2.in'
+ }, endTime);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-1-prod/src/compositions/graphics.html b/packages/producer/tests/style-1-prod/src/compositions/graphics.html
new file mode 100644
index 0000000000..40227f25a5
--- /dev/null
+++ b/packages/producer/tests/style-1-prod/src/compositions/graphics.html
@@ -0,0 +1,239 @@
+<template id="graphics-template">
+ <div data-composition-id="graphics-comp" data-width="1920" data-height="1080" data-duration="17">
+ <!-- Intro Elements -->
+ <div class="intro-container">
+ <div class="black-circle"></div>
+ <div class="intro-text">ASKED & ANSWERED</div>
+ </div>
+
+ <!-- Stat 1: 47% NEED MOTION (A-roll is at right: x:700, y:216) -->
+ <div class="stat-container stat-1">
+ <div class="vermillion-square"></div>
+ <div class="stat-number">47%</div>
+ <div class="stat-subtext">NEED MOTION</div>
+ </div>
+
+ <!-- Stat 2: 62% INEFFECTIVE (A-roll is at left: x:68, y:216) -->
+ <div class="stat-container stat-2">
+ <div class="white-circle">
+ <div class="stat-number">62%</div>
+ <div class="stat-subtext">INEFFECTIVE</div>
+ </div>
+ </div>
+
+ <!-- Stat 3: 75% LACK SKILLS (A-roll is centered small: x:480, y:450) -->
+ <div class="stat-container stat-3">
+ <div class="black-rectangle"></div>
+ <div class="stat-number">75%</div>
+ <div class="stat-subtext">LACK SKILLS</div>
+ </div>
+
+ <!-- Outro: EDITOR AGENT -->
+ <div class="outro-container">
+ <div class="outro-circle"></div>
+ <div class="outro-text">EDITOR AGENT</div>
+ </div>
+
+ <style>
+ [data-composition-id="graphics-comp"] {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1920px;
+ height: 1080px;
+ font-family: 'Futura', 'DIN Alternate', 'Arial Black', sans-serif;
+ overflow: hidden;
+ }
+
+ /* Common Styles */
+ .intro-container, .stat-container, .outro-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ opacity: 0;
+ pointer-events: none;
+ }
+
+ .stat-number {
+ font-size: 200px;
+ font-weight: 900;
+ line-height: 1;
+ z-index: 2;
+ }
+
+ .stat-subtext {
+ position: absolute;
+ font-size: 60px;
+ font-weight: 900;
+ z-index: 3;
+ text-align: center;
+ width: 800px;
+ }
+
+ /* Intro Styles - Centered behind A-roll (A-roll is full screen) */
+ .black-circle {
+ width: 800px;
+ height: 800px;
+ background-color: #000000;
+ border-radius: 50%;
+ position: absolute;
+ }
+
+ .intro-text {
+ font-size: 100px;
+ font-weight: 900;
+ color: #D0021B;
+ z-index: 2;
+ text-align: center;
+ width: 1000px;
+ }
+
+ /* Stat 1 Styles (Left side) - A-roll is at x:700 */
+ .stat-1 .vermillion-square {
+ width: 600px;
+ height: 600px;
+ background-color: #D0021B;
+ position: absolute;
+ left: 50px;
+ top: 240px;
+ }
+
+ .stat-1 .stat-number {
+ color: #FFFFFF;
+ position: absolute;
+ left: 100px;
+ top: 400px;
+ }
+
+ .stat-1 .stat-subtext {
+ color: #000000;
+ left: 100px;
+ top: 650px;
+ text-align: left;
+ }
+
+ /* Stat 2 Styles (Right side) - A-roll is at x:68 */
+ .stat-2 {
+ opacity: 0;
+ pointer-events: none;
+ }
+
+ .stat-2 .white-circle {
+ width: 550px; /* Scaled down from 650px to avoid clipping */
+ height: 550px;
+ background-color: #D0021B; /* Vermillion background */
+ border-radius: 50%;
+ position: absolute;
+ right: 100px; /* Moved further right to avoid A-roll */
+ top: 265px;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ }
+
+ .stat-2 .stat-number {
+ color: #000000; /* Black text */
+ position: relative;
+ right: auto;
+ top: auto;
+ font-size: 180px; /* Slightly adjusted for better fit in circle */
+ }
+
+ .stat-2 .stat-subtext {
+ color: #000000; /* Black text */
+ position: relative;
+ right: auto;
+ top: auto;
+ text-align: center;
+ width: auto;
+ font-size: 50px; /* Slightly adjusted for better fit in circle */
+ }
+
+ /* Stat 3 Styles (Top Center) - A-roll is at y:450 */
+ .stat-3 .black-rectangle {
+ width: 1000px;
+ height: 350px;
+ background-color: #000000;
+ position: absolute;
+ top: 50px;
+ }
+
+ .stat-3 .stat-number {
+ color: #D0021B;
+ position: absolute;
+ top: 100px;
+ }
+
+ .stat-3 .stat-subtext {
+ color: #FFFFFF;
+ top: 300px;
+ }
+
+ /* Outro Styles */
+ .outro-circle {
+ width: 900px;
+ height: 900px;
+ background-color: #D0021B;
+ border-radius: 50%;
+ position: absolute;
+ }
+
+ .outro-text {
+ font-size: 150px;
+ font-weight: 900;
+ color: #000000;
+ z-index: 2;
+ text-align: center;
+ width: 1000px;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.86, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics,', 'start': 3.579, 'end': 4.599}, {'text': 'sixty-two', 'start': 4.679, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.079, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.42}, {'text': 'look', 'start': 10.519, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want,', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.859}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Editor', 'start': 15.079, 'end': 15.42}, {'text': 'Agent.', 'start': 15.619, 'end': 16.02}];
+ const tl = gsap.timeline({ paused: true });
+
+ // 1. Intro (0-1.8s)
+ tl.set('.intro-container', { opacity: 1 }, 0);
+ tl.from('.black-circle', { scale: 0, duration: 0.3, ease: 'power2.out' }, 0);
+ tl.from('.intro-text', { x: -100, opacity: 0, duration: 0.3, ease: 'power2.out' }, 0.1);
+ tl.set('.intro-container', { opacity: 0 }, 1.8);
+
+ // 2. Stat 1 (1.86s - 4.6s) - "Forty-seven percent"
+ const stat1Time = 1.86;
+ tl.set('.stat-1', { opacity: 1 }, stat1Time);
+ tl.from('.stat-1 .vermillion-square', { x: -1000, duration: 0.3, ease: 'power2.out' }, stat1Time);
+ tl.from('.stat-1 .stat-number', { opacity: 0, scale: 0.8, duration: 0.2, ease: 'power2.out' }, stat1Time + 0.1);
+ tl.from('.stat-1 .stat-subtext', { opacity: 0, y: 20, duration: 0.2, ease: 'power2.out' }, stat1Time + 0.2);
+ tl.set('.stat-1', { opacity: 0 }, 4.6);
+
+ // 3. Stat 2 (4.679s - 8.8s) - "Sixty-two percent"
+ const stat2Time = 4.679;
+ tl.set('.stat-2', { opacity: 1 }, stat2Time);
+ tl.from('.stat-2 .white-circle', { scale: 0, duration: 0.3, ease: 'power2.out' }, stat2Time);
+ tl.set('.stat-2', { opacity: 0 }, 8.8);
+
+ // 4. Stat 3 (8.88s - 14.2s) - "Three out of four"
+ const stat3Time = 8.88;
+ tl.set('.stat-3', { opacity: 1 }, stat3Time);
+ tl.from('.stat-3 .black-rectangle', { width: 0, duration: 0.3, ease: 'power2.out' }, stat3Time);
+ tl.from('.stat-3 .stat-number', { opacity: 0, y: -30, duration: 0.2, ease: 'power2.out' }, stat3Time + 0.1);
+ tl.from('.stat-3 .stat-subtext', { opacity: 0, y: 20, duration: 0.2, ease: 'power2.out' }, stat3Time + 0.2);
+ tl.set('.stat-3', { opacity: 0 }, 14.2);
+
+ // 5. Outro (14.239s - 17s) - "So we built Editor Agent"
+ tl.set('.outro-container', { opacity: 1 }, 14.239);
+ tl.from('.outro-circle', { scale: 0, duration: 0.3, ease: 'power2.out' }, 14.239);
+ tl.from('.outro-text', { scale: 1.5, opacity: 0, duration: 0.3, ease: 'power2.out' }, 14.3);
+
+ window.__timelines["graphics-comp"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-1-prod/src/design_review.md b/packages/producer/tests/style-1-prod/src/design_review.md
new file mode 100644
index 0000000000..796ad380aa
--- /dev/null
+++ b/packages/producer/tests/style-1-prod/src/design_review.md
@@ -0,0 +1,61 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a PowerPoint presentation from a 2010 corporate retreat that's trying way too hard to be "modern." It’s a chaotic mess of geometric shapes and primary colors that lacks any sense of sophisticated art direction.
+
+---
+
+## CRITICAL Design Failures
+
+Issues that make this look unprofessional or straight-up ugly. These MUST be fixed.
+
+### The "Primary School" Color Palette
+**Where:** `compositions/graphics.html`
+**What's wrong:** You're using `#D0021B` (a generic, aggressive red), pure black `#000000`, and pure white `#FFFFFF`. It’s the most basic, uninspired color combination possible. It lacks depth, vibration, or any sense of modern aesthetic.
+**Why it matters:** It looks cheap and amateur. High-end design uses nuanced tones, not the default colors from a 1995 Windows paint bucket.
+**Fix it:** Move to a more sophisticated palette. Try a deep crimson or a vibrant coral instead of that "stop sign" red. Use an off-white or a very light gray (`#F5F5F5`) instead of pure white to reduce eye strain and look more "editorial."
+
+### Typography Hierarchy is Non-Existent
+**Where:** `compositions/graphics.html` and `compositions/captions.html`
+**What's wrong:** Everything is just "BIG AND BOLD." You're using `font-weight: 900` for everything from the 200px stats to the 56px captions. When everything is shouting, nothing is heard.
+**Why it matters:** There's no visual path for the eye to follow. The viewer is just bombarded with heavy blocks of text.
+**Fix it:** Introduce contrast in weight. Use a lighter weight (300 or 400) for subtext and captions to let the big numbers actually pop. Vary the tracking (letter-spacing) more intentionally.
+
+### The "Floating Box" Caption Aesthetic
+**Where:** `compositions/captions.html`
+**What's wrong:** A solid black rectangle with white text slapped on the bottom. It’s the "default" look of every low-budget social media video.
+**Why it matters:** It obscures the composition and looks like an afterthought rather than an integrated design element.
+**Fix it:** Remove the solid black background. Use a subtle text shadow or a very slight gradient overlay if readability is an issue. Or, better yet, integrate the captions into the geometric style of the rest of the video.
+
+---
+
+## Design Improvements
+
+Things that aren't broken but are boring, lazy, or could be significantly better.
+
+### Robotic Motion Curves
+**Where:** `index.html` and `compositions/graphics.html`
+**The problem:** You're using `power2.out` for almost everything. It’s the "safe" choice, which makes it the "boring" choice. The transitions feel mechanical and predictable.
+**Make it better:** Use more expressive easing. Try `expo.out` for faster, snappier entrances, or `back.out(1.7)` for a slight overshoot that gives the geometric shapes some "weight" and personality.
+
+### Static Background Void
+**Where:** `index.html` (`#bg-shapes`)
+**The problem:** You have a layer for background shapes that is completely empty. The video just sits on a flat white or black void when it's scaled down.
+**Make it better:** Actually use that layer. Add some subtle, slow-moving geometric patterns or a slight grain texture to give the composition some "atmosphere" so the A-roll doesn't look like it's floating in a vacuum.
+
+---
+
+## What Actually Works
+
+The layout shifts in `index.html` (moving the A-roll from right to left to center) show a basic understanding of composition and screen real estate. It’s the only thing keeping this from being a total disaster. The timing of the transitions (0.3s) is also decent—it’s quick enough to keep the pace up.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 3/10 - It’s loud, but not in a good way. It’s the visual equivalent of someone shouting "LOOK AT ME" while wearing a neon vest.
+**Color & Typography:** 2/10 - Lazy, default choices that scream "I didn't want to spend time on this."
+**Motion & Animation Feel:** 4/10 - Functional but generic. No soul, no rhythm.
+**Overall Aesthetic:** 3/10 - Amateur corporate template vibes.
+
+**Bottom Line:** I wouldn't show this to a client unless I wanted to be fired. It needs a complete overhaul of its visual identity—start by picking a real color palette and learning that "bold" isn't the only font weight that exists.
diff --git a/packages/producer/tests/style-1-prod/src/index.html b/packages/producer/tests/style-1-prod/src/index.html
new file mode 100644
index 0000000000..2b570c29d4
--- /dev/null
+++ b/packages/producer/tests/style-1-prod/src/index.html
@@ -0,0 +1,130 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Geometric Bold - Ikko Tanaka Style</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1920px;
+ height: 1080px;
+ overflow: hidden;
+ background-color: #FFFFFF;
+ }
+
+ #main-canvas {
+ width: 100%;
+ height: 100%;
+ position: relative;
+ }
+
+ .aroll-container {
+ position: absolute;
+ overflow: hidden;
+ border-radius: 12px;
+ background: #000;
+ }
+
+ #aroll-video {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+
+ /* Background Shapes Layer */
+ #bg-shapes {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 0;
+ }
+ </style>
+</head>
+<body>
+ <div id="main-canvas" data-composition-id="main-video" data-width="1920" data-height="1080" data-duration="17">
+
+ <video id="aroll-video"
+ data-start="0"
+ data-track-index="1"
+ class="aroll-container"
+ style="width: 1920px; height: 1080px; top: 0; left: 0; position: absolute; overflow: hidden; border-radius: 12px; object-fit: cover; background: #000;"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/743011f1_e3c6afe3b7aa42369ce01e4961c60e22.mp4">
+ </video>
+
+ <!-- Background Shapes Layer -->
+ <div id="bg-shapes" data-composition-id="bg-layer" data-width="1920" data-height="1080" data-start="0" data-duration="17" data-track-index="0">
+ <script>
+ const bgTl = gsap.timeline({ paused: true });
+ window.__timelines["bg-layer"] = bgTl;
+ </script>
+ </div>
+
+ <!-- Intro / Graphics Layer -->
+ <div id="graphics-layer"
+ data-composition-id="graphics-comp"
+ data-composition-src="compositions/graphics.html"
+ data-start="0"
+ data-duration="17"
+ data-track-index="2">
+ </div>
+
+ <!-- Captions Layer -->
+ <div id="captions-layer"
+ data-composition-id="captions-comp"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="17"
+ data-track-index="3">
+ </div>
+
+ <!-- Transition SFX -->
+ <audio id="click-sfx" data-start="0" data-track-index="4" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/853dda23_70261e8b676444bfbfe147e34803851e.mp3"></audio>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+ const aroll = document.getElementById('aroll-video');
+
+ // --- A-ROLL FRAMING LOGIC (LANDSCAPE 1920x1080) ---
+ // 0-3s: Intro - Slide in from right & Scale. Full screen.
+ tl.fromTo(aroll,
+ { x: 1920, scale: 0.8 },
+ { x: 0, scale: 1, duration: 0.3, ease: "power2.out" }, 0);
+
+ // Moment 1: 1.86s (Transition to first stat: "Forty-seven percent")
+ // Scale down to 60%, reposition to right side (next to graphic)
+ tl.to(aroll, {
+ width: 1152, height: 648, x: 700, y: 216,
+ duration: 0.3, ease: "power2.out"
+ }, 1.86);
+
+ // Moment 2: 4.679s (Transition to second stat: "Sixty-two percent")
+ // Shift to left side (next to graphic)
+ tl.to(aroll, {
+ x: 68, y: 216,
+ duration: 0.3, ease: "power2.out"
+ }, 4.679);
+
+ // Moment 3: 8.88s (Transition to third stat: "Three out of four")
+ // Center and scale down (graphic will be above/below)
+ tl.to(aroll, {
+ width: 960, height: 540, x: 480, y: 450,
+ duration: 0.3, ease: "power2.out"
+ }, 8.88);
+
+ // Moment 4: 14.239s (Closing/Editor Agent Reveal: "So we built...")
+ // Full screen zoom center
+ tl.to(aroll, {
+ width: 1920, height: 1080, x: 0, y: 0, scale: 1,
+ duration: 0.3, ease: "power2.out"
+ }, 14.239);
+
+ window.__timelines["main-video"] = tl;
+ </script>
+ </div>
+</body>
+</html>
diff --git a/packages/producer/tests/style-10-prod/meta.json b/packages/producer/tests/style-10-prod/meta.json
new file mode 100644
index 0000000000..baf580d9a2
--- /dev/null
+++ b/packages/producer/tests/style-10-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-10-prod",
+ "description": "Regression fixture imported from normalized style pack style-10-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "landscape"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-10-prod/src/code_review.md b/packages/producer/tests/style-10-prod/src/code_review.md
new file mode 100644
index 0000000000..c52f62f750
--- /dev/null
+++ b/packages/producer/tests/style-10-prod/src/code_review.md
@@ -0,0 +1,59 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 4
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None found. All compositions follow the core schema rules for determinism, finite timelines, and registration.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images used)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - all absolute)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+## File-by-File Analysis
+
+### index.html
+**Status**: COMPLIANT
+- Correctly defines the master composition with `data-composition-id="master"`.
+- Uses portrait dimensions (1080x1920).
+- Loads sub-compositions using `data-composition-src`.
+- Registers `master` timeline in `window.__timelines`.
+
+### compositions/main-orchestration.html
+**Status**: COMPLIANT
+- Correctly uses `<template>` and `data-composition-id`.
+- Registers `main-orchestration` timeline.
+- Deterministic GSAP animations for background and video.
+- Audio clips are correctly defined with `id`, `data-start`, and `data-track`.
+- **Note**: Ensure audio files do not overlap on track 1 if their duration exceeds the gap between start times.
+
+### compositions/captions.html
+**Status**: COMPLIANT
+- Correctly handles dynamic caption generation within a composition.
+- Registers `captions` timeline.
+- Uses deterministic logic for word animations based on a fixed transcript.
+- Correctly uses `data-width` and `data-height`.
+
+### compositions/graphics.html
+**Status**: COMPLIANT
+- Correctly uses `<template>` and `data-composition-id`.
+- Registers `graphics` timeline.
+- Uses deterministic pop-in and exit animations.
+- Ambient motion is deterministic (uses fixed durations and repeats).
+- Audio clips for SFX are correctly defined on track 10.
+- **Note**: Ensure SFX audio files do not overlap on track 10 if their duration exceeds the gap between start times.
diff --git a/packages/producer/tests/style-10-prod/src/compositions/captions.html b/packages/producer/tests/style-10-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..a384f3c497
--- /dev/null
+++ b/packages/producer/tests/style-10-prod/src/compositions/captions.html
@@ -0,0 +1,125 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1080" data-height="1920" data-duration="16.04">
+ <div id="captions-container"></div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@900&display=swap');
+
+ [data-composition-id="captions"] {
+ width: 1080px;
+ height: 1920px;
+ display: flex;
+ justify-content: center;
+ align-items: flex-start;
+ padding-top: 200px;
+ font-family: 'Nunito', sans-serif;
+ font-weight: 900;
+ pointer-events: none;
+ background: transparent;
+ }
+
+ [data-composition-id="captions"] #captions-container {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ position: relative;
+ }
+
+ .caption-group {
+ background-color: #FF2D8A;
+ border-radius: 40px;
+ padding: 20px 40px;
+ display: flex;
+ flex-wrap: nowrap;
+ justify-content: center;
+ align-items: center;
+ gap: 20px;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ white-space: nowrap;
+ box-shadow: 0 15px 45px rgba(255, 45, 138, 0.4);
+ max-width: 960px;
+ box-sizing: border-box;
+ }
+
+ .word {
+ color: #FFFFFF;
+ font-size: 60px;
+ text-transform: uppercase;
+ display: inline-block;
+ opacity: 0;
+ transform: translateY(30px) scale(0.8);
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.839, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics.', 'start': 3.579, 'end': 4.639}, {'text': 'Sixty-two', 'start': 4.659, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.099, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.479}, {'text': 'look', 'start': 10.52, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.86}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Editor', 'start': 15.079, 'end': 15.42}, {'text': 'Agent', 'start': 15.619, 'end': 16.019}];
+ const container = document.getElementById('captions-container');
+ const tl = gsap.timeline({ paused: true });
+
+ // Group transcript into lines based on word count and character count
+ const groups = [];
+ let currentGroup = [];
+ let currentChars = 0;
+ const MAX_WORDS = 3;
+ const MAX_CHARS = 20;
+
+ TRANSCRIPT.forEach(word => {
+ if (currentGroup.length >= MAX_WORDS || (currentChars + word.text.length) > MAX_CHARS) {
+ groups.push(currentGroup);
+ currentGroup = [];
+ currentChars = 0;
+ }
+ currentGroup.push(word);
+ currentChars += word.text.length;
+ });
+ if (currentGroup.length > 0) {
+ groups.push(currentGroup);
+ }
+
+ groups.forEach((group, groupIndex) => {
+ const groupEl = document.createElement('div');
+ groupEl.className = 'caption-group';
+ groupEl.id = `group-${groupIndex}`;
+ container.appendChild(groupEl);
+
+ const groupStart = group[0].start;
+ const nextGroupStart = (groupIndex < groups.length - 1) ? groups[groupIndex + 1][0].start : group[group.length - 1].end + 0.5;
+ const groupEnd = nextGroupStart;
+
+ // Show group
+ tl.set(groupEl, { opacity: 1 }, groupStart);
+
+ group.forEach((wordData, wordIndex) => {
+ // 2. Create Word Element
+ const wordEl = document.createElement('span');
+ wordEl.className = 'word';
+ wordEl.textContent = wordData.text;
+ groupEl.appendChild(wordEl);
+
+ // 3. Animation with Stagger and Power4.out
+ // Stagger: 0.05s delay between words in a group
+ const staggerDelay = wordIndex * 0.05;
+ const startTime = wordData.start + staggerDelay;
+
+ tl.to(wordEl, {
+ opacity: 1,
+ y: 0,
+ scale: 1,
+ duration: 0.4,
+ ease: "power4.out"
+ }, startTime);
+ });
+
+ // Hide group
+ tl.set(groupEl, { opacity: 0 }, groupEnd);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-10-prod/src/compositions/graphics.html b/packages/producer/tests/style-10-prod/src/compositions/graphics.html
new file mode 100644
index 0000000000..da9f56e763
--- /dev/null
+++ b/packages/producer/tests/style-10-prod/src/compositions/graphics.html
@@ -0,0 +1,204 @@
+<template id="graphics-template">
+ <div data-composition-id="graphics" data-width="1080" data-height="1920" data-duration="16.04">
+ <!-- Composition 1: 47% needed motion graphics (1.8s - 4.6s) -->
+ <div id="graphic-1" class="graphic-container" style="left: 540px; top: 1360px;">
+ <div class="sticker-container">
+ <div class="content-wrapper">
+ <div class="stat-text blue-text">47%</div>
+ <div class="sub-text blue-text">NEEDED<br>MOTION<br>GRAPHICS</div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Composition 2: 62% attention (4.6s - 8.6s) -->
+ <div id="graphic-2" class="graphic-container" style="left: 540px; top: 1360px;">
+ <div class="sticker-container">
+ <div class="content-wrapper">
+ <div class="stat-text pink-text">62%</div>
+ <div class="pill-shape blue-bg">
+ <div class="pill-text white-text">ATTENTION LOSS</div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Composition 3: 75% lack skills (8.8s - 13.2s) -->
+ <div id="graphic-3" class="graphic-container" style="left: 540px; top: 560px;">
+ <div class="sticker-container">
+ <div class="content-wrapper">
+ <div class="stat-text green-text">75%</div>
+ <div class="sub-text blue-text">SKILL<br>GAP</div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Finale: EDITOR AGENT (14.2s - 16s) -->
+ <div id="graphic-finale" class="graphic-container" style="left: 540px; top: 1500px;">
+ <div class="sticker-container pink-bg">
+ <div class="content-wrapper">
+ <div class="finale-text blue-text">EDITOR AGENT</div>
+ </div>
+ </div>
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@400;700;900&display=swap');
+
+ [data-composition-id="graphics"] {
+ font-family: 'Nunito', sans-serif;
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ overflow: hidden;
+ }
+
+ .graphic-container {
+ position: absolute;
+ transform: translate(-50%, -50%) scale(0);
+ opacity: 0;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ pointer-events: none;
+ }
+
+ .sticker-container {
+ position: relative;
+ background-color: rgba(255, 255, 255, 0.9);
+ border: 4px solid white;
+ border-radius: 20px;
+ backdrop-filter: blur(10px);
+ box-shadow: 0 20px 50px rgba(0,0,0,0.2);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ }
+
+ .sticker-container.pink-bg {
+ background-color: rgba(255, 45, 138, 0.9);
+ border-color: #FF2D8A;
+ }
+
+ .content-wrapper {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 40px 60px;
+ }
+
+ .stat-text {
+ font-size: 160px;
+ line-height: 0.9;
+ font-weight: 900;
+ letter-spacing: 4px;
+ }
+
+ .sub-text {
+ font-size: 60px;
+ line-height: 1.1;
+ font-weight: 900;
+ text-align: center;
+ margin-top: 15px;
+ letter-spacing: 6px;
+ }
+
+ .pill-shape {
+ padding: 20px 50px;
+ border-radius: 100px;
+ margin-top: 30px;
+ }
+
+ .pill-text {
+ font-size: 40px;
+ font-weight: 900;
+ white-space: nowrap;
+ letter-spacing: 2px;
+ }
+
+ .finale-text {
+ font-size: 100px;
+ font-weight: 900;
+ white-space: nowrap;
+ letter-spacing: 2px;
+ }
+
+ .blue-text { color: #0033CC; }
+ .pink-text { color: #FF2D8A; }
+ .green-text { color: #A3E635; }
+ .white-text { color: white; }
+ .blue-bg { background-color: #0033CC; }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.839, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics.', 'start': 3.579, 'end': 4.639}, {'text': 'Sixty-two', 'start': 4.659, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.099, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.479}, {'text': 'look', 'start': 10.52, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.86}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Editor', 'start': 15.079, 'end': 15.42}, {'text': 'Agent', 'start': 15.619, 'end': 16.019}];
+ const tl = gsap.timeline({ paused: true });
+
+ // Helper for pop-in animation
+ function popIn(id, startTime) {
+ tl.to(`#${id}`, {
+ opacity: 1,
+ scale: 1.1,
+ duration: 0.4,
+ ease: "power4.out"
+ }, startTime)
+ .to(`#${id}`, {
+ scale: 1,
+ duration: 0.2,
+ ease: "power2.out"
+ }, startTime + 0.4);
+ }
+
+ // Helper for exit animation
+ function exit(id, endTime) {
+ tl.to(`#${id}`, {
+ scale: 0,
+ opacity: 0,
+ duration: 0.3,
+ ease: "power4.in"
+ }, endTime);
+ }
+
+ // 1. 47% needed motion graphics (1.8s - 4.6s)
+ popIn("graphic-1", 1.8);
+ exit("graphic-1", 4.3);
+
+ // 2. 62% attention (4.6s - 8.6s)
+ popIn("graphic-2", 4.6);
+ exit("graphic-2", 8.3);
+
+ // 3. 75% lack skills (8.8s - 13.2s)
+ popIn("graphic-3", 8.8);
+ exit("graphic-3", 12.9);
+
+ // 4. Finale (14.2s - 16s)
+ popIn("graphic-finale", 14.2);
+ exit("graphic-finale", 15.7);
+
+ // Ambient motion for all active graphics
+ const graphics = ["graphic-1", "graphic-2", "graphic-3", "graphic-finale"];
+ graphics.forEach((id, index) => {
+ // Subtle floating motion
+ tl.to(`#${id} .sticker-container`, {
+ y: "+=20",
+ rotation: index % 2 === 0 ? "+=2" : "-=2",
+ duration: 2.5 + (index * 0.2),
+ repeat: 10, // Finite repeat to cover duration
+ yoyo: true,
+ ease: "sine.inOut"
+ }, 0);
+ });
+
+ window.__timelines["graphics"] = tl;
+ })();
+ </script>
+
+ <!-- SFX Clips -->
+ <audio id="sfx-1" data-start="1.8" data-track-index="10" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/5a6b802e_a03d12a382bd40a3a6e70de32fbbcfc3.mp3"></audio>
+ <audio id="sfx-2" data-start="4.6" data-track-index="10" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/5a6b802e_a03d12a382bd40a3a6e70de32fbbcfc3.mp3"></audio>
+ <audio id="sfx-3" data-start="8.8" data-track-index="10" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/5a6b802e_a03d12a382bd40a3a6e70de32fbbcfc3.mp3"></audio>
+ <audio id="sfx-4" data-start="14.2" data-track-index="10" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/5a6b802e_a03d12a382bd40a3a6e70de32fbbcfc3.mp3"></audio>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-10-prod/src/compositions/main-orchestration.html b/packages/producer/tests/style-10-prod/src/compositions/main-orchestration.html
new file mode 100644
index 0000000000..a307666a18
--- /dev/null
+++ b/packages/producer/tests/style-10-prod/src/compositions/main-orchestration.html
@@ -0,0 +1,150 @@
+<template id="main-orchestration-template">
+ <div data-composition-id="main-orchestration" data-width="1080" data-height="1920" data-duration="16.04">
+ <!-- Background Layer -->
+ <div class="background"></div>
+ <div class="bg-pattern"></div>
+
+ <!-- A-roll Layer -->
+ <div class="a-roll-container">
+ <video id="short_mag_cut" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/45a6a87b_ccb8e5b8362f48129491b55141ca3cb3.mp4" data-start="0" data-duration="16.04" data-track-index="0" crossorigin="anonymous"></video>
+ </div>
+
+ <!-- SFX Layer (Invisible) -->
+ <audio id="sfx-bounce" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/731894a4_d2374e83720e4b339b6b71ceec1337d7.mp3" data-start="0" data-track-index="1"></audio>
+ <audio id="sfx-shift-1" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/9e9b7f8a_b36aec8bcce6491f8da430e7e189f1a5.mp3" data-start="3" data-track-index="1"></audio>
+ <audio id="sfx-shift-2" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/9e9b7f8a_b36aec8bcce6491f8da430e7e189f1a5.mp3" data-start="8.6" data-track-index="1"></audio>
+ <audio id="sfx-pop" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/3a7e8a33_f7ebce6d456345779477498996aa0f74.mp3" data-start="14" data-track-index="1"></audio>
+
+ <style>
+ [data-composition-id="main-orchestration"] {
+ width: 1080px;
+ height: 1920px;
+ overflow: hidden;
+ background-color: #F8F9FA;
+ position: relative;
+ }
+
+ [data-composition-id="main-orchestration"] .background {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 0;
+ background-color: #F8F9FA;
+ }
+
+ [data-composition-id="main-orchestration"] .bg-pattern {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 1;
+ opacity: 0;
+ background-image: radial-gradient(#001F3F 3px, transparent 3px);
+ background-size: 80px 80px;
+ background-position: 0 0;
+ }
+
+ [data-composition-id="main-orchestration"] .a-roll-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 2;
+ }
+
+ [data-composition-id="main-orchestration"] video {
+ width: 100%;
+ height: auto;
+ aspect-ratio: 16/9;
+ object-fit: cover;
+ border-radius: 40px;
+ transform-origin: center center;
+ box-shadow: 0 40px 80px rgba(0,0,0,0.5);
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const bg = document.querySelector('[data-composition-id="main-orchestration"] .background');
+ const pattern = document.querySelector('[data-composition-id="main-orchestration"] .bg-pattern');
+ const video = document.querySelector('[data-composition-id="main-orchestration"] video');
+
+ // --- Background Color Logic (Pop Cuts) ---
+ // 0-3s: Light Gray #F8F9FA
+ // 3-8.6s: Deep Navy Gradient
+ tl.set(bg, { background: 'linear-gradient(135deg, #001F3F 0%, #0033CC 100%)' }, 3);
+ tl.to(pattern, { opacity: 0.2, duration: 0.3 }, 3);
+
+ // 8.6-14s: Light Gray #F8F9FA
+ tl.set(bg, { background: '#F8F9FA' }, 8.6);
+ tl.to(pattern, { opacity: 0, duration: 0.3 }, 8.6);
+
+ // 14-16.04s: Deep Navy Gradient
+ tl.set(bg, { background: 'linear-gradient(135deg, #001F3F 0%, #0033CC 100%)' }, 14);
+ tl.to(pattern, { opacity: 0.2, duration: 0.3 }, 14);
+
+ // --- Background Pattern Animation ---
+ tl.to(pattern, {
+ backgroundPosition: "60px 60px",
+ duration: 16.04,
+ ease: "none"
+ }, 0);
+
+ // --- A-roll Animation Logic ---
+
+ // Initial State: 10% off-screen top (1920 * 0.1 = 192)
+ gsap.set(video, { y: -192, scale: 0.8, x: 0, rotation: 0 });
+
+ // 0-3s: Bounce in from top with elastic overshoot. Position: Centered, scale 1.2.
+ tl.to(video, {
+ y: 0,
+ scale: 1.2,
+ duration: 1.2,
+ ease: "elastic.out(1, 0.75)"
+ }, 0);
+
+ // 3-8.6s: Shift to Top (y: -400). Whip pan / Pop with bounce.
+ tl.to(video, {
+ y: -400,
+ scale: 1.0,
+ rotation: -3,
+ duration: 0.5,
+ ease: "back.out(1.7)"
+ }, 3);
+
+ // 8.6-14s: Shift to Bottom (y: 400).
+ tl.to(video, {
+ y: 400,
+ scale: 1.0,
+ rotation: 3,
+ duration: 0.5,
+ ease: "power4.inOut"
+ }, 8.6)
+ .to(video, {
+ scale: 1.0,
+ duration: 0.2,
+ ease: "back.out(1.2)"
+ }, 8.9);
+
+ // 14-16.04s: Zoom in to Center (scale 1.3).
+ tl.to(video, {
+ y: 0,
+ scale: 1.3,
+ rotation: 0,
+ duration: 0.4,
+ ease: "back.out(1.5)"
+ }, 14);
+
+ window.__timelines["main-orchestration"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-10-prod/src/design_review.md b/packages/producer/tests/style-10-prod/src/design_review.md
new file mode 100644
index 0000000000..e2d2a9bc14
--- /dev/null
+++ b/packages/producer/tests/style-10-prod/src/design_review.md
@@ -0,0 +1,57 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a corporate HR training video had a mid-life crisis and tried to dress like a TikTok influencer. It’s a confused mess of "safe" professional choices and "edgy" motion that doesn't land.
+
+---
+
+## CRITICAL Design Failures
+
+### The "Floating Head" Video Problem
+**Where:** `compositions/main-orchestration.html` - `video` element
+**What's wrong:** You've taken a 16:9 video, slapped a 40px border radius on it, and let it float in the middle of a 9:16 portrait frame. It looks like a lost window on a desktop, not a deliberate mobile-first composition.
+**Why it matters:** It screams "I didn't have the right assets so I just centered it." It wastes 70% of the screen real estate and makes the actual content feel tiny and insignificant.
+**Fix it:** Crop the video to fill the width or use a more aggressive layout. If it must be a "window," give it a reason to exist—don't just let it drift aimlessly with a generic drop shadow.
+
+### Typography Hierarchy is Non-Existent
+**Where:** `compositions/captions.html` and `compositions/graphics.html`
+**What's wrong:** You're using Nunito for everything. Nunito is the "I want to look friendly but I have no personality" font of the 2010s. The captions are 72px, the stats are 160px, and the sub-text is 60px. It’s just a wall of rounded, bubbly text.
+**Why it matters:** There is no visual tension. Everything is "loud" in the same boring way. It feels like a children's app, not a professional data-driven message.
+**Fix it:** Pair a high-contrast Serif or a brutalist Sans-Serif with your body text. Vary the weights more aggressively. Stop relying on "Extra Bold" to do all the heavy lifting.
+
+### The "Sticker" Aesthetic is Lazy
+**Where:** `compositions/graphics.html` - `.sticker-container`
+**What's wrong:** A white box with a 20px border radius and a generic drop shadow is not a "design choice," it's a default setting. The 0.9 opacity backdrop-filter is barely visible against the light gray background.
+**Why it matters:** It looks like a template from a free online editor. It lacks any sense of brand identity or sophisticated art direction.
+**Fix it:** Lose the generic white boxes. Use bold, solid color blocks that interact with the background, or go full glassmorphism with actual contrast.
+
+---
+
+## Design Improvements
+
+### Background Pattern is a Ghost
+**Where:** `compositions/main-orchestration.html` - `.bg-pattern`
+**The problem:** A radial gradient of 2px dots at 0.1 opacity? You might as well not have it. It’s so subtle it looks like screen noise or a rendering artifact rather than a deliberate texture.
+**Make it better:** Crank the opacity or change the pattern to something with more character—grid lines, topographic maps, or bold geometric shapes. If you're going to have a pattern, let us actually see it.
+
+### Animation "Bounce" Overload
+**Where:** `compositions/main-orchestration.html` and `compositions/graphics.html`
+**The problem:** Everything is "elastic.out" or "back.out." It’s bouncy, it’s poppy, and it’s exhausting. It feels like the UI is constantly trying to jump out of the screen.
+**Make it better:** Use more sophisticated easing. Not everything needs to overshoot. Try some "power4.inOut" for smoother, more cinematic transitions. Save the "bounce" for the one thing you actually want people to notice.
+
+---
+
+## What Actually Works
+
+**The Color Palette (Almost):** The combination of Deep Navy (#001F3F), Pink (#FF2D8A), and Lime (#A3E635) is actually a strong, modern trio. It has high energy and good contrast. It’s the only thing saving this from being completely forgettable.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 3/10 - It’s a floating video in a sea of gray. Boring.
+**Color & Typography:** 4/10 - Good colors, but the font choice is painfully generic.
+**Motion & Animation Feel:** 5/10 - Technically functional, but over-indexed on "bouncy" presets.
+**Overall Aesthetic:** 3.5/10 - Feels like a "My First Video Project" template.
+
+**Bottom Line:** I wouldn't show this to a client unless I wanted them to fire me. It needs a complete rethink of how it uses the vertical space. Stop playing it safe with rounded corners and Nunito.
diff --git a/packages/producer/tests/style-10-prod/src/index.html b/packages/producer/tests/style-10-prod/src/index.html
new file mode 100644
index 0000000000..88b4d665dd
--- /dev/null
+++ b/packages/producer/tests/style-10-prod/src/index.html
@@ -0,0 +1,90 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Ahn Sang-soo Play Mode Video</title>
+ <style>
+ html, body {
+ margin: 0;
+ padding: 0;
+ width: 1080px;
+ height: 1920px;
+ }
+
+ body {
+ background-color: #000;
+ overflow: hidden;
+ }
+
+ #master-root {
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ overflow: hidden;
+ }
+
+ #main-layer,
+ #graphics-layer,
+ #captions-layer {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ }
+
+ #main-layer {
+ z-index: 0;
+ }
+
+ #graphics-layer {
+ z-index: 10;
+ }
+
+ #captions-layer {
+ z-index: 20;
+ }
+ </style>
+</head>
+<body>
+ <div id="master-root" data-composition-id="master" data-width="1080" data-height="1920" data-duration="16.04">
+
+ <!-- Main Orchestration: Background and A-roll -->
+ <div id="main-layer"
+ data-composition-id="main-orchestration"
+ data-composition-src="compositions/main-orchestration.html"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="0">
+ </div>
+
+ <!-- Graphics Overlay: Stats and Titles -->
+ <div id="graphics-layer"
+ data-composition-id="graphics"
+ data-composition-src="compositions/graphics.html"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="1">
+ </div>
+
+ <!-- Captions Overlay: Topmost Layer -->
+ <div id="captions-layer"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="2">
+ </div>
+
+ </div>
+
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <script>
+ // Master conductor timeline - framework handles nesting automatically
+ const masterTL = gsap.timeline({ paused: true });
+ window.__timelines = window.__timelines || {};
+ window.__timelines["master"] = masterTL;
+ </script>
+</body>
+</html>
diff --git a/packages/producer/tests/style-11-prod/meta.json b/packages/producer/tests/style-11-prod/meta.json
new file mode 100644
index 0000000000..342b103f42
--- /dev/null
+++ b/packages/producer/tests/style-11-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-11-prod",
+ "description": "Regression fixture imported from normalized style pack style-11-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "portrait"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-11-prod/src/code_review.md b/packages/producer/tests/style-11-prod/src/code_review.md
new file mode 100644
index 0000000000..08f2460d96
--- /dev/null
+++ b/packages/producer/tests/style-11-prod/src/code_review.md
@@ -0,0 +1,50 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 4
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None. The compositions follow the HyperFrame schema correctly, including deterministic logic, finite timelines, and proper registration.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no `<img>` clips used)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - absolute timing used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+### [index.html]
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. The root composition correctly orchestrates sub-compositions and the A-roll video.
+
+### [compositions/bg-grid.html]
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. The script uses deterministic loops and fixed arrays for cube placement. The timeline is registered correctly.
+
+### [compositions/mg-overlays.html]
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. The script uses a finite loop for the background grid pulse instead of an infinite repeat, ensuring a finite timeline.
+
+### [compositions/captions.html]
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Captions are grouped and animated deterministically based on the transcript.
diff --git a/packages/producer/tests/style-11-prod/src/compositions/bg-grid.html b/packages/producer/tests/style-11-prod/src/compositions/bg-grid.html
new file mode 100644
index 0000000000..4d87084c32
--- /dev/null
+++ b/packages/producer/tests/style-11-prod/src/compositions/bg-grid.html
@@ -0,0 +1,243 @@
+<template id="bg-grid-template">
+ <div data-composition-id="bg-grid-comp" data-width="1080" data-height="1920" data-duration="13.88">
+ <div class="grid-container" id="grid-container"></div>
+ <div class="wash-container" id="wash-container"></div>
+ <div class="cubes-container" id="cubes-container"></div>
+
+ <style>
+ [data-composition-id="bg-grid-comp"] {
+ width: 1080px;
+ height: 1920px;
+ background:
+ linear-gradient(180deg, rgba(255, 255, 255, 0.42) 0%, rgba(255, 255, 255, 0) 24%),
+ linear-gradient(180deg, #F7F2E9 0%, #EFE8DD 100%);
+ position: relative;
+ overflow: hidden;
+ }
+
+ [data-composition-id="bg-grid-comp"] .grid-container {
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ }
+
+ [data-composition-id="bg-grid-comp"] .wash-container {
+ position: absolute;
+ inset: 0;
+ z-index: 0;
+ }
+
+ [data-composition-id="bg-grid-comp"] .wash-band {
+ position: absolute;
+ opacity: 0;
+ mix-blend-mode: multiply;
+ }
+
+ [data-composition-id="bg-grid-comp"] .grid-line {
+ position: absolute;
+ background-color: #1E1E1E;
+ opacity: 0;
+ }
+
+ [data-composition-id="bg-grid-comp"] .grid-line.horizontal {
+ height: 1px;
+ width: 100%;
+ }
+
+ [data-composition-id="bg-grid-comp"] .grid-line.vertical {
+ width: 1px;
+ height: 100%;
+ }
+
+ [data-composition-id="bg-grid-comp"] .cubes-container {
+ position: absolute;
+ inset: 0;
+ z-index: 2;
+ pointer-events: none;
+ }
+
+ [data-composition-id="bg-grid-comp"] .cube-cell {
+ position: absolute;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+
+ [data-composition-id="bg-grid-comp"] .cube-svg {
+ width: 74%;
+ height: 74%;
+ overflow: visible;
+ }
+
+ [data-composition-id="bg-grid-comp"] .cube-path {
+ fill: none;
+ stroke: #1E1E1E;
+ stroke-width: 1.8;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+ }
+
+ [data-composition-id="bg-grid-comp"] .cube-face {
+ opacity: 0;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const compId = "bg-grid-comp";
+ const width = 1080;
+ const height = 1920;
+ const cols = 10;
+ const rows = 18;
+ const cellW = width / cols;
+ const cellH = height / rows;
+
+ const container = document.getElementById('grid-container');
+ const washContainer = document.getElementById('wash-container');
+ const cubesContainer = document.getElementById('cubes-container');
+ const tl = gsap.timeline({ paused: true });
+
+ const washBands = [
+ { x: 0, y: 213.33, w: 324, h: 320, color: 'rgba(204, 51, 51, 0.08)' },
+ { x: 648, y: 0, w: 432, h: 426.67, color: 'rgba(51, 119, 187, 0.08)' },
+ { x: 756, y: 1280, w: 324, h: 320, color: 'rgba(51, 119, 187, 0.05)' },
+ { x: 0, y: 1493.33, w: 432, h: 426.67, color: 'rgba(30, 30, 30, 0.05)' }
+ ];
+
+ washBands.forEach((band, index) => {
+ const el = document.createElement('div');
+ el.className = 'wash-band';
+ el.style.left = band.x + 'px';
+ el.style.top = band.y + 'px';
+ el.style.width = band.w + 'px';
+ el.style.height = band.h + 'px';
+ el.style.background = band.color;
+ washContainer.appendChild(el);
+
+ tl.to(el, {
+ opacity: 1,
+ duration: 0.7,
+ ease: "power2.out"
+ }, 0.2 + (index * 0.28));
+ });
+
+ for (let i = 0; i <= rows; i++) {
+ const line = document.createElement('div');
+ line.className = 'grid-line horizontal';
+ line.style.top = (i * cellH) + 'px';
+ container.appendChild(line);
+
+ tl.to(line, {
+ opacity: 0.24,
+ duration: 0.7,
+ ease: "expo.out"
+ }, (i / rows) * 0.48);
+ }
+
+ for (let j = 0; j <= cols; j++) {
+ const line = document.createElement('div');
+ line.className = 'grid-line vertical';
+ line.style.left = (j * cellW) + 'px';
+ container.appendChild(line);
+
+ tl.to(line, {
+ opacity: 0.24,
+ duration: 0.7,
+ ease: "expo.out"
+ }, (j / cols) * 0.48 + 0.18);
+ }
+
+ const cubeCells = [
+ { r: 2, c: 2, color: '#3377BB' },
+ { r: 4, c: 7, color: '#CC3333' },
+ { r: 8, c: 3, color: '#3377BB' },
+ { r: 11, c: 6, color: '#CC3333' },
+ { r: 15, c: 8, color: '#3377BB' }
+ ];
+
+ cubeCells.forEach((cell, index) => {
+ const cellDiv = document.createElement('div');
+ cellDiv.className = 'cube-cell';
+ cellDiv.style.width = cellW + 'px';
+ cellDiv.style.height = cellH + 'px';
+ cellDiv.style.left = (cell.c * cellW) + 'px';
+ cellDiv.style.top = (cell.r * cellH) + 'px';
+
+ const svg = `
+ <svg viewBox="0 0 100 100" class="cube-svg">
+ <path class="cube-face top-face" d="M50 20 L80 35 L50 50 L20 35 Z" fill="${cell.color}" />
+ <path class="cube-face right-face" d="M50 50 L80 35 L80 65 L50 80 Z" fill="${cell.color}" />
+ <path class="cube-face left-face" d="M20 35 L50 50 L50 80 L20 65 Z" fill="${cell.color}" />
+ <path class="cube-path outline" d="M50 20 L80 35 L80 65 L50 80 L20 65 L20 35 Z" />
+ <path class="cube-path inner-lines" d="M50 20 L50 50 M50 50 L80 35 M50 50 L20 35 M50 50 L50 80" />
+ </svg>
+ `;
+
+ cellDiv.innerHTML = svg;
+ cubesContainer.appendChild(cellDiv);
+
+ const paths = cellDiv.querySelectorAll('.cube-path');
+ const faces = cellDiv.querySelectorAll('.cube-face');
+
+ paths.forEach(path => {
+ const length = path.getTotalLength();
+ gsap.set(path, { strokeDasharray: length, strokeDashoffset: length });
+ });
+
+ const startTime = 1.45 + (index * 1.4);
+
+ paths.forEach((path, pIndex) => {
+ tl.to(path, {
+ strokeDashoffset: 0,
+ duration: 0.95,
+ ease: "power2.inOut"
+ }, startTime + (pIndex * 0.2));
+ });
+
+ faces.forEach((face, fIndex) => {
+ const faceTime = startTime + 0.8 + (fIndex * 0.1);
+ tl.to(face, {
+ opacity: 0.24,
+ duration: 0.45,
+ ease: "power2.out"
+ }, faceTime);
+
+ tl.to(face, {
+ opacity: 0.06,
+ duration: 1.2,
+ ease: "sine.out"
+ }, faceTime + 0.45);
+ });
+
+ tl.to(cellDiv, {
+ y: -12,
+ duration: 2.6,
+ ease: "sine.inOut"
+ }, startTime + 0.35);
+
+ tl.to(cellDiv, {
+ y: -4,
+ duration: 2.8,
+ ease: "sine.inOut"
+ }, startTime + 2.95);
+ });
+
+ tl.to(container, {
+ x: 8,
+ y: 8,
+ duration: 13.88,
+ ease: "none"
+ }, 0);
+
+ tl.to(cubesContainer, {
+ x: -6,
+ y: 4,
+ duration: 13.88,
+ ease: "none"
+ }, 0);
+
+ window.__timelines[compId] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-11-prod/src/compositions/captions.html b/packages/producer/tests/style-11-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..7ca77c8e62
--- /dev/null
+++ b/packages/producer/tests/style-11-prod/src/compositions/captions.html
@@ -0,0 +1,108 @@
+<template id="captions-template">
+ <div data-composition-id="captions-comp" data-width="1080" data-height="1920" data-duration="13.88">
+ <div id="captions-rail">
+ <div id="captions-kicker">Narration</div>
+ <div id="captions-container"></div>
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@700;900&display=swap');
+
+ [data-composition-id="captions-comp"] {
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ pointer-events: none;
+ }
+
+ [data-composition-id="captions-comp"] #captions-rail {
+ position: absolute;
+ left: 108px;
+ bottom: 118px;
+ width: 864px;
+ min-height: 258px;
+ border-top: 2px solid #1E1E1E;
+ padding-top: 18px;
+ background: linear-gradient(180deg, rgba(245, 241, 234, 0) 0%, rgba(245, 241, 234, 0.88) 18%, rgba(245, 241, 234, 0.97) 100%);
+ }
+
+ [data-composition-id="captions-comp"] #captions-kicker {
+ font-family: 'IBM Plex Mono', monospace;
+ font-size: 18px;
+ font-weight: 700;
+ letter-spacing: 0.24em;
+ text-transform: uppercase;
+ color: rgba(30, 30, 30, 0.64);
+ }
+
+ [data-composition-id="captions-comp"] #captions-container {
+ position: relative;
+ margin-top: 18px;
+ width: 100%;
+ min-height: 184px;
+ }
+
+ [data-composition-id="captions-comp"] .caption-line {
+ font-family: 'IBM Plex Mono', monospace;
+ font-size: 56px;
+ font-weight: 900;
+ color: #1E1E1E;
+ opacity: 0;
+ position: absolute;
+ left: 0;
+ width: 96%;
+ line-height: 1.06;
+ text-transform: uppercase;
+ }
+
+ [data-composition-id="captions-comp"] .word {
+ display: inline-block;
+ margin: 0 6px 0 0;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const container = document.getElementById('captions-container');
+ const tl = gsap.timeline({ paused: true });
+
+ const groups = [
+ { text: "We asked what you needed.", start: 0.14, end: 1.179 },
+ { text: "Forty-seven percent of you said motion graphics,", start: 1.199, end: 3.759 },
+ { text: "sixty-two percent said static content", start: 3.799, end: 5.639 },
+ { text: "was costing you attention,", start: 5.679, end: 7.299 },
+ { text: "and three out of four said you know", start: 7.319, end: 8.739 },
+ { text: "the look you want but don't have", start: 8.8, end: 10.3 },
+ { text: "the editing skills to get there.", start: 10.5, end: 12.239 },
+ { text: "So we built Editor Agent.", start: 12.3, end: 13.84 }
+ ];
+
+ groups.forEach(group => {
+ const el = document.createElement('div');
+ el.className = 'caption-line';
+ el.innerHTML = group.text.split(' ').map(word => `<span class="word">${word}</span>`).join(' ');
+ container.appendChild(el);
+
+ tl.fromTo(el, {
+ opacity: 0,
+ y: 26
+ }, {
+ opacity: 1,
+ y: 0,
+ duration: 0.18,
+ ease: "power2.out"
+ }, group.start);
+
+ tl.to(el, {
+ opacity: 0,
+ y: -12,
+ duration: 0.12,
+ ease: "power2.in"
+ }, group.end);
+ });
+
+ window.__timelines["captions-comp"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-11-prod/src/compositions/mg-overlays.html b/packages/producer/tests/style-11-prod/src/compositions/mg-overlays.html
new file mode 100644
index 0000000000..93f3b21215
--- /dev/null
+++ b/packages/producer/tests/style-11-prod/src/compositions/mg-overlays.html
@@ -0,0 +1,256 @@
+<template id="mg-overlays-template">
+ <div data-composition-id="mg-overlays-comp" data-width="1080" data-height="1920" data-duration="13.88">
+ <div class="overlay-container">
+ <div id="system-kicker">Editor Agent / Survey System</div>
+
+ <svg id="drawing-canvas" viewBox="0 0 1080 1920" preserveAspectRatio="xMidYMid slice">
+ <defs>
+ <pattern id="gridPattern" width="108" height="106.66666666666667" patternUnits="userSpaceOnUse">
+ <path d="M 108 0 L 0 0 0 106.66666666666667" fill="none" stroke="#1E1E1E" stroke-width="1" opacity="0.12"/>
+ </pattern>
+ </defs>
+
+ <rect class="ambient-grid" width="100%" height="100%" fill="url(#gridPattern)" />
+
+ <g id="structure-1" class="structure" transform="translate(108, 1108)">
+ <rect class="draw-line" x="0" y="0" width="324" height="245.33" fill="none" stroke="#CC3333" stroke-width="2" />
+ <rect class="fill-box red" x="0" y="0" width="324" height="245.33" fill="#CC3333" opacity="0" />
+ </g>
+
+ <g id="structure-2" class="structure" transform="translate(864, 214)">
+ <rect class="draw-line" x="-270" y="0" width="270" height="224" fill="none" stroke="#3377BB" stroke-width="2" />
+ <rect class="fill-box blue" x="-270" y="0" width="270" height="224" fill="#3377BB" opacity="0" />
+ </g>
+
+ <g id="structure-3" class="structure" transform="translate(540, 1328)">
+ <rect class="draw-line" x="0" y="0" width="432" height="245.33" fill="none" stroke="#1E1E1E" stroke-width="2" />
+ <rect class="fill-box gray" x="0" y="0" width="432" height="245.33" fill="#1E1E1E" opacity="0" />
+ </g>
+ </svg>
+
+ <div id="content-1" class="content-block" style="top: 1128px; left: 108px; width: 352px;">
+ <div class="eyebrow">Need motion</div>
+ <div class="stat-number">47%</div>
+ <div class="stat-label">Asked for motion graphics</div>
+ <div class="stat-note">Sharper pacing, clearer transitions, more visual energy.</div>
+ </div>
+
+ <div id="content-2" class="content-block align-right" style="top: 238px; left: 864px; width: 270px; transform: translateX(-100%);">
+ <div class="eyebrow">Attention drop</div>
+ <div class="stat-number">62%</div>
+ <div class="stat-label">Were stuck with static content</div>
+ <div class="stat-note">The message was right. The cut was not landing.</div>
+ </div>
+
+ <div id="content-3" class="content-block" style="top: 1348px; left: 540px; width: 432px;">
+ <div class="eyebrow">Execution gap</div>
+ <div class="stat-number">75%</div>
+ <div class="stat-label">Knew the look, needed the edit</div>
+ <div class="stat-note">The direction was clear. The hands-on workflow was the bottleneck.</div>
+ </div>
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;700&display=swap');
+
+ [data-composition-id="mg-overlays-comp"] .overlay-container {
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ color: #1E1E1E;
+ font-family: 'IBM Plex Mono', monospace;
+ pointer-events: none;
+ }
+
+ [data-composition-id="mg-overlays-comp"] #system-kicker {
+ position: absolute;
+ top: 78px;
+ left: 108px;
+ z-index: 120;
+ font-size: 20px;
+ letter-spacing: 0.26em;
+ text-transform: uppercase;
+ opacity: 0;
+ }
+
+ [data-composition-id="mg-overlays-comp"] #drawing-canvas {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ }
+
+ [data-composition-id="mg-overlays-comp"] .content-block {
+ position: absolute;
+ opacity: 0;
+ z-index: 100;
+ padding-top: 18px;
+ border-top: 2px solid #1E1E1E;
+ }
+
+ [data-composition-id="mg-overlays-comp"] .content-block.align-right {
+ text-align: right;
+ }
+
+ [data-composition-id="mg-overlays-comp"] #content-2 {
+ border-top-color: #3377BB;
+ }
+
+ [data-composition-id="mg-overlays-comp"] .eyebrow {
+ font-size: 18px;
+ text-transform: uppercase;
+ letter-spacing: 0.22em;
+ color: rgba(30, 30, 30, 0.72);
+ }
+
+ [data-composition-id="mg-overlays-comp"] .stat-number {
+ margin-top: 10px;
+ font-size: 132px;
+ font-weight: 700;
+ line-height: 0.92;
+ color: #1E1E1E;
+ }
+
+ [data-composition-id="mg-overlays-comp"] .stat-label {
+ margin-top: 16px;
+ font-size: 30px;
+ line-height: 1.2;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ }
+
+ [data-composition-id="mg-overlays-comp"] .stat-note {
+ margin-top: 14px;
+ font-size: 22px;
+ line-height: 1.45;
+ color: rgba(30, 30, 30, 0.72);
+ }
+
+ [data-composition-id="mg-overlays-comp"] .draw-line {
+ stroke-dasharray: 1400;
+ stroke-dashoffset: 1400;
+ }
+
+ [data-composition-id="mg-overlays-comp"] #content-1 .stat-number {
+ color: #CC3333;
+ }
+
+ [data-composition-id="mg-overlays-comp"] #content-2 .stat-number {
+ color: #3377BB;
+ }
+
+ [data-composition-id="mg-overlays-comp"] #content-2 .stat-label {
+ font-size: 24px;
+ }
+
+ [data-composition-id="mg-overlays-comp"] #content-2 .stat-note {
+ font-size: 19px;
+ line-height: 1.38;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ const revealStat = ({
+ start,
+ end,
+ structure,
+ fill,
+ content,
+ fromX = 0,
+ fromY = 0,
+ }) => {
+ tl.to(`${structure} .draw-line`, {
+ strokeDashoffset: 0,
+ duration: 0.75,
+ ease: "power2.out"
+ }, start);
+
+ tl.to(fill, {
+ opacity: 0.1,
+ duration: 0.32,
+ ease: "power2.out"
+ }, start + 0.26);
+
+ tl.fromTo(content, {
+ opacity: 0,
+ x: fromX,
+ y: fromY
+ }, {
+ opacity: 1,
+ x: 0,
+ y: 0,
+ duration: 0.55,
+ ease: "power3.out"
+ }, start + 0.18);
+
+ tl.to([content, structure], {
+ opacity: 0,
+ y: -10,
+ duration: 0.28,
+ ease: "power2.in"
+ }, end - 0.28);
+ };
+
+ tl.fromTo("#system-kicker", {
+ opacity: 0,
+ y: -18
+ }, {
+ opacity: 1,
+ y: 0,
+ duration: 0.5,
+ ease: "power2.out"
+ }, 0.35);
+
+ revealStat({
+ start: 1.199,
+ end: 3.759,
+ structure: "#structure-1",
+ fill: "#structure-1 .fill-box.red",
+ content: "#content-1",
+ fromY: 22
+ });
+
+ revealStat({
+ start: 3.799,
+ end: 7.299,
+ structure: "#structure-2",
+ fill: "#structure-2 .fill-box.blue",
+ content: "#content-2",
+ fromX: 26
+ });
+
+ revealStat({
+ start: 7.319,
+ end: 12.239,
+ structure: "#structure-3",
+ fill: "#structure-3 .fill-box.gray",
+ content: "#content-3",
+ fromY: -22
+ });
+
+ tl.to(".ambient-grid", {
+ opacity: 0.22,
+ duration: 4.6,
+ ease: "sine.inOut"
+ }, 0);
+
+ tl.to(".ambient-grid", {
+ opacity: 0.1,
+ duration: 4.64,
+ ease: "sine.inOut"
+ }, 4.6);
+
+ tl.to(".ambient-grid", {
+ opacity: 0.2,
+ duration: 4.64,
+ ease: "sine.inOut"
+ }, 9.24);
+
+ window.__timelines["mg-overlays-comp"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-11-prod/src/design_review.md b/packages/producer/tests/style-11-prod/src/design_review.md
new file mode 100644
index 0000000000..ef72af2b15
--- /dev/null
+++ b/packages/producer/tests/style-11-prod/src/design_review.md
@@ -0,0 +1,57 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a "Sol LeWitt" tribute act performed by someone who only saw a thumbnail of his work on a broken phone. It’s a sterile, confused mess that tries to be "minimalist" but ends up just being "unfinished."
+
+---
+
+## CRITICAL Design Failures
+
+### Typographic Identity Crisis
+**Where:** `compositions/mg-overlays.html` and `compositions/captions.html`
+**What's wrong:** You're mixing **IBM Plex Mono** (a technical, rigid font) for your "data" with **Inter** (the most overused, generic UI font in existence) for your captions. It’s a jarring clash of "I'm a coder" and "I'm a SaaS landing page from 2019."
+**Why it matters:** It destroys any sense of a cohesive visual brand. The viewer doesn't know if they're watching a technical documentary or a generic corporate explainer.
+**Fix it:** Commit to the bit. Use IBM Plex Mono for *everything* to lean into the Sol LeWitt / Blueprint aesthetic, or find a high-contrast serif to actually provide some visual interest.
+
+### The "Floating in a Void" Problem
+**Where:** `compositions/mg-overlays.html`
+**What's wrong:** Your stats (`47%`, `62%`, `75%`) are just... there. They have no relationship to the grid or the isometric cubes. They're just floating at arbitrary coordinates like `top: 1200px; left: 100px;`.
+**Why it matters:** It looks like a mistake. In a grid-based design, *everything* must respect the grid. If it doesn't, the grid is just useless wallpaper.
+**Fix it:** Align your text blocks strictly to the grid lines defined in `bg-grid.html`. Use the `cellW` and `cellH` logic to position your content so it feels structurally sound.
+
+### Caption Background Cowardice
+**Where:** `compositions/captions.html`
+**What's wrong:** `background-color: rgba(0, 0, 0, 0.4);` with a `backdrop-filter: blur(4px);`. This is the "I don't know how to handle contrast" starter pack. It’s ugly, it’s muddy, and it obscures your "beautiful" background grid.
+**Why it matters:** It creates a heavy, dark blob at the bottom of an otherwise light and airy composition. It’s visually exhausting.
+**Fix it:** Remove the background and blur. If you need legibility, use a subtle drop shadow or, better yet, ensure your video/background doesn't compete with the text. Since your background is `#F4F4F4`, just use black text for the captions.
+
+---
+
+## Design Improvements
+
+### Robotic Animation Pacing
+**Where:** `compositions/bg-grid.html` and `compositions/mg-overlays.html`
+**The problem:** Your animations are all using `power2.inOut` or `expo.out`. It’s predictable and lacks "soul." The cubes draw themselves, then they pulse, then they float. It feels like a loading screen, not a dynamic video.
+**Make it better:** Vary the easing. Use `back.out` for the stats (which you did, barely) but make it more aggressive. Give the grid lines a staggered "wipe" effect rather than just fading in. Make the motion feel like it has momentum.
+
+### Color Palette Anemia
+**Where:** `compositions/bg-grid.html`
+**The problem:** `#3377BB` and `#CC3333`. These are the default "Blue" and "Red" from a 1990s Excel chart. They are boring, primary, and have zero personality.
+**Make it better:** Use more sophisticated tones. Try a deeper Cobalt or a muted Terracotta. Or, go full LeWitt and use high-saturation CMYK-style colors, but give them some breathing room.
+
+---
+
+## What Actually Works
+
+The **Isometric Cube SVG** construction in `bg-grid.html` is actually decent. The way you've broken down the paths for a drawing effect shows you at least understand how to build a technical asset. The `stroke-dashoffset` animation is a classic for a reason—it works. If only the rest of the design had that much thought put into it.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 3/10 - It’s as exciting as a graph paper notebook.
+**Color & Typography:** 2/10 - A total lack of direction and courage.
+**Motion & Animation Feel:** 4/10 - Functional, but lacks any rhythmic "snap."
+**Overall Aesthetic:** 3/10 - "Corporate Minimalist" is just a polite way of saying "I didn't try."
+
+**Bottom Line:** This looks like a technical demo for a library, not a finished piece of media. It’s cold, it’s disjointed, and it’s boring. Fix the typography and respect your own grid, or don't bother calling it "design."
diff --git a/packages/producer/tests/style-11-prod/src/index.html b/packages/producer/tests/style-11-prod/src/index.html
new file mode 100644
index 0000000000..bfc2158813
--- /dev/null
+++ b/packages/producer/tests/style-11-prod/src/index.html
@@ -0,0 +1,167 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Editor Agent - Sol LeWitt Style</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1080px;
+ height: 1920px;
+ background-color: #F5F1EA;
+ overflow: hidden;
+ font-family: 'IBM Plex Mono', 'Courier New', Courier, monospace;
+ }
+
+ #main-canvas {
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ overflow: hidden;
+ background: linear-gradient(180deg, #F6F1E8 0%, #EFE8DE 100%);
+ }
+
+ #bg-grid-comp,
+ #mg-overlays-comp,
+ #captions-comp,
+ #aroll-frame {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ }
+
+ #bg-grid-comp {
+ z-index: 0;
+ }
+
+ #aroll-frame {
+ top: 188px;
+ left: 108px;
+ width: 756px;
+ height: 1180px;
+ background: #111111;
+ overflow: hidden;
+ border: 2px solid #1D1D1D;
+ box-shadow: 0 22px 48px rgba(17, 17, 17, 0.16);
+ z-index: 10;
+ }
+
+ #aroll-frame::before {
+ content: "";
+ position: absolute;
+ inset: 14px;
+ border: 1px solid rgba(255, 255, 255, 0.28);
+ pointer-events: none;
+ z-index: 3;
+ }
+
+ #aroll-video,
+ #aroll-frame img.__render_frame__,
+ #aroll-frame img.__preview_render_frame__ {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ filter: saturate(0.88) contrast(1.06) brightness(0.97);
+ }
+
+ .frame-meta {
+ position: absolute;
+ left: 18px;
+ right: 18px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ color: rgba(255, 255, 255, 0.9);
+ font-size: 18px;
+ letter-spacing: 0.18em;
+ text-transform: uppercase;
+ z-index: 4;
+ pointer-events: none;
+ }
+
+ .frame-meta.top {
+ top: 18px;
+ }
+
+ .frame-meta.bottom {
+ bottom: 18px;
+ }
+
+ #mg-overlays-comp {
+ z-index: 20;
+ }
+
+ #captions-comp {
+ z-index: 30;
+ pointer-events: none;
+ }
+ </style>
+</head>
+<body>
+ <div id="main-canvas" data-composition-id="main-comp" data-width="1080" data-height="1920" data-start="0" data-duration="13.88">
+ <div id="bg-grid-comp"
+ data-composition-id="bg-grid-comp"
+ data-composition-src="compositions/bg-grid.html"
+ data-start="0"
+ data-duration="13.88"
+ data-track-index="1">
+ </div>
+
+ <div id="aroll-frame">
+ <div class="frame-meta top">
+ <span>Editor Agent</span>
+ <span>Portrait System</span>
+ </div>
+ <video id="aroll-video"
+ data-start="0"
+ data-duration="13.88"
+ data-track-index="2"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/a8bed725_8ae955c61e3141e09d9eadb97e0eef93.mp4">
+ </video>
+ <div class="frame-meta bottom">
+ <span>Survey Cut</span>
+ <span>13.88s</span>
+ </div>
+ </div>
+
+ <div id="mg-overlays-comp"
+ data-composition-id="mg-overlays-comp"
+ data-composition-src="compositions/mg-overlays.html"
+ data-start="0"
+ data-duration="13.88"
+ data-track-index="3">
+ </div>
+
+ <div id="captions-comp"
+ data-composition-id="captions-comp"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="13.88"
+ data-track-index="4">
+ </div>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+
+ tl.fromTo('#aroll-frame', {
+ y: 18,
+ scale: 1.02
+ }, {
+ y: 0,
+ scale: 1,
+ duration: 0.9,
+ ease: "power2.out"
+ }, 0);
+
+ window.__timelines["main-comp"] = tl;
+ </script>
+ </div>
+</body>
+</html>
diff --git a/packages/producer/tests/style-12-prod/meta.json b/packages/producer/tests/style-12-prod/meta.json
new file mode 100644
index 0000000000..2a6bdc49f7
--- /dev/null
+++ b/packages/producer/tests/style-12-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-12-prod",
+ "description": "Regression fixture imported from normalized style pack style-12-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "portrait"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-12-prod/src/code_review.md b/packages/producer/tests/style-12-prod/src/code_review.md
new file mode 100644
index 0000000000..b52d2a2838
--- /dev/null
+++ b/packages/producer/tests/style-12-prod/src/code_review.md
@@ -0,0 +1,56 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 4
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None. All compositions follow the core deterministic and structural requirements of the HyperFrame schema.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images)
+- [x] No manual media playback control (`video.play()`, `video.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - all absolute)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+## File Reviews
+
+### [index.html]
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. The file correctly uses `data-composition-id`, `data-width`, `data-height`, `data-start`, `data-duration`, and `data-track`. It registers its timeline in `window.__timelines`.
+
+### [compositions/mondrian-bg.html]
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Correct use of `<template>`, `data-composition-id`, and timeline registration. Animations are deterministic.
+
+### [compositions/mondrian-colors.html]
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. The script uses a fixed `TRANSCRIPT` array and deterministic logic to build the timeline.
+
+### [compositions/mondrian-captions.html]
+**Status**: COMPLIANT
+
+**Issues Found**:
+- **Note**: The script dynamically creates DOM elements based on a static `TRANSCRIPT` array. This is acceptable within a composition as long as the logic is deterministic and the composition itself is registered in `window.__timelines`.
+
+## Recommendations
+1. **Deterministic Captions**: Ensure the `TRANSCRIPT` array remains static and the logic for grouping words is consistent across all environments.
+2. **Track Overlap Check**: The current track assignments (Track 1: BG, Track 2: Video, Track 3: Colors, Track 4: Captions) are well-organized and prevent overlap.
diff --git a/packages/producer/tests/style-12-prod/src/compositions/mondrian-bg.html b/packages/producer/tests/style-12-prod/src/compositions/mondrian-bg.html
new file mode 100644
index 0000000000..1f0928b596
--- /dev/null
+++ b/packages/producer/tests/style-12-prod/src/compositions/mondrian-bg.html
@@ -0,0 +1,79 @@
+<template id="mondrian-bg-template">
+ <div data-composition-id="mondrian-bg" data-width="1080" data-height="1920" data-duration="14">
+ <div class="mondrian-container">
+ <div class="grid-line horizontal primary" style="top: 248px; height: 4px;"></div>
+ <div class="grid-line horizontal primary" style="top: 898px; height: 4px;"></div>
+ <div class="grid-line horizontal secondary" style="top: 1510px; height: 2px;"></div>
+ <div class="grid-line vertical primary" style="left: 246px; width: 4px;"></div>
+ <div class="grid-line vertical primary" style="left: 834px; width: 4px;"></div>
+ <div class="grid-line vertical secondary" style="left: 960px; width: 2px;"></div>
+
+ <div class="sliding-bar horizontal bar-1" style="top: 248px; height: 4px;"></div>
+ <div class="sliding-bar vertical bar-2" style="left: 834px; width: 4px;"></div>
+ <div class="sliding-bar horizontal bar-3" style="top: 898px; height: 4px;"></div>
+ <div class="sliding-bar vertical bar-4" style="left: 246px; width: 4px;"></div>
+ </div>
+
+ <style>
+ [data-composition-id="mondrian-bg"] {
+ background-color: #FFFFFF;
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ overflow: hidden;
+ }
+
+ [data-composition-id="mondrian-bg"] .mondrian-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ }
+
+ [data-composition-id="mondrian-bg"] .grid-line {
+ position: absolute;
+ background-color: #000000;
+ }
+
+ [data-composition-id="mondrian-bg"] .grid-line.horizontal {
+ width: 100%;
+ left: 0;
+ }
+
+ [data-composition-id="mondrian-bg"] .grid-line.vertical {
+ height: 100%;
+ top: 0;
+ }
+
+ [data-composition-id="mondrian-bg"] .sliding-bar {
+ position: absolute;
+ background-color: #000000;
+ z-index: 10;
+ }
+
+ [data-composition-id="mondrian-bg"] .sliding-bar.horizontal {
+ width: 100%;
+ left: -100%;
+ }
+
+ [data-composition-id="mondrian-bg"] .sliding-bar.vertical {
+ height: 100%;
+ top: -100%;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ tl.to('.bar-1', { left: '100%', duration: 0.45, ease: 'expo.out' }, 1.1);
+ tl.to('.bar-2', { top: '100%', duration: 0.55, ease: 'expo.out' }, 4.05);
+ tl.to('.bar-3', { left: '100%', duration: 0.48, ease: 'expo.out' }, 7.35);
+ tl.to('.bar-4', { top: '100%', duration: 0.55, ease: 'expo.out' }, 10.25);
+
+ window.__timelines["mondrian-bg"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-12-prod/src/compositions/mondrian-captions.html b/packages/producer/tests/style-12-prod/src/compositions/mondrian-captions.html
new file mode 100644
index 0000000000..8400ab2126
--- /dev/null
+++ b/packages/producer/tests/style-12-prod/src/compositions/mondrian-captions.html
@@ -0,0 +1,101 @@
+<template id="mondrian-captions-template">
+ <div data-composition-id="mondrian-captions" data-width="1080" data-height="1920" data-duration="14">
+ <div id="captions-panel">
+ <div id="captions-kicker">Editor Agent</div>
+ <div id="captions-container"></div>
+ </div>
+
+ <style>
+ [data-composition-id="mondrian-captions"] {
+ width: 1080px;
+ height: 1920px;
+ background: transparent;
+ font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ font-weight: 900;
+ text-transform: uppercase;
+ overflow: hidden;
+ position: relative;
+ }
+
+ [data-composition-id="mondrian-captions"] #captions-panel {
+ position: absolute;
+ left: 246px;
+ top: 1484px;
+ width: 588px;
+ min-height: 300px;
+ background: rgba(255, 255, 255, 0.96);
+ border: 4px solid #000;
+ box-sizing: border-box;
+ padding: 22px 28px 28px;
+ z-index: 10;
+ }
+
+ [data-composition-id="mondrian-captions"] #captions-kicker {
+ font-size: 20px;
+ letter-spacing: 0.24em;
+ margin-bottom: 18px;
+ }
+
+ [data-composition-id="mondrian-captions"] #captions-container {
+ position: relative;
+ min-height: 206px;
+ }
+
+ [data-composition-id="mondrian-captions"] .caption-group {
+ position: absolute;
+ inset: 0;
+ opacity: 0;
+ visibility: hidden;
+ }
+
+ [data-composition-id="mondrian-captions"] .caption-text {
+ color: #000000;
+ font-size: 62px;
+ line-height: 1.02;
+ letter-spacing: -2px;
+ white-space: normal;
+ text-align: left;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.14, 'end': 0.239}, {'text': 'asked', 'start': 0.28, 'end': 0.459}, {'text': 'what', 'start': 0.5, 'end': 0.619}, {'text': 'you', 'start': 0.659, 'end': 0.779}, {'text': 'needed.', 'start': 0.8, 'end': 1.179}, {'text': 'Forty-seven', 'start': 1.199, 'end': 1.619}, {'text': 'percent', 'start': 1.699, 'end': 1.96}, {'text': 'of', 'start': 1.979, 'end': 2.059}, {'text': 'you', 'start': 2.099, 'end': 2.299}, {'text': 'said', 'start': 2.319, 'end': 2.499}, {'text': 'motion', 'start': 2.559, 'end': 2.839}, {'text': 'graphics,', 'start': 2.899, 'end': 3.759}, {'text': 'sixty-two', 'start': 3.799, 'end': 4.159}, {'text': 'percent', 'start': 4.239, 'end': 4.559}, {'text': 'said', 'start': 4.639, 'end': 4.799}, {'text': 'static', 'start': 4.859, 'end': 5.199}, {'text': 'content', 'start': 5.239, 'end': 5.639}, {'text': 'was', 'start': 5.679, 'end': 5.779}, {'text': 'costing', 'start': 5.859, 'end': 6.219}, {'text': 'you', 'start': 6.259, 'end': 6.339}, {'text': 'attention,', 'start': 6.379, 'end': 7.299}, {'text': 'and', 'start': 7.319, 'end': 7.439}, {'text': 'three', 'start': 7.48, 'end': 7.599}, {'text': 'out', 'start': 7.679, 'end': 7.779}, {'text': 'of', 'start': 7.799, 'end': 7.879}, {'text': 'four', 'start': 7.94, 'end': 8.139}, {'text': 'said', 'start': 8.279, 'end': 8.46}, {'text': 'you', 'start': 8.519, 'end': 8.6}, {'text': 'know', 'start': 8.619, 'end': 8.739}, {'text': 'the', 'start': 8.8, 'end': 8.88}, {'text': 'look', 'start': 8.92, 'end': 9.079}, {'text': 'you', 'start': 9.119, 'end': 9.259}, {'text': 'want', 'start': 9.279, 'end': 9.619}, {'text': 'but', 'start': 9.779, 'end': 9.88}, {'text': "don't", 'start': 9.92, 'end': 10.1}, {'text': 'have', 'start': 10.159, 'end': 10.3}, {'text': 'the', 'start': 10.3, 'end': 10.42}, {'text': 'editing', 'start': 10.5, 'end': 10.779}, {'text': 'skills', 'start': 10.86, 'end': 11.139}, {'text': 'to', 'start': 11.159, 'end': 11.239}, {'text': 'get', 'start': 11.279, 'end': 11.439}, {'text': 'there.', 'start': 11.46, 'end': 12.239}, {'text': 'So', 'start': 12.3, 'end': 12.38}, {'text': 'we', 'start': 12.399, 'end': 12.519}, {'text': 'built', 'start': 12.539, 'end': 12.759}, {'text': 'Editor', 'start': 12.84, 'end': 13.119}, {'text': 'Agent.', 'start': 13.239, 'end': 13.84}];
+ const container = document.getElementById('captions-container');
+ const tl = gsap.timeline({ paused: true });
+
+ const groups = [];
+ let currentGroup = [];
+ let wordCount = 0;
+
+ TRANSCRIPT.forEach((word, index) => {
+ currentGroup.push(word);
+ wordCount++;
+ const isLastWord = index === TRANSCRIPT.length - 1;
+ const hasPunctuation = /[.!?]/.test(word.text);
+ if (wordCount >= 4 || hasPunctuation || isLastWord) {
+ groups.push([...currentGroup]);
+ currentGroup = [];
+ wordCount = 0;
+ }
+ });
+
+ groups.forEach((group, i) => {
+ const groupEl = document.createElement('div');
+ groupEl.className = 'caption-group';
+ const textEl = document.createElement('div');
+ textEl.className = 'caption-text';
+ textEl.innerText = group.map(w => w.text).join(' ');
+ groupEl.appendChild(textEl);
+ container.appendChild(groupEl);
+ const startTime = group[0].start;
+ const endTime = group[group.length - 1].end;
+ tl.fromTo(groupEl, { autoAlpha: 0, y: 18 }, { autoAlpha: 1, y: 0, duration: 0.12, ease: 'power2.out' }, startTime);
+ tl.to(groupEl, { autoAlpha: 0, y: -8, duration: 0.1, ease: 'power2.in' }, endTime);
+ });
+
+ window.__timelines["mondrian-captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-12-prod/src/compositions/mondrian-colors.html b/packages/producer/tests/style-12-prod/src/compositions/mondrian-colors.html
new file mode 100644
index 0000000000..786b4814e6
--- /dev/null
+++ b/packages/producer/tests/style-12-prod/src/compositions/mondrian-colors.html
@@ -0,0 +1,154 @@
+<template id="mondrian-colors-template">
+ <div data-composition-id="mondrian-colors" data-width="1080" data-height="1920" data-duration="14">
+ <div class="mondrian-grid">
+ <div class="block block-1 border-right border-bottom">
+ <div class="color-fill red"></div>
+ <div class="block-text text-47 light">47%</div>
+ </div>
+ <div class="block block-2 border-bottom">
+ <div class="color-fill yellow"></div>
+ </div>
+
+ <div class="block block-3 border-right border-bottom">
+ <div class="color-fill blue"></div>
+ <div class="block-text text-62 light">62%</div>
+ </div>
+ <div class="block block-empty border-bottom"></div>
+ <div class="block block-4 border-bottom">
+ <div class="color-fill red"></div>
+ </div>
+
+ <div class="block block-5 border-right">
+ <div class="color-fill yellow"></div>
+ <div class="block-text text-34 dark">3/4</div>
+ </div>
+ <div class="block block-6">
+ <div class="color-fill blue"></div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="mondrian-colors"] {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ background-color: transparent;
+ overflow: hidden;
+ }
+
+ [data-composition-id="mondrian-colors"] .mondrian-grid {
+ display: grid;
+ grid-template-columns: 246px 588px 246px;
+ grid-template-rows: 248px 650px 1022px;
+ width: 1080px;
+ height: 1920px;
+ border: 4px solid #000;
+ }
+
+ [data-composition-id="mondrian-colors"] .block {
+ position: relative;
+ background-color: transparent;
+ overflow: hidden;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+
+ [data-composition-id="mondrian-colors"] .color-fill {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ opacity: 0;
+ transform: scale(0.92);
+ }
+
+ [data-composition-id="mondrian-colors"] .block-text {
+ position: relative;
+ z-index: 2;
+ font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ font-weight: 900;
+ opacity: 0;
+ transform: scale(0.7);
+ letter-spacing: -3px;
+ line-height: 0.92;
+ }
+
+ [data-composition-id="mondrian-colors"] .text-47,
+ [data-composition-id="mondrian-colors"] .text-62 {
+ font-size: 106px;
+ }
+
+ [data-composition-id="mondrian-colors"] .text-34 {
+ font-size: 176px;
+ letter-spacing: -8px;
+ }
+
+ [data-composition-id="mondrian-colors"] .light {
+ color: #FFFFFF;
+ }
+
+ [data-composition-id="mondrian-colors"] .dark {
+ color: #000000;
+ }
+
+ [data-composition-id="mondrian-colors"] .red { background-color: #FF1A1A; }
+ [data-composition-id="mondrian-colors"] .yellow { background-color: #FFEA00; }
+ [data-composition-id="mondrian-colors"] .blue { background-color: #0A36FF; }
+
+ [data-composition-id="mondrian-colors"] .border-right { border-right: 4px solid #000; }
+ [data-composition-id="mondrian-colors"] .border-bottom { border-bottom: 4px solid #000; }
+
+ [data-composition-id="mondrian-colors"] .block-1 { grid-column: 1 / 2; grid-row: 1 / 2; }
+ [data-composition-id="mondrian-colors"] .block-2 { grid-column: 2 / 4; grid-row: 1 / 2; }
+ [data-composition-id="mondrian-colors"] .block-3 { grid-column: 1 / 2; grid-row: 2 / 3; }
+ [data-composition-id="mondrian-colors"] .block-empty { grid-column: 2 / 3; grid-row: 2 / 3; background-color: transparent; pointer-events: none; }
+ [data-composition-id="mondrian-colors"] .block-4 { grid-column: 3 / 4; grid-row: 2 / 3; border-left: 4px solid #000; }
+ [data-composition-id="mondrian-colors"] .block-5 { grid-column: 1 / 3; grid-row: 3 / 4; justify-content: flex-start; padding-left: 56px; }
+ [data-composition-id="mondrian-colors"] .block-6 { grid-column: 3 / 4; grid-row: 3 / 4; }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.14, 'end': 0.239}, {'text': 'asked', 'start': 0.28, 'end': 0.459}, {'text': 'what', 'start': 0.5, 'end': 0.619}, {'text': 'you', 'start': 0.659, 'end': 0.779}, {'text': 'needed.', 'start': 0.8, 'end': 1.179}, {'text': 'Forty-seven', 'start': 1.199, 'end': 1.619}, {'text': 'percent', 'start': 1.699, 'end': 1.96}, {'text': 'of', 'start': 1.979, 'end': 2.059}, {'text': 'you', 'start': 2.099, 'end': 2.299}, {'text': 'said', 'start': 2.319, 'end': 2.499}, {'text': 'motion', 'start': 2.559, 'end': 2.839}, {'text': 'graphics,', 'start': 2.899, 'end': 3.759}, {'text': 'sixty-two', 'start': 3.799, 'end': 4.159}, {'text': 'percent', 'start': 4.239, 'end': 4.559}, {'text': 'said', 'start': 4.639, 'end': 4.799}, {'text': 'static', 'start': 4.859, 'end': 5.199}, {'text': 'content', 'start': 5.239, 'end': 5.639}, {'text': 'was', 'start': 5.679, 'end': 5.779}, {'text': 'costing', 'start': 5.859, 'end': 6.219}, {'text': 'you', 'start': 6.259, 'end': 6.339}, {'text': 'attention,', 'start': 6.379, 'end': 7.299}, {'text': 'and', 'start': 7.319, 'end': 7.439}, {'text': 'three', 'start': 7.48, 'end': 7.599}, {'text': 'out', 'start': 7.679, 'end': 7.779}, {'text': 'of', 'start': 7.799, 'end': 7.879}, {'text': 'four', 'start': 7.94, 'end': 8.139}, {'text': 'said', 'start': 8.279, 'end': 8.46}, {'text': 'you', 'start': 8.519, 'end': 8.6}, {'text': 'know', 'start': 8.619, 'end': 8.739}, {'text': 'the', 'start': 8.8, 'end': 8.88}, {'text': 'look', 'start': 8.92, 'end': 9.079}, {'text': 'you', 'start': 9.119, 'end': 9.259}, {'text': 'want', 'start': 9.279, 'end': 9.619}, {'text': 'but', 'start': 9.779, 'end': 9.88}, {'text': "don't", 'start': 9.92, 'end': 10.1}, {'text': 'have', 'start': 10.159, 'end': 10.3}, {'text': 'the', 'start': 10.3, 'end': 10.42}, {'text': 'editing', 'start': 10.5, 'end': 10.779}, {'text': 'skills', 'start': 10.86, 'end': 11.139}, {'text': 'to', 'start': 11.159, 'end': 11.239}, {'text': 'get', 'start': 11.279, 'end': 11.439}, {'text': 'there.', 'start': 11.46, 'end': 12.239}, {'text': 'So', 'start': 12.3, 'end': 12.38}, {'text': 'we', 'start': 12.399, 'end': 12.519}, {'text': 'built', 'start': 12.539, 'end': 12.759}, {'text': 'Editor', 'start': 12.84, 'end': 13.119}, {'text': 'Agent.', 'start': 13.239, 'end': 13.84}];
+ const tl = gsap.timeline({ paused: true });
+
+ function getWordTime(text) {
+ const word = TRANSCRIPT.find(w => w.text.toLowerCase().includes(text.toLowerCase()));
+ return word ? word.start : null;
+ }
+
+ const time47 = getWordTime('forty-seven');
+ const time62 = getWordTime('sixty-two');
+ const time75 = getWordTime('three');
+
+ if (time47 !== null) {
+ tl.to('.block-1 .color-fill', { opacity: 0.96, scale: 1, duration: 0.24, ease: 'power2.out' }, time47);
+ tl.to('.block-1 .block-text', { opacity: 1, scale: 1, duration: 0.24, ease: 'power2.out' }, time47 + 0.06);
+ tl.to('.block-2 .color-fill', { opacity: 0.92, scale: 1, duration: 0.24, ease: 'power2.out' }, time47 + 0.08);
+ }
+
+ if (time62 !== null) {
+ tl.to('.block-3 .color-fill', { opacity: 0.96, scale: 1, duration: 0.24, ease: 'power2.out' }, time62);
+ tl.to('.block-3 .block-text', { opacity: 1, scale: 1, duration: 0.24, ease: 'power2.out' }, time62 + 0.06);
+ tl.to('.block-4 .color-fill', { opacity: 0.96, scale: 1, duration: 0.24, ease: 'power2.out' }, time62 + 0.08);
+ tl.to('.block-1 .color-fill', { opacity: 0.18, duration: 0.24, ease: 'power2.out' }, time62 + 0.42);
+ tl.to('.block-1 .block-text', { opacity: 0.22, duration: 0.24, ease: 'power2.out' }, time62 + 0.42);
+ }
+
+ if (time75 !== null) {
+ tl.to('.block-5 .color-fill', { opacity: 0.92, scale: 1, duration: 0.24, ease: 'power2.out' }, time75);
+ tl.to('.block-5 .block-text', { opacity: 1, scale: 1, duration: 0.24, ease: 'power2.out' }, time75 + 0.06);
+ tl.to('.block-6 .color-fill', { opacity: 0.96, scale: 1, duration: 0.24, ease: 'power2.out' }, time75 + 0.08);
+ tl.to('.block-3 .color-fill', { opacity: 0.18, duration: 0.24, ease: 'power2.out' }, time75 + 0.42);
+ tl.to('.block-3 .block-text', { opacity: 0.22, duration: 0.24, ease: 'power2.out' }, time75 + 0.42);
+ }
+
+ window.__timelines["mondrian-colors"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-12-prod/src/design_review.md b/packages/producer/tests/style-12-prod/src/design_review.md
new file mode 100644
index 0000000000..ea7ee2b251
--- /dev/null
+++ b/packages/producer/tests/style-12-prod/src/design_review.md
@@ -0,0 +1,61 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a Piet Mondrian painting had a mid-life crisis and tried to become a TikTok influencer. It’s a bold concept, but the execution is currently a cluttered mess of competing geometries and muddy colors.
+
+---
+
+## CRITICAL Design Failures
+
+Issues that make this look unprofessional or straight-up ugly. These MUST be fixed.
+
+### The "Safe Zone" is a Visual Black Hole
+**Where:** `compositions/mondrian-colors.html` - `.block-empty`
+**What's wrong:** You've left a giant, gaping hole in the middle of your grid for the "speaker's face," but the surrounding black borders are 10px thick. It looks like the video is trapped in a cage.
+**Why it matters:** Instead of the video feeling integrated into the design, it feels like an afterthought being squeezed by a heavy, oppressive frame.
+**Fix it:** Reduce the border weight to 4px or 6px, or better yet, let the video bleed *under* some of the lines rather than being perfectly boxed in.
+
+### Muddy "Mondrian" Palette
+**Where:** `compositions/mondrian-colors.html` - `.red`, `.yellow`, `.blue`
+**What's wrong:** You're using "Oxblood Red" (#8B0000), "Saffron Yellow" (#F4C430), and "Cobalt Blue" (#0047AB). These aren't Mondrian colors; they're the colors of a dusty university library.
+**Why it matters:** De Stijl is about primary, vibrant, high-contrast colors. These muted tones make the whole composition look dated and heavy rather than modern and sharp.
+**Fix it:** Use true primary colors: Red (#FF0000), Yellow (#FFEF00), and Blue (#0000FF). And make the background a crisp white (#FFFFFF), not this "fdfdfd" off-white nonsense.
+
+### Typography Hierarchy is Non-Existent
+**Where:** `compositions/mondrian-colors.html` - `.block-text` and `compositions/mondrian-captions.html` - `.caption-text`
+**What's wrong:** You're using 100px Inter Black for everything. The "47%" is the same weight as the captions, which are the same weight as the "3/4".
+**Why it matters:** When everything is loud, nothing is heard. The viewer doesn't know where to look because every element is screaming for attention with the same visual volume.
+**Fix it:** Vary your weights. Use Inter Tight for the big numbers and maybe a lighter weight or a different tracking for the captions. Create a clear path for the eye.
+
+---
+
+## Design Improvements
+
+Things that aren't broken but are boring, lazy, or could be significantly better.
+
+### Robotic Motion
+**Where:** `compositions/mondrian-bg.html` - `.sliding-bar`
+**The problem:** Your sliding bars use `expo.inOut` and just slide across the screen at 3-second intervals. It’s predictable and lacks "snap."
+**Make it better:** Use `expo.out` for a faster start and a smoother settle. Offset the timing so they don't feel like they're on a conveyor belt. Add a slight overshoot to give them some personality.
+
+### Caption Backgrounds are Distracting
+**Where:** `compositions/mondrian-captions.html` - `.caption-group`
+**The problem:** You're cycling through background colors for every 4 words. It’s a strobe light effect that makes the text harder to read.
+**Make it better:** Stick to one background style for the captions (maybe just the white box with the black border) and let the *color blocks* in the background handle the visual variety.
+
+---
+
+## What Actually Works
+
+The concept of using the Mondrian grid to reveal statistics (47%, 62%, 3/4) is actually clever. When the video cuts out at 7.4s to show the "3/4" stat on a full canvas, it creates a genuine moment of impact. It’s the only part of this that feels like it was designed by someone with a pulse.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 4/10 - Bold idea, but currently looks like a PowerPoint template from a "Modern Art" seminar.
+**Color & Typography:** 2/10 - The colors are depressing and the typography is a blunt instrument.
+**Motion & Animation Feel:** 5/10 - Functional, but lacks the "premium" feel required for a high-end edit.
+**Overall Aesthetic:** 3/10 - It’s trying too hard to be "artistic" without understanding the fundamentals of the style it's mimicking.
+
+**Bottom Line:** This needs a massive injection of contrast and a serious diet for those borders. Right now, it’s a claustrophobic mess. Fix the colors, thin the lines, and give the type some room to breathe.
diff --git a/packages/producer/tests/style-12-prod/src/index.html b/packages/producer/tests/style-12-prod/src/index.html
new file mode 100644
index 0000000000..d18b84a299
--- /dev/null
+++ b/packages/producer/tests/style-12-prod/src/index.html
@@ -0,0 +1,143 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=1080, height=1920">
+ <title>Editor Agent - De Stijl Edition</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1080px;
+ height: 1920px;
+ background-color: #FFFFFF;
+ overflow: hidden;
+ }
+
+ #main-comp {
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ overflow: hidden;
+ background: #FFFFFF;
+ }
+
+ #bg-layer,
+ #colors-layer,
+ #captions-layer,
+ #a-roll-frame {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ }
+
+ #bg-layer {
+ z-index: 0;
+ }
+
+ #a-roll-frame {
+ z-index: 10;
+ overflow: hidden;
+ background: #111111;
+ }
+
+ #a-roll-video,
+ #a-roll-frame img.__render_frame__,
+ #a-roll-frame img.__preview_render_frame__ {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ filter: saturate(0.9) contrast(1.04);
+ }
+
+ #colors-layer {
+ z-index: 20;
+ pointer-events: none;
+ }
+
+ #captions-layer {
+ z-index: 30;
+ pointer-events: none;
+ }
+ </style>
+</head>
+<body>
+ <div id="main-comp"
+ data-composition-id="main-video"
+ data-width="1080"
+ data-height="1920"
+ data-start="0"
+ data-duration="14">
+
+ <!-- 1. Background Grid Layer -->
+ <div id="bg-layer"
+ data-composition-id="mondrian-bg"
+ data-composition-src="compositions/mondrian-bg.html"
+ data-start="0"
+ data-track-index="1"
+ data-duration="14">
+ </div>
+
+ <!-- 2. A-roll Video Layer -->
+ <div id="a-roll-frame">
+ <video id="a-roll-video"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/61ae9527_715ce519da784c0daae4f3aade82ee56.mp4"
+ data-start="0"
+ data-duration="14"
+ data-track-index="2">
+ </video>
+ </div>
+
+ <!-- 3. Color Block Reaction Layer -->
+ <div id="colors-layer"
+ data-composition-id="mondrian-colors"
+ data-composition-src="compositions/mondrian-colors.html"
+ data-start="0"
+ data-track-index="3"
+ data-duration="14">
+ </div>
+
+ <!-- 4. Captions Layer -->
+ <div id="captions-layer"
+ data-composition-id="mondrian-captions"
+ data-composition-src="compositions/mondrian-captions.html"
+ data-start="0"
+ data-track-index="4"
+ data-duration="14">
+ </div>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ tl.fromTo('#a-roll-frame', {
+ scale: 1.02
+ }, {
+ scale: 1,
+ duration: 0.8,
+ ease: 'power2.out'
+ }, 0);
+
+ tl.to('#a-roll-frame', {
+ opacity: 0.34,
+ duration: 0.35,
+ ease: 'power2.inOut'
+ }, 7.4);
+
+ tl.to('#a-roll-frame', {
+ opacity: 1,
+ duration: 0.4,
+ ease: 'power2.inOut'
+ }, 10.5);
+
+ window.__timelines["main-video"] = tl;
+ })();
+ </script>
+ </div>
+</body>
+</html>
diff --git a/packages/producer/tests/style-13-prod/meta.json b/packages/producer/tests/style-13-prod/meta.json
new file mode 100644
index 0000000000..b404a324b8
--- /dev/null
+++ b/packages/producer/tests/style-13-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-13-prod",
+ "description": "Regression fixture imported from normalized style pack style-13-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "portrait"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-13-prod/src/code_review.md b/packages/producer/tests/style-13-prod/src/code_review.md
new file mode 100644
index 0000000000..b351dfd08a
--- /dev/null
+++ b/packages/producer/tests/style-13-prod/src/code_review.md
@@ -0,0 +1,56 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 5
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None found.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images used)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - absolute timing used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+### index.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. The file correctly orchestrates sub-compositions and a primitive video clip using the required data attributes.
+
+### compositions/background.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Uses deterministic loops to simulate breathing/pulsing effects over the 16s duration.
+
+### compositions/transitions.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Correctly registers its timeline and uses deterministic animations.
+
+### compositions/captions.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Dynamically creates content within a composition container and manages it via a GSAP timeline registered in `window.__timelines`.
+
+### compositions/overlays.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Uses deterministic staggers and loops for grid animations.
diff --git a/packages/producer/tests/style-13-prod/src/compositions/background.html b/packages/producer/tests/style-13-prod/src/compositions/background.html
new file mode 100644
index 0000000000..73ea55b8a2
--- /dev/null
+++ b/packages/producer/tests/style-13-prod/src/compositions/background.html
@@ -0,0 +1,162 @@
+<template id="background-template">
+ <div data-composition-id="background" data-width="1080" data-height="1920" data-duration="16">
+ <div class="bg-container">
+ <!-- Dot Matrix Grid -->
+ <div class="dot-grid"></div>
+
+ <!-- Grid Lines -->
+ <div class="grid-lines-h"></div>
+ <div class="grid-lines-v"></div>
+
+ <!-- Scanline -->
+ <div class="scanline"></div>
+ </div>
+
+ <style>
+ [data-composition-id="background"] .bg-container {
+ width: 1080px;
+ height: 1920px;
+ background-color: #1A1A1A;
+ position: relative;
+ overflow: hidden;
+ }
+
+ /* Dot Matrix */
+ [data-composition-id="background"] .dot-grid {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-image: radial-gradient(#333333 1.5px, transparent 1.5px);
+ background-size: 40px 40px;
+ opacity: 0.45; /* Initial mid-point for breathing */
+ transform-origin: center center;
+ }
+
+ /* Grid Lines */
+ [data-composition-id="background"] .grid-lines-h,
+ [data-composition-id="background"] .grid-lines-v {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ }
+
+ [data-composition-id="background"] .grid-lines-h {
+ background-image: linear-gradient(to bottom, rgba(0, 255, 128, 0.15) 1px, transparent 1px);
+ background-size: 100% 160px; /* Larger grid for lines */
+ }
+
+ [data-composition-id="background"] .grid-lines-v {
+ background-image: linear-gradient(to right, rgba(0, 255, 128, 0.15) 1px, transparent 1px);
+ background-size: 160px 100%;
+ }
+
+ /* Scanline */
+ [data-composition-id="background"] .scanline {
+ position: absolute;
+ top: -100px;
+ left: 0;
+ width: 100%;
+ height: 100px;
+ background: linear-gradient(to bottom,
+ transparent,
+ rgba(0, 255, 128, 0.25) 50%,
+ transparent
+ );
+ pointer-events: none;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const duration = 16;
+
+ // 1. Breathing Dots Animation
+ // Using a deterministic sine-like wave with multiple steps to simulate breathing
+ // Since we can't use repeat: -1, we'll build the sequence for the full duration
+ const breathingCycle = 2;
+ const breathingSteps = Math.ceil(duration / breathingCycle);
+ for (let i = 0; i < breathingSteps; i++) {
+ tl.to('.dot-grid', {
+ opacity: 0.6,
+ scale: 1.02,
+ duration: 1,
+ ease: "power1.inOut"
+ }, i * breathingCycle);
+ tl.to('.dot-grid', {
+ opacity: 0.3,
+ scale: 0.98,
+ duration: 1,
+ ease: "power1.inOut"
+ }, i * breathingCycle + 1);
+ }
+
+ // 2. Grid Lines Pulse/Glow
+ // Pulse every 2 seconds deterministically
+ const pulseCycle = 2;
+ const pulseSteps = Math.ceil(duration / pulseCycle);
+ for (let i = 0; i < pulseSteps; i++) {
+ const startTime = i * pulseCycle + 0.5; // Offset slightly from breathing
+ tl.to(['.grid-lines-h', '.grid-lines-v'], {
+ opacity: 0.8,
+ filter: "drop-shadow(0 0 5px #00CC66)",
+ duration: 0.1,
+ ease: "none"
+ }, startTime);
+ tl.to(['.grid-lines-h', '.grid-lines-v'], {
+ opacity: 0.1,
+ filter: "drop-shadow(0 0 0px #00CC66)",
+ duration: 0.4,
+ ease: "power2.out"
+ }, startTime + 0.1);
+ }
+
+ // 3. Scanline Movement & Parallax
+ // Moves from top to bottom every 4 seconds
+ const scanlineCycle = 4;
+ const scanlineSteps = Math.ceil(duration / scanlineCycle);
+ for (let i = 0; i < scanlineSteps; i++) {
+ tl.fromTo('.scanline',
+ { top: -100 },
+ { top: 1920, duration: scanlineCycle, ease: "none" },
+ i * scanlineCycle
+ );
+
+ // Subtle parallax shift on grid lines
+ tl.to('.grid-lines-h', {
+ y: "+=40",
+ duration: scanlineCycle,
+ ease: "none"
+ }, i * scanlineCycle);
+
+ tl.to('.grid-lines-v', {
+ x: "+=40",
+ duration: scanlineCycle,
+ ease: "none"
+ }, i * scanlineCycle);
+ }
+
+ // Parallax shift synced with A-roll exit (7.3s to 7.9s)
+ tl.to('.dot-grid', {
+ x: "-=50",
+ duration: 0.6,
+ ease: "expo.inOut"
+ }, 7.3);
+
+ tl.to('.dot-grid', {
+ x: 0,
+ duration: 0.6,
+ ease: "back.out(1.2)"
+ }, 12.3);
+
+ // Register the timeline
+ window.__timelines["background"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-13-prod/src/compositions/captions.html b/packages/producer/tests/style-13-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..c4373788b0
--- /dev/null
+++ b/packages/producer/tests/style-13-prod/src/compositions/captions.html
@@ -0,0 +1,171 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1080" data-height="1920" data-duration="16">
+ <div id="captions-container"></div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@700&display=swap');
+
+ [data-composition-id="captions"] {
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ display: flex;
+ justify-content: center;
+ align-items: center; /* Centered vertically */
+ font-family: 'Space Mono', monospace;
+ }
+
+ #captions-container {
+ width: 1000px;
+ display: flex;
+ justify-content: center;
+ position: relative;
+ }
+
+ .caption-group {
+ position: absolute;
+ bottom: 0;
+ display: flex;
+ justify-content: center;
+ flex-wrap: wrap;
+ gap: 15px;
+ opacity: 0;
+ width: 100%;
+ padding: 30px 40px;
+ background-color: rgba(26, 26, 26, 0.95); /* Solid high-contrast background */
+ border-radius: 4px;
+ border-left: 8px solid #00FF80;
+ box-shadow: 0 10px 30px rgba(0,0,0,0.5);
+ }
+
+ .word {
+ font-size: 54px;
+ font-weight: 700;
+ color: #FFFFFF;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ display: flex;
+ overflow: hidden;
+ }
+
+ .char {
+ display: inline-block;
+ opacity: 0;
+ color: #FFFFFF; /* White for better legibility */
+ }
+
+ .char.revealed {
+ opacity: 1;
+ color: #FFFFFF;
+ }
+
+ /* Glitch effect styles */
+ .glitch-char {
+ position: relative;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.14, 'end': 0.239}, {'text': 'asked', 'start': 0.28, 'end': 0.459}, {'text': 'what', 'start': 0.5, 'end': 0.619}, {'text': 'you', 'start': 0.659, 'end': 0.779}, {'text': 'needed.', 'start': 0.8, 'end': 1.179}, {'text': 'Forty-seven', 'start': 1.199, 'end': 1.619}, {'text': 'percent', 'start': 1.699, 'end': 1.96}, {'text': 'of', 'start': 1.979, 'end': 2.059}, {'text': 'you', 'start': 2.099, 'end': 2.299}, {'text': 'said', 'start': 2.319, 'end': 2.499}, {'text': 'motion', 'start': 2.559, 'end': 2.839}, {'text': 'graphics,', 'start': 2.899, 'end': 3.759}, {'text': 'sixty-two', 'start': 3.799, 'end': 4.159}, {'text': 'percent', 'start': 4.239, 'end': 4.559}, {'text': 'said', 'start': 4.639, 'end': 4.799}, {'text': 'static', 'start': 4.859, 'end': 5.199}, {'text': 'content', 'start': 5.239, 'end': 5.639}, {'text': 'was', 'start': 5.679, 'end': 5.779}, {'text': 'costing', 'start': 5.859, 'end': 6.219}, {'text': 'you', 'start': 6.259, 'end': 6.339}, {'text': 'attention,', 'start': 6.379, 'end': 7.299}, {'text': 'and', 'start': 7.319, 'end': 7.439}, {'text': 'three', 'start': 7.48, 'end': 7.599}, {'text': 'out', 'start': 7.679, 'end': 7.779}, {'text': 'of', 'start': 7.799, 'end': 7.879}, {'text': 'four', 'start': 7.94, 'end': 8.139}, {'text': 'said', 'start': 8.279, 'end': 8.46}, {'text': 'you', 'start': 8.519, 'end': 8.6}, {'text': 'know', 'start': 8.619, 'end': 8.739}, {'text': 'the', 'start': 8.8, 'end': 8.88}, {'text': 'look', 'start': 8.92, 'end': 9.079}, {'text': 'you', 'start': 9.119, 'end': 9.259}, {'text': 'want', 'start': 9.279, 'end': 9.619}, {'text': 'but', 'start': 9.779, 'end': 9.88}, {'text': "don't", 'start': 9.92, 'end': 10.1}, {'text': 'have', 'start': 10.159, 'end': 10.3}, {'text': 'the', 'start': 10.3, 'end': 10.42}, {'text': 'editing', 'start': 10.5, 'end': 10.779}, {'text': 'skills', 'start': 10.86, 'end': 11.139}, {'text': 'to', 'start': 11.159, 'end': 11.239}, {'text': 'get', 'start': 11.279, 'end': 11.439}, {'text': 'there.', 'start': 11.46, 'end': 12.239}, {'text': 'So', 'start': 12.3, 'end': 12.38}, {'text': 'we', 'start': 12.399, 'end': 12.519}, {'text': 'built', 'start': 12.539, 'end': 12.759}, {'text': 'Editor', 'start': 12.84, 'end': 13.119}, {'text': 'Agent.', 'start': 13.239, 'end': 13.84}];
+ const container = document.getElementById('captions-container');
+ const tl = gsap.timeline({ paused: true });
+
+ // Group transcript into lines (approx 3-5 words per line)
+ const groups = [];
+ let currentGroup = [];
+ TRANSCRIPT.forEach((word, i) => {
+ currentGroup.push(word);
+ // Grouping logic: max 4 words or end of sentence
+ if (currentGroup.length >= 4 || word.text.includes('.') || word.text.includes('?') || word.text.includes('!') || i === TRANSCRIPT.length - 1) {
+ groups.push([...currentGroup]);
+ currentGroup = [];
+ }
+ });
+
+ groups.forEach((group, groupIndex) => {
+ const groupDiv = document.createElement('div');
+ groupDiv.className = 'caption-group';
+ groupDiv.id = `group-${groupIndex}`;
+
+ group.forEach((wordData, wordIdx) => {
+ const wordDiv = document.createElement('div');
+ wordDiv.className = 'word';
+ wordDiv.dataset.word = wordData.text;
+
+ // Split word into characters for typewriter/glitch reveal
+ wordData.text.split('').forEach(char => {
+ const charSpan = document.createElement('span');
+ charSpan.className = 'char';
+ charSpan.textContent = char;
+ wordDiv.appendChild(charSpan);
+ });
+
+ groupDiv.appendChild(wordDiv);
+ });
+
+ container.appendChild(groupDiv);
+
+ const groupStartTime = group[0].start;
+ const groupEndTime = group[group.length - 1].end;
+
+ // Group Entrance
+ tl.to(groupDiv, {
+ opacity: 1,
+ y: 0,
+ duration: 0.2,
+ ease: "power2.out"
+ }, groupStartTime);
+
+ // Word/Character Reveal
+ group.forEach((wordData, wordInGroupIndex) => {
+ const wordElement = groupDiv.querySelectorAll('.word')[wordInGroupIndex];
+ const chars = wordElement.querySelectorAll('.char');
+
+ const wordDuration = wordData.end - wordData.start;
+ const charStagger = wordDuration / (chars.length + 1);
+
+ chars.forEach((char, charIdx) => {
+ const charStartTime = wordData.start + (charIdx * charStagger);
+ const originalChar = char.textContent;
+ const glitchChars = "X01@#%&";
+
+ // Typewriter + Glitch Reveal
+ tl.to(char, {
+ opacity: 1,
+ x: (charIdx % 2 === 0 ? 4 : -4), // More aggressive horizontal shift
+ duration: 0.1, // Longer glitch state
+ onStart: () => {
+ char.style.color = '#FFFFFF';
+ char.style.backgroundColor = '#00FF80';
+ // Deterministic character cycling
+ char.textContent = glitchChars[charIdx % glitchChars.length];
+ }
+ }, charStartTime);
+
+ tl.to(char, {
+ backgroundColor: 'transparent',
+ color: '#FFFFFF',
+ x: 0,
+ duration: 0.1,
+ onStart: () => {
+ char.textContent = originalChar;
+ },
+ ease: "none"
+ }, charStartTime + 0.1);
+ });
+ });
+
+ // Group Exit
+ tl.to(groupDiv, {
+ opacity: 0,
+ duration: 0.2,
+ ease: "power2.in"
+ }, groupEndTime);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-13-prod/src/compositions/overlays.html b/packages/producer/tests/style-13-prod/src/compositions/overlays.html
new file mode 100644
index 0000000000..2fc54e35c0
--- /dev/null
+++ b/packages/producer/tests/style-13-prod/src/compositions/overlays.html
@@ -0,0 +1,344 @@
+<template id="overlays-template">
+ <div data-composition-id="overlays" data-width="1080" data-height="1920" data-duration="16">
+ <div id="stats-container">
+ <!-- Stat 1: 47% NEED MOTION GRAPHICS -->
+ <div id="stat-1" class="stat-box top-right">
+ <div class="number-row" id="num-1"></div>
+ <div class="label-container">
+ <div class="label-text" id="label-1">Need Motion Graphics</div>
+ <div class="scanline"></div>
+ </div>
+ </div>
+
+ <!-- Stat 2: 62% STATIC CONTENT REDUCES ENGAGEMENT -->
+ <div id="stat-2" class="stat-box top-left">
+ <div class="number-row" id="num-2"></div>
+ <div class="label-container">
+ <div class="label-text" id="label-2">Static content reduces engagement</div>
+ <div class="scanline"></div>
+ </div>
+ </div>
+
+ <!-- Stat 3: 75% LACK TECHNICAL SKILLS -->
+ <div id="stat-3" class="stat-box centered">
+ <div class="number-row large" id="num-3"></div>
+ <div class="label-container">
+ <div class="label-text large" id="label-3">LACK TECHNICAL SKILLS</div>
+ <div class="scanline"></div>
+ </div>
+ </div>
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=Archivo+Black&family=Space+Mono:wght@700&display=swap');
+
+ [data-composition-id="overlays"] {
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ color: white;
+ font-family: 'Space Mono', monospace;
+ overflow: hidden;
+ }
+
+ .stat-box {
+ position: absolute;
+ opacity: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 20px;
+ }
+
+ /* Positioning based on face zone avoidance (x:300-776, y:320-796) */
+ .top-right {
+ top: 100px;
+ right: 60px;
+ align-items: flex-end;
+ }
+
+ .top-left {
+ top: 100px;
+ left: 60px;
+ align-items: flex-start;
+ }
+
+ .centered {
+ top: 1400px; /* Moved lower to avoid overlap with centered captions */
+ left: 50%;
+ transform: translateX(-50%);
+ align-items: center;
+ width: 880px; /* 1080 - 200 (100px padding each side) */
+ }
+
+ .number-row {
+ display: flex;
+ gap: 10px;
+ }
+
+ .number-grid {
+ display: grid;
+ grid-template-columns: repeat(11, 15px);
+ grid-template-rows: repeat(15, 15px);
+ gap: 4px;
+ }
+
+ .number-row.large .number-grid {
+ grid-template-columns: repeat(11, 20px);
+ grid-template-rows: repeat(15, 20px);
+ gap: 6px;
+ }
+
+ .dot {
+ width: 100%;
+ height: 100%;
+ background-color: #00FF80; /* Brighter Green for better contrast */
+ border-radius: 2px;
+ opacity: 0;
+ }
+
+ .label-container {
+ position: relative;
+ overflow: hidden;
+ padding: 5px 10px;
+ }
+
+ .label-text {
+ color: #00FF80; /* Brighter Green */
+ font-family: 'Space Mono', monospace; /* Mono for supporting text */
+ font-size: 24px; /* Smaller */
+ font-weight: 400; /* Lighter */
+ letter-spacing: 1px;
+ opacity: 0;
+ text-transform: none; /* Stop using uppercase for everything */
+ text-shadow: 0 0 10px rgba(0, 0, 0, 0.8);
+ }
+
+ .label-text.large {
+ font-family: 'Archivo Black', sans-serif; /* Keep headers bold */
+ font-size: 48px;
+ font-weight: 900;
+ text-transform: uppercase;
+ text-align: center;
+ }
+
+ .scanline {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 4px;
+ background-color: #FF6600; /* Signal Orange for small UI detail */
+ box-shadow: 0 0 10px #FF6600;
+ transform: translateY(-100%);
+ pointer-events: none;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.14, 'end': 0.239}, {'text': 'asked', 'start': 0.28, 'end': 0.459}, {'text': 'what', 'start': 0.5, 'end': 0.619}, {'text': 'you', 'start': 0.659, 'end': 0.779}, {'text': 'needed.', 'start': 0.8, 'end': 1.179}, {'text': 'Forty-seven', 'start': 1.199, 'end': 1.619}, {'text': 'percent', 'start': 1.699, 'end': 1.96}, {'text': 'of', 'start': 1.979, 'end': 2.059}, {'text': 'you', 'start': 2.099, 'end': 2.299}, {'text': 'said', 'start': 2.319, 'end': 2.499}, {'text': 'motion', 'start': 2.559, 'end': 2.839}, {'text': 'graphics,', 'start': 2.899, 'end': 3.759}, {'text': 'sixty-two', 'start': 3.799, 'end': 4.159}, {'text': 'percent', 'start': 4.239, 'end': 4.559}, {'text': 'said', 'start': 4.639, 'end': 4.799}, {'text': 'static', 'start': 4.859, 'end': 5.199}, {'text': 'content', 'start': 5.239, 'end': 5.639}, {'text': 'was', 'start': 5.679, 'end': 5.779}, {'text': 'costing', 'start': 5.859, 'end': 6.219}, {'text': 'you', 'start': 6.259, 'end': 6.339}, {'text': 'attention,', 'start': 6.379, 'end': 7.299}, {'text': 'and', 'start': 7.319, 'end': 7.439}, {'text': 'three', 'start': 7.48, 'end': 7.599}, {'text': 'out', 'start': 7.679, 'end': 7.779}, {'text': 'of', 'start': 7.799, 'end': 7.879}, {'text': 'four', 'start': 7.94, 'end': 8.139}, {'text': 'said', 'start': 8.279, 'end': 8.46}, {'text': 'you', 'start': 8.519, 'end': 8.6}, {'text': 'know', 'start': 8.619, 'end': 8.739}, {'text': 'the', 'start': 8.8, 'end': 8.88}, {'text': 'look', 'start': 8.92, 'end': 9.079}, {'text': 'you', 'start': 9.119, 'end': 9.259}, {'text': 'want', 'start': 9.279, 'end': 9.619}, {'text': 'but', 'start': 9.779, 'end': 9.88}, {'text': "don't", 'start': 9.92, 'end': 10.1}, {'text': 'have', 'start': 10.159, 'end': 10.3}, {'text': 'the', 'start': 10.3, 'end': 10.42}, {'text': 'editing', 'start': 10.5, 'end': 10.779}, {'text': 'skills', 'start': 10.86, 'end': 11.139}, {'text': 'to', 'start': 11.159, 'end': 11.239}, {'text': 'get', 'start': 11.279, 'end': 11.439}, {'text': 'there.', 'start': 11.46, 'end': 12.239}, {'text': 'So', 'start': 12.3, 'end': 12.38}, {'text': 'we', 'start': 12.399, 'end': 12.519}, {'text': 'built', 'start': 12.539, 'end': 12.759}, {'text': 'Editor', 'start': 12.84, 'end': 13.119}, {'text': 'Agent.', 'start': 13.239, 'end': 13.84}];
+ const tl = gsap.timeline({ paused: true });
+
+ // Wim Crouwel inspired grid definitions (11x15 grid)
+ const GRIDS = {
+ '4': [
+ 0,0,0,0,0,0,0,1,1,0,0,
+ 0,0,0,0,0,0,1,1,1,0,0,
+ 0,0,0,0,0,1,1,1,1,0,0,
+ 0,0,0,0,1,1,0,1,1,0,0,
+ 0,0,0,1,1,0,0,1,1,0,0,
+ 0,0,1,1,0,0,0,1,1,0,0,
+ 0,1,1,0,0,0,0,1,1,0,0,
+ 1,1,1,1,1,1,1,1,1,1,1,
+ 1,1,1,1,1,1,1,1,1,1,1,
+ 0,0,0,0,0,0,0,1,1,0,0,
+ 0,0,0,0,0,0,0,1,1,0,0,
+ 0,0,0,0,0,0,0,1,1,0,0,
+ 0,0,0,0,0,0,0,1,1,0,0,
+ 0,0,0,0,0,0,0,1,1,0,0,
+ 0,0,0,0,0,0,0,1,1,0,0
+ ],
+ '7': [
+ 1,1,1,1,1,1,1,1,1,1,1,
+ 1,1,1,1,1,1,1,1,1,1,1,
+ 0,0,0,0,0,0,0,0,1,1,0,
+ 0,0,0,0,0,0,0,1,1,0,0,
+ 0,0,0,0,0,0,1,1,0,0,0,
+ 0,0,0,0,0,1,1,0,0,0,0,
+ 0,0,0,0,1,1,0,0,0,0,0,
+ 0,0,0,1,1,0,0,0,0,0,0,
+ 0,0,1,1,0,0,0,0,0,0,0,
+ 0,1,1,0,0,0,0,0,0,0,0,
+ 1,1,0,0,0,0,0,0,0,0,0,
+ 1,1,0,0,0,0,0,0,0,0,0,
+ 1,1,0,0,0,0,0,0,0,0,0,
+ 1,1,0,0,0,0,0,0,0,0,0,
+ 1,1,0,0,0,0,0,0,0,0,0
+ ],
+ '6': [
+ 0,0,0,1,1,1,1,1,0,0,0,
+ 0,0,1,1,1,1,1,1,1,0,0,
+ 0,1,1,0,0,0,0,0,1,1,0,
+ 1,1,0,0,0,0,0,0,0,0,0,
+ 1,1,0,0,1,1,1,1,0,0,0,
+ 1,1,1,1,1,1,1,1,1,0,0,
+ 1,1,1,0,0,0,0,0,1,1,0,
+ 1,1,0,0,0,0,0,0,1,1,0,
+ 1,1,0,0,0,0,0,0,1,1,0,
+ 1,1,0,0,0,0,0,0,1,1,0,
+ 1,1,0,0,0,0,0,0,1,1,0,
+ 0,1,1,0,0,0,0,0,1,1,0,
+ 0,0,1,1,1,1,1,1,1,0,0,
+ 0,0,0,1,1,1,1,1,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0
+ ],
+ '2': [
+ 0,0,1,1,1,1,1,1,1,0,0,
+ 0,1,1,1,1,1,1,1,1,1,0,
+ 1,1,0,0,0,0,0,0,1,1,0,
+ 0,0,0,0,0,0,0,0,1,1,0,
+ 0,0,0,0,0,0,0,1,1,0,0,
+ 0,0,0,0,0,0,1,1,0,0,0,
+ 0,0,0,0,0,1,1,0,0,0,0,
+ 0,0,0,0,1,1,0,0,0,0,0,
+ 0,0,0,1,1,0,0,0,0,0,0,
+ 0,0,1,1,0,0,0,0,0,0,0,
+ 0,1,1,0,0,0,0,0,0,0,0,
+ 1,1,0,0,0,0,0,0,0,0,0,
+ 1,1,1,1,1,1,1,1,1,1,1,
+ 1,1,1,1,1,1,1,1,1,1,1,
+ 0,0,0,0,0,0,0,0,0,0,0
+ ],
+ '5': [
+ 1,1,1,1,1,1,1,1,1,1,1,
+ 1,1,1,1,1,1,1,1,1,1,1,
+ 1,1,0,0,0,0,0,0,0,0,0,
+ 1,1,0,0,0,0,0,0,0,0,0,
+ 1,1,1,1,1,1,1,1,0,0,0,
+ 1,1,1,1,1,1,1,1,1,0,0,
+ 0,0,0,0,0,0,0,0,1,1,0,
+ 0,0,0,0,0,0,0,0,1,1,0,
+ 0,0,0,0,0,0,0,0,1,1,0,
+ 0,0,0,0,0,0,0,0,1,1,0,
+ 1,1,0,0,0,0,0,0,1,1,0,
+ 1,1,0,0,0,0,0,1,1,1,0,
+ 0,1,1,1,1,1,1,1,1,0,0,
+ 0,0,1,1,1,1,1,1,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0
+ ],
+ '%': [
+ 1,1,0,0,0,0,0,0,1,1,0,
+ 1,1,0,0,0,0,0,1,1,0,0,
+ 0,0,0,0,0,0,1,1,0,0,0,
+ 0,0,0,0,0,1,1,0,0,0,0,
+ 0,0,0,0,1,1,0,0,0,0,0,
+ 0,0,0,1,1,0,0,0,0,0,0,
+ 0,0,1,1,0,0,0,0,0,0,0,
+ 0,1,1,0,0,0,0,0,0,0,0,
+ 1,1,0,0,0,0,0,0,1,1,0,
+ 0,0,0,0,0,0,0,1,1,1,1,
+ 0,0,0,0,0,0,0,1,1,1,1,
+ 0,0,0,0,0,0,0,1,1,1,1,
+ 0,0,0,0,0,0,0,1,1,1,1,
+ 0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0
+ ]
+ };
+
+ function createNumber(containerId, digits) {
+ const container = document.getElementById(containerId);
+ digits.split('').forEach((digit, dIdx) => {
+ const grid = document.createElement('div');
+ grid.className = 'number-grid';
+
+ const pattern = GRIDS[digit] || GRIDS['%'];
+ pattern.forEach((val, i) => {
+ const dot = document.createElement('div');
+ dot.className = 'dot dot-' + containerId + '-' + dIdx + '-' + i;
+ if (val === 1) {
+ dot.style.opacity = '0';
+ } else {
+ dot.style.visibility = 'hidden';
+ }
+ grid.appendChild(dot);
+ });
+ container.appendChild(grid);
+ });
+ }
+
+ createNumber('num-1', '47%');
+ createNumber('num-2', '62%');
+ createNumber('num-3', '75%');
+
+ function animateStat(id, start, end) {
+ const stat = document.querySelector('#' + id);
+ const label = stat.querySelector('.label-text');
+ const scanline = stat.querySelector('.scanline');
+ const dots = stat.querySelectorAll('.dot');
+
+ // Entrance
+ tl.to(stat, { opacity: 1, duration: 0.1 }, start);
+
+ // Number assembly (dots)
+ // Using a deterministic stagger pattern
+ tl.to(dots, {
+ opacity: 1,
+ duration: 0.6,
+ stagger: {
+ each: 0.003,
+ from: "start",
+ grid: [15, 11]
+ },
+ ease: "expo.out"
+ }, start);
+
+ // Scanline sweep for text
+ tl.fromTo(scanline,
+ { translateY: "-100%" },
+ { translateY: "100%", duration: 0.8, ease: "none" },
+ start + 0.3
+ );
+ tl.to(label, { opacity: 1, duration: 0.1 }, start + 0.3);
+ tl.fromTo(label,
+ { clipPath: "inset(0 0 100% 0)" },
+ { clipPath: "inset(0 0 0% 0)", duration: 0.8, ease: "none" },
+ start + 0.3
+ );
+
+ // Exit
+ tl.to(stat, { opacity: 0, duration: 0.3, ease: "power2.in" }, end - 0.3);
+ }
+
+ // Sync with transcript timings
+ // 1. "47% NEED MOTION GRAPHICS" (1.199s to 3.759s)
+ animateStat('stat-1', 1.199, 3.759);
+
+ // 2. "62% STATIC CONTENT REDUCES ENGAGEMENT" (3.799s to 7.299s)
+ animateStat('stat-2', 3.799, 7.299);
+
+ // 3. "75% LACK TECHNICAL SKILLS" (7.48s to 12.239s)
+ animateStat('stat-3', 7.48, 12.239);
+
+ // Ambient motion: subtle grid pulse
+ // Deterministic loop for exact duration (13.88s)
+ const pulseDuration = 2;
+ const totalDuration = 16;
+ for (let t = 0; t < totalDuration; t += pulseDuration * 2) {
+ tl.to('.dot', {
+ scale: 1.1,
+ duration: pulseDuration,
+ yoyo: true,
+ repeat: 1,
+ ease: "sine.inOut",
+ stagger: {
+ each: 0.01,
+ from: "center"
+ }
+ }, t);
+ }
+
+ window.__timelines["overlays"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-13-prod/src/compositions/transitions.html b/packages/producer/tests/style-13-prod/src/compositions/transitions.html
new file mode 100644
index 0000000000..03c55e71f1
--- /dev/null
+++ b/packages/producer/tests/style-13-prod/src/compositions/transitions.html
@@ -0,0 +1,107 @@
+<template id="transitions-template">
+ <div data-composition-id="transitions" data-width="1080" data-height="1920" data-duration="16">
+ <div class="scanline-container">
+ <div class="scanline" id="scanline-1">
+ <div class="grid-pattern"></div>
+ <div class="accent-line"></div>
+ </div>
+ <div class="scanline" id="scanline-2">
+ <div class="grid-pattern"></div>
+ <div class="accent-line"></div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="transitions"] {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ pointer-events: none;
+ overflow: hidden;
+ }
+
+ [data-composition-id="transitions"] .scanline-container {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ }
+
+ [data-composition-id="transitions"] .scanline {
+ position: absolute;
+ left: 0;
+ width: 100%;
+ height: 320px; /* Slightly taller for more presence */
+ background-color: rgba(18, 18, 18, 0.95); /* Dark Charcoal - more sophisticated */
+ opacity: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ box-shadow: 0 0 100px rgba(0, 0, 0, 0.9);
+ z-index: 100;
+ border-left: 0;
+ border-right: 0;
+ }
+
+ /* Subtle dark charcoal grid pattern */
+ [data-composition-id="transitions"] .grid-pattern {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-image:
+ linear-gradient(to right, rgba(18, 18, 18, 0.3) 1px, transparent 1px),
+ linear-gradient(to bottom, rgba(18, 18, 18, 0.3) 1px, transparent 1px);
+ background-size: 40px 40px;
+ }
+
+ /* Orange accent line - sophisticated highlight */
+ [data-composition-id="transitions"] .accent-line {
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ width: 100%;
+ height: 2px; /* More subtle accent */
+ background-color: #FF6600; /* Signal Orange */
+ box-shadow: 0 0 10px rgba(255, 102, 0, 0.4);
+ }
+
+ /* Reverse direction accent for upward sweep */
+ [data-composition-id="transitions"] #scanline-2 .accent-line {
+ top: 0;
+ bottom: auto;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // Sweep 1: At 7.3s (when A-roll exits)
+ // Top to Bottom
+ tl.set("#scanline-1", { y: -320, opacity: 1 }, 7.0);
+ tl.to("#scanline-1", {
+ y: 1920,
+ duration: 0.9,
+ ease: "power3.inOut"
+ }, 7.0);
+ tl.set("#scanline-1", { opacity: 0 }, 7.9);
+
+ // Sweep 2: At 12.3s (when A-roll returns)
+ // Bottom to Top
+ tl.set("#scanline-2", { y: 1920, opacity: 1 }, 12.0);
+ tl.to("#scanline-2", {
+ y: -320,
+ duration: 0.9,
+ ease: "power3.inOut"
+ }, 12.0);
+ tl.set("#scanline-2", { opacity: 0 }, 12.9);
+
+ window.__timelines["transitions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-13-prod/src/design_review.md b/packages/producer/tests/style-13-prod/src/design_review.md
new file mode 100644
index 0000000000..2687b8bb64
--- /dev/null
+++ b/packages/producer/tests/style-13-prod/src/design_review.md
@@ -0,0 +1,61 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a "hacker aesthetic" template from a 2014 YouTube tutorial. It’s trying so hard to be "techy" with its scanlines and dot grids that it forgets to actually be legible or modern.
+
+---
+
+## CRITICAL Design Failures
+
+Issues that make this look unprofessional or straight-up ugly. These MUST be fixed.
+
+### The "Everything is a Scanline" Obsession
+**Where:** `compositions/background.html`, `compositions/transitions.html`, `compositions/overlays.html`
+**What's wrong:** You have three different types of scanlines/grids fighting for dominance. The background has a scanline, the transitions are giant scanline blocks, and the overlays have mini scanlines. It’s visual clutter that serves no purpose other than to scream "I just learned CSS gradients."
+**Why it matters:** It creates a vibrating, noisy mess that distracts from the actual content. It feels dated and amateur.
+**Fix it:** Pick ONE subtle scanline effect for the background and kill the rest. Use clean, solid shapes for UI elements.
+
+### Typography Identity Crisis
+**Where:** `compositions/overlays.html`
+**What's wrong:** You're mixing 'Space Mono' (thin/techy) with 'Archivo Black' (heavy/brutal) in the same overlay (`#stat-3`). The contrast isn't intentional; it's jarring. Furthermore, the captions use 'Space Mono' at 54px with a 15px gap—it's going to look like a wall of unreadable code.
+**Why it matters:** Good design requires a clear typographic hierarchy. This feels like a random font-picker result.
+**Fix it:** Commit to one aesthetic. If you want Wim Crouwel, stick to a strict grid and a single, highly structured typeface. Lose the 'Archivo Black' or use it exclusively for headers.
+
+### The "Face Zone" Collision
+**Where:** `index.html`, `compositions/captions.html`
+**What's wrong:** You've centered the captions vertically (`align-items: center` in `[data-composition-id="captions"]`). In a 9:16 portrait video, the subject's face is almost always in the upper-middle third. You are literally slapping text over the speaker's mouth.
+**Why it matters:** It’s the #1 amateur mistake in video editing. You never cover the face.
+**Fix it:** Move the captions to the lower third (around `bottom: 20%`).
+
+---
+
+## Design Improvements
+
+Things that aren't broken but are boring, lazy, or could be significantly better.
+
+### Robotic Motion
+**Where:** `index.html` (A-roll exit)
+**The problem:** The A-roll video exits at 7.3s with a simple `x: -1080`. It’s a flat, linear-feeling slide that lacks any cinematic weight.
+**Make it better:** Add a slight `z` depth (scale down more) and a more aggressive `expo.in` ease. If it's leaving the screen, it should feel like it's being pulled away, not just sliding on a rail.
+
+### Color Overload
+**Where:** `compositions/transitions.html` (Orange) vs `compositions/captions.html` (Green)
+**The problem:** You have "Signal Orange" (#FF6600) and "Spring Green" (#00FF80) competing. It looks like a construction site.
+**Make it better:** Choose a primary accent and a secondary. If Green is your "action" color for captions, use a muted version of the Orange or a neutral gray for the UI "scanlines."
+
+---
+
+## What Actually Works
+
+The **Wim Crouwel inspired dot-matrix numbers** in `compositions/overlays.html` are actually sophisticated. The custom grid definitions for '47%', '62%', etc., show a level of craft that the rest of the project lacks. It’s a high-concept detail that deserves a better environment than this "scanline-heavy" graveyard.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 4/10 - It’s loud, but for all the wrong reasons.
+**Color & Typography:** 3/10 - A clashing mess of "tech" tropes and mismatched weights.
+**Motion & Animation Feel:** 5/10 - The GSAP logic is sound, but the easing is generic.
+**Overall Aesthetic:** 4/10 - Feels like a 2010s "Cyber" template rather than a 2026 "Editor Agent."
+
+**Bottom Line:** Stop hiding behind scanlines and "glitch" effects. Clean up the layout, respect the subject's face, and let those dot-matrix numbers be the star of the show. Right now, it's a mess.
diff --git a/packages/producer/tests/style-13-prod/src/index.html b/packages/producer/tests/style-13-prod/src/index.html
new file mode 100644
index 0000000000..bce8cde4f0
--- /dev/null
+++ b/packages/producer/tests/style-13-prod/src/index.html
@@ -0,0 +1,106 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Editor Agent - Wim Crouwel Style</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1080px;
+ height: 1920px;
+ background-color: #1A1A1A;
+ overflow: hidden;
+ font-family: monospace; /* Fallback for grid style */
+ }
+ #main-canvas {
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ }
+ #aroll-video {
+ width: 1080px;
+ height: 1920px;
+ object-fit: cover;
+ position: absolute;
+ top: 0;
+ left: 0;
+ }
+ </style>
+</head>
+<body>
+ <div id="main-canvas" data-composition-id="main-video" data-width="1080" data-height="1920" data-duration="16">
+
+ <!-- Background Layer -->
+ <div id="bg-comp"
+ data-composition-id="background"
+ data-composition-src="compositions/background.html"
+ data-start="0"
+ data-duration="16"
+ data-track-index="0">
+ </div>
+
+ <!-- A-Roll Video -->
+ <video id="aroll-video"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/f82d6e98_9076b56b449e44ac95a2099375863f91.mp4"
+ data-start="0"
+ data-duration="16"
+ data-track-index="1">
+ </video>
+
+ <!-- Overlays Layer (Stats/Graphics) -->
+ <div id="overlays-comp"
+ data-composition-id="overlays"
+ data-composition-src="compositions/overlays.html"
+ data-start="0"
+ data-duration="16"
+ data-track-index="2">
+ </div>
+
+ <!-- Captions Layer -->
+ <div id="captions-comp"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="16"
+ data-track-index="3">
+ </div>
+
+ <!-- Transitions Layer (Scanlines) -->
+ <div id="transitions-comp"
+ data-composition-id="transitions"
+ data-composition-src="compositions/transitions.html"
+ data-start="0"
+ data-duration="16"
+ data-track-index="4">
+ </div>
+
+ </div>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+
+ // A-roll exit and return logic
+ // Leave at 7.3s (after "attention") and return at 12.3s (before "So we built")
+ tl.to("#aroll-video", {
+ x: -1080,
+ scale: 0.9,
+ rotation: -5,
+ duration: 0.6,
+ ease: "expo.inOut"
+ }, 7.3);
+
+ tl.to("#aroll-video", {
+ x: 0,
+ scale: 1,
+ rotation: 0,
+ duration: 0.6,
+ ease: "back.out(1.2)" /* Slight overshoot for more "soul" */
+ }, 12.3);
+
+ window.__timelines["main-video"] = tl;
+ </script>
+</body>
+</html>
diff --git a/packages/producer/tests/style-15-prod/meta.json b/packages/producer/tests/style-15-prod/meta.json
new file mode 100644
index 0000000000..908e2103d2
--- /dev/null
+++ b/packages/producer/tests/style-15-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-15-prod",
+ "description": "Regression fixture imported from normalized style pack style-15-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "portrait"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-15-prod/src/code_review.md b/packages/producer/tests/style-15-prod/src/code_review.md
new file mode 100644
index 0000000000..0c857844d9
--- /dev/null
+++ b/packages/producer/tests/style-15-prod/src/code_review.md
@@ -0,0 +1,62 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 6
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None found.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (no circular refs, referenced clips have known duration)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+### index.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None.
+
+### compositions/background.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None.
+
+### compositions/captions.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None.
+
+### compositions/aroll.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None.
+
+### compositions/mograph_overlays.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None.
+
+### compositions/hero_moment.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None.
diff --git a/packages/producer/tests/style-15-prod/src/compositions/aroll.html b/packages/producer/tests/style-15-prod/src/compositions/aroll.html
new file mode 100644
index 0000000000..3e3ee3d1cb
--- /dev/null
+++ b/packages/producer/tests/style-15-prod/src/compositions/aroll.html
@@ -0,0 +1,188 @@
+<template id="aroll-template">
+ <div data-composition-id="aroll" data-width="1080" data-height="1920" data-duration="14">
+ <!-- Grid Background -->
+ <div class="grid-container">
+ <div class="grid-line horizontal" style="top: 20%;"></div>
+ <div class="grid-line horizontal" style="top: 40%;"></div>
+ <div class="grid-line horizontal" style="top: 60%;"></div>
+ <div class="grid-line horizontal" style="top: 80%;"></div>
+ <div class="grid-line vertical" style="left: 20%;"></div>
+ <div class="grid-line vertical" style="left: 40%;"></div>
+ <div class="grid-line vertical" style="left: 60%;"></div>
+ <div class="grid-line vertical" style="left: 80%;"></div>
+ </div>
+
+ <!-- Video Container -->
+ <div class="video-frame">
+ <div class="video-mask">
+ <video
+ id="aroll-video"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/c10d5d5c_5e0cbe68f361481f8d2c77b028e84504.mp4"
+ data-start="0"
+ data-duration="14"
+ data-track-index="0"
+ crossorigin="anonymous"
+ ></video>
+ </div>
+ <!-- Diagonal Rule Lines for Wipe Effect -->
+ <div class="wipe-line wipe-line-1"></div>
+ <div class="wipe-line wipe-line-2"></div>
+ </div>
+
+ <style>
+ [data-composition-id="aroll"] {
+ background: transparent;
+ font-family: sans-serif;
+ overflow: hidden;
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ }
+
+ /* Grid Styling */
+ [data-composition-id="aroll"] .grid-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ opacity: 0.2;
+ pointer-events: none;
+ }
+
+ [data-composition-id="aroll"] .grid-line {
+ position: absolute;
+ background: #444;
+ }
+
+ [data-composition-id="aroll"] .grid-line.horizontal {
+ width: 100%;
+ height: 1px;
+ }
+
+ [data-composition-id="aroll"] .grid-line.vertical {
+ width: 1px;
+ height: 100%;
+ }
+
+ /* Video Frame Styling */
+ [data-composition-id="aroll"] .video-frame {
+ position: absolute;
+ /* Full width and height for impact, no padding */
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: #111;
+ overflow: hidden;
+ border: none;
+ transform: translate(0, 0) scale(1);
+ z-index: 10;
+ }
+
+ [data-composition-id="aroll"] .video-mask {
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ position: relative;
+ }
+
+ [data-composition-id="aroll"] video {
+ width: 100%;
+ height: 100%;
+ object-fit: cover; /* Crop portrait video into the frame */
+ display: block;
+ }
+
+ /* Wipe Lines */
+ [data-composition-id="aroll"] .wipe-line {
+ position: absolute;
+ background: #fff;
+ z-index: 10;
+ pointer-events: none;
+ width: 200%;
+ height: 4px;
+ left: -50%;
+ opacity: 0;
+ }
+
+ [data-composition-id="aroll"] .wipe-line-1 {
+ top: 0;
+ transform: rotate(45deg) translateY(-500px);
+ }
+
+ [data-composition-id="aroll"] .wipe-line-2 {
+ bottom: 0;
+ transform: rotate(45deg) translateY(500px);
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const frame = document.querySelector('[data-composition-id="aroll"] .video-frame');
+ const wipe1 = document.querySelector('[data-composition-id="aroll"] .wipe-line-1');
+ const wipe2 = document.querySelector('[data-composition-id="aroll"] .wipe-line-2');
+
+ // 1. Entrance & Scale Down (0s - 1.5s)
+ // Starts full screen and scales down slightly to establish the grid
+ tl.fromTo(frame, {
+ scale: 1.1,
+ opacity: 0
+ }, {
+ scale: 1.0, /* Fixed scale to fill frame better */
+ opacity: 1,
+ duration: 1.5,
+ ease: 'power4.out'
+ }, 0);
+
+ tl.fromTo(wipe1,
+ { opacity: 1, y: -500 },
+ { y: 1500, duration: 1.5, ease: 'power2.inOut' },
+ 0
+ );
+ tl.fromTo(wipe2,
+ { opacity: 1, y: 500 },
+ { y: -1500, duration: 1.5, ease: 'power2.inOut' },
+ 0.1
+ );
+ tl.to([wipe1, wipe2], { opacity: 0, duration: 0.3 }, 1.5);
+
+ // 2. Ambient Motion (1.5s - 7.319s)
+ tl.to(frame, {
+ y: '+=15',
+ duration: 3,
+ ease: 'sine.inOut',
+ repeat: 1,
+ yoyo: true
+ }, 1.5);
+
+ // 3. Hero Moment Exit (7.319s - 8.319s)
+ tl.to(frame, {
+ scale: 0,
+ opacity: 0,
+ duration: 0.8,
+ ease: 'power3.in'
+ }, 7.319);
+
+ // 4. Hero Moment Return (12.239s - 13.739s)
+ tl.to(frame, {
+ scale: 1.0, /* Fixed return scale */
+ opacity: 1,
+ duration: 1.2,
+ ease: 'back.out(1.2)'
+ }, 12.239);
+
+ // 5. Final Exit (13.8s - 14s)
+ tl.to(frame, {
+ opacity: 0,
+ scale: 0.6,
+ duration: 0.5,
+ ease: 'power2.in'
+ }, 13.5);
+
+ window.__timelines["aroll"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-15-prod/src/compositions/background.html b/packages/producer/tests/style-15-prod/src/compositions/background.html
new file mode 100644
index 0000000000..86730609b1
--- /dev/null
+++ b/packages/producer/tests/style-15-prod/src/compositions/background.html
@@ -0,0 +1,144 @@
+<template id="background-template">
+ <div data-composition-id="background" data-width="1080" data-height="1920" data-duration="14">
+ <div class="paper-texture"></div>
+
+ <!-- Grid Lines Container -->
+ <div class="grid-container">
+ <!-- Horizontal Lines -->
+ <div class="line horizontal h1" style="top: 15%; height: 2px;"></div>
+ <div class="line horizontal h2" style="top: 45%; height: 6px;"></div>
+ <div class="line horizontal h3" style="top: 85%; height: 1px;"></div>
+
+ <!-- Vertical Lines -->
+ <div class="line vertical v1" style="left: 20%; width: 4px;"></div>
+ <div class="line vertical v2" style="left: 65%; width: 2px;"></div>
+ <div class="line vertical v3" style="left: 80%; width: 8px;"></div>
+ </div>
+
+ <!-- Bauhaus Red Circle -->
+ <div class="circle-element"></div>
+
+ <style>
+ [data-composition-id="background"] {
+ width: 1080px;
+ height: 1920px;
+ background-color: transparent;
+ position: relative;
+ overflow: hidden;
+ font-family: 'Helvetica', 'Arial', sans-serif;
+ }
+
+ /* Subtle Paper Texture */
+ [data-composition-id="background"] .paper-texture {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ opacity: 0.1; /* Increased for tactile feel */
+ pointer-events: none;
+ background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E");
+ }
+
+ [data-composition-id="background"] .grid-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ }
+
+ [data-composition-id="background"] .line {
+ position: absolute;
+ background-color: #000000;
+ }
+
+ [data-composition-id="background"] .horizontal {
+ width: 100%;
+ left: 0;
+ transform: scaleX(0);
+ transform-origin: left center;
+ }
+
+ [data-composition-id="background"] .vertical {
+ height: 100%;
+ top: 0;
+ transform: scaleY(0);
+ transform-origin: center top;
+ }
+
+ [data-composition-id="background"] .circle-element {
+ position: absolute;
+ width: 400px;
+ height: 400px;
+ background-color: #BE1E2D;
+ border-radius: 50%;
+ top: 25%;
+ left: 60%;
+ transform: scale(0);
+ z-index: 10;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // 1. Grid Lines Animation (0s - 1s)
+ // Staggered entrance for horizontal lines
+ tl.to('[data-composition-id="background"] .horizontal', {
+ scaleX: 1,
+ duration: 0.8,
+ stagger: 0.15,
+ ease: "power4.inOut"
+ }, 0);
+
+ // Staggered entrance for vertical lines
+ tl.to('[data-composition-id="background"] .vertical', {
+ scaleY: 1,
+ duration: 0.8,
+ stagger: 0.1,
+ ease: "power4.inOut"
+ }, 0.2);
+
+ // 2. Circular Element Animation (0.5s - 1.2s)
+ tl.to('[data-composition-id="background"] .circle-element', {
+ scale: 1,
+ duration: 0.7,
+ ease: "circ.out"
+ }, 0.5);
+
+ // 3. Ambient Motion (1s - 14s)
+ // Subtle drift for the circle
+ tl.to('[data-composition-id="background"] .circle-element', {
+ x: -30,
+ y: 20,
+ duration: 6.5,
+ yoyo: true,
+ repeat: 1,
+ ease: "sine.inOut"
+ }, 1);
+
+ // Subtle weight shift for lines (simulating paper expansion/contraction or focus shift)
+ tl.to('[data-composition-id="background"] .h2', {
+ height: "8px",
+ duration: 6,
+ yoyo: true,
+ repeat: 1,
+ ease: "sine.inOut"
+ }, 1);
+
+ tl.to('[data-composition-id="background"] .v3', {
+ width: "12px",
+ duration: 5,
+ yoyo: true,
+ repeat: 1,
+ ease: "sine.inOut"
+ }, 3);
+
+ // Register the timeline
+ window.__timelines["background"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-15-prod/src/compositions/captions.html b/packages/producer/tests/style-15-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..ce732f5d68
--- /dev/null
+++ b/packages/producer/tests/style-15-prod/src/compositions/captions.html
@@ -0,0 +1,187 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1080" data-height="1920" data-duration="14">
+ <div class="captions-container">
+ <!-- Groups will be injected here -->
+ </div>
+
+ <style>
+ [data-composition-id="captions"] {
+ background: transparent;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; /* Akzidenz-Grotesk/Futura vibe */
+ color: #000000;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ }
+
+ [data-composition-id="captions"] .captions-container {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: flex-end; /* Align to bottom */
+ padding-bottom: 30%; /* Position 30% from bottom of screen */
+ }
+
+ [data-composition-id="captions"] .caption-group {
+ position: absolute;
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ align-items: center;
+ width: 85%; /* Slightly narrower to force wrapping */
+ height: 250px; /* Reduced height to strictly enforce 2 lines */
+ overflow: hidden; /* Enforce at most 2 lines */
+ opacity: 0;
+ visibility: hidden;
+ text-transform: uppercase; /* Tschichold often used uppercase for impact */
+ letter-spacing: -0.02em;
+ line-height: 1.1; /* Increased line height for breathing room */
+ text-align: center;
+ }
+
+ [data-composition-id="captions"] .word {
+ display: inline-block;
+ margin: 5px 15px; /* Added vertical margin */
+ font-size: 80px; /* Supporting words standardized */
+ font-weight: 300; /* Lighter weight for supporting words */
+ white-space: nowrap;
+ letter-spacing: -0.04em;
+ }
+
+ /* Extreme scale and weight for keywords */
+ [data-composition-id="captions"] .word.bold {
+ font-size: 120px; /* Reduced scale variance for better fit */
+ font-weight: 900;
+ color: #BE1E2D; /* Bauhaus Red for emphasis */
+ }
+
+ /* Extreme weight for emphasis on keywords */
+ [data-composition-id="captions"] .word.bold {
+ font-weight: 900;
+ }
+
+ /* Grid rail lines (decorative Tschichold elements) */
+ [data-composition-id="captions"] .rail {
+ position: absolute;
+ background: #000000;
+ opacity: 0.05;
+ pointer-events: none;
+ }
+
+ [data-composition-id="captions"] .rail-h {
+ width: 100%;
+ height: 2px;
+ left: 0;
+ }
+
+ [data-composition-id="captions"] .rail-v {
+ width: 2px;
+ height: 100%;
+ top: 0;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.14, 'end': 0.239}, {'text': 'asked', 'start': 0.28, 'end': 0.459}, {'text': 'what', 'start': 0.5, 'end': 0.619}, {'text': 'you', 'start': 0.659, 'end': 0.779}, {'text': 'needed.', 'start': 0.8, 'end': 1.179}, {'text': 'Forty-seven', 'start': 1.199, 'end': 1.619}, {'text': 'percent', 'start': 1.699, 'end': 1.96}, {'text': 'of', 'start': 1.979, 'end': 2.059}, {'text': 'you', 'start': 2.099, 'end': 2.299}, {'text': 'said', 'start': 2.319, 'end': 2.499}, {'text': 'motion', 'start': 2.559, 'end': 2.839}, {'text': 'graphics,', 'start': 2.899, 'end': 3.759}, {'text': 'sixty-two', 'start': 3.799, 'end': 4.159}, {'text': 'percent', 'start': 4.239, 'end': 4.559}, {'text': 'said', 'start': 4.639, 'end': 4.799}, {'text': 'static', 'start': 4.859, 'end': 5.199}, {'text': 'content', 'start': 5.239, 'end': 5.639}, {'text': 'was', 'start': 5.679, 'end': 5.779}, {'text': 'costing', 'start': 5.859, 'end': 6.219}, {'text': 'you', 'start': 6.259, 'end': 6.339}, {'text': 'attention,', 'start': 6.379, 'end': 7.299}, {'text': 'and', 'start': 7.319, 'end': 7.439}, {'text': 'three', 'start': 7.48, 'end': 7.599}, {'text': 'out', 'start': 7.679, 'end': 7.779}, {'text': 'of', 'start': 7.799, 'end': 7.879}, {'text': 'four', 'start': 7.94, 'end': 8.139}, {'text': 'said', 'start': 8.279, 'end': 8.46}, {'text': 'you', 'start': 8.519, 'end': 8.6}, {'text': 'know', 'start': 8.619, 'end': 8.739}, {'text': 'the', 'start': 8.8, 'end': 8.88}, {'text': 'look', 'start': 8.92, 'end': 9.079}, {'text': 'you', 'start': 9.119, 'end': 9.259}, {'text': 'want', 'start': 9.279, 'end': 9.619}, {'text': 'but', 'start': 9.779, 'end': 9.88}, {'text': "don't", 'start': 9.92, 'end': 10.1}, {'text': 'have', 'start': 10.159, 'end': 10.3}, {'text': 'the', 'start': 10.3, 'end': 10.42}, {'text': 'editing', 'start': 10.5, 'end': 10.779}, {'text': 'skills', 'start': 10.86, 'end': 11.139}, {'text': 'to', 'start': 11.159, 'end': 11.239}, {'text': 'get', 'start': 11.279, 'end': 11.439}, {'text': 'there.', 'start': 11.46, 'end': 12.239}, {'text': 'So', 'start': 12.3, 'end': 12.38}, {'text': 'we', 'start': 12.399, 'end': 12.519}, {'text': 'built', 'start': 12.539, 'end': 12.759}, {'text': 'Editor', 'start': 12.84, 'end': 13.119}, {'text': 'Agent.', 'start': 13.239, 'end': 13.84}];
+ const groups = [
+ { text: "We asked what you needed.", start: 0.14, end: 1.179 },
+ { text: "Forty-seven percent of you said motion graphics,", start: 1.199, end: 3.759 },
+ { text: "sixty-two percent said static content was costing you attention,", start: 3.799, end: 7.299 },
+ { text: "and three out of four said you know the look you want", start: 7.319, end: 9.619 },
+ { text: "but don't have the editing skills to get there.", start: 9.779, end: 12.239 },
+ { text: "So we built Editor Agent.", start: 12.3, end: 13.84 }
+ ];
+
+ const container = document.querySelector('[data-composition-id="captions"] .captions-container');
+ const tl = gsap.timeline({ paused: true });
+
+ // Add background "rails" for Tschichold aesthetic - reduced to 2-3 strategic lines
+ const railPositions = [
+ { type: 'h', pos: '30%' },
+ { type: 'h', pos: '70%' },
+ { type: 'v', pos: '25%' }
+ ];
+
+ railPositions.forEach(rail => {
+ const el = document.createElement('div');
+ el.className = `rail rail-${rail.type}`;
+ if (rail.type === 'h') {
+ el.style.top = rail.pos;
+ } else {
+ el.style.left = rail.pos;
+ }
+ container.appendChild(el);
+ });
+
+ const keywords = ["asked", "needed", "forty-seven", "percent", "motion", "graphics", "sixty-two", "static", "content", "attention", "three", "four", "editing", "skills", "editor", "agent"];
+
+ groups.forEach((group, index) => {
+ const groupEl = document.createElement('div');
+ groupEl.className = 'caption-group';
+ groupEl.id = 'group-' + index;
+
+ const words = group.text.split(' ');
+ words.forEach(wordText => {
+ const span = document.createElement('span');
+ span.className = 'word';
+ const cleanWord = wordText.toLowerCase().replace(/[^\w]/g, '');
+ if (keywords.includes(cleanWord)) {
+ span.classList.add('bold');
+ }
+ span.textContent = wordText;
+ groupEl.appendChild(span);
+ });
+
+ container.appendChild(groupEl);
+
+ const groupWords = groupEl.querySelectorAll('.word');
+
+ // Entrance
+ tl.set(groupEl, { visibility: 'visible' }, group.start);
+ tl.to(groupEl, { opacity: 1, duration: 0.1 }, group.start);
+
+ // Words slide into alignment along "rails"
+ tl.from(groupWords, {
+ x: (i) => (i % 2 === 0 ? -150 : 150),
+ opacity: 0,
+ duration: 0.8,
+ stagger: 0.04,
+ ease: "power4.out"
+ }, group.start);
+
+ // Exit
+ const exitTime = group.end;
+ tl.to(groupEl, {
+ opacity: 0,
+ duration: 0.2,
+ ease: "power2.in"
+ }, exitTime);
+ tl.set(groupEl, { visibility: 'hidden' }, exitTime + 0.2);
+ });
+
+ // Ambient motion for the rails
+ tl.to('.rail-h', {
+ scaleX: 0.9,
+ opacity: 0.03,
+ duration: 14,
+ ease: "none"
+ }, 0);
+
+ tl.to('.rail-v', {
+ scaleY: 0.9,
+ opacity: 0.03,
+ duration: 14,
+ ease: "none"
+ }, 0);
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-15-prod/src/compositions/hero_moment.html b/packages/producer/tests/style-15-prod/src/compositions/hero_moment.html
new file mode 100644
index 0000000000..eb92257f86
--- /dev/null
+++ b/packages/producer/tests/style-15-prod/src/compositions/hero_moment.html
@@ -0,0 +1,300 @@
+<template id="hero-moment-template">
+ <div data-composition-id="hero-moment" data-width="1080" data-height="1920" data-duration="14">
+ <div class="background">
+ <div class="paper-texture"></div>
+ <div class="grid-lines"></div>
+ <div class="accent-circle"></div>
+ </div>
+
+ <div class="content-layer">
+ <div class="stat-container">
+ <div class="stat-number">75%</div>
+ <div class="stat-fraction">(3 out of 4)</div>
+ </div>
+
+ <div class="text-container">
+ <div class="line line-1">LACK</div>
+ <div class="line line-2">THE ESSENTIAL</div>
+ <div class="line line-3">SKILLS</div>
+ </div>
+
+ <div class="geometric-elements">
+ <div class="rule-line horizontal"></div>
+ <div class="rule-line vertical"></div>
+ <div class="square-accent"></div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="hero-moment"] {
+ background-color: transparent;
+ color: #000000;
+ font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ overflow: hidden;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ }
+
+ [data-composition-id="hero-moment"] .paper-texture {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ opacity: 0.05; /* Standardized to 0.05 */
+ pointer-events: none;
+ background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E");
+ z-index: 0;
+ }
+
+ [data-composition-id="hero-moment"] .background {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 0;
+ }
+
+ [data-composition-id="hero-moment"] .grid-lines {
+ position: absolute;
+ width: 200%;
+ height: 200%;
+ top: -50%;
+ left: -50%;
+ background-image:
+ linear-gradient(to right, rgba(0,0,0,0.05) 1px, transparent 1px),
+ linear-gradient(to bottom, rgba(0,0,0,0.05) 1px, transparent 1px);
+ background-size: 100px 100px;
+ transform: rotate(-15deg);
+ }
+
+ [data-composition-id="hero-moment"] .accent-circle {
+ position: absolute;
+ width: 800px;
+ height: 800px;
+ border: 2px solid #BE1E2D;
+ border-radius: 50%;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%) scale(0);
+ opacity: 0;
+ }
+
+ [data-composition-id="hero-moment"] .content-layer {
+ position: relative;
+ z-index: 1;
+ width: 900px;
+ height: 1600px;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ }
+
+ [data-composition-id="hero-moment"] .stat-container {
+ position: absolute;
+ top: 10%;
+ left: 50%;
+ transform: translateX(-50%);
+ text-align: center;
+ }
+
+ [data-composition-id="hero-moment"] .stat-number {
+ font-size: 280px; /* Reduced massiveness for better hierarchy */
+ font-weight: 300; /* Slightly more weight for legibility */
+ line-height: 0.8;
+ color: #BE1E2D;
+ letter-spacing: -10px;
+ opacity: 0;
+ }
+
+ [data-composition-id="hero-moment"] .stat-fraction {
+ font-size: 48px; /* Slightly larger supporting text */
+ font-weight: 300;
+ margin-top: 10px;
+ letter-spacing: 12px; /* More tracking */
+ text-transform: uppercase;
+ opacity: 0;
+ }
+
+ [data-composition-id="hero-moment"] .text-container {
+ position: absolute;
+ bottom: 15%;
+ left: 50%;
+ transform: translateX(-50%);
+ text-align: center;
+ width: 100%;
+ }
+
+ [data-composition-id="hero-moment"] .line {
+ font-size: 120px; /* Increased for impact */
+ font-weight: 800;
+ line-height: 0.8; /* Tighter line height */
+ margin-bottom: 10px;
+ letter-spacing: 4px; /* More tracking */
+ opacity: 0;
+ }
+
+ [data-composition-id="hero-moment"] .line-2 {
+ font-size: 60px;
+ font-weight: 400;
+ color: #BE1E2D;
+ }
+
+ [data-composition-id="hero-moment"] .geometric-elements {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ top: 0;
+ left: 0;
+ }
+
+ [data-composition-id="hero-moment"] .rule-line {
+ position: absolute;
+ background-color: #000000;
+ opacity: 0;
+ }
+
+ [data-composition-id="hero-moment"] .rule-line.horizontal {
+ width: 0%;
+ height: 4px;
+ top: 45%;
+ left: 0;
+ }
+
+ [data-composition-id="hero-moment"] .rule-line.vertical {
+ width: 4px;
+ height: 0%;
+ top: 0;
+ left: 50%;
+ }
+
+ [data-composition-id="hero-moment"] .square-accent {
+ position: absolute;
+ width: 60px;
+ height: 60px;
+ background-color: #BE1E2D;
+ top: 43.5%;
+ left: 47.5%;
+ transform: scale(0);
+ opacity: 0;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.14, 'end': 0.239}, {'text': 'asked', 'start': 0.28, 'end': 0.459}, {'text': 'what', 'start': 0.5, 'end': 0.619}, {'text': 'you', 'start': 0.659, 'end': 0.779}, {'text': 'needed.', 'start': 0.8, 'end': 1.179}, {'text': 'Forty-seven', 'start': 1.199, 'end': 1.619}, {'text': 'percent', 'start': 1.699, 'end': 1.96}, {'text': 'of', 'start': 1.979, 'end': 2.059}, {'text': 'you', 'start': 2.099, 'end': 2.299}, {'text': 'said', 'start': 2.319, 'end': 2.499}, {'text': 'motion', 'start': 2.559, 'end': 2.839}, {'text': 'graphics,', 'start': 2.899, 'end': 3.759}, {'text': 'sixty-two', 'start': 3.799, 'end': 4.159}, {'text': 'percent', 'start': 4.239, 'end': 4.559}, {'text': 'said', 'start': 4.639, 'end': 4.799}, {'text': 'static', 'start': 4.859, 'end': 5.199}, {'text': 'content', 'start': 5.239, 'end': 5.639}, {'text': 'was', 'start': 5.679, 'end': 5.779}, {'text': 'costing', 'start': 5.859, 'end': 6.219}, {'text': 'you', 'start': 6.259, 'end': 6.339}, {'text': 'attention,', 'start': 6.379, 'end': 7.299}, {'text': 'and', 'start': 7.319, 'end': 7.439}, {'text': 'three', 'start': 7.48, 'end': 7.599}, {'text': 'out', 'start': 7.679, 'end': 7.779}, {'text': 'of', 'start': 7.799, 'end': 7.879}, {'text': 'four', 'start': 7.94, 'end': 8.139}, {'text': 'said', 'start': 8.279, 'end': 8.46}, {'text': 'you', 'start': 8.519, 'end': 8.6}, {'text': 'know', 'start': 8.619, 'end': 8.739}, {'text': 'the', 'start': 8.8, 'end': 8.88}, {'text': 'look', 'start': 8.92, 'end': 9.079}, {'text': 'you', 'start': 9.119, 'end': 9.259}, {'text': 'want', 'start': 9.279, 'end': 9.619}, {'text': 'but', 'start': 9.779, 'end': 9.88}, {'text': "don't", 'start': 9.92, 'end': 10.1}, {'text': 'have', 'start': 10.159, 'end': 10.3}, {'text': 'the', 'start': 10.3, 'end': 10.42}, {'text': 'editing', 'start': 10.5, 'end': 10.779}, {'text': 'skills', 'start': 10.86, 'end': 11.139}, {'text': 'to', 'start': 11.159, 'end': 11.239}, {'text': 'get', 'start': 11.279, 'end': 11.439}, {'text': 'there.', 'start': 11.46, 'end': 12.239}, {'text': 'So', 'start': 12.3, 'end': 12.38}, {'text': 'we', 'start': 12.399, 'end': 12.519}, {'text': 'built', 'start': 12.539, 'end': 12.759}, {'text': 'Editor', 'start': 12.84, 'end': 13.119}, {'text': 'Agent.', 'start': 13.239, 'end': 13.84}];
+ const tl = gsap.timeline({ paused: true });
+
+ // Helper to find word timing
+ function getWordTime(word) {
+ const found = TRANSCRIPT.find(w => w.text.toLowerCase().replace(/[^\w]/g, '') === word.toLowerCase());
+ return found ? found.start : 0;
+ }
+
+ // 1. Entrance (Starts at 7.319s)
+ tl.to('[data-composition-id="hero-moment"] .accent-circle', {
+ opacity: 0.2,
+ scale: 1.2,
+ duration: 1,
+ ease: 'power2.out'
+ }, 7.319);
+
+ tl.to('[data-composition-id="hero-moment"] .rule-line.horizontal', {
+ width: '100%',
+ opacity: 0.3,
+ duration: 0.8,
+ ease: 'expo.out'
+ }, 7.4);
+
+ tl.to('[data-composition-id="hero-moment"] .rule-line.vertical', {
+ height: '100%',
+ opacity: 0.3,
+ duration: 0.8,
+ ease: 'expo.out'
+ }, 7.5);
+
+ tl.to('[data-composition-id="hero-moment"] .square-accent', {
+ scale: 1,
+ opacity: 1,
+ duration: 0.5,
+ ease: 'back.out(1.7)'
+ }, 7.8);
+
+ // 2. Kinetic Typography synced to transcript
+ // "75%" (three out of four)
+ const timeThree = getWordTime('three');
+ tl.to('[data-composition-id="hero-moment"] .stat-number', {
+ opacity: 1,
+ duration: 0.8,
+ ease: 'power4.out'
+ }, timeThree);
+
+ tl.to('[data-composition-id="hero-moment"] .stat-fraction', {
+ opacity: 0.8,
+ duration: 0.8,
+ ease: 'power2.out'
+ }, timeThree + 0.2);
+
+ // "lack"
+ const timeSkills = getWordTime('skills');
+ tl.to('[data-composition-id="hero-moment"] .line-1', {
+ opacity: 1,
+ duration: 0.6,
+ ease: 'back.out(1.2)'
+ }, timeSkills - 0.4);
+
+ // "essential"
+ tl.to('[data-composition-id="hero-moment"] .line-2', {
+ opacity: 1,
+ duration: 0.6,
+ ease: 'back.out(1.2)'
+ }, timeSkills - 0.2);
+
+ // "skills"
+ tl.to('[data-composition-id="hero-moment"] .line-3', {
+ opacity: 1,
+ duration: 0.6,
+ ease: 'back.out(1.2)'
+ }, timeSkills);
+
+ // 3. Ambient Motion (Continuous)
+ tl.to('[data-composition-id="hero-moment"] .grid-lines', {
+ x: '+=50',
+ y: '+=50',
+ duration: 14,
+ ease: 'none'
+ }, 0);
+
+ tl.to('[data-composition-id="hero-moment"] .accent-circle', {
+ scale: 1.3,
+ duration: 14,
+ ease: 'sine.inOut'
+ }, 0);
+
+ // 4. Exit (Starts at 12.239s)
+ tl.to('[data-composition-id="hero-moment"] .content-layer, [data-composition-id="hero-moment"] .geometric-elements', {
+ opacity: 0,
+ y: 50,
+ duration: 0.6,
+ ease: 'power3.in'
+ }, 12.239);
+
+ tl.to('[data-composition-id="hero-moment"] .accent-circle', {
+ scale: 2,
+ opacity: 0,
+ duration: 0.8,
+ ease: 'power2.in'
+ }, 12.239);
+
+ window.__timelines["hero-moment"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-15-prod/src/compositions/mograph_overlays.html b/packages/producer/tests/style-15-prod/src/compositions/mograph_overlays.html
new file mode 100644
index 0000000000..181df5b679
--- /dev/null
+++ b/packages/producer/tests/style-15-prod/src/compositions/mograph_overlays.html
@@ -0,0 +1,226 @@
+<template id="mograph-overlays-template">
+ <div data-composition-id="mograph-overlays" data-width="1080" data-height="1920" data-duration="14">
+ <div id="mograph-container">
+ <!-- Ambient Elements -->
+ <div class="diagonal-line line-1"></div>
+ <div class="diagonal-line line-2"></div>
+ <div class="marker marker-tl"></div>
+ <div class="marker marker-tr"></div>
+ <div class="marker marker-bl"></div>
+ <div class="marker marker-br"></div>
+
+ <!-- Alignment Indicators -->
+ <div class="alignment-h"></div>
+ <div class="alignment-v"></div>
+ </div>
+
+ <style>
+ [data-composition-id="mograph-overlays"] {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ overflow: hidden;
+ font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ color: #000000;
+ }
+
+ [data-composition-id="mograph-overlays"] #mograph-container {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ }
+
+ /* Diagonal Lines - Modernist Red */
+ [data-composition-id="mograph-overlays"] .diagonal-line {
+ position: absolute;
+ background: #BE1E2D;
+ height: 1px;
+ opacity: 0.2;
+ }
+
+ [data-composition-id="mograph-overlays"] .line-1 {
+ width: 600px;
+ top: 150px;
+ left: -150px;
+ transform: rotate(45deg);
+ }
+
+ [data-composition-id="mograph-overlays"] .line-2 {
+ width: 800px;
+ bottom: 200px;
+ right: -200px;
+ transform: rotate(-45deg);
+ }
+
+ /* Geometric Markers - Clean Lines */
+ [data-composition-id="mograph-overlays"] .marker {
+ position: absolute;
+ width: 30px;
+ height: 30px;
+ border: 1px solid #000000;
+ opacity: 0.4;
+ }
+
+ [data-composition-id="mograph-overlays"] .marker-tl { top: 60px; left: 60px; border-right: 0; border-bottom: 0; }
+ [data-composition-id="mograph-overlays"] .marker-tr { top: 60px; right: 60px; border-left: 0; border-bottom: 0; }
+ [data-composition-id="mograph-overlays"] .marker-bl { bottom: 60px; left: 60px; border-right: 0; border-top: 0; }
+ [data-composition-id="mograph-overlays"] .marker-br { bottom: 60px; right: 60px; border-left: 0; border-top: 0; }
+
+ /* Alignment Indicators - Subtle Grid */
+ [data-composition-id="mograph-overlays"] .alignment-h {
+ position: absolute;
+ top: 50%;
+ left: 80px;
+ right: 80px;
+ height: 1px;
+ background: rgba(0,0,0,0.05);
+ }
+
+ [data-composition-id="mograph-overlays"] .alignment-v {
+ position: absolute;
+ left: 50%;
+ top: 80px;
+ bottom: 80px;
+ width: 1px;
+ background: rgba(0,0,0,0.05);
+ }
+
+ /* Dynamic Graphic - Modernist Museum Style */
+ [data-composition-id="mograph-overlays"] .dynamic-graphic {
+ position: absolute;
+ opacity: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ padding: 20px;
+ }
+
+ [data-composition-id="mograph-overlays"] .graphic-value {
+ font-size: 80px;
+ font-weight: 300; /* Lighter weight for museum feel */
+ line-height: 0.9;
+ color: #000000;
+ letter-spacing: -0.04em;
+ }
+
+ [data-composition-id="mograph-overlays"] .graphic-label {
+ font-size: 18px;
+ font-weight: 500;
+ letter-spacing: 6px;
+ margin-top: 15px;
+ color: #BE1E2D; /* Accent color for label */
+ text-transform: uppercase;
+ }
+
+ [data-composition-id="mograph-overlays"] .graphic-line {
+ width: 0;
+ height: 1px;
+ background: #000000;
+ margin-top: 10px;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.14, 'end': 0.239}, {'text': 'asked', 'start': 0.28, 'end': 0.459}, {'text': 'what', 'start': 0.5, 'end': 0.619}, {'text': 'you', 'start': 0.659, 'end': 0.779}, {'text': 'needed.', 'start': 0.8, 'end': 1.179}, {'text': 'Forty-seven', 'start': 1.199, 'end': 1.619}, {'text': 'percent', 'start': 1.699, 'end': 1.96}, {'text': 'of', 'start': 1.979, 'end': 2.059}, {'text': 'you', 'start': 2.099, 'end': 2.299}, {'text': 'said', 'start': 2.319, 'end': 2.499}, {'text': 'motion', 'start': 2.559, 'end': 2.839}, {'text': 'graphics,', 'start': 2.899, 'end': 3.759}, {'text': 'sixty-two', 'start': 3.799, 'end': 4.159}, {'text': 'percent', 'start': 4.239, 'end': 4.559}, {'text': 'said', 'start': 4.639, 'end': 4.799}, {'text': 'static', 'start': 4.859, 'end': 5.199}, {'text': 'content', 'start': 5.239, 'end': 5.639}, {'text': 'was', 'start': 5.679, 'end': 5.779}, {'text': 'costing', 'start': 5.859, 'end': 6.219}, {'text': 'you', 'start': 6.259, 'end': 6.339}, {'text': 'attention,', 'start': 6.379, 'end': 7.299}, {'text': 'and', 'start': 7.319, 'end': 7.439}, {'text': 'three', 'start': 7.48, 'end': 7.599}, {'text': 'out', 'start': 7.679, 'end': 7.779}, {'text': 'of', 'start': 7.799, 'end': 7.879}, {'text': 'four', 'start': 7.94, 'end': 8.139}, {'text': 'said', 'start': 8.279, 'end': 8.46}, {'text': 'you', 'start': 8.519, 'end': 8.6}, {'text': 'know', 'start': 8.619, 'end': 8.739}, {'text': 'the', 'start': 8.8, 'end': 8.88}, {'text': 'look', 'start': 8.92, 'end': 9.079}, {'text': 'you', 'start': 9.119, 'end': 9.259}, {'text': 'want', 'start': 9.279, 'end': 9.619}, {'text': 'but', 'start': 9.779, 'end': 9.88}, {'text': "don't", 'start': 9.92, 'end': 10.1}, {'text': 'have', 'start': 10.159, 'end': 10.3}, {'text': 'the', 'start': 10.3, 'end': 10.42}, {'text': 'editing', 'start': 10.5, 'end': 10.779}, {'text': 'skills', 'start': 10.86, 'end': 11.139}, {'text': 'to', 'start': 11.159, 'end': 11.239}, {'text': 'get', 'start': 11.279, 'end': 11.439}, {'text': 'there.', 'start': 11.46, 'end': 12.239}, {'text': 'So', 'start': 12.3, 'end': 12.38}, {'text': 'we', 'start': 12.399, 'end': 12.519}, {'text': 'built', 'start': 12.539, 'end': 12.759}, {'text': 'Editor', 'start': 12.84, 'end': 13.119}, {'text': 'Agent.', 'start': 13.239, 'end': 13.84}];
+ const tl = gsap.timeline({ paused: true });
+
+ // Face Avoidance Area: x:300-776, y:320-796
+ // Safe zones: Right side (x > 800), Top (y < 300), Bottom (y > 800)
+
+ // 1. Ambient Motion (Continuous & Subtle)
+ tl.to('.line-1', { x: 30, y: 10, duration: 14, ease: 'none' }, 0);
+ tl.to('.line-2', { x: -30, y: -10, duration: 14, ease: 'none' }, 0);
+
+ tl.from('.marker', {
+ scale: 0.9,
+ opacity: 0,
+ duration: 1.5,
+ stagger: 0.3,
+ ease: 'power2.out'
+ }, 0);
+
+ // 2. Transcript-Synced Graphics
+ // Updated content based on design review
+ const triggerWords = [
+ { word: "47%", label: "USER SURVEY" },
+ { word: "static", label: "CONTENT ENGAGEMENT" },
+ { word: "editing", label: "TECHNICAL SKILLS" },
+ { word: "Editor", label: "SYSTEM ARCHITECTURE" }
+ ];
+
+ triggerWords.forEach((trigger, index) => {
+ const wordData = TRANSCRIPT.find(w => w.text.toLowerCase().includes(trigger.word.toLowerCase()));
+ if (wordData) {
+ const startTime = wordData.start;
+ const duration = 3.0;
+
+ // Deterministic positioning outside face area (Vertical Safe Zones)
+ // Face: x:300-776, y:320-796 (approx in vertical)
+ const positions = [
+ { x: 50, y: 1500 }, // Bottom Left
+ { x: 600, y: 1600 }, // Bottom Right
+ { x: 100, y: 100 }, // Top Left
+ { x: 500, y: 50 } // Top Right
+ ];
+ const pos = positions[index % positions.length];
+
+ // Create a unique graphic for each trigger
+ const graphicId = `graphic-${index}`;
+ const graphicHtml = `
+ <div id="${graphicId}" class="dynamic-graphic" style="left: ${pos.x}px; top: ${pos.y}px;">
+ <div class="graphic-value">${trigger.word.toUpperCase()}</div>
+ <div class="graphic-label">${trigger.label}</div>
+ <div class="graphic-line"></div>
+ </div>
+ `;
+ document.getElementById('mograph-container').insertAdjacentHTML('beforeend', graphicHtml);
+
+ const graphicSelector = `#${graphicId}`;
+
+ // Entrance - Clean and Sophisticated
+ tl.to(graphicSelector, {
+ opacity: 1,
+ duration: 1.0,
+ ease: 'power3.out'
+ }, startTime);
+
+ tl.from(`${graphicSelector} .graphic-value`, {
+ x: -20,
+ opacity: 0,
+ duration: 1.2,
+ ease: 'power4.out'
+ }, startTime + 0.1);
+
+ tl.to(`${graphicSelector} .graphic-line`, {
+ width: 250,
+ duration: 1.5,
+ ease: 'expo.out'
+ }, startTime + 0.4);
+
+ // Exit - Smooth Fade
+ tl.to(graphicSelector, {
+ opacity: 0,
+ x: 20,
+ duration: 0.8,
+ ease: 'power2.in'
+ }, startTime + duration);
+ }
+ });
+
+ // 3. Subtle Grid/Alignment pulses
+ tl.to('.alignment-h, .alignment-v', {
+ opacity: 0.2,
+ duration: 0.5,
+ repeat: 3,
+ yoyo: true,
+ ease: 'power1.inOut'
+ }, 1);
+
+ window.__timelines["mograph-overlays"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-15-prod/src/design_review.md b/packages/producer/tests/style-15-prod/src/design_review.md
new file mode 100644
index 0000000000..c9796f65a1
--- /dev/null
+++ b/packages/producer/tests/style-15-prod/src/design_review.md
@@ -0,0 +1,61 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a Bauhaus-inspired museum exhibit had a head-on collision with a TikTok ad. It’s trying to be Jan Tschichold, but it’s currently closer to "I just discovered the Helvetica font and the color red."
+
+---
+
+## CRITICAL Design Failures
+
+Issues that make this look unprofessional or straight-up ugly. These MUST be fixed.
+
+### The "Floating Head" Problem
+**Where:** `compositions/aroll.html`
+**What's wrong:** The A-Roll video is set to `object-fit: cover` and fills the entire 1080x1920 frame. While bold, it completely ignores the "safe zones" for the face. The `mograph_overlays.html` then proceeds to slap text directly over where the speaker's face likely is.
+**Why it matters:** You're literally covering the speaker's mouth or eyes with "USER SURVEY" and "47%". It looks like a mistake, not a design choice.
+**Fix it:** Scale the A-Roll video down or use a mask that respects the rule of thirds. If you're going full-screen, your overlays need to be pushed to the extreme margins.
+
+### Caption Chaos
+**Where:** `compositions/captions.html`
+**What's wrong:** You have words jumping from `font-size: 50px` to `140px` with a `line-height: 0.9`. In a 9:16 portrait format, this is going to cause massive, ugly overlaps and erratic wrapping.
+**Why it matters:** Readability is the first casualty of "cool" design. If the viewer has to squint or decode which word comes next because they're stacked like a game of Tetris, you've failed.
+**Fix it:** Standardize the scale variance. 50px to 140px is too wide a gap. Try 80px to 120px. Increase the `line-height` to at least `1.1` to give the descenders some breathing room.
+
+### The "Dead" Background
+**Where:** `compositions/background.html`
+**What's wrong:** A `#FAF5E8` (off-white) background with a `0.05` opacity noise filter is basically just a flat, boring beige on most mobile screens. The grid lines are too thin (`1px`, `2px`) to feel intentional; they just look like screen artifacts.
+**Why it matters:** It lacks depth. It feels like a default template rather than a premium "New Typography" aesthetic.
+**Fix it:** Increase the noise opacity to `0.1` or `0.15`. Make the grid lines bolder—use `4px` and `8px` consistently to create a real sense of structure.
+
+---
+
+## Design Improvements
+
+Things that aren't broken but are boring, lazy, or could be significantly better.
+
+### Robotic Motion
+**Where:** `compositions/mograph_overlays.html`
+**The problem:** The diagonal lines and markers just "drift" linearly. It’s the most basic GSAP animation possible.
+**Make it better:** Add some "snap" to the entrance. Use `expo.out` or `back.out` for the markers. Give the lines a slight pulse in opacity or thickness to make them feel like they're reacting to the audio, not just floating in space.
+
+### Hero Moment Hierarchy
+**Where:** `compositions/hero_moment.html`
+**The problem:** The "75%" is `280px` while the supporting text is `120px`. It’s a bit of a "shouting match" between elements.
+**Make it better:** Lean into the Tschichold asymmetry. Move the "75%" off-center. Use a much heavier weight for the number and a much lighter, tracked-out weight for the text. Contrast is your friend; stop making everything "big."
+
+---
+
+## What Actually Works
+
+The use of **Bauhaus Red (#BE1E2D)** against the off-white is a classic for a reason. When it hits, it hits hard. The "rail" concept in the captions is a genuine nod to modernist layout principles—it just needs better execution. The "wipe-line" entrance in the A-Roll is actually quite sophisticated and provides a nice "editorial" feel.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 6/10 - It has a clear direction, but it's playing it too safe.
+**Color & Typography:** 5/10 - Good palette, but the typographic hierarchy is a mess of competing scales.
+**Motion & Animation Feel:** 4/10 - Too much linear drifting; needs more rhythmic "pop."
+**Overall Aesthetic:** 5/10 - It looks like a student project trying to mimic a master.
+
+**Bottom Line:** It’s not a disaster, but it’s forgettable. You’ve got the ingredients for a high-end editorial look, but you’re currently serving it on a paper plate. Fix the face-blocking overlays and the caption scaling before you show this to anyone with a pulse.
diff --git a/packages/producer/tests/style-15-prod/src/index.html b/packages/producer/tests/style-15-prod/src/index.html
new file mode 100644
index 0000000000..a176d1bf37
--- /dev/null
+++ b/packages/producer/tests/style-15-prod/src/index.html
@@ -0,0 +1,86 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Jan Tschichold Typography Video</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1080px;
+ height: 1920px;
+ overflow: hidden;
+ background-color: #FAF5E8;
+ }
+ #master-composition {
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ z-index: 0;
+ }
+ #bg-comp { z-index: 1; }
+ #aroll-comp { z-index: 2; }
+ #hero-comp { z-index: 3; }
+ #mograph-comp { z-index: 4; }
+ #captions-comp { z-index: 5; }
+ </style>
+</head>
+<body>
+ <div id="master-composition" data-composition-id="master" data-width="1080" data-height="1920" data-duration="14">
+
+ <!-- Background Layer -->
+ <div id="bg-comp"
+ data-composition-id="background"
+ data-composition-src="compositions/background.html"
+ data-start="0"
+ data-duration="14"
+ data-track-index="0">
+ </div>
+
+ <!-- A-Roll Video Layer -->
+ <div id="aroll-comp"
+ data-composition-id="aroll"
+ data-composition-src="compositions/aroll.html"
+ data-start="0"
+ data-duration="14"
+ data-track-index="1">
+ </div>
+
+ <!-- Hero Moment (Full Canvas) -->
+ <div id="hero-comp"
+ data-composition-id="hero-moment"
+ data-composition-src="compositions/hero_moment.html"
+ data-start="0"
+ data-duration="14"
+ data-track-index="2">
+ </div>
+
+ <!-- Motion Graphic Overlays -->
+ <div id="mograph-comp"
+ data-composition-id="mograph-overlays"
+ data-composition-src="compositions/mograph_overlays.html"
+ data-start="0"
+ data-duration="14"
+ data-track-index="3">
+ </div>
+
+ <!-- Captions Layer -->
+ <div id="captions-comp"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="14"
+ data-track-index="4">
+ </div>
+
+ </div>
+
+ <script>
+ window.__timelines = {};
+ const masterTL = gsap.timeline({ paused: true });
+ window.__timelines["master"] = masterTL;
+ </script>
+</body>
+</html>
diff --git a/packages/producer/tests/style-16-prod/meta.json b/packages/producer/tests/style-16-prod/meta.json
new file mode 100644
index 0000000000..7223591935
--- /dev/null
+++ b/packages/producer/tests/style-16-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-16-prod",
+ "description": "Regression fixture imported from normalized style pack style-16-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "portrait"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-16-prod/src/assets/shapes.svg b/packages/producer/tests/style-16-prod/src/assets/shapes.svg
new file mode 100644
index 0000000000..0ad65bcb6c
--- /dev/null
+++ b/packages/producer/tests/style-16-prod/src/assets/shapes.svg
@@ -0,0 +1,35 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1080 1920" width="1080" height="1920">
+ <defs>
+ <pattern id="diagonal-grid" width="60" height="60" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
+ <line x1="0" y1="0" x2="0" y2="60" stroke="#7A7A7A" stroke-width="3" />
+ <line x1="0" y1="0" x2="60" y2="0" stroke="#7A7A7A" stroke-width="3" />
+ </pattern>
+ </defs>
+
+ <!-- Background -->
+ <rect id="background" width="1080" height="1920" fill="#F4F4F4" />
+
+ <!-- Grey diagonal grid pattern -->
+ <rect id="grid-pattern" x="140" y="200" width="800" height="1520" fill="url(#diagonal-grid)" />
+
+ <!-- Large black circle -->
+ <circle id="black-circle" cx="650" cy="750" r="420" fill="#000000" />
+
+ <!-- Sharp red wedge pointing towards the center -->
+ <polygon id="red-wedge" points="100,1600 250,1750 750,850" fill="#CC0000" />
+
+ <!-- Stencil-style numbers '47' and '62' in black -->
+ <g id="stencil-numbers">
+ <!-- Number 47 -->
+ <text id="number-47" x="180" y="450" font-family="'Arial Black', Impact, sans-serif" font-size="300" fill="#000000" font-weight="900" letter-spacing="-15">47</text>
+ <!-- Stencil cuts for 47 -->
+ <line x1="150" y1="280" x2="550" y2="280" stroke="#F4F4F4" stroke-width="15" />
+ <line x1="150" y1="360" x2="550" y2="360" stroke="#F4F4F4" stroke-width="15" />
+
+ <!-- Number 62 -->
+ <text id="number-62" x="580" y="1550" font-family="'Arial Black', Impact, sans-serif" font-size="350" fill="#000000" font-weight="900" letter-spacing="-20">62</text>
+ <!-- Stencil cuts for 62 -->
+ <line x1="550" y1="1350" x2="1050" y2="1350" stroke="#F4F4F4" stroke-width="18" />
+ <line x1="550" y1="1450" x2="1050" y2="1450" stroke="#F4F4F4" stroke-width="18" />
+ </g>
+</svg>
\ No newline at end of file
diff --git a/packages/producer/tests/style-16-prod/src/code_review.md b/packages/producer/tests/style-16-prod/src/code_review.md
new file mode 100644
index 0000000000..b22a1d9383
--- /dev/null
+++ b/packages/producer/tests/style-16-prod/src/code_review.md
@@ -0,0 +1,44 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 3
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - absolute timing used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+### index.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None.
+
+### compositions/motion-graphics.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None.
+
+### compositions/captions.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None.
diff --git a/packages/producer/tests/style-16-prod/src/compositions/captions.html b/packages/producer/tests/style-16-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..78f6fbccc0
--- /dev/null
+++ b/packages/producer/tests/style-16-prod/src/compositions/captions.html
@@ -0,0 +1,151 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1080" data-height="1920" data-duration="13.88">
+ <div id="caption-panel">
+ <div id="caption-kicker">Narration</div>
+ <div id="captions-container"></div>
+ </div>
+
+ <style>
+ [data-composition-id="captions"] {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ pointer-events: none;
+ font-family: 'Montserrat', 'Impact', 'Arial Black', sans-serif;
+ text-transform: uppercase;
+ overflow: hidden;
+ }
+
+ [data-composition-id="captions"] #caption-panel {
+ position: absolute;
+ left: 92px;
+ bottom: 112px;
+ width: 896px;
+ min-height: 278px;
+ background: rgba(232, 220, 200, 0.96);
+ border: 3px solid #000000;
+ box-shadow: 14px 14px 0 #CC0000;
+ box-sizing: border-box;
+ padding: 20px 24px 26px;
+ }
+
+ [data-composition-id="captions"] #caption-kicker {
+ font-size: 18px;
+ letter-spacing: 0.24em;
+ margin-bottom: 18px;
+ }
+
+ [data-composition-id="captions"] #captions-container {
+ position: relative;
+ width: 100%;
+ min-height: 186px;
+ }
+
+ [data-composition-id="captions"] .caption-group {
+ position: absolute;
+ inset: 0;
+ opacity: 0;
+ }
+
+ [data-composition-id="captions"] .word-wrapper {
+ display: inline-block;
+ margin: 6px 10px 6px 0;
+ padding: 8px 14px;
+ background-color: #000000;
+ color: #FFFFFF;
+ font-size: 54px;
+ line-height: 1;
+ box-shadow: 6px 6px 0px #CC0000;
+ }
+
+ [data-composition-id="captions"] .word-wrapper.highlight {
+ background-color: #CC0000;
+ color: #000000;
+ box-shadow: 6px 6px 0px #000000;
+ }
+
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.14, 'end': 0.239}, {'text': 'asked', 'start': 0.28, 'end': 0.459}, {'text': 'what', 'start': 0.5, 'end': 0.619}, {'text': 'you', 'start': 0.659, 'end': 0.779}, {'text': 'needed.', 'start': 0.8, 'end': 1.179}, {'text': 'Forty-seven', 'start': 1.199, 'end': 1.619}, {'text': 'percent', 'start': 1.699, 'end': 1.96}, {'text': 'of', 'start': 1.979, 'end': 2.059}, {'text': 'you', 'start': 2.099, 'end': 2.299}, {'text': 'said', 'start': 2.319, 'end': 2.499}, {'text': 'motion', 'start': 2.559, 'end': 2.839}, {'text': 'graphics,', 'start': 2.899, 'end': 3.759}, {'text': 'sixty-two', 'start': 3.799, 'end': 4.159}, {'text': 'percent', 'start': 4.239, 'end': 4.559}, {'text': 'said', 'start': 4.639, 'end': 4.799}, {'text': 'static', 'start': 4.859, 'end': 5.199}, {'text': 'content', 'start': 5.239, 'end': 5.639}, {'text': 'was', 'start': 5.679, 'end': 5.779}, {'text': 'costing', 'start': 5.859, 'end': 6.219}, {'text': 'you', 'start': 6.259, 'end': 6.339}, {'text': 'attention,', 'start': 6.379, 'end': 7.299}, {'text': 'and', 'start': 7.319, 'end': 7.439}, {'text': 'three', 'start': 7.48, 'end': 7.599}, {'text': 'out', 'start': 7.679, 'end': 7.779}, {'text': 'of', 'start': 7.799, 'end': 7.879}, {'text': 'four', 'start': 7.94, 'end': 8.139}, {'text': 'said', 'start': 8.279, 'end': 8.46}, {'text': 'you', 'start': 8.519, 'end': 8.6}, {'text': 'know', 'start': 8.619, 'end': 8.739}, {'text': 'the', 'start': 8.8, 'end': 8.88}, {'text': 'look', 'start': 8.92, 'end': 9.079}, {'text': 'you', 'start': 9.119, 'end': 9.259}, {'text': 'want', 'start': 9.279, 'end': 9.619}, {'text': 'but', 'start': 9.779, 'end': 9.88}, {'text': "don't", 'start': 9.92, 'end': 10.1}, {'text': 'have', 'start': 10.159, 'end': 10.3}, {'text': 'the', 'start': 10.3, 'end': 10.42}, {'text': 'editing', 'start': 10.5, 'end': 10.779}, {'text': 'skills', 'start': 10.86, 'end': 11.139}, {'text': 'to', 'start': 11.159, 'end': 11.239}, {'text': 'get', 'start': 11.279, 'end': 11.439}, {'text': 'there.', 'start': 11.46, 'end': 12.239}, {'text': 'So', 'start': 12.3, 'end': 12.38}, {'text': 'we', 'start': 12.399, 'end': 12.519}, {'text': 'built', 'start': 12.539, 'end': 12.759}, {'text': 'Editor', 'start': 12.84, 'end': 13.119}, {'text': 'Agent.', 'start': 13.239, 'end': 13.84}];
+ const container = document.getElementById('captions-container');
+ const tl = gsap.timeline({ paused: true });
+
+ const groups = [];
+ let currentGroup = [];
+
+ TRANSCRIPT.forEach((word, index) => {
+ currentGroup.push(word);
+ if (currentGroup.length >= 4 || word.text.includes('.') || word.text.includes('?') || index === TRANSCRIPT.length - 1) {
+ groups.push([...currentGroup]);
+ currentGroup = [];
+ }
+ });
+
+ groups.forEach((group, gIndex) => {
+ const groupEl = document.createElement('div');
+ groupEl.className = 'caption-group';
+ groupEl.id = `group-${gIndex}`;
+
+ group.forEach((word, wIndex) => {
+ const wordWrapper = document.createElement('div');
+ wordWrapper.className = 'word-wrapper';
+
+ wordWrapper.textContent = word.text.replace(/[.,?!]/g, '');
+ wordWrapper.id = `word-${gIndex}-${wIndex}`;
+ groupEl.appendChild(wordWrapper);
+
+ // Word highlight animation
+ tl.to(wordWrapper, {
+ backgroundColor: '#CC0000',
+ color: '#000000',
+ boxShadow: '6px 6px 0px #000000',
+ duration: 0.1,
+ ease: 'none'
+ }, word.start);
+
+ tl.to(wordWrapper, {
+ backgroundColor: '#000000',
+ color: '#FFFFFF',
+ boxShadow: '6px 6px 0px #CC0000',
+ duration: 0.1,
+ ease: 'none'
+ }, word.end);
+ });
+
+ container.appendChild(groupEl);
+
+ // Group entrance/exit
+ const groupStart = group[0].start;
+ const groupEnd = group[group.length - 1].end;
+
+ tl.fromTo(groupEl, {
+ opacity: 0,
+ y: 18
+ }, {
+ opacity: 1,
+ y: 0,
+ duration: 0.22,
+ ease: 'power2.out'
+ }, groupStart);
+
+ tl.to(groupEl, {
+ opacity: 0,
+ y: -10,
+ duration: 0.14,
+ ease: 'power2.in'
+ }, groupEnd);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-16-prod/src/compositions/motion-graphics.html b/packages/producer/tests/style-16-prod/src/compositions/motion-graphics.html
new file mode 100644
index 0000000000..58b1dae08b
--- /dev/null
+++ b/packages/producer/tests/style-16-prod/src/compositions/motion-graphics.html
@@ -0,0 +1,396 @@
+<template id="motion-graphics-template">
+ <div data-composition-id="motion-graphics" data-width="1080" data-height="1920" data-duration="13.88">
+ <!-- Background Base -->
+ <div class="bg-base"></div>
+ <div class="newsprint-texture"></div>
+ <div class="frame-outline"></div>
+ <div class="frame-shadow"></div>
+
+ <!-- Parallax Background Elements (Ambient Motion) -->
+ <div class="parallax-container">
+ <div class="bg-shape bg-circle-1"></div>
+ <div class="bg-shape bg-wedge-1"></div>
+ <div class="bg-shape bg-line-1"></div>
+ <div class="bg-shape bg-line-2"></div>
+ </div>
+
+ <!-- Section 1: 1.5s - 4.0s (47% OF YOU NEED MOTION GRAPHICS) -->
+ <div class="section section-1">
+ <div class="stat-panel stat-panel-left"></div>
+ <div class="burst burst-1"></div>
+ <div class="wedge-thrust"></div>
+ <div class="text-container">
+ <div class="kicker">Survey signal</div>
+ <div class="stencil-text percent-47">47%</div>
+ <div class="bold-text">OF YOU NEED<br>MOTION GRAPHICS</div>
+ </div>
+ </div>
+
+ <!-- Section 2: 4.0s - 7.5s (62% SAID STATIC CONTENT REDUCES ENGAGEMENT) -->
+ <div class="section section-2">
+ <div class="stat-panel stat-panel-top"></div>
+ <div class="burst burst-2"></div>
+ <div class="diagonal-grid"></div>
+ <div class="text-container">
+ <div class="kicker">Engagement drop</div>
+ <div class="stencil-text percent-62">62%</div>
+ <div class="bold-text">SAID STATIC CONTENT<br>REDUCES ENGAGEMENT</div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="motion-graphics"] {
+ position: relative;
+ width: 1080px;
+ height: 1920px;
+ background-color: transparent;
+ overflow: hidden;
+ font-family: 'Montserrat', 'Arial Black', sans-serif;
+ }
+
+ [data-composition-id="motion-graphics"] .bg-base {
+ position: absolute;
+ top: 112px;
+ left: 112px;
+ width: 856px;
+ height: 1328px;
+ background: transparent;
+ box-shadow: 0 0 0 9999px #E8DCC8;
+ }
+
+ [data-composition-id="motion-graphics"] .newsprint-texture {
+ position: absolute;
+ inset: 0;
+ opacity: 0.04;
+ background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E");
+ pointer-events: none;
+ mix-blend-mode: multiply;
+ }
+
+ [data-composition-id="motion-graphics"] .frame-outline,
+ [data-composition-id="motion-graphics"] .frame-shadow {
+ position: absolute;
+ top: 112px;
+ left: 112px;
+ width: 856px;
+ height: 1328px;
+ pointer-events: none;
+ }
+
+ [data-composition-id="motion-graphics"] .frame-outline {
+ border: 3px solid #151515;
+ z-index: 12;
+ }
+
+ [data-composition-id="motion-graphics"] .frame-shadow {
+ box-shadow: 16px 16px 0 #CC0000;
+ z-index: 11;
+ }
+
+ /* Parallax Background */
+ [data-composition-id="motion-graphics"] .parallax-container {
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ }
+
+ [data-composition-id="motion-graphics"] .bg-shape {
+ position: absolute;
+ background-color: #7A7A7A;
+ opacity: 0.3;
+ }
+
+ [data-composition-id="motion-graphics"] .bg-circle-1 {
+ width: 320px;
+ height: 320px;
+ border-radius: 50%;
+ top: 118px;
+ left: -86px;
+ }
+
+ [data-composition-id="motion-graphics"] .bg-wedge-1 {
+ width: 0;
+ height: 0;
+ border-left: 86px solid transparent;
+ border-right: 86px solid transparent;
+ border-bottom: 240px solid #CC0000;
+ opacity: 0.16;
+ bottom: 240px;
+ right: 18px;
+ transform: rotate(28deg);
+ }
+
+ [data-composition-id="motion-graphics"] .bg-line-1 {
+ width: 2000px;
+ height: 2px;
+ background-color: #000000;
+ top: 30%;
+ left: -500px;
+ transform: rotate(-15deg);
+ }
+
+ [data-composition-id="motion-graphics"] .bg-line-2 {
+ width: 2000px;
+ height: 4px;
+ background-color: #CC0000;
+ top: 70%;
+ left: -500px;
+ transform: rotate(10deg);
+ }
+
+ /* Sections */
+ [data-composition-id="motion-graphics"] .section {
+ position: absolute;
+ inset: 0;
+ opacity: 0;
+ z-index: 10;
+ }
+
+ [data-composition-id="motion-graphics"] .stat-panel {
+ position: absolute;
+ background: rgba(232, 220, 200, 0.94);
+ border: 3px solid #000000;
+ z-index: 12;
+ }
+
+ [data-composition-id="motion-graphics"] .stat-panel-left {
+ left: 48px;
+ bottom: 308px;
+ width: 450px;
+ height: 370px;
+ }
+
+ [data-composition-id="motion-graphics"] .stat-panel-top {
+ top: 96px;
+ right: 56px;
+ width: 472px;
+ height: 420px;
+ }
+
+ /* Burst */
+ [data-composition-id="motion-graphics"] .burst {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: 100px;
+ height: 100px;
+ background-color: #CC0000;
+ border-radius: 50%;
+ transform: translate(-50%, -50%) scale(0);
+ z-index: 5;
+ }
+
+ /* Section 1 Elements */
+ [data-composition-id="motion-graphics"] .wedge-thrust {
+ position: absolute;
+ width: 0;
+ height: 0;
+ border-left: 180px solid transparent;
+ border-right: 180px solid transparent;
+ border-bottom: 700px solid #CC0000;
+ top: 640px;
+ left: 44px;
+ transform: rotate(-18deg) scale(0);
+ z-index: 7;
+ }
+
+ /* Section 2 Elements */
+ [data-composition-id="motion-graphics"] .diagonal-grid {
+ position: absolute;
+ top: 68px;
+ right: 24px;
+ width: 520px;
+ height: 540px;
+ background-image:
+ linear-gradient(45deg, #7A7A7A 1px, transparent 1px),
+ linear-gradient(-45deg, #7A7A7A 1px, transparent 1px);
+ background-size: 88px 88px;
+ opacity: 0.22;
+ z-index: 6;
+ }
+
+ /* Typography */
+ [data-composition-id="motion-graphics"] .text-container {
+ position: absolute;
+ z-index: 20;
+ color: #000000;
+ }
+
+ [data-composition-id="motion-graphics"] .section-1 .text-container {
+ left: 84px;
+ bottom: 336px;
+ width: 430px;
+ text-align: left;
+ }
+
+ [data-composition-id="motion-graphics"] .section-2 .text-container {
+ top: 132px;
+ right: 92px;
+ width: 392px;
+ text-align: right;
+ }
+
+ [data-composition-id="motion-graphics"] .kicker {
+ font-size: 20px;
+ letter-spacing: 0.26em;
+ text-transform: uppercase;
+ margin-bottom: 22px;
+ color: #000000;
+ }
+
+ [data-composition-id="motion-graphics"] .stencil-text {
+ font-size: 220px;
+ font-weight: 900;
+ line-height: 0.88;
+ margin-bottom: 16px;
+ color: #000000;
+ /* Stencil effect */
+ -webkit-text-stroke: 2px #000000;
+ letter-spacing: -5px;
+ }
+
+ [data-composition-id="motion-graphics"] .section-1 .stencil-text {
+ color: #E8DCC8;
+ -webkit-text-fill-color: #E8DCC8;
+ text-shadow: 4px 4px 0px #000000;
+ }
+
+ [data-composition-id="motion-graphics"] .section-2 .stencil-text {
+ color: #CC0000;
+ -webkit-text-fill-color: #CC0000;
+ }
+
+ [data-composition-id="motion-graphics"] .bold-text {
+ font-size: 42px;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ background-color: #000000;
+ color: #E8DCC8;
+ padding: 14px 18px;
+ display: inline-block;
+ }
+
+ /* Face Box Protection (Visual Guide - Hidden) */
+ /* Face Box: x1:300, y1:320, x2:776, y2:796 */
+ /* We ensure text and primary elements avoid this area if possible,
+ or use it as a framing device. */
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ tl.to('.bg-circle-1', {
+ y: 88,
+ x: 42,
+ duration: 13.88,
+ ease: 'none'
+ }, 0);
+ tl.to('.bg-wedge-1', {
+ rotation: 72,
+ y: -120,
+ duration: 13.88,
+ ease: 'none'
+ }, 0);
+ tl.to('.bg-line-1', {
+ y: 140,
+ duration: 13.88,
+ ease: 'none'
+ }, 0);
+ tl.to('.bg-line-2', {
+ y: -160,
+ duration: 13.88,
+ ease: 'none'
+ }, 0);
+ tl.to('.newsprint-texture', {
+ x: 18,
+ y: -14,
+ duration: 13.88,
+ ease: 'none'
+ }, 0);
+
+ tl.to('.burst-1', {
+ scale: 16,
+ opacity: 0,
+ duration: 0.7,
+ ease: 'expo.out'
+ }, 1.5);
+
+ tl.to('.section-1', { opacity: 1, duration: 0.1 }, 1.5);
+
+ tl.fromTo('.wedge-thrust',
+ { scale: 0, x: -220, y: 520 },
+ { scale: 1, x: 0, y: 0, duration: 0.95, ease: 'power4.out' },
+ 1.5
+ );
+
+ tl.from('.stat-panel-left', {
+ x: -420,
+ duration: 0.8,
+ ease: 'expo.out'
+ }, 1.56);
+
+ tl.from('.section-1 .text-container', {
+ opacity: 0,
+ x: -70,
+ duration: 0.65,
+ ease: 'power3.out'
+ }, 1.72);
+
+ tl.to('.section-1', {
+ opacity: 0,
+ x: -220,
+ duration: 0.45,
+ ease: 'power2.in'
+ }, 3.8);
+
+ tl.to('.section-2', { opacity: 1, duration: 0.1 }, 4.0);
+
+ tl.from('.stat-panel-top', {
+ x: 420,
+ duration: 0.8,
+ ease: 'expo.out'
+ }, 4.0);
+
+ tl.from('.diagonal-grid', {
+ opacity: 0,
+ x: 140,
+ scale: 1.15,
+ duration: 0.9,
+ ease: 'power2.out'
+ }, 4.0);
+
+ tl.from('.section-2 .text-container', {
+ opacity: 0,
+ x: 90,
+ duration: 0.7,
+ ease: 'power3.out'
+ }, 4.24);
+
+ tl.to('.burst-2', {
+ scale: 18,
+ opacity: 0,
+ duration: 0.85,
+ ease: 'expo.out'
+ }, 7.5);
+
+ tl.to('.section-2', {
+ opacity: 0,
+ x: 260,
+ duration: 0.5,
+ ease: 'power2.in'
+ }, 7.5);
+
+ tl.to('.bg-shape', {
+ scale: 1.05,
+ duration: 2.1,
+ repeat: 1,
+ yoyo: true,
+ ease: 'sine.inOut'
+ }, 7.5);
+
+ window.__timelines["motion-graphics"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-16-prod/src/design_review.md b/packages/producer/tests/style-16-prod/src/design_review.md
new file mode 100644
index 0000000000..998b6223ba
--- /dev/null
+++ b/packages/producer/tests/style-16-prod/src/design_review.md
@@ -0,0 +1,51 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a high-budget punk-rock zine collided with a modern data visualization, and I don't hate it. The "Newsprint Tan" and aggressive red/black palette is a bold choice that actually has some soul, unlike the usual corporate blue-and-white garbage.
+
+---
+
+## CRITICAL Design Failures
+
+### The "Floating Head" Problem
+**Where:** `index.html` / `#aroll`
+**What's wrong:** The A-roll video is just a raw `object-fit: cover` rectangle that slides in and out like a sliding glass door. It’s jarringly literal and lacks any stylistic integration with the "Newsprint" aesthetic of the background.
+**Why it matters:** It breaks the immersion. You have this cool, textured, graphic world in the background, and then a clean, digital video just sits on top of it like a sticker that won't stick.
+**Fix it:** Add a mask or a rough-edge border to the `#aroll` video. Give it a slight CSS filter (maybe a tiny bit of grain or a subtle contrast boost) to make it feel like it belongs in the same universe as the background.
+
+### Typography Hierarchy Chaos
+**Where:** `compositions/motion-graphics.html`
+**What's wrong:** The `.stencil-text` is massive (280px) and the `.bold-text` is 64px. While I appreciate the aggression, the letter-spacing of `-10px` on the stencil text makes "47%" look like a tangled mess of geometry rather than a number.
+**Why it matters:** If I have to squint to realize that's a "4" and a "7", you've failed the most basic rule of design: communication.
+**Fix it:** Back off the negative letter-spacing to `-4px` or `-5px`. Let the glyphs breathe so they can actually be read at a glance.
+
+---
+
+## Design Improvements
+
+### The "Static" Background
+**Where:** `compositions/motion-graphics.html`
+**The problem:** The `.newsprint-texture` is a static SVG filter. In a video about *motion graphics*, having a static texture feels lazy.
+**Make it better:** Animate the `baseFrequency` of the SVG turbulence filter or just shift the background position slightly every few frames to create a "boiling" paper texture effect. It adds life to the "dead" space.
+
+### Caption Shadow Monotony
+**Where:** `compositions/captions.html`
+**The problem:** The `8px 8px 0px #CC0000` hard shadow is used on every single word. It’s a good look, but it becomes repetitive over 13 seconds.
+**Make it better:** Vary the shadow direction or offset based on the word's position or the "kinetic" entrance. If a word flies in from the left, the shadow should react.
+
+---
+
+## What Actually Works
+
+The **Color Palette** (`#E8DCC8`, `#CC0000`, `#000000`) is excellent. It feels tactile, urgent, and professional without being "tech-bro." The use of the diagonal grid and the wedge thrusts in the motion graphics layer provides a strong sense of direction and energy that matches the transcript's "problem/solution" narrative.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 8/10 - It grabs you by the throat immediately.
+**Color & Typography:** 7/10 - Great colors, but the typography is bordering on unreadable in its quest for "edge."
+**Motion & Animation Feel:** 6/10 - The GSAP transitions are smooth, but the A-roll movement is too linear and robotic.
+**Overall Aesthetic:** 7.5/10 - A strong, cohesive identity that just needs some "grit" and refinement.
+
+**Bottom Line:** This is 90% of the way to being a top-tier social ad. Fix the A-roll integration and stop strangling your kerning, and you'll have something worth showing.
diff --git a/packages/producer/tests/style-16-prod/src/index.html b/packages/producer/tests/style-16-prod/src/index.html
new file mode 100644
index 0000000000..0779d2e8c5
--- /dev/null
+++ b/packages/producer/tests/style-16-prod/src/index.html
@@ -0,0 +1,156 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Editor Agent Video</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body,
+ html {
+ margin: 0;
+ padding: 0;
+ background-color: #E8DCC8; /* Newsprint Tan */
+ overflow: hidden;
+ width: 1080px;
+ height: 1920px;
+ font-family: 'Montserrat', 'Arial Black', sans-serif;
+ }
+ #main-comp {
+ position: relative;
+ width: 1080px;
+ height: 1920px;
+ overflow: hidden;
+ background:
+ linear-gradient(180deg, #ECDDCA 0%, #E2D3BE 100%);
+ }
+ #motion-layer,
+ #captions-layer {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ pointer-events: none;
+ }
+ #motion-layer {
+ z-index: 20;
+ }
+ #aroll-frame {
+ position: absolute;
+ top: 112px;
+ left: 112px;
+ width: 856px;
+ height: 1328px;
+ overflow: hidden;
+ background: #0D0D0D;
+ border: 3px solid #151515;
+ box-shadow: 16px 16px 0 #CC0000;
+ z-index: 10;
+ }
+ #aroll-frame::before {
+ content: "";
+ position: absolute;
+ inset: 14px;
+ border: 1px solid rgba(232, 220, 200, 0.35);
+ z-index: 3;
+ pointer-events: none;
+ }
+ #aroll-frame::after {
+ content: "EDITOR AGENT / CUT 07";
+ position: absolute;
+ left: 18px;
+ top: 18px;
+ font-size: 18px;
+ letter-spacing: 0.22em;
+ color: rgba(232, 220, 200, 0.92);
+ z-index: 4;
+ }
+ #aroll {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ filter: contrast(1.08) saturate(0.9) brightness(0.98);
+ }
+ #aroll-frame img.__render_frame__,
+ #aroll-frame img.__preview_render_frame__ {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ filter: contrast(1.08) saturate(0.9) brightness(0.98);
+ }
+ #captions-layer {
+ z-index: 30;
+ }
+ </style>
+</head>
+<body>
+ <div id="main-comp" data-composition-id="main" data-width="1080" data-height="1920" data-start="0" data-duration="13.88">
+ <!-- Background/Motion Graphics Layer -->
+ <div id="motion-layer"
+ data-composition-id="motion-graphics"
+ data-composition-src="compositions/motion-graphics.html"
+ data-start="0"
+ data-duration="13.88"
+ data-track-index="1">
+ </div>
+
+ <!-- A-roll Video Layer -->
+ <div id="aroll-frame">
+ <video id="aroll"
+ data-start="0"
+ data-duration="13.88"
+ data-track-index="2"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/fba9969d_c8c30a7e22ac40029c24c5135d27df04.mp4">
+ </video>
+ </div>
+
+ <!-- Captions Layer -->
+ <div id="captions-layer"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="13.88"
+ data-track-index="3">
+ </div>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+
+ tl.fromTo('#aroll-frame', {
+ scale: 1.03,
+ y: 22
+ }, {
+ scale: 1,
+ y: 0,
+ duration: 0.85,
+ ease: "power2.out"
+ }, 0);
+
+ tl.to('#aroll-frame', {
+ x: 64,
+ duration: 0.65,
+ ease: "power2.inOut"
+ }, 1.5);
+
+ tl.to('#aroll-frame', {
+ x: -52,
+ duration: 0.7,
+ ease: "power2.inOut"
+ }, 4.0);
+
+ tl.to('#aroll-frame', {
+ x: 0,
+ duration: 0.65,
+ ease: "power2.out"
+ }, 7.5);
+
+ window.__timelines["main"] = tl;
+ </script>
+ </div>
+</body>
+</html>
diff --git a/packages/producer/tests/style-17-prod/meta.json b/packages/producer/tests/style-17-prod/meta.json
new file mode 100644
index 0000000000..675267fce8
--- /dev/null
+++ b/packages/producer/tests/style-17-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-17-prod",
+ "description": "Regression fixture imported from normalized style pack style-17-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "portrait"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-17-prod/src/assets/saul_bass_assets.svg b/packages/producer/tests/style-17-prod/src/assets/saul_bass_assets.svg
new file mode 100644
index 0000000000..807db6c61b
--- /dev/null
+++ b/packages/producer/tests/style-17-prod/src/assets/saul_bass_assets.svg
@@ -0,0 +1,32 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1080 1920" width="1080" height="1920">
+ <!-- Background -->
+ <rect width="1080" height="1920" fill="#000000" />
+
+ <!-- Tear Mask / Transition Shape -->
+ <path id="tear-mask" d="M 0 0 L 400 0 L 450 150 L 380 300 L 480 450 L 420 600 L 500 750 L 430 900 L 520 1050 L 450 1200 L 550 1350 L 480 1500 L 530 1650 L 460 1800 L 510 1920 L 0 1920 Z" fill="#FFF5DC" />
+
+ <!-- Silhouette -->
+ <g id="silhouette" fill="#FFF5DC">
+ <!-- Head -->
+ <polygon points="600,300 680,280 750,290 780,380 760,450 650,480 620,400" />
+ <!-- Torso -->
+ <polygon points="550,520 700,500 850,510 830,700 820,950 700,960 580,980 560,750" />
+ <!-- Arm L -->
+ <polygon points="450,550 530,540 520,650 500,800 420,780 440,660" />
+ <!-- Arm R -->
+ <polygon points="870,520 950,530 960,640 980,750 900,770 880,650" />
+ <!-- Leg L -->
+ <polygon points="600,1020 700,1000 690,1200 680,1400 580,1420 590,1220" />
+ <!-- Leg R -->
+ <polygon points="720,990 820,1010 830,1230 850,1450 750,1430 730,1210" />
+ </g>
+
+ <!-- Shapes -->
+ <polygon id="shape-orange-1" points="100,100 200,90 300,80 320,160 350,250 220,280 150,300 120,200" fill="#FF4500" />
+ <polygon id="shape-mustard-1" points="800,100 900,120 1000,150 980,250 950,350 850,320 750,300 780,200" fill="#E8A317" />
+
+ <polygon points="200,1500 300,1480 400,1450 420,1580 450,1700 350,1720 250,1750 220,1620" fill="#FF4500" />
+ <polygon points="700,1600 800,1580 900,1550 920,1680 950,1800 850,1820 750,1850 720,1720" fill="#E8A317" />
+ <polygon points="800,1100 900,1080 950,1150 920,1250 850,1280 780,1200" fill="#FF4500" />
+ <polygon points="150,800 250,780 300,850 280,950 180,980 120,900" fill="#E8A317" />
+</svg>
\ No newline at end of file
diff --git a/packages/producer/tests/style-17-prod/src/code_review.md b/packages/producer/tests/style-17-prod/src/code_review.md
new file mode 100644
index 0000000000..c66be23f50
--- /dev/null
+++ b/packages/producer/tests/style-17-prod/src/code_review.md
@@ -0,0 +1,50 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 4
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None found.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images used)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - absolute timing used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+### index.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None.
+
+### compositions/bg-graphics.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None.
+
+### compositions/data-viz.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None.
+
+### compositions/captions.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None.
diff --git a/packages/producer/tests/style-17-prod/src/compositions/bg-graphics.html b/packages/producer/tests/style-17-prod/src/compositions/bg-graphics.html
new file mode 100644
index 0000000000..0be1d24a3f
--- /dev/null
+++ b/packages/producer/tests/style-17-prod/src/compositions/bg-graphics.html
@@ -0,0 +1,227 @@
+<template id="bg-graphics-template">
+ <div data-composition-id="bg-graphics" data-width="1080" data-height="1920" data-duration="13.88">
+ <div class="bg-container">
+ <!-- Background Shapes -->
+ <div class="shape shape-1"></div>
+ <div class="shape shape-2"></div>
+ <div class="shape shape-3"></div>
+
+ <!-- Paper Cut Shapes (SVG) -->
+ <div class="paper-cuts">
+ <svg viewBox="0 0 1080 1920" class="svg-assets">
+ <path id="cut-1" d="M100,200 L400,150 L450,500 L150,550 Z" fill="#FF4500" />
+ <path id="cut-2" d="M600,800 L900,750 L950,1100 L650,1150 Z" fill="#E8A317" />
+ <path id="cut-3" d="M200,1300 L500,1250 L550,1600 L250,1650 Z" fill="#FFF5DC" />
+ </svg>
+ </div>
+
+ <!-- Fragmented Title -->
+ <div class="title-container">
+ <div class="title-part" id="part-E">E</div>
+ <div class="title-part" id="part-D">D</div>
+ <div class="title-part" id="part-I">I</div>
+ <div class="title-part" id="part-T">T</div>
+ <div class="title-part" id="part-O">O</div>
+ <div class="title-part" id="part-R">R</div>
+ <div class="title-space"></div>
+ <div class="title-part" id="part-A">A</div>
+ <div class="title-part" id="part-G">G</div>
+ <div class="title-part" id="part-E2">E</div>
+ <div class="title-part" id="part-N">N</div>
+ <div class="title-part" id="part-T2">T</div>
+ </div>
+
+ <!-- Tear Transitions -->
+ <div class="tear-container" id="tear-1">
+ <svg viewBox="0 0 1080 1920" preserveAspectRatio="none">
+ <path id="tear-path-1" d="M-100,0 L0,0 L50,400 L-20,800 L60,1200 L-10,1600 L40,1920 L-100,1920 Z" fill="#000000" />
+ </svg>
+ </div>
+ <div class="tear-container" id="tear-2">
+ <svg viewBox="0 0 1080 1920" preserveAspectRatio="none">
+ <path id="tear-path-2" d="M1180,0 L1080,0 L1030,400 L1100,800 L1020,1200 L1090,1600 L1040,1920 L1180,1920 Z" fill="#000000" />
+ </svg>
+ </div>
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=League+Gothic&display=swap');
+
+ [data-composition-id="bg-graphics"] {
+ width: 1080px;
+ height: 1920px;
+ background-color: transparent; /* Changed to transparent to see A-roll */
+ overflow: hidden;
+ position: relative;
+ font-family: 'League Gothic', sans-serif;
+ }
+
+ [data-composition-id="bg-graphics"] .bg-container {
+ width: 100%;
+ height: 100%;
+ position: absolute;
+ top: 0;
+ left: 0;
+ }
+
+ [data-composition-id="bg-graphics"] .shape {
+ position: absolute;
+ opacity: 0.3; /* Reduced from 0.6 */
+ }
+
+ [data-composition-id="bg-graphics"] .shape-1 {
+ width: 600px;
+ height: 800px;
+ background: #FF4500;
+ top: 10%;
+ left: -10%;
+ clip-path: polygon(10% 0%, 100% 20%, 90% 100%, 0% 80%);
+ }
+
+ [data-composition-id="bg-graphics"] .shape-2 {
+ width: 500px;
+ height: 700px;
+ background: #E8A317;
+ bottom: 15%;
+ right: -5%;
+ clip-path: polygon(0% 15%, 85% 0%, 100% 85%, 15% 100%);
+ }
+
+ [data-composition-id="bg-graphics"] .shape-3 {
+ width: 400px;
+ height: 400px;
+ background: #FFF5DC;
+ top: 40%;
+ left: 30%;
+ clip-path: polygon(20% 0%, 80% 10%, 100% 90%, 0% 100%);
+ }
+
+ [data-composition-id="bg-graphics"] .paper-cuts {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ top: 0;
+ left: 0;
+ pointer-events: none;
+ }
+
+ [data-composition-id="bg-graphics"] .svg-assets {
+ width: 100%;
+ height: 100%;
+ }
+
+ [data-composition-id="bg-graphics"] .title-container {
+ position: absolute;
+ top: 15%;
+ left: 10%;
+ display: flex;
+ flex-wrap: wrap;
+ width: 800px;
+ gap: 10px;
+ pointer-events: none;
+ }
+
+ [data-composition-id="bg-graphics"] .title-part {
+ font-size: 220px;
+ font-weight: 900;
+ color: #FFF5DC;
+ line-height: 0.8;
+ text-transform: uppercase;
+ filter: url(#rough-filter);
+ }
+
+ [data-composition-id="bg-graphics"] .title-space {
+ width: 100%;
+ height: 40px;
+ }
+
+ [data-composition-id="bg-graphics"] .tear-container {
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ z-index: 100;
+ }
+
+ [data-composition-id="bg-graphics"] #tear-1 { left: 0; }
+ [data-composition-id="bg-graphics"] #tear-2 { left: 0; }
+ </style>
+
+ <svg style="position: absolute; width: 0; height: 0;">
+ <filter id="rough-filter">
+ <feTurbulence type="fractalNoise" baseFrequency="0.05" numOctaves="2" result="noise" />
+ <feDisplacementMap in="SourceGraphic" in2="noise" scale="5" />
+ </filter>
+ </svg>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // Deterministic animations added to the timeline
+ tl.to('.shape-1', { x: 30, y: -20, rotation: 2, duration: 4, repeat: 3, yoyo: true, ease: "sine.inOut" }, 0);
+ tl.to('.shape-2', { x: -40, y: 30, rotation: -3, duration: 5, repeat: 2, yoyo: true, ease: "sine.inOut" }, 0);
+ tl.to('.shape-3', { scale: 1.1, rotation: 5, duration: 6, repeat: 2, yoyo: true, ease: "sine.inOut" }, 0);
+
+ tl.from('#cut-1', { x: -1000, y: -500, rotation: -45, duration: 1.5, ease: "power3.out" }, 0);
+ tl.from('#cut-2', { x: 1000, y: 500, rotation: 45, duration: 1.5, ease: "power3.out" }, 0.2);
+ tl.from('#cut-3', { scale: 0, opacity: 0, duration: 1.2, ease: "back.out(1.7)" }, 0.5);
+
+ const titleParts = document.querySelectorAll('.title-part');
+ tl.from(titleParts, {
+ opacity: 0,
+ y: (i) => (i % 2 === 0 ? -100 : 100),
+ x: (i) => (i % 3 === 0 ? -50 : 50),
+ rotation: (i) => (i % 2 === 0 ? -15 : 15),
+ duration: 0.8,
+ stagger: 0.05,
+ ease: "expo.out"
+ }, 1);
+
+ // Improved "snap" for tears
+ tl.to('#tear-path-1', {
+ attr: { d: "M-100,0 L1180,0 L1230,400 L1160,800 L1240,1200 L1170,1600 L1220,1920 L-100,1920 Z" },
+ duration: 0.4,
+ ease: "expo.in"
+ }, 3.4);
+ tl.set('#tear-path-1', { opacity: 0 }, 4.0);
+
+ // Exit Title and Squares after 3 seconds
+ tl.to(titleParts, {
+ opacity: 0,
+ scale: 0.5,
+ y: (i) => (i % 2 === 0 ? -200 : 200),
+ rotation: (i) => (i % 2 === 0 ? -45 : 45),
+ duration: 0.6,
+ stagger: 0.02,
+ ease: "power2.in"
+ }, 3.0);
+
+ tl.to(['#cut-1', '#cut-2', '#cut-3'], {
+ opacity: 0,
+ scale: 0,
+ x: (i) => (i === 0 ? -500 : 500),
+ duration: 0.6,
+ ease: "power2.in"
+ }, 3.0);
+
+ tl.fromTo('#tear-path-2',
+ { attr: { d: "M1180,0 L1080,0 L1030,400 L1100,800 L1020,1200 L1090,1600 L1040,1920 L1180,1920 Z" }, opacity: 1 },
+ {
+ attr: { d: "M1180,0 L-100,0 L-150,400 L-80,800 L-160,1200 L-90,1600 L-140,1920 L1180,1920 Z" },
+ duration: 0.4,
+ ease: "expo.in"
+ }, 7.0);
+ tl.set('#tear-path-2', { opacity: 0 }, 7.6);
+
+ // Final exit sequence (moved or kept for other elements if any)
+ // Since title and cuts already left at 3s, these are redundant but kept if they target other elements
+ // tl.to(titleParts, { ... }, 12.5);
+ // tl.to(['#cut-1', '#cut-2', '#cut-3'], { ... }, 12.8);
+
+ window.__timelines["bg-graphics"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-17-prod/src/compositions/captions.html b/packages/producer/tests/style-17-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..30677be01b
--- /dev/null
+++ b/packages/producer/tests/style-17-prod/src/compositions/captions.html
@@ -0,0 +1,157 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1080" data-height="1920" data-duration="13.88">
+ <div id="captions-container"></div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=League+Gothic&display=swap');
+
+ [data-composition-id="captions"] {
+ width: 1080px;
+ height: 1920px;
+ position: absolute;
+ top: 0;
+ left: 0;
+ display: flex;
+ flex-direction: column;
+ justify-content: center; /* Changed from flex-end to center */
+ align-items: center;
+ padding-top: 400px; /* Offset to move it up from the exact center if needed */
+ pointer-events: none;
+ }
+
+ #captions-container {
+ width: 900px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ }
+
+ .caption-group {
+ position: absolute;
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ opacity: 0;
+ bottom: 0;
+ }
+
+ .word-wrapper {
+ display: inline-block;
+ margin: 10px 15px;
+ position: relative;
+ overflow: visible;
+ }
+
+ .paper-cut {
+ background-color: #000;
+ padding: 20px 35px; /* Increased breathing room */
+ display: inline-block;
+ transform: rotate(var(--rotation));
+ clip-path: polygon(
+ 0% 10%, 20% 0%, 50% 5%, 80% 0%, 100% 10%,
+ 95% 40%, 100% 70%, 90% 100%, 50% 95%, 10% 100%,
+ 0% 70%, 5% 40%
+ ); /* Simplified clip-path for legibility */
+ box-shadow: 5px 5px 0px rgba(0,0,0,0.3);
+ }
+
+ .word-text {
+ font-family: 'League Gothic', sans-serif;
+ font-size: 110px;
+ text-transform: uppercase;
+ letter-spacing: -2px;
+ line-height: 0.9;
+ color: #FFF5DC;
+ }
+
+ .word-text.mustard {
+ color: #E8A317;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.14, 'end': 0.239}, {'text': 'asked', 'start': 0.28, 'end': 0.459}, {'text': 'what', 'start': 0.5, 'end': 0.619}, {'text': 'you', 'start': 0.659, 'end': 0.779}, {'text': 'needed.', 'start': 0.8, 'end': 1.179}, {'text': 'Forty-seven', 'start': 1.199, 'end': 1.619}, {'text': 'percent', 'start': 1.699, 'end': 1.96}, {'text': 'of', 'start': 1.979, 'end': 2.059}, {'text': 'you', 'start': 2.099, 'end': 2.299}, {'text': 'said', 'start': 2.319, 'end': 2.499}, {'text': 'motion', 'start': 2.559, 'end': 2.839}, {'text': 'graphics,', 'start': 2.899, 'end': 3.759}, {'text': 'sixty-two', 'start': 3.799, 'end': 4.159}, {'text': 'percent', 'start': 4.239, 'end': 4.559}, {'text': 'said', 'start': 4.639, 'end': 4.799}, {'text': 'static', 'start': 4.859, 'end': 5.199}, {'text': 'content', 'start': 5.239, 'end': 5.639}, {'text': 'was', 'start': 5.679, 'end': 5.779}, {'text': 'costing', 'start': 5.859, 'end': 6.219}, {'text': 'you', 'start': 6.259, 'end': 6.339}, {'text': 'attention,', 'start': 6.379, 'end': 7.299}, {'text': 'and', 'start': 7.319, 'end': 7.439}, {'text': 'three', 'start': 7.48, 'end': 7.599}, {'text': 'out', 'start': 7.679, 'end': 7.779}, {'text': 'of', 'start': 7.799, 'end': 7.879}, {'text': 'four', 'start': 7.94, 'end': 8.139}, {'text': 'said', 'start': 8.279, 'end': 8.46}, {'text': 'you', 'start': 8.519, 'end': 8.6}, {'text': 'know', 'start': 8.619, 'end': 8.739}, {'text': 'the', 'start': 8.8, 'end': 8.88}, {'text': 'look', 'start': 8.92, 'end': 9.079}, {'text': 'you', 'start': 9.119, 'end': 9.259}, {'text': 'want', 'start': 9.279, 'end': 9.619}, {'text': 'but', 'start': 9.779, 'end': 9.88}, {'text': "don't", 'start': 9.92, 'end': 10.1}, {'text': 'have', 'start': 10.159, 'end': 10.3}, {'text': 'the', 'start': 10.3, 'end': 10.42}, {'text': 'editing', 'start': 10.5, 'end': 10.779}, {'text': 'skills', 'start': 10.86, 'end': 11.139}, {'text': 'to', 'start': 11.159, 'end': 11.239}, {'text': 'get', 'start': 11.279, 'end': 11.439}, {'text': 'there.', 'start': 11.46, 'end': 12.239}, {'text': 'So', 'start': 12.3, 'end': 12.38}, {'text': 'we', 'start': 12.399, 'end': 12.519}, {'text': 'built', 'start': 12.539, 'end': 12.759}, {'text': 'Editor', 'start': 12.84, 'end': 13.119}, {'text': 'Agent.', 'start': 13.239, 'end': 13.84}];
+ const container = document.getElementById('captions-container');
+ const tl = gsap.timeline({ paused: true });
+
+ const groups = [];
+ let currentGroup = [];
+
+ TRANSCRIPT.forEach((word, index) => {
+ currentGroup.push(word);
+ if (currentGroup.length === 3 || index === TRANSCRIPT.length - 1) {
+ groups.push([...currentGroup]);
+ currentGroup = [];
+ }
+ });
+
+ groups.forEach((group, groupIndex) => {
+ const groupEl = document.createElement('div');
+ groupEl.className = 'caption-group';
+ groupEl.id = `group-${groupIndex}`;
+
+ group.forEach((wordData, wordIndex) => {
+ const wrapper = document.createElement('div');
+ wrapper.className = 'word-wrapper';
+
+ const paper = document.createElement('div');
+ paper.className = 'paper-cut';
+
+ const rotation = ((groupIndex * 7 + wordIndex * 13) % 4) - 2; // Reduced rotation variance to +/- 2 deg
+ paper.style.setProperty('--rotation', `${rotation}deg`);
+
+ const text = document.createElement('span');
+ text.className = 'word-text';
+ if ((groupIndex + wordIndex) % 3 === 0) {
+ text.classList.add('mustard');
+ }
+ text.textContent = wordData.text.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
+
+ paper.appendChild(text);
+ wrapper.appendChild(paper);
+ groupEl.appendChild(wrapper);
+ });
+
+ container.appendChild(groupEl);
+
+ const startTime = group[0].start;
+ const endTime = group[group.length - 1].end;
+
+ tl.set(groupEl, { opacity: 1 }, startTime);
+
+ // Add vertical movement to avoid blocking graphics
+ // 0-3s: Title/Squares are at top (15%)
+ // 3.7-7.3s: Data Viz is at center
+ if (startTime >= 3.7 && startTime <= 7.3) {
+ tl.to(groupEl, { y: 300, duration: 0.4, ease: "power2.inOut" }, startTime);
+ } else if (startTime < 3) {
+ tl.to(groupEl, { y: 200, duration: 0.4, ease: "power2.inOut" }, startTime);
+ } else {
+ tl.to(groupEl, { y: 0, duration: 0.4, ease: "power2.inOut" }, startTime);
+ }
+
+ const words = groupEl.querySelectorAll('.word-wrapper');
+ words.forEach((word, i) => {
+ tl.from(word, {
+ scale: 0,
+ rotation: (i % 2 === 0 ? 45 : -45),
+ x: (i % 2 === 0 ? -100 : 100),
+ y: (i % 2 === 0 ? 50 : -50),
+ duration: 0.4,
+ ease: "back.out(1.7)"
+ }, startTime + (i * 0.05));
+ });
+
+ tl.set(groupEl, { opacity: 0 }, endTime);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-17-prod/src/compositions/data-viz.html b/packages/producer/tests/style-17-prod/src/compositions/data-viz.html
new file mode 100644
index 0000000000..e88dccdcc8
--- /dev/null
+++ b/packages/producer/tests/style-17-prod/src/compositions/data-viz.html
@@ -0,0 +1,175 @@
+<template id="data-viz-template">
+ <div data-composition-id="data-viz" data-width="1080" data-height="1920" data-duration="3.6">
+ <div class="canvas-container">
+ <div class="bg-shape shape-1"></div>
+ <div class="bg-shape shape-2"></div>
+
+ <div class="content-wrapper">
+ <div class="stat-container">
+ <div class="number-wrapper">
+ <div class="number-fragment frag-1">6</div>
+ <div class="number-fragment frag-2">2</div>
+ <div class="number-fragment frag-3">%</div>
+ </div>
+ <div class="text-container">
+ <div class="text-line line-1">STATIC CONTENT</div>
+ <div class="text-line line-2">COSTING YOU ATTENTION</div>
+ </div>
+ </div>
+ </div>
+
+ <div class="tear-overlay"></div>
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=League+Gothic&display=swap');
+
+ [data-composition-id="data-viz"] {
+ width: 1080px;
+ height: 1920px;
+ background-color: transparent; /* Changed to transparent to see A-roll */
+ overflow: hidden;
+ font-family: 'League Gothic', sans-serif;
+ color: #FFF5DC;
+ }
+
+ [data-composition-id="data-viz"] .canvas-container {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ }
+
+ [data-composition-id="data-viz"] .bg-shape {
+ position: absolute;
+ background-color: #FF4500;
+ opacity: 0.4; /* Reduced from 0.8 */
+ }
+
+ [data-composition-id="data-viz"] .shape-1 {
+ width: 600px;
+ height: 800px;
+ top: 10%;
+ left: -10%;
+ transform: rotate(-15deg);
+ clip-path: polygon(0% 0%, 100% 5%, 95% 95%, 5% 100%);
+ }
+
+ [data-composition-id="data-viz"] .shape-2 {
+ width: 500px;
+ height: 600px;
+ bottom: 5%;
+ right: -5%;
+ background-color: #E8A317;
+ transform: rotate(10deg);
+ clip-path: polygon(5% 10%, 95% 0%, 100% 90%, 10% 100%);
+ }
+
+ [data-composition-id="data-viz"] .content-wrapper {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ z-index: 10;
+ }
+
+ [data-composition-id="data-viz"] .stat-container {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 40px;
+ }
+
+ [data-composition-id="data-viz"] .number-wrapper {
+ display: flex;
+ font-size: 300px; /* Reduced from 400px */
+ font-weight: 900;
+ color: #FFF5DC;
+ line-height: 1;
+ }
+
+ [data-composition-id="data-viz"] .number-fragment {
+ position: relative;
+ display: inline-block;
+ padding: 0 10px;
+ }
+
+ [data-composition-id="data-viz"] .frag-1 { transform: rotate(-5deg) translateY(20px); }
+ [data-composition-id="data-viz"] .frag-2 { transform: rotate(3deg) translateY(-10px); }
+ [data-composition-id="data-viz"] .frag-3 {
+ font-size: 200px;
+ align-self: flex-end;
+ margin-bottom: 40px;
+ color: #E8A317;
+ }
+
+ [data-composition-id="data-viz"] .text-container {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 20px;
+ }
+
+ [data-composition-id="data-viz"] .text-line {
+ font-size: 84px;
+ font-weight: bold;
+ background-color: #FFF5DC;
+ color: #000000;
+ padding: 10px 30px;
+ transform: rotate(-2deg);
+ clip-path: polygon(2% 5%, 98% 0%, 100% 95%, 0% 100%);
+ }
+
+ [data-composition-id="data-viz"] .line-2 {
+ background-color: #E8A317;
+ transform: rotate(1.5deg) translateY(60px); /* Added translateY to move it lower */
+ font-size: 62px;
+ }
+
+ [data-composition-id="data-viz"] .tear-overlay {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-color: #000000;
+ z-index: 100;
+ clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ tl.to('[data-composition-id="data-viz"] .tear-overlay', {
+ duration: 0.6,
+ clipPath: 'polygon(0% 0%, 0% 0%, 0% 100%, 0% 100%)',
+ ease: 'power4.inOut'
+ }, 0);
+
+ tl.to('[data-composition-id="data-viz"] .shape-1', { rotation: -12, x: 20, y: -10, duration: 3.6, ease: 'none' }, 0);
+ tl.to('[data-composition-id="data-viz"] .shape-2', { rotation: 13, x: -15, y: 15, duration: 3.6, ease: 'none' }, 0);
+
+ tl.set('[data-composition-id="data-viz"] .number-fragment', { opacity: 0, scale: 1.5, y: 100 }, 0);
+ tl.to('[data-composition-id="data-viz"] .frag-1', { opacity: 1, scale: 1, y: 20, duration: 0.5, ease: 'back.out(1.7)' }, 0.099);
+ tl.to('[data-composition-id="data-viz"] .frag-2', { opacity: 1, scale: 1, y: -10, duration: 0.5, ease: 'back.out(1.7)' }, 0.199);
+ tl.to('[data-composition-id="data-viz"] .frag-3', { opacity: 1, scale: 1, y: 0, duration: 0.5, ease: 'back.out(1.7)' }, 0.299);
+
+ tl.set('[data-composition-id="data-viz"] .line-1', { opacity: 0, x: -100, rotation: -10 }, 0);
+ tl.to('[data-composition-id="data-viz"] .line-1', { opacity: 1, x: 0, rotation: -2, duration: 0.6, ease: 'power3.out' }, 1.159);
+
+ tl.set('[data-composition-id="data-viz"] .line-2', { opacity: 0, x: 100, rotation: 10 }, 0);
+ tl.to('[data-composition-id="data-viz"] .line-2', { opacity: 1, x: 0, y: 60, rotation: 1.5, duration: 0.6, ease: 'power3.out' }, 2.159);
+
+ tl.to('[data-composition-id="data-viz"] .content-wrapper', { opacity: 0, scale: 0.9, duration: 0.3, ease: 'power2.in' }, 3.3);
+
+ window.__timelines["data-viz"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-17-prod/src/design_review.md b/packages/producer/tests/style-17-prod/src/design_review.md
new file mode 100644
index 0000000000..ca206a7341
--- /dev/null
+++ b/packages/producer/tests/style-17-prod/src/design_review.md
@@ -0,0 +1,61 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a Saul Bass tribute act that forgot the "tribute" and went straight to "parody." It’s a chaotic mess of paper-cut aesthetics that lacks the sophisticated restraint of the master.
+
+---
+
+## CRITICAL Design Failures
+
+Issues that make this look unprofessional or straight-up ugly. These MUST be fixed.
+
+### The "Everything Everywhere All At Once" Layout
+**Where:** `index.html` / `compositions/captions.html`
+**What's wrong:** You have a background layer, an A-roll video, a data-viz overlay, and captions all fighting for the same real estate. The captions are centered and moved up by 400px (`padding-top: 400px`), which puts them right in the middle of the frame where the A-roll subject's face likely is.
+**Why it matters:** It’s visual claustrophobia. The viewer doesn't know where to look, and the most important information (the speaker and the text) are literally on top of each other.
+**Fix it:** Move the captions to the bottom third. If you want to be "edgy," offset them to the left or right, but stop trying to make them the center of the universe.
+
+### Contrast Suicide
+**Where:** `compositions/data-viz.html`
+**What's wrong:** You’re using `#FFF5DC` (Cream) text on top of `#E8A317` (Mustard) and `#FF4500` (Orange) shapes with 40% opacity.
+**Why it matters:** The contrast ratio is abysmal. It’s a muddy, vibrating mess that is physically painful to read. Saul Bass used high-contrast, bold colors for a reason—not this washed-out "vintage filter" nonsense.
+**Fix it:** Use black (`#000000`) for text when it's over the mustard or orange shapes. Keep the cream for the background or very specific highlights.
+
+### Robotic "Organic" Shapes
+**Where:** `compositions/bg-graphics.html`
+**What's wrong:** Your `clip-path` polygons are too geometric. A 4-point polygon (`polygon(10% 0%, 100% 20%, 90% 100%, 0% 80%)`) doesn't look like hand-cut paper; it looks like a CSS developer who discovered the `clip-path` property five minutes ago.
+**Why it matters:** The Saul Bass aesthetic relies on the "imperfection of the human hand." These shapes feel sterile and digital, which completely breaks the illusion.
+**Fix it:** Add more points to your polygons. Make them irregular. Use the `rough-filter` you already defined in the SVG more aggressively across ALL shapes, not just the title.
+
+---
+
+## Design Improvements
+
+Things that aren't broken but are boring, lazy, or could be significantly better.
+
+### Typography Hierarchy is Non-Existent
+**Where:** `compositions/captions.html`
+**The problem:** Every word is 110px. Every word is uppercase. Every word is League Gothic. It’s a wall of shouting.
+**Make it better:** Vary the font sizes. Make the "Mustard" words 20% larger than the cream ones. Give the keywords some actual weight so the eye knows what to prioritize.
+
+### The "Tear" Transition is a Gimmick
+**Where:** `compositions/bg-graphics.html`
+**The problem:** The tear animation (`#tear-path-1`) is a simple linear slide. It’s predictable and lacks the "snap" of a real paper tear.
+**Make it better:** Use a more aggressive easing (like `back.in` or a custom elastic ease) and add a slight "shake" or "jitter" to the path as it moves. A tear isn't a sliding door; it's a violent separation.
+
+---
+
+## What Actually Works
+
+The **color palette** (`#FF4500`, `#E8A317`, `#FFF5DC`) is actually a solid foundation. It captures that mid-century modern warmth perfectly. If you can stop burying it under bad layout choices, it might actually look professional. The **staggered title animation** in `bg-graphics.html` is also a rare moment of competence—the `expo.out` ease gives it a nice "pop."
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 4/10 - It tries hard but fails to land the landing.
+**Color & Typography:** 5/10 - Good colors, but the typography is a monotonous wall of noise.
+**Motion & Animation Feel:** 6/10 - The GSAP work is technically sound, but the "feel" is too digital for the "analog" style.
+**Overall Aesthetic:** 4/10 - It feels like a template, not a composition.
+
+**Bottom Line:** This looks like a student project from someone who read a Wikipedia article on Saul Bass but never actually looked at his posters. Fix the contrast and the layout before you show this to anyone with eyes.
diff --git a/packages/producer/tests/style-17-prod/src/index.html b/packages/producer/tests/style-17-prod/src/index.html
new file mode 100644
index 0000000000..e0397e1b25
--- /dev/null
+++ b/packages/producer/tests/style-17-prod/src/index.html
@@ -0,0 +1,76 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Editor Agent - Saul Bass Style</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1080px;
+ height: 1920px;
+ background: #000000;
+ overflow: hidden;
+ }
+ #main-composition {
+ width: 1080px;
+ height: 1920px;
+ position: relative;
+ }
+ video {
+ width: 1080px;
+ height: 1920px;
+ object-fit: cover;
+ position: absolute;
+ top: 0;
+ left: 0;
+ }
+ </style>
+</head>
+<body>
+ <div id="main-composition" data-composition-id="main-video" data-width="1080" data-height="1920" data-duration="13.88">
+ <!-- Background Graphics (Track 1) -->
+ <div id="bg-layer"
+ data-composition-id="bg-graphics"
+ data-composition-src="compositions/bg-graphics.html"
+ data-start="0"
+ data-duration="13.88"
+ data-track-index="1">
+ </div>
+
+ <!-- Continuous A-roll Video (Track 0 - Base Layer) -->
+ <video id="aroll-continuous"
+ data-start="0"
+ data-duration="13.88"
+ data-track-index="0"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/64b11740_ce531703293e4dbfa1de029a692e93e4.mp4">
+ </video>
+
+ <!-- Data Visualization Overlay (Track 2 - Covers A-roll 3.7s-7.3s) -->
+ <div id="data-layer"
+ data-composition-id="data-viz"
+ data-composition-src="compositions/data-viz.html"
+ data-start="3.7"
+ data-duration="3.6"
+ data-track-index="2">
+ </div>
+
+ <!-- Captions Layer (Track 3) -->
+ <div id="captions-layer"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="13.88"
+ data-track-index="3">
+ </div>
+ </div>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+ // Main orchestration timeline
+ window.__timelines["main-video"] = tl;
+ </script>
+</body>
+</html>
diff --git a/packages/producer/tests/style-18-prod/meta.json b/packages/producer/tests/style-18-prod/meta.json
new file mode 100644
index 0000000000..8c531d1a1b
--- /dev/null
+++ b/packages/producer/tests/style-18-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-18-prod",
+ "description": "Regression fixture imported from normalized style pack style-18-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "portrait"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-18-prod/src/code_review.md b/packages/producer/tests/style-18-prod/src/code_review.md
new file mode 100644
index 0000000000..2b503b9d4f
--- /dev/null
+++ b/packages/producer/tests/style-18-prod/src/code_review.md
@@ -0,0 +1,50 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 4
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None. The compositions follow the core requirements for deterministic execution, finite timelines, and proper registration.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images used)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - absolute timing used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+### index.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. The root composition correctly orchestrates sub-compositions and the A-roll video.
+
+### compositions/background-grid.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Uses deterministic loops and index-based calculations for animations. Correctly registers its timeline.
+
+### compositions/stats-overlay.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Uses a static transcript for timing and follows the schema for sub-compositions.
+
+### compositions/captions.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Correctly wraps dynamic caption groups within a composition and manages them via script.
diff --git a/packages/producer/tests/style-18-prod/src/compositions/background-grid.html b/packages/producer/tests/style-18-prod/src/compositions/background-grid.html
new file mode 100644
index 0000000000..b3ec066d62
--- /dev/null
+++ b/packages/producer/tests/style-18-prod/src/compositions/background-grid.html
@@ -0,0 +1,216 @@
+<template id="background-grid-template">
+ <div data-composition-id="background-grid" data-width="1080" data-height="1920" data-duration="14">
+ <div class="canvas-container">
+ <!-- Washes -->
+ <div class="wash blush" id="wash-blush"></div>
+ <div class="wash gold" id="wash-gold"></div>
+
+ <!-- Grid -->
+ <div class="grid-container" id="grid-container">
+ <!-- Grid lines will be generated by script -->
+ </div>
+
+ <!-- Horizontal Banding -->
+ <div class="banding-container" id="banding-container">
+ <!-- Bands will be generated by script -->
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="background-grid"] {
+ width: 1080px;
+ height: 1920px;
+ background-color: #F5F0E8; /* Pale Linen */
+ overflow: hidden;
+ position: relative;
+ }
+
+ [data-composition-id="background-grid"] .canvas-container {
+ width: 100%;
+ height: 100%;
+ position: absolute;
+ top: 0;
+ left: 0;
+ }
+
+ [data-composition-id="background-grid"] .wash {
+ position: absolute;
+ width: 120%;
+ height: 120%;
+ top: -10%;
+ left: -10%;
+ filter: blur(100px);
+ opacity: 0.15;
+ pointer-events: none;
+ }
+
+ [data-composition-id="background-grid"] .wash.blush {
+ background: radial-gradient(circle, #E8D0C0 0%, transparent 70%);
+ transform: translate(-10%, -10%);
+ }
+
+ [data-composition-id="background-grid"] .wash.gold {
+ background: radial-gradient(circle, #E5D9B0 0%, transparent 70%);
+ transform: translate(10%, 10%);
+ }
+
+ [data-composition-id="background-grid"] .grid-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ }
+
+ [data-composition-id="background-grid"] .grid-line {
+ position: absolute;
+ background-color: #444444; /* Darkened Soft Graphite */
+ opacity: 0.6; /* Increased opacity for visibility */
+ }
+
+ [data-composition-id="background-grid"] .grid-line.horizontal {
+ width: 100%;
+ height: 0.5px;
+ }
+
+ [data-composition-id="background-grid"] .grid-line.vertical {
+ width: 0.5px;
+ height: 100%;
+ }
+
+ [data-composition-id="background-grid"] .banding-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ }
+
+ [data-composition-id="background-grid"] .band {
+ position: absolute;
+ width: 100%;
+ height: 128px; /* 1920 / 15 */
+ background-color: #E5D9B0;
+ opacity: 0;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const compId = "background-grid";
+ const container = document.querySelector(`[data-composition-id="${compId}"]`);
+ const gridContainer = container.querySelector('#grid-container');
+ const bandingContainer = container.querySelector('#banding-container');
+
+ const ROWS = 15;
+ const COLS = 10;
+ const WIDTH = 1080;
+ const HEIGHT = 1920;
+ const CELL_W = WIDTH / COLS;
+ const CELL_H = HEIGHT / ROWS;
+
+ // Create Grid Lines
+ // Horizontal lines
+ for (let i = 0; i <= ROWS; i++) {
+ const line = document.createElement('div');
+ line.className = 'grid-line horizontal';
+ line.style.top = `${i * CELL_H}px`;
+ gridContainer.appendChild(line);
+ }
+
+ // Vertical lines
+ for (let i = 0; i <= COLS; i++) {
+ const line = document.createElement('div');
+ line.className = 'grid-line vertical';
+ line.style.left = `${i * CELL_W}px`;
+ gridContainer.appendChild(line);
+ }
+
+ // Create Bands
+ for (let i = 0; i < ROWS; i++) {
+ const band = document.createElement('div');
+ band.className = 'band';
+ band.style.top = `${i * CELL_H}px`;
+ // Alternate colors deterministically
+ band.style.backgroundColor = i % 2 === 0 ? '#E8D0C0' : '#E5D9B0';
+ bandingContainer.appendChild(band);
+ }
+
+ const tl = gsap.timeline({ paused: true });
+
+ // 1. Ambient Wash Motion
+ tl.to('#wash-blush', {
+ x: '5%',
+ y: '5%',
+ duration: 7,
+ ease: 'sine.inOut',
+ yoyo: true,
+ repeat: 1
+ }, 0);
+
+ tl.to('#wash-gold', {
+ x: '-5%',
+ y: '-5%',
+ duration: 7,
+ ease: 'sine.inOut',
+ yoyo: true,
+ repeat: 1
+ }, 0);
+
+ // 2. Grid Breathing (Opacity and Shift)
+ const hLines = container.querySelectorAll('.grid-line.horizontal');
+ const vLines = container.querySelectorAll('.grid-line.vertical');
+
+ hLines.forEach((line, i) => {
+ // Deterministic variation based on index
+ const duration = 4 + (i % 3);
+ const delay = (i % 5) * 0.2;
+
+ tl.to(line, {
+ opacity: 0.6,
+ y: 1.5,
+ duration: duration,
+ ease: 'sine.inOut',
+ yoyo: true,
+ repeat: Math.floor(14 / (duration * 2)) + 1
+ }, delay);
+ });
+
+ vLines.forEach((line, i) => {
+ const duration = 5 + (i % 2);
+ const delay = (i % 4) * 0.3;
+
+ tl.to(line, {
+ opacity: 0.2,
+ x: 1.5,
+ duration: duration,
+ ease: 'sine.inOut',
+ yoyo: true,
+ repeat: Math.floor(14 / (duration * 2)) + 1
+ }, delay);
+ });
+
+ // 3. Horizontal Banding Pulse
+ const bands = container.querySelectorAll('.band');
+ bands.forEach((band, i) => {
+ const duration = 6 + (i % 4);
+ const delay = (i % 6) * 0.5;
+
+ tl.to(band, {
+ opacity: 0.08,
+ duration: duration,
+ ease: 'sine.inOut',
+ yoyo: true,
+ repeat: Math.floor(14 / (duration * 2)) + 1
+ }, delay);
+ });
+
+ // Ensure timeline is exactly 14s or slightly more for buffer
+ // tl.to({}, { duration: 0.1 }, 14); // Removed redundant empty tween
+
+ window.__timelines[compId] = tl;
+ })();
+ </script>
+ </div>
+</template>
\ No newline at end of file
diff --git a/packages/producer/tests/style-18-prod/src/compositions/captions.html b/packages/producer/tests/style-18-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..39f40d4e84
--- /dev/null
+++ b/packages/producer/tests/style-18-prod/src/compositions/captions.html
@@ -0,0 +1,87 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1080" data-height="1920" data-duration="14">
+ <div id="captions-container">
+ <!-- Caption groups will be rendered here -->
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=EB+Garamond:wght@400&display=swap');
+
+ [data-composition-id="captions"] {
+ width: 1080px;
+ height: 1920px;
+ display: flex;
+ justify-content: center;
+ align-items: flex-start;
+ background: transparent;
+ font-family: 'EB Garamond', serif;
+ text-transform: lowercase;
+ color: #999999; /* Soft Graphite */
+ }
+
+ [data-composition-id="captions"] #captions-container {
+ position: absolute;
+ top: 1450px; /* Moved up from 1600px to avoid UI overlap */
+ width: 900px; /* Centered with margins */
+ text-align: center;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ }
+
+ [data-composition-id="captions"] .caption-group {
+ position: absolute;
+ width: 100%;
+ font-size: 64px; /* Increased from 52px for better readability */
+ line-height: 1.2;
+ letter-spacing: 0.02em;
+ opacity: 0;
+ padding: 10px 20px;
+ border-radius: 4px;
+ color: #333333; /* Darker for better contrast */
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const container = document.querySelector('[data-composition-id="captions"] #captions-container');
+
+ const captionGroups = [
+ { text: "we asked what you needed.", start: 0.14, end: 1.18 },
+ { text: "forty-seven percent of you said motion graphics,", start: 1.20, end: 3.76 },
+ { text: "sixty-two percent said static content was costing you attention,", start: 3.80, end: 7.30 },
+ { text: "and three out of four said you know the look you want", start: 7.32, end: 9.62 },
+ { text: "but don't have the editing skills to get there.", start: 9.78, end: 12.24 },
+ { text: "so we built editor agent", start: 12.30, end: 13.84 }
+ ];
+
+ captionGroups.forEach((group, index) => {
+ const div = document.createElement('div');
+ div.className = 'caption-group';
+ div.id = `group-${index}`;
+ div.textContent = group.text;
+ container.appendChild(div);
+
+ const fadeDuration = 0.2;
+
+ // Fade in
+ tl.to(div, {
+ opacity: 1,
+ duration: fadeDuration,
+ ease: "power2.out"
+ }, group.start);
+
+ // Fade out
+ tl.to(div, {
+ opacity: 0,
+ duration: fadeDuration,
+ ease: "power2.in"
+ }, group.end - fadeDuration);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-18-prod/src/compositions/stats-overlay.html b/packages/producer/tests/style-18-prod/src/compositions/stats-overlay.html
new file mode 100644
index 0000000000..db18c9db0c
--- /dev/null
+++ b/packages/producer/tests/style-18-prod/src/compositions/stats-overlay.html
@@ -0,0 +1,217 @@
+<template id="stats-overlay-template">
+ <div data-composition-id="stats-overlay" data-width="1080" data-height="1920" data-duration="14">
+ <div class="container">
+ <!-- Grid/Lines for Agnes Martin aesthetic -->
+ <div class="grid-lines">
+ <div class="line horizontal h1"></div>
+ <div class="line horizontal h2"></div>
+ <div class="line vertical v1"></div>
+ <div class="line vertical v2"></div>
+ </div>
+
+ <!-- Stat 1: 47% -->
+ <div class="stat-group" id="stat-1">
+ <div class="number">47%</div>
+ <div class="subtitle">needed motion graphics</div>
+ </div>
+
+ <!-- Stat 2: 62% -->
+ <div class="stat-group" id="stat-2">
+ <div class="number">62%</div>
+ <div class="subtitle">static content reduces engagement</div>
+ </div>
+
+ <!-- Stat 3: 75% -->
+ <div class="stat-group" id="stat-3">
+ <div class="number">75%</div>
+ <div class="subtitle">lack technical skills</div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="stats-overlay"] {
+ font-family: "EB Garamond", "Garamond", serif;
+ color: #444444; /* Darkened Soft Graphite for better contrast */
+ background: transparent;
+ }
+
+ [data-composition-id="stats-overlay"] .container {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ }
+
+ /* Agnes Martin Aesthetic: Delicate lines */
+ [data-composition-id="stats-overlay"] .grid-lines {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ }
+
+ [data-composition-id="stats-overlay"] .line {
+ position: absolute;
+ background-color: #E5D9B0; /* Pale Gold */
+ opacity: 0.6; /* Increased opacity for visibility */
+ }
+
+ [data-composition-id="stats-overlay"] .horizontal {
+ width: 100%;
+ height: 1px;
+ }
+
+ [data-composition-id="stats-overlay"] .vertical {
+ width: 1px;
+ height: 100%;
+ }
+
+ /* Positioning lines to create a subtle grid */
+ [data-composition-id="stats-overlay"] .h1 { top: 20%; }
+ [data-composition-id="stats-overlay"] .h2 { bottom: 20%; }
+ [data-composition-id="stats-overlay"] .v1 { left: 15%; }
+ [data-composition-id="stats-overlay"] .v2 { right: 15%; }
+
+ [data-composition-id="stats-overlay"] .stat-group {
+ position: absolute;
+ opacity: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ }
+
+ /* Avoid face: x: 300-776, y: 320-796 */
+ /* Stat 1 & 2: Positioned to the left or right of the face area */
+ #stat-1 {
+ top: 480px; /* Aligned to grid row 4 (1920/15 * 3.75) */
+ left: 108px; /* Aligned to grid col 1 (1080/10 * 1) */
+ }
+
+ #stat-2 {
+ top: 896px; /* Aligned to grid row 7 (1920/15 * 7) */
+ right: 108px; /* Aligned to grid col 9 (1080/10 * 1) */
+ align-items: flex-end;
+ text-align: right;
+ }
+
+ /* Stat 3: Full canvas moment, centered but avoiding the face if it were there (though A-roll is hidden) */
+ #stat-3 {
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ align-items: center;
+ text-align: center;
+ width: 80%;
+ }
+
+ [data-composition-id="stats-overlay"] .number {
+ font-size: 220px; /* Slightly increased from 200px */
+ font-weight: 200;
+ line-height: 1;
+ margin-bottom: 10px;
+ }
+
+ [data-composition-id="stats-overlay"] .subtitle {
+ font-size: 64px; /* Increased from 32px for better hierarchy */
+ font-style: italic;
+ color: #C29B8A; /* Darkened Blush for better contrast */
+ text-transform: lowercase;
+ letter-spacing: 0.05em;
+ }
+
+ #stat-3 .number {
+ font-size: 320px; /* Slightly increased from 280px */
+ color: #C29B8A; /* Darkened Blush */
+ }
+
+ #stat-3 .subtitle {
+ font-size: 80px; /* Increased from 44px */
+ color: #444444;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.14, 'end': 0.239}, {'text': 'asked', 'start': 0.28, 'end': 0.459}, {'text': 'what', 'start': 0.5, 'end': 0.619}, {'text': 'you', 'start': 0.659, 'end': 0.779}, {'text': 'needed.', 'start': 0.8, 'end': 1.179}, {'text': 'Forty-seven', 'start': 1.199, 'end': 1.619}, {'text': 'percent', 'start': 1.699, 'end': 1.96}, {'text': 'of', 'start': 1.979, 'end': 2.059}, {'text': 'you', 'start': 2.099, 'end': 2.299}, {'text': 'said', 'start': 2.319, 'end': 2.499}, {'text': 'motion', 'start': 2.559, 'end': 2.839}, {'text': 'graphics,', 'start': 2.899, 'end': 3.759}, {'text': 'sixty-two', 'start': 3.799, 'end': 4.159}, {'text': 'percent', 'start': 4.239, 'end': 4.559}, {'text': 'said', 'start': 4.639, 'end': 4.799}, {'text': 'static', 'start': 4.859, 'end': 5.199}, {'text': 'content', 'start': 5.239, 'end': 5.639}, {'text': 'was', 'start': 5.679, 'end': 5.779}, {'text': 'costing', 'start': 5.859, 'end': 6.219}, {'text': 'you', 'start': 6.259, 'end': 6.339}, {'text': 'attention,', 'start': 6.379, 'end': 7.299}, {'text': 'and', 'start': 7.319, 'end': 7.439}, {'text': 'three', 'start': 7.48, 'end': 7.599}, {'text': 'out', 'start': 7.679, 'end': 7.779}, {'text': 'of', 'start': 7.799, 'end': 7.879}, {'text': 'four', 'start': 7.94, 'end': 8.139}, {'text': 'said', 'start': 8.279, 'end': 8.46}, {'text': 'you', 'start': 8.519, 'end': 8.6}, {'text': 'know', 'start': 8.619, 'end': 8.739}, {'text': 'the', 'start': 8.8, 'end': 8.88}, {'text': 'look', 'start': 8.92, 'end': 9.079}, {'text': 'you', 'start': 9.119, 'end': 9.259}, {'text': 'want', 'start': 9.279, 'end': 9.619}, {'text': 'but', 'start': 9.779, 'end': 9.88}, {'text': "don't", 'start': 9.92, 'end': 10.1}, {'text': 'have', 'start': 10.159, 'end': 10.3}, {'text': 'the', 'start': 10.3, 'end': 10.42}, {'text': 'editing', 'start': 10.5, 'end': 10.779}, {'text': 'skills', 'start': 10.86, 'end': 11.139}, {'text': 'to', 'start': 11.159, 'end': 11.239}, {'text': 'get', 'start': 11.279, 'end': 11.439}, {'text': 'there.', 'start': 11.46, 'end': 12.239}, {'text': 'So', 'start': 12.3, 'end': 12.38}, {'text': 'we', 'start': 12.399, 'end': 12.519}, {'text': 'built', 'start': 12.539, 'end': 12.759}, {'text': 'Editor', 'start': 12.84, 'end': 13.119}, {'text': 'Agent', 'start': 13.239, 'end': 13.839}];
+ const tl = gsap.timeline({ paused: true });
+
+ // Helper to find transcript times
+ function getWordTime(text, type = 'start') {
+ const word = TRANSCRIPT.find(w => w.text.toLowerCase().includes(text.toLowerCase()));
+ return word ? word[type] : null;
+ }
+
+ // 1. "47% Motion Graphics" (1.2s to 3.7s)
+ const start1 = 1.2;
+ const end1 = 3.7;
+
+ tl.to('#stat-1', {
+ opacity: 1,
+ scale: 1.05,
+ duration: 1.5,
+ ease: "power2.out"
+ }, start1);
+
+ tl.to('#stat-1', {
+ opacity: 0,
+ duration: 0.5,
+ ease: "power2.in"
+ }, end1);
+
+ // 2. "62% Static Content" (3.8s to 7.3s)
+ const start2 = 3.8;
+ const end2 = 7.3;
+
+ tl.to('#stat-2', {
+ opacity: 1,
+ scale: 1.05,
+ duration: 1.5,
+ ease: "power2.out"
+ }, start2);
+
+ tl.to('#stat-2', {
+ opacity: 0,
+ duration: 0.5,
+ ease: "power2.in"
+ }, end2);
+
+ // 3. "75% Editing Skills" (7.4s to 12.2s) - Full Canvas Moment
+ const start3 = 7.4;
+ const end3 = 12.2;
+
+ // Animate grid lines expanding for the full canvas moment
+ tl.to('.h1', { top: '10%', duration: 1, ease: "power2.out" }, start3);
+ tl.to('.h2', { bottom: '10%', duration: 1, ease: "power2.out" }, start3);
+ tl.to('.v1', { left: '5%', duration: 1, ease: "power2.out" }, start3);
+ tl.to('.v2', { right: '5%', duration: 1, ease: "power2.out" }, start3);
+
+ tl.to('#stat-3', {
+ opacity: 1,
+ scale: 1.1,
+ duration: 2,
+ ease: "power2.out"
+ }, start3);
+
+ // Subtle background line animation during the big moment
+ tl.to('.line', {
+ opacity: 0.8,
+ duration: 2,
+ stagger: 0.2,
+ ease: "sine.inOut"
+ }, start3);
+
+ tl.to('#stat-3', {
+ opacity: 0,
+ duration: 0.8,
+ ease: "power2.in"
+ }, end3);
+
+ // Buffer at the end - Removed redundant empty tween
+
+ window.__timelines["stats-overlay"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-18-prod/src/design_review.md b/packages/producer/tests/style-18-prod/src/design_review.md
new file mode 100644
index 0000000000..816fe813cc
--- /dev/null
+++ b/packages/producer/tests/style-18-prod/src/design_review.md
@@ -0,0 +1,59 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a high-end museum exhibit had a baby with a spreadsheet, and then someone forgot to turn the lights on. It’s "Agnes Martin" inspired, which is a polite way of saying it's dangerously close to being invisible.
+
+---
+
+## CRITICAL Design Failures
+
+### The "Ghost" Contrast Ratio
+**Where:** `compositions/background-grid.html`, `compositions/stats-overlay.html`
+**What's wrong:** You're using `#F5F0E8` (Pale Linen) for the background and `#999999` (Soft Graphite) or `#E5D9B0` (Pale Gold) for critical UI elements. On a mobile screen, in anything other than a pitch-black room, this is going to look like a blank screen. The grid lines at `0.4` opacity are practically non-existent.
+**Why it matters:** If the viewer has to squint to see your "aesthetic," they aren't looking at your content—they're wondering if their screen is broken.
+**Fix it:** Punch up the contrast. If you want to keep the "soft" look, darken the graphite to `#444444` (which you started to do in some places, but not consistently) and make those grid lines actually visible.
+
+### Typography Hierarchy is a Mess
+**Where:** `compositions/stats-overlay.html`
+**What's wrong:** You have a `200px` number next to a `32px` subtitle. The scale jump is so massive it feels disconnected. Then, in the "full canvas moment," you jump to `280px` and `44px`. It’s arbitrary and lacks a cohesive typographic system.
+**Why it matters:** Good design guides the eye. This just slaps a giant number in the viewer's face and hopes they notice the tiny, italicized lowercase text underneath.
+**Fix it:** Bring the subtitle size up to at least `60px-80px`. Use weight, not just massive size differences, to create hierarchy.
+
+### The "Dead Zone" Layout
+**Where:** `compositions/stats-overlay.html` (#stat-1, #stat-2)
+**What's wrong:** You're positioning stats at `top: 450px; left: 80px;` and `top: 850px; right: 80px;`. In a 9:16 portrait format, these are floating in no-man's-land. They feel like they were placed by a random number generator rather than a designer.
+**Why it matters:** It creates a chaotic visual flow. The eye has to jump across the screen in a zig-zag pattern that feels accidental, not intentional.
+**Fix it:** Align these elements to a stronger internal grid. If you're going for Agnes Martin, the grid should be the *hero*, not a suggestion. Align text to the grid lines you've drawn.
+
+---
+
+## Design Improvements
+
+### Robotic Motion
+**Where:** `compositions/background-grid.html` (Grid Breathing)
+**The problem:** You're using `sine.inOut` for everything. It’s the "safe" choice, but it makes the animation feel like a screensaver from 1998. The "breathing" is too mechanical.
+**Make it better:** Use more sophisticated easing like `expo.out` for entrances and `power3.inOut` for the breathing. Vary the timing more aggressively so it feels organic, not like a loop.
+
+### Caption Boredom
+**Where:** `compositions/captions.html`
+**The problem:** Centered, lowercase, gray text at the bottom of the screen. It’s the "I don't know what to do with captions" starter pack.
+**Make it better:** Since the rest of the design is so minimal, make the captions part of the art. Use the grid. Maybe they shouldn't be centered. Maybe they should interact with the lines.
+
+---
+
+## What Actually Works
+
+The **Color Palette** (Pale Linen, Blush, Gold) is actually sophisticated. It’s a refreshing break from the "Neon Cyberpunk" or "Corporate Blue" garbage I usually see. If you can fix the contrast, this has the potential to look genuinely premium and "editorial."
+
+The **Full Canvas Moment** at 7.4s where the grid lines expand is a solid conceptual move. It shows you're thinking about the relationship between the background and the content.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 4/10 - It’s too timid. It’s whispering when it should be speaking clearly.
+**Color & Typography:** 5/10 - Great colors, but the typography is "First Year Design Student" level.
+**Motion & Animation Feel:** 3/10 - It’s a screensaver. There’s no "snap" or "soul" to the movement.
+**Overall Aesthetic:** 4/10 - It has a "vibe," but it lacks the execution to pull it off.
+
+**Bottom Line:** This is a "mood board" that someone tried to turn into a video without finishing the design. It’s too faint to be functional and too disorganized to be "minimalist art." Fix the contrast and the type hierarchy, or don't bother shipping it.
diff --git a/packages/producer/tests/style-18-prod/src/index.html b/packages/producer/tests/style-18-prod/src/index.html
new file mode 100644
index 0000000000..93241556a1
--- /dev/null
+++ b/packages/producer/tests/style-18-prod/src/index.html
@@ -0,0 +1,120 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <title>Editor Agent - Agnes Martin Style</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body {
+ margin: 0;
+ padding: 0;
+ background: #F5F0E8; /* Pale Linen */
+ overflow: hidden;
+ width: 1080px;
+ height: 1920px;
+ }
+ #main-container {
+ position: relative;
+ width: 1080px;
+ height: 1920px;
+ }
+ .full-screen {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ }
+ #bg-comp,
+ #stats-comp,
+ #captions-comp,
+ #a-roll-frame {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ }
+ #bg-comp {
+ z-index: 0;
+ }
+ #a-roll-frame {
+ z-index: 10;
+ overflow: hidden;
+ }
+ #a-roll,
+ #a-roll-frame img.__render_frame__,
+ #a-roll-frame img.__preview_render_frame__ {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ #stats-comp {
+ z-index: 20;
+ pointer-events: none;
+ }
+ #captions-comp {
+ z-index: 30;
+ pointer-events: none;
+ }
+ </style>
+</head>
+<body>
+ <div id="main-comp" data-composition-id="main-comp" data-width="1080" data-height="1920" data-start="0" data-duration="14">
+
+ <!-- Track 0: Background Grid -->
+ <div id="bg-comp"
+ data-composition-id="background-grid"
+ data-composition-src="compositions/background-grid.html"
+ data-start="0"
+ data-duration="14"
+ data-track-index="0">
+ </div>
+
+ <!-- Track 1: A-Roll Video -->
+ <!-- Single video element for the entire duration to ensure audio persistence -->
+ <div id="a-roll-frame">
+ <video id="a-roll"
+ class="full-screen"
+ data-start="0"
+ data-duration="14"
+ data-track-index="1"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/1dd17e4d_2c60a8b3482744e29584975d2b84164a.mp4">
+ </video>
+ </div>
+
+ <!-- Track 2: Stats Overlay -->
+ <div id="stats-comp"
+ data-composition-id="stats-overlay"
+ data-composition-src="compositions/stats-overlay.html"
+ data-start="0"
+ data-duration="14"
+ data-track-index="2">
+ </div>
+
+ <!-- Track 3: Captions -->
+ <div id="captions-comp"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="14"
+ data-track-index="3">
+ </div>
+
+ <script>
+ // Main orchestration timeline
+ const tl = gsap.timeline({ paused: true });
+
+ // Handle the "full-canvas moment" by animating video opacity
+ // Video is visible initially, fades out at 7.1s, and fades back in at 11.5s
+ tl.set('#a-roll-frame', { opacity: 1 });
+ tl.to('#a-roll-frame', { opacity: 0, duration: 0.5, ease: "power2.inOut" }, 7.1);
+ tl.to('#a-roll-frame', { opacity: 1, duration: 0.5, ease: "power2.inOut" }, 11.5);
+
+ window.__timelines["main-comp"] = tl;
+ </script>
+ </div>
+</body>
+</html>
\ No newline at end of file
diff --git a/packages/producer/tests/style-2-prod/meta.json b/packages/producer/tests/style-2-prod/meta.json
new file mode 100644
index 0000000000..2562b40833
--- /dev/null
+++ b/packages/producer/tests/style-2-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-2-prod",
+ "description": "Regression fixture imported from normalized style pack style-2-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "landscape"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-2-prod/src/code_review.md b/packages/producer/tests/style-2-prod/src/code_review.md
new file mode 100644
index 0000000000..90eacaebb7
--- /dev/null
+++ b/packages/producer/tests/style-2-prod/src/code_review.md
@@ -0,0 +1,63 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 4
+- Critical issues: 1
+- Overall compliance status: NEEDS_WORK
+
+## Critical Issues
+
+### Top-Level Container Missing Composition ID
+- **File**: index.html:59
+- **Violation**: The top-level container has `id="main-comp"` but the schema requires `data-composition-id` for all top-level containers.
+- **Schema Rule**: "Every top-level HTML container MUST be a composition (i.e., have a `data-composition-id` attribute)."
+- **Impact**: The framework will not recognize the root element as a composition, potentially failing to initialize the master timeline or manage its children correctly.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - using absolute timing)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+## File-Specific Reviews
+
+### index.html
+**Status**: HAS_ISSUES
+
+**Issues Found**:
+1. **Top-Level Composition ID**: Line 59. The root `div` uses `id="main-comp"` but should use `data-composition-id="main-comp"`.
+2. **Redundant Duration**: Line 96, 104, 112. Sub-compositions `intro`, `stats`, and `captions` have `data-duration` in `index.html`. While allowed, the schema notes that `data-duration` on the composition element itself (inside the template) is the source of truth.
+3. **Track Overlap**: The `aroll` video (Track 1) and `audio-1` in `stats.html` (Track 1) are on the same track number. While they are in different compositions, it's best practice to keep track numbers unique across the project if they represent different layers. However, since they are in different composition scopes, this is technically valid but worth noting.
+
+### compositions/intro.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Correctly uses `<template>`, `data-composition-id`, `data-width`, `data-height`, and `data-duration`. Timeline is registered correctly.
+
+### compositions/captions.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Correctly handles dynamic content by wrapping it in a composition and using a GSAP timeline for word-level timing.
+
+### compositions/stats.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Correctly uses `data-start` and `data-track` for audio primitives and registers the timeline.
+
+## Recommendations
+1. **Fix Root Attribute**: Change `id="main-comp"` to `data-composition-id="main-comp"` in `index.html`.
+2. **Deterministic Check**: Ensure the `TRANSCRIPT` data remains static and is not generated at runtime using non-deterministic methods (it is currently hardcoded, which is perfect).
diff --git a/packages/producer/tests/style-2-prod/src/compositions/captions.html b/packages/producer/tests/style-2-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..9c1c8ff833
--- /dev/null
+++ b/packages/producer/tests/style-2-prod/src/compositions/captions.html
@@ -0,0 +1,81 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1920" data-height="1080" data-duration="17">
+ <div id="caption-container">
+ <div id="caption-box">
+ <span id="caption-text"></span>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="captions"] #caption-container {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: flex-end;
+ padding-bottom: 15%; /* 85% y-position */
+ pointer-events: none;
+ }
+
+ [data-composition-id="captions"] #caption-box {
+ background-color: #1A1A1A;
+ padding: 20px 40px;
+ border-radius: 0px;
+ display: none; /* Hidden by default */
+ max-width: 90%;
+ text-align: center;
+ }
+
+ [data-composition-id="captions"] #caption-text {
+ font-family: 'Helvetica Bold', 'Helvetica', Arial, sans-serif;
+ font-size: 48px;
+ font-weight: bold;
+ color: #FFFFFF;
+ line-height: 1.2;
+ white-space: pre-wrap;
+ display: inline-block;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.86, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics,', 'start': 3.579, 'end': 4.599}, {'text': 'sixty-two', 'start': 4.679, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.079, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.42}, {'text': 'look', 'start': 10.519, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want,', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.859}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Editor', 'start': 15.079, 'end': 15.42}, {'text': 'Agent.', 'start': 15.619, 'end': 16.02}];
+ const tl = gsap.timeline({ paused: true });
+
+ const captionBox = document.querySelector('[data-composition-id="captions"] #caption-box');
+ const captionText = document.querySelector('[data-composition-id="captions"] #caption-text');
+
+ // Group words into segments (max 5 words)
+ const segments = [];
+ for (let i = 0; i < TRANSCRIPT.length; i += 5) {
+ segments.push(TRANSCRIPT.slice(i, i + 5));
+ }
+
+ segments.forEach((segment, index) => {
+ const startTime = segment[0].start;
+ const endTime = segment[segment.length - 1].end;
+ const text = segment.map(w => w.text).join(' ');
+
+ // Show segment
+ tl.set(captionBox, { display: 'block' }, startTime);
+ tl.set(captionText, { textContent: text }, startTime);
+
+ // Sharp 150ms slide-up for new lines
+ // The prompt says "Hard cuts or sharp 150ms slide-up for new lines"
+ // I'll use the slide-up for a more "motion graphics" feel while keeping it Swiss-sharp.
+ tl.fromTo(captionBox,
+ { y: 10, opacity: 0.9 },
+ { y: 0, opacity: 1, duration: 0.15, ease: "power1.out" },
+ startTime
+ );
+
+ // Hide segment
+ tl.set(captionBox, { display: 'none' }, endTime);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-2-prod/src/compositions/intro.html b/packages/producer/tests/style-2-prod/src/compositions/intro.html
new file mode 100644
index 0000000000..9e77bd11f4
--- /dev/null
+++ b/packages/producer/tests/style-2-prod/src/compositions/intro.html
@@ -0,0 +1,104 @@
+<template id="intro-template">
+ <div data-composition-id="intro" data-width="1920" data-height="1080" data-duration="4">
+ <div class="container">
+ <div class="grid-accent"></div>
+ <div class="text-content">
+ <h1 class="title">SURVEY FINDINGS</h1>
+ <h2 class="subtitle">CONTENT CREATION 2026</h2>
+ </div>
+ </div>
+
+ <audio id="snap-sound" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/a5bd8b8b_86b432b7de4c4fa6937b6a9cd37c67db.mp3" data-start="0.5" data-duration="1" data-track-index="1"></audio>
+
+ <style>
+ [data-composition-id="intro"] .container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1920px;
+ height: 1080px;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ padding-left: 10%; /* Align to 10% grid column */
+ font-family: 'Helvetica Bold', 'Helvetica', Arial, sans-serif;
+ font-weight: bold;
+ }
+
+ [data-composition-id="intro"] .grid-accent {
+ position: absolute;
+ left: 10%;
+ top: 0;
+ width: 8px;
+ height: 100%;
+ background-color: #E2001A;
+ transform: scaleY(0);
+ transform-origin: top;
+ }
+
+ [data-composition-id="intro"] .text-content {
+ margin-left: 40px; /* Space from the grid line */
+ overflow: hidden;
+ }
+
+ [data-composition-id="intro"] .title {
+ font-size: 120px;
+ color: #E2001A;
+ margin: 0;
+ line-height: 1;
+ transform: translateX(-110%);
+ }
+
+ [data-composition-id="intro"] .subtitle {
+ font-size: 48px;
+ color: #1A1A1A;
+ margin: 10px 0 0 0;
+ line-height: 1;
+ transform: translateX(-110%);
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // 0.5s: Grid line snaps in
+ tl.to('.grid-accent', {
+ scaleY: 1,
+ duration: 0.2,
+ ease: "expo.out"
+ }, 0.5);
+
+ // 0.5s: Title and subtitle slide in horizontally from the left
+ // Mechanical, sharp ease-out (150-250ms)
+ tl.to('.title', {
+ x: 0,
+ duration: 0.25,
+ ease: "power2.out"
+ }, 0.5);
+
+ tl.to('.subtitle', {
+ x: 0,
+ duration: 0.2,
+ ease: "power2.out"
+ }, 0.6);
+
+ // Exit animation (around 3s)
+ tl.to('.text-content', {
+ opacity: 0,
+ x: -50,
+ duration: 0.3,
+ ease: "power2.in"
+ }, 3.2);
+
+ tl.to('.grid-accent', {
+ scaleY: 0,
+ duration: 0.3,
+ ease: "power2.in"
+ }, 3.3);
+
+ window.__timelines["intro"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-2-prod/src/compositions/stats.html b/packages/producer/tests/style-2-prod/src/compositions/stats.html
new file mode 100644
index 0000000000..ba15ca06b1
--- /dev/null
+++ b/packages/producer/tests/style-2-prod/src/compositions/stats.html
@@ -0,0 +1,137 @@
+<template id="stats-template">
+ <div data-composition-id="stats" data-width="1920" data-height="1080" data-duration="17">
+
+ <!-- Stat 1: 47% MOTION GRAPHICS -->
+ <div id="stat-1" class="stat-container right-align">
+ <div class="stat-number">47%</div>
+ <div class="stat-divider"></div>
+ <div class="stat-label">MOTION GRAPHICS</div>
+ </div>
+
+ <!-- Stat 2: 62% ATTENTION LOSS -->
+ <div id="stat-2" class="stat-container right-align">
+ <div class="stat-number">62%</div>
+ <div class="stat-divider"></div>
+ <div class="stat-label">STATIC CONTENT</div>
+ </div>
+
+ <!-- Stat 3: 75% SKILL GAP -->
+ <div id="stat-3" class="stat-container left-align">
+ <div class="stat-number">75%</div>
+ <div class="stat-divider long-left"></div>
+ <div class="stat-label">EDITING SKILLS</div>
+ </div>
+
+ <!-- Audio triggers -->
+ <audio id="audio-1" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/a5bd8b8b_86b432b7de4c4fa6937b6a9cd37c67db.mp3" data-start="1.86" data-track-index="1"></audio>
+ <audio id="audio-2" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/a5bd8b8b_86b432b7de4c4fa6937b6a9cd37c67db.mp3" data-start="4.679" data-track-index="2"></audio>
+ <audio id="audio-3" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/a5bd8b8b_86b432b7de4c4fa6937b6a9cd37c67db.mp3" data-start="8.88" data-track-index="3"></audio>
+
+ <style>
+ [data-composition-id="stats"] {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1920px;
+ height: 1080px;
+ font-family: 'Helvetica', Arial, sans-serif;
+ color: #1A1A1A;
+ overflow: hidden;
+ }
+
+ [data-composition-id="stats"] .stat-container {
+ position: absolute;
+ display: flex;
+ flex-direction: column;
+ opacity: 0;
+ width: 600px;
+ }
+
+ [data-composition-id="stats"] .right-align {
+ left: 70%;
+ top: 50%;
+ transform: translateY(-50%);
+ }
+
+ [data-composition-id="stats"] .left-align {
+ left: 10%;
+ top: 50%;
+ transform: translateY(-50%);
+ }
+
+ [data-composition-id="stats"] .stat-number {
+ font-size: 220px;
+ font-weight: 900; /* Helvetica Black */
+ color: #E2001A;
+ line-height: 0.8;
+ letter-spacing: -0.06em;
+ margin-bottom: 20px;
+ }
+
+ [data-composition-id="stats"] .stat-divider {
+ width: 100%;
+ height: 2px;
+ background-color: #1A1A1A;
+ margin: 10px 0;
+ }
+
+ [data-composition-id="stats"] .long-left {
+ width: 1000px;
+ position: relative;
+ left: -830px; /* Aligns right edge to right edge of 75% text (approx width of text is 170px, container is 600px, 1000-170=830) */
+ }
+
+ [data-composition-id="stats"] .stat-label {
+ font-size: 42px;
+ font-weight: 300; /* Helvetica Light */
+ letter-spacing: 0.15em;
+ color: #1A1A1A;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.86, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics,', 'start': 3.579, 'end': 4.599}, {'text': 'sixty-two', 'start': 4.679, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.079, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.42}, {'text': 'look', 'start': 10.519, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want,', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.859}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Editor', 'start': 15.079, 'end': 15.42}, {'text': 'Agent.', 'start': 15.619, 'end': 16.02}];
+ const tl = gsap.timeline({ paused: true });
+
+ // Stat 1: 47% MOTION GRAPHICS
+ // Start: 1.86s, End: 4.5s
+ tl.fromTo('#stat-1',
+ { x: 200, opacity: 0 },
+ { x: 0, opacity: 1, duration: 0.4, ease: "power2.out" },
+ 1.86
+ );
+ tl.to('#stat-1',
+ { x: 200, opacity: 0, duration: 0.3, ease: "power2.in" },
+ 4.2
+ );
+
+ // Stat 2: 62% ATTENTION LOSS
+ // Start: 4.679s, End: 8.6s
+ tl.fromTo('#stat-2',
+ { x: 200, opacity: 0 },
+ { x: 0, opacity: 1, duration: 0.4, ease: "power2.out" },
+ 4.679
+ );
+ tl.to('#stat-2',
+ { x: 200, opacity: 0, duration: 0.3, ease: "power2.in" },
+ 8.3
+ );
+
+ // Stat 3: 75% SKILL GAP
+ // Start: 8.88s, End: 14s
+ tl.fromTo('#stat-3',
+ { x: -200, opacity: 0 },
+ { x: 0, opacity: 1, duration: 0.4, ease: "power2.out" },
+ 8.88
+ );
+ tl.to('#stat-3',
+ { x: -200, opacity: 0, duration: 0.3, ease: "power2.in" },
+ 13.7
+ );
+
+ window.__timelines["stats"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-2-prod/src/design_review.md b/packages/producer/tests/style-2-prod/src/design_review.md
new file mode 100644
index 0000000000..9a16a93ae1
--- /dev/null
+++ b/packages/producer/tests/style-2-prod/src/design_review.md
@@ -0,0 +1,57 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a Swiss Design student's first attempt at a "modern" video, and they've clearly prioritized the grid over the actual content. It's clean, sure, but it's also sterile, predictable, and lacks the punch required for a 2026 audience.
+
+---
+
+## CRITICAL Design Failures
+
+### The "Watermark" Eyesore
+**Where:** `index.html` - `.watermark`
+**What's wrong:** A 600px "2026" at 3% opacity isn't "subtle branding," it's a visual smudge. It looks like a rendering error or a dirty screen. It adds zero value and only serves to muddy the background.
+**Why it matters:** It distracts the viewer without conveying information. If you want a background element, make it intentional, not a ghostly mistake.
+**Fix it:** Either commit to it with a bolder weight and slightly higher opacity (maybe 5-8%) or kill it entirely.
+
+### The "Floating Head" Problem
+**Where:** `index.html` - `#aroll` animation
+**What's wrong:** You're scaling the A-roll video down to 60% and 65% and just... leaving it there against a light gray background with some faint grid lines. It looks like a window floating in a void.
+**Why it matters:** It feels unfinished. There's no framing, no container, and no visual relationship between the video and the stats appearing next to it. It's amateurish.
+**Fix it:** Add a subtle border or a more pronounced shadow to the video when it's scaled down. Better yet, use the grid lines to "lock" the video into a specific quadrant so it feels like part of the layout, not a lost asset.
+
+### Caption Box Laziness
+**Where:** `compositions/captions.html` - `#caption-box`
+**What's wrong:** A solid `#1A1A1A` box with white text and zero border-radius. It's the most generic "caption style" possible. It clashes with the "Swiss Grid" aesthetic which usually favors more sophisticated typographic integration.
+**Why it matters:** It looks like a default YouTube caption. It breaks the "premium" feel you're trying to establish with the red accents and Helvetica.
+**Fix it:** Remove the background box. Use a heavy weight for the text, maybe a slight text-shadow for legibility, and align it to the grid. If you must have a box, make it a brand color or use a more interesting shape.
+
+---
+
+## Design Improvements
+
+### Typography Hierarchy
+**Where:** `compositions/stats.html`
+**The problem:** The "75%" is massive (220px), but the "EDITING SKILLS" label is a measly 42px with "Light" weight. The contrast in weight is okay, but the scale difference makes the label feel like an afterthought.
+**Make it better:** Increase the label size to at least 60px and use a Medium weight. The "Swiss" look relies on strong, readable type, not just big numbers.
+
+### Motion Rhythm
+**Where:** `index.html` and `compositions/stats.html`
+**The problem:** Every single animation uses `expo.out` or `power2.out`. It's monotonous. The A-roll shifts at the same speed the stats appear.
+**Make it better:** Vary the easing. Use a "back.out" for the stats to give them a little "pop" when they arrive, or make the A-roll shifts even faster (0.15s) to feel more "mechanical" and precise.
+
+---
+
+## What Actually Works
+
+The **Red Grid Accent** in `intro.html` is actually a solid choice. The `scaleY` animation from the top is sharp, aggressive, and sets a tone that the rest of the video fails to live up to. The use of `#E2001A` against the light gray is a classic high-contrast pairing that works well for "Survey Findings."
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 4/10 - It's safe, boring, and lacks any real "wow" factor.
+**Color & Typography:** 6/10 - The palette is fine, but the typographic execution is lazy.
+**Motion & Animation Feel:** 5/10 - Smooth, but lacks personality and rhythmic variety.
+**Overall Aesthetic:** 5/10 - It's "fine," which is the worst thing a design can be.
+
+**Bottom Line:** This looks like a corporate template. It's technically functional but visually soulless. If you want people to care about these stats, you need to make the design feel as important as the data. Right now, it feels like a PowerPoint presentation that's trying too hard to be "minimalist."
diff --git a/packages/producer/tests/style-2-prod/src/index.html b/packages/producer/tests/style-2-prod/src/index.html
new file mode 100644
index 0000000000..9db69d6561
--- /dev/null
+++ b/packages/producer/tests/style-2-prod/src/index.html
@@ -0,0 +1,181 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Swiss Grid Video</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1920px;
+ height: 1080px;
+ background-color: #F2F2F2;
+ overflow: hidden;
+ font-family: 'Helvetica', Arial, sans-serif;
+ }
+
+ #main-comp {
+ position: relative;
+ width: 1920px;
+ height: 1080px;
+ background-color: #F2F2F2;
+ }
+
+ #aroll-frame {
+ position: absolute;
+ border-radius: 8px;
+ z-index: 1;
+ transform-origin: center center;
+ overflow: hidden;
+ background: #000;
+ box-shadow: 0 20px 50px rgba(0,0,0,0.1);
+ }
+
+ #aroll,
+ #aroll-frame > img.__render_frame__,
+ #aroll-frame > img.__preview_render_frame__ {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ object-position: center;
+ display: block;
+ }
+
+ /* Modular Grid Lines (Visual Only) */
+ .grid-line {
+ position: absolute;
+ background-color: rgba(26, 26, 26, 0.15);
+ z-index: 1;
+ }
+ .grid-v { width: 1px; height: 100%; top: 0; }
+ .grid-h { height: 1px; width: 100%; left: 0; }
+
+ /* Background Watermark */
+ .watermark {
+ position: absolute;
+ font-size: 600px;
+ font-weight: 900;
+ color: rgba(26, 26, 26, 0.03);
+ z-index: 0;
+ white-space: nowrap;
+ pointer-events: none;
+ left: 5%;
+ top: 20%;
+ }
+
+ #intro-comp,
+ #stats-comp,
+ #captions-comp {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ }
+
+ #intro-comp { z-index: 5; }
+ #stats-comp { z-index: 6; }
+ #captions-comp { z-index: 10; }
+ </style>
+</head>
+<body>
+ <div id="main-comp" data-composition-id="main-comp" data-width="1920" data-height="1080" data-duration="17">
+
+ <div class="watermark">2026</div>
+ <div class="grid-line grid-v" style="left: 10%;"></div>
+ <div class="grid-line grid-v" style="left: 20%;"></div>
+ <div class="grid-line grid-v" style="left: 30%;"></div>
+ <div class="grid-line grid-v" style="left: 40%;"></div>
+ <div class="grid-line grid-v" style="left: 50%;"></div>
+ <div class="grid-line grid-v" style="left: 60%;"></div>
+ <div class="grid-line grid-v" style="left: 70%;"></div>
+ <div class="grid-line grid-v" style="left: 80%;"></div>
+ <div class="grid-line grid-v" style="left: 90%;"></div>
+
+ <div class="grid-line grid-h" style="top: 10%;"></div>
+ <div class="grid-line grid-h" style="top: 20%;"></div>
+ <div class="grid-line grid-h" style="top: 30%;"></div>
+ <div class="grid-line grid-h" style="top: 40%;"></div>
+ <div class="grid-line grid-h" style="top: 50%;"></div>
+ <div class="grid-line grid-h" style="top: 60%;"></div>
+ <div class="grid-line grid-h" style="top: 70%;"></div>
+ <div class="grid-line grid-h" style="top: 80%;"></div>
+ <div class="grid-line grid-h" style="top: 90%;"></div>
+
+ <!-- A-roll Video -->
+ <div id="aroll-frame" style="width: 1920px; height: 1080px; left: 0; top: 0;">
+ <video id="aroll"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/57704cd3_8424a748578a497084fd1278949184fc.mp4"
+ data-start="0"
+ data-duration="17"
+ data-track-index="1">
+ </video>
+ </div>
+
+ <!-- Sub-compositions -->
+ <div id="intro-comp"
+ data-composition-id="intro"
+ data-composition-src="compositions/intro.html"
+ data-start="0"
+ data-duration="4"
+ data-track-index="5">
+ </div>
+
+ <div id="stats-comp"
+ data-composition-id="stats"
+ data-composition-src="compositions/stats.html"
+ data-start="0"
+ data-duration="17"
+ data-track-index="6">
+ </div>
+
+ <div id="captions-comp"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="17"
+ data-track-index="10">
+ </div>
+
+ </div>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+
+ // Initial state: Off-screen bottom
+ gsap.set('#aroll-frame', { y: 1080 });
+
+ // 0-1.5s: Slide in from bottom
+ tl.to('#aroll-frame', { y: 0, duration: 1.5, ease: "expo.out" }, 0.5);
+
+ // A-roll Framing Shifts
+ // 5s: Scale down and move left
+ tl.to('#aroll-frame', {
+ scale: 0.6,
+ x: -384, // Align to grid (20% offset)
+ duration: 0.25,
+ ease: "expo.out"
+ }, 4.8);
+
+ // 8.5s: Shift to Right (Before 75% stat at 8.88s)
+ tl.to('#aroll-frame', {
+ x: 384,
+ scale: 0.65,
+ duration: 0.25,
+ ease: "expo.out"
+ }, 8.5);
+
+ // 14.5s: Center and Scale Up
+ tl.to('#aroll-frame', {
+ x: 0,
+ scale: 0.85,
+ duration: 0.25,
+ ease: "expo.out"
+ }, 14.3);
+
+ window.__timelines["main-comp"] = tl;
+ </script>
+</body>
+</html>
diff --git a/packages/producer/tests/style-3-prod/meta.json b/packages/producer/tests/style-3-prod/meta.json
new file mode 100644
index 0000000000..11ec673669
--- /dev/null
+++ b/packages/producer/tests/style-3-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-3-prod",
+ "description": "Regression fixture imported from normalized style pack style-3-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "landscape"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-3-prod/src/assets/swiss-grid.svg b/packages/producer/tests/style-3-prod/src/assets/swiss-grid.svg
new file mode 100644
index 0000000000..a3fb54f753
--- /dev/null
+++ b/packages/producer/tests/style-3-prod/src/assets/swiss-grid.svg
@@ -0,0 +1,116 @@
+<svg viewBox="0 0 1920 1080" xmlns="http://www.w3.org/2000/svg">
+ <rect width="1920" height="1080" fill="#F2F2F2" />
+
+ <g id="thin-grid-lines" stroke="#0A1E3D" stroke-width="1" opacity="0.1">
+ <line id="v-thin-1" x1="60" y1="0" x2="60" y2="1080" />
+ <line id="v-thin-2" x1="120" y1="0" x2="120" y2="1080" />
+ <line id="v-thin-3" x1="180" y1="0" x2="180" y2="1080" />
+ <line id="v-thin-5" x1="300" y1="0" x2="300" y2="1080" />
+ <line id="v-thin-6" x1="360" y1="0" x2="360" y2="1080" />
+ <line id="v-thin-7" x1="420" y1="0" x2="420" y2="1080" />
+ <line id="v-thin-9" x1="540" y1="0" x2="540" y2="1080" />
+ <line id="v-thin-10" x1="600" y1="0" x2="600" y2="1080" />
+ <line id="v-thin-11" x1="660" y1="0" x2="660" y2="1080" />
+ <line id="v-thin-13" x1="780" y1="0" x2="780" y2="1080" />
+ <line id="v-thin-14" x1="840" y1="0" x2="840" y2="1080" />
+ <line id="v-thin-15" x1="900" y1="0" x2="900" y2="1080" />
+ <line id="v-thin-17" x1="1020" y1="0" x2="1020" y2="1080" />
+ <line id="v-thin-18" x1="1080" y1="0" x2="1080" y2="1080" />
+ <line id="v-thin-19" x1="1140" y1="0" x2="1140" y2="1080" />
+ <line id="v-thin-21" x1="1260" y1="0" x2="1260" y2="1080" />
+ <line id="v-thin-22" x1="1320" y1="0" x2="1320" y2="1080" />
+ <line id="v-thin-23" x1="1380" y1="0" x2="1380" y2="1080" />
+ <line id="v-thin-25" x1="1500" y1="0" x2="1500" y2="1080" />
+ <line id="v-thin-26" x1="1560" y1="0" x2="1560" y2="1080" />
+ <line id="v-thin-27" x1="1620" y1="0" x2="1620" y2="1080" />
+ <line id="v-thin-29" x1="1740" y1="0" x2="1740" y2="1080" />
+ <line id="v-thin-30" x1="1800" y1="0" x2="1800" y2="1080" />
+ <line id="v-thin-31" x1="1860" y1="0" x2="1860" y2="1080" />
+ <line id="h-thin-1" x1="0" y1="60" x2="1920" y2="60" />
+ <line id="h-thin-2" x1="0" y1="120" x2="1920" y2="120" />
+ <line id="h-thin-3" x1="0" y1="180" x2="1920" y2="180" />
+ <line id="h-thin-5" x1="0" y1="300" x2="1920" y2="300" />
+ <line id="h-thin-6" x1="0" y1="360" x2="1920" y2="360" />
+ <line id="h-thin-7" x1="0" y1="420" x2="1920" y2="420" />
+ <line id="h-thin-9" x1="0" y1="540" x2="1920" y2="540" />
+ <line id="h-thin-10" x1="0" y1="600" x2="1920" y2="600" />
+ <line id="h-thin-11" x1="0" y1="660" x2="1920" y2="660" />
+ <line id="h-thin-13" x1="0" y1="780" x2="1920" y2="780" />
+ <line id="h-thin-14" x1="0" y1="840" x2="1920" y2="840" />
+ <line id="h-thin-15" x1="0" y1="900" x2="1920" y2="900" />
+ <line id="h-thin-17" x1="0" y1="1020" x2="1920" y2="1020" />
+ </g>
+
+ <g id="thick-grid-lines" stroke="#0A1E3D" stroke-width="3" opacity="0.2">
+ <line id="v-thick-1" x1="240" y1="0" x2="240" y2="1080" />
+ <line id="v-thick-2" x1="480" y1="0" x2="480" y2="1080" />
+ <line id="v-thick-3" x1="720" y1="0" x2="720" y2="1080" />
+ <line id="v-thick-4" x1="960" y1="0" x2="960" y2="1080" />
+ <line id="v-thick-5" x1="1200" y1="0" x2="1200" y2="1080" />
+ <line id="v-thick-6" x1="1440" y1="0" x2="1440" y2="1080" />
+ <line id="v-thick-7" x1="1680" y1="0" x2="1680" y2="1080" />
+ <line id="h-thick-1" x1="0" y1="240" x2="1920" y2="240" />
+ <line id="h-thick-2" x1="0" y1="480" x2="1920" y2="480" />
+ <line id="h-thick-3" x1="0" y1="720" x2="1920" y2="720" />
+ <line id="h-thick-4" x1="0" y1="960" x2="1920" y2="960" />
+ </g>
+
+ <g id="intersections" stroke="#0A1E3D" stroke-width="2" opacity="0.3">
+ <line x1="230" y1="240" x2="250" y2="240" />
+ <line x1="240" y1="230" x2="240" y2="250" />
+ <line x1="230" y1="480" x2="250" y2="480" />
+ <line x1="240" y1="470" x2="240" y2="490" />
+ <line x1="230" y1="720" x2="250" y2="720" />
+ <line x1="240" y1="710" x2="240" y2="730" />
+ <line x1="230" y1="960" x2="250" y2="960" />
+ <line x1="240" y1="950" x2="240" y2="970" />
+ <line x1="470" y1="240" x2="490" y2="240" />
+ <line x1="480" y1="230" x2="480" y2="250" />
+ <line x1="470" y1="480" x2="490" y2="480" />
+ <line x1="480" y1="470" x2="480" y2="490" />
+ <line x1="470" y1="720" x2="490" y2="720" />
+ <line x1="480" y1="710" x2="480" y2="730" />
+ <line x1="470" y1="960" x2="490" y2="960" />
+ <line x1="480" y1="950" x2="480" y2="970" />
+ <line x1="710" y1="240" x2="730" y2="240" />
+ <line x1="720" y1="230" x2="720" y2="250" />
+ <line x1="710" y1="480" x2="730" y2="480" />
+ <line x1="720" y1="470" x2="720" y2="490" />
+ <line x1="710" y1="720" x2="730" y2="720" />
+ <line x1="720" y1="710" x2="720" y2="730" />
+ <line x1="710" y1="960" x2="730" y2="960" />
+ <line x1="720" y1="950" x2="720" y2="970" />
+ <line x1="950" y1="240" x2="970" y2="240" />
+ <line x1="960" y1="230" x2="960" y2="250" />
+ <line x1="950" y1="480" x2="970" y2="480" />
+ <line x1="960" y1="470" x2="960" y2="490" />
+ <line x1="950" y1="720" x2="970" y2="720" />
+ <line x1="960" y1="710" x2="960" y2="730" />
+ <line x1="950" y1="960" x2="970" y2="960" />
+ <line x1="960" y1="950" x2="960" y2="970" />
+ <line x1="1190" y1="240" x2="1210" y2="240" />
+ <line x1="1200" y1="230" x2="1200" y2="250" />
+ <line x1="1190" y1="480" x2="1210" y2="480" />
+ <line x1="1200" y1="470" x2="1200" y2="490" />
+ <line x1="1190" y1="720" x2="1210" y2="720" />
+ <line x1="1200" y1="710" x2="1200" y2="730" />
+ <line x1="1190" y1="960" x2="1210" y2="960" />
+ <line x1="1200" y1="950" x2="1200" y2="970" />
+ <line x1="1430" y1="240" x2="1450" y2="240" />
+ <line x1="1440" y1="230" x2="1440" y2="250" />
+ <line x1="1430" y1="480" x2="1450" y2="480" />
+ <line x1="1440" y1="470" x2="1440" y2="490" />
+ <line x1="1430" y1="720" x2="1450" y2="720" />
+ <line x1="1440" y1="710" x2="1440" y2="730" />
+ <line x1="1430" y1="960" x2="1450" y2="960" />
+ <line x1="1440" y1="950" x2="1440" y2="970" />
+ <line x1="1670" y1="240" x2="1690" y2="240" />
+ <line x1="1680" y1="230" x2="1680" y2="250" />
+ <line x1="1670" y1="480" x2="1690" y2="480" />
+ <line x1="1680" y1="470" x2="1680" y2="490" />
+ <line x1="1670" y1="720" x2="1690" y2="720" />
+ <line x1="1680" y1="710" x2="1680" y2="730" />
+ <line x1="1670" y1="960" x2="1690" y2="960" />
+ <line x1="1680" y1="950" x2="1680" y2="970" />
+ </g>
+</svg>
\ No newline at end of file
diff --git a/packages/producer/tests/style-3-prod/src/code_review.md b/packages/producer/tests/style-3-prod/src/code_review.md
new file mode 100644
index 0000000000..d41062026d
--- /dev/null
+++ b/packages/producer/tests/style-3-prod/src/code_review.md
@@ -0,0 +1,53 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 4
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None. All files now comply with the HyperFrame schema.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - absolute used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+## File Reviews
+
+### index.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Correctly uses `data-composition-id`, `data-width`, `data-height`, and `data-duration`. Registers `master` timeline.
+
+### compositions/intro.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- None. Correctly uses `<template>`, registers `intro` timeline, and has required attributes.
+
+### compositions/captions.html
+**Status**: HAS_ISSUES
+
+**Issues Found**:
+- **Line 95**: Attempting to set `data-duration` via script. This should be a static attribute on the composition root (Line 2).
+- **Line 2**: `data-duration="30"` is set, but the script calculates a different duration. These should be synchronized manually in the HTML.
+
+### compositions/graphics.html
+**Status**: COMPLIANT
+
+**Issues Found**:
+- **Line 135**: Redundant GSAP script import inside a composition template. While not a schema violation, it's unnecessary as GSAP is loaded in `index.html`.
diff --git a/packages/producer/tests/style-3-prod/src/compositions/captions.html b/packages/producer/tests/style-3-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..d599bd894c
--- /dev/null
+++ b/packages/producer/tests/style-3-prod/src/compositions/captions.html
@@ -0,0 +1,95 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1920" data-height="1080" data-duration="16.04">
+ <div id="caption-container"></div>
+
+ <style>
+ [data-composition-id="captions"] {
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ font-family: 'Helvetica', 'Arial', sans-serif;
+ font-weight: bold;
+ overflow: hidden;
+ }
+
+ [data-composition-id="captions"] #caption-container {
+ position: absolute;
+ bottom: 120px; /* Consistent bottom positioning */
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ }
+
+ [data-composition-id="captions"] .caption-box {
+ background-color: #0A1E3D; /* Solid navy */
+ padding: 20px 40px;
+ display: none; /* Hidden by default, shown via GSAP */
+ justify-content: center;
+ align-items: center;
+ /* Swiss Grid: sharp corners, solid block */
+ }
+
+ [data-composition-id="captions"] .caption-text {
+ color: #F2F2F2; /* Off-white */
+ font-size: 72px;
+ text-transform: uppercase; /* Swiss style often uses uppercase for impact */
+ letter-spacing: -2px;
+ line-height: 1;
+ white-space: nowrap;
+ text-align: center;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.86, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics,', 'start': 3.579, 'end': 4.599}, {'text': 'sixty-two', 'start': 4.679, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.079, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.42}, {'text': 'look', 'start': 10.519, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.86}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Editor', 'start': 15.079, 'end': 15.42}, {'text': 'Agent.', 'start': 15.619, 'end': 16.02}];
+ const container = document.getElementById('caption-container');
+ const tl = gsap.timeline({ paused: true });
+
+ if (!TRANSCRIPT || TRANSCRIPT.length === 0) {
+ window.__timelines["captions"] = tl;
+ return;
+ }
+
+ // Group transcript into max 5 words per group
+ const groups = [];
+ let currentGroup = [];
+
+ TRANSCRIPT.forEach((word, index) => {
+ currentGroup.push(word);
+ // Group by 5 words OR if it's the last word
+ if (currentGroup.length === 5 || index === TRANSCRIPT.length - 1) {
+ groups.push([...currentGroup]);
+ currentGroup = [];
+ }
+ });
+
+ // Create DOM elements and timeline for each group
+ groups.forEach((group, i) => {
+ const box = document.createElement('div');
+ box.className = 'caption-box';
+ box.id = `group-${i}`;
+
+ const text = document.createElement('div');
+ text.className = 'caption-text';
+ text.textContent = group.map(w => w.text).join(' ');
+
+ box.appendChild(text);
+ container.appendChild(box);
+
+ const startTime = group[0].start;
+ const endTime = group[group.length - 1].end;
+
+ // Hard cut animation (no fades) as requested
+ tl.set(box, { display: 'flex' }, startTime);
+ tl.set(box, { display: 'none' }, endTime);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-3-prod/src/compositions/graphics.html b/packages/producer/tests/style-3-prod/src/compositions/graphics.html
new file mode 100644
index 0000000000..64134a57a5
--- /dev/null
+++ b/packages/producer/tests/style-3-prod/src/compositions/graphics.html
@@ -0,0 +1,198 @@
+<template id="graphics-template">
+ <div data-composition-id="graphics" data-width="1920" data-height="1080" data-duration="15">
+ <div class="grid-container">
+ <!-- Stat 1: 47% -->
+ <div id="stat1" class="stat-group">
+ <div class="stat-value">47%</div>
+ <div class="stat-label">NEED MOTION GRAPHICS</div>
+ </div>
+
+ <!-- Stat 2: 62% -->
+ <div id="stat2" class="stat-group">
+ <div class="stat-value">62%</div>
+ <div class="stat-label">LOSING ATTENTION</div>
+ <div class="progress-container">
+ <div class="progress-bar"></div>
+ </div>
+ </div>
+
+ <!-- Stat 3: 3 OF 4 -->
+ <div id="stat3" class="stat-group">
+ <div class="stat-value">3 OF 4</div>
+ <div class="stat-label">LACK EDITING SKILLS</div>
+ <div class="grid-blocks">
+ <div class="block gold"></div>
+ <div class="block gold"></div>
+ <div class="block gold"></div>
+ <div class="block navy"></div>
+ </div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="graphics"] {
+ font-family: 'Helvetica', Arial, sans-serif;
+ color: #0A1E3D;
+ background: transparent;
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ overflow: hidden;
+ }
+
+ [data-composition-id="graphics"] .grid-container {
+ display: grid;
+ grid-template-columns: repeat(12, 1fr);
+ grid-template-rows: repeat(12, 1fr);
+ width: 100%;
+ height: 100%;
+ padding: 80px;
+ gap: 20px;
+ }
+
+ [data-composition-id="graphics"] .stat-group {
+ opacity: 0;
+ display: flex;
+ flex-direction: column;
+ justify-content: flex-start;
+ align-items: flex-start;
+ background: #F2F2F2;
+ padding: 40px;
+ border-left: 10px solid #D4A017;
+ box-shadow: 20px 20px 0px rgba(10, 30, 61, 0.1);
+ }
+
+ /* Positioning Stats on Grid - Adjusted for A-roll structure */
+ [data-composition-id="graphics"] #stat1 {
+ grid-column: 2 / 6;
+ grid-row: 3 / 7;
+ }
+
+ [data-composition-id="graphics"] #stat2 {
+ grid-column: 2 / 6;
+ grid-row: 3 / 7;
+ }
+
+ [data-composition-id="graphics"] #stat3 {
+ grid-column: 7 / 12;
+ grid-row: 3 / 7;
+ }
+
+ [data-composition-id="graphics"] .stat-value {
+ font-size: 140px;
+ font-weight: 900;
+ color: #D4A017;
+ line-height: 0.8;
+ margin-bottom: 15px;
+ }
+
+ [data-composition-id="graphics"] .stat-label {
+ font-size: 24px;
+ font-weight: 300; /* Lighter weight */
+ color: #0A1E3D;
+ letter-spacing: 2px;
+ text-transform: uppercase;
+ }
+
+ /* Progress Bar for Stat 2 */
+ [data-composition-id="graphics"] .progress-container {
+ width: 100%;
+ height: 24px;
+ background: #E0E0E0;
+ margin-top: 30px;
+ border: 2px solid #0A1E3D;
+ position: relative;
+ }
+
+ [data-composition-id="graphics"] .progress-bar {
+ width: 0%;
+ height: 100%;
+ background: #D4A017;
+ }
+
+ /* Grid Blocks for Stat 3 */
+ [data-composition-id="graphics"] .grid-blocks {
+ display: flex;
+ gap: 20px;
+ margin-top: 30px;
+ }
+
+ [data-composition-id="graphics"] .block {
+ width: 80px;
+ height: 80px;
+ border: 3px solid #0A1E3D;
+ }
+
+ [data-composition-id="graphics"] .block.gold {
+ background: #D4A017;
+ }
+
+ [data-composition-id="graphics"] .block.navy {
+ background: #0A1E3D;
+ }
+ </style>
+
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // Timing Constants
+ const S1_START = 1.86;
+ const S1_END = 4.5;
+ const S2_START = 4.68;
+ const S2_END = 8.6;
+ const S3_START = 8.88;
+ const S3_END = 14.2;
+
+ const SLIDE_DUR = 0.25; // 250ms
+ const SHARP_EASE = "power2.out";
+
+ // Stat 1 Animation
+ tl.fromTo('#stat1',
+ { x: -200, opacity: 0 },
+ { x: 0, opacity: 1, duration: SLIDE_DUR, ease: SHARP_EASE },
+ S1_START
+ );
+ tl.to('#stat1',
+ { x: 200, opacity: 0, duration: SLIDE_DUR, ease: "power2.in" },
+ S1_END - SLIDE_DUR
+ );
+
+ // Stat 2 Animation
+ tl.fromTo('#stat2',
+ { y: 200, opacity: 0 },
+ { y: 0, opacity: 1, duration: SLIDE_DUR, ease: SHARP_EASE },
+ S2_START
+ );
+ // Progress bar fill
+ tl.to('#stat2 .progress-bar',
+ { width: '62%', duration: S2_END - S2_START - (SLIDE_DUR * 2), ease: "none" },
+ S2_START + SLIDE_DUR
+ );
+ tl.to('#stat2',
+ { y: -200, opacity: 0, duration: SLIDE_DUR, ease: "power2.in" },
+ S2_END - SLIDE_DUR
+ );
+
+ // Stat 3 Animation
+ tl.fromTo('#stat3',
+ { x: 200, opacity: 0 },
+ { x: 0, opacity: 1, duration: SLIDE_DUR, ease: SHARP_EASE },
+ S3_START
+ );
+ // Stagger blocks
+ tl.from('#stat3 .block',
+ { scale: 0, duration: 0.3, stagger: 0.1, ease: "back.out(1.7)" },
+ S3_START + SLIDE_DUR
+ );
+ tl.to('#stat3',
+ { x: -200, opacity: 0, duration: SLIDE_DUR, ease: "power2.in" },
+ S3_END - SLIDE_DUR
+ );
+
+ window.__timelines["graphics"] = tl;
+ })();
+ </script>
+ </div>
+</template>
\ No newline at end of file
diff --git a/packages/producer/tests/style-3-prod/src/compositions/intro.html b/packages/producer/tests/style-3-prod/src/compositions/intro.html
new file mode 100644
index 0000000000..e373d5335a
--- /dev/null
+++ b/packages/producer/tests/style-3-prod/src/compositions/intro.html
@@ -0,0 +1,114 @@
+<template id="intro-template">
+ <div data-composition-id="intro" data-width="1920" data-height="1080" data-duration="1.86">
+ <div class="container">
+ <div class="grid-line"></div>
+ <div class="text-wrapper">
+ <h1 class="title">EDITOR AGENT</h1>
+ <h2 class="subtitle">THE SURVEY FINDINGS</h2>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="intro"] {
+ background-color: #F5F5F5; /* Off-white */
+ width: 1920px;
+ height: 1080px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ overflow: hidden;
+ }
+
+ [data-composition-id="intro"] .container {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ padding-left: 160px; /* Swiss grid alignment */
+ }
+
+ [data-composition-id="intro"] .grid-line {
+ position: absolute;
+ left: 160px;
+ top: 50%;
+ width: 0px;
+ height: 12px;
+ background-color: #0A1E3D; /* Navy */
+ transform: translateY(-180px); /* Positioned above the text */
+ }
+
+ [data-composition-id="intro"] .text-wrapper {
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+ overflow: hidden;
+ }
+
+ [data-composition-id="intro"] .title {
+ color: #0A1E3D;
+ font-size: 180px;
+ font-weight: 900; /* Black weight */
+ line-height: 0.9;
+ margin: 0;
+ letter-spacing: -0.04em;
+ text-transform: uppercase;
+ transform: translateX(-100%); /* Start off-screen left */
+ }
+
+ [data-composition-id="intro"] .subtitle {
+ color: #0A1E3D;
+ font-size: 64px;
+ font-weight: 300; /* Lighter weight for contrast */
+ line-height: 1.2;
+ margin: 0;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ transform: translateX(-100%); /* Start off-screen left */
+ margin-top: 20px;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // Mechanical timing: 200ms (0.2s)
+ const MECHANICAL_DURATION = 0.2;
+ const STAGGER = 0.1;
+
+ // 1. Animate the grid line first
+ tl.to('.grid-line', {
+ width: '1200px',
+ duration: 0.4,
+ ease: 'power4.out'
+ }, 0.2);
+
+ // 2. Slide in the title
+ tl.to('.title', {
+ x: 0,
+ duration: MECHANICAL_DURATION,
+ ease: 'power2.inOut'
+ }, 0.5);
+
+ // 3. Slide in the subtitle with a slight stagger
+ tl.to('.subtitle', {
+ x: 0,
+ duration: MECHANICAL_DURATION,
+ ease: 'power2.inOut'
+ }, 0.5 + STAGGER);
+
+ // 4. Subtle ambient motion (slow drift) to keep it alive
+ tl.to('.text-wrapper', {
+ x: 30,
+ duration: 1.16, // Adjusted to fit 1.86s total
+ ease: 'none'
+ }, 0.7);
+
+ window.__timelines["intro"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-3-prod/src/design_review.md b/packages/producer/tests/style-3-prod/src/design_review.md
new file mode 100644
index 0000000000..ddb02f76b5
--- /dev/null
+++ b/packages/producer/tests/style-3-prod/src/design_review.md
@@ -0,0 +1,57 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a "Swiss Style" template that someone found in a dumpster and tried to glue back together. It’s a clinical, soulless mess that mistakes "minimalism" for "I didn't have time to finish the design."
+
+---
+
+## CRITICAL Design Failures
+
+### The "Swiss Grid" is a Lie
+**Where:** `assets/swiss-grid.svg` and `index.html`
+**What's wrong:** You’ve included a grid background that looks like a blueprint for a parking lot. It’s distracting, cluttered, and serves no purpose other than to scream "I'm trying to be edgy." The intersections and thick lines create a visual vibration that makes the actual content hard to focus on.
+**Why it matters:** A grid should be a guide for the designer, not a cage for the viewer. It’s visually exhausting and makes the entire composition feel like a technical drawing rather than a professional video.
+**Fix it:** Lower the opacity of the grid to 0.05 or remove it entirely. Use the grid to align elements, don't make the viewer look at it.
+
+### Typography Hierarchy is Non-Existent
+**Where:** `compositions/intro.html` and `compositions/graphics.html`
+**What's wrong:** You’re using Helvetica (the default choice of the uninspired) and just cranking the font size up to 180px. The "EDITOR AGENT" title is so massive it’s practically shouting in the viewer's face, while the subtitle is just... there. There’s no elegance, no play with weight, just "BIG TEXT" and "SMALLER TEXT."
+**Why it matters:** Without a clear typographic hierarchy, the viewer doesn't know where to look first. It feels amateur and "default."
+**Fix it:** Experiment with tighter letter spacing (kerning) and more dramatic weight contrasts. Try a heavier weight for the title and a much lighter, tracked-out weight for the subtitle.
+
+### The "Gold" is Actually Mustard
+**Where:** `compositions/graphics.html` (`#D4A017`)
+**What's wrong:** You’ve paired a sophisticated Navy (`#0A1E3D`) with a "gold" that looks like expired Dijon mustard. It’s flat, muddy, and lacks any premium feel.
+**Why it matters:** Color choice dictates the "vibe." This color palette feels like a budget airline from the 90s, not a cutting-edge "Editor Agent."
+**Fix it:** Use a more vibrant, metallic-leaning gold or a sharp, high-contrast accent color like a neon cyan or a deep crimson to actually give this some life.
+
+---
+
+## Design Improvements
+
+### Robotic Motion
+**Where:** `compositions/graphics.html` and `index.html`
+**The problem:** The animations are "mechanical" in the worst way. `power2.out` is the "I just started using GSAP" of easing functions. The A-roll video jumps around the screen like a glitchy security camera.
+**Make it better:** Use more sophisticated easing like `expo.out` or `customEase`. Add some secondary motion—maybe the text doesn't just slide, it scales slightly or has a subtle blur on entry. Make the transitions feel like they have weight and momentum.
+
+### Caption Box Laziness
+**Where:** `compositions/captions.html`
+**The problem:** A solid navy box with white text. It’s the most basic implementation possible. It covers up the A-roll and looks like a closed-captioning fail.
+**Make it better:** Lose the solid box. Use a subtle text shadow or a semi-transparent blurred background (glassmorphism) to keep the text readable without blocking the frame. Or, lean into the Swiss style and use a high-contrast, offset background block that actually feels intentional.
+
+---
+
+## What Actually Works
+
+The **layout logic** in `index.html` where the A-roll moves to accommodate the graphics is actually a smart move. It shows you’re thinking about the composition as a whole, even if the execution is currently hideous. The use of a 12x12 grid for positioning is a solid foundation—you just need to stop showing your work.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 3/10 - It’s as exciting as a spreadsheet.
+**Color & Typography:** 2/10 - Helvetica and mustard. Groundbreaking.
+**Motion & Animation Feel:** 4/10 - Functional, but lacks any soul or "flow."
+**Overall Aesthetic:** 3/10 - A "Swiss Style" attempt that fell off the mountain.
+
+**Bottom Line:** This looks like a prototype for a corporate training video that everyone will mute and minimize. It needs a massive injection of personality, better color theory, and motion that doesn't feel like it was programmed by a calculator. Fix the grid, fix the colors, and for the love of design, find a better font.
diff --git a/packages/producer/tests/style-3-prod/src/index.html b/packages/producer/tests/style-3-prod/src/index.html
new file mode 100644
index 0000000000..709c0e3d51
--- /dev/null
+++ b/packages/producer/tests/style-3-prod/src/index.html
@@ -0,0 +1,172 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Swiss Grid - Editor Agent</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1920px;
+ height: 1080px;
+ background-color: #F2F2F2;
+ overflow: hidden;
+ font-family: 'Helvetica', Arial, sans-serif;
+ }
+
+ #master-root {
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ }
+
+ .background-grid {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 0;
+ }
+
+ /* A-roll styling */
+ #short_mag_cut_frame {
+ position: absolute;
+ border-radius: 8px; /* Required */
+ z-index: 1;
+ box-shadow: 0 20px 40px rgba(0,0,0,0.3);
+ overflow: hidden;
+ background: #000;
+ }
+
+ #short_mag_cut,
+ #short_mag_cut_frame > img.__render_frame__,
+ #short_mag_cut_frame > img.__preview_render_frame__ {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ object-position: center;
+ display: block;
+ }
+
+ /* Overlay layers */
+ .overlay-layer {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ }
+
+ #intro-comp { z-index: 2; }
+ #graphics-comp { z-index: 3; }
+ #captions-comp { z-index: 4; }
+ </style>
+</head>
+<body>
+ <div id="master-root" data-composition-id="master" data-width="1920" data-height="1080" data-duration="16.04">
+
+ <!-- Background Grid -->
+ <img id="bg-grid"
+ class="background-grid"
+ src="assets/swiss-grid.svg"
+ alt="Grid"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="0">
+
+ <!-- A-roll Video -->
+ <div id="short_mag_cut_frame">
+ <video id="short_mag_cut"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/8eb26801_b5ca4d50bb91437dac375c58b86d005c.mp4"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="1">
+ </video>
+ </div>
+
+ <!-- Intro Sub-composition -->
+ <div id="intro-comp"
+ class="overlay-layer"
+ data-composition-id="intro"
+ data-composition-src="compositions/intro.html"
+ data-start="0"
+ data-duration="1.86"
+ data-track-index="2">
+ </div>
+
+ <!-- Graphics Sub-composition -->
+ <div id="graphics-comp"
+ class="overlay-layer"
+ data-composition-id="graphics"
+ data-composition-src="compositions/graphics.html"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="3">
+ </div>
+
+ <!-- Captions Sub-composition -->
+ <div id="captions-comp"
+ class="overlay-layer"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="4">
+ </div>
+
+ <!-- Sound Effects -->
+ <audio id="sfx-intro" data-start="0" data-track-index="5" data-duration="1" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/051b5d38_af2426f283a749de94ab615d459a565d.mp3"></audio>
+ <audio id="sfx-stat1" data-start="1.86" data-track-index="5" data-duration="1" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/bd3cb328_5d3f0ddf41c14bb8bfad8ae242024334.mp3"></audio>
+ <audio id="sfx-stat2" data-start="4.68" data-track-index="5" data-duration="1" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/61ada7ed_142d9432f783410185afebd0d00f1b7a.mp3"></audio>
+ <audio id="sfx-stat3" data-start="8.88" data-track-index="5" data-duration="1" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/bd3cb328_5d3f0ddf41c14bb8bfad8ae242024334.mp3"></audio>
+
+ <script>
+ window.__timelines = window.__timelines || {};
+
+ const masterTL = gsap.timeline({ paused: true });
+ const v = document.getElementById('short_mag_cut_frame');
+
+ // --- A-ROLL MOVEMENT (Structured Swiss Layout) ---
+
+ // 1. Entrance (0-1.86s): Slide in from left, settle centered for Intro
+ masterTL.fromTo(v,
+ { x: -1000, y: 120, width: 960, height: 840 },
+ { x: 480, y: 120, width: 960, height: 840, duration: 0.8, ease: "power2.out" },
+ 0
+ );
+
+ // 2. Stat 1 (1.86s - 4.68s): Move to right side (Graphic is on left)
+ masterTL.to(v, {
+ x: 1080, y: 120, width: 720, height: 720,
+ duration: 0.25, ease: "expo.out"
+ }, 1.86);
+
+ // 3. Stat 2 (4.68s - 8.88s): Stay right, zoom in slightly
+ masterTL.to(v, {
+ x: 1080, y: 60, width: 780, height: 780,
+ duration: 0.25, ease: "expo.out"
+ }, 4.68);
+
+ // 4. Stat 3 (8.88s - 14.2s): Move to left side (Graphic is on right)
+ masterTL.to(v, {
+ x: 120, y: 120, width: 720, height: 720,
+ duration: 0.25, ease: "expo.out"
+ }, 8.88);
+
+ // 5. Conclusion (14.2s - 16.04s): Center large
+ masterTL.to(v, {
+ x: 240, y: 60, width: 1440, height: 810,
+ duration: 0.5, ease: "expo.out"
+ }, 14.2);
+
+ window.__timelines["master"] = masterTL;
+ </script>
+ </div>
+</body>
+</html>
diff --git a/packages/producer/tests/style-4-prod/meta.json b/packages/producer/tests/style-4-prod/meta.json
new file mode 100644
index 0000000000..4d0b69860c
--- /dev/null
+++ b/packages/producer/tests/style-4-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-4-prod",
+ "description": "Regression fixture imported from normalized style pack style-4-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "landscape"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-4-prod/src/code_review.md b/packages/producer/tests/style-4-prod/src/code_review.md
new file mode 100644
index 0000000000..c8c9e1e6d9
--- /dev/null
+++ b/packages/producer/tests/style-4-prod/src/code_review.md
@@ -0,0 +1,65 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 4
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None found. The compositions follow the deterministic requirements and structural rules of the HyperFrame schema.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images used)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - absolute timing used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+## File Analysis
+
+### index.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Correctly defines the root composition `main-video`.
+- Uses `data-composition-src` to load sub-compositions.
+- Properly registers the master timeline in `window.__timelines`.
+- Uses deterministic GSAP animations for the A-roll video.
+- Note: The `grain-overlay` is defined as an inline composition, which is acceptable for simple effects.
+
+### compositions/intro.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Uses `<template>` tag as required.
+- Root element has `data-composition-id`, `data-width`, `data-height`, and `data-duration`.
+- Timeline is correctly registered and scoped within an IIFE.
+- Animation is deterministic.
+
+### compositions/captions.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Uses `<template>` tag.
+- Correctly handles dynamic caption generation within a composition.
+- Timeline registration is correct.
+- Deterministic timing based on a static script array.
+
+### compositions/graphics.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Uses `<template>` tag.
+- Root element has all required data attributes.
+- GSAP animations are deterministic and use explicit durations.
+- Timeline registration is correct.
diff --git a/packages/producer/tests/style-4-prod/src/compositions/captions.html b/packages/producer/tests/style-4-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..2b0f607731
--- /dev/null
+++ b/packages/producer/tests/style-4-prod/src/compositions/captions.html
@@ -0,0 +1,134 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1920" data-height="1080" data-duration="18">
+ <div class="captions-container">
+ <div id="caption-box" class="caption-box">
+ <span id="caption-text" class="caption-text"></span>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="captions"] .captions-container {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: flex-end;
+ padding-bottom: 230px; /* Position at y: 850 (1080 - 230 = 850) */
+ pointer-events: none;
+ }
+
+ [data-composition-id="captions"] .caption-box {
+ background-color: #7A6248;
+ padding: 12px 32px;
+ border-radius: 24px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ min-width: 100px;
+ max-width: 80%;
+ opacity: 0;
+ box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
+ }
+
+ [data-composition-id="captions"] .caption-text {
+ color: #F5F0E0;
+ font-family: 'Outfit', sans-serif;
+ font-size: 48px;
+ font-weight: 700;
+ text-align: center;
+ line-height: 1.2;
+ white-space: nowrap;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const script = [
+ {"text": "We", "start": 0.119, "end": 0.259},
+ {"text": "asked", "start": 0.319, "end": 0.479},
+ {"text": "what", "start": 0.519, "end": 0.659},
+ {"text": "you", "start": 0.699, "end": 0.819},
+ {"text": "needed.", "start": 0.859, "end": 1.819},
+ {"text": "Forty-seven", "start": 1.86, "end": 2.299},
+ {"text": "percent", "start": 2.399, "end": 2.679},
+ {"text": "of", "start": 2.7, "end": 2.799},
+ {"text": "you", "start": 2.839, "end": 2.939},
+ {"text": "said", "start": 3.039, "end": 3.179},
+ {"text": "motion", "start": 3.24, "end": 3.559},
+ {"text": "graphics,", "start": 3.579, "end": 4.599},
+ {"text": "sixty-two", "start": 4.679, "end": 5.179},
+ {"text": "percent", "start": 5.299, "end": 5.759},
+ {"text": "said", "start": 5.859, "end": 5.98},
+ {"text": "static", "start": 6.079, "end": 6.399},
+ {"text": "content", "start": 6.46, "end": 6.879},
+ {"text": "was", "start": 6.92, "end": 7.079},
+ {"text": "costing", "start": 7.099, "end": 7.48},
+ {"text": "you", "start": 7.5, "end": 7.579},
+ {"text": "attention,", "start": 7.679, "end": 8.659},
+ {"text": "and", "start": 8.699, "end": 8.86},
+ {"text": "three", "start": 8.88, "end": 9.06},
+ {"text": "out", "start": 9.079, "end": 9.18},
+ {"text": "of", "start": 9.199, "end": 9.34},
+ {"text": "four", "start": 9.38, "end": 9.799},
+ {"text": "said", "start": 9.84, "end": 10.0},
+ {"text": "you", "start": 10.019, "end": 10.159},
+ {"text": "know", "start": 10.179, "end": 10.36},
+ {"text": "the", "start": 10.38, "end": 10.42},
+ {"text": "look", "start": 10.519, "end": 10.699},
+ {"text": "you", "start": 10.739, "end": 10.859},
+ {"text": "want", "start": 10.98, "end": 11.34},
+ {"text": "but", "start": 11.359, "end": 11.52},
+ {"text": "don't", "start": 11.56, "end": 11.779},
+ {"text": "have", "start": 11.819, "end": 11.94},
+ {"text": "the", "start": 11.96, "end": 12.06},
+ {"text": "editing", "start": 12.079, "end": 12.4},
+ {"text": "skills", "start": 12.52, "end": 12.86},
+ {"text": "to", "start": 12.88, "end": 13.0},
+ {"text": "get", "start": 13.019, "end": 13.18},
+ {"text": "there.", "start": 13.22, "end": 14.22},
+ {"text": "So", "start": 14.239, "end": 14.399},
+ {"text": "we", "start": 14.42, "end": 14.52},
+ {"text": "built", "start": 14.619, "end": 14.88},
+ {"text": "Editor", "start": 15.079, "end": 15.42},
+ {"text": "Agent.", "start": 15.619, "end": 16.02}
+ ];
+
+ // Group words into lines (max 5 words per line)
+ const lines = [];
+ for (let i = 0; i < script.length; i += 5) {
+ const lineWords = script.slice(i, i + 5);
+ lines.push({
+ text: lineWords.map(w => w.text).join(' '),
+ start: lineWords[0].start,
+ end: lineWords[lineWords.length - 1].end
+ });
+ }
+
+ const tl = gsap.timeline({ paused: true });
+ const box = document.querySelector('[data-composition-id="captions"] #caption-box');
+ const textEl = document.querySelector('[data-composition-id="captions"] #caption-text');
+
+ lines.forEach((line, index) => {
+ // Fade in and set text
+ tl.to(box, {
+ opacity: 1,
+ duration: 0.1,
+ ease: "power2.out",
+ onStart: () => {
+ textEl.textContent = line.text;
+ }
+ }, line.start);
+
+ // Fade out at the end of the line
+ tl.to(box, {
+ opacity: 0,
+ duration: 0.1,
+ ease: "power2.in"
+ }, line.end);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-4-prod/src/compositions/graphics.html b/packages/producer/tests/style-4-prod/src/compositions/graphics.html
new file mode 100644
index 0000000000..e684da13de
--- /dev/null
+++ b/packages/producer/tests/style-4-prod/src/compositions/graphics.html
@@ -0,0 +1,157 @@
+<template id="graphics-template">
+ <div data-composition-id="graphics" data-width="1920" data-height="1080" data-duration="14">
+ <!-- Moment 1: 47% Stat (1.8s - 4.5s) -->
+ <div id="moment-1" class="moment circle-stat">
+ <div class="stat-content">
+ <div class="stat-text">47%</div>
+ <div class="stat-desc">Need Motion Graphics</div>
+ </div>
+ </div>
+
+ <!-- Moment 2: 62% Stat (4.6s - 8.6s) -->
+ <div id="moment-2" class="moment pill-stat">
+ <div class="stat-text">62%</div>
+ </div>
+
+ <!-- Moment 3: Editing Skills (8.8s - 14s) -->
+ <div id="moment-3" class="moment rect-stat">
+ <div class="icon-shape">
+ <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
+ <path d="M20,20 Q50,0 80,20 Q100,50 80,80 Q50,100 20,80 Q0,50 20,20" fill="currentColor" />
+ </svg>
+ </div>
+ <div class="stat-text">Editing Skills</div>
+ </div>
+
+ <style>
+ [data-composition-id="graphics"] {
+ position: relative;
+ width: 1920px;
+ height: 1080px;
+ font-family: 'Outfit', sans-serif;
+ color: white;
+ overflow: hidden;
+ }
+
+ [data-composition-id="graphics"] .moment {
+ position: absolute;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0;
+ /* We'll use GSAP to handle the centering and drift */
+ }
+
+ /* Moment 1: Forest Green Circle */
+ [data-composition-id="graphics"] #moment-1 {
+ width: 500px;
+ height: 500px;
+ background-color: #3B5E3A;
+ border-radius: 50%;
+ left: 1400px;
+ top: 540px;
+ transform: translate(-50%, -50%);
+ }
+
+ [data-composition-id="graphics"] .stat-content {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ text-align: center;
+ }
+
+ [data-composition-id="graphics"] .stat-desc {
+ font-size: 36px;
+ font-weight: 400;
+ margin-top: 10px;
+ max-width: 300px;
+ line-height: 1.2;
+ }
+
+ /* Moment 2: Ochre Pill */
+ [data-composition-id="graphics"] #moment-2 {
+ width: 500px;
+ height: 220px;
+ background-color: #CC8832;
+ border-radius: 110px;
+ left: 960px;
+ top: 200px;
+ transform: translate(-50%, -50%);
+ }
+
+ /* Moment 3: Terracotta Rounded Rect */
+ [data-composition-id="graphics"] #moment-3 {
+ width: 550px;
+ height: 180px;
+ background-color: #C45D3E;
+ border-radius: 40px;
+ left: 400px;
+ top: 540px;
+ transform: translate(-50%, -50%);
+ padding: 0 40px;
+ justify-content: center;
+ gap: 30px;
+ }
+
+ [data-composition-id="graphics"] .stat-text {
+ font-size: 80px;
+ font-weight: 700;
+ letter-spacing: -2px;
+ }
+
+ [data-composition-id="graphics"] #moment-3 .stat-text {
+ font-size: 54px;
+ letter-spacing: -1px;
+ }
+
+ [data-composition-id="graphics"] .icon-shape {
+ width: 80px;
+ height: 80px;
+ color: rgba(255, 255, 255, 0.9);
+ }
+
+ [data-composition-id="graphics"] .icon-shape svg {
+ width: 100%;
+ height: 100%;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // Moment 1: 1.8s - 4.5s
+ // Gentle drift into place and settle
+ tl.fromTo('#moment-1',
+ { opacity: 0, x: '+=40', y: '+=15', scale: 0.8 },
+ { opacity: 1, x: 0, y: 0, scale: 1, duration: 1.2, ease: 'back.out(1.7)' },
+ 1.8
+ );
+ // Hold until 4.5s, then fade out
+ tl.to('#moment-1', { opacity: 0, scale: 0.8, duration: 0.3, ease: 'power2.in' }, 4.2);
+
+ // Moment 2: 4.6s - 8.6s
+ // Gentle drift into place and settle
+ tl.fromTo('#moment-2',
+ { opacity: 0, y: '-=40', x: '+=10', scale: 0.8 },
+ { opacity: 1, y: 0, x: 0, scale: 1, duration: 1.2, ease: 'back.out(1.7)' },
+ 4.6
+ );
+ // Hold until 8.6s, then fade out
+ tl.to('#moment-2', { opacity: 0, scale: 0.8, duration: 0.3, ease: 'power2.in' }, 8.3);
+
+ // Moment 3: 8.8s - 14s
+ // Gentle drift into place and settle
+ tl.fromTo('#moment-3',
+ { opacity: 0, x: '-=40', y: '-=10', scale: 0.8 },
+ { opacity: 1, x: 0, y: 0, scale: 1, duration: 1.2, ease: 'back.out(1.7)' },
+ 8.8
+ );
+ // Hold until end (14s)
+ tl.to('#moment-3', { opacity: 0, duration: 0.5, ease: 'power2.in' }, 13.5);
+
+ window.__timelines["graphics"] = tl;
+ })();
+ </script>
+ </div>
+</template>
\ No newline at end of file
diff --git a/packages/producer/tests/style-4-prod/src/compositions/intro.html b/packages/producer/tests/style-4-prod/src/compositions/intro.html
new file mode 100644
index 0000000000..e17051e369
--- /dev/null
+++ b/packages/producer/tests/style-4-prod/src/compositions/intro.html
@@ -0,0 +1,77 @@
+<template id="intro-template">
+ <div data-composition-id="intro" data-width="1920" data-height="1080" data-duration="3">
+ <div class="container">
+ <div class="title-card">
+ <h1 class="title">Editor Agent</h1>
+ <p class="subtitle">Design simplified.</p>
+ </div>
+ </div>
+
+ <style>
+ /* Import a rounded humanist sans-serif font */
+ @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;600&display=swap');
+
+ [data-composition-id="intro"] .container {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: flex-start; /* Align to left for speaker card */
+ align-items: center;
+ padding-left: 5%;
+ font-family: 'Outfit', sans-serif;
+ background: transparent;
+ }
+
+ [data-composition-id="intro"] .title-card {
+ background-color: #3B5E3A; /* Forest Green for contrast */
+ padding: 40px 60px;
+ border-radius: 30px;
+ box-shadow: 0 15px 40px rgba(0,0,0,0.2);
+ text-align: left;
+ opacity: 0;
+ transform: translateX(-100%); /* Start off-screen left */
+ }
+
+ [data-composition-id="intro"] .title {
+ font-size: 100px;
+ font-weight: 600;
+ color: #F5F0E0; /* Cream text on green card */
+ margin: 0;
+ line-height: 1.1;
+ letter-spacing: -2px;
+ }
+
+ [data-composition-id="intro"] .subtitle {
+ font-size: 50px;
+ font-weight: 400;
+ color: #CC8832; /* Ochre accent */
+ margin: 10px 0 0 0;
+ line-height: 1.2;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // Animation: Speaker card slides in from the left
+ tl.to('[data-composition-id="intro"] .title-card', {
+ opacity: 1,
+ x: 0,
+ duration: 0.8,
+ ease: 'power2.out'
+ }, 0.2);
+
+ // Exit: Slide off left at 1.8s (synced with 47% graphic)
+ tl.to('[data-composition-id="intro"] .title-card', {
+ x: '-120%',
+ opacity: 0,
+ duration: 0.6,
+ ease: 'power2.in'
+ }, 1.8);
+
+ window.__timelines["intro"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-4-prod/src/design_review.md b/packages/producer/tests/style-4-prod/src/design_review.md
new file mode 100644
index 0000000000..33abcb5891
--- /dev/null
+++ b/packages/producer/tests/style-4-prod/src/design_review.md
@@ -0,0 +1,58 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a "warm and cozy" template that's trying too hard to be organic and ends up feeling like a corporate HR presentation from 2018. The "grain" is a lazy attempt at personality, and the layout is a chaotic mess of shifting boxes that lack any real editorial rhythm.
+
+---
+
+## CRITICAL Design Failures
+
+### The "Drunken" A-Roll Framing
+**Where:** `index.html` (GSAP timeline)
+**What's wrong:** The video is constantly shifting, scaling, and sliding around the screen like it's trying to escape the viewer. At one point it's at `x: 1100`, then `x: 600`, then `y: 750`, then `x: 1320`.
+**Why it matters:** It’s physically nauseating. Instead of creating a dynamic layout, you've created a composition that feels unstable. The viewer's eyes never know where to settle because the primary subject (the speaker) is in a state of perpetual motion for no reason.
+**Fix it:** Pick two or three solid "anchor" layouts (e.g., Left-Third, Right-Third, Center-Full) and snap between them with intent. Stop the slow, aimless drifting.
+
+### The "Safety First" Color Palette
+**Where:** `compositions/intro.html`, `compositions/graphics.html`
+**What's wrong:** Forest Green (`#3B5E3A`), Ochre (`#CC8832`), and Terracotta (`#C45D3E`) on a Cream background. It’s the "Earth Tones Starter Pack." It’s safe, it’s boring, and it has zero energy for a video about "Editor Agents" and "Motion Graphics."
+**Why it matters:** There is no visual "pop." The colors are so muted they bleed into each other, making the graphics feel heavy and dated rather than modern and sharp.
+**Fix it:** Introduce a high-contrast accent color or lean harder into a monochromatic sophisticated look. Right now, it looks like a brochure for a national park.
+
+### Caption Box Suffocation
+**Where:** `compositions/captions.html`
+**What's wrong:** The caption box has a fixed `padding: 12px 32px` and a `min-width: 100px`, but the text inside is a massive `48px` bold Outfit. When the text gets long, it’s going to hit the edges of that box and look like it's trying to burst out.
+**Why it matters:** It lacks "breathing room." Good typography needs negative space to feel premium. This feels cramped and amateur.
+**Fix it:** Increase the padding significantly or use a dynamic width that scales better with the text. Also, consider a semi-transparent background instead of that solid muddy brown (`#7A6248`).
+
+---
+
+## Design Improvements
+
+### The "Grain" is a Lie
+**Where:** `index.html` (`.grain-texture`)
+**The problem:** You’re using a static PNG pattern (`natural-paper.png`) and jittering it at `0.15` opacity. It doesn't look like film grain; it looks like the screen is dirty.
+**Make it better:** Use a real SVG noise filter or a higher-frequency noise. If you want "Warm Grain," make it feel like a texture, not a CSS glitch.
+
+### Robotic Graphic Entrances
+**Where:** `compositions/graphics.html`
+**The problem:** Every single graphic uses the exact same `back.out(1.7)` ease. It’s the "My First GSAP Animation" preset.
+**Make it better:** Vary the entrance logic. Maybe the pill slides in, the circle expands from the center, and the rectangle fades with a staggered text reveal. Giving everything the same "bounce" makes the whole video feel repetitive by the 5-second mark.
+
+---
+
+## What Actually Works
+
+### Typography Choice
+The use of **Outfit** is actually a decent choice. It’s a clean, geometric sans-serif that bridges the gap between "tech" and "friendly." The weights are used correctly to create some semblance of hierarchy in the intro, even if the rest of the design fails it.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 3/10 - It’s forgettable. It looks like a template you’d find on page 4 of a stock site.
+**Color & Typography:** 5/10 - Typography is fine; the color palette is a snooze-fest.
+**Motion & Animation Feel:** 2/10 - The A-roll movement is erratic and the graphic eases are generic.
+**Overall Aesthetic:** 3/10 - "Corporate Organic" is a hard look to pull off, and this doesn't do it.
+
+**Bottom Line:** I wouldn't show this to a client unless I wanted them to fall asleep or get motion sickness. It needs a complete overhaul of the layout strategy and a much bolder approach to color.
diff --git a/packages/producer/tests/style-4-prod/src/index.html b/packages/producer/tests/style-4-prod/src/index.html
new file mode 100644
index 0000000000..a4702ab04d
--- /dev/null
+++ b/packages/producer/tests/style-4-prod/src/index.html
@@ -0,0 +1,195 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Warm Grain - Editor Agent</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1920px;
+ height: 1080px;
+ overflow: hidden;
+ background-color: #F5F0E0; /* Cream background */
+ font-family: 'Outfit', 'Lexend', sans-serif;
+ }
+
+ #main-composition {
+ position: relative;
+ width: 1920px;
+ height: 1080px;
+ overflow: hidden;
+ }
+
+ /* Paper texture and Grain overlay */
+ #grain-overlay-comp {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ z-index: 100;
+ }
+
+ /* Grain animation */
+ @keyframes grain-noise {
+ 0%, 100% { transform: translate(0, 0); }
+ 10% { transform: translate(-5%, -5%); }
+ 20% { transform: translate(-10%, 5%); }
+ 30% { transform: translate(5%, -10%); }
+ 40% { transform: translate(-5%, 15%); }
+ 50% { transform: translate(-10%, 5%); }
+ 60% { transform: translate(15%, 0); }
+ 70% { transform: translate(0, 10%); }
+ 80% { transform: translate(-15%, 0); }
+ 90% { transform: translate(10%, 5%); }
+ }
+
+ .grain-texture {
+ position: absolute;
+ top: -50%;
+ left: -50%;
+ width: 200%;
+ height: 200%;
+ background: url('https://www.transparenttextures.com/patterns/natural-paper.png');
+ opacity: 0.15;
+ animation: grain-noise 0.5s steps(1) infinite;
+ }
+
+ #a-roll {
+ position: absolute;
+ border-radius: 16px;
+ object-fit: cover;
+ box-shadow: 0 10px 30px rgba(0,0,0,0.1);
+ }
+
+ .comp-layer {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ }
+ </style>
+</head>
+<body>
+ <div id="main-composition" data-composition-id="main-video" data-width="1920" data-height="1080" data-duration="17">
+
+ <!-- Background Layer -->
+ <div id="grain-overlay-comp" data-composition-id="grain-overlay" data-width="1920" data-height="1080" data-duration="17" data-track-index="100">
+ <div class="grain-texture"></div>
+ <script>
+ const grainTl = gsap.timeline({ paused: true });
+ window.__timelines["grain-overlay"] = grainTl;
+ </script>
+ </div>
+
+ <!-- A-Roll Video -->
+ <video id="a-roll"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/2111e840_0579531a2ffe4c3ea8295b42051fb394.mp4"
+ data-start="0"
+ data-duration="17"
+ data-track-index="0">
+ </video>
+
+ <!-- Compositions -->
+ <div id="intro-layer" class="comp-layer"
+ data-composition-id="intro"
+ data-composition-src="compositions/intro.html"
+ data-start="0"
+ data-duration="2.5"
+ data-track-index="1">
+ </div>
+
+ <div id="graphics-layer" class="comp-layer"
+ data-composition-id="graphics"
+ data-composition-src="compositions/graphics.html"
+ data-start="0"
+ data-duration="17"
+ data-track-index="2">
+ </div>
+
+ <div id="captions-layer" class="comp-layer"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="17"
+ data-track-index="3">
+ </div>
+
+ <!-- SFX -->
+ <audio id="sfx-swipe-1" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/3af40f3b_386326216dcf4956984e4c1c25663cdd.mp3" data-start="1.8" data-duration="1" data-track-index="4"></audio>
+ <audio id="sfx-swipe-2" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/3af40f3b_386326216dcf4956984e4c1c25663cdd.mp3" data-start="4.6" data-duration="1" data-track-index="4"></audio>
+ <audio id="sfx-swipe-3" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/3af40f3b_386326216dcf4956984e4c1c25663cdd.mp3" data-start="8.8" data-duration="1" data-track-index="4"></audio>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+
+ // A-Roll Framing Strategy
+ // 1. 0s-1.8s: Intro scale up from small (60%) to medium (80%) - Shifted right slightly to clear speaker card
+ // 2. 1.8s-4.6s: Grid view / Shift Left (x: 600, scale: 70%) for 47% graphic
+ // 3. 4.6s-8.8s: Shift Center-Bottom (y: 800, scale: 70%) for 62% graphic (top)
+ // 4. 8.8s-14s: Shift Right (x: 1320, scale: 75%) for Editing Skills graphic (left)
+ // 5. 14s-17s: Final Reveal (Center, scale: 100%)
+
+ // Initial state
+ gsap.set('#a-roll', { x: 1100, y: 540, xPercent: -50, yPercent: -50, width: 1920 * 0.6, height: 1080 * 0.6 });
+
+ // 1. Intro Scale Up (0s - 1.8s)
+ tl.to('#a-roll', {
+ x: 1200,
+ width: 1920 * 0.8,
+ height: 1080 * 0.8,
+ duration: 1.8,
+ ease: "power2.inOut"
+ }, 0);
+
+ // 2. Moment 1: 47% Graphic Trigger (1.8s) - Shift Left
+ tl.to('#a-roll', {
+ x: 600,
+ y: 540,
+ width: 1920 * 0.7,
+ height: 1080 * 0.7,
+ duration: 0.5,
+ ease: "power2.inOut"
+ }, 1.8);
+
+ // 3. Moment 2: 62% Graphic Trigger (4.6s) - Shift Center-Bottom
+ tl.to('#a-roll', {
+ x: 960,
+ y: 750,
+ width: 1920 * 0.7,
+ height: 1080 * 0.7,
+ duration: 0.5,
+ ease: "power2.inOut"
+ }, 4.6);
+
+ // 4. Moment 3: Editing Skills Trigger (8.8s) - Shift Right
+ tl.to('#a-roll', {
+ x: 1320,
+ y: 540,
+ width: 1920 * 0.75,
+ height: 1080 * 0.75,
+ duration: 0.5,
+ ease: "power2.inOut"
+ }, 8.8);
+
+ // 5. Final Reveal (14s - 17s)
+ tl.to('#a-roll', {
+ x: 960,
+ y: 540,
+ width: 1920 * 1.0,
+ height: 1080 * 1.0,
+ duration: 1.0,
+ ease: "power2.inOut"
+ }, 14);
+
+ window.__timelines["main-video"] = tl;
+ </script>
+ </div>
+</body>
+</html>
diff --git a/packages/producer/tests/style-5-prod/meta.json b/packages/producer/tests/style-5-prod/meta.json
new file mode 100644
index 0000000000..c2fe76cf63
--- /dev/null
+++ b/packages/producer/tests/style-5-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-5-prod",
+ "description": "Regression fixture imported from normalized style pack style-5-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "landscape"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-5-prod/src/code_review.md b/packages/producer/tests/style-5-prod/src/code_review.md
new file mode 100644
index 0000000000..9051aabb5c
--- /dev/null
+++ b/packages/producer/tests/style-5-prod/src/code_review.md
@@ -0,0 +1,67 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 5
+- Critical issues: 1
+- Overall compliance status: NEEDS_WORK
+
+## Critical Issues
+
+### Empty Tween for Duration
+- **File**: compositions/captions.html:98
+- **Violation**: `tl.to({}, { duration: 2 });`
+- **Schema Rule**: "**NEVER create empty tweens** like `tl.to({}, { duration: N })` just to set duration — use `data-duration` instead"
+- **Impact**: Violates the declarative timing model. The framework uses `data-duration` to determine the composition's length on the master timeline.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images used)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (no circular refs, referenced clips have known duration)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+## File-Specific Reviews
+
+### index.html
+**Status**: COMPLIANT
+- Correctly uses `data-composition-id`, `data-width`, `data-height`, and `data-duration`.
+- Correctly loads sub-compositions using `data-composition-src`.
+- Registers `master` timeline in `window.__timelines`.
+- **Note**: The `video` element (line 67) uses an absolute `data-start="3"`. This is valid.
+
+### compositions/intro-seq.html
+**Status**: COMPLIANT
+- Correctly uses `<template>` and `data-composition-id`.
+- Dimensions and duration are explicitly set.
+- Script is deterministic (uses fixed text and timing).
+- Registers `intro-seq` timeline.
+
+### compositions/grid-bg.html
+**Status**: COMPLIANT
+- Correctly uses `<template>` and `data-composition-id`.
+- Dimensions and duration are explicitly set.
+- Loops are finite and deterministic.
+- Registers `grid-bg` timeline.
+
+### compositions/captions.html
+**Status**: HAS_ISSUES
+- **Issue**: Line 98 uses an empty tween `tl.to({}, { duration: 2 })` to extend the timeline.
+- **Fix**: Remove the empty tween. The duration is already correctly defined in the `data-duration="16.04"` attribute on the root `div` (line 2).
+- **Issue**: The `data-duration` is set to `16.04`, but the last caption ends at `16.019`. This is fine as `data-duration` takes precedence.
+
+### compositions/data-graphics.html
+**Status**: COMPLIANT
+- Correctly uses `<template>` and `data-composition-id`.
+- Dimensions and duration are explicitly set.
+- Counter animation is deterministic in its logic.
+- Registers `data-graphics` timeline.
diff --git a/packages/producer/tests/style-5-prod/src/compositions/background.html b/packages/producer/tests/style-5-prod/src/compositions/background.html
new file mode 100644
index 0000000000..cf3c1911ab
--- /dev/null
+++ b/packages/producer/tests/style-5-prod/src/compositions/background.html
@@ -0,0 +1,111 @@
+<template id="background-template">
+ <div data-composition-id="background" data-width="1920" data-height="1080" data-duration="19.04">
+ <div class="grid-container">
+ <div class="modular-grid"></div>
+ <div class="dot-matrix"></div>
+ <div class="scan-line"></div>
+ </div>
+
+ <style>
+ [data-composition-id="background"] {
+ width: 1920px;
+ height: 1080px;
+ background-color: #0A0A0A;
+ overflow: hidden;
+ position: relative;
+ }
+
+ [data-composition-id="background"] .grid-container {
+ width: 100%;
+ height: 100%;
+ position: absolute;
+ top: 0;
+ left: 0;
+ }
+
+ /* Modular Grid Lines - Subtle and Technical */
+ [data-composition-id="background"] .modular-grid {
+ width: calc(100% + 100px); /* Extra width for drift */
+ height: 100%;
+ position: absolute;
+ top: 0;
+ left: 0;
+ background-image:
+ linear-gradient(to right, rgba(138, 138, 138, 0.05) 1px, transparent 1px),
+ linear-gradient(to bottom, rgba(138, 138, 138, 0.05) 1px, transparent 1px);
+ background-size: 60px 60px;
+ }
+
+ /* Dot Matrix Pattern - Finer and Sophisticated */
+ [data-composition-id="background"] .dot-matrix {
+ width: 100%;
+ height: 100%;
+ position: absolute;
+ top: 0;
+ left: 0;
+ background-image: radial-gradient(rgba(138, 138, 138, 0.1) 1px, transparent 1px);
+ background-size: 20px 20px;
+ }
+
+ /* Scan Line - Subtle Texture */
+ [data-composition-id="background"] .scan-line {
+ width: 100%;
+ height: 100px; /* Taller for a softer gradient feel */
+ background: linear-gradient(to bottom,
+ transparent,
+ rgba(26, 26, 26, 0.1) 50%,
+ transparent
+ );
+ position: absolute;
+ top: -100px;
+ left: 0;
+ z-index: 10;
+ pointer-events: none;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const duration = 19.04;
+
+ // 1. Subtle Grid Drift
+ // Move 60px (one grid unit) horizontally over the full duration
+ tl.to('[data-composition-id="background"] .modular-grid', {
+ x: -60,
+ duration: duration,
+ ease: "none"
+ }, 0);
+
+ // 2. Subtle Scan Line Texture
+ // Dark gray/blue (#1A1A1A) at 0.1 opacity
+ const scanCycle = 8; // Slower, more sophisticated movement
+ const cycles = Math.ceil(duration / scanCycle);
+
+ for (let i = 0; i < cycles; i++) {
+ tl.fromTo('[data-composition-id="background"] .scan-line',
+ { y: -100 },
+ {
+ y: 1180,
+ duration: scanCycle,
+ ease: "none"
+ },
+ i * scanCycle
+ );
+ }
+
+ // 3. Ambient Opacity Pulse
+ // Very subtle breathing effect for the dot matrix
+ tl.to('[data-composition-id="background"] .dot-matrix', {
+ opacity: 0.6,
+ duration: duration / 2,
+ ease: "sine.inOut",
+ yoyo: true,
+ repeat: 1
+ }, 0);
+
+ window.__timelines["background"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-5-prod/src/compositions/captions.html b/packages/producer/tests/style-5-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..6577a6263b
--- /dev/null
+++ b/packages/producer/tests/style-5-prod/src/compositions/captions.html
@@ -0,0 +1,101 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1920" data-height="1080" data-duration="16.04">
+ <div id="captions-container"></div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@700&display=swap');
+
+ [data-composition-id="captions"] {
+ width: 1920px;
+ height: 1080px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ pointer-events: none;
+ background: transparent;
+ }
+
+ [data-composition-id="captions"] #captions-container {
+ width: 100%;
+ height: 100%;
+ position: relative;
+ display: flex;
+ justify-content: center;
+ align-items: flex-end; /* Align to bottom */
+ padding-bottom: 100px; /* Offset from the very bottom edge */
+ }
+
+ .caption-line {
+ position: absolute;
+ bottom: 15%; /* Positioned in the bottom 3rd */
+ left: 50%;
+ transform: translateX(-50%);
+ width: 90%; /* Prevent bleeding */
+ max-width: 1728px; /* 1920 * 0.9 */
+ font-family: 'Space Mono', monospace;
+ font-weight: 700;
+ font-size: 64px;
+ color: #33FF66;
+ text-transform: uppercase;
+ text-align: center;
+ opacity: 0;
+ line-height: 1.2;
+ white-space: normal; /* Allow wrapping if necessary, though groups are short */
+ word-wrap: break-word;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.839, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics.', 'start': 3.579, 'end': 4.639}, {'text': 'Sixty-two', 'start': 4.659, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.099, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.479}, {'text': 'look', 'start': 10.52, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.86}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Editor', 'start': 15.079, 'end': 15.42}, {'text': 'Agent', 'start': 15.619, 'end': 16.019}];
+ const container = document.getElementById('captions-container');
+ const tl = gsap.timeline({ paused: true });
+
+ // Grouping logic based on the provided transcript and timing
+ // We use the transcript token directly to ensure deterministic behavior
+ // and sync with the actual audio.
+
+ const captionGroups = [
+ { text: 'WE ASKED WHAT YOU NEEDED.', start: 0.119, end: 1.839 },
+ { text: 'FORTY-SEVEN PERCENT OF YOU SAID', start: 1.839, end: 3.24 },
+ { text: 'MOTION GRAPHICS.', start: 3.24, end: 4.659 },
+ { text: 'SIXTY-TWO PERCENT SAID STATIC', start: 4.659, end: 6.46 },
+ { text: 'CONTENT WAS COSTING YOU ATTENTION,', start: 6.46, end: 8.699 },
+ { text: 'AND THREE OUT OF FOUR', start: 8.699, end: 9.84 },
+ { text: 'SAID YOU KNOW THE LOOK', start: 9.84, end: 10.739 },
+ { text: 'YOU WANT BUT DON\'T HAVE', start: 10.739, end: 11.96 },
+ { text: 'THE EDITING SKILLS TO GET', start: 11.96, end: 13.22 },
+ { text: 'THERE. SO WE BUILT EDITOR', start: 13.22, end: 15.619 },
+ { text: 'AGENT', start: 15.619, end: 16.019 }
+ ];
+
+ captionGroups.forEach((group, index) => {
+ const div = document.createElement('div');
+ div.className = 'caption-line';
+ div.id = `caption-${index}`;
+ div.textContent = group.text;
+ container.appendChild(div);
+
+ // Show the caption
+ // Using a very short duration for a "cut" effect, or 0 for instant
+ tl.to(div, {
+ opacity: 1,
+ duration: 0.05,
+ ease: "none"
+ }, group.start);
+
+ // Hide the caption when the next one starts, or at its end if it's the last one
+ const hideTime = (index < captionGroups.length - 1) ? captionGroups[index + 1].start : group.end;
+
+ tl.to(div, {
+ opacity: 0,
+ duration: 0.05,
+ ease: "none"
+ }, hideTime);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-5-prod/src/compositions/data-graphics.html b/packages/producer/tests/style-5-prod/src/compositions/data-graphics.html
new file mode 100644
index 0000000000..6ff2323732
--- /dev/null
+++ b/packages/producer/tests/style-5-prod/src/compositions/data-graphics.html
@@ -0,0 +1,326 @@
+<template id="data-graphics-template">
+ <div data-composition-id="data-graphics" data-width="1920" data-height="1080" data-duration="16.04">
+ <div class="grid-container">
+ <!-- Graphic 1: 47% NEED MOTION GRAPHICS -->
+ <div id="graphic-1" class="graphic-box" style="opacity: 0;">
+ <div class="label">47% NEED MOTION GRAPHICS</div>
+ <div class="progress-bar-container">
+ <div class="progress-bar-bg"></div>
+ <div id="bar-1" class="progress-bar-fill"></div>
+ </div>
+ <div id="counter-1" class="counter">00%</div>
+ </div>
+
+ <!-- Graphic 2: 62% LOSE ATTENTION -->
+ <div id="graphic-2" class="graphic-box" style="opacity: 0;">
+ <div class="label">62% LOSE ATTENTION</div>
+ <div class="chart-container">
+ <div class="bar-group">
+ <div class="bar-label">STATIC</div>
+ <div class="bar-wrapper"><div id="bar-2-static" class="bar-fill gray"></div></div>
+ </div>
+ <div class="bar-group">
+ <div class="bar-label">MOTION</div>
+ <div id="counter-2" class="counter small">00%</div>
+ <div class="bar-wrapper"><div id="bar-2-motion" class="bar-fill green"></div></div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Graphic 3: 75% LACK SKILLS -->
+ <div id="graphic-3" class="graphic-box" style="opacity: 0;">
+ <div class="label">75% LACK SKILLS</div>
+ <div class="radial-container">
+ <div class="radial-svg-wrapper">
+ <svg viewBox="0 0 100 100" class="radial-svg">
+ <circle cx="50" cy="50" r="45" class="radial-bg" />
+ <circle id="radial-fill" cx="50" cy="50" r="45" class="radial-progress" />
+ </svg>
+ </div>
+ <div id="counter-3" class="counter">00%</div>
+ </div>
+ </div>
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap');
+
+ [data-composition-id="data-graphics"] {
+ background: transparent;
+ font-family: 'Space Mono', monospace;
+ text-transform: uppercase;
+ color: #8A8A8A;
+ overflow: hidden;
+ width: 1920px;
+ height: 1080px;
+ }
+
+ [data-composition-id="data-graphics"] .grid-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ display: grid;
+ grid-template-columns: repeat(24, 1fr);
+ grid-template-rows: repeat(12, 1fr);
+ padding: 40px;
+ gap: 0; /* Removed gap for precise grid snapping */
+ }
+
+ [data-composition-id="data-graphics"] .graphic-box {
+ grid-column: 18 / 25; /* Positioned on the right side for A-roll scale down */
+ background: rgba(0, 0, 0, 0.6);
+ backdrop-filter: blur(10px);
+ -webkit-backdrop-filter: blur(10px);
+ border: 1px solid rgba(138, 138, 138, 0.4);
+ padding: 30px;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: flex-start;
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
+ }
+
+ [data-composition-id="data-graphics"] #graphic-1 { grid-row: 2 / 5; margin-bottom: 10px; }
+ [data-composition-id="data-graphics"] #graphic-2 { grid-row: 5 / 8; margin-bottom: 10px; }
+ [data-composition-id="data-graphics"] #graphic-3 { grid-row: 8 / 11; }
+
+ [data-composition-id="data-graphics"] .label {
+ font-size: 20px;
+ font-weight: 700;
+ margin-bottom: 20px;
+ letter-spacing: 1px;
+ color: rgba(255, 255, 255, 0.9);
+ }
+
+ [data-composition-id="data-graphics"] .counter {
+ font-size: 48px;
+ font-weight: 700;
+ color: rgba(51, 255, 102, 0.9); /* Softened green with opacity */
+ margin-top: 15px;
+ }
+
+ [data-composition-id="data-graphics"] .counter.small {
+ font-size: 32px;
+ margin-top: 0;
+ margin-bottom: 10px;
+ }
+
+ /* Progress Bar Styles */
+ [data-composition-id="data-graphics"] .progress-bar-container {
+ width: 100%;
+ height: 24px;
+ position: relative;
+ background: rgba(138, 138, 138, 0.1);
+ border: 1px solid rgba(138, 138, 138, 0.3);
+ }
+
+ [data-composition-id="data-graphics"] .progress-bar-bg {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: repeating-linear-gradient(90deg, rgba(138, 138, 138, 0.2), rgba(138, 138, 138, 0.2) 2px, transparent 2px, transparent 12px);
+ }
+
+ [data-composition-id="data-graphics"] .progress-bar-fill {
+ position: absolute;
+ top: 0;
+ left: 0;
+ height: 100%;
+ background: rgba(51, 255, 102, 0.8); /* Softened green */
+ width: 0%;
+ }
+
+ /* Bar Chart Styles */
+ [data-composition-id="data-graphics"] .chart-container {
+ width: 100%;
+ display: flex;
+ gap: 30px;
+ height: 140px;
+ align-items: flex-end;
+ }
+
+ [data-composition-id="data-graphics"] .bar-group {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ flex: 1;
+ }
+
+ [data-composition-id="data-graphics"] .bar-label {
+ font-size: 12px;
+ margin-bottom: 10px;
+ color: rgba(138, 138, 138, 0.8);
+ }
+
+ [data-composition-id="data-graphics"] .bar-wrapper {
+ width: 100%;
+ height: 100px;
+ background: rgba(138, 138, 138, 0.1);
+ border: 1px solid rgba(138, 138, 138, 0.3);
+ position: relative;
+ }
+
+ [data-composition-id="data-graphics"] .bar-fill {
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ width: 100%;
+ height: 0%;
+ }
+
+ [data-composition-id="data-graphics"] .bar-fill.green { background: rgba(51, 255, 102, 0.8); }
+ [data-composition-id="data-graphics"] .bar-fill.gray { background: rgba(138, 138, 138, 0.5); }
+
+ /* Radial Styles */
+ [data-composition-id="data-graphics"] .radial-container {
+ width: 100%;
+ display: flex;
+ align-items: center;
+ gap: 40px;
+ }
+
+ [data-composition-id="data-graphics"] .radial-svg-wrapper {
+ width: 110px;
+ height: 110px;
+ transform: rotate(-90deg);
+ }
+
+ [data-composition-id="data-graphics"] .radial-svg {
+ width: 100%;
+ height: 100%;
+ }
+
+ [data-composition-id="data-graphics"] .radial-bg {
+ fill: none;
+ stroke: rgba(138, 138, 138, 0.2);
+ stroke-width: 10;
+ stroke-dasharray: 4 4;
+ }
+
+ [data-composition-id="data-graphics"] .radial-progress {
+ fill: none;
+ stroke: rgba(51, 255, 102, 0.8);
+ stroke-width: 10;
+ stroke-dasharray: 282.74; /* 2 * PI * 45 */
+ stroke-dashoffset: 282.74;
+ stroke-linecap: round;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const REVEAL_DURATION = 0.8;
+ const EASE = "power2.out";
+ const graphicSelectors = [
+ '[data-composition-id="data-graphics"] #graphic-1',
+ '[data-composition-id="data-graphics"] #graphic-2',
+ '[data-composition-id="data-graphics"] #graphic-3'
+ ];
+
+ // Helper for counter animation
+ function animateCounter(id, target, duration, startTime) {
+ const obj = { val: 0 };
+ const el = document.querySelector(`[data-composition-id="data-graphics"] #${id}`);
+ if (!el) return;
+
+ tl.to(obj, {
+ val: target,
+ duration: duration,
+ ease: EASE,
+ onUpdate: () => {
+ el.innerText = Math.floor(obj.val).toString().padStart(2, '0') + '%';
+ }
+ }, startTime);
+ }
+
+ gsap.set(graphicSelectors, { x: 24 });
+
+ // 1. 47% NEED MOTION GRAPHICS at 1.839s
+ tl.to('[data-composition-id="data-graphics"] #graphic-1', {
+ opacity: 1,
+ x: 0,
+ duration: 0.5,
+ ease: "power2.out"
+ }, 1.839);
+
+ tl.to('[data-composition-id="data-graphics"] #bar-1', {
+ width: '47%',
+ duration: REVEAL_DURATION,
+ ease: EASE
+ }, 1.839 + 0.2);
+
+ animateCounter('counter-1', 47, REVEAL_DURATION, 1.839 + 0.2);
+
+ // 2. 62% LOSE ATTENTION at 4.659s
+ tl.to('[data-composition-id="data-graphics"] #graphic-2', {
+ opacity: 1,
+ duration: 0.5,
+ ease: "power2.out"
+ }, 4.659);
+
+ tl.to('[data-composition-id="data-graphics"] #bar-2-static', {
+ height: '30%',
+ duration: REVEAL_DURATION,
+ ease: EASE
+ }, 4.659 + 0.2);
+
+ tl.to('[data-composition-id="data-graphics"] #bar-2-motion', {
+ height: '62%',
+ duration: REVEAL_DURATION,
+ ease: EASE
+ }, 4.659 + 0.4);
+
+ animateCounter('counter-2', 62, REVEAL_DURATION, 4.659 + 0.4);
+
+ // 3. 75% LACK SKILLS at 8.88s
+ tl.to('[data-composition-id="data-graphics"] #graphic-3', {
+ opacity: 1,
+ duration: 0.5,
+ ease: "power2.out"
+ }, 8.88);
+
+ const circumference = 282.74;
+ const offset = circumference - (0.75 * circumference);
+
+ tl.to('[data-composition-id="data-graphics"] #radial-fill', {
+ strokeDashoffset: offset,
+ duration: REVEAL_DURATION,
+ ease: EASE
+ }, 8.88 + 0.2);
+
+ animateCounter('counter-3', 75, REVEAL_DURATION, 8.88 + 0.2);
+
+ // A one-way settle keeps the UI alive without repeat/yoyo timeline noise.
+ const greenElements = [
+ '[data-composition-id="data-graphics"] .progress-bar-fill',
+ '[data-composition-id="data-graphics"] .bar-fill.green',
+ '[data-composition-id="data-graphics"] .radial-progress',
+ '[data-composition-id="data-graphics"] .counter'
+ ];
+
+ gsap.set(greenElements, { opacity: 0.85 });
+ tl.to(greenElements, {
+ opacity: 1,
+ duration: 1.2,
+ stagger: 0.08,
+ ease: "none"
+ }, 2);
+
+ // Outro: Fade all out near the end
+ tl.to(['[data-composition-id="data-graphics"] #graphic-1', '[data-composition-id="data-graphics"] #graphic-2', '[data-composition-id="data-graphics"] #graphic-3'], {
+ opacity: 0,
+ y: 20,
+ duration: 0.5,
+ ease: "power2.in"
+ }, 15.5);
+
+ window.__timelines["data-graphics"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-5-prod/src/compositions/grid-bg.html b/packages/producer/tests/style-5-prod/src/compositions/grid-bg.html
new file mode 100644
index 0000000000..e688c5894c
--- /dev/null
+++ b/packages/producer/tests/style-5-prod/src/compositions/grid-bg.html
@@ -0,0 +1,87 @@
+<template id="grid-bg-template">
+ <div data-composition-id="grid-bg" data-width="1920" data-height="1080" data-duration="19.04">
+ <div class="bg-container">
+ <div class="grid-overlay"></div>
+ <div class="scan-line"></div>
+ </div>
+
+ <style>
+ [data-composition-id="grid-bg"] .bg-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1920px;
+ height: 1080px;
+ background-color: #0A0A0A;
+ overflow: hidden;
+ }
+
+ [data-composition-id="grid-bg"] .grid-overlay {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ /* 40px grid pattern using linear-gradients */
+ background-image:
+ linear-gradient(to right, rgba(138, 138, 138, 0.1) 1px, transparent 1px),
+ linear-gradient(to bottom, rgba(138, 138, 138, 0.1) 1px, transparent 1px);
+ background-size: 40px 40px;
+ transform-origin: center center;
+ }
+
+ [data-composition-id="grid-bg"] .scan-line {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 2px;
+ background-color: #33FF66;
+ opacity: 0.2;
+ box-shadow: 0 0 10px 1px rgba(51, 255, 102, 0.3);
+ transform: translateY(-10px);
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const totalDuration = 19.04;
+ const scanLineSelector = '[data-composition-id="grid-bg"] .scan-line';
+ const gridSelector = '[data-composition-id="grid-bg"] .grid-overlay';
+ const halfDuration = totalDuration / 2;
+
+ gsap.set(scanLineSelector, { y: -20 });
+ gsap.set(gridSelector, { scale: 1, opacity: 0.9 });
+
+ // 1. Single continuous scan keeps the texture moving without stacked fromTo loops.
+ tl.to(scanLineSelector, {
+ y: 1100,
+ duration: totalDuration,
+ ease: "none"
+ }, 0);
+
+ // 2. Gentle scale breathe across the full composition window.
+ tl.to(gridSelector, {
+ scale: 1.02,
+ duration: halfDuration,
+ ease: "sine.inOut"
+ }, 0);
+ tl.to(gridSelector, {
+ scale: 1,
+ duration: totalDuration - halfDuration,
+ ease: "sine.inOut"
+ }, halfDuration);
+
+ // 3. One-way opacity settle keeps the grid alive without repeat/yoyo artifacts.
+ tl.to(gridSelector, {
+ opacity: 1,
+ duration: 1.2,
+ ease: "none"
+ }, 0);
+
+ window.__timelines["grid-bg"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-5-prod/src/compositions/intro-seq.html b/packages/producer/tests/style-5-prod/src/compositions/intro-seq.html
new file mode 100644
index 0000000000..035878411a
--- /dev/null
+++ b/packages/producer/tests/style-5-prod/src/compositions/intro-seq.html
@@ -0,0 +1,138 @@
+<template id="intro-seq-template">
+ <div data-composition-id="intro-seq" data-width="1920" data-height="1080" data-duration="3">
+ <div class="terminal-container">
+ <div id="line1" class="terminal-line"></div>
+ <div id="line2" class="terminal-line"></div>
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap');
+
+ [data-composition-id="intro-seq"] {
+ background-color: #0A0A0A;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ font-family: 'Space Mono', monospace;
+ width: 100%;
+ height: 100%;
+ color: #33FF66;
+ }
+
+ [data-composition-id="intro-seq"] .terminal-container {
+ display: flex;
+ flex-direction: column;
+ gap: 30px;
+ width: 80%;
+ max-width: 1200px;
+ }
+
+ [data-composition-id="intro-seq"] .terminal-line {
+ font-size: 72px;
+ font-weight: 700;
+ text-transform: uppercase;
+ min-height: 1.2em;
+ white-space: pre;
+ text-shadow: 0 0 10px rgba(51, 255, 102, 0.6), 0 0 20px rgba(51, 255, 102, 0.2);
+ display: flex;
+ align-items: center;
+ }
+
+ [data-composition-id="intro-seq"] .char {
+ opacity: 0;
+ display: inline-block;
+ }
+
+ [data-composition-id="intro-seq"] .cursor {
+ display: inline-block;
+ width: 0.6em;
+ height: 1.1em;
+ background-color: #33FF66;
+ margin-left: 5px;
+ box-shadow: 0 0 10px rgba(51, 255, 102, 0.8);
+ opacity: 0;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ const line1Text = 'SYSTEM BOOTING...';
+ const line2Text = 'EDITOR AGENT v1.0';
+ const charDuration = 0.05;
+ const blinkDuration = 0.1;
+
+ const line1El = document.getElementById('line1');
+ const line2El = document.getElementById('line2');
+
+ function createLine(el, text, startTime) {
+ // Clear and create spans
+ el.innerHTML = '';
+ const chars = text.split('').map(char => {
+ const span = document.createElement('span');
+ span.className = 'char';
+ span.textContent = char === ' ' ? '\u00A0' : char;
+ el.appendChild(span);
+ return span;
+ });
+
+ const cursor = document.createElement('div');
+ cursor.className = 'cursor';
+ el.appendChild(cursor);
+
+ tl.set(cursor, {
+ display: 'inline-block',
+ opacity: 1
+ }, startTime);
+
+ // Animate characters
+ chars.forEach((char, i) => {
+ const time = startTime + (i * charDuration);
+
+ tl.to(char, {
+ opacity: 1,
+ duration: 0.01,
+ ease: "none"
+ }, time);
+ });
+
+ // Give the cursor a short deterministic settle instead of a repeat/yoyo blink.
+ const lineEndTime = startTime + (chars.length * charDuration);
+ tl.to(cursor, {
+ opacity: 0.25,
+ duration: blinkDuration,
+ ease: "none"
+ }, lineEndTime);
+ tl.to(cursor, {
+ opacity: 1,
+ duration: blinkDuration,
+ ease: "none"
+ }, lineEndTime + blinkDuration);
+ tl.set(cursor, {
+ opacity: 0
+ }, lineEndTime + (blinkDuration * 2));
+
+ return lineEndTime + 0.5;
+ }
+
+ // Line 1
+ const line1End = createLine(line1El, line1Text, 0.2);
+
+ // Line 2
+ createLine(line2El, line2Text, line1End);
+
+ // A subtle one-way settle keeps the intro alive without repeat/yoyo seek edge cases.
+ tl.fromTo('[data-composition-id="intro-seq"] .terminal-container', {
+ opacity: 0.92
+ }, {
+ opacity: 1,
+ duration: 0.6,
+ ease: "none"
+ }, 0);
+
+ window.__timelines["intro-seq"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-5-prod/src/compositions/intro.html b/packages/producer/tests/style-5-prod/src/compositions/intro.html
new file mode 100644
index 0000000000..23bcb85b3c
--- /dev/null
+++ b/packages/producer/tests/style-5-prod/src/compositions/intro.html
@@ -0,0 +1,88 @@
+<template id="intro-template">
+ <div data-composition-id="intro" data-width="1920" data-height="1080" data-duration="3">
+ <div class="terminal-container">
+ <div id="terminal-text" class="terminal-text"></div>
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&display=swap');
+
+ [data-composition-id="intro"] {
+ background: transparent;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ font-family: 'JetBrains Mono', monospace;
+ }
+
+ [data-composition-id="intro"] .terminal-container {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ height: 100%;
+ }
+
+ [data-composition-id="intro"] .terminal-text {
+ color: #FFFFFF;
+ font-size: 72px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 6px;
+ white-space: pre;
+ /* Subtle glow: #33FF66 at 0.2 opacity */
+ text-shadow: 0 0 15px rgba(51, 255, 102, 0.2);
+ display: flex;
+ }
+
+ [data-composition-id="intro"] .char {
+ opacity: 0;
+ display: inline-block;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const text = "SYSTEM BOOT: EDITOR AGENT";
+ const container = document.getElementById('terminal-text');
+
+ // Clear and create character spans for precise animation
+ container.innerHTML = '';
+ const chars = text.split('').map(char => {
+ const span = document.createElement('span');
+ span.className = 'char';
+ span.textContent = char === ' ' ? '\u00A0' : char; // Use non-breaking space for layout
+ container.appendChild(span);
+ return span;
+ });
+
+ const charDuration = 0.04; // 40ms per character
+ const tl = gsap.timeline({ paused: true });
+
+ // Character-by-character reveal
+ // Using stagger for a more modern, sophisticated implementation
+ tl.to(chars, {
+ opacity: 1,
+ duration: 0.01, // Instant reveal per character
+ stagger: {
+ each: charDuration,
+ ease: "none" // Linear sequence
+ }
+ }, 0);
+
+ // Add a subtle "flicker" or "pulse" to the glow for sophistication
+ // This adds the "2-3 simultaneous motion sources" requirement
+ tl.to(container, {
+ textShadow: "0 0 25px rgba(51, 255, 102, 0.4)",
+ duration: 1.5,
+ ease: "sine.inOut",
+ yoyo: true,
+ repeat: 1 // Finite repeat to fit 3s duration
+ }, 0);
+
+ // Register the timeline
+ window.__timelines["intro"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-5-prod/src/compositions/main.html b/packages/producer/tests/style-5-prod/src/compositions/main.html
new file mode 100644
index 0000000000..03bf71656c
--- /dev/null
+++ b/packages/producer/tests/style-5-prod/src/compositions/main.html
@@ -0,0 +1,145 @@
+<template id="main-template">
+ <div data-composition-id="main" data-width="1920" data-height="1080" data-duration="16.04">
+ <!-- A-roll Video -->
+ <video id="aroll"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/008477bc_391124feb22641f19fd463e5aeb1aeef.mp4"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="1">
+ </video>
+
+ <!-- Captions Container -->
+ <div id="captions-container"></div>
+
+ <style>
+ [data-composition-id="main"] {
+ background-color: transparent;
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ overflow: hidden;
+ }
+
+ [data-composition-id="main"] #aroll {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ border-radius: 4px;
+ object-fit: cover;
+ width: 1920px;
+ height: 1080px;
+ /* Initial state for wipe reveal */
+ clip-path: inset(0 100% 0 0);
+ }
+
+ [data-composition-id="main"] #captions-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ pointer-events: none;
+ z-index: 10;
+ }
+
+ .caption-line {
+ font-family: 'JetBrains Mono', monospace;
+ font-weight: bold;
+ font-size: 64px;
+ color: #FFFFFF;
+ text-transform: uppercase;
+ text-align: center;
+ opacity: 0;
+ position: absolute;
+ width: 100%;
+ padding: 0 100px;
+ /* Terminal aesthetic start position */
+ transform: translateY(10px);
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.839, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics.', 'start': 3.579, 'end': 4.639}, {'text': 'Sixty-two', 'start': 4.659, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.099, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.479}, {'text': 'look', 'start': 10.52, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.86}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Editor', 'start': 15.079, 'end': 15.42}, {'text': 'Agent', 'start': 15.619, 'end': 16.019}];
+ const TRANSITION_DURATION = 0.25; // 250ms
+
+ const container = document.querySelector('[data-composition-id="main"]');
+ const aroll = container.querySelector('#aroll');
+ const captionsContainer = container.querySelector('#captions-container');
+
+ // --- A-roll Choreography ---
+
+ // 1. At 0.0s (relative to composition start at 3s): A-roll enters with a clean left-to-right wipe reveal.
+ tl.to(aroll, {
+ clipPath: 'inset(0 0% 0 0)',
+ duration: TRANSITION_DURATION,
+ ease: 'none'
+ }, 0.0);
+
+ // 2. At 1.839s (relative to composition start at 3s): A-roll scales down and shifts.
+ // (4.839 - 3 = 1.839)
+ tl.to(aroll, {
+ scale: 0.6,
+ x: -384,
+ duration: TRANSITION_DURATION,
+ ease: 'none'
+ }, 1.839);
+
+ // 3. At 14.239s (relative to composition start at 3s): A-roll scales back up and recenters.
+ // (17.239 - 3 = 14.239)
+ tl.to(aroll, {
+ scale: 1,
+ x: 0,
+ duration: TRANSITION_DURATION,
+ ease: 'none'
+ }, 14.239);
+
+ // --- Captions Logic ---
+
+ function groupTranscript(transcript, maxWords) {
+ const groups = [];
+ for (let i = 0; i < transcript.length; i += maxWords) {
+ groups.push(transcript.slice(i, i + maxWords));
+ }
+ return groups;
+ }
+
+ const captionGroups = groupTranscript(TRANSCRIPT, 5);
+
+ captionGroups.forEach((group, index) => {
+ const startTime = group[0].start;
+ // Stay visible until the next group replaces them.
+ const endTime = (index < captionGroups.length - 1)
+ ? captionGroups[index + 1][0].start
+ : 16.04; // End of composition
+
+ const text = group.map(w => w.text).join(' ');
+ const el = document.createElement('div');
+ el.className = 'caption-line';
+ el.innerText = text;
+ captionsContainer.appendChild(el);
+
+ // Caption transitions: slight vertical shift
+ tl.to(el, {
+ opacity: 1,
+ y: 0,
+ duration: 0.2,
+ ease: 'none'
+ }, startTime);
+
+ // Hide caption when next one starts
+ if (index < captionGroups.length - 1) {
+ tl.set(el, { opacity: 0 }, endTime);
+ }
+ });
+
+ window.__timelines["main"] = tl;
+ })();
+ </script>
+ </div>
+</template>
\ No newline at end of file
diff --git a/packages/producer/tests/style-5-prod/src/compositions/stats.html b/packages/producer/tests/style-5-prod/src/compositions/stats.html
new file mode 100644
index 0000000000..85e4d7b2a4
--- /dev/null
+++ b/packages/producer/tests/style-5-prod/src/compositions/stats.html
@@ -0,0 +1,215 @@
+<template id="stats-template">
+ <div data-composition-id="stats" data-width="1920" data-height="1080" data-duration="16.04">
+ <div class="grid-container">
+ <!-- Stat 1: Horizontal Progress Bar -->
+ <div id="stat-1" class="stat-box">
+ <div class="stat-header">
+ <div class="stat-value" id="val-1">0%</div>
+ <div class="stat-label">NEED MOTION GRAPHICS</div>
+ </div>
+ <div class="progress-bar-container">
+ <div class="progress-bar-fill" id="fill-1"></div>
+ </div>
+ </div>
+
+ <!-- Stat 2: Circular Progress Ring (Sharp Segments) -->
+ <div id="stat-2" class="stat-box">
+ <div class="stat-header">
+ <div class="stat-value" id="val-2">0%</div>
+ <div class="stat-label">STATIC CONTENT LOSES ATTENTION</div>
+ </div>
+ <div class="progress-ring-container">
+ <svg viewBox="0 0 200 200" class="progress-ring">
+ <circle class="ring-bg" cx="100" cy="100" r="80" />
+ <circle class="ring-fill" id="fill-2" cx="100" cy="100" r="80" />
+ </svg>
+ </div>
+ </div>
+
+ <!-- Stat 3: Vertical Bar Chart -->
+ <div id="stat-3" class="stat-box">
+ <div class="stat-header">
+ <div class="stat-value" id="val-3">0%</div>
+ <div class="stat-label">LACK EDITING SKILLS</div>
+ </div>
+ <div class="bar-chart-container">
+ <div class="bar-chart-fill" id="fill-3"></div>
+ </div>
+ </div>
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;800&display=swap');
+
+ [data-composition-id="stats"] {
+ font-family: 'JetBrains Mono', monospace;
+ text-transform: uppercase;
+ color: #FFFFFF;
+ background: transparent;
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ overflow: hidden;
+ }
+
+ [data-composition-id="stats"] .grid-container {
+ position: absolute;
+ right: 100px; /* Positioned on the RIGHT side */
+ top: 0;
+ width: 800px;
+ height: 1080px;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ gap: 120px;
+ }
+
+ [data-composition-id="stats"] .stat-box {
+ opacity: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ transform: translateX(20px); /* Initial slide-in position */
+ }
+
+ [data-composition-id="stats"] .stat-header {
+ display: flex;
+ align-items: baseline;
+ gap: 20px;
+ margin-bottom: 20px;
+ }
+
+ [data-composition-id="stats"] .stat-value {
+ font-size: 80px;
+ font-weight: 800;
+ color: #FFFFFF;
+ line-height: 1;
+ }
+
+ [data-composition-id="stats"] .stat-label {
+ font-size: 32px;
+ font-weight: 400;
+ color: #8A8A8A;
+ letter-spacing: 1px;
+ max-width: 500px;
+ }
+
+ /* Stat 1: Horizontal Bar */
+ [data-composition-id="stats"] .progress-bar-container {
+ width: 600px;
+ height: 12px;
+ background: #0A0A0A;
+ }
+
+ [data-composition-id="stats"] .progress-bar-fill {
+ width: 0%;
+ height: 100%;
+ background: #FFFFFF;
+ }
+
+ /* Stat 2: Circular Ring */
+ [data-composition-id="stats"] .progress-ring-container {
+ width: 240px;
+ height: 240px;
+ }
+
+ [data-composition-id="stats"] .progress-ring {
+ transform: rotate(-90deg);
+ }
+
+ [data-composition-id="stats"] .ring-bg {
+ fill: none;
+ stroke: #0A0A0A;
+ stroke-width: 24;
+ }
+
+ [data-composition-id="stats"] .ring-fill {
+ fill: none;
+ stroke: #FFFFFF;
+ stroke-width: 24;
+ stroke-dasharray: 502.65; /* 2 * PI * 80 */
+ stroke-dashoffset: 502.65;
+ stroke-linecap: butt; /* Sharp segments */
+ }
+
+ /* Stat 3: Vertical Bar */
+ [data-composition-id="stats"] .bar-chart-container {
+ width: 60px;
+ height: 240px;
+ background: #0A0A0A;
+ position: relative;
+ }
+
+ [data-composition-id="stats"] .bar-chart-fill {
+ width: 100%;
+ height: 0%;
+ background: #FFFFFF;
+ position: absolute;
+ bottom: 0;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // Timestamps (relative to composition start at 3s)
+ const T1 = 1.839; // 4.839 - 3
+ const T2 = 4.659; // 7.659 - 3
+ const T3 = 8.88; // 11.88 - 3
+ const END = 16.04; // 19.04 - 3
+ const FADE_DUR = 0.2;
+ const SLIDE_DUR = 0.3;
+ const FILL_DUR = 0.3;
+
+ // Helper for number animation
+ function animateNumber(id, targetVal, startTime) {
+ const obj = { val: 0 };
+ tl.to(obj, {
+ val: targetVal,
+ duration: FILL_DUR,
+ ease: 'none',
+ onUpdate: function() {
+ const valEl = document.getElementById(id);
+ if (valEl) valEl.innerText = Math.floor(obj.val) + '%';
+ }
+ }, startTime);
+ }
+
+ // Stat 1 Animation
+ tl.to('#stat-1', { opacity: 1, duration: FADE_DUR, ease: 'none' }, T1);
+ tl.to('#stat-1', { x: 0, duration: SLIDE_DUR, ease: 'none' }, T1);
+ tl.to('#fill-1', { width: '47%', duration: FILL_DUR, ease: 'none' }, T1);
+ animateNumber('val-1', 47, T1);
+
+ // Hide Stat 1 when Stat 2 starts
+ tl.to('#stat-1', { opacity: 0, x: -20, duration: FADE_DUR, ease: 'none' }, T2);
+
+ // Stat 2 Animation
+ const ringCircumference = 2 * Math.PI * 80;
+ tl.to('#stat-2', { opacity: 1, duration: FADE_DUR, ease: 'none' }, T2);
+ tl.to('#stat-2', { x: 0, duration: SLIDE_DUR, ease: 'none' }, T2);
+ tl.to('#fill-2', {
+ strokeDashoffset: ringCircumference * (1 - 0.62),
+ duration: FILL_DUR,
+ ease: 'none'
+ }, T2);
+ animateNumber('val-2', 62, T2);
+
+ // Hide Stat 2 when Stat 3 starts
+ tl.to('#stat-2', { opacity: 0, x: -20, duration: FADE_DUR, ease: 'none' }, T3);
+
+ // Stat 3 Animation
+ tl.to('#stat-3', { opacity: 1, duration: FADE_DUR, ease: 'none' }, T3);
+ tl.to('#stat-3', { x: 0, duration: SLIDE_DUR, ease: 'none' }, T3);
+ tl.to('#fill-3', { height: '75%', duration: FILL_DUR, ease: 'none' }, T3);
+ animateNumber('val-3', 75, T3);
+
+ // Hide Stat 3 at the end
+ tl.to('#stat-3', { opacity: 0, x: -20, duration: FADE_DUR, ease: 'none' }, END - 0.5);
+
+ window.__timelines["stats"] = tl;
+ })();
+ </script>
+ </div>
+</template>
\ No newline at end of file
diff --git a/packages/producer/tests/style-5-prod/src/design_review.md b/packages/producer/tests/style-5-prod/src/design_review.md
new file mode 100644
index 0000000000..1ebe3f3b6c
--- /dev/null
+++ b/packages/producer/tests/style-5-prod/src/design_review.md
@@ -0,0 +1,58 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a "hacker" template from a 2014 stock asset site. It’s trying so hard to be "digital" and "techy" that it forgets to be actually sophisticated. The neon green on black is the most tired trope in the industry.
+
+---
+
+## CRITICAL Design Failures
+
+### The "Matrix" Color Palette
+**Where:** Global (`#33FF66` on `#0A0A0A`)
+**What's wrong:** Using pure neon green on a near-black background is lazy. It’s high-contrast in the worst way—it causes eye strain and looks like a parody of a terminal.
+**Why it matters:** It lacks professional polish. Real high-end tech brands (like Stripe, Vercel, or even Apple’s developer materials) use more nuanced greens, subtle gradients, and varied opacities to create depth. This is just flat and aggressive.
+**Fix it:** Shift the green to a more sophisticated mint or emerald (e.g., `#00FF9F` or `#4ADE80`). Introduce a secondary accent color like a deep slate blue or a muted purple to break the monotony.
+
+### Typography Hierarchy is Non-Existent
+**Where:** `compositions/captions.html` and `compositions/data-graphics.html`
+**What's wrong:** Everything is screaming. The captions are 64px, the terminal lines are 72px, and the data counters are 48px. All of them are in 'Space Mono' or 'Courier New'.
+**Why it matters:** When everything is bold, uppercase, and huge, nothing is important. The viewer doesn't know where to look. It feels like being shouted at by a calculator.
+**Fix it:** Use a variable font. Mix weights. Make the labels in the data graphics much smaller (12-14px) and lighter. Use a clean sans-serif (like Inter or Geist) for the main captions and keep the mono font for the "data" elements only.
+
+### The "Floating Box" Syndrome
+**Where:** `compositions/data-graphics.html`
+**What's wrong:** The data boxes are just floating on the right with a generic `backdrop-filter: blur(10px)`. They have no relationship to the grid behind them or the video next to them.
+**Why it matters:** It looks like a UI overlay from a cheap mobile game. There’s no sense of "physicality" or integrated design.
+**Fix it:** Align the boxes strictly to the background grid lines. Use "connector" lines or brackets that "anchor" the data to the video frame. Make the borders thinner (0.5px) and use multiple layers of subtle shadows to create real depth.
+
+---
+
+## Design Improvements
+
+### Robotic Motion
+**Where:** `index.html` (A-roll transitions)
+**The problem:** The scale and position shifts of the video (`scale: 0.6`, `x: -400`) are basic linear-feeling movements. The "wipe" reveal is a standard `clip-path` that feels like a default PowerPoint transition.
+**Make it better:** Use more aggressive easing (e.g., `expo.out` or `custom-elastic`). Add a slight "overshoot" to the scaling. When the video moves, maybe it should have a slight tilt or a "glitch" chromatic aberration effect during the transition to match the "system" theme.
+
+### Static Grid Background
+**Where:** `compositions/grid-bg.html`
+**The problem:** A 40px grid is fine, but it’s just... there. The "scan line" is a single 2px bar moving top to bottom. It’s predictable and boring.
+**Make it better:** Add "data noise"—tiny flickering pixels, coordinate numbers that change in the corners of the grid, or subtle "interference" patterns. Make the grid lines vary in opacity so it doesn't look like a math notebook.
+
+---
+
+## What Actually Works
+
+### The Terminal Boot Sequence
+The `intro-seq.html` actually has a decent rhythm. The character-by-character reveal with the slight "blink" on the current character is a nice touch. It’s the only part of the composition that feels like it had some thought put into the *feeling* of the animation rather than just the mechanics.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 3/10 - It’s a cliché "tech" look that fails to stand out.
+**Color & Typography:** 2/10 - Monospaced fonts and neon green are the "Hello World" of design.
+**Motion & Animation Feel:** 4/10 - Functional but lacks the "snap" and "juice" of professional motion design.
+**Overall Aesthetic:** 3/10 - Amateurish. It looks like a developer's first attempt at "cool" UI.
+
+**Bottom Line:** This needs a complete stylistic overhaul. Stop trying to look like a 90s movie version of a "hacker" and start looking like a modern, high-end SaaS product. Kill the neon green, fix the typography, and give the layout some room to breathe.
diff --git a/packages/producer/tests/style-5-prod/src/index.html b/packages/producer/tests/style-5-prod/src/index.html
new file mode 100644
index 0000000000..d1b8d96b5c
--- /dev/null
+++ b/packages/producer/tests/style-5-prod/src/index.html
@@ -0,0 +1,126 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Digital Grid — Wim Crouwel Style</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1920px;
+ height: 1080px;
+ background-color: #0A0A0A;
+ overflow: hidden;
+ font-family: 'Courier New', Courier, monospace;
+ }
+
+ #master-composition {
+ position: relative;
+ width: 1920px;
+ height: 1080px;
+ }
+
+ #aroll-video {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ width: 1920px;
+ height: 1080px;
+ border-radius: 4px;
+ object-fit: cover;
+ clip-path: inset(0 100% 0 0); /* For left-to-right wipe */
+ }
+ </style>
+</head>
+<body>
+ <div id="master-composition" data-composition-id="master" data-width="1920" data-height="1080" data-duration="19.04">
+
+ <!-- Persistent Grid Background -->
+ <div id="grid-bg-comp"
+ data-composition-id="grid-bg"
+ data-composition-src="compositions/grid-bg.html"
+ data-start="0"
+ data-track-index="0">
+ </div>
+
+ <!-- Intro Sequence (0-3s) -->
+ <div id="intro-seq-comp"
+ data-composition-id="intro-seq"
+ data-composition-src="compositions/intro-seq.html"
+ data-start="0"
+ data-track-index="1"
+ data-duration="3">
+ </div>
+
+ <!-- Data Graphics Layer -->
+ <div id="data-graphics-comp"
+ data-composition-id="data-graphics"
+ data-composition-src="compositions/data-graphics.html"
+ data-start="3"
+ data-track-index="2">
+ </div>
+
+ <!-- A-roll Video (Starts after intro) -->
+ <video id="aroll-video"
+ data-start="3"
+ data-duration="16.04"
+ data-track-index="3"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/3053bdbd_3b610ff665ee4d11858cba59dbf47b8c.mp4">
+ </video>
+
+ <!-- Captions Layer -->
+ <div id="captions-comp"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="3"
+ data-track-index="4">
+ </div>
+
+ </div>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const video = document.getElementById('aroll-video');
+
+ // 1. A-roll entrance: Clean left-to-right wipe reveal at 3s
+ tl.to(video, {
+ clipPath: 'inset(0 0% 0 0)',
+ duration: 0.5,
+ ease: "power2.inOut"
+ }, 3);
+
+ // 2. First stat (47%) at 3 + 1.839 = 4.839s
+ // Trigger: A-roll scales down and shifts to left
+ tl.to(video, {
+ scale: 0.6,
+ x: -400,
+ duration: 0.4,
+ ease: "power2.inOut"
+ }, 4.839);
+
+ // 3. Second stat (62%) at 3 + 4.659 = 7.659s
+ // Stays scaled down
+
+ // 4. Next major narrative beat (75% lack skills) at 3 + 13.22 = 16.22s
+ // Trigger: A-roll scales back up to 100% and recenters after "editing skills to get there"
+ tl.to(video, {
+ scale: 1,
+ x: 0,
+ duration: 0.4,
+ ease: "power2.inOut"
+ }, 16.22);
+
+ // 5. Final beat (Editor Agent) at 3 + 14.22 = 17.22s
+ // Scale down again for final reveal? Or stay centered.
+ // Prompt says: "When the next major narrative beat begins: A-roll scales back up to 100% and recenters."
+ // "A-roll remains visible and on screen through the end of the video."
+
+ window.__timelines["master"] = tl;
+ })();
+ </script>
+</body>
+</html>
diff --git a/packages/producer/tests/style-6-prod/meta.json b/packages/producer/tests/style-6-prod/meta.json
new file mode 100644
index 0000000000..c20cddb10d
--- /dev/null
+++ b/packages/producer/tests/style-6-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-6-prod",
+ "description": "Regression fixture imported from normalized style pack style-6-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "landscape"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-6-prod/src/code_review.md b/packages/producer/tests/style-6-prod/src/code_review.md
new file mode 100644
index 0000000000..61804188f2
--- /dev/null
+++ b/packages/producer/tests/style-6-prod/src/code_review.md
@@ -0,0 +1,68 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 4
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None. The compositions follow the core deterministic and structural requirements of the HyperFrame schema.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images used)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - absolute timing used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+## File-by-File Analysis
+
+### index.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Correctly defines the root composition with `data-composition-id="main"`.
+- Includes required `data-width`, `data-height`, and `data-duration`.
+- Orchestrates sub-compositions using `data-composition-src`.
+- Script registers the timeline in `window.__timelines["main"]`.
+- Uses deterministic GSAP animations for the A-roll video.
+
+### compositions/intro.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Uses `<template>` tag as required for external compositions.
+- Root element inside template has `data-composition-id`, `data-width`, `data-height`, and `data-duration`.
+- Script is wrapped in an IIFE and correctly registers the timeline.
+- Animations are fully deterministic.
+
+### compositions/captions.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Correctly uses `<template>` and required data attributes.
+- Manages dynamic text content within a composition, which is the recommended approach for captions.
+- Timeline registration is correct.
+- **Note**: `data-duration` is set to 20s, while the parent `index.html` limits it to 19.04s. This is acceptable as the parent's `data-duration` or the timeline's bounds will effectively clip it.
+
+### compositions/stats.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Follows all schema rules for external compositions.
+- Uses deterministic animations for complex sport-broadcast style graphics.
+- Correctly registers `window.__timelines["stats-graphics"]`.
+
+## Recommendations
+- **Relative Timing**: While absolute timing is used correctly, consider using relative timing (e.g., `data-start="intro-comp"`) for better maintainability if the intro duration changes.
+- **Consistency**: `captions.html` has a `data-duration="20"`, while other files use `19.04`. Aligning these to the exact master duration is a minor best practice but not a schema violation.
diff --git a/packages/producer/tests/style-6-prod/src/compositions/captions.html b/packages/producer/tests/style-6-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..46deff8a47
--- /dev/null
+++ b/packages/producer/tests/style-6-prod/src/compositions/captions.html
@@ -0,0 +1,80 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1920" data-height="1080" data-duration="20">
+ <div class="captions-container">
+ <div id="caption-text" class="caption-text"></div>
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=Oswald:wght@700&display=swap');
+
+ [data-composition-id="captions"] {
+ width: 1920px;
+ height: 1080px;
+ display: flex;
+ justify-content: center;
+ align-items: flex-end;
+ padding-bottom: 150px; /* Position towards bottom 20% */
+ }
+
+ [data-composition-id="captions"] .captions-container {
+ width: 100%;
+ display: flex;
+ justify-content: center;
+ text-align: center;
+ }
+
+ [data-composition-id="captions"] .caption-text {
+ font-family: 'Oswald', sans-serif;
+ font-weight: 700;
+ font-size: 80px;
+ color: white;
+ text-transform: uppercase;
+ text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.9);
+ line-height: 1.2;
+ max-width: 80%;
+ opacity: 0;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const captionEl = document.getElementById('caption-text');
+ const OFFSET = 3;
+
+ const groups = [
+ { text: "WE ASKED WHAT YOU NEEDED.", start: 0.119, end: 1.839 },
+ { text: "FORTY-SEVEN PERCENT OF YOU SAID", start: 1.839, end: 3.24 },
+ { text: "MOTION GRAPHICS.", start: 3.24, end: 4.659 },
+ { text: "SIXTY-TWO PERCENT SAID", start: 4.659, end: 6.099 },
+ { text: "STATIC CONTENT WAS COSTING YOU", start: 6.099, end: 7.679 },
+ { text: "ATTENTION, AND THREE OUT OF", start: 7.679, end: 9.38 },
+ { text: "FOUR SAID YOU KNOW THE", start: 9.38, end: 10.52 },
+ { text: "LOOK YOU WANT BUT DON'T", start: 10.52, end: 11.819 },
+ { text: "HAVE THE EDITING SKILLS TO", start: 11.819, end: 13.019 },
+ { text: "GET THERE.", start: 13.019, end: 14.239 },
+ { text: "SO WE BUILT", start: 14.239, end: 15.079 },
+ { text: "EDITOR AGENT", start: 15.079, end: 17.2 } // End at 17.2 as requested
+ ];
+
+ groups.forEach((group, index) => {
+ const startTime = group.start + OFFSET;
+ const endTime = group.end + OFFSET;
+
+ // Show caption
+ tl.set(captionEl, {
+ innerHTML: group.text,
+ opacity: 1
+ }, startTime);
+
+ // If it's the last group, hide it at the end
+ if (index === groups.length - 1) {
+ tl.set(captionEl, { opacity: 0 }, endTime);
+ }
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-6-prod/src/compositions/intro.html b/packages/producer/tests/style-6-prod/src/compositions/intro.html
new file mode 100644
index 0000000000..15730270ec
--- /dev/null
+++ b/packages/producer/tests/style-6-prod/src/compositions/intro.html
@@ -0,0 +1,131 @@
+<template id="intro-template">
+ <div data-composition-id="intro-anim" data-width="1920" data-height="1080" data-duration="3">
+ <div class="intro-container">
+ <!-- Subtle Background Wipe -->
+ <div class="wipe"></div>
+
+ <!-- Text Container -->
+ <div class="text-wrapper">
+ <div class="line line-1">WE ASKED</div>
+ <div class="line line-2">WHAT YOU</div>
+ <div class="line line-3">NEEDED.</div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="intro-anim"] {
+ background-color: #000000;
+ width: 1920px;
+ height: 1080px;
+ overflow: hidden;
+ font-family: 'Oswald', 'Bebas Neue', sans-serif;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ }
+
+ [data-composition-id="intro-anim"] .intro-container {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ }
+
+ [data-composition-id="intro-anim"] .wipe {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-color: #CDFF00; /* Volt */
+ transform: translateX(-100%);
+ z-index: 1;
+ opacity: 0.15; /* Subtle wipe that doesn't block text */
+ }
+
+ [data-composition-id="intro-anim"] .text-wrapper {
+ position: relative;
+ z-index: 2;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ text-align: center;
+ }
+
+ [data-composition-id="intro-anim"] .line {
+ font-size: 180px;
+ font-weight: 900;
+ line-height: 1.1;
+ color: #FFFFFF;
+ text-transform: uppercase;
+ letter-spacing: -2px;
+ opacity: 0;
+ /* Initial state for entrance */
+ transform: translateY(50px) scale(1.2);
+ }
+
+ [data-composition-id="intro-anim"] .line-2 {
+ color: #CDFF00; /* Volt accent */
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // 1. Subtle Wipe Animation
+ tl.to('.wipe', {
+ x: '100%',
+ duration: 1.5,
+ ease: 'power2.inOut'
+ }, 0);
+
+ // 2. Text Entrance Animations based on transcript
+ // "WE ASKED" (We at 0.119, asked at 0.319)
+ tl.to('.line-1', {
+ opacity: 1,
+ y: 0,
+ scale: 1,
+ duration: 0.8,
+ ease: 'expo.out'
+ }, 0.119);
+
+ // "WHAT YOU" (what at 0.519, you at 0.699)
+ tl.to('.line-2', {
+ opacity: 1,
+ y: 0,
+ scale: 1,
+ duration: 0.8,
+ ease: 'expo.out'
+ }, 0.519);
+
+ // "NEEDED." (needed. at 0.859)
+ tl.to('.line-3', {
+ opacity: 1,
+ y: 0,
+ scale: 1,
+ duration: 0.8,
+ ease: 'expo.out'
+ }, 0.859);
+
+ // 3. Ambient Motion (Slow zoom for depth)
+ tl.to('.text-wrapper', {
+ scale: 1.05,
+ duration: 3,
+ ease: 'none'
+ }, 0);
+
+ // 4. Fade-out transition (2.7s to 3s)
+ tl.to('.intro-container', {
+ opacity: 0,
+ duration: 0.3,
+ ease: 'power2.inOut'
+ }, 2.7);
+
+ window.__timelines["intro-anim"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-6-prod/src/compositions/stats.html b/packages/producer/tests/style-6-prod/src/compositions/stats.html
new file mode 100644
index 0000000000..a589d068e3
--- /dev/null
+++ b/packages/producer/tests/style-6-prod/src/compositions/stats.html
@@ -0,0 +1,316 @@
+<template id="stats-template">
+ <div data-composition-id="stats-graphics" data-width="1920" data-height="1080" data-duration="19.04">
+ <!-- Background Elements (Ambient Motion) -->
+ <div class="bg-container">
+ <div class="slash slash-1"></div>
+ <div class="slash slash-2"></div>
+ <div class="slash slash-3"></div>
+ </div>
+
+ <!-- Video Reveal Container (Entrance at 3s) -->
+ <div class="video-reveal-container">
+ <div class="reveal-bar top"></div>
+ <div class="reveal-bar bottom"></div>
+ </div>
+
+ <!-- Stat 1: 47% -->
+ <div class="stat-container right-side" id="stat-47">
+ <div class="stat-value">47%</div>
+ <div class="stat-label">NEED MOTION GRAPHICS</div>
+ <div class="accent-bar"></div>
+ </div>
+
+ <!-- Stat 2: 62% -->
+ <div class="stat-container right-side" id="stat-62">
+ <div class="stat-value">62%</div>
+ <div class="stat-label">STATIC LOSES ATTENTION</div>
+ <div class="accent-bar"></div>
+ </div>
+
+ <!-- Stat 3: 3 out of 4 -->
+ <div class="stat-container centered-margins" id="stat-3-4">
+ <div class="stat-value-row">
+ <span class="white">3</span>
+ <span class="volt">OUT OF</span>
+ <span class="white">4</span>
+ </div>
+ <div class="stat-label">LACK SKILLS</div>
+ <div class="accent-bar"></div>
+ </div>
+
+ <!-- Title Card: EDITOR AGENT -->
+ <div class="title-card" id="title-card">
+ <div class="title-bg"></div>
+ <div class="title-content">
+ <div class="title-main">EDITOR</div>
+ <div class="title-sub">AGENT</div>
+ </div>
+ <div class="title-accent"></div>
+ </div>
+
+ <style>
+ [data-composition-id="stats-graphics"] {
+ font-family: 'Oswald', 'Bebas Neue', sans-serif;
+ color: white;
+ overflow: hidden;
+ background: transparent;
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ }
+
+ /* Sport Broadcast Style: Bold Condensed Uppercase */
+ [data-composition-id="stats-graphics"] .stat-value,
+ [data-composition-id="stats-graphics"] .stat-value-row {
+ font-size: 280px;
+ font-weight: 900;
+ line-height: 0.8;
+ letter-spacing: -10px;
+ text-transform: uppercase;
+ font-stretch: condensed;
+ color: #CDFF00; /* Volt */
+ margin-bottom: 20px;
+ filter: drop-shadow(10px 10px 0px rgba(0,0,0,0.5));
+ }
+
+ /* 30px spacing between text layers in 3 out of 4 */
+ [data-composition-id="stats-graphics"] .stat-value-row {
+ display: flex;
+ gap: 30px;
+ align-items: baseline;
+ }
+
+ [data-composition-id="stats-graphics"] .stat-label {
+ font-size: 60px;
+ font-weight: 800;
+ color: white;
+ text-transform: uppercase;
+ letter-spacing: 2px;
+ background: black;
+ padding: 10px 30px;
+ display: inline-block;
+ transform: skewX(-10deg);
+ }
+
+ [data-composition-id="stats-graphics"] .stat-container {
+ position: absolute;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ opacity: 0;
+ pointer-events: none;
+ }
+
+ /* Positioning */
+ [data-composition-id="stats-graphics"] .right-side {
+ right: 100px;
+ top: 50%;
+ transform: translateY(-50%);
+ align-items: flex-end;
+ text-align: right;
+ }
+
+ [data-composition-id="stats-graphics"] .centered-margins {
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ align-items: center;
+ text-align: center;
+ width: 100%;
+ }
+
+ [data-composition-id="stats-graphics"] .stat-value-row .white { color: white; }
+ [data-composition-id="stats-graphics"] .stat-value-row .volt { color: #CDFF00; }
+
+ /* Diagonal Slashes */
+ [data-composition-id="stats-graphics"] .bg-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ z-index: -1;
+ }
+
+ [data-composition-id="stats-graphics"] .slash {
+ position: absolute;
+ background: rgba(205, 255, 0, 0.05);
+ width: 150px;
+ height: 200%;
+ transform: rotate(25deg);
+ top: -50%;
+ filter: blur(40px);
+ }
+
+ [data-composition-id="stats-graphics"] .slash-1 { left: 20%; }
+ [data-composition-id="stats-graphics"] .slash-2 { left: 50%; }
+ [data-composition-id="stats-graphics"] .slash-3 { left: 80%; }
+
+ [data-composition-id="stats-graphics"] .accent-bar {
+ width: 100%;
+ height: 15px;
+ background: #CDFF00;
+ margin-top: 10px;
+ transform: skewX(-10deg);
+ }
+
+ /* Video Reveal Bars */
+ [data-composition-id="stats-graphics"] .video-reveal-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ z-index: 2;
+ }
+
+ [data-composition-id="stats-graphics"] .reveal-bar {
+ position: absolute;
+ left: 0;
+ width: 100%;
+ height: 50%;
+ background: black;
+ box-sizing: border-box;
+ }
+
+ [data-composition-id="stats-graphics"] .reveal-bar.top {
+ top: 0;
+ border-bottom: 4px solid #CDFF00;
+ box-shadow: 0 10px 30px rgba(205, 255, 0, 0.2);
+ }
+ [data-composition-id="stats-graphics"] .reveal-bar.bottom {
+ bottom: 0;
+ border-top: 4px solid #CDFF00;
+ box-shadow: 0 -10px 30px rgba(205, 255, 0, 0.2);
+ }
+
+ /* Title Card Styles */
+ [data-composition-id="stats-graphics"] .title-card {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ width: 1200px;
+ height: 600px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ opacity: 0;
+ pointer-events: none;
+ z-index: 10;
+ }
+
+ [data-composition-id="stats-graphics"] .title-bg {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ background: black;
+ transform: skewX(-15deg);
+ border: 10px solid #CDFF00;
+ box-shadow: 20px 20px 0px rgba(0,0,0,0.5);
+ }
+
+ [data-composition-id="stats-graphics"] .title-content {
+ position: relative;
+ text-align: center;
+ z-index: 1;
+ }
+
+ [data-composition-id="stats-graphics"] .title-main {
+ font-size: 220px;
+ font-weight: 900;
+ color: white;
+ line-height: 0.8;
+ letter-spacing: -5px;
+ font-stretch: condensed;
+ }
+
+ [data-composition-id="stats-graphics"] .title-sub {
+ font-size: 180px;
+ font-weight: 900;
+ color: #CDFF00;
+ line-height: 0.8;
+ letter-spacing: 10px;
+ font-stretch: condensed;
+ }
+
+ [data-composition-id="stats-graphics"] .title-accent {
+ position: absolute;
+ bottom: -40px;
+ width: 80%;
+ height: 20px;
+ background: #CDFF00;
+ transform: skewX(-15deg);
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // Ambient Motion: Slashes drifting
+ tl.to('[data-composition-id="stats-graphics"] .slash', {
+ x: 100,
+ duration: 19,
+ ease: 'none'
+ }, 0);
+
+ // 1. Video Entrance Animation (3s)
+ // Reveal bars split open to show the video area
+ tl.to('.reveal-bar.top', { yPercent: -100, duration: 0.8, ease: 'expo.inOut' }, 3);
+ tl.to('.reveal-bar.bottom', { yPercent: 100, duration: 0.8, ease: 'expo.inOut' }, 3);
+
+ // 2. Stat 1: 47% (4.839s)
+ tl.fromTo('#stat-47',
+ { opacity: 0, scale: 3, x: 500, rotation: 10 },
+ { opacity: 1, scale: 1, x: 0, rotation: 0, duration: 0.4, ease: 'power2.out' },
+ 4.839
+ );
+ // Exit before next stat
+ tl.to('#stat-47', { opacity: 0, x: -100, duration: 0.4, ease: 'power2.in' }, 7.2);
+
+ // 3. Stat 2: 62% (7.659s)
+ tl.fromTo('#stat-62',
+ { opacity: 0, scale: 3, x: 500, rotation: -10 },
+ { opacity: 1, scale: 1, x: 0, rotation: 0, duration: 0.4, ease: 'power2.out' },
+ 7.659
+ );
+ // Exit before next stat
+ tl.to('#stat-62', { opacity: 0, x: -100, duration: 0.4, ease: 'power2.in' }, 11.4);
+
+ // 4. Stat 3: 3 out of 4 (11.88s)
+ tl.fromTo('#stat-3-4',
+ { opacity: 0, scale: 0.5, y: 200 },
+ { opacity: 1, scale: 1, y: 0, duration: 0.8, ease: 'elastic.out(1, 0.75)' },
+ 11.88
+ );
+
+ // 5. Slide out '3 out of 4' and show Title Card (14.619s)
+ tl.to('#stat-3-4', {
+ x: -2000,
+ opacity: 0,
+ duration: 0.4,
+ ease: 'power3.in'
+ }, 14.619);
+
+ // Show Title Card (14.619s)
+ tl.fromTo('#title-card',
+ { opacity: 0, scale: 0.8, x: 2000 },
+ { opacity: 1, scale: 1, x: 0, duration: 0.8, ease: 'back.out(1.7)' },
+ 14.619
+ );
+
+ // Slide out Title Card (18.5s)
+ tl.to('#title-card', {
+ x: -2000,
+ duration: 0.5,
+ ease: 'power3.in'
+ }, 18.5);
+
+ window.__timelines["stats-graphics"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-6-prod/src/design_review.md b/packages/producer/tests/style-6-prod/src/design_review.md
new file mode 100644
index 0000000000..5730d80e96
--- /dev/null
+++ b/packages/producer/tests/style-6-prod/src/design_review.md
@@ -0,0 +1,58 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a high-energy sports broadcast package that's trying way too hard to be "extreme" but ends up feeling like a template from a 2012 "Epic Sports Opener" pack. The "Volt" green is doing all the heavy lifting while the layout and typography are just shouting into the void.
+
+---
+
+## CRITICAL Design Failures
+
+### The "Volt" Overdose & Contrast Suicide
+**Where:** `compositions/intro.html`, `compositions/stats.html`
+**What's wrong:** You've picked `#CDFF00` (Volt) as your primary accent, which is fine for a "sporty" look, but you're using it on white backgrounds or with white text in ways that make my eyes bleed. In `intro.html`, you have a 15% opacity Volt wipe behind white text. In `stats.html`, you have "3 OUT OF 4" where "OUT OF" is Volt and "3" and "4" are white.
+**Why it matters:** The contrast ratio between white and that specific neon green is abysmal. It’s vibrating. It’s unreadable. It looks like a mistake, not a design choice.
+**Fix it:** Use the Volt green *only* against black or very dark backgrounds. Never put white text directly next to or on top of it without a massive dark stroke or shadow to separate them.
+
+### The "Floating Head" Caption Problem
+**Where:** `compositions/captions.html`
+**What's wrong:** You have massive 80px Oswald Bold caps just sitting at the bottom 20% of the screen with a generic `2px 2px 4px` drop shadow. It looks like a DVD player's default subtitle setting from 2005.
+**Why it matters:** It completely clashes with the "premium" sports aesthetic you're trying to build in the stats layer. It feels like an afterthought.
+**Fix it:** Give the captions some container love. Use a skewed black background box (matching the `.stat-label` style) or at least use a more modern text-shadow (multiple layers of blur, not just a 2px offset).
+
+### Layout Suffocation
+**Where:** `compositions/stats.html` - `.right-side`
+**What's wrong:** You've positioned your stats with `right: 100px`. On a 1920px wide screen, with 280px font size and `-10px` letter spacing, your text is practically hugging the edge of the frame.
+**Why it matters:** It feels cramped and amateur. Professional broadcast design respects "Action Safe" zones and uses negative space to create impact.
+**Fix it:** Increase the margin to at least 150px-200px. Let the composition breathe. If the text is too big, scale it down. Impact comes from contrast and placement, not just raw font size.
+
+---
+
+## Design Improvements
+
+### Robotic Motion Curves
+**Where:** `index.html`, `compositions/stats.html`
+**The problem:** You're using `back.out(1.7)` for almost every major transition. It’s the "I just discovered GSAP" of easing functions. It makes the video and the title card feel like they're bouncing on a trampoline.
+**Make it better:** Use more sophisticated easing. `expo.out` for fast, aggressive entrances; `power4.out` for smooth settles. Reserve the "back" ease for small UI elements, not the entire 1920x1080 video frame.
+
+### Static Background Slashes
+**Where:** `compositions/stats.html` - `.slash`
+**The problem:** You have these diagonal slashes at 5% opacity with a 40px blur. They aren't "ambient motion"; they're just "smudges on the screen."
+**Make it better:** Give them some actual personality. Vary their widths, use different opacities, and maybe add a subtle "glitch" or "shimmer" effect. Right now, they look like CSS gradients that didn't load properly.
+
+---
+
+## What Actually Works
+
+### The "Reveal Bar" Concept
+The use of `reveal-bar top` and `reveal-bar bottom` to split the screen and introduce the video at 3s is actually a solid broadcast technique. It creates a clear transition from the "Intro" phase to the "Content" phase. The 4px Volt border on the bars adds a nice "laser-cut" feel.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 6/10 - It’s loud and aggressive, which fits the brief, but it lacks finesse.
+**Color & Typography:** 4/10 - The Oswald/Bebas combo is a cliché, and the contrast issues are amateur hour.
+**Motion & Animation Feel:** 5/10 - Too much "bouncing," not enough "snapping."
+**Overall Aesthetic:** 5/10 - It looks like a mid-tier YouTube sports channel intro.
+
+**Bottom Line:** It’s functional, but it’s not "premium." If you want this to look like Nike or ESPN, you need to stop relying on font size and start caring about white space and contrast. Fix the Volt-on-White crime immediately.
\ No newline at end of file
diff --git a/packages/producer/tests/style-6-prod/src/index.html b/packages/producer/tests/style-6-prod/src/index.html
new file mode 100644
index 0000000000..ddbf5c38c2
--- /dev/null
+++ b/packages/producer/tests/style-6-prod/src/index.html
@@ -0,0 +1,119 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Athletic Bold — Sport Broadcast</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1920px;
+ height: 1080px;
+ background: #000000;
+ overflow: hidden;
+ }
+ #main-comp {
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ }
+ #aroll-video {
+ width: 100%;
+ height: 100%;
+ border-radius: 8px;
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ object-fit: cover;
+ z-index: 1;
+ }
+ .composition-layer {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ }
+ #intro-comp { z-index: 2; }
+ #stats-comp { z-index: 3; }
+ #captions-comp { z-index: 4; }
+ </style>
+</head>
+<body>
+ <div id="main-comp" data-composition-id="main" data-width="1920" data-height="1080" data-duration="19.04">
+
+ <!-- A-roll Video (Starts at 3s, Duration 16.04s) -->
+ <video id="aroll-video"
+ data-start="3"
+ data-track-index="1"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/852b4a6c_22c6186c3b844db1955bc9aaee70d348.mp4"
+ data-duration="16.04"></video>
+
+ <!-- Intro Sequence (0-3s) -->
+ <div id="intro-comp"
+ class="composition-layer"
+ data-composition-id="intro-anim"
+ data-composition-src="compositions/intro.html"
+ data-start="0"
+ data-duration="3"
+ data-track-index="2">
+ </div>
+
+ <!-- Stats Graphics (3s onwards) -->
+ <div id="stats-comp"
+ class="composition-layer"
+ data-composition-id="stats-graphics"
+ data-composition-src="compositions/stats.html"
+ data-start="0"
+ data-duration="19.04"
+ data-track-index="3">
+ </div>
+
+ <!-- Captions (0s onwards, matching transcript) -->
+ <div id="captions-comp"
+ class="composition-layer"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="0"
+ data-duration="19.04"
+ data-track-index="4">
+ </div>
+
+ <!-- Woosh Sound Effect (3s) -->
+ <audio id="woosh-sfx"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/70b67ff2_d2b6d384b6124d01ba8d826bb8c1b43f.mp3"
+ data-start="3"
+ data-track-index="5"
+ data-duration="2"></audio>
+
+ <script>
+ const tl = gsap.timeline({ paused: true });
+
+ // "47%" trigger (transcript 1.839s -> absolute 4.839s)
+ // Scales down and shifts left.
+ tl.fromTo("#aroll-video", { opacity: 0 }, { opacity: 1, duration: 0.5 }, 3);
+
+ tl.to("#aroll-video", {
+ scale: 0.7,
+ x: -400, // Move left (1920 * -0.2 approx)
+ duration: 0.2,
+ ease: "back.out(1.7)"
+ }, 4.839);
+
+ // "3 out of 4" trigger (transcript 8.88s -> absolute 11.88s)
+ // Scales back to 100% and recenters.
+ tl.to("#aroll-video", {
+ scale: 1.0,
+ x: 0,
+ duration: 0.2,
+ ease: "back.out(1.7)"
+ }, 11.88);
+
+ window.__timelines["main"] = tl;
+ </script>
+ </div>
+</body>
+</html>
\ No newline at end of file
diff --git a/packages/producer/tests/style-7-prod/meta.json b/packages/producer/tests/style-7-prod/meta.json
new file mode 100644
index 0000000000..3a5bf1d357
--- /dev/null
+++ b/packages/producer/tests/style-7-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-7-prod",
+ "description": "Regression fixture imported from normalized style pack style-7-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "landscape"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-7-prod/src/code_review.md b/packages/producer/tests/style-7-prod/src/code_review.md
new file mode 100644
index 0000000000..3d3bdd5604
--- /dev/null
+++ b/packages/producer/tests/style-7-prod/src/code_review.md
@@ -0,0 +1,68 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 4
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None found. All compositions follow the deterministic and finite timeline requirements.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images used)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - no relative timing used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+## File-by-File Analysis
+
+### index.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Correctly defines the root composition with `data-composition-id="root"`.
+- Properly loads sub-compositions using `data-composition-src`.
+- Registers the root timeline in `window.__timelines`.
+- Audio clip has all required attributes (`id`, `data-start`, `data-duration`, `data-track`).
+
+### compositions/intro.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Uses `<template>` tag correctly.
+- Composition root has `data-width`, `data-height`, and `data-duration`.
+- Script is deterministic (uses string splitting and fixed durations).
+- Timeline is correctly registered.
+
+### compositions/captions.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Uses `<template>` tag correctly.
+- Composition root has `data-width`, `data-height`, and `data-duration`.
+- Script is deterministic, iterating over a fixed array of caption data.
+- Timeline is correctly registered.
+
+### compositions/main.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Uses `<template>` tag correctly.
+- Composition root has `data-width`, `data-height`, and `data-duration`.
+- Video clip has all required attributes (`id`, `data-start`, `data-duration`, `data-track`).
+- Script-animated content (`.stats-container`) is correctly wrapped inside the `main` composition.
+- Timeline is correctly registered.
+
+## Actionable Fixes
+No fixes required. The project structure and implementation are in full accordance with the HyperFrame schema.
diff --git a/packages/producer/tests/style-7-prod/src/compositions/captions.html b/packages/producer/tests/style-7-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..b2874dfe11
--- /dev/null
+++ b/packages/producer/tests/style-7-prod/src/compositions/captions.html
@@ -0,0 +1,112 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1920" data-height="1080" data-duration="16.7">
+ <div class="bg-gradient"></div>
+ <div class="caption-wrapper">
+ <div id="caption-container">
+ <div id="caption-text"></div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="captions"] {
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ overflow: hidden;
+ }
+
+ [data-composition-id="captions"] .bg-gradient {
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ width: 100%;
+ height: 25%; /* Reduced height to focus on bottom */
+ background: linear-gradient(to top, rgba(0, 0, 0, 0.9) 0%, rgba(0, 0, 0, 0.6) 50%, rgba(0, 0, 0, 0) 100%);
+ pointer-events: none;
+ opacity: 0;
+ }
+
+ [data-composition-id="captions"] .caption-wrapper {
+ position: absolute;
+ bottom: 54px; /* 5% of 1080px */
+ left: 0;
+ width: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ z-index: 10;
+ }
+
+ [data-composition-id="captions"] #caption-container {
+ min-width: 400px;
+ max-width: 1600px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ padding: 10px 60px;
+ opacity: 0;
+ }
+
+ [data-composition-id="captions"] #caption-text {
+ color: #FFFFFF;
+ font-family: 'Inter', 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ font-size: 42px;
+ font-weight: 300; /* Light */
+ text-transform: uppercase;
+ letter-spacing: 0.4em; /* Wide letter-spacing, but readable */
+ text-align: center;
+ line-height: 1.4;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const container = document.querySelector('[data-composition-id="captions"] #caption-container');
+ const textElement = document.querySelector('[data-composition-id="captions"] #caption-text');
+ const bgGradient = document.querySelector('[data-composition-id="captions"] .bg-gradient');
+
+ const OFFSET = 0; // Adjusted to 0 as per standard unless specified otherwise by Lyra's context, but keeping logic flexible.
+
+ const captions = [
+ { start: 0.1, end: 1.8, text: "WE ASKED WHAT YOU NEEDED" },
+ { start: 1.8, end: 4.6, text: "47 PERCENT SAID MOTION GRAPHICS" },
+ { start: 4.6, end: 6.9, text: "62 PERCENT SAID STATIC CONTENT" },
+ { start: 6.9, end: 8.6, text: "WAS COSTING YOU ATTENTION" },
+ { start: 8.6, end: 10.0, text: "THREE OUT OF FOUR SAID" },
+ { start: 10.0, end: 11.3, text: "KNOW THE LOOK YOU WANT" },
+ { start: 11.3, end: 12.8, text: "BUT NO EDITING SKILLS" },
+ { start: 12.8, end: 14.2, text: "TO GET THERE" },
+ { start: 14.2, end: 16.2, text: "SO WE BUILT EDITOR AGENT" }
+ ];
+
+ if (captions.length > 0) {
+ const firstStart = captions[0].start + OFFSET;
+ const lastEnd = captions[captions.length - 1].end + OFFSET;
+
+ // Fade in gradient and container
+ tl.to([bgGradient, container], { opacity: 1, duration: 0.5, ease: "power2.out" }, firstStart);
+
+ captions.forEach((cap, index) => {
+ const startTime = cap.start + OFFSET;
+
+ // Update text
+ tl.set(textElement, { innerText: cap.text }, startTime);
+
+ // Subtle scale/fade effect for each new line to make it feel modern
+ tl.fromTo(textElement,
+ { opacity: 0.7, scale: 0.98 },
+ { opacity: 1, scale: 1, duration: 0.3, ease: "power1.out" },
+ startTime
+ );
+ });
+
+ // Fade out at the very end
+ tl.to([bgGradient, container], { opacity: 0, duration: 0.5, ease: "power2.in" }, lastEnd);
+ }
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-7-prod/src/compositions/intro.html b/packages/producer/tests/style-7-prod/src/compositions/intro.html
new file mode 100644
index 0000000000..623db937d8
--- /dev/null
+++ b/packages/producer/tests/style-7-prod/src/compositions/intro.html
@@ -0,0 +1,107 @@
+<template id="intro-template">
+ <div data-composition-id="intro" data-width="1920" data-height="1080" data-duration="3">
+ <div class="container">
+ <div class="title">EDITOR AGENT</div>
+ <div class="rule"></div>
+ </div>
+
+ <style>
+ [data-composition-id="intro"] {
+ background-color: #000000;
+ width: 1920px;
+ height: 1080px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ font-family: "Helvetica", "Arial", sans-serif;
+ color: #FFFFFF;
+ overflow: hidden;
+ }
+
+ [data-composition-id="intro"] .container {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ /* Vignelli style: precise, clean spacing */
+ gap: 40px;
+ }
+
+ [data-composition-id="intro"] .title {
+ font-size: 120px;
+ font-weight: 700; /* Vignelli often used bold Helvetica */
+ text-transform: uppercase;
+ letter-spacing: 1em;
+ /* Offset the last letter's spacing to keep it centered */
+ margin-right: -1em;
+ display: flex;
+ justify-content: center;
+ }
+
+ [data-composition-id="intro"] .char {
+ display: inline-block;
+ opacity: 0;
+ }
+
+ [data-composition-id="intro"] .rule {
+ width: 800px;
+ height: 4px;
+ background-color: #FFFFFF;
+ transform: scaleX(0);
+ transform-origin: center;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const compId = "intro";
+ const root = document.querySelector(`[data-composition-id="${compId}"]`);
+ const titleEl = root.querySelector('.title');
+ const ruleEl = root.querySelector('.rule');
+
+ // Split text into spans for staggered animation
+ const text = titleEl.textContent;
+ titleEl.innerHTML = '';
+ [...text].forEach(char => {
+ const span = document.createElement('span');
+ span.textContent = char === ' ' ? '\u00A0' : char;
+ span.className = 'char';
+ titleEl.appendChild(span);
+ });
+
+ const tl = gsap.timeline({ paused: true });
+
+ // 1. Horizontal rule expands from center
+ tl.to(ruleEl, {
+ scaleX: 1,
+ duration: 1.5,
+ ease: "power4.inOut"
+ }, 0);
+
+ // 2. Tracking animation (letter-spacing: 1em to 0.5em)
+ tl.to(titleEl, {
+ letterSpacing: "0.5em",
+ marginRight: "-0.5em",
+ duration: 3,
+ ease: "power2.out"
+ }, 0);
+
+ // 3. Staggered letter fade-in
+ tl.to(root.querySelectorAll('.char'), {
+ opacity: 1,
+ duration: 0.8,
+ stagger: 0.1,
+ ease: "power1.out"
+ }, 0.2);
+
+ // Ambient motion: subtle scale pulse for the whole container
+ tl.to(root.querySelector('.container'), {
+ scale: 1.05,
+ duration: 3,
+ ease: "none"
+ }, 0);
+
+ window.__timelines[compId] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-7-prod/src/compositions/main.html b/packages/producer/tests/style-7-prod/src/compositions/main.html
new file mode 100644
index 0000000000..eb9c022bfa
--- /dev/null
+++ b/packages/producer/tests/style-7-prod/src/compositions/main.html
@@ -0,0 +1,190 @@
+<template id="main-template">
+ <div data-composition-id="main" data-width="1920" data-height="1080" data-duration="16.7">
+ <!-- A-roll Video -->
+ <video id="aroll"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/70648f53_abe84fb9991841ae8ba82ee21ba6d37e.mp4"
+ data-start="0"
+ data-duration="16.7"
+ data-track-index="1"
+ muted
+ crossorigin="anonymous">
+ </video>
+
+ <!-- Statistics Overlay -->
+ <div class="stats-container">
+ <div class="stat-item" id="stat-1">
+ <div class="stat-bg"></div>
+ <div class="stat-content">
+ <div class="stat-value">47%</div>
+ <div class="stat-subtext">MOTION GRAPHICS</div>
+ </div>
+ </div>
+ <div class="stat-item" id="stat-2">
+ <div class="stat-bg"></div>
+ <div class="stat-content">
+ <div class="stat-value">62%</div>
+ <div class="stat-subtext">STATIC CONTENT</div>
+ </div>
+ </div>
+ <div class="stat-item" id="stat-3">
+ <div class="stat-bg"></div>
+ <div class="stat-content">
+ <div class="stat-value">75%</div>
+ <div class="stat-subtext">LACK SKILLS</div>
+ </div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="main"] {
+ background-color: #000000;
+ font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ overflow: hidden;
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ }
+
+ [data-composition-id="main"] #aroll {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ border-radius: 6px;
+ opacity: 0;
+ z-index: 1;
+ }
+
+ [data-composition-id="main"] .stats-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ z-index: 10;
+ pointer-events: none;
+ }
+
+ [data-composition-id="main"] .stat-item {
+ position: absolute;
+ opacity: 0;
+ text-align: center;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ bottom: 15%;
+ left: 50%;
+ transform: translateX(-50%);
+ }
+
+ [data-composition-id="main"] .stat-bg {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ width: 110%;
+ height: 110%;
+ background-color: rgba(0, 0, 0, 0.4);
+ border-radius: 20px;
+ z-index: -1;
+ filter: blur(20px);
+ }
+
+ [data-composition-id="main"] .stat-content {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding: 40px 80px;
+ }
+
+ [data-composition-id="main"] .stat-value {
+ font-size: 180px; /* Large, centered, and precise */
+ font-weight: 900;
+ color: #6B0F1A; /* Deep Burgundy for emphasis */
+ line-height: 0.9;
+ letter-spacing: -5px;
+ text-shadow: 0 10px 30px rgba(0,0,0,0.5);
+ }
+
+ [data-composition-id="main"] .stat-subtext {
+ font-size: 60px;
+ font-weight: 700;
+ color: #FFFFFF;
+ letter-spacing: 4px;
+ margin-top: 10px;
+ text-transform: uppercase;
+ text-shadow: 0 5px 15px rgba(0,0,0,0.5);
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const aroll = '#aroll';
+
+ // 1. At 3.0s: A-roll fades in smoothly (500ms) at 100% scale, centered.
+ tl.to(aroll, {
+ opacity: 1,
+ duration: 0.5,
+ ease: 'power2.inOut'
+ }, 3.0);
+
+ // 2. Stat 1 (1.8s - 4.6s)
+ tl.to('#stat-1', {
+ opacity: 1,
+ y: -20,
+ duration: 0.8,
+ ease: 'expo.out'
+ }, 1.8);
+
+ // 3. At 4.6s (Stat 2): Cross-dissolve Stat 1 to Stat 2
+ tl.to('#stat-1', {
+ opacity: 0,
+ y: -40,
+ duration: 0.5,
+ ease: 'power2.inOut'
+ }, 4.6);
+
+ tl.to('#stat-2', {
+ opacity: 1,
+ y: -20,
+ duration: 0.8,
+ ease: 'expo.out'
+ }, 4.6);
+
+ // 4. At 8.6s (Stat 3): Cross-dissolve Stat 2 to Stat 3
+ tl.to('#stat-2', {
+ opacity: 0,
+ y: -40,
+ duration: 0.5,
+ ease: 'power2.inOut'
+ }, 8.6);
+
+ tl.to('#stat-3', {
+ opacity: 1,
+ y: -20,
+ duration: 0.8,
+ ease: 'expo.out'
+ }, 8.6);
+
+ // 5. At 14.2s: Stat 3 fades out.
+ tl.to('#stat-3', {
+ opacity: 0,
+ y: -40,
+ duration: 0.5,
+ ease: 'power2.inOut'
+ }, 14.2);
+
+ window.__timelines["main"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-7-prod/src/design_review.md b/packages/producer/tests/style-7-prod/src/design_review.md
new file mode 100644
index 0000000000..519ef21965
--- /dev/null
+++ b/packages/producer/tests/style-7-prod/src/design_review.md
@@ -0,0 +1,61 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a "minimalist" template designed by someone who thinks Helvetica and a black background are a substitute for actual creative direction. It's safe, it's sterile, and it's dangerously close to being completely forgettable.
+
+---
+
+## CRITICAL Design Failures
+
+Issues that make this look unprofessional or straight-up ugly. These MUST be fixed.
+
+### The "Giant Stat" Obstruction
+**Where:** `compositions/main.html` - `.stat-value` (240px)
+**What's wrong:** You've slapped a 240px font size statistic right in the middle of the screen. It's not "bold," it's obnoxious. It's going to cover the subject's face or the primary action of the A-roll video.
+**Why it matters:** If I can't see the video because a giant "47%" is screaming in my face, the video is useless. You're sacrificing the primary content for a secondary metric.
+**Fix it:** Reduce the `stat-value` to 120px-140px and move the `.stat-item` to a corner (e.g., bottom-left or top-right) with proper padding. Let the video breathe.
+
+### Caption Letter-Spacing Overkill
+**Where:** `compositions/captions.html` - `#caption-text` (`letter-spacing: 0.6em`)
+**What's wrong:** 0.6em letter spacing on a 42px font is absurd. It makes the words fall apart. The human eye shouldn't have to work this hard to reassemble "MOTION GRAPHICS" into a coherent thought.
+**Why it matters:** Captions are for readability. This is "aesthetic" at the expense of function. It looks like a broken typewriter.
+**Fix it:** Bring that `letter-spacing` down to 0.1em or 0.2em max. If you want "wide," do it subtly, not like you're trying to fill the entire 1920px width with one word.
+
+### The "Vignelli" Identity Crisis
+**Where:** `compositions/intro.html`
+**What's wrong:** You claim "Vignelli style" in the comments but then use a 1em letter-spacing on the title. Vignelli was about tight, intentional kerning and powerful grids, not "let's see how far apart I can push these letters before they fall off the screen."
+**Why it matters:** It feels like a parody of modernism rather than an execution of it.
+**Fix it:** Tighten the `letter-spacing` to 0.05em or even slightly negative for that true high-end Swiss feel. Use a heavier weight and let the white space around the text do the work, not the gaps between the letters.
+
+---
+
+## Design Improvements
+
+Things that aren't broken but are boring, lazy, or could be significantly better.
+
+### Robotic Stat Transitions
+**Where:** `compositions/main.html` - GSAP Timeline
+**The problem:** The stats just fade and move 'y: -20'. It's the most basic "PowerPoint" transition imaginable.
+**Make it better:** Use a "counter" animation for the numbers. Have the percentage roll up from 0 to 47. It adds dynamic energy and makes the data feel "live" rather than static.
+
+### Generic Background Gradient
+**Where:** `compositions/captions.html` - `.bg-gradient`
+**The problem:** A simple black-to-transparent linear gradient is the "I don't know what else to do" of video design.
+**Make it better:** Add a subtle blur or a frosted glass (backdrop-filter) effect to the caption container instead. It feels more premium and less like a 2010 YouTube tutorial.
+
+---
+
+## What Actually Works
+
+The **Intro Rule Animation** (`.rule` scaleX) is actually decent. It provides a clean, architectural anchor for the text. It’s the only thing in this entire project that feels like it had a moment of genuine thought behind its motion.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 4/10 - It’s "clean" only because there’s nothing there.
+**Color & Typography:** 3/10 - Black and white is a cop-out when the typography is this poorly spaced.
+**Motion & Animation Feel:** 5/10 - Standard GSAP eases. Nothing offensive, nothing inspiring.
+**Overall Aesthetic:** 4/10 - Corporate minimalism that forgot the "design" part.
+
+**Bottom Line:** This looks like a wireframe that someone forgot to skin. It’s functional, but it has zero soul. If you want this to look professional, stop spacing your letters like they’re social distancing and stop blocking your video with giant numbers.
diff --git a/packages/producer/tests/style-7-prod/src/index.html b/packages/producer/tests/style-7-prod/src/index.html
new file mode 100644
index 0000000000..9b7e53d4e1
--- /dev/null
+++ b/packages/producer/tests/style-7-prod/src/index.html
@@ -0,0 +1,82 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Editor Agent - Velvet Standard</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1920px;
+ height: 1080px;
+ overflow: hidden;
+ background-color: #000;
+ }
+ #viewport {
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ }
+ </style>
+</head>
+<body>
+ <div id="viewport"
+ data-composition-id="root"
+ data-width="1920"
+ data-height="1080"
+ data-duration="16.7">
+
+ <!-- Intro Sequence (0-3s) -->
+ <div id="intro-layer"
+ data-composition-src="compositions/intro.html"
+ data-composition-id="intro"
+ data-start="0"
+ data-duration="3"
+ data-width="1920"
+ data-height="1080"
+ data-track-index="10"
+ style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10;">
+ </div>
+
+ <!-- Main A-roll and Stats (3s - End) -->
+ <div id="main-layer"
+ data-composition-src="compositions/main.html"
+ data-composition-id="main"
+ data-start="0"
+ data-duration="16.7"
+ data-width="1920"
+ data-height="1080"
+ data-track-index="5"
+ style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 5;">
+ </div>
+
+ <!-- Captions (3s - End) -->
+ <div id="captions-layer"
+ data-composition-src="compositions/captions.html"
+ data-composition-id="captions"
+ data-start="0"
+ data-duration="16.7"
+ data-width="1920"
+ data-height="1080"
+ data-track-index="20"
+ style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 20;">
+ </div>
+
+ <!-- Background Audio (A-roll Audio) -->
+ <audio id="aroll-audio"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/70648f53_abe84fb9991841ae8ba82ee21ba6d37e.mp4"
+ data-start="0"
+ data-duration="16.7"
+ data-track-index="1">
+ </audio>
+ </div>
+
+ <script>
+ window.__timelines = {};
+ const mainTimeline = gsap.timeline({ paused: true });
+ window.__timelines["root"] = mainTimeline;
+ </script>
+</body>
+</html>
diff --git a/packages/producer/tests/style-8-prod/meta.json b/packages/producer/tests/style-8-prod/meta.json
new file mode 100644
index 0000000000..9454ff5e66
--- /dev/null
+++ b/packages/producer/tests/style-8-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-8-prod",
+ "description": "Regression fixture imported from normalized style pack style-8-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "landscape"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-8-prod/src/assets/abstract_shapes.svg b/packages/producer/tests/style-8-prod/src/assets/abstract_shapes.svg
new file mode 100644
index 0000000000..ad9f40863f
--- /dev/null
+++ b/packages/producer/tests/style-8-prod/src/assets/abstract_shapes.svg
@@ -0,0 +1,16 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" width="1920" height="1080">
+ <defs>
+ <filter id="soft-edge">
+ <feGaussianBlur stdDeviation="8" />
+ </filter>
+ </defs>
+
+ <!-- Soft-edged translucent color field -->
+ <path id="color-field" d="M 60 100 C 60 60, 140 50, 150 100 C 160 150, 80 160, 60 100 Z" fill="#4A5568" opacity="0.3" filter="url(#soft-edge)" />
+
+ <!-- Gestural brushstroke / torn paper fragment -->
+ <path id="brushstroke" d="M 30 140 C 50 110, 90 130, 120 90 C 140 60, 170 80, 180 50 C 175 70, 150 100, 130 120 C 100 150, 60 130, 40 160 Z" fill="#F7F3ED" />
+
+ <!-- Compositional anchor -->
+ <circle id="anchor" cx="160" cy="150" r="6" fill="#1A1A2E" />
+</svg>
\ No newline at end of file
diff --git a/packages/producer/tests/style-8-prod/src/assets/accent_shape.svg b/packages/producer/tests/style-8-prod/src/assets/accent_shape.svg
new file mode 100644
index 0000000000..c5d117bdd2
--- /dev/null
+++ b/packages/producer/tests/style-8-prod/src/assets/accent_shape.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100%" height="100%">
+ <path id="accent-shape" fill="#C0392B" d="M 15 85 C 35 60, 55 40, 80 20 L 65 15 C 75 10, 85 5, 95 5 C 95 15, 90 25, 85 35 L 70 30 C 45 50, 25 70, 15 85 Z" />
+</svg>
\ No newline at end of file
diff --git a/packages/producer/tests/style-8-prod/src/code_review.md b/packages/producer/tests/style-8-prod/src/code_review.md
new file mode 100644
index 0000000000..484b3b95b4
--- /dev/null
+++ b/packages/producer/tests/style-8-prod/src/code_review.md
@@ -0,0 +1,70 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 4
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None found. The compositions follow the HyperFrame schema correctly, including deterministic code, finite timelines, and proper registration.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images used)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - absolute timing used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+## File Analysis
+
+### index.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Correctly defines the master composition with `data-composition-id="editor-agent"`.
+- Includes `data-width`, `data-height`, and `data-duration`.
+- Orchestrates sub-compositions using `data-composition-src`.
+- Registers the master timeline in `window.__timelines`.
+
+### compositions/title-card.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Uses `<template>` tag as required.
+- Root element has `data-composition-id`, `data-width`, `data-height`, and `data-duration`.
+- Script is deterministic and registers the timeline correctly.
+- Styles are scoped using the `[data-composition-id="title-card"]` selector.
+
+### compositions/captions.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Uses `<template>` tag.
+- Root element has all required data attributes.
+- Script uses a deterministic array of timings for caption animations.
+- Correctly registers the timeline.
+
+### compositions/main-video.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Uses `<template>` tag.
+- Root element has all required data attributes.
+- Contains a primitive `<video>` clip with `id`, `data-start`, `data-duration`, and `data-track`.
+- Script handles visual animations (scaling, positioning, opacity) without interfering with video playback.
+- Background animations are deterministic (fixed durations and values).
+- Correctly registers the timeline.
+
+## Recommendations
+- **Relative Timing**: While absolute timing is used correctly, consider using relative timing (e.g., `data-start="title-card"`) in `index.html` for better maintainability if durations change.
+- **Asset Paths**: Ensure all asset paths (like `assets/abstract_shapes.svg`) are correct relative to the final deployment structure.
diff --git a/packages/producer/tests/style-8-prod/src/compositions/captions.html b/packages/producer/tests/style-8-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..4ff4ebaf60
--- /dev/null
+++ b/packages/producer/tests/style-8-prod/src/compositions/captions.html
@@ -0,0 +1,100 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1920" data-height="1080" data-duration="16.04">
+ <div class="captions-container">
+ <div id="caption-1" class="caption-group">WE ASKED WHAT YOU NEEDED.</div>
+ <div id="caption-2" class="caption-group">FORTY-SEVEN PERCENT OF YOU SAID</div>
+ <div id="caption-3" class="caption-group">MOTION GRAPHICS.</div>
+ <div id="caption-4" class="caption-group">SIXTY-TWO PERCENT SAID STATIC</div>
+ <div id="caption-5" class="caption-group">CONTENT WAS COSTING YOU ATTENTION,</div>
+ <div id="caption-6" class="caption-group">AND THREE OUT OF FOUR</div>
+ <div id="caption-7" class="caption-group">SAID YOU KNOW THE LOOK</div>
+ <div id="caption-8" class="caption-group">YOU WANT BUT DON'T HAVE</div>
+ <div id="caption-9" class="caption-group">THE EDITING SKILLS TO GET</div>
+ <div id="caption-10" class="caption-group">THERE.</div>
+ <div id="caption-11" class="caption-group">SO WE BUILT</div>
+ <div id="caption-12" class="caption-group">EDITOR AGENT</div>
+ </div>
+
+ <style>
+ [data-composition-id="captions"] {
+ width: 100%;
+ height: 100%;
+ font-family: 'Inter', sans-serif;
+ overflow: hidden;
+ }
+
+ [data-composition-id="captions"] .captions-container {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: flex-end;
+ padding-bottom: 15%; /* Positioning: bottom 15% of the screen */
+ }
+
+ [data-composition-id="captions"] .caption-group {
+ position: absolute;
+ opacity: 0;
+ color: #F7F3ED; /* Clean, white typography */
+ font-size: 48px;
+ font-weight: 300; /* weight 300 */
+ text-transform: uppercase; /* uppercase */
+ letter-spacing: 0.2em; /* letter-spacing 0.2em */
+ text-align: center;
+ /* Subtle text-shadow for legibility */
+ text-shadow: 0 2px 10px rgba(0,0,0,0.5);
+ white-space: nowrap;
+ max-width: 90%;
+ /* background-color: rgba(0, 0, 0, 0.5) REMOVED */
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ const groups = [
+ { id: '#caption-1', start: 0.119, end: 1.819 },
+ { id: '#caption-2', start: 1.839, end: 3.179 },
+ { id: '#caption-3', start: 3.24, end: 4.639 },
+ { id: '#caption-4', start: 4.659, end: 6.399 },
+ { id: '#caption-5', start: 6.46, end: 8.659 },
+ { id: '#caption-6', start: 8.699, end: 9.799 },
+ { id: '#caption-7', start: 9.84, end: 10.699 },
+ { id: '#caption-8', start: 10.739, end: 11.779 },
+ { id: '#caption-9', start: 11.819, end: 13.18 },
+ { id: '#caption-10', start: 13.22, end: 14.22 },
+ { id: '#caption-11', start: 14.239, end: 14.88 },
+ { id: '#caption-12', start: 15.079, end: 16.019 }
+ ];
+
+ const FADE_DURATION = 0.4; // Smooth 400ms fades
+
+ groups.forEach((group, index) => {
+ const nextGroup = groups[index + 1];
+ // Timing: Stay visible until replaced by the next group
+ const displayEnd = nextGroup ? nextGroup.start : group.end;
+
+ // Fade In
+ tl.to(group.id, {
+ opacity: 1,
+ duration: FADE_DURATION,
+ ease: "power2.out"
+ }, group.start);
+
+ // Fade Out
+ // We start the fade out exactly when the next group starts to fade in
+ // This ensures a smooth transition between groups
+ tl.to(group.id, {
+ opacity: 0,
+ duration: FADE_DURATION,
+ ease: "power2.in"
+ }, displayEnd);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-8-prod/src/compositions/main-video.html b/packages/producer/tests/style-8-prod/src/compositions/main-video.html
new file mode 100644
index 0000000000..10e884ee99
--- /dev/null
+++ b/packages/producer/tests/style-8-prod/src/compositions/main-video.html
@@ -0,0 +1,220 @@
+<template id="main-video-template">
+ <div data-composition-id="main-video" data-width="1920" data-height="1080" data-duration="19.04">
+ <!-- Background Layer -->
+ <div class="background-container">
+ <div class="abstract-shape shape-1"></div>
+ <div class="abstract-shape shape-2"></div>
+ <div class="abstract-shape shape-3"></div>
+ </div>
+
+ <!-- A-roll Container -->
+ <div class="aroll-wrapper">
+ <video id="aroll-video"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/c311bdbf_97f959ca3be34382be873d54a405711b.mp4"
+ data-start="3"
+ data-duration="16.04"
+ data-track-index="0"
+ crossorigin="anonymous">
+ </video>
+ </div>
+
+ <!-- Stats Layer -->
+ <div class="stats-container">
+ <div id="stat-47" class="stat-text color-red">47%</div>
+ <div id="stat-62" class="stat-text color-gold">62%</div>
+ <div id="stat-75" class="stat-text color-olive">75%</div>
+ </div>
+
+ <style>
+ [data-composition-id="main-video"] {
+ background-color: #1A1A2E; /* charcoal */
+ font-family: 'Inter', sans-serif;
+ overflow: hidden;
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ }
+
+ [data-composition-id="main-video"] .background-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 0;
+ }
+
+ [data-composition-id="main-video"] .abstract-shape {
+ position: absolute;
+ background-image: url('assets/abstract_shapes.svg');
+ background-repeat: no-repeat;
+ background-size: contain;
+ opacity: 0.15;
+ }
+
+ [data-composition-id="main-video"] .shape-1 { width: 800px; height: 800px; top: -200px; left: -200px; }
+ [data-composition-id="main-video"] .shape-2 { width: 600px; height: 600px; bottom: -100px; right: -100px; }
+ [data-composition-id="main-video"] .shape-3 { width: 400px; height: 400px; top: 20%; right: 10%; }
+
+ [data-composition-id="main-video"] .aroll-wrapper {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ width: 1920px;
+ height: 1080px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 1;
+ }
+
+ [data-composition-id="main-video"] #aroll-video {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ border-radius: 6px;
+ opacity: 0; /* Start hidden for fade in */
+ }
+
+ [data-composition-id="main-video"] .stats-container {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ z-index: 2;
+ }
+
+ [data-composition-id="main-video"] .stat-text {
+ position: absolute;
+ font-size: 280px;
+ font-weight: 800;
+ opacity: 0;
+ text-shadow: 0 20px 40px rgba(0,0,0,0.4);
+ letter-spacing: -0.05em;
+ }
+
+ [data-composition-id="main-video"] .color-red { color: #E74C3C; }
+ [data-composition-id="main-video"] .color-gold { color: #F1C40F; }
+ [data-composition-id="main-video"] .color-olive { color: #82956D; }
+
+ /* Positioning for stats */
+ [data-composition-id="main-video"] #stat-47,
+ [data-composition-id="main-video"] #stat-62 {
+ right: 12%;
+ top: 50%;
+ transform: translateY(-50%);
+ }
+
+ [data-composition-id="main-video"] #stat-75 {
+ left: 50%;
+ bottom: 8%;
+ transform: translateX(-50%);
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.839, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics.', 'start': 3.579, 'end': 4.639}, {'text': 'Sixty-two', 'start': 4.659, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.099, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.479}, {'text': 'look', 'start': 10.52, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.86}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Editor', 'start': 15.079, 'end': 15.42}, {'text': 'Agent', 'start': 15.619, 'end': 16.019}];
+ const AROLL_START = 3; // Master timeline start for A-roll
+ const TOTAL_DURATION = 19.04;
+
+ // 1. A-roll starts (after title card ends at 3s): fades in over 500ms at 100% scale, centered.
+ tl.to('#aroll-video', {
+ opacity: 1,
+ duration: 0.5,
+ ease: 'power2.inOut'
+ }, AROLL_START);
+
+ // 2. First stat (47%): At 1.839s (A-roll playback time), A-roll scales down to 70% and shifts to the left side.
+ // A-roll playback time 1.839s = 3 + 1.839 = 4.839s on master.
+ const STAT_1_TIME = AROLL_START + 1.839;
+ tl.to('#aroll-video', {
+ scale: 0.7,
+ x: -400, // Shift left
+ duration: 0.8,
+ ease: 'expo.out'
+ }, STAT_1_TIME);
+
+ // Graphic 1 (47%): At 1.839s, text "47%" fades in. Stay until 4.639s (A-roll time).
+ // 4.639s A-roll time = 7.639s master.
+ tl.fromTo('#stat-47',
+ { opacity: 0, scale: 0.8, x: 50 },
+ { opacity: 1, scale: 1, x: 0, duration: 0.8, ease: 'expo.out' },
+ STAT_1_TIME
+ );
+ tl.to('#stat-47', {
+ opacity: 0,
+ scale: 1.1,
+ duration: 0.5,
+ ease: 'power2.in'
+ }, AROLL_START + 4.639);
+
+ // 3. Second stat (62%): A-roll remains scaled down/shifted.
+ // Graphic 2 (62%): At 4.659s (A-roll time), text "62%" fades in. Stay until 8.659s (A-roll time).
+ const STAT_2_TIME = AROLL_START + 4.659;
+ tl.fromTo('#stat-62',
+ { opacity: 0, scale: 0.8, x: 50 },
+ { opacity: 1, scale: 1, x: 0, duration: 0.8, ease: 'expo.out' },
+ STAT_2_TIME
+ );
+ tl.to('#stat-62', {
+ opacity: 0,
+ scale: 1.1,
+ duration: 0.5,
+ ease: 'power2.in'
+ }, AROLL_START + 8.659);
+
+ // 4. Third major narrativa beat ("three out of four" = 75%): At 8.88s (A-roll playback time), A-roll scales back up to 100% and recenters.
+ const STAT_3_TIME = AROLL_START + 8.88;
+ tl.to('#aroll-video', {
+ scale: 1,
+ x: 0,
+ duration: 1.0,
+ ease: 'expo.out'
+ }, STAT_3_TIME);
+
+ // Graphic 3 (75%): At 8.88s, text "75%" fades in below the centered A-roll. Stay until 14.22s (A-roll time).
+ tl.fromTo('#stat-75',
+ { opacity: 0, scale: 0.8, y: 50 },
+ { opacity: 1, scale: 1, y: 0, duration: 0.8, ease: 'expo.out' },
+ STAT_3_TIME
+ );
+ tl.to('#stat-75', {
+ opacity: 0,
+ scale: 1.1,
+ duration: 0.5,
+ ease: 'power2.in'
+ }, AROLL_START + 14.22);
+
+ // Ambient Background Motion (Drift throughout entire 19.04s duration)
+ tl.to('.shape-1', {
+ x: 100,
+ y: 60,
+ rotation: 15,
+ duration: TOTAL_DURATION,
+ ease: 'none'
+ }, 0);
+ tl.to('.shape-2', {
+ x: -80,
+ y: -40,
+ rotation: -10,
+ duration: TOTAL_DURATION,
+ ease: 'none'
+ }, 0);
+ tl.to('.shape-3', {
+ scale: 1.3,
+ x: -30,
+ duration: TOTAL_DURATION,
+ ease: 'none'
+ }, 0);
+
+ // Register timeline
+ window.__timelines["main-video"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-8-prod/src/compositions/title-card.html b/packages/producer/tests/style-8-prod/src/compositions/title-card.html
new file mode 100644
index 0000000000..a7f4c4570c
--- /dev/null
+++ b/packages/producer/tests/style-8-prod/src/compositions/title-card.html
@@ -0,0 +1,105 @@
+<template id="title-card-template">
+ <div data-composition-id="title-card" data-width="1920" data-height="1080" data-duration="3">
+ <div class="background"></div>
+ <div class="fragment"></div>
+ <div class="title-container">
+ <h1 class="title">EDITOR AGENT</h1>
+ </div>
+
+ <style>
+ [data-composition-id="title-card"] {
+ width: 1920px;
+ height: 1080px;
+ background-color: #4A5568;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ overflow: hidden;
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
+ }
+
+ [data-composition-id="title-card"] .background {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: radial-gradient(circle at 50% 50%, #5A677C 0%, #4A5568 100%);
+ pointer-events: none;
+ }
+
+ [data-composition-id="title-card"] .fragment {
+ position: absolute;
+ width: 400px;
+ height: 400px;
+ background-color: #F7F3ED;
+ border-radius: 45% 55% 70% 30% / 30% 40% 60% 70%;
+ filter: blur(20px);
+ opacity: 0;
+ pointer-events: none;
+ left: 20%;
+ top: 30%;
+ }
+
+ [data-composition-id="title-card"] .title-container {
+ z-index: 10;
+ }
+
+ [data-composition-id="title-card"] .title {
+ color: #F7F3ED;
+ font-size: 84px;
+ font-weight: 100;
+ letter-spacing: 0.4em;
+ margin: 0;
+ opacity: 0;
+ text-transform: uppercase;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const compSelector = '[data-composition-id="title-card"]';
+
+ // Title Animation: Fade in over 1.5s and slight drift
+ tl.fromTo(`${compSelector} .title`,
+ {
+ opacity: 0,
+ y: 20
+ },
+ {
+ opacity: 1,
+ y: 0,
+ duration: 1.5,
+ ease: "power3.out"
+ }, 0);
+
+ // Fragment Animation: Drift in and increase opacity to 0.3
+ tl.fromTo(`${compSelector} .fragment`,
+ {
+ x: -100,
+ y: 50,
+ opacity: 0,
+ scale: 0.9
+ },
+ {
+ x: 0,
+ y: 0,
+ opacity: 0.3,
+ scale: 1,
+ duration: 3,
+ ease: "power2.out"
+ }, 0);
+
+ // Ambient drift for the title throughout the 3s
+ tl.to(`${compSelector} .title`, {
+ y: -10,
+ duration: 3,
+ ease: "none"
+ }, 0);
+
+ window.__timelines["title-card"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-8-prod/src/design_review.md b/packages/producer/tests/style-8-prod/src/design_review.md
new file mode 100644
index 0000000000..e8d9716c5d
--- /dev/null
+++ b/packages/producer/tests/style-8-prod/src/design_review.md
@@ -0,0 +1,61 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a corporate PowerPoint presentation from 2012 trying to be "edgy" with a dark theme. It’s static, the typography is uninspired, and the layout is as predictable as a dial-tone.
+
+---
+
+## CRITICAL Design Failures
+
+Issues that make this look unprofessional or straight-up ugly. These MUST be fixed.
+
+### Obscene Stat Typography
+**Where:** `compositions/main-video.html` - `.stat-text`
+**What's wrong:** A font size of `280px` is not a "design choice," it's a cry for help. Using `Inter` at that scale with a generic `text-shadow` looks amateurish and clutters the frame. The colors (#E74C3C, #F1C40F, #82956D) are straight out of a default CSS color palette and clash horribly with the "charcoal" background.
+**Why it matters:** It screams "I don't know how to create visual hierarchy, so I'll just make the numbers huge." It distracts from the A-roll and makes the entire composition feel cheap.
+**Fix it:** Reduce the font size to something sane (e.g., `120px-160px`). Use a more sophisticated color palette—muted tones or high-contrast neons, not "primary school red and yellow." Lose the heavy text-shadow; it’s dated.
+
+### The "Floating Video" Syndrome
+**Where:** `compositions/main-video.html` - `#aroll-video`
+**What's wrong:** Scaling the video down to 70% and just shoving it to the left (`x: -400`) leaves a massive, awkward void on the right. The `border-radius: 6px` is so subtle it might as well not be there.
+**Why it matters:** It lacks intentionality. It looks like the video is hiding from the text. There’s no framing, no container, no stylistic treatment to make the video feel like part of the design.
+**Fix it:** Give the video a proper frame or a stylized border. Use the `abstract_shapes.svg` more effectively to "cradle" the video or create a more dynamic split-screen layout rather than just "sliding it over."
+
+### Caption Legibility & Placement
+**Where:** `compositions/captions.html` - `.captions-container`
+**What's wrong:** Bottom 15% placement with a `0.2em` letter spacing on `Inter` weight 300 is a recipe for unreadability. The `text-shadow` is a lazy fix for poor contrast.
+**Why it matters:** If the viewer has to squint to read the core message, you’ve failed. The wide letter-spacing on thin weights makes the words fall apart visually.
+**Fix it:** Increase the font weight to 500 or 600. Reduce letter-spacing to `0.05em`. Consider a subtle semi-transparent background blur (backdrop-filter) instead of a muddy text-shadow.
+
+---
+
+## Design Improvements
+
+Things that aren't broken but are boring, lazy, or could be significantly better.
+
+### Title Card Lethargy
+**Where:** `compositions/title-card.html`
+**The problem:** A 3-second fade-in of "EDITOR AGENT" with a single blurry blob (`.fragment`) is the definition of "minimum viable product." It’s forgettable.
+**Make it better:** Use the `accent_shape.svg` to create some sharp, aggressive geometric interest. Animate the letters individually or use a mask reveal. Make the background gradient more dynamic—right now it’s just a static gray smudge.
+
+### Robotic Motion
+**Where:** `compositions/main-video.html` - GSAP Timelines
+**The problem:** The background shapes move at a constant `ease: 'none'` for 19 seconds. It’s robotic and lacks the "organic" feel the SVG shapes suggest.
+**Make it better:** Use `sine.inOut` or `power1.inOut` for the background drift to create a more natural, floating sensation. Vary the speeds of the three shapes to create actual parallax depth.
+
+---
+
+## What Actually Works
+
+The use of `Inter` weight 100 for the title card is actually a decent nod to high-end editorial design. It’s the only part of this that feels like it belongs in this decade. The "Henryk Tomaszewski Style" mentioned in the title suggests an intent for Polish Poster School aesthetics—the abstract shapes are a good start, but they need to be much bolder and more integrated into the layout to actually achieve that look.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 3/10 - It has the presence of a corporate training video.
+**Color & Typography:** 2/10 - Default colors and "big text" do not equal design.
+**Motion & Animation Feel:** 4/10 - Functional but lacks any soul or rhythm.
+**Overall Aesthetic:** 3/10 - Amateurish and dated.
+
+**Bottom Line:** This needs a complete visual overhaul. Stop relying on font size to do the heavy lifting and start thinking about composition, color theory, and modern motion principles. Right now, it’s a mess.
diff --git a/packages/producer/tests/style-8-prod/src/index.html b/packages/producer/tests/style-8-prod/src/index.html
new file mode 100644
index 0000000000..14d24717d3
--- /dev/null
+++ b/packages/producer/tests/style-8-prod/src/index.html
@@ -0,0 +1,53 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Editor Agent - Henryk Tomaszewski Style</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@100;300;800&display=swap" rel="stylesheet">
+ <style>
+ body { margin: 0; padding: 0; background-color: #1A1A2E; overflow: hidden; width: 1920px; height: 1080px; }
+ #master-composition { width: 1920px; height: 1080px; position: relative; }
+ </style>
+</head>
+<body>
+ <div id="master-composition" data-composition-id="editor-agent" data-width="1920" data-height="1080" data-duration="19.04">
+
+ <!-- Main Video & A-roll -->
+ <div id="main-video-comp"
+ data-composition-id="main-video"
+ data-composition-src="compositions/main-video.html"
+ data-start="0"
+ data-duration="19.04"
+ data-track-index="0">
+ </div>
+
+ <!-- Title Card (0-3s) -->
+ <div id="title-card-comp"
+ data-composition-id="title-card"
+ data-composition-src="compositions/title-card.html"
+ data-start="0"
+ data-duration="3"
+ data-track-index="1">
+ </div>
+
+ <!-- Captions (Overlay) -->
+ <div id="captions-comp"
+ data-composition-id="captions"
+ data-composition-src="compositions/captions.html"
+ data-start="3"
+ data-duration="16.04"
+ data-track-index="2">
+ </div>
+
+ </div>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ window.__timelines["editor-agent"] = tl;
+ })();
+ </script>
+</body>
+</html>
diff --git a/packages/producer/tests/style-9-prod/meta.json b/packages/producer/tests/style-9-prod/meta.json
new file mode 100644
index 0000000000..6daa0c98fb
--- /dev/null
+++ b/packages/producer/tests/style-9-prod/meta.json
@@ -0,0 +1,17 @@
+{
+ "name": "style-9-prod",
+ "description": "Regression fixture imported from normalized style pack style-9-prod",
+ "tags": [
+ "style-regression",
+ "prod-style",
+ "slow",
+ "landscape"
+ ],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/style-9-prod/src/code_review.md b/packages/producer/tests/style-9-prod/src/code_review.md
new file mode 100644
index 0000000000..09c50c87a9
--- /dev/null
+++ b/packages/producer/tests/style-9-prod/src/code_review.md
@@ -0,0 +1,61 @@
+# HyperFrame Schema Compliance Review
+
+## Executive Summary
+- Total files reviewed: 4
+- Critical issues: 0
+- Overall compliance status: PASS
+
+## Critical Issues
+None found. The compositions follow the deterministic requirements and structural rules of the HyperFrame schema.
+
+## Compliance Checklist
+- [x] All compositions have `data-width` and `data-height` attributes
+- [x] All timelines are finite with duration > 0
+- [x] All compositions registered in `window.__timelines`
+- [x] No use of `Math.random()`, `Date.now()`, or non-deterministic code
+- [x] Primitive clips have required data attributes (`id`, `data-start`, `data-track`)
+- [x] `data-duration` specified for all `<img>` clips (N/A - no images used)
+- [x] No manual media playback control (`video.play()`, `audio.pause()`, etc.)
+- [x] No manual clip mounting/unmounting in scripts
+- [x] Relative timing references are valid (N/A - absolute timing used)
+- [x] Clips on same track don't overlap in time
+- [x] Reusable compositions in separate HTML files
+- [x] Composition files use `<template>` tags
+- [x] External compositions loaded via `data-composition-src`
+- [x] All script-animated content wrapped in compositions
+- [x] No infinite or zero-duration timelines
+
+### index.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Correctly defines the root composition `main-video`.
+- Uses `data-composition-src` for external compositions.
+- Registers its timeline in `window.__timelines`.
+- Audio clips have `id`, `data-start`, and `data-track`.
+
+### compositions/intro.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Wrapped in a `<template>` tag.
+- Root element has `data-composition-id`, `data-width`, `data-height`, and `data-duration`.
+- Script is deterministic and registers the timeline.
+
+### compositions/captions.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Wrapped in a `<template>` tag.
+- Root element has `data-composition-id`, `data-width`, `data-height`, and `data-duration`.
+- Script uses a fixed transcript for deterministic caption generation.
+- Correctly registers the timeline.
+
+### compositions/stats.html
+**Status**: COMPLIANT
+
+**Observations**:
+- Wrapped in a `<template>` tag.
+- Root element has `data-composition-id`, `data-width`, `data-height`, and `data-duration`.
+- Script is deterministic. Ambient motion is implemented using a finite loop based on `totalDuration`, avoiding infinite repeats which is good practice for the renderer.
+- Correctly registers the timeline.
diff --git a/packages/producer/tests/style-9-prod/src/compositions/captions.html b/packages/producer/tests/style-9-prod/src/compositions/captions.html
new file mode 100644
index 0000000000..e3dee62cca
--- /dev/null
+++ b/packages/producer/tests/style-9-prod/src/compositions/captions.html
@@ -0,0 +1,97 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1920" data-height="1080" data-duration="16.04">
+ <div id="captions-container"></div>
+
+ <style>
+ [data-composition-id="captions"] {
+ width: 1920px;
+ height: 1080px;
+ pointer-events: none;
+ }
+
+ [data-composition-id="captions"] #captions-container {
+ position: absolute;
+ bottom: 100px; /* Position in bottom 1/3 */
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ height: 150px; /* Fixed height for the caption box */
+ }
+
+ .caption-box {
+ position: absolute; /* Stacked in the same place */
+ background-color: #FF2D8A;
+ color: white;
+ padding: 20px 40px;
+ border-radius: 16px;
+ font-family: 'Nunito', sans-serif;
+ font-weight: 900; /* Nunito Black */
+ font-size: 64px;
+ text-align: center;
+ display: inline-block;
+ white-space: nowrap;
+ opacity: 0;
+ visibility: hidden;
+ transform: scale(0);
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.839, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics.', 'start': 3.579, 'end': 4.639}, {'text': 'Sixty-two', 'start': 4.659, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.099, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.479}, {'text': 'look', 'start': 10.52, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.86}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Editor', 'start': 15.079, 'end': 15.42}, {'text': 'Agent', 'start': 15.619, 'end': 16.019}];
+ const container = document.getElementById('captions-container');
+ const tl = gsap.timeline({ paused: true });
+
+ // Group transcript into lines (max 5 words)
+ const lines = [];
+ for (let i = 0; i < TRANSCRIPT.length; i += 5) {
+ lines.push(TRANSCRIPT.slice(i, i + 5));
+ }
+
+ lines.forEach((lineWords, index) => {
+ const lineText = lineWords.map(w => w.text).join(' ');
+ const startTime = lineWords[0].start;
+ const endTime = lineWords[lineWords.length - 1].end;
+
+ // Create element
+ const el = document.createElement('div');
+ el.className = 'caption-box';
+ el.textContent = lineText;
+ el.id = `caption-line-${index}`;
+ container.appendChild(el);
+
+ // Animation: Pop in with scale-up bounce (0% to 110% to 100%)
+ tl.to(el, {
+ autoAlpha: 1,
+ scale: 1.1,
+ duration: 0.2,
+ ease: "power2.out"
+ }, startTime);
+
+ tl.to(el, {
+ scale: 1,
+ duration: 0.1,
+ ease: "power2.inOut"
+ }, startTime + 0.2);
+
+ // Stay visible until next line or end of its duration
+ // We hide it when the next line starts or at its own end time
+ const hideTime = (index < lines.length - 1) ? Math.min(endTime, lines[index+1][0].start) : endTime;
+
+ tl.to(el, {
+ autoAlpha: 0,
+ scale: 0,
+ duration: 0.15,
+ ease: "power2.in"
+ }, hideTime);
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-9-prod/src/compositions/intro.html b/packages/producer/tests/style-9-prod/src/compositions/intro.html
new file mode 100644
index 0000000000..fa98e3090c
--- /dev/null
+++ b/packages/producer/tests/style-9-prod/src/compositions/intro.html
@@ -0,0 +1,88 @@
+<template id="intro-template">
+ <div id="intro-comp" data-composition-id="intro" data-start="0" data-duration="16.04" data-width="1920" data-height="1080">
+ <div class="intro-container">
+ <h1 class="title">EDITOR AGENT</h1>
+ </div>
+
+ <style>
+ @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@900&display=swap');
+
+ [data-composition-id="intro"] .intro-container {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ pointer-events: none;
+ }
+
+ [data-composition-id="intro"] .title {
+ font-family: 'Nunito', sans-serif;
+ font-weight: 900;
+ font-size: 180px;
+ color: #FF2D8A; /* Hot Pink */
+ text-transform: uppercase;
+ transform: rotate(-5deg); /* Tilted 5 degrees */
+ margin: 0;
+ padding: 20px;
+ /* Layered offset shadow for depth without suffocating letterforms */
+ filter: drop-shadow(8px 8px 0 #FFFFFF) drop-shadow(15px 15px 0 rgba(0,0,0,0.1));
+ opacity: 0;
+ scale: 0;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ // --- INTRO SEQUENCE ---
+ // Animation: Scale-up bounce (0% to 110% to 100%) with elastic overshoot
+ // Starts at 0.5s, lasts until 3s
+ tl.to('[data-composition-id="intro"] .title', {
+ opacity: 1,
+ scale: 1.1,
+ duration: 0.6,
+ ease: "back.out(1.7)",
+ delay: 0.5
+ })
+ .to('[data-composition-id="intro"] .title', {
+ scale: 1,
+ duration: 0.4,
+ ease: "elastic.out(1, 0.3)"
+ })
+ // Ambient motion
+ .to('[data-composition-id="intro"] .title', {
+ rotation: "-3deg",
+ duration: 1,
+ repeat: 1,
+ yoyo: true,
+ ease: "sine.inOut"
+ }, "-=0.5")
+ // Exit intro
+ .to('[data-composition-id="intro"] .title', {
+ opacity: 0,
+ scale: 0.5,
+ duration: 0.3,
+ ease: "power2.in"
+ }, 1.4);
+
+ // --- END CARD SEQUENCE ---
+ // Appears at 14.619s (after Moment 3 finishes exiting at 14.239 + 0.3)
+ tl.to('[data-composition-id="intro"] .title', {
+ opacity: 1,
+ scale: 1.1,
+ duration: 0.6,
+ ease: "back.out(1.7)"
+ }, 14.619)
+ .to('[data-composition-id="intro"] .title', {
+ scale: 1,
+ duration: 0.4,
+ ease: "elastic.out(1, 0.3)"
+ });
+
+ window.__timelines["intro"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-9-prod/src/compositions/stats.html b/packages/producer/tests/style-9-prod/src/compositions/stats.html
new file mode 100644
index 0000000000..17940c73ce
--- /dev/null
+++ b/packages/producer/tests/style-9-prod/src/compositions/stats.html
@@ -0,0 +1,252 @@
+<template id="stats-template">
+ <div data-composition-id="stats" data-width="1920" data-height="1080" data-duration="16.04">
+ <div id="stats-container">
+ <!-- Moment 1: 47% NEED MOTION GRAPHICS -->
+ <div id="moment-1" class="moment" style="opacity: 0; transform: scale(0) rotate(8deg);">
+ <div class="sticker-stack">
+ <div class="sticker-bg blue-bg"></div>
+ <div class="sticker-content white-bg blue-border">
+ <div class="stat-number blue-text">47%</div>
+ <div class="stat-label blue-text">NEED MOTION GRAPHICS</div>
+ </div>
+ </div>
+ <!-- Decorative shapes -->
+ <div class="shape circle pink-bg" style="top: -40px; left: -40px; width: 80px; height: 80px;"></div>
+ <div class="shape pill lime-bg" style="bottom: -30px; right: -50px; width: 120px; height: 40px; transform: rotate(-15deg);"></div>
+ </div>
+
+ <!-- Moment 2: 62% STRUGGLE WITH STATIC CONTENT -->
+ <div id="moment-2" class="moment" style="opacity: 0; transform: scale(0) rotate(-5deg);">
+ <div class="sticker-stack">
+ <div class="sticker-bg white-bg"></div>
+ <div class="sticker-content blue-bg white-border">
+ <div class="stat-number white-text">62%</div>
+ <div class="stat-label white-text">STRUGGLE WITH STATIC CONTENT</div>
+ </div>
+ </div>
+ <!-- Decorative shapes -->
+ <div class="shape blob yellow-bg" style="top: -50px; right: -30px; width: 100px; height: 100px; border-radius: 40% 60% 70% 30% / 40% 50% 60% 50%;"></div>
+ <div class="shape circle pink-bg" style="bottom: -20px; left: -40px; width: 60px; height: 60px;"></div>
+ </div>
+
+ <!-- Moment 3: 75% LACK EDITING SKILLS -->
+ <div id="moment-3" class="moment" style="opacity: 0; transform: scale(0) rotate(3deg);">
+ <div class="sticker-stack">
+ <div class="sticker-bg pink-bg"></div>
+ <div class="sticker-content white-bg pink-border">
+ <div class="stat-number pink-text">75%</div>
+ <div class="stat-label pink-text">LACK EDITING SKILLS</div>
+ </div>
+ </div>
+ <!-- Decorative shapes -->
+ <div class="shape pill blue-bg" style="top: -30px; left: 50%; transform: translateX(-50%) rotate(5deg); width: 150px; height: 45px;"></div>
+ <div class="shape circle yellow-bg" style="bottom: -40px; right: -20px; width: 90px; height: 90px;"></div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="stats"] {
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ font-family: 'Nunito', sans-serif;
+ overflow: hidden;
+ }
+
+ [data-composition-id="stats"] #stats-container {
+ width: 100%;
+ height: 100%;
+ position: relative;
+ }
+
+ [data-composition-id="stats"] .moment {
+ position: absolute;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 40px;
+ z-index: 100;
+ }
+
+ /* Layout Positions */
+ [data-composition-id="stats"] #moment-1 {
+ top: 200px;
+ right: 150px; /* Right side when A-roll is Left */
+ width: 600px;
+ }
+
+ [data-composition-id="stats"] #moment-2 {
+ top: 250px;
+ left: 100px; /* Left side when A-roll is Right */
+ width: 700px;
+ }
+
+ [data-composition-id="stats"] #moment-3 {
+ bottom: 100px; /* Below A-roll when centered */
+ left: 50%;
+ transform: translateX(-50%);
+ width: 800px;
+ }
+
+ /* Sticker Stack Effect */
+ [data-composition-id="stats"] .sticker-stack {
+ position: relative;
+ width: 100%;
+ padding: 40px;
+ filter: drop-shadow(0 15px 0 rgba(0, 87, 255, 0.2));
+ }
+
+ [data-composition-id="stats"] .sticker-bg {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ border-radius: 40px;
+ z-index: -1;
+ transform: rotate(-2deg);
+ }
+
+ [data-composition-id="stats"] .sticker-content {
+ position: relative;
+ padding: 40px;
+ border-radius: 35px;
+ border: 8px solid currentColor;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ text-align: center;
+ }
+
+ /* Colors */
+ [data-composition-id="stats"] .blue-bg { background-color: #0057FF; }
+ [data-composition-id="stats"] .pink-bg { background-color: #FF2D8A; }
+ [data-composition-id="stats"] .lime-bg { background-color: #7FFF00; }
+ [data-composition-id="stats"] .yellow-bg { background-color: #FFE500; }
+ [data-composition-id="stats"] .white-bg { background-color: #FFFFFF; }
+
+ [data-composition-id="stats"] .blue-text { color: #0057FF; }
+ [data-composition-id="stats"] .white-text { color: #FFFFFF; }
+ [data-composition-id="stats"] .pink-text { color: #FF2D8A; }
+
+ [data-composition-id="stats"] .blue-border { border-color: #0057FF; }
+ [data-composition-id="stats"] .white-border { border-color: #FFFFFF; }
+ [data-composition-id="stats"] .pink-border { border-color: #FF2D8A; }
+
+ /* Typography */
+ [data-composition-id="stats"] .stat-number {
+ font-size: 180px;
+ font-weight: 900;
+ line-height: 1;
+ margin-bottom: 10px;
+ }
+
+ [data-composition-id="stats"] .stat-label {
+ font-size: 48px;
+ font-weight: 900;
+ line-height: 1.1;
+ max-width: 500px;
+ }
+
+ /* Shapes */
+ [data-composition-id="stats"] .shape {
+ position: absolute;
+ z-index: -2;
+ border-radius: 50%;
+ }
+ [data-composition-id="stats"] .pill {
+ border-radius: 100px;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [{'text': 'We', 'start': 0.119, 'end': 0.259}, {'text': 'asked', 'start': 0.319, 'end': 0.479}, {'text': 'what', 'start': 0.519, 'end': 0.659}, {'text': 'you', 'start': 0.699, 'end': 0.819}, {'text': 'needed.', 'start': 0.859, 'end': 1.819}, {'text': 'Forty-seven', 'start': 1.839, 'end': 2.299}, {'text': 'percent', 'start': 2.399, 'end': 2.679}, {'text': 'of', 'start': 2.7, 'end': 2.799}, {'text': 'you', 'start': 2.839, 'end': 2.939}, {'text': 'said', 'start': 3.039, 'end': 3.179}, {'text': 'motion', 'start': 3.24, 'end': 3.559}, {'text': 'graphics.', 'start': 3.579, 'end': 4.639}, {'text': 'Sixty-two', 'start': 4.659, 'end': 5.179}, {'text': 'percent', 'start': 5.299, 'end': 5.759}, {'text': 'said', 'start': 5.859, 'end': 5.98}, {'text': 'static', 'start': 6.099, 'end': 6.399}, {'text': 'content', 'start': 6.46, 'end': 6.879}, {'text': 'was', 'start': 6.92, 'end': 7.079}, {'text': 'costing', 'start': 7.099, 'end': 7.48}, {'text': 'you', 'start': 7.5, 'end': 7.579}, {'text': 'attention,', 'start': 7.679, 'end': 8.659}, {'text': 'and', 'start': 8.699, 'end': 8.86}, {'text': 'three', 'start': 8.88, 'end': 9.06}, {'text': 'out', 'start': 9.079, 'end': 9.18}, {'text': 'of', 'start': 9.199, 'end': 9.34}, {'text': 'four', 'start': 9.38, 'end': 9.799}, {'text': 'said', 'start': 9.84, 'end': 10.0}, {'text': 'you', 'start': 10.019, 'end': 10.159}, {'text': 'know', 'start': 10.179, 'end': 10.36}, {'text': 'the', 'start': 10.38, 'end': 10.479}, {'text': 'look', 'start': 10.52, 'end': 10.699}, {'text': 'you', 'start': 10.739, 'end': 10.859}, {'text': 'want', 'start': 10.98, 'end': 11.34}, {'text': 'but', 'start': 11.359, 'end': 11.52}, {'text': "don't", 'start': 11.56, 'end': 11.779}, {'text': 'have', 'start': 11.819, 'end': 11.94}, {'text': 'the', 'start': 11.96, 'end': 12.06}, {'text': 'editing', 'start': 12.079, 'end': 12.4}, {'text': 'skills', 'start': 12.52, 'end': 12.86}, {'text': 'to', 'start': 12.88, 'end': 13.0}, {'text': 'get', 'start': 13.019, 'end': 13.18}, {'text': 'there.', 'start': 13.22, 'end': 14.22}, {'text': 'So', 'start': 14.239, 'end': 14.399}, {'text': 'we', 'start': 14.42, 'end': 14.52}, {'text': 'built', 'start': 14.619, 'end': 14.88}, {'text': 'Editor', 'start': 15.079, 'end': 15.42}, {'text': 'Agent', 'start': 15.619, 'end': 16.019}];
+ const tl = gsap.timeline({ paused: true });
+
+ // Helper to find word timing
+ function getWordTime(wordText) {
+ const word = TRANSCRIPT.find(w =>
+ w.text.toLowerCase().replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"").startsWith(wordText.toLowerCase())
+ );
+ return word ? word.start : null;
+ }
+
+ // Timings from transcript
+ const t1 = getWordTime("Forty-seven") || 1.839;
+ const t2 = getWordTime("Sixty-two") || 4.659;
+ const t3 = getWordTime("three") || 8.88;
+
+ // Moment 1 Animation (approx 5s)
+ tl.to('#moment-1', {
+ opacity: 1,
+ scale: 1,
+ duration: 0.8,
+ ease: "elastic.out(1, 0.6)",
+ onStart: () => gsap.set('#moment-1', { transformOrigin: "center center" })
+ }, t1);
+
+ // Moment 1 Exit (before Moment 2)
+ tl.to('#moment-1', {
+ opacity: 0,
+ scale: 0.5,
+ duration: 0.3,
+ ease: "back.in(1.7)"
+ }, t2 - 0.4);
+
+ // Moment 2 Animation (approx 9s)
+ tl.to('#moment-2', {
+ opacity: 1,
+ scale: 1,
+ duration: 0.8,
+ ease: "elastic.out(1, 0.6)",
+ onStart: () => gsap.set('#moment-2', { transformOrigin: "center center" })
+ }, t2);
+
+ // Moment 2 Exit (before Moment 3)
+ tl.to('#moment-2', {
+ opacity: 0,
+ scale: 0.5,
+ duration: 0.3,
+ ease: "back.in(1.7)"
+ }, t3 - 0.4);
+
+ // Moment 3 Animation (approx 13s)
+ tl.to('#moment-3', {
+ opacity: 1,
+ scale: 1,
+ duration: 0.8,
+ ease: "elastic.out(1, 0.6)",
+ onStart: () => gsap.set('#moment-3', { transformOrigin: "center center" })
+ }, t3);
+
+ // Moment 3 Exit: 3 words before 'Editor Agent'
+ // 'Editor' is at 15.079. 3 words before is 'So' at 14.239.
+ tl.to('#moment-3', {
+ opacity: 0,
+ scale: 0.5,
+ duration: 0.3,
+ ease: "back.in(1.7)"
+ }, 14.239);
+
+ // Ambient Motion (Finite)
+ const totalDuration = 16.04;
+ gsap.utils.toArray('.shape').forEach((shape, i) => {
+ const stepDuration = 2 + (i * 0.2);
+ const steps = Math.ceil(totalDuration / stepDuration);
+ for(let s = 0; s < steps; s++) {
+ tl.to(shape, {
+ y: (s % 2 === 0 ? 15 : -15),
+ rotation: (s % 2 === 0 ? 5 : -5),
+ duration: stepDuration,
+ ease: "sine.inOut"
+ }, s * stepDuration);
+ }
+ });
+
+ window.__timelines["stats"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/style-9-prod/src/design_review.md b/packages/producer/tests/style-9-prod/src/design_review.md
new file mode 100644
index 0000000000..267cfab7f7
--- /dev/null
+++ b/packages/producer/tests/style-9-prod/src/design_review.md
@@ -0,0 +1,62 @@
+# HyperFrames Design Review
+
+## First Impression
+This looks like a high-energy, "MrBeast-lite" social media ad that's trying way too hard to be "fun" but ends up feeling like a chaotic sticker book. It's loud, it's pink, and it's visually exhausting.
+
+---
+
+## CRITICAL Design Failures
+
+Issues that make this look unprofessional or straight-up ugly. These MUST be fixed.
+
+### The "Sticker Book" Chaos
+**Where:** `compositions/stats.html`
+**What's wrong:** You've got a hot pink title, a blue background that switches to white, and then "stickers" with blue, pink, lime, and yellow accents. It’s a color palette car crash. There is zero visual cohesion; it looks like a child found the "shapes" tool in PowerPoint and went to town.
+**Why it matters:** Instead of focusing on the data (the stats), the viewer is blinded by a random assortment of neon blobs. It screams "amateur" and "template."
+**Fix it:** Pick a primary brand color (the hot pink is fine) and use a consistent secondary palette. Ditch the lime and yellow unless they serve a specific functional purpose. Use a consistent "sticker" style instead of varying the border colors and background stacks for every single moment.
+
+### Typography Suffocation
+**Where:** `compositions/intro.html` and `compositions/stats.html`
+**What's wrong:** `Nunito Black` at 180px with a 5-degree tilt and multiple drop shadows? It’s heavy, dated, and lacks any elegance. The "layered offset shadow" (`filter: drop-shadow(8px 8px 0 #FFFFFF) drop-shadow(15px 15px 0 rgba(0,0,0,0.1))`) makes the text look muddy rather than deep.
+**Why it matters:** Heavy, tilted text is a 2015 YouTube thumbnail trope. It lacks the professional polish required for a tool called "Editor Agent."
+**Fix it:** Reduce the font weight or the size. If you must tilt it, keep the shadow clean—one sharp offset or a soft blur, not both. Consider a more modern, geometric sans-serif if you want to look like a "tech" tool.
+
+### The "Elastic" Overdose
+**Where:** `index.html` (A-roll) and `compositions/stats.html`
+**What's wrong:** Every single element enters with `elastic.out` or `back.out`. The A-roll bounces, the stats bounce, the intro bounces. It’s like watching a video inside a bouncy castle.
+**Why it matters:** When everything is "energetic," nothing is. The constant bouncing becomes a visual distraction that makes the content harder to digest. It feels robotic and "default GSAP."
+**Fix it:** Use `power2.out` or `expo.out` for most transitions. Reserve the elastic/back eases for the *most* important "pop" moments. Vary the rhythm.
+
+---
+
+## Design Improvements
+
+Things that aren't broken but are boring, lazy, or could be significantly better.
+
+### Caption Box Laziness
+**Where:** `compositions/captions.html`
+**The problem:** The captions are just white text on a pink rounded rectangle. It’s the most basic "social media caption" style possible.
+**Make it better:** Add some personality. Try a "karaoke" style where words highlight as they are spoken, or use a more interesting container than a simple rounded box. Maybe lose the box entirely and use a strong text stroke or a more dynamic background shape.
+
+### Static Background Transitions
+**Where:** `index.html` (Background Layer)
+**The problem:** The background just snaps from White to Blue to White. It’s jarring and lacks the "motion graphics" quality the video is literally bragging about.
+**Make it better:** Use a gradient transition, or better yet, an animated background pattern (subtle dots or lines) that moves with the A-roll. A flat color flip is lazy.
+
+---
+
+## What Actually Works
+
+### A-Roll Framing
+The way the A-roll container (`#aroll-container`) shifts scale and position to make room for the stats is actually a decent functional layout choice. It creates a clear "stage" for the supplemental information without completely hiding the speaker. The `16px` border and `60px` shadow on the video give it a nice "floating" UI feel that works well for a tech demo.
+
+---
+
+## Design Verdict
+
+**Visual Impact:** 4/10 - It grabs attention, but for the wrong reasons (visual noise).
+**Color & Typography:** 3/10 - A messy palette and "YouTube-thumbnail" typography.
+**Motion & Animation Feel:** 5/10 - Technically functional, but over-reliant on "bouncy" presets.
+**Overall Aesthetic:** 4/10 - Feels like a generic "viral video" template rather than a professional tool.
+
+**Bottom Line:** This design is trying to hide a lack of visual identity behind a wall of hot pink and elastic eases. It needs a serious "clean up" phase—simplify the colors, refine the type, and stop making everything bounce like a rubber ball.
diff --git a/packages/producer/tests/style-9-prod/src/index.html b/packages/producer/tests/style-9-prod/src/index.html
new file mode 100644
index 0000000000..e70dc11925
--- /dev/null
+++ b/packages/producer/tests/style-9-prod/src/index.html
@@ -0,0 +1,173 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Editor Agent - Play Mode</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <style>
+ body, html {
+ margin: 0;
+ padding: 0;
+ width: 1920px;
+ height: 1080px;
+ overflow: hidden;
+ background-color: #FFFFFF;
+ font-family: 'Nunito', sans-serif;
+ }
+
+ #main-composition {
+ width: 1920px;
+ height: 1080px;
+ position: relative;
+ }
+
+ #bg-comp,
+ #aroll-comp,
+ #intro-comp,
+ #stats-comp,
+ #captions-comp {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ }
+
+ #bg-comp {
+ z-index: 1;
+ }
+
+ #aroll-comp {
+ z-index: 10;
+ }
+
+ #intro-comp {
+ z-index: 100;
+ }
+
+ #stats-comp {
+ z-index: 150;
+ }
+
+ #captions-comp {
+ z-index: 200;
+ }
+
+ #aroll-container {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ z-index: 0;
+ }
+
+ #short_mag_cut {
+ border-radius: 16px;
+ box-shadow: 0 20px 60px rgba(0,0,0,0.4);
+ border: 8px solid #FFFFFF;
+ }
+
+ #background-layer {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-color: #FFFFFF;
+ z-index: 0;
+ }
+ </style>
+ <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@900&display=swap" rel="stylesheet">
+</head>
+<body>
+ <div id="main-composition" data-composition-id="main-video" data-start="0" data-duration="16.04" data-width="1920" data-height="1080">
+ <!-- Background Layer Composition -->
+ <div id="bg-comp" data-composition-id="background" data-start="0" data-duration="16.04" data-width="1920" data-height="1080" data-track-index="1">
+ <div id="background-layer"></div>
+ <style>
+ #background-layer {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-color: #FFFFFF;
+ }
+ </style>
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const bg = document.getElementById('background-layer');
+ // Sync with A-roll framing 3 (4.659s)
+ tl.to(bg, { backgroundColor: "#0057FF", duration: 0.5 }, 4.659);
+ // Sync with A-roll framing 4 (8.88s)
+ tl.to(bg, { backgroundColor: "#FFFFFF", duration: 0.5 }, 8.88);
+ window.__timelines["background"] = tl;
+ })();
+ </script>
+ </div>
+
+ <!-- A-roll Layer Composition -->
+ <div id="aroll-comp" data-composition-id="aroll-layer" data-start="0" data-duration="16.04" data-width="1920" data-height="1080" data-track-index="10">
+ <div id="aroll-container">
+ <video id="short_mag_cut"
+ src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/e5d69fa9_6c6509753f4643cd9bef0b1dc9e1e001.mp4"
+ data-start="0"
+ data-duration="16.04"
+ data-track-index="1"
+ style="width: 100%; height: auto;"></video>
+ </div>
+ <style>
+ #aroll-container {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ }
+ #short_mag_cut {
+ border-radius: 16px;
+ box-shadow: 0 20px 60px rgba(0,0,0,0.4);
+ border: 8px solid #FFFFFF;
+ }
+ </style>
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+ const container = document.getElementById('aroll-container');
+ gsap.set(container, { y: -1100, scale: 0.8 });
+ tl.to(container, { y: 0, duration: 1.2, ease: "elastic.out(1, 0.6)" }, 0);
+ tl.to(container, { scale: 1.4, x: -300, duration: 1, ease: "back.out(1.7)" }, 1.839);
+ tl.to(container, { scale: 0.7, x: 400, duration: 1, ease: "back.out(1.7)" }, 4.659);
+ tl.to(container, { scale: 0.9, x: 0, duration: 1, ease: "back.out(1.7)" }, 8.88);
+ window.__timelines["aroll-layer"] = tl;
+ })();
+ </script>
+ </div>
+
+ <!-- Compositions -->
+ <div id="intro-comp" data-composition-id="intro" data-composition-src="compositions/intro.html" data-start="0" data-duration="16.04" data-width="1920" data-height="1080" data-track-index="100"></div>
+ <div id="captions-comp" data-composition-id="captions" data-composition-src="compositions/captions.html" data-start="0" data-duration="16.04" data-width="1920" data-height="1080" data-track-index="200"></div>
+ <div id="stats-comp" data-composition-id="stats" data-composition-src="compositions/stats.html" data-start="0" data-duration="16.04" data-width="1920" data-height="1080" data-track-index="150"></div>
+
+ <!-- Audio Clips -->
+ <audio id="sfx-bounce-0" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/4ea1246d_d3e9e87e46be4104817dcd75d0adcef0.mp3" data-start="0" data-track-index="5"></audio>
+ <audio id="sfx-whoosh-1" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52dc4e22_72f17e2dfc9f40c08f4a5cc82f53db61.mp3" data-start="1.839" data-track-index="6"></audio>
+ <audio id="sfx-pop-1" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/7ae8806d_d8eacbb4b2ab4a77af89be7208c0c918.mp3" data-start="2.039" data-track-index="7"></audio>
+ <audio id="sfx-whoosh-2" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52dc4e22_72f17e2dfc9f40c08f4a5cc82f53db61.mp3" data-start="4.659" data-track-index="6"></audio>
+ <audio id="sfx-pop-2" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/7ae8806d_d8eacbb4b2ab4a77af89be7208c0c918.mp3" data-start="4.859" data-track-index="7"></audio>
+ <audio id="sfx-whoosh-3" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/52dc4e22_72f17e2dfc9f40c08f4a5cc82f53db61.mp3" data-start="8.88" data-track-index="6"></audio>
+ <audio id="sfx-pop-3" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/generated_assets/7ae8806d_d8eacbb4b2ab4a77af89be7208c0c918.mp3" data-start="9.08" data-track-index="7"></audio>
+
+ <script>
+ window.__timelines = window.__timelines || {};
+ const tl = gsap.timeline({ paused: true });
+ window.__timelines["main-video"] = tl;
+ </script>
+ </div>
+</body>
+</html>
\ No newline at end of file
diff --git a/packages/producer/tests/vignelli-stacking/meta.json b/packages/producer/tests/vignelli-stacking/meta.json
new file mode 100644
index 0000000000..bfdd4074ec
--- /dev/null
+++ b/packages/producer/tests/vignelli-stacking/meta.json
@@ -0,0 +1,15 @@
+{
+ "name": "Vignelli Video Stacking",
+ "description": "Tests that producer video frame swapping preserves authored stacking so overlays and captions stay above the a-roll video.",
+ "tags": ["video", "captions", "stacking", "z-index", "animations"],
+
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+
+ "minAudioCorrelation": 0.9,
+ "maxAudioLagWindows": 120,
+
+ "renderConfig": {
+ "fps": 30
+ }
+}
diff --git a/packages/producer/tests/vignelli-stacking/src/compositions/captions.html b/packages/producer/tests/vignelli-stacking/src/compositions/captions.html
new file mode 100644
index 0000000000..0739f2b78d
--- /dev/null
+++ b/packages/producer/tests/vignelli-stacking/src/compositions/captions.html
@@ -0,0 +1,114 @@
+<template id="captions-template">
+ <div data-composition-id="captions" data-width="1080" data-height="1920" data-duration="10.24">
+ <div id="captions-container"></div>
+
+ <style>
+ [data-composition-id="captions"] {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ background-color: transparent;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ text-transform: uppercase;
+ overflow: hidden;
+ }
+
+ [data-composition-id="captions"] .caption-group {
+ position: absolute;
+ top: 1528px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 900px;
+ background-color: #FFFFFF;
+ color: #000000;
+ padding: 60px;
+ border-top: 8px solid #CC0000;
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ align-items: center;
+ opacity: 0;
+ box-sizing: border-box;
+ }
+
+ [data-composition-id="captions"] .word {
+ font-weight: 700;
+ font-size: 72px;
+ letter-spacing: -0.02em;
+ margin: 0 10px;
+ display: inline-block;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const TRANSCRIPT = [
+ { text: 'Hola,', start: 1.22, end: 1.879 },
+ { text: 'esto', start: 1.919, end: 2.119 },
+ { text: 'es', start: 2.139, end: 2.199 },
+ { text: 'una', start: 2.24, end: 2.46 },
+ { text: 'prueba.', start: 2.46, end: 4.239 },
+ { text: 'Yo', start: 4.279, end: 4.619 },
+ { text: 'quiero', start: 4.679, end: 4.979 },
+ { text: 'definitivamente', start: 5.0, end: 6.539 },
+ { text: 'poder', start: 6.559, end: 6.879 },
+ { text: 'grabar', start: 6.899, end: 7.279 },
+ { text: 'contenido,', start: 7.299, end: 8.099 },
+ { text: 'pero', start: 8.119, end: 8.3 },
+ { text: 'ser', start: 8.399, end: 8.519 },
+ { text: 'yo', start: 8.6, end: 8.74 },
+ { text: 'misma', start: 8.76, end: 9.14 },
+ { text: 'también', start: 9.159, end: 10.26 }
+ ];
+
+ const container = document.getElementById('captions-container');
+ const tl = gsap.timeline({ paused: true });
+ const chunks = [];
+ let currentChunk = [];
+
+ TRANSCRIPT.forEach((word, index) => {
+ currentChunk.push(word);
+ if (currentChunk.length >= 3 || index === TRANSCRIPT.length - 1) {
+ chunks.push([...currentChunk]);
+ currentChunk = [];
+ }
+ });
+
+ chunks.forEach((chunk, i) => {
+ const group = document.createElement('div');
+ group.className = 'caption-group';
+ group.id = `group-${i}`;
+
+ chunk.forEach((wordData) => {
+ const span = document.createElement('span');
+ span.className = 'word';
+ span.textContent = wordData.text;
+ group.appendChild(span);
+ });
+
+ container.appendChild(group);
+
+ const startTime = chunk[0].start;
+ const endTime = chunk[chunk.length - 1].end;
+
+ tl.fromTo(
+ group,
+ { opacity: 0, y: 20 },
+ { opacity: 1, y: 0, duration: 0.3, ease: "power2.out" },
+ startTime
+ );
+
+ tl.to(
+ group,
+ { opacity: 0, y: -10, duration: 0.2, ease: "power2.in" },
+ endTime
+ );
+ });
+
+ window.__timelines["captions"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/vignelli-stacking/src/compositions/overlays.html b/packages/producer/tests/vignelli-stacking/src/compositions/overlays.html
new file mode 100644
index 0000000000..134dff433a
--- /dev/null
+++ b/packages/producer/tests/vignelli-stacking/src/compositions/overlays.html
@@ -0,0 +1,172 @@
+<template id="overlays-template">
+ <div data-composition-id="overlays" data-width="1080" data-height="1920" data-duration="10.24">
+ <div id="graphic-1" class="vignelli-container">
+ <div class="white-box">
+ <div class="text-black">PRUEBA</div>
+ </div>
+ </div>
+
+ <div id="graphic-2" class="vignelli-container">
+ <div class="white-box">
+ <div class="text-black">GRABAR<br>CONTENIDO</div>
+ </div>
+ </div>
+
+ <div id="graphic-3" class="vignelli-full">
+ <div class="charcoal-bg"></div>
+ <div class="full-content">
+ <div class="text-white">SER YO<br>MISMA</div>
+ </div>
+ </div>
+
+ <style>
+ [data-composition-id="overlays"] {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1080px;
+ height: 1920px;
+ font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ overflow: hidden;
+ }
+
+ .vignelli-container {
+ position: absolute;
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ padding-left: 100px;
+ opacity: 0;
+ pointer-events: none;
+ }
+
+ .white-box {
+ background-color: #FFFFFF;
+ padding: 40px 60px;
+ border-left: 30px solid #CC0000;
+ position: relative;
+ }
+
+ .text-black {
+ color: #1A1A1A;
+ font-size: 100px;
+ font-weight: 900;
+ line-height: 0.9;
+ text-transform: uppercase;
+ }
+
+ #graphic-1 {
+ top: 200px;
+ }
+
+ #graphic-1 .text-black {
+ font-size: 140px;
+ }
+
+ #graphic-2 {
+ top: 1150px;
+ }
+
+ .vignelli-full {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: flex-start;
+ align-items: center;
+ padding-left: 100px;
+ pointer-events: none;
+ }
+
+ .charcoal-bg {
+ position: absolute;
+ top: 0;
+ left: 100%;
+ width: 100%;
+ height: 100%;
+ background-color: #1A1A1A;
+ }
+
+ .full-content {
+ position: relative;
+ z-index: 2;
+ opacity: 0;
+ text-align: left;
+ border-left: 30px solid #CC0000;
+ padding-left: 60px;
+ }
+
+ .full-content .text-white {
+ color: #FFFFFF;
+ font-size: 180px;
+ font-weight: 900;
+ line-height: 0.85;
+ text-transform: uppercase;
+ }
+ </style>
+
+ <script>
+ (function() {
+ const tl = gsap.timeline({ paused: true });
+
+ const G1_IN = 1.22;
+ const G1_OUT = 4.23;
+ const G2_IN = 4.67;
+ const G2_OUT = 8.09;
+ const G3_IN = 8.3;
+ const G3_OUT = 10.24;
+
+ tl.fromTo(
+ '#graphic-1',
+ { opacity: 0, x: -100 },
+ { opacity: 1, x: 0, duration: 0.8, ease: "power3.out" },
+ G1_IN
+ );
+
+ tl.to(
+ '#graphic-1',
+ { opacity: 0, x: 100, duration: 0.4, ease: "power3.in" },
+ G1_OUT - 0.4
+ );
+
+ tl.fromTo(
+ '#graphic-2',
+ { opacity: 0, x: -100 },
+ { opacity: 1, x: 0, duration: 0.8, ease: "power3.out" },
+ G2_IN
+ );
+
+ tl.to(
+ '#graphic-2',
+ { opacity: 0, x: 100, duration: 0.4, ease: "power3.in" },
+ G2_OUT - 0.4
+ );
+
+ tl.to(
+ '.charcoal-bg',
+ { left: 0, duration: 0.8, ease: "power3.inOut" },
+ G3_IN
+ );
+
+ tl.fromTo(
+ '.full-content',
+ { opacity: 0, x: -50 },
+ { opacity: 1, x: 0, duration: 0.8, ease: "back.out(1.2)" },
+ G3_IN + 0.4
+ );
+
+ tl.to(
+ '#graphic-3',
+ { opacity: 0, duration: 0.24 },
+ G3_OUT - 0.24
+ );
+
+ window.__timelines = window.__timelines || {};
+ window.__timelines["overlays"] = tl;
+ })();
+ </script>
+ </div>
+</template>
diff --git a/packages/producer/tests/vignelli-stacking/src/index.html b/packages/producer/tests/vignelli-stacking/src/index.html
new file mode 100644
index 0000000000..900c224f58
--- /dev/null
+++ b/packages/producer/tests/vignelli-stacking/src/index.html
@@ -0,0 +1,74 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Vignelli Style Video</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
+ <script src=""></script>
+ <style>
+ body {
+ margin: 0;
+ padding: 0;
+ background: #FFFFFF;
+ overflow: hidden;
+ font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ }
+
+ #main-composition {
+ position: relative;
+ width: 1080px;
+ height: 1920px;
+ background: #FFFFFF;
+ }
+
+ #a-roll-wrapper {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ z-index: 1;
+ overflow: hidden;
+ }
+
+ video {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+
+ [data-composition-id="overlays"] {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 2;
+ }
+
+ [data-composition-id="captions"] {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 3;
+ }
+ </style>
+</head>
+<body>
+ <div id="main-composition" data-composition-id="main-comp" data-width="1080" data-height="1920" data-duration="10.24">
+ <div id="a-roll-wrapper">
+ <video id="a-roll" src="https://gen-os-static.s3.us-east-2.amazonaws.com/astral_assets/uploaded_assets/f140a7f9_c8ae0ae2698f4a6895110bb9cbaadd74.mp4" data-start="0" data-duration="10.24" data-track-index="0">
+ </video>
+ </div>
+
+ <div id="overlays-comp" data-composition-src="compositions/overlays.html" data-composition-id="overlays" data-start="0" data-duration="10.24" data-track-index="2" data-width="1080" data-height="1920">
+ </div>
+
+ <div id="captions-comp" data-composition-src="compositions/captions.html" data-composition-id="captions" data-start="0" data-duration="10.24" data-track-index="3" data-width="1080" data-height="1920">
+ </div>
+ </div>
+
+<script>
+ const tl = gsap.timeline({ paused: true });
+ window.__timelines = window.__timelines || {};
+ window.__timelines["main-comp"] = tl;
+</script>
+</body>
+</html>
diff --git a/packages/producer/tsconfig.json b/packages/producer/tsconfig.json
new file mode 100644
index 0000000000..d672cb2b7c
--- /dev/null
+++ b/packages/producer/tsconfig.json
@@ -0,0 +1,18 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "esModuleInterop": true,
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "skipLibCheck": true,
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/packages/studio/index.html b/packages/studio/index.html
new file mode 100644
index 0000000000..3496b68ab1
--- /dev/null
+++ b/packages/studio/index.html
@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>HyperFrames Studio</title>
+</head>
+<body>
+ <div id="root"></div>
+ <script type="module" src="/src/main.tsx"></script>
+</body>
+</html>
diff --git a/packages/studio/package.json b/packages/studio/package.json
new file mode 100644
index 0000000000..5e23b0cf41
--- /dev/null
+++ b/packages/studio/package.json
@@ -0,0 +1,50 @@
+{
+ "name": "@hyperframes/studio",
+ "version": "0.1.0",
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts",
+ "./tailwind-preset": "./src/styles/tailwind-preset.ts"
+ },
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "files": [
+ "src",
+ "dist"
+ ],
+ "scripts": {
+ "dev": "vite",
+ "build": "vite build",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@hyperframes/core": "workspace:*",
+ "@codemirror/autocomplete": "^6.20.1",
+ "@codemirror/commands": "^6.10.3",
+ "@codemirror/lang-css": "^6.3.1",
+ "@codemirror/lang-html": "^6.4.9",
+ "@codemirror/lang-javascript": "^6.2.2",
+ "@codemirror/language": "^6.12.2",
+ "@codemirror/search": "^6.6.0",
+ "@codemirror/state": "^6.6.0",
+ "@codemirror/theme-one-dark": "^6.1.2",
+ "@codemirror/view": "^6.40.0",
+ "@phosphor-icons/react": "^2.1.10",
+ "codemirror": "^6.0.1"
+ },
+ "peerDependencies": {
+ "react": "^18.0.0 || ^19.0.0",
+ "react-dom": "^18.0.0 || ^19.0.0",
+ "zustand": "^4.0.0 || ^5.0.0"
+ },
+ "devDependencies": {
+ "@types/react": "^19.0.0",
+ "@types/react-dom": "^19.0.0",
+ "@vitejs/plugin-react": "^4.0.0",
+ "autoprefixer": "^10.4.0",
+ "postcss": "^8.4.0",
+ "tailwindcss": "^3.4.0",
+ "typescript": "^5.0.0",
+ "vite": "^5.0.0"
+ }
+}
diff --git a/packages/studio/postcss.config.js b/packages/studio/postcss.config.js
new file mode 100644
index 0000000000..2aa7205d4b
--- /dev/null
+++ b/packages/studio/postcss.config.js
@@ -0,0 +1,6 @@
+export default {
+ plugins: {
+ tailwindcss: {},
+ autoprefixer: {},
+ },
+};
diff --git a/packages/studio/public/icons/timeline/audio.svg b/packages/studio/public/icons/timeline/audio.svg
new file mode 100644
index 0000000000..0a5ce98a3a
--- /dev/null
+++ b/packages/studio/public/icons/timeline/audio.svg
@@ -0,0 +1,7 @@
+<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M6.875 2.5C6.875 2.15482 7.15482 1.875 7.5 1.875C7.84518 1.875 8.125 2.15482 8.125 2.5V12.5C8.125 12.8452 7.84518 13.125 7.5 13.125C7.15482 13.125 6.875 12.8452 6.875 12.5V2.5Z" fill="#512000"/>
+<path d="M4.0625 3.75C4.0625 3.40482 4.34232 3.125 4.6875 3.125C5.03268 3.125 5.3125 3.40482 5.3125 3.75V10C5.3125 10.3452 5.03268 10.625 4.6875 10.625C4.34232 10.625 4.0625 10.3452 4.0625 10V3.75Z" fill="#512000"/>
+<path d="M1.875 4.375C1.52982 4.375 1.25 4.65482 1.25 5V7.5C1.25 7.84518 1.52982 8.125 1.875 8.125C2.22018 8.125 2.5 7.84518 2.5 7.5V5C2.5 4.65482 2.22018 4.375 1.875 4.375Z" fill="#512000"/>
+<path d="M10.9375 11.25C10.9375 11.5952 10.6577 11.875 10.3125 11.875C9.96732 11.875 9.6875 11.5952 9.6875 11.25L9.6875 5C9.6875 4.65482 9.96732 4.375 10.3125 4.375C10.6577 4.375 10.9375 4.65482 10.9375 5L10.9375 11.25Z" fill="#512000"/>
+<path d="M13.125 10.625C13.4702 10.625 13.75 10.3452 13.75 10V7.5C13.75 7.15482 13.4702 6.875 13.125 6.875C12.7798 6.875 12.5 7.15482 12.5 7.5V10C12.5 10.3452 12.7798 10.625 13.125 10.625Z" fill="#512000"/>
+</svg>
diff --git a/packages/studio/public/icons/timeline/captions.svg b/packages/studio/public/icons/timeline/captions.svg
new file mode 100644
index 0000000000..978923a2e9
--- /dev/null
+++ b/packages/studio/public/icons/timeline/captions.svg
@@ -0,0 +1,5 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M6.86328 11.9695C6.86328 11.5153 6.96513 11.1112 7.16883 10.7574C7.37253 10.3993 7.65545 10.1219 8.01758 9.9254C8.38424 9.72448 8.79843 9.62402 9.26014 9.62402C9.82597 9.62402 10.3104 9.76816 10.7132 10.0564C11.0567 10.3022 11.3031 10.6241 11.4524 11.0222C11.4923 11.1285 11.4066 11.2357 11.2894 11.2357H10.3574C10.2886 11.2357 10.2269 11.1969 10.1916 11.1398C10.1013 10.9942 9.98321 10.8798 9.83729 10.7968C9.66528 10.6963 9.46837 10.6461 9.24656 10.6461C8.88896 10.6461 8.59925 10.7662 8.37745 11.0064C8.15564 11.2466 8.04474 11.5677 8.04474 11.9695C8.04474 12.3714 8.15564 12.6924 8.37745 12.9326C8.59925 13.1728 8.88896 13.293 9.24656 13.293C9.46837 13.293 9.66528 13.2427 9.83729 13.1423C9.98321 13.0592 10.1013 12.9449 10.1916 12.7992C10.2269 12.7422 10.2886 12.7033 10.3574 12.7033H11.2894C11.4066 12.7033 11.4923 12.8105 11.4524 12.9168C11.3031 13.3149 11.0567 13.6369 10.7132 13.8826C10.3104 14.1665 9.82597 14.3085 9.26014 14.3085C8.79843 14.3085 8.38424 14.2102 8.01758 14.0137C7.65545 13.8127 7.37253 13.5354 7.16883 13.1816C6.96513 12.8278 6.86328 12.4238 6.86328 11.9695Z" fill="black"/>
+<path d="M12.0352 11.9695C12.0352 11.5153 12.137 11.1112 12.3407 10.7574C12.5444 10.3993 12.8273 10.1219 13.1895 9.9254C13.5561 9.72448 13.9703 9.62402 14.432 9.62402C14.9979 9.62402 15.4822 9.76816 15.8851 10.0564C16.2285 10.3022 16.4749 10.6241 16.6243 11.0222C16.6641 11.1285 16.5784 11.2357 16.4613 11.2357H15.5293C15.4604 11.2357 15.3987 11.1969 15.3634 11.1398C15.2732 10.9942 15.1551 10.8798 15.0092 10.7968C14.8372 10.6963 14.6402 10.6461 14.4184 10.6461C14.0608 10.6461 13.7711 10.7662 13.5493 11.0064C13.3275 11.2466 13.2166 11.5677 13.2166 11.9695C13.2166 12.3714 13.3275 12.6924 13.5493 12.9326C13.7711 13.1728 14.0608 13.293 14.4184 13.293C14.6402 13.293 14.8372 13.2427 15.0092 13.1423C15.1551 13.0592 15.2732 12.9449 15.3634 12.7992C15.3987 12.7422 15.4604 12.7033 15.5293 12.7033H16.4613C16.5784 12.7033 16.6641 12.8105 16.6243 12.9168C16.4749 13.3149 16.2285 13.6369 15.8851 13.8826C15.4822 14.1665 14.9979 14.3085 14.432 14.3085C13.9703 14.3085 13.5561 14.2102 13.1895 14.0137C12.8273 13.8127 12.5444 13.5354 12.3407 13.1816C12.137 12.8278 12.0352 12.4238 12.0352 11.9695Z" fill="black"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M4.1377 9.10331C4.1377 7.94458 4.1377 7.36522 4.3714 6.92264C4.57697 6.53334 4.90499 6.21683 5.30845 6.01847C5.76712 5.79297 6.36755 5.79297 7.56842 5.79297H16.4311C17.632 5.79297 18.2324 5.79297 18.6911 6.01847C19.0945 6.21683 19.4226 6.53334 19.6281 6.92264C19.8618 7.36522 19.8618 7.94458 19.8618 9.10331V14.8964C19.8618 16.0551 19.8618 16.6345 19.6281 17.0771C19.4226 17.4664 19.0945 17.7829 18.6911 17.9813C18.2324 18.2068 17.632 18.2068 16.4311 18.2068H7.56842C6.36755 18.2068 5.76712 18.2068 5.30845 17.9813C4.90499 17.7829 4.57697 17.4664 4.3714 17.0771C4.1377 16.6345 4.1377 16.0551 4.1377 14.8964V9.10331ZM7.56842 7.17228H16.4311C17.0551 7.17228 17.4372 7.17335 17.723 7.19589C17.8562 7.20638 17.9367 7.21957 17.9857 7.23069C18.0089 7.23598 18.0232 7.24041 18.031 7.24307C18.0384 7.24563 18.0421 7.24745 18.0421 7.24745C18.1766 7.31357 18.2859 7.41907 18.3545 7.54884C18.3545 7.54884 18.3563 7.5524 18.359 7.55957C18.3618 7.56704 18.3664 7.58086 18.3718 7.60331C18.3834 7.65052 18.397 7.72826 18.4079 7.85674C18.4313 8.13255 18.4324 8.50119 18.4324 9.10331V14.8964C18.4324 15.4985 18.4313 15.8672 18.4079 16.143C18.397 16.2715 18.3834 16.3492 18.3718 16.3964C18.3664 16.4189 18.3618 16.4327 18.359 16.4402C18.3563 16.4473 18.3545 16.4509 18.3545 16.4509C18.2859 16.5807 18.1766 16.6862 18.0421 16.7523L18.0396 16.7534C18.0396 16.7534 18.035 16.7553 18.031 16.7567C18.0232 16.7593 18.0089 16.7638 17.9857 16.769C17.9367 16.7802 17.8562 16.7933 17.723 16.8038C17.4372 16.8264 17.0551 16.8275 16.4311 16.8275H7.56842C6.9444 16.8275 6.56234 16.8264 6.2765 16.8038C6.14335 16.7933 6.06279 16.7802 6.01386 16.769C5.99059 16.7638 5.97628 16.7593 5.96854 16.7567C5.96111 16.7541 5.95741 16.7523 5.95741 16.7523C5.82293 16.6862 5.71359 16.5807 5.64506 16.4509C5.64506 16.4509 5.64318 16.4473 5.64053 16.4402C5.63777 16.4327 5.63317 16.4189 5.62769 16.3964C5.61617 16.3492 5.60251 16.2715 5.59163 16.143C5.56827 15.8672 5.56716 15.4985 5.56716 14.8964V9.10331C5.56716 8.50119 5.56827 8.13255 5.59163 7.85674C5.60251 7.72826 5.61617 7.65052 5.62769 7.60331C5.63317 7.58086 5.63777 7.56704 5.64053 7.55957C5.64318 7.5524 5.64506 7.54884 5.64506 7.54884C5.71359 7.41907 5.82293 7.31357 5.95741 7.24745C5.95741 7.24745 5.96111 7.24563 5.96854 7.24307C5.97628 7.24041 5.99059 7.23598 6.01386 7.23069C6.06279 7.21957 6.14335 7.20638 6.2765 7.19589C6.56234 7.17335 6.9444 7.17228 7.56842 7.17228Z" fill="black"/>
+</svg>
diff --git a/packages/studio/public/icons/timeline/composition.svg b/packages/studio/public/icons/timeline/composition.svg
new file mode 100644
index 0000000000..bdb54dc89a
--- /dev/null
+++ b/packages/studio/public/icons/timeline/composition.svg
@@ -0,0 +1,12 @@
+<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M1.39176 5.03406C1.45724 5 1.54296 5 1.71441 5H1.9593C2.13075 5 2.21647 5 2.28195 5.03406C2.33955 5.06402 2.38638 5.11183 2.41573 5.17063C2.4491 5.23748 2.4491 5.32498 2.4491 5.5V6.375C2.4491 6.55002 2.4491 6.63752 2.41573 6.70437C2.38638 6.76317 2.33955 6.81098 2.28195 6.84094C2.21647 6.875 2.13075 6.875 1.9593 6.875H1.71441C1.54296 6.875 1.45724 6.875 1.39176 6.84094C1.33415 6.81098 1.28732 6.76317 1.25797 6.70437C1.22461 6.63752 1.22461 6.55002 1.22461 6.375V5.5C1.22461 5.32498 1.22461 5.23748 1.25797 5.17063C1.28732 5.11183 1.33415 5.06402 1.39176 5.03406Z" fill="#1A2B03"/>
+<path d="M2.28055 3.71808C2.21679 3.75 2.13249 3.75 1.96389 3.75H1.71886C1.54551 3.75 1.45884 3.75 1.39194 3.71408C1.33446 3.68323 1.28533 3.63086 1.2576 3.57091C1.22533 3.50114 1.22892 3.41627 1.23608 3.24653C1.25437 2.81345 1.3018 2.52021 1.4248 2.27377C1.6009 1.92096 1.88188 1.63413 2.22748 1.45436C2.46889 1.32879 2.75615 1.28038 3.18039 1.26171C3.34666 1.2544 3.4298 1.25074 3.49816 1.28368C3.55688 1.31198 3.60818 1.36214 3.63841 1.42081C3.67359 1.48911 3.67359 1.57759 3.67359 1.75454V2.00468C3.67359 2.1768 3.67359 2.26285 3.64232 2.32794C3.61399 2.38692 3.57237 2.43164 3.51612 2.46354C3.45404 2.49874 3.36517 2.50339 3.18743 2.51268C3.14116 2.51509 3.09778 2.51797 3.05673 2.52139C2.94267 2.53091 2.87366 2.54286 2.83175 2.55293C2.81182 2.55772 2.79955 2.56174 2.79292 2.56416C2.78655 2.56648 2.78339 2.56812 2.78339 2.56812C2.66819 2.62804 2.57453 2.72365 2.51583 2.84126C2.51583 2.84126 2.51422 2.84449 2.51195 2.85099C2.50958 2.85775 2.50565 2.87027 2.50095 2.89062C2.49108 2.93341 2.47938 3.00385 2.47006 3.12029C2.4667 3.16219 2.46388 3.20646 2.46152 3.25369C2.45242 3.43514 2.44787 3.52587 2.41339 3.58925C2.38214 3.64667 2.33833 3.68916 2.28055 3.71808Z" fill="#1A2B03"/>
+<path d="M5.06522 1.28406C5.13071 1.25 5.21643 1.25 5.38788 1.25H5.63277C5.80422 1.25 5.88994 1.25 5.95542 1.28406C6.01302 1.31402 6.05985 1.36183 6.0892 1.42063C6.12257 1.48748 6.12257 1.57498 6.12257 1.75L6.12257 2C6.12257 2.17502 6.12257 2.26252 6.0892 2.32937C6.05985 2.38817 6.01302 2.43598 5.95542 2.46594C5.88994 2.5 5.80422 2.5 5.63277 2.5L5.38788 2.5C5.21643 2.5 5.13071 2.5 5.06522 2.46594C5.00762 2.43598 4.96079 2.38817 4.93144 2.32937C4.89808 2.26252 4.89808 2.17502 4.89808 2L4.89808 1.75C4.89808 1.57498 4.89808 1.48748 4.93144 1.42063C4.96079 1.36183 5.00762 1.31402 5.06522 1.28406Z" fill="#1A2B03"/>
+<path d="M13.4361 8.92063C13.4695 8.98747 13.4695 9.07498 13.4695 9.25V9.5C13.4695 9.67502 13.4695 9.76252 13.4361 9.82937C13.4068 9.88817 13.36 9.93598 13.3024 9.96594C13.2369 10 13.1512 10 12.9797 10H12.7348C12.5634 10 12.4776 10 12.4122 9.96594C12.3546 9.93598 12.3077 9.88817 12.2784 9.82937C12.245 9.76252 12.245 9.67502 12.245 9.5V9.25C12.245 9.07498 12.245 8.98747 12.2784 8.92063C12.3077 8.86183 12.3546 8.81402 12.4122 8.78406C12.4776 8.75 12.5634 8.75 12.7348 8.75H12.9797C13.1512 8.75 13.2369 8.75 13.3024 8.78406C13.36 8.81402 13.4068 8.86183 13.4361 8.92063Z" fill="#1A2B03"/>
+<path d="M13.4365 11.4291C13.4688 11.4989 13.4652 11.5837 13.458 11.7535C13.4397 12.1866 13.3923 12.4798 13.2693 12.7262C13.0932 13.079 12.8122 13.3659 12.4666 13.5456C12.2252 13.6712 11.938 13.7196 11.5137 13.7383C11.3475 13.7456 11.2643 13.7493 11.196 13.7163C11.1372 13.688 11.0859 13.6379 11.0557 13.5792C11.0205 13.5109 11.0205 13.4224 11.0205 13.2455V12.9953C11.0205 12.8232 11.0205 12.7371 11.0518 12.6721C11.0801 12.6131 11.1217 12.5684 11.178 12.5365C11.2401 12.5013 11.329 12.4966 11.5067 12.4873C11.553 12.4849 11.5963 12.482 11.6374 12.4786C11.7514 12.4691 11.8205 12.4571 11.8624 12.4471C11.8823 12.4423 11.8946 12.4383 11.9012 12.4358C11.9076 12.4335 11.9107 12.4319 11.9107 12.4319C12.0259 12.372 12.1196 12.2763 12.1783 12.1587C12.1783 12.1587 12.1787 12.1579 12.1792 12.1568C12.1798 12.1553 12.1808 12.1528 12.1822 12.149C12.1845 12.1422 12.1885 12.1297 12.1932 12.1094C12.203 12.0666 12.2147 11.9961 12.2241 11.8797C12.2274 11.8378 12.2302 11.7935 12.2326 11.7463C12.2417 11.5649 12.2462 11.4741 12.2807 11.4108C12.312 11.3533 12.3558 11.3108 12.4136 11.2819C12.4773 11.25 12.5616 11.25 12.7302 11.25H12.9753C13.1486 11.25 13.2353 11.25 13.3022 11.2859C13.3597 11.3168 13.4088 11.3691 13.4365 11.4291Z" fill="#1A2B03"/>
+<path d="M9.62889 13.7159C9.56341 13.75 9.47769 13.75 9.30624 13.75H8.4491C8.27766 13.75 8.19193 13.75 8.12645 13.7159C8.06885 13.686 8.02202 13.6382 7.99267 13.5794C7.9593 13.5125 7.9593 13.425 7.9593 13.25V13C7.9593 12.825 7.9593 12.7375 7.99267 12.6706C8.02202 12.6118 8.06885 12.564 8.12645 12.5341C8.19193 12.5 8.27766 12.5 8.4491 12.5H9.30624C9.47769 12.5 9.56341 12.5 9.62889 12.5341C9.68649 12.564 9.73333 12.6118 9.76267 12.6706C9.79604 12.7375 9.79604 12.825 9.79604 13V13.25C9.79604 13.425 9.79604 13.5125 9.76267 13.5794C9.73333 13.6382 9.68649 13.686 9.62889 13.7159Z" fill="#1A2B03"/>
+<path d="M6.56767 13.7159C6.50219 13.75 6.41646 13.75 6.24502 13.75H5.38788C5.21643 13.75 5.13071 13.75 5.06523 13.7159C5.00762 13.686 4.96079 13.6382 4.93144 13.5794C4.89808 13.5125 4.89808 13.425 4.89808 13.25V13C4.89808 12.825 4.89808 12.7375 4.93144 12.6706C4.96079 12.6118 5.00762 12.564 5.06523 12.5341C5.13071 12.5 5.21643 12.5 5.38788 12.5H6.24502C6.41646 12.5 6.50219 12.5 6.56767 12.5341C6.62527 12.564 6.6721 12.6118 6.70145 12.6706C6.73481 12.7375 6.73481 12.825 6.73481 13V13.25C6.73481 13.425 6.73481 13.5125 6.70145 13.5794C6.6721 13.6382 6.62527 13.686 6.56767 13.7159Z" fill="#1A2B03"/>
+<path d="M3.49816 13.7163C3.4298 13.7493 3.34667 13.7456 3.18039 13.7383C2.75615 13.7196 2.46889 13.6712 2.22748 13.5456C1.88188 13.3659 1.6009 13.079 1.4248 12.7262C1.3018 12.4798 1.25437 12.1866 1.23608 11.7535C1.22892 11.5837 1.22533 11.4989 1.2576 11.4291C1.28533 11.3691 1.33446 11.3168 1.39194 11.2859C1.45884 11.25 1.54551 11.25 1.71886 11.25H1.96389C2.13249 11.25 2.21679 11.25 2.28055 11.2819C2.33833 11.3108 2.38214 11.3533 2.41339 11.4108C2.44787 11.4741 2.45242 11.5649 2.46152 11.7463C2.46389 11.7935 2.4667 11.8378 2.47006 11.8797C2.47938 11.9961 2.49108 12.0666 2.50095 12.1094C2.50565 12.1297 2.50958 12.1422 2.51195 12.149C2.51422 12.1555 2.51583 12.1587 2.51583 12.1587C2.57453 12.2763 2.66819 12.372 2.78339 12.4319C2.78339 12.4319 2.78655 12.4335 2.79292 12.4358C2.79955 12.4383 2.81182 12.4423 2.83175 12.4471C2.87366 12.4571 2.94267 12.4691 3.05673 12.4786C3.09778 12.482 3.14114 12.4849 3.18741 12.4873C3.36516 12.4966 3.45404 12.5013 3.51612 12.5365C3.57237 12.5684 3.61399 12.6131 3.64232 12.6721C3.67359 12.7371 3.67359 12.8232 3.67359 12.9953V13.2455C3.67359 13.4224 3.67359 13.5109 3.63841 13.5792C3.60818 13.6379 3.55688 13.688 3.49816 13.7163Z" fill="#1A2B03"/>
+<path d="M1.25797 9.82937C1.22461 9.76252 1.22461 9.67502 1.22461 9.5V8.625C1.22461 8.44998 1.22461 8.36248 1.25797 8.29563C1.28732 8.23683 1.33415 8.18902 1.39176 8.15906C1.45724 8.125 1.54296 8.125 1.71441 8.125H1.9593C2.13075 8.125 2.21647 8.125 2.28195 8.15906C2.33955 8.18902 2.38639 8.23683 2.41573 8.29563C2.4491 8.36248 2.4491 8.44998 2.4491 8.625V9.5C2.4491 9.67502 2.4491 9.76252 2.41573 9.82937C2.38639 9.88817 2.33955 9.93598 2.28195 9.96594C2.21647 10 2.13075 10 1.9593 10H1.71441C1.54296 10 1.45724 10 1.39176 9.96594C1.33415 9.93598 1.28732 9.88817 1.25797 9.82937Z" fill="#1A2B03"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M9.67359 8.125C8.64492 8.125 8.13059 8.125 7.73769 7.92064C7.39209 7.74087 7.1111 7.45404 6.93501 7.10123C6.73481 6.70015 6.73481 6.1751 6.73481 5.125V4.25C6.73481 3.1999 6.73481 2.67485 6.93501 2.27377C7.1111 1.92096 7.39209 1.63413 7.73769 1.45436C8.13059 1.25 8.64492 1.25 9.67359 1.25H10.5307C11.5594 1.25 12.0737 1.25 12.4666 1.45436C12.8122 1.63412 13.0932 1.92096 13.2693 2.27377C13.4695 2.67485 13.4695 3.1999 13.4695 4.25V5.125C13.4695 6.1751 13.4695 6.70015 13.2693 7.10123C13.0932 7.45404 12.8122 7.74087 12.4666 7.92064C12.0737 8.125 11.5594 8.125 10.5307 8.125H9.67359ZM7.9593 5.125V4.25C7.9593 3.70432 7.96026 3.37024 7.98026 3.12029C7.98958 3.00385 8.00129 2.93341 8.01116 2.89062C8.01585 2.87027 8.01979 2.85775 8.02215 2.85098C8.02443 2.84449 8.02604 2.84126 8.02604 2.84126C8.08473 2.72365 8.17839 2.62804 8.2936 2.56812C8.2936 2.56812 8.29676 2.56648 8.30313 2.56416C8.30976 2.56174 8.32202 2.55772 8.34196 2.55293C8.38387 2.54286 8.45288 2.53091 8.56694 2.52139C8.81179 2.50097 9.13905 2.5 9.67359 2.5H10.5307C11.0653 2.5 11.3925 2.50097 11.6374 2.52139C11.7514 2.53091 11.8205 2.54286 11.8624 2.55293C11.8823 2.55772 11.8946 2.56174 11.9012 2.56416C11.9076 2.56648 11.9107 2.56812 11.9107 2.56812C12.0259 2.62804 12.1196 2.72365 12.1783 2.84126C12.1783 2.84126 12.1799 2.84449 12.1822 2.85098C12.1845 2.85775 12.1885 2.87027 12.1932 2.89062C12.203 2.93341 12.2147 3.00385 12.2241 3.12029C12.2441 3.37024 12.245 3.70432 12.245 4.25V5.125C12.245 5.67068 12.2441 6.00475 12.2241 6.25471C12.2147 6.37115 12.203 6.44159 12.1932 6.48438C12.1885 6.50473 12.1845 6.51725 12.1822 6.52401C12.1799 6.53051 12.1783 6.53374 12.1783 6.53374C12.1196 6.65134 12.0259 6.74696 11.9107 6.80688C11.9107 6.80688 11.9076 6.80852 11.9012 6.81084C11.8946 6.81326 11.8823 6.81728 11.8624 6.82207C11.8205 6.83214 11.7514 6.84409 11.6374 6.85361C11.3925 6.87403 11.0653 6.875 10.5307 6.875H9.67359C9.13905 6.875 8.81179 6.87403 8.56694 6.85361C8.45288 6.84409 8.38387 6.83214 8.34196 6.82207C8.32202 6.81728 8.30976 6.81326 8.30313 6.81084C8.29676 6.80852 8.2936 6.80688 8.2936 6.80688C8.17839 6.74696 8.08473 6.65135 8.02604 6.53374C8.02604 6.53374 8.02443 6.53051 8.02215 6.52401C8.01979 6.51725 8.01585 6.50473 8.01116 6.48438C8.00129 6.44159 7.98958 6.37115 7.98026 6.25471C7.96026 6.00475 7.9593 5.67068 7.9593 5.125Z" fill="#1A2B03"/>
+</svg>
diff --git a/packages/studio/public/icons/timeline/image.svg b/packages/studio/public/icons/timeline/image.svg
new file mode 100644
index 0000000000..38393b5e57
--- /dev/null
+++ b/packages/studio/public/icons/timeline/image.svg
@@ -0,0 +1,18 @@
+<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_1632_277)">
+<path d="M4.2665 5.75742C4.2665 6.30648 3.82178 6.75121 3.27271 6.75121C2.72365 6.75121 2.27893 6.30648 2.27893 5.75742C2.27893 5.20835 2.72365 4.76363 3.27271 4.76363C3.82178 4.76363 4.2665 5.20835 4.2665 5.75742Z" fill="black"/>
+<path d="M0.788398 11.3182C1.06294 11.3182 1.28529 11.0958 1.28529 10.8213V9.33061C1.28529 9.05607 1.06294 8.83372 0.788398 8.83372C0.513858 8.83372 0.291504 9.05607 0.291504 9.33061V10.8213C0.291504 11.0958 0.513858 11.3182 0.788398 11.3182Z" fill="black"/>
+<path d="M0.788398 8.33681C1.06294 8.33681 1.28529 8.11446 1.28529 7.83992V6.34924C1.28529 6.0747 1.06294 5.85234 0.788398 5.85234C0.513858 5.85234 0.291504 6.0747 0.291504 6.34924V7.83992C0.291504 8.11446 0.513858 8.33681 0.788398 8.33681Z" fill="black"/>
+<path d="M0.788401 5.35545C1.06294 5.35545 1.28529 5.1331 1.28529 4.85856V4.30328C1.28529 4.08961 1.34989 3.88527 1.47225 3.71197C1.63002 3.48712 1.57598 3.1778 1.35176 3.01941C1.12753 2.86165 0.817593 2.91569 0.659827 3.13991C0.418837 3.48214 0.292125 3.88401 0.292125 4.30326V4.85854C0.292125 5.13308 0.514479 5.35544 0.789019 5.35544L0.788401 5.35545Z" fill="black"/>
+<path d="M5.3231 3.27279H6.81378C7.08832 3.27279 7.31068 3.05044 7.31068 2.7759C7.31068 2.50136 7.08832 2.279 6.81378 2.279H5.3231C5.04856 2.279 4.82621 2.50136 4.82621 2.7759C4.82621 3.05044 5.04856 3.27279 5.3231 3.27279Z" fill="black"/>
+<path d="M2.34174 3.27279H3.83242C4.10696 3.27279 4.32931 3.05044 4.32931 2.7759C4.32931 2.50136 4.10696 2.279 3.83242 2.279H2.34174C2.0672 2.279 1.84484 2.50136 1.84484 2.7759C1.84484 3.05044 2.0672 3.27279 2.34174 3.27279Z" fill="black"/>
+<path d="M11.223 6.34113C10.9485 6.34113 10.7261 6.56349 10.7261 6.83803V8.32871C10.7261 8.60325 10.9485 8.8256 11.223 8.8256C11.4976 8.8256 11.7199 8.60325 11.7199 8.32871V6.83803C11.7199 6.56349 11.4976 6.34113 11.223 6.34113Z" fill="black"/>
+<path d="M11.223 9.32249C11.0963 9.32249 10.982 9.37094 10.8944 9.4492L9.02549 7.58024C8.25095 6.80571 6.99068 6.80571 6.21553 7.58024L1.49257 12.3032C1.44475 12.2398 1.40313 12.1703 1.37083 12.0957C1.26151 11.8442 0.967719 11.7293 0.716791 11.8392C0.465244 11.9492 0.35033 12.2417 0.460267 12.4933C0.62735 12.8759 0.906231 13.1889 1.25034 13.4019C1.25096 13.4026 1.25158 13.4032 1.2522 13.4032C1.25344 13.4038 1.25468 13.4044 1.25593 13.4051C1.33357 13.4529 1.41369 13.497 1.49754 13.5342C1.75344 13.6485 2.0317 13.7082 2.31616 13.7082H9.695C10.8118 13.7082 11.7198 12.8001 11.7198 11.6834V9.81999C11.7198 9.54545 11.4974 9.3231 11.2229 9.3231L11.223 9.32249Z" fill="black"/>
+<path d="M13.5063 2.63565C12.0492 2.23254 11.769 1.95242 11.366 0.493362C11.333 0.374108 11.225 0.291504 11.1014 0.291504C10.9777 0.291504 10.8697 0.374112 10.8368 0.493362C10.4343 1.95237 10.1541 2.23257 8.69701 2.63565C8.57775 2.66857 8.49577 2.77727 8.49577 2.90025C8.49577 3.02386 8.57838 3.13255 8.69701 3.16486C10.1542 3.56733 10.4343 3.84809 10.8368 5.30651C10.8697 5.42576 10.9777 5.50837 11.1014 5.50837C11.225 5.50837 11.333 5.42576 11.366 5.30651C11.7684 3.8475 12.0486 3.5673 13.5063 3.16486C13.6256 3.13194 13.7076 3.02324 13.7076 2.90025C13.7076 2.77665 13.625 2.66796 13.5063 2.63565Z" fill="black"/>
+</g>
+<defs>
+<clipPath id="clip0_1632_277">
+<rect width="14" height="14" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/packages/studio/public/icons/timeline/music.svg b/packages/studio/public/icons/timeline/music.svg
new file mode 100644
index 0000000000..ccb3afd990
--- /dev/null
+++ b/packages/studio/public/icons/timeline/music.svg
@@ -0,0 +1,10 @@
+<svg width="14" height="15" viewBox="0 0 14 15" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_1264_9865)">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M4.76273 0.617647C4.59359 0.588283 4.42061 0.637924 4.28978 0.753378C4.15894 0.868831 4.0835 1.0384 4.0835 1.21702V4.70069C4.08337 4.70802 4.08337 4.71534 4.0835 4.72263V8.22621C3.74029 8.01941 3.34183 7.90105 2.91683 7.90105C1.62817 7.90105 0.583496 8.98924 0.583496 10.3316C0.583496 11.674 1.62817 12.7622 2.91683 12.7622C4.15198 12.7622 5.16298 11.7625 5.24482 10.4975C5.24834 10.4704 5.25016 10.4429 5.25016 10.4148V5.43278L11.9585 6.64222V9.44149C11.6153 9.23469 11.2168 9.11633 10.7918 9.11633C9.50317 9.11633 8.4585 10.2045 8.4585 11.5469C8.4585 12.8892 9.50317 13.9774 10.7918 13.9774C12.0805 13.9774 13.1252 12.8892 13.1252 11.5469V2.58421C13.1252 2.28717 12.919 2.03367 12.6377 1.98483L4.76273 0.617647ZM11.9585 11.5469C11.9585 10.8757 11.4362 10.3316 10.7918 10.3316C10.1475 10.3316 9.62516 10.8757 9.62516 11.5469C9.62516 12.2181 10.1475 12.7622 10.7918 12.7622C11.4362 12.7622 11.9585 12.2181 11.9585 11.5469ZM11.9585 5.40887L5.25016 4.19944V1.93431L11.9585 3.09895V5.40887ZM4.0835 10.3316C4.0835 9.66042 3.56116 9.11633 2.91683 9.11633C2.2725 9.11633 1.75016 9.66042 1.75016 10.3316C1.75016 11.0028 2.2725 11.5469 2.91683 11.5469C3.56116 11.5469 4.0835 11.0028 4.0835 10.3316Z" fill="#013A4B"/>
+</g>
+<defs>
+<clipPath id="clip0_1264_9865">
+<rect width="14" height="14.5833" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/packages/studio/public/icons/timeline/text.svg b/packages/studio/public/icons/timeline/text.svg
new file mode 100644
index 0000000000..f43cd0aef0
--- /dev/null
+++ b/packages/studio/public/icons/timeline/text.svg
@@ -0,0 +1,3 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M2 3.5V2H10V3.5M4.5 10H7.5M6 2V10" stroke="#024A03" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx
new file mode 100644
index 0000000000..dc7eeb4742
--- /dev/null
+++ b/packages/studio/src/App.tsx
@@ -0,0 +1,557 @@
+import { useState, useCallback, useRef, useEffect } from "react";
+import { NLELayout } from "./components/nle/NLELayout";
+import { SourceEditor } from "./components/editor/SourceEditor";
+import { FileTree } from "./components/editor/FileTree";
+import {
+ XIcon,
+ CodeIcon,
+ WarningIcon,
+ CheckCircleIcon,
+ CaretRightIcon,
+} from "@phosphor-icons/react";
+
+interface EditingFile {
+ path: string;
+ content: string;
+}
+
+interface ProjectEntry {
+ id: string;
+ title?: string;
+ sessionId?: string;
+}
+
+interface LintFinding {
+ severity: "error" | "warning";
+ message: string;
+ file?: string;
+ fixHint?: string;
+}
+
+// ── Project Picker ──
+
+function ProjectPicker({ onSelect }: { onSelect: (id: string) => void }) {
+ const [projects, setProjects] = useState<ProjectEntry[]>([]);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ fetch("/api/projects")
+ .then((r) => r.json())
+ .then((data: { projects?: ProjectEntry[] }) => {
+ setProjects(data.projects ?? []);
+ setLoading(false);
+ })
+ .catch(() => setLoading(false));
+ }, []);
+
+ return (
+ <div className="h-screen w-screen bg-neutral-950 overflow-y-auto">
+ <div className="max-w-lg w-full mx-auto px-4 py-12">
+ <h1 className="text-xl font-semibold text-neutral-200 mb-1">HyperFrames Studio</h1>
+ <p className="text-sm text-neutral-500 mb-6">Select a project to open</p>
+ {loading ? (
+ <div className="text-sm text-neutral-600">Loading projects...</div>
+ ) : projects.length === 0 ? (
+ <div className="text-sm text-neutral-600">No projects found.</div>
+ ) : (
+ <div className="flex flex-col gap-1.5">
+ {projects.map((p) => (
+ <button
+ key={p.id}
+ onClick={() => onSelect(p.id)}
+ className="text-left px-4 py-3 rounded-lg bg-neutral-900 border border-neutral-800 hover:border-neutral-600 hover:bg-neutral-800/80 transition-all group"
+ >
+ <div className="text-sm text-neutral-200 truncate">{p.title ?? p.id}</div>
+ <div className="text-[11px] text-neutral-600 font-mono truncate mt-0.5 group-hover:text-neutral-500">
+ {p.id}
+ </div>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// ── Lint Modal ──
+
+function LintModal({ findings, onClose }: { findings: LintFinding[]; onClose: () => void }) {
+ const errors = findings.filter((f) => f.severity === "error");
+ const warnings = findings.filter((f) => f.severity === "warning");
+ const hasIssues = findings.length > 0;
+
+ return (
+ <div
+ className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm"
+ onClick={onClose}
+ >
+ <div
+ className="bg-neutral-950 border border-neutral-800 rounded-xl shadow-2xl w-full max-w-xl max-h-[80vh] flex flex-col overflow-hidden"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {/* Header */}
+ <div className="flex items-center justify-between px-5 py-4 border-b border-neutral-800">
+ <div className="flex items-center gap-3">
+ {hasIssues ? (
+ <div className="w-8 h-8 rounded-full bg-red-500/10 flex items-center justify-center">
+ <WarningIcon size={18} className="text-red-400" weight="fill" />
+ </div>
+ ) : (
+ <div className="w-8 h-8 rounded-full bg-green-500/10 flex items-center justify-center">
+ <CheckCircleIcon size={18} className="text-green-400" weight="fill" />
+ </div>
+ )}
+ <div>
+ <h2 className="text-sm font-semibold text-neutral-200">
+ {hasIssues
+ ? `${errors.length} error${errors.length !== 1 ? "s" : ""}, ${warnings.length} warning${warnings.length !== 1 ? "s" : ""}`
+ : "All checks passed"}
+ </h2>
+ <p className="text-xs text-neutral-500">HyperFrame Lint Results</p>
+ </div>
+ </div>
+ <button
+ onClick={onClose}
+ className="p-1.5 rounded-lg text-neutral-500 hover:text-neutral-200 hover:bg-neutral-800 transition-colors"
+ >
+ <XIcon size={16} />
+ </button>
+ </div>
+
+ {/* Findings */}
+ <div className="flex-1 overflow-y-auto px-5 py-3">
+ {!hasIssues && (
+ <div className="py-8 text-center text-neutral-500 text-sm">
+ No errors or warnings found. Your composition looks good!
+ </div>
+ )}
+ {errors.map((f, i) => (
+ <div key={`e-${i}`} className="py-3 border-b border-neutral-800/50 last:border-0">
+ <div className="flex items-start gap-2">
+ <WarningIcon
+ size={14}
+ className="text-red-400 flex-shrink-0 mt-0.5"
+ weight="fill"
+ />
+ <div className="min-w-0">
+ <p className="text-sm text-neutral-200">{f.message}</p>
+ {f.file && <p className="text-xs text-neutral-600 font-mono mt-0.5">{f.file}</p>}
+ {f.fixHint && (
+ <div className="flex items-start gap-1 mt-1.5">
+ <CaretRightIcon size={10} className="text-blue-400 flex-shrink-0 mt-0.5" />
+ <p className="text-xs text-blue-400">{f.fixHint}</p>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ ))}
+ {warnings.map((f, i) => (
+ <div key={`w-${i}`} className="py-3 border-b border-neutral-800/50 last:border-0">
+ <div className="flex items-start gap-2">
+ <WarningIcon size={14} className="text-amber-400 flex-shrink-0 mt-0.5" />
+ <div className="min-w-0">
+ <p className="text-sm text-neutral-300">{f.message}</p>
+ {f.file && <p className="text-xs text-neutral-600 font-mono mt-0.5">{f.file}</p>}
+ {f.fixHint && (
+ <div className="flex items-start gap-1 mt-1.5">
+ <CaretRightIcon size={10} className="text-blue-400 flex-shrink-0 mt-0.5" />
+ <p className="text-xs text-blue-400">{f.fixHint}</p>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+// ── Main App ──
+
+export function StudioApp() {
+ const [projectId, setProjectId] = useState<string | null>(null);
+ const [resolving, setResolving] = useState(true);
+
+ useEffect(() => {
+ const hash = window.location.hash;
+ const projectMatch = hash.match(/project\/([^/]+)/);
+ const sessionMatch = hash.match(/session\/([^/]+)/);
+ if (projectMatch) {
+ setProjectId(projectMatch[1]);
+ setResolving(false);
+ } else if (sessionMatch) {
+ fetch(`/api/resolve-session/${sessionMatch[1]}`)
+ .then((r) => r.json())
+ .then((data: { projectId?: string }) => {
+ if (data.projectId) {
+ window.location.hash = `#project/${data.projectId}`;
+ setProjectId(data.projectId);
+ }
+ setResolving(false);
+ })
+ .catch(() => setResolving(false));
+ } else {
+ setResolving(false);
+ }
+ }, []);
+
+ const [editingFile, setEditingFile] = useState<EditingFile | null>(null);
+ const [sidebarOpen, setSidebarOpen] = useState(false);
+ const [fileTree, setFileTree] = useState<string[]>([]);
+ const [lintModal, setLintModal] = useState<LintFinding[] | null>(null);
+ const [linting, setLinting] = useState(false);
+ const [refreshKey, setRefreshKey] = useState(0);
+ const [renderState, setRenderState] = useState<"idle" | "rendering" | "complete" | "error">(
+ "idle",
+ );
+ const [renderProgress, setRenderProgress] = useState(0);
+ const [renderError, setRenderError] = useState<string | null>(null);
+ const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const projectIdRef = useRef(projectId);
+
+ // Listen for external file changes (user editing HTML outside the editor)
+ useEffect(() => {
+ if (!import.meta.hot) return;
+ const handler = () => {
+ if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
+ refreshTimerRef.current = setTimeout(() => setRefreshKey((k) => k + 1), 400);
+ };
+ import.meta.hot.on("hf:file-change", handler);
+ return () => import.meta.hot?.off?.("hf:file-change", handler);
+ }, []);
+ projectIdRef.current = projectId;
+
+ // Load file tree when projectId changes
+ const prevProjectIdRef = useRef<string | null>(null);
+ if (projectId && projectId !== prevProjectIdRef.current) {
+ prevProjectIdRef.current = projectId;
+ fetch(`/api/projects/${projectId}`)
+ .then((r) => r.json())
+ .then((data: { files?: string[] }) => {
+ if (data.files) setFileTree(data.files);
+ })
+ .catch(() => {});
+ }
+
+ const handleSelectProject = useCallback((id: string) => {
+ window.location.hash = `#project/${id}`;
+ setProjectId(id);
+ }, []);
+
+ const handleFileSelect = useCallback((path: string) => {
+ const pid = projectIdRef.current;
+ if (!pid) return;
+ fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`)
+ .then((r) => r.json())
+ .then((data: { content?: string }) => {
+ if (data.content != null) {
+ setEditingFile({ path, content: data.content });
+ setSidebarOpen(true);
+ }
+ })
+ .catch(() => {});
+ }, []);
+
+ const editingPathRef = useRef(editingFile?.path);
+ editingPathRef.current = editingFile?.path;
+
+ const handleContentChange = useCallback((content: string) => {
+ const pid = projectIdRef.current;
+ const path = editingPathRef.current;
+ if (!pid || !path) return;
+ // Don't update editingFile state — the editor manages its own content.
+ // Only save to disk and refresh the preview.
+ fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`, {
+ method: "PUT",
+ headers: { "Content-Type": "text/plain" },
+ body: content,
+ })
+ .then(() => {
+ if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
+ refreshTimerRef.current = setTimeout(() => setRefreshKey((k) => k + 1), 600);
+ })
+ .catch(() => {});
+ }, []);
+
+ const handleLint = useCallback(async () => {
+ const pid = projectIdRef.current;
+ if (!pid) return;
+ setLinting(true);
+ try {
+ // Fetch all HTML files and lint them client-side using the core linter
+ const res = await fetch(`/api/projects/${pid}`);
+ const data = await res.json();
+ const files: string[] = data.files?.filter((f: string) => f.endsWith(".html")) ?? [];
+
+ const findings: LintFinding[] = [];
+ for (const file of files) {
+ const fileRes = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(file)}`);
+ const fileData = await fileRes.json();
+ if (!fileData.content) continue;
+
+ // Basic lint checks (subset of the full linter)
+ const html = fileData.content as string;
+
+ if (file === "index.html") {
+ // Check for root composition
+ if (!html.includes("data-composition-id")) {
+ findings.push({
+ severity: "error",
+ message: "No element with `data-composition-id` found.",
+ file,
+ fixHint: "Add `data-composition-id` to the root composition wrapper.",
+ });
+ }
+ // Check for timeline registration
+ if (!html.includes("__timelines")) {
+ findings.push({
+ severity: "error",
+ message: "Missing `window.__timelines` registration.",
+ file,
+ fixHint: 'Add: window.__timelines["compositionId"] = tl;',
+ });
+ }
+ // Check for TARGET_DURATION
+ if (
+ html.includes("gsap.timeline") &&
+ !html.includes("TARGET_DURATION") &&
+ !html.includes("tl.set({}, {},")
+ ) {
+ findings.push({
+ severity: "warning",
+ message: "No TARGET_DURATION spacer found. Video may be shorter than intended.",
+ file,
+ fixHint:
+ "Add: const TARGET_DURATION = 30; if (tl.duration() < TARGET_DURATION) { tl.set({}, {}, TARGET_DURATION); }",
+ });
+ }
+ }
+
+ // Check for composition hosts missing dimensions
+ const hostRe = /data-composition-src=["']([^"']+)["']/g;
+ let hostMatch;
+ while ((hostMatch = hostRe.exec(html)) !== null) {
+ const surrounding = html.slice(
+ Math.max(0, hostMatch.index - 300),
+ hostMatch.index + hostMatch[0].length + 50,
+ );
+ const hasDataDims =
+ /data-width\s*=/i.test(surrounding) && /data-height\s*=/i.test(surrounding);
+ const hasStyleDims = /style\s*=.*width:\s*\d+px.*height:\s*\d+px/i.test(surrounding);
+ if (!hasDataDims && !hasStyleDims) {
+ findings.push({
+ severity: "warning",
+ message: `Composition host for "${hostMatch[1]}" missing data-width/data-height. May render with zero dimensions.`,
+ file,
+ fixHint:
+ 'Add data-width="1920" data-height="1080" style="position:relative;width:1920px;height:1080px"',
+ });
+ }
+ }
+
+ // Check for repeat: -1
+ if (/repeat\s*:\s*-\s*1/.test(html)) {
+ findings.push({
+ severity: "error",
+ message: "GSAP `repeat: -1` found — infinite loop breaks timeline duration.",
+ file,
+ fixHint: "Use a finite repeat count or CSS animation.",
+ });
+ }
+
+ // Check script syntax
+ const scriptRe = /<script\b(?![^>]*\bsrc\s*=)[^>]*>([\s\S]*?)<\/script>/gi;
+ let scriptMatch;
+ while ((scriptMatch = scriptRe.exec(html)) !== null) {
+ const js = scriptMatch[1]?.trim();
+ if (!js) continue;
+ try {
+ new Function(js);
+ } catch (e) {
+ findings.push({
+ severity: "error",
+ message: `Script syntax error: ${e instanceof Error ? e.message : String(e)}`,
+ file,
+ });
+ }
+ }
+ }
+
+ setLintModal(findings);
+ } catch {
+ setLintModal([{ severity: "error", message: "Failed to run lint." }]);
+ } finally {
+ setLinting(false);
+ }
+ }, []);
+
+ const handleRender = useCallback(async () => {
+ const pid = projectIdRef.current;
+ if (!pid || renderState === "rendering") return;
+ setRenderState("rendering");
+ setRenderProgress(0);
+ setRenderError(null);
+ try {
+ // Start render via studio backend
+ const res = await fetch(`/api/projects/${pid}/render`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({}),
+ });
+ if (!res.ok) throw new Error(`Render failed: ${res.status}`);
+ const { jobId } = await res.json();
+
+ // Subscribe to progress via SSE
+ const eventSource = new EventSource(`/api/render/${jobId}/progress`);
+ eventSource.addEventListener("progress", (event) => {
+ try {
+ const data = JSON.parse(event.data);
+ setRenderProgress(data.progress ?? 0);
+ if (data.status === "complete") {
+ setRenderState("complete");
+ eventSource.close();
+ // Auto-download
+ window.open(`/api/render/${jobId}/download`, "_blank");
+ } else if (data.status === "failed") {
+ setRenderState("error");
+ setRenderError(data.error || "Render failed");
+ eventSource.close();
+ }
+ } catch {
+ /* ignore */
+ }
+ });
+ eventSource.onerror = () => {
+ setRenderState("error");
+ setRenderError("Lost connection to render server");
+ eventSource.close();
+ };
+ } catch (err) {
+ setRenderState("error");
+ setRenderError(err instanceof Error ? err.message : "Render failed");
+ }
+ }, [renderState]);
+
+ if (resolving) {
+ return (
+ <div className="h-screen w-screen bg-neutral-950 flex items-center justify-center">
+ <div className="text-sm text-neutral-500">Loading...</div>
+ </div>
+ );
+ }
+
+ if (!projectId) {
+ return <ProjectPicker onSelect={handleSelectProject} />;
+ }
+
+ return (
+ <div className="flex h-screen w-screen bg-neutral-950">
+ {/* NLE: Preview + Timeline */}
+ <div className="flex-1 relative min-w-0">
+ <NLELayout
+ projectId={projectId}
+ refreshKey={refreshKey}
+ activeCompositionPath={
+ editingFile?.path?.startsWith("compositions/") ? editingFile.path : null
+ }
+ />
+ </div>
+
+ {/* Action buttons — positioned based on sidebar state */}
+ {!sidebarOpen && (
+ <div className="absolute top-3 right-3 z-50 flex items-center gap-1.5">
+ <button
+ onClick={() => setSidebarOpen(true)}
+ className="h-8 px-3 rounded-lg bg-neutral-900 border border-neutral-800 text-neutral-500 hover:text-neutral-200 transition-colors flex items-center justify-center"
+ title="Source editor"
+ >
+ <CodeIcon size={16} />
+ </button>
+ <button
+ onClick={handleLint}
+ disabled={linting}
+ className="h-8 px-3 rounded-lg bg-neutral-900 border border-neutral-800 text-xs font-medium text-neutral-400 hover:text-amber-300 hover:border-amber-800/50 transition-colors disabled:opacity-40"
+ >
+ {linting ? "Linting..." : "Lint"}
+ </button>
+ <button
+ onClick={handleRender}
+ disabled={renderState === "rendering"}
+ className="h-8 px-3 rounded-lg bg-blue-600 border border-blue-500 text-xs font-semibold text-white hover:bg-blue-500 transition-colors disabled:opacity-60 tabular-nums"
+ >
+ {renderState === "rendering"
+ ? `${Math.round(renderProgress)}%`
+ : renderState === "complete"
+ ? "Done!"
+ : "Export MP4"}
+ </button>
+ </div>
+ )}
+
+ {/* Source editor sidebar */}
+ {sidebarOpen && (
+ <div className="w-[420px] flex flex-col border-l border-neutral-800 bg-neutral-900">
+ <div className="flex items-center justify-between px-3 py-2 border-b border-neutral-800 gap-2">
+ <span className="text-xs font-medium text-neutral-500 truncate min-w-0 flex-1">
+ {editingFile?.path ?? "Source"}
+ </span>
+ <div className="flex items-center gap-1.5 flex-shrink-0">
+ <button
+ onClick={handleLint}
+ disabled={linting}
+ className="px-2 py-1 rounded text-[11px] font-medium text-neutral-500 hover:text-amber-300 transition-colors disabled:opacity-40"
+ >
+ {linting ? "..." : "Lint"}
+ </button>
+ <button
+ onClick={handleRender}
+ disabled={renderState === "rendering"}
+ className="px-2 py-1 rounded text-[11px] font-semibold text-blue-400 hover:text-blue-300 transition-colors disabled:opacity-60 tabular-nums"
+ >
+ {renderState === "rendering" ? `${Math.round(renderProgress)}%` : "Export MP4"}
+ </button>
+ <button
+ onClick={() => setSidebarOpen(false)}
+ className="p-1 rounded text-neutral-600 hover:text-neutral-200 hover:bg-neutral-800 transition-colors"
+ title="Close source panel"
+ >
+ <XIcon size={14} />
+ </button>
+ </div>
+ </div>
+
+ {fileTree.length > 0 && (
+ <div className="border-b border-neutral-800 max-h-40 overflow-y-auto">
+ <FileTree
+ files={fileTree}
+ activeFile={editingFile?.path ?? null}
+ onSelectFile={handleFileSelect}
+ />
+ </div>
+ )}
+
+ <div className="flex-1 overflow-hidden">
+ {editingFile ? (
+ <SourceEditor
+ content={editingFile.content}
+ filePath={editingFile.path}
+ onChange={handleContentChange}
+ />
+ ) : (
+ <div className="flex items-center justify-center h-full text-neutral-600 text-sm">
+ Select a file to edit
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Lint modal */}
+ {lintModal !== null && <LintModal findings={lintModal} onClose={() => setLintModal(null)} />}
+ </div>
+ );
+}
diff --git a/packages/studio/src/components/editor/FileTree.tsx b/packages/studio/src/components/editor/FileTree.tsx
new file mode 100644
index 0000000000..31d3f8aa91
--- /dev/null
+++ b/packages/studio/src/components/editor/FileTree.tsx
@@ -0,0 +1,70 @@
+import { memo } from "react";
+import { FileCode, Image, Film, Music, File } from "../../icons/SystemIcons";
+
+interface FileTreeProps {
+ files: string[];
+ activeFile: string | null;
+ onSelectFile: (path: string) => void;
+}
+
+const FILE_ICONS: Record<string, { icon: typeof File; color: string }> = {
+ html: { icon: FileCode, color: "#3B82F6" },
+ css: { icon: FileCode, color: "#A855F7" },
+ js: { icon: FileCode, color: "#F59E0B" },
+ ts: { icon: FileCode, color: "#3B82F6" },
+ json: { icon: File, color: "#22C55E" },
+ png: { icon: Image, color: "#22C55E" },
+ jpg: { icon: Image, color: "#22C55E" },
+ svg: { icon: Image, color: "#F97316" },
+ mp4: { icon: Film, color: "#A855F7" },
+ mp3: { icon: Music, color: "#F59E0B" },
+ wav: { icon: Music, color: "#F59E0B" },
+};
+
+function getFileIcon(path: string) {
+ const ext = path.split(".").pop()?.toLowerCase() ?? "";
+ return FILE_ICONS[ext] ?? { icon: File, color: "#737373" };
+}
+
+export const FileTree = memo(function FileTree({ files, activeFile, onSelectFile }: FileTreeProps) {
+ const sorted = [...files].sort((a, b) => {
+ // index.html first, then alphabetical
+ if (a === "index.html") return -1;
+ if (b === "index.html") return 1;
+ return a.localeCompare(b);
+ });
+
+ return (
+ <div className="flex flex-col h-full min-h-0">
+ <div className="px-2.5 py-1.5 border-b border-neutral-800 flex-shrink-0">
+ <span className="text-2xs font-medium text-neutral-500 uppercase tracking-caps">Files</span>
+ </div>
+ <div className="flex-1 overflow-y-auto py-1">
+ {sorted.map((path) => {
+ const { icon: Icon, color } = getFileIcon(path);
+ const isActive = path === activeFile;
+ const name = path.split("/").pop() ?? path;
+ const dir = path.includes("/") ? path.split("/").slice(0, -1).join("/") + "/" : "";
+
+ return (
+ <button
+ key={path}
+ onClick={() => onSelectFile(path)}
+ className={`w-full flex items-center gap-2 px-2.5 py-1 min-h-7 text-left transition-all duration-press text-xs ${
+ isActive
+ ? "bg-neutral-800/60 text-neutral-200"
+ : "text-neutral-500 hover:bg-neutral-800/30 hover:text-neutral-300 active:scale-[0.98]"
+ }`}
+ >
+ <Icon size={12} style={{ color }} className="flex-shrink-0" />
+ <span className="truncate">
+ {dir && <span className="text-neutral-600">{dir}</span>}
+ {name}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ );
+});
diff --git a/packages/studio/src/components/editor/PropertyPanel.tsx b/packages/studio/src/components/editor/PropertyPanel.tsx
new file mode 100644
index 0000000000..7ab4cadb82
--- /dev/null
+++ b/packages/studio/src/components/editor/PropertyPanel.tsx
@@ -0,0 +1,209 @@
+import { memo } from "react";
+import { X, MousePointer, Move, Type, Palette, Clock, Eye } from "../../icons/SystemIcons";
+import { Button, IconButton } from "../ui";
+import type { PickedElement } from "../../hooks/useElementPicker";
+
+interface PropertyPanelProps {
+ element: PickedElement | null;
+ isPickMode: boolean;
+ onEnablePick: () => void;
+ onDisablePick: () => void;
+ onClearPick: () => void;
+ onSetStyle: (prop: string, value: string) => void;
+ onSetDataAttr: (attr: string, value: string) => void;
+ onSetText?: (text: string) => void;
+}
+
+function PropertyRow({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
+ return (
+ <div className="flex items-center gap-2">
+ <span className="text-2xs text-neutral-600 w-16 flex-shrink-0 text-right">{label}</span>
+ <input
+ type="text"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ className="flex-1 bg-neutral-900 border border-neutral-800 rounded px-1.5 py-0.5 text-2xs text-neutral-200 font-mono outline-none focus:border-neutral-600 min-w-0"
+ />
+ </div>
+ );
+}
+
+function ColorRow({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
+ return (
+ <div className="flex items-center gap-2">
+ <span className="text-2xs text-neutral-600 w-16 flex-shrink-0 text-right">{label}</span>
+ <div className="flex items-center gap-1 flex-1">
+ <div className="w-5 h-5 rounded border border-neutral-700 flex-shrink-0" style={{ backgroundColor: value }} />
+ <input
+ type="text"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ className="flex-1 bg-neutral-900 border border-neutral-800 rounded px-1.5 py-0.5 text-2xs text-neutral-200 font-mono outline-none focus:border-neutral-600 min-w-0"
+ />
+ </div>
+ </div>
+ );
+}
+
+function SectionHeader({ icon: Icon, label }: { icon: typeof Move; label: string }) {
+ return (
+ <div className="flex items-center gap-1.5 mt-2 mb-1">
+ <Icon size={10} className="text-neutral-600" />
+ <span className="text-2xs font-medium text-neutral-500 uppercase tracking-wider">{label}</span>
+ </div>
+ );
+}
+
+export const PropertyPanel = memo(function PropertyPanel({
+ element,
+ isPickMode,
+ onEnablePick,
+ onDisablePick,
+ onClearPick,
+ onSetStyle,
+ onSetDataAttr,
+ onSetText,
+}: PropertyPanelProps) {
+ if (!element) {
+ return (
+ <div className="flex flex-col items-center justify-center h-full px-4 text-center">
+ <MousePointer size={20} className="text-neutral-700 mb-2" />
+ <p className="text-xs text-neutral-500">Click an element in the preview to inspect it</p>
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={isPickMode ? onDisablePick : onEnablePick}
+ className={`mt-3 ${isPickMode ? "bg-blue-500/20 text-blue-400 border-blue-500/30" : ""}`}
+ >
+ {isPickMode ? "Pick mode active..." : "Enable Pick Mode"}
+ </Button>
+ </div>
+ );
+ }
+
+ const s = element.computedStyles;
+
+ return (
+ <div className="flex flex-col h-full min-h-0">
+ {/* Header */}
+ <div className="flex items-center justify-between px-3 py-2 border-b border-neutral-800 flex-shrink-0">
+ <div className="flex items-center gap-1.5 min-w-0">
+ <span className="text-2xs font-mono text-blue-400 truncate">{element.selector}</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <IconButton
+ icon={<MousePointer size={11} />}
+ aria-label={isPickMode ? "Disable pick mode" : "Enable pick mode"}
+ size="sm"
+ onClick={isPickMode ? onDisablePick : onEnablePick}
+ className={isPickMode ? "text-blue-400 bg-blue-500/10" : ""}
+ />
+ <IconButton icon={<X size={11} />} aria-label="Clear selection" size="sm" onClick={onClearPick} />
+ </div>
+ </div>
+
+ {/* Properties */}
+ <div className="flex-1 overflow-y-auto px-3 py-2 space-y-1">
+ {/* Element info */}
+ <div className="flex items-center gap-2 mb-2">
+ <span className="text-2xs text-neutral-300 font-medium">{element.label}</span>
+ <span className="text-2xs text-neutral-600 font-mono">&lt;{element.tagName}&gt;</span>
+ </div>
+
+ {/* Position & Size */}
+ <SectionHeader icon={Move} label="Position & Size" />
+ <div className="grid grid-cols-2 gap-1">
+ <PropertyRow label="X" value={s["left"] ?? "auto"} onChange={(v) => onSetStyle("left", v)} />
+ <PropertyRow label="Y" value={s["top"] ?? "auto"} onChange={(v) => onSetStyle("top", v)} />
+ <PropertyRow label="W" value={s["width"] ?? "auto"} onChange={(v) => onSetStyle("width", v)} />
+ <PropertyRow label="H" value={s["height"] ?? "auto"} onChange={(v) => onSetStyle("height", v)} />
+ </div>
+
+ {/* Typography */}
+ {(element.tagName === "div" ||
+ element.tagName === "span" ||
+ element.tagName === "p" ||
+ element.tagName === "h1" ||
+ element.tagName === "h2") && (
+ <>
+ <SectionHeader icon={Type} label="Typography" />
+ <PropertyRow label="Size" value={s["font-size"] ?? ""} onChange={(v) => onSetStyle("font-size", v)} />
+ <PropertyRow label="Weight" value={s["font-weight"] ?? ""} onChange={(v) => onSetStyle("font-weight", v)} />
+ <PropertyRow
+ label="Family"
+ value={s["font-family"]?.split(",")[0] ?? ""}
+ onChange={(v) => onSetStyle("font-family", v)}
+ />
+ </>
+ )}
+
+ {/* Colors */}
+ <SectionHeader icon={Palette} label="Colors" />
+ <ColorRow label="Color" value={s["color"] ?? "#fff"} onChange={(v) => onSetStyle("color", v)} />
+ <ColorRow
+ label="Background"
+ value={s["background-color"] ?? "transparent"}
+ onChange={(v) => onSetStyle("background-color", v)}
+ />
+
+ {/* Appearance */}
+ <SectionHeader icon={Eye} label="Appearance" />
+ <PropertyRow label="Opacity" value={s["opacity"] ?? "1"} onChange={(v) => onSetStyle("opacity", v)} />
+ <PropertyRow
+ label="Radius"
+ value={s["border-radius"] ?? "0"}
+ onChange={(v) => onSetStyle("border-radius", v)}
+ />
+ <PropertyRow label="Z-index" value={s["z-index"] ?? "auto"} onChange={(v) => onSetStyle("z-index", v)} />
+ <PropertyRow label="Transform" value={s["transform"] ?? "none"} onChange={(v) => onSetStyle("transform", v)} />
+
+ {/* Timing */}
+ {(element.dataAttributes["start"] || element.dataAttributes["duration"]) && (
+ <>
+ <SectionHeader icon={Clock} label="Timing" />
+ {element.dataAttributes["start"] != null && (
+ <PropertyRow
+ label="Start"
+ value={element.dataAttributes["start"]}
+ onChange={(v) => onSetDataAttr("start", v)}
+ />
+ )}
+ {element.dataAttributes["duration"] != null && (
+ <PropertyRow
+ label="Duration"
+ value={element.dataAttributes["duration"]}
+ onChange={(v) => onSetDataAttr("duration", v)}
+ />
+ )}
+ {element.dataAttributes["track-index"] != null && (
+ <PropertyRow
+ label="Track"
+ value={element.dataAttributes["track-index"]}
+ onChange={(v) => onSetDataAttr("track-index", v)}
+ />
+ )}
+ </>
+ )}
+
+ {/* Editable text content */}
+ {element.textContent && (
+ <>
+ <SectionHeader icon={Type} label="Text Content" />
+ <textarea
+ defaultValue={element.textContent}
+ onBlur={(e) => onSetText?.(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && e.metaKey) {
+ (e.target as HTMLTextAreaElement).blur();
+ }
+ }}
+ rows={3}
+ className="w-full bg-neutral-900 border border-neutral-800 rounded px-2 py-1.5 text-xs text-neutral-200 outline-none focus:border-neutral-600 resize-y leading-relaxed"
+ placeholder="Edit text..."
+ />
+ </>
+ )}
+ </div>
+ </div>
+ );
+});
diff --git a/packages/studio/src/components/editor/SourceEditor.tsx b/packages/studio/src/components/editor/SourceEditor.tsx
new file mode 100644
index 0000000000..97b204ac2e
--- /dev/null
+++ b/packages/studio/src/components/editor/SourceEditor.tsx
@@ -0,0 +1,116 @@
+import { useRef, useCallback, memo } from "react";
+import { EditorView, keymap, lineNumbers, highlightActiveLine, highlightActiveLineGutter } from "@codemirror/view";
+import { EditorState } from "@codemirror/state";
+import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";
+import { bracketMatching, foldGutter, indentOnInput } from "@codemirror/language";
+import { closeBrackets, closeBracketsKeymap } from "@codemirror/autocomplete";
+import { highlightSelectionMatches, searchKeymap } from "@codemirror/search";
+import { oneDark } from "@codemirror/theme-one-dark";
+import { html } from "@codemirror/lang-html";
+import { css } from "@codemirror/lang-css";
+import { javascript } from "@codemirror/lang-javascript";
+
+function getLanguageExtension(language: string) {
+ switch (language) {
+ case "html":
+ return html();
+ case "css":
+ return css();
+ case "javascript":
+ case "js":
+ case "typescript":
+ case "ts":
+ return javascript({ typescript: language === "typescript" || language === "ts" });
+ default:
+ return html();
+ }
+}
+
+function detectLanguage(filePath: string): string {
+ const ext = filePath.split(".").pop()?.toLowerCase() ?? "";
+ const map: Record<string, string> = {
+ html: "html",
+ htm: "html",
+ css: "css",
+ js: "javascript",
+ ts: "typescript",
+ jsx: "javascript",
+ tsx: "typescript",
+ json: "javascript",
+ };
+ return map[ext] ?? "html";
+}
+
+interface SourceEditorProps {
+ content: string;
+ filePath?: string;
+ language?: string;
+ onChange?: (content: string) => void;
+ readOnly?: boolean;
+}
+
+export const SourceEditor = memo(function SourceEditor({
+ content,
+ filePath,
+ language,
+ onChange,
+ readOnly = false,
+}: SourceEditorProps) {
+ const editorRef = useRef<EditorView | null>(null);
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const onChangeRef = useRef(onChange);
+ onChangeRef.current = onChange;
+
+ const mountEditor = useCallback(
+ (node: HTMLDivElement | null) => {
+ if (editorRef.current) {
+ editorRef.current.destroy();
+ editorRef.current = null;
+ }
+ if (!node) return;
+ containerRef.current = node;
+
+ const lang = language ?? (filePath ? detectLanguage(filePath) : "html");
+
+ const updateListener = EditorView.updateListener.of((update) => {
+ if (update.docChanged && onChangeRef.current) {
+ onChangeRef.current(update.state.doc.toString());
+ }
+ });
+
+ const state = EditorState.create({
+ doc: content,
+ extensions: [
+ lineNumbers(),
+ highlightActiveLine(),
+ highlightActiveLineGutter(),
+ history(),
+ foldGutter(),
+ indentOnInput(),
+ bracketMatching(),
+ closeBrackets(),
+ highlightSelectionMatches(),
+ keymap.of([
+ ...closeBracketsKeymap,
+ ...defaultKeymap,
+ ...searchKeymap,
+ ...historyKeymap,
+ ]),
+ getLanguageExtension(lang),
+ oneDark,
+ updateListener,
+ EditorState.readOnly.of(readOnly),
+ EditorView.theme({
+ "&": { height: "100%" },
+ ".cm-scroller": { overflow: "auto" },
+ }),
+ ],
+ });
+
+ editorRef.current = new EditorView({ state, parent: node });
+ },
+ [content, filePath, language, readOnly],
+ );
+
+ return <div ref={mountEditor} className="h-full w-full overflow-hidden" />;
+});
diff --git a/packages/studio/src/components/nle/CompositionBreadcrumb.tsx b/packages/studio/src/components/nle/CompositionBreadcrumb.tsx
new file mode 100644
index 0000000000..7165042a44
--- /dev/null
+++ b/packages/studio/src/components/nle/CompositionBreadcrumb.tsx
@@ -0,0 +1,57 @@
+import { ArrowLeft, CaretRight } from "@phosphor-icons/react";
+
+export interface CompositionLevel {
+ /** Unique id — "master" or composition file path */
+ id: string;
+ /** Display label — "Master" or filename without extension */
+ label: string;
+ /** Preview URL for this composition level */
+ previewUrl: string;
+}
+
+interface CompositionBreadcrumbProps {
+ stack: CompositionLevel[];
+ onNavigate: (index: number) => void;
+}
+
+export function CompositionBreadcrumb({ stack, onNavigate }: CompositionBreadcrumbProps) {
+ if (stack.length <= 1) return null;
+
+ return (
+ <nav
+ aria-label="Composition navigation"
+ className="flex items-center gap-1 px-2 h-8 border-b border-neutral-800/50 bg-neutral-900/50 flex-shrink-0"
+ >
+ {/* Back button — always goes to parent */}
+ <button
+ type="button"
+ onClick={() => onNavigate(stack.length - 2)}
+ className="flex items-center gap-1 px-1.5 py-0.5 rounded text-xs text-neutral-400 hover:text-white hover:bg-neutral-800 transition-colors"
+ title="Back (Esc)"
+ >
+ <ArrowLeft size={12} weight="bold" />
+ </button>
+
+ {/* Breadcrumb path */}
+ {stack.map((level, i) => {
+ const isLast = i === stack.length - 1;
+ return (
+ <span key={level.id} className="flex items-center gap-1">
+ {i > 0 && <CaretRight size={10} className="text-neutral-600 flex-shrink-0" />}
+ {isLast ? (
+ <span className="text-xs text-neutral-200 font-medium">{level.label}</span>
+ ) : (
+ <button
+ type="button"
+ onClick={() => onNavigate(i)}
+ className="text-xs text-neutral-500 hover:text-neutral-200 transition-colors"
+ >
+ {level.label}
+ </button>
+ )}
+ </span>
+ );
+ })}
+ </nav>
+ );
+}
diff --git a/packages/studio/src/components/nle/NLELayout.tsx b/packages/studio/src/components/nle/NLELayout.tsx
new file mode 100644
index 0000000000..6fc5720e77
--- /dev/null
+++ b/packages/studio/src/components/nle/NLELayout.tsx
@@ -0,0 +1,252 @@
+import { useState, useEffect, useCallback, useRef, memo, type ReactNode } from "react";
+import { useTimelinePlayer, PlayerControls, Timeline, usePlayerStore } from "../../player";
+import type { TimelineElement } from "../../player";
+import { NLEPreview } from "./NLEPreview";
+import { CompositionBreadcrumb, type CompositionLevel } from "./CompositionBreadcrumb";
+
+interface NLELayoutProps {
+ projectId: string;
+ portrait?: boolean;
+ /** Slot for overlays rendered on top of the preview (cursors, highlights, etc.) */
+ previewOverlay?: ReactNode;
+ /** Slot rendered below the timeline tracks (e.g., agent activity swim lanes) */
+ timelineFooter?: ReactNode;
+ /** Increment to force the preview to reload (e.g., after file writes) */
+ refreshKey?: number;
+ /** Navigate to a specific composition path (e.g., "compositions/intro.html") */
+ activeCompositionPath?: string | null;
+ /** Callback to expose the iframe ref (for element picker, etc.) */
+ onIframeRef?: (iframe: HTMLIFrameElement | null) => void;
+}
+
+const MIN_TIMELINE_H = 100;
+const DEFAULT_TIMELINE_H = 220;
+const MIN_PREVIEW_H = 120;
+
+export const NLELayout = memo(function NLELayout({
+ projectId,
+ portrait,
+ previewOverlay,
+ timelineFooter,
+ refreshKey,
+ activeCompositionPath,
+ onIframeRef,
+}: NLELayoutProps) {
+ const { iframeRef, togglePlay, seek, onIframeLoad: baseOnIframeLoad, saveSeekPosition } = useTimelinePlayer();
+
+ // Preserve seek position when refreshKey changes (iframe will remount via key prop).
+ const prevRefreshKeyRef = useRef(refreshKey);
+ if (refreshKey !== prevRefreshKeyRef.current) {
+ prevRefreshKeyRef.current = refreshKey;
+ saveSeekPosition();
+ }
+
+ // Wrap onIframeLoad to also notify parent of iframe ref
+ const onIframeLoad = useCallback(() => {
+ baseOnIframeLoad();
+ onIframeRef?.(iframeRef.current);
+ }, [baseOnIframeLoad, iframeRef, onIframeRef]);
+
+ // Composition ID → actual file path mapping, built from the raw index.html
+ const [compIdToSrc, setCompIdToSrc] = useState<Map<string, string>>(new Map());
+ useEffect(() => {
+ fetch(`/api/projects/${projectId}/files/index.html`)
+ .then((r) => r.json())
+ .then((data: { content?: string }) => {
+ const html = data.content || "";
+ const map = new Map<string, string>();
+ const re = /data-composition-id=["']([^"']+)["'][^>]*data-composition-src=["']([^"']+)["']|data-composition-src=["']([^"']+)["'][^>]*data-composition-id=["']([^"']+)["']/g;
+ let match;
+ while ((match = re.exec(html)) !== null) {
+ const id = match[1] || match[4];
+ const src = match[2] || match[3];
+ if (id && src) map.set(id, src);
+ }
+ setCompIdToSrc(map);
+ })
+ .catch(() => {});
+ }, [projectId]);
+
+ // Composition drill-down stack
+ const [compositionStack, setCompositionStack] = useState<CompositionLevel[]>([
+ { id: "master", label: "Master", previewUrl: `/api/projects/${projectId}/preview` },
+ ]);
+
+ // Resizable timeline height
+ const [timelineH, setTimelineH] = useState(DEFAULT_TIMELINE_H);
+ const isDragging = useRef(false);
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ // Current preview URL — derived from composition stack
+ const currentLevel = compositionStack[compositionStack.length - 1];
+ const directUrl = compositionStack.length > 1 ? currentLevel.previewUrl : undefined;
+
+ // Drill-down: push a sub-composition onto the stack
+ const iframeRef_ = iframeRef; // stable ref for the callback
+ const handleDrillDown = useCallback(
+ (element: TimelineElement) => {
+ if (!element.compositionSrc) return;
+ // compositionSrc may be a full URL (from runtime manifest) or a relative path
+ // Extract the element's composition ID from its timeline ID
+ const compId = element.id;
+
+ // 1. Check compIdToSrc map (from index.html)
+ // 2. Scan the current iframe DOM for data-composition-src attribute
+ // 3. Fall back to stripping the compositionSrc to a relative path
+ let resolvedPath = compIdToSrc.get(compId);
+ if (!resolvedPath) {
+ try {
+ const doc = iframeRef_.current?.contentDocument;
+ if (doc) {
+ const host = doc.querySelector(`[data-composition-id="${compId}"][data-composition-src]`);
+ if (host) {
+ resolvedPath = host.getAttribute("data-composition-src") || undefined;
+ }
+ }
+ } catch { /* cross-origin */ }
+ }
+ if (!resolvedPath) {
+ // Strip full URL to relative path if needed
+ const src = element.compositionSrc;
+ const compMatch = src.match(/compositions\/.*\.html/);
+ resolvedPath = compMatch ? compMatch[0] : src;
+ }
+
+ usePlayerStore.getState().setElements([]);
+
+ // Toggle: if already viewing this composition, go back to parent (like Premiere)
+ setCompositionStack((prev) => {
+ const currentId = prev[prev.length - 1].id;
+ if (currentId === resolvedPath && prev.length > 1) {
+ return prev.slice(0, -1);
+ }
+ // Extract a clean label from the path (strip directories and extension)
+ const label = resolvedPath.split("/").pop()?.replace(/\.html$/, "") || resolvedPath;
+ const previewUrl = `/api/projects/${projectId}/preview/comp/${resolvedPath}`;
+ return [...prev, { id: resolvedPath, label, previewUrl }];
+ });
+ },
+ [projectId, compIdToSrc],
+ );
+
+ // Navigate back to a specific breadcrumb level
+ const handleNavigateComposition = useCallback(
+ (index: number) => {
+ usePlayerStore.getState().setElements([]);
+ setCompositionStack((prev) => prev.slice(0, index + 1));
+ },
+ [],
+ );
+
+ // Navigate to a composition when activeCompositionPath changes
+ const prevActiveCompRef = useRef<string | null>(null);
+ if (activeCompositionPath && activeCompositionPath !== prevActiveCompRef.current) {
+ prevActiveCompRef.current = activeCompositionPath;
+ queueMicrotask(() => usePlayerStore.getState().setElements([]));
+ if (activeCompositionPath === "index.html") {
+ setCompositionStack((prev) => prev.length > 1 ? [prev[0]] : prev);
+ } else if (activeCompositionPath.startsWith("compositions/")) {
+ const label = activeCompositionPath.replace(/^compositions\//, "").replace(/\.html$/, "");
+ const previewUrl = `/api/projects/${projectId}/preview/comp/${activeCompositionPath}`;
+ setCompositionStack((prev) => {
+ if (prev[prev.length - 1].id === activeCompositionPath) return prev;
+ return [
+ { id: "master", label: "Master", previewUrl: `/api/projects/${projectId}/preview` },
+ { id: activeCompositionPath, label, previewUrl },
+ ];
+ });
+ }
+ } else if (!activeCompositionPath && prevActiveCompRef.current) {
+ prevActiveCompRef.current = null;
+ queueMicrotask(() => usePlayerStore.getState().setElements([]));
+ }
+
+ // Resize divider handlers
+ const handleDividerPointerDown = useCallback((e: React.PointerEvent) => {
+ e.preventDefault();
+ isDragging.current = true;
+ (e.target as HTMLElement).setPointerCapture(e.pointerId);
+ }, []);
+
+ const handleDividerPointerMove = useCallback((e: React.PointerEvent) => {
+ if (!isDragging.current || !containerRef.current) return;
+ const rect = containerRef.current.getBoundingClientRect();
+ const mouseY = e.clientY - rect.top;
+ const containerH = rect.height;
+ const newTimelineH = Math.max(
+ MIN_TIMELINE_H,
+ Math.min(containerH - MIN_PREVIEW_H, containerH - mouseY),
+ );
+ setTimelineH(newTimelineH);
+ }, []);
+
+ const handleDividerPointerUp = useCallback(() => {
+ isDragging.current = false;
+ }, []);
+
+ // Keyboard: Escape to pop composition level
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (e.key === "Escape" && compositionStack.length > 1) {
+ setCompositionStack((prev) => prev.slice(0, -1));
+ }
+ },
+ [compositionStack.length],
+ );
+
+ return (
+ <div
+ ref={containerRef}
+ className="flex flex-col h-full min-h-0 bg-neutral-950"
+ onKeyDown={handleKeyDown}
+ tabIndex={-1}
+ >
+ {/* Preview — takes remaining space above timeline */}
+ <div className="flex-1 min-h-0 relative">
+ <NLEPreview
+ projectId={projectId}
+ iframeRef={iframeRef}
+ onIframeLoad={onIframeLoad}
+ portrait={portrait}
+ directUrl={directUrl}
+ refreshKey={refreshKey}
+ />
+ {previewOverlay}
+ </div>
+
+ {/* Resize divider */}
+ <div
+ className="h-1 flex-shrink-0 bg-neutral-800 hover:bg-blue-500 cursor-row-resize transition-colors active:bg-blue-400 z-10"
+ style={{ touchAction: "none" }}
+ onPointerDown={handleDividerPointerDown}
+ onPointerMove={handleDividerPointerMove}
+ onPointerUp={handleDividerPointerUp}
+ />
+
+ {/* Timeline section — fixed height, resizable */}
+ <div className="flex flex-col flex-shrink-0" style={{ height: timelineH }}>
+ {/* Breadcrumb + Player controls */}
+ <div className="bg-neutral-950 border-t border-neutral-800/50 flex-shrink-0">
+ {compositionStack.length > 1 && (
+ <CompositionBreadcrumb stack={compositionStack} onNavigate={handleNavigateComposition} />
+ )}
+ <PlayerControls onTogglePlay={togglePlay} onSeek={seek} />
+ </div>
+
+ {/* Timeline tracks */}
+ <div
+ className="flex-1 min-h-0 overflow-y-auto bg-neutral-950"
+ onDoubleClick={(e) => {
+ if ((e.target as HTMLElement).closest("[data-clip]")) return;
+ if (compositionStack.length > 1) {
+ setCompositionStack((prev) => prev.slice(0, -1));
+ }
+ }}
+ >
+ <Timeline onSeek={seek} onDrillDown={handleDrillDown} />
+ {timelineFooter}
+ </div>
+ </div>
+ </div>
+ );
+});
diff --git a/packages/studio/src/components/nle/NLEPreview.tsx b/packages/studio/src/components/nle/NLEPreview.tsx
new file mode 100644
index 0000000000..c0722909af
--- /dev/null
+++ b/packages/studio/src/components/nle/NLEPreview.tsx
@@ -0,0 +1,37 @@
+import { memo, type Ref } from "react";
+import { Player } from "../../player";
+
+interface NLEPreviewProps {
+ projectId: string;
+ iframeRef: Ref<HTMLIFrameElement>;
+ onIframeLoad: () => void;
+ portrait?: boolean;
+ directUrl?: string;
+ refreshKey?: number;
+}
+
+export const NLEPreview = memo(function NLEPreview({
+ projectId,
+ iframeRef,
+ onIframeLoad,
+ portrait,
+ directUrl,
+ refreshKey,
+}: NLEPreviewProps) {
+ const playerKey = `${directUrl ?? projectId}_${refreshKey ?? 0}`;
+
+ return (
+ <div className="flex flex-col h-full min-h-0">
+ <div className="flex-1 flex items-center justify-center p-2 overflow-hidden min-h-0">
+ <Player
+ key={playerKey}
+ ref={iframeRef}
+ projectId={directUrl ? undefined : projectId}
+ directUrl={directUrl}
+ onLoad={onIframeLoad}
+ portrait={portrait}
+ />
+ </div>
+ </div>
+ );
+});
diff --git a/packages/studio/src/components/ui/Button.tsx b/packages/studio/src/components/ui/Button.tsx
new file mode 100644
index 0000000000..f0a24ac424
--- /dev/null
+++ b/packages/studio/src/components/ui/Button.tsx
@@ -0,0 +1,123 @@
+/**
+ * Button & IconButton — The most important primitive.
+ *
+ * Absorbs: active state (scale 0.98), hit target (min 32px),
+ * shadow anatomy (primary), focus ring, disabled state,
+ * loading state, reduced motion, proper timing tokens.
+ *
+ * Rules applied:
+ * - physics-active-state: scale(0.98) on :active
+ * - ux-fitts-target-size: min 32px hit target
+ * - visual-button-shadow-anatomy: 6-layer shadow on primary
+ * - duration-press-hover: 120ms press, 150ms hover
+ */
+
+import { forwardRef, type ButtonHTMLAttributes, type ReactNode } from "react";
+
+// -- Button --
+
+type ButtonVariant = "primary" | "secondary" | "danger" | "ghost";
+type ButtonSize = "sm" | "md" | "lg";
+
+interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
+ variant?: ButtonVariant;
+ size?: ButtonSize;
+ loading?: boolean;
+ icon?: ReactNode;
+}
+
+const variantStyles: Record<ButtonVariant, string> = {
+ primary: [
+ "bg-white text-neutral-950 font-medium",
+ "shadow-btn-primary",
+ "hover:bg-neutral-200",
+ "active:scale-[0.97]",
+ ].join(" "),
+ secondary: [
+ "bg-transparent text-neutral-300 font-medium",
+ "border border-border",
+ "hover:bg-surface-hover hover:text-white hover:border-border-strong",
+ "active:scale-[0.98]",
+ ].join(" "),
+ danger: ["bg-accent-red text-white font-medium", "hover:bg-red-600", "active:scale-[0.97]"].join(" "),
+ ghost: ["bg-transparent text-neutral-400", "hover:bg-surface-hover hover:text-white", "active:scale-[0.98]"].join(
+ " ",
+ ),
+};
+
+const sizeStyles: Record<ButtonSize, string> = {
+ sm: "h-7 px-2.5 text-xs gap-1.5 rounded-button",
+ md: "h-8 px-3 text-sm gap-1.5 rounded-button",
+ lg: "h-9 px-4 text-base gap-2 rounded-button",
+};
+
+export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
+ ({ variant = "secondary", size = "md", loading, icon, children, className = "", disabled, ...props }, ref) => {
+ return (
+ <button
+ ref={ref}
+ disabled={disabled || loading}
+ className={[
+ "inline-flex items-center justify-center",
+ "transition-all duration-press ease-standard",
+ "disabled:opacity-40 disabled:pointer-events-none",
+ "select-none cursor-pointer",
+ variantStyles[variant],
+ sizeStyles[size],
+ className,
+ ].join(" ")}
+ {...props}
+ >
+ {loading ? (
+ <svg className="animate-spin h-3.5 w-3.5" viewBox="0 0 24 24" fill="none">
+ <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
+ <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
+ </svg>
+ ) : icon ? (
+ <span className="flex-shrink-0">{icon}</span>
+ ) : null}
+ {children && <span>{children}</span>}
+ </button>
+ );
+ },
+);
+Button.displayName = "Button";
+
+// -- IconButton --
+// For icon-only buttons. Enforces min 32px hit target.
+
+interface IconButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
+ icon: ReactNode;
+ size?: ButtonSize;
+ variant?: ButtonVariant;
+ "aria-label": string; // REQUIRED for accessibility
+}
+
+const iconSizeStyles: Record<ButtonSize, string> = {
+ sm: "min-w-7 min-h-7 rounded-button", // 28px
+ md: "min-w-8 min-h-8 rounded-button", // 32px — minimum recommended
+ lg: "min-w-9 min-h-9 rounded-button", // 36px
+};
+
+export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(
+ ({ icon, size = "md", variant = "ghost", className = "", ...props }, ref) => {
+ return (
+ <button
+ ref={ref}
+ className={[
+ "inline-flex items-center justify-center",
+ "transition-all duration-press ease-standard",
+ "disabled:opacity-40 disabled:pointer-events-none",
+ "select-none cursor-pointer",
+ variantStyles[variant],
+ iconSizeStyles[size],
+ className,
+ ].join(" ")}
+ {...props}
+ >
+ {icon}
+ </button>
+ );
+ },
+);
+IconButton.displayName = "IconButton";
diff --git a/packages/studio/src/components/ui/index.ts b/packages/studio/src/components/ui/index.ts
new file mode 100644
index 0000000000..3f5812e0c2
--- /dev/null
+++ b/packages/studio/src/components/ui/index.ts
@@ -0,0 +1,2 @@
+// Minimal UI primitives for studio canvas components
+export { Button, IconButton } from "./Button";
diff --git a/packages/studio/src/hooks/useCodeEditor.ts b/packages/studio/src/hooks/useCodeEditor.ts
new file mode 100644
index 0000000000..d9c552e894
--- /dev/null
+++ b/packages/studio/src/hooks/useCodeEditor.ts
@@ -0,0 +1,82 @@
+import { useState, useCallback } from "react";
+
+export interface OpenFile {
+ path: string;
+ content: string;
+ savedContent: string;
+ isDirty: boolean;
+}
+
+export interface UseCodeEditorReturn {
+ openFiles: OpenFile[];
+ activeFilePath: string | null;
+ activeFile: OpenFile | null;
+ openFile: (path: string, content: string) => void;
+ closeFile: (path: string) => void;
+ setActiveFile: (path: string) => void;
+ updateContent: (content: string) => void;
+ markSaved: (path: string) => void;
+ /** External update from agent — updates saved content, shows reload indicator */
+ externalUpdate: (path: string, content: string) => void;
+}
+
+export function useCodeEditor(): UseCodeEditorReturn {
+ const [openFiles, setOpenFiles] = useState<OpenFile[]>([]);
+ const [activeFilePath, setActiveFilePath] = useState<string | null>(null);
+
+ const activeFile = openFiles.find((f) => f.path === activeFilePath) ?? null;
+
+ const openFile = useCallback((path: string, content: string) => {
+ setOpenFiles((prev) => {
+ const existing = prev.find((f) => f.path === path);
+ if (existing) return prev;
+ return [...prev, { path, content, savedContent: content, isDirty: false }];
+ });
+ setActiveFilePath(path);
+ }, []);
+
+ const closeFile = useCallback(
+ (path: string) => {
+ setOpenFiles((prev) => prev.filter((f) => f.path !== path));
+ setActiveFilePath((prev) => {
+ if (prev === path) {
+ const remaining = openFiles.filter((f) => f.path !== path);
+ return remaining.length > 0 ? remaining[remaining.length - 1].path : null;
+ }
+ return prev;
+ });
+ },
+ [openFiles],
+ );
+
+ const updateContent = useCallback(
+ (content: string) => {
+ setOpenFiles((prev) =>
+ prev.map((f) => (f.path === activeFilePath ? { ...f, content, isDirty: content !== f.savedContent } : f)),
+ );
+ },
+ [activeFilePath],
+ );
+
+ const markSaved = useCallback((path: string) => {
+ setOpenFiles((prev) => prev.map((f) => (f.path === path ? { ...f, savedContent: f.content, isDirty: false } : f)));
+ }, []);
+
+ const externalUpdate = useCallback((path: string, content: string) => {
+ setOpenFiles((prev) =>
+ prev.map((f) => (f.path === path ? { ...f, savedContent: content, content, isDirty: false } : f)),
+ );
+ }, []);
+
+ return {
+ openFiles,
+ activeFilePath,
+ activeFile,
+ openFile,
+ closeFile,
+ setActiveFile: setActiveFilePath,
+ updateContent,
+ markSaved,
+ externalUpdate,
+ };
+}
diff --git a/packages/studio/src/hooks/useElementPicker.ts b/packages/studio/src/hooks/useElementPicker.ts
new file mode 100644
index 0000000000..5060f4153d
--- /dev/null
+++ b/packages/studio/src/hooks/useElementPicker.ts
@@ -0,0 +1,338 @@
+import { useState, useCallback, useRef } from "react";
+import { useMountEffect } from "./useMountEffect";
+import { resolveSourceFile, applyPatch } from "../utils/sourcePatcher";
+
+export interface PickedElement {
+ id: string | null;
+ tagName: string;
+ selector: string;
+ label: string;
+ boundingBox: { x: number; y: number; width: number; height: number };
+ textContent: string | null;
+ src: string | null;
+ dataAttributes: Record<string, string>;
+ computedStyles: Record<string, string>;
+}
+
+interface UseElementPickerReturn {
+ isPickMode: boolean;
+ pickedElement: PickedElement | null;
+ enablePick: () => void;
+ disablePick: () => void;
+ clearPick: () => void;
+ /** Update a CSS property on the picked element live + persist to source */
+ setStyle: (prop: string, value: string) => void;
+ /** Update a data attribute on the picked element + persist to source */
+ setDataAttr: (attr: string, value: string) => void;
+ /** Update the text content of the picked element + persist to source */
+ setTextContent: (text: string) => void;
+ /** Override the active iframe (for zoomed canvas view). Pass null to restore primary. */
+ setActiveIframe: (el: HTMLIFrameElement | null) => void;
+ /** Ref that always points to the active iframe (focused canvas frame or preview panel) */
+ activeIframeRef: React.RefObject<HTMLIFrameElement | null>;
+}
+
+interface PickerOptions {
+ /** Workspace files for source patching */
+ workspaceFiles?: Record<string, string>;
+ /** Callback to sync patched files to the project */
+ onSyncFiles?: (files: Record<string, string>) => void;
+}
+
+/**
+ * Hook for element picking via the HyperFrame runtime's picker API.
+ * Communicates with the iframe via postMessage.
+ */
+export function useElementPicker(
+ iframeRef: React.RefObject<HTMLIFrameElement | null>,
+ options?: PickerOptions,
+): UseElementPickerReturn {
+ const [isPickMode, setIsPickMode] = useState(false);
+ const [pickedElement, setPickedElement] = useState<PickedElement | null>(null);
+
+ // Secondary/override iframe ref — set when a zoomed frame is active.
+ // When set, all postMessage sends and DOM reads go to this ref instead.
+ const activeOverrideRef = useRef<HTMLIFrameElement | null>(null);
+
+ const getActiveIframe = useCallback((): HTMLIFrameElement | null => {
+ return activeOverrideRef.current ?? iframeRef.current;
+ }, [iframeRef]);
+
+ // Exposed so the host page can wire the focused view's iframe into the picker
+ const setActiveIframe = useCallback((el: HTMLIFrameElement | null) => {
+ activeOverrideRef.current = el;
+ }, []);
+
+ const enablePick = useCallback(() => {
+ try {
+ getActiveIframe()?.contentWindow?.postMessage(
+ { source: "hf-parent", type: "control", action: "enable-pick-mode" },
+ "*",
+ );
+ setIsPickMode(true);
+ } catch {
+ /* cross-origin */
+ }
+ }, [getActiveIframe]);
+
+ const disablePick = useCallback(() => {
+ try {
+ getActiveIframe()?.contentWindow?.postMessage(
+ { source: "hf-parent", type: "control", action: "disable-pick-mode" },
+ "*",
+ );
+ } catch {
+ /* cross-origin */
+ }
+ setIsPickMode(false);
+ }, [getActiveIframe]);
+
+ const clearPick = useCallback(() => {
+ setPickedElement(null);
+ }, []);
+
+ // Listen for picker messages from the iframe
+ useMountEffect(() => {
+ const handleMessage = (e: MessageEvent) => {
+ const data = e.data;
+ if (data?.source !== "hf-preview") return;
+ // Accept events from either the primary iframe or the active override
+ const activeIframe = getActiveIframe();
+ if (!activeIframe) return;
+ if (e.source !== activeIframe.contentWindow && e.source !== iframeRef.current?.contentWindow) return;
+
+ if (data.type === "element-picked") {
+ const el = data.elementInfo;
+ if (el) {
+ const styles = readComputedStyles(activeIframe, el.selector);
+ setPickedElement({
+ id: el.id ?? null,
+ tagName: el.tagName ?? "div",
+ selector: el.selector ?? "",
+ label: el.label ?? el.tagName ?? "Element",
+ boundingBox: el.boundingBox ?? { x: 0, y: 0, width: 0, height: 0 },
+ textContent: el.textContent ?? null,
+ src: el.src ?? null,
+ dataAttributes: el.dataAttributes ?? {},
+ computedStyles: styles,
+ });
+ setIsPickMode(false);
+ }
+ } else if (data.type === "element-pick-candidates") {
+ // Multiple candidates at click point — pick the first one
+ const el = data.candidates?.[data.selectedIndex ?? 0];
+ if (el) {
+ const styles = readComputedStyles(activeIframe, el.selector);
+ setPickedElement({
+ id: el.id ?? null,
+ tagName: el.tagName ?? "div",
+ selector: el.selector ?? "",
+ label: el.label ?? el.tagName ?? "Element",
+ boundingBox: el.boundingBox ?? { x: 0, y: 0, width: 0, height: 0 },
+ textContent: el.textContent ?? null,
+ src: el.src ?? null,
+ dataAttributes: el.dataAttributes ?? {},
+ computedStyles: styles,
+ });
+ }
+ }
+
+ if (data.type === "pick-mode-cancelled") {
+ setIsPickMode(false);
+ }
+ };
+
+ window.addEventListener("message", handleMessage);
+ return () => window.removeEventListener("message", handleMessage);
+ });
+
+ // Ref for options to avoid stale closures in debounced callback
+ const optionsRef = useRef(options);
+ optionsRef.current = options;
+
+ // Sync immediately (not debounced) — save on every change for reliability
+ const syncToSource = useCallback(
+ (
+ elementId: string,
+ selector: string,
+ op: { type: "inline-style" | "attribute" | "text-content"; property: string; value: string },
+ ) => {
+ const opts = optionsRef.current;
+ if (!opts?.workspaceFiles || !opts.onSyncFiles || !elementId) return;
+ const files = opts.workspaceFiles;
+ const sourceFile = resolveSourceFile(elementId, selector, files);
+ if (!sourceFile || !files[sourceFile]) {
+ return;
+ }
+ const patched = applyPatch(files[sourceFile], elementId, op);
+ if (patched !== files[sourceFile]) {
+ opts.onSyncFiles({ [sourceFile]: patched });
+ }
+ },
+ [],
+ );
+
+ const setStyle = useCallback(
+ (prop: string, value: string) => {
+ const activeIframe = getActiveIframe();
+ if (!pickedElement?.selector || !activeIframe) return;
+ try {
+ const doc = activeIframe.contentDocument;
+ const el = doc?.querySelector(pickedElement.selector) as HTMLElement | null;
+ if (el) {
+ el.style.setProperty(prop, value);
+ setPickedElement((prev) =>
+ prev
+ ? {
+ ...prev,
+ computedStyles: { ...prev.computedStyles, [prop]: value },
+ }
+ : null,
+ );
+ // Persist to source file
+ if (pickedElement.id) {
+ // ID-based patching — surgical edit of just the element's style
+ syncToSource(pickedElement.id, pickedElement.selector, { type: "inline-style", property: prop, value });
+ } else {
+ // No ID — save the full composition HTML from the iframe
+ // This captures ALL inline style changes, not just the targeted one
+ try {
+ const fullHtml = activeIframe.contentDocument?.documentElement.outerHTML;
+ if (fullHtml && optionsRef.current?.onSyncFiles) {
+ // Determine which file this iframe represents
+ const src = activeIframe.getAttribute("src") ?? "";
+ const compMatch = src.match(/\/comp\/(.+?)(?:\?|$)/);
+ const filePath = compMatch ? compMatch[1] : "index.html";
+ optionsRef.current.onSyncFiles({ [filePath]: `<!DOCTYPE html>\n<html>${fullHtml.replace(/<html[^>]*>/, "")}` });
+ }
+ } catch { /* cross-origin */ }
+ }
+ }
+ } catch {
+ /* cross-origin */
+ }
+ },
+ [pickedElement, getActiveIframe, syncToSource],
+ );
+
+ const setDataAttr = useCallback(
+ (attr: string, value: string) => {
+ const activeIframe = getActiveIframe();
+ if (!pickedElement?.selector || !activeIframe) return;
+ try {
+ const doc = activeIframe.contentDocument;
+ const el = doc?.querySelector(pickedElement.selector);
+ if (el) {
+ el.setAttribute(`data-${attr}`, value);
+ setPickedElement((prev) =>
+ prev
+ ? {
+ ...prev,
+ dataAttributes: { ...prev.dataAttributes, [attr]: value },
+ }
+ : null,
+ );
+ // Persist to source file immediately
+ if (pickedElement.id) {
+ syncToSource(pickedElement.id, pickedElement.selector, { type: "attribute", property: attr, value });
+ }
+ }
+ } catch {
+ /* cross-origin */
+ }
+ },
+ [pickedElement, getActiveIframe, syncToSource],
+ );
+
+ const setTextContent = useCallback(
+ (text: string) => {
+ const activeIframe = getActiveIframe();
+ if (!pickedElement?.selector || !activeIframe) return;
+ try {
+ const doc = activeIframe.contentDocument;
+ const el = doc?.querySelector(pickedElement.selector);
+ if (el) {
+ el.textContent = text;
+ setPickedElement((prev) => (prev ? { ...prev, textContent: text } : null));
+ // Persist to source file
+ if (pickedElement.id) {
+ syncToSource(pickedElement.id, pickedElement.selector, {
+ type: "text-content",
+ property: "textContent",
+ value: text,
+ });
+ }
+ }
+ } catch {
+ /* cross-origin */
+ }
+ },
+ [pickedElement, getActiveIframe, syncToSource],
+ );
+
+ // Ref-like object that always points to the active iframe (override or primary)
+ const activeIframeRef = useRef<HTMLIFrameElement | null>(null);
+ activeIframeRef.current = getActiveIframe();
+
+ return {
+ isPickMode,
+ pickedElement,
+ enablePick,
+ disablePick,
+ clearPick,
+ setStyle,
+ setDataAttr,
+ setTextContent,
+ setActiveIframe,
+ /** Ref that always points to the active iframe (focused canvas frame or preview panel) */
+ activeIframeRef,
+ };
+}
+
+/** Read a subset of computed styles from an element in the iframe */
+function readComputedStyles(iframe: HTMLIFrameElement, selector: string): Record<string, string> {
+ const styles: Record<string, string> = {};
+ try {
+ const doc = iframe.contentDocument;
+ const el = doc?.querySelector(selector);
+ if (!el) return styles;
+ const computed = iframe.contentWindow?.getComputedStyle(el);
+ if (!computed) return styles;
+
+ const props = [
+ "position",
+ "top",
+ "left",
+ "right",
+ "bottom",
+ "width",
+ "height",
+ "margin-top",
+ "margin-right",
+ "margin-bottom",
+ "margin-left",
+ "padding-top",
+ "padding-right",
+ "padding-bottom",
+ "padding-left",
+ "font-size",
+ "font-weight",
+ "font-family",
+ "color",
+ "background-color",
+ "background",
+ "opacity",
+ "border-radius",
+ "transform",
+ "z-index",
+ ];
+
+ for (const prop of props) {
+ const val = computed.getPropertyValue(prop);
+ if (val) styles[prop] = val;
+ }
+ } catch {
+ /* cross-origin */
+ }
+ return styles;
+}
diff --git a/packages/studio/src/hooks/useMountEffect.ts b/packages/studio/src/hooks/useMountEffect.ts
new file mode 100644
index 0000000000..28e12612f9
--- /dev/null
+++ b/packages/studio/src/hooks/useMountEffect.ts
@@ -0,0 +1,18 @@
+import { useEffect } from "react";
+
+/**
+ * Run an effect exactly once on mount (and optional cleanup on unmount).
+ * This is the ONLY sanctioned way to call useEffect in this codebase.
+ *
+ * If you need to react to prop/state changes, use one of:
+ * - Derived state (compute inline, no hook needed)
+ * - Event handlers (onClick, onChange, etc.)
+ * - `key` prop to force remount
+ * - Data-fetching library (useQuery, useSWR)
+ *
+ * @see https://react.dev/learn/you-might-not-need-an-effect
+ */
+export function useMountEffect(effect: () => void | (() => void)) {
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ useEffect(effect, []);
+}
diff --git a/packages/studio/src/icons/SystemIcons.tsx b/packages/studio/src/icons/SystemIcons.tsx
new file mode 100644
index 0000000000..e3df7dc89b
--- /dev/null
+++ b/packages/studio/src/icons/SystemIcons.tsx
@@ -0,0 +1,130 @@
+import {
+ WarningCircle,
+ Warning,
+ ArrowLeft as PhArrowLeft,
+ Check as PhCheck,
+ CheckCircle as PhCheckCircle,
+ Circle as PhCircle,
+ Clock as PhClock,
+ Code as PhCode,
+ DownloadSimple,
+ Pencil as PhPencil,
+ ArrowSquareOut,
+ Eye as PhEye,
+ EyeClosed,
+ File as PhFile,
+ FileCode as PhFileCode,
+ FileText as PhFileText,
+ FilmStrip,
+ Heart as PhHeart,
+ Image as PhImage,
+ Info as PhInfo,
+ Stack,
+ SpinnerGap,
+ ArrowsOut,
+ CornersOut,
+ ChatCircle,
+ ChatCenteredText,
+ Cursor,
+ ArrowsOutCardinal,
+ MusicNote,
+ Palette as PhPalette,
+ Paperclip as PhPaperclip,
+ Pause as PhPause,
+ Play as PhPlay,
+ Plus as PhPlus,
+ MagnifyingGlass,
+ PaperPlaneRight,
+ SkipBack as PhSkipBack,
+ SkipForward as PhSkipForward,
+ Square as PhSquare,
+ Trash,
+ TextT,
+ UploadSimple,
+ User as PhUser,
+ UsersThree,
+ VideoCamera,
+ X as PhX,
+ Lightning,
+ MagnifyingGlassPlus,
+ MagnifyingGlassMinus,
+ Terminal as PhTerminal,
+ CaretDown,
+ CaretRight,
+ ClipboardText,
+ ArrowCounterClockwise,
+ Gear,
+} from "@phosphor-icons/react";
+import type { Icon as PhosphorIcon, IconProps as PhosphorIconProps } from "@phosphor-icons/react";
+
+type IconProps = PhosphorIconProps & { title?: string };
+
+const makeIcon = (Icon: PhosphorIcon) => {
+ const Wrapped = ({ title, ...props }: IconProps) => (
+ <Icon alt={title} aria-label={title} aria-hidden={title ? undefined : true} {...props} />
+ );
+ return Wrapped;
+};
+
+// Lucide name → Phosphor equivalent
+export const AlertCircle = makeIcon(WarningCircle);
+export const AlertTriangle = makeIcon(Warning);
+export const ArrowLeft = makeIcon(PhArrowLeft);
+export const Check = makeIcon(PhCheck);
+export const CheckCircle = makeIcon(PhCheckCircle);
+/** CheckCircle2 in lucide is visually identical to CheckCircle */
+export const CheckCircle2 = makeIcon(PhCheckCircle);
+export const Circle = makeIcon(PhCircle);
+export const Clock = makeIcon(PhClock);
+export const Code = makeIcon(PhCode);
+export const Download = makeIcon(DownloadSimple);
+export const Edit2 = makeIcon(PhPencil);
+export const ExternalLink = makeIcon(ArrowSquareOut);
+export const Eye = makeIcon(PhEye);
+export const EyeOff = makeIcon(EyeClosed);
+export const File = makeIcon(PhFile);
+export const FileCode = makeIcon(PhFileCode);
+// FileIcon alias (lucide exports both `File` and `FileIcon`)
+export const FileIcon = makeIcon(PhFile);
+export const FileText = makeIcon(PhFileText);
+export const Film = makeIcon(FilmStrip);
+export const Heart = makeIcon(PhHeart);
+export const Image = makeIcon(PhImage);
+export const Info = makeIcon(PhInfo);
+export const Layers = makeIcon(Stack);
+export const Loader2 = makeIcon(SpinnerGap);
+export const Maximize = makeIcon(ArrowsOut);
+export const Maximize2 = makeIcon(CornersOut);
+export const MessageCircle = makeIcon(ChatCircle);
+export const MessageSquare = makeIcon(ChatCenteredText);
+export const MousePointer = makeIcon(Cursor);
+export const Move = makeIcon(ArrowsOutCardinal);
+export const Music = makeIcon(MusicNote);
+export const Palette = makeIcon(PhPalette);
+export const Paperclip = makeIcon(PhPaperclip);
+export const Pause = makeIcon(PhPause);
+export const Pencil = makeIcon(PhPencil);
+export const Play = makeIcon(PhPlay);
+export const Plus = makeIcon(PhPlus);
+export const Search = makeIcon(MagnifyingGlass);
+export const Send = makeIcon(PaperPlaneRight);
+export const SkipBack = makeIcon(PhSkipBack);
+export const SkipForward = makeIcon(PhSkipForward);
+export const Square = makeIcon(PhSquare);
+export const Trash2 = makeIcon(Trash);
+export const Type = makeIcon(TextT);
+export const Upload = makeIcon(UploadSimple);
+export const User = makeIcon(PhUser);
+export const Users = makeIcon(UsersThree);
+export const Video = makeIcon(VideoCamera);
+export const X = makeIcon(PhX);
+export const Zap = makeIcon(Lightning);
+export const ZoomIn = makeIcon(MagnifyingGlassPlus);
+export const ZoomOut = makeIcon(MagnifyingGlassMinus);
+// Extra icons used in this project (not in lucide's default mapping above)
+export const Terminal = makeIcon(PhTerminal);
+export const ChevronDown = makeIcon(CaretDown);
+export const ChevronRight = makeIcon(CaretRight);
+export const ClipboardList = makeIcon(ClipboardText);
+export const RotateCcw = makeIcon(ArrowCounterClockwise);
+export const Settings = makeIcon(Gear);
diff --git a/packages/studio/src/index.ts b/packages/studio/src/index.ts
new file mode 100644
index 0000000000..5ead3f48b9
--- /dev/null
+++ b/packages/studio/src/index.ts
@@ -0,0 +1,31 @@
+// NLE Layout
+export { NLELayout } from "./components/nle/NLELayout";
+export { NLEPreview } from "./components/nle/NLEPreview";
+export { CompositionBreadcrumb } from "./components/nle/CompositionBreadcrumb";
+export type { CompositionLevel } from "./components/nle/CompositionBreadcrumb";
+
+// Player (preview, timeline, playback controls)
+export {
+ Player,
+ PlayerControls,
+ Timeline,
+ PreviewPanel,
+ AgentActivityTrack,
+ useTimelinePlayer,
+ usePlayerStore,
+ liveTime,
+ formatTime,
+} from "./player";
+export type { AgentActivity, TimelineElement, ActiveEdits } from "./player";
+
+// Editor
+export { SourceEditor } from "./components/editor/SourceEditor";
+export { PropertyPanel } from "./components/editor/PropertyPanel";
+export { FileTree } from "./components/editor/FileTree";
+
+// App
+export { StudioApp } from "./App";
+
+// Hooks
+export { useCodeEditor } from "./hooks/useCodeEditor";
+export { useElementPicker } from "./hooks/useElementPicker";
diff --git a/packages/studio/src/main.tsx b/packages/studio/src/main.tsx
new file mode 100644
index 0000000000..12e93ed283
--- /dev/null
+++ b/packages/studio/src/main.tsx
@@ -0,0 +1,10 @@
+import { StrictMode } from "react";
+import { createRoot } from "react-dom/client";
+import { StudioApp } from "./App";
+import "./styles/studio.css";
+
+createRoot(document.getElementById("root")!).render(
+ <StrictMode>
+ <StudioApp />
+ </StrictMode>,
+);
diff --git a/packages/studio/src/player/components/AgentActivityTrack.tsx b/packages/studio/src/player/components/AgentActivityTrack.tsx
new file mode 100644
index 0000000000..cef10e8e26
--- /dev/null
+++ b/packages/studio/src/player/components/AgentActivityTrack.tsx
@@ -0,0 +1,98 @@
+import { memo } from "react";
+
+const TRACK_H = 20;
+const GUTTER = 32;
+
+export interface AgentActivity {
+ agentId: string;
+ name: string;
+ color: string;
+ /** Active work periods mapped to VIDEO time (not wall clock) */
+ periods: Array<{ start: number; end: number }>;
+ /** Element creation events at specific video times */
+ events: Array<{ time: number; type: "create" | "modify" }>;
+}
+
+interface AgentActivityTrackProps {
+ agents: AgentActivity[];
+ duration: number;
+}
+
+export const AgentActivityTrack = memo(function AgentActivityTrack({ agents, duration }: AgentActivityTrackProps) {
+ if (agents.length === 0 || duration <= 0) return null;
+
+ return (
+ <div className="border-t border-neutral-800/30">
+ {/* Section header */}
+ <div className="flex items-center gap-1.5 px-2 py-1 text-[9px] text-neutral-600 font-medium uppercase tracking-wider">
+ <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="12" r="4" /></svg>
+ Agent Activity
+ </div>
+
+ {agents.map((agent) => (
+ <div
+ key={agent.agentId}
+ className="relative flex"
+ style={{ height: TRACK_H }}
+ >
+ {/* Gutter: agent name */}
+ <div
+ className="flex-shrink-0 flex items-center justify-center"
+ style={{ width: GUTTER }}
+ title={agent.name}
+ >
+ <div
+ className="w-2 h-2 rounded-full"
+ style={{ backgroundColor: agent.color }}
+ />
+ </div>
+
+ {/* Lane */}
+ <div className="flex-1 relative" style={{ backgroundColor: `${agent.color}06` }}>
+ {/* Active work periods */}
+ {agent.periods.map((period, i) => {
+ const leftPct = (period.start / duration) * 100;
+ const widthPct = ((period.end - period.start) / duration) * 100;
+ return (
+ <div
+ key={`period-${i}`}
+ className="absolute top-1 bottom-1 rounded-sm"
+ style={{
+ left: `${leftPct}%`,
+ width: `${Math.max(widthPct, 0.5)}%`,
+ backgroundColor: `${agent.color}30`,
+ border: `1px solid ${agent.color}20`,
+ }}
+ />
+ );
+ })}
+
+ {/* Events: diamonds for create, circles for modify */}
+ {agent.events.map((event, i) => {
+ const leftPct = (event.time / duration) * 100;
+ return (
+ <div
+ key={`event-${i}`}
+ className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2"
+ style={{ left: `${leftPct}%` }}
+ >
+ {event.type === "create" ? (
+ <div
+ className="w-2 h-2 rotate-45"
+ style={{ backgroundColor: agent.color }}
+ />
+ ) : (
+ <div
+ className="w-1.5 h-1.5 rounded-full"
+ style={{ backgroundColor: agent.color }}
+ />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+});
diff --git a/packages/studio/src/player/components/Player.tsx b/packages/studio/src/player/components/Player.tsx
new file mode 100644
index 0000000000..1754b58cd2
--- /dev/null
+++ b/packages/studio/src/player/components/Player.tsx
@@ -0,0 +1,120 @@
+import { forwardRef, useRef, useState, useCallback } from "react";
+import { useMountEffect } from "../lib/useMountEffect";
+
+const NATIVE_W = 1920;
+const NATIVE_H = 1080;
+
+interface PlayerProps {
+ projectId?: string;
+ directUrl?: string;
+ onLoad: () => void;
+ portrait?: boolean;
+}
+
+export const Player = forwardRef<HTMLIFrameElement, PlayerProps>(({ projectId, directUrl, onLoad, portrait }, ref) => {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [scale, setScale] = useState(1);
+ const dimsRef = useRef({ w: portrait ? NATIVE_H : NATIVE_W, h: portrait ? NATIVE_W : NATIVE_H });
+ const [dims, setDims] = useState(dimsRef.current);
+ const loadCountRef = useRef(0);
+
+ const updateScale = useCallback(() => {
+ const el = containerRef.current;
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+ const d = dimsRef.current;
+ setScale(Math.min(rect.width / d.w, rect.height / d.h));
+ }, []);
+
+ useMountEffect(() => {
+ updateScale();
+ const ro = new ResizeObserver(updateScale);
+ if (containerRef.current) ro.observe(containerRef.current);
+
+ // Listen for stage-size messages from the runtime
+ const handleMessage = (e: MessageEvent) => {
+ const data = e.data;
+ if ((data?.source === "hf-preview" || data?.source === "hf-preview") && data?.type === "stage-size" && data.width > 0 && data.height > 0) {
+ if (dimsRef.current.w !== data.width || dimsRef.current.h !== data.height) {
+ dimsRef.current = { w: data.width, h: data.height };
+ setDims(dimsRef.current);
+ updateScale();
+ }
+ }
+ };
+ window.addEventListener("message", handleMessage);
+
+ return () => {
+ ro.disconnect();
+ window.removeEventListener("message", handleMessage);
+ };
+ });
+
+ const handleLoad = useCallback(() => {
+ loadCountRef.current++;
+
+ // Auto-detect dimensions from the composition's data-width/data-height
+ try {
+ const iframeEl = typeof ref === "function" ? null : ref?.current;
+ const doc = iframeEl?.contentDocument;
+ if (doc) {
+ const root = doc.querySelector("[data-composition-id]");
+ if (root) {
+ const dw = parseInt(root.getAttribute("data-width") || "0", 10);
+ const dh = parseInt(root.getAttribute("data-height") || "0", 10);
+ if (dw > 0 && dh > 0 && (dw !== dimsRef.current.w || dh !== dimsRef.current.h)) {
+ dimsRef.current = { w: dw, h: dh };
+ setDims(dimsRef.current);
+ // Recalc scale with new dims
+ const el = containerRef.current;
+ if (el) {
+ const rect = el.getBoundingClientRect();
+ setScale(Math.min(rect.width / dw, rect.height / dh));
+ }
+ }
+ }
+ }
+ } catch {
+ // Cross-origin
+ }
+
+ if (loadCountRef.current > 1) {
+ const el = containerRef.current;
+ if (el) {
+ el.classList.remove("preview-revealing");
+ void el.offsetWidth;
+ el.classList.add("preview-revealing");
+ const onEnd = () => el.classList.remove("preview-revealing");
+ el.addEventListener("animationend", onEnd, { once: true });
+ }
+ }
+ onLoad();
+ }, [onLoad, ref]);
+
+ return (
+ <div
+ ref={containerRef}
+ className="w-full h-full max-w-full max-h-full overflow-hidden shadow-float border border-neutral-800 bg-black flex items-center justify-center rounded-card-inner"
+ >
+ <iframe
+ ref={ref}
+ src={directUrl || `/api/projects/${projectId}/preview`}
+ onLoad={handleLoad}
+ sandbox="allow-scripts allow-same-origin"
+ allow="autoplay; fullscreen"
+ referrerPolicy="no-referrer"
+ title="Project Preview"
+ style={{
+ width: dims.w,
+ height: dims.h,
+ border: "none",
+ transform: `scale(${scale})`,
+ transformOrigin: "center center",
+ flexShrink: 0,
+ }}
+ />
+ </div>
+ );
+});
+
+Player.displayName = "Player";
diff --git a/packages/studio/src/player/components/PlayerControls.tsx b/packages/studio/src/player/components/PlayerControls.tsx
new file mode 100644
index 0000000000..0bf9cb5147
--- /dev/null
+++ b/packages/studio/src/player/components/PlayerControls.tsx
@@ -0,0 +1,181 @@
+import { useRef, useState, useCallback, memo } from "react";
+import { formatTime } from "../lib/time";
+import { usePlayerStore, liveTime } from "../store/playerStore";
+import { useMountEffect } from "../lib/useMountEffect";
+
+const SPEED_OPTIONS = [0.25, 0.5, 1, 1.5, 2] as const;
+
+interface PlayerControlsProps {
+ /** @deprecated Pass via store — kept for backwards compat */
+ isPlaying?: boolean;
+ /** @deprecated Pass via store — kept for backwards compat */
+ duration?: number;
+ /** @deprecated Pass via store — kept for backwards compat */
+ timelineReady?: boolean;
+ onTogglePlay: () => void;
+ onSeek: (time: number) => void;
+}
+
+export const PlayerControls = memo(function PlayerControls({ onTogglePlay, onSeek, ...overrides }: PlayerControlsProps) {
+ // Subscribe to only the fields we render — each selector prevents cascading re-renders
+ const storeIsPlaying = usePlayerStore((s) => s.isPlaying);
+ const storeDuration = usePlayerStore((s) => s.duration);
+ const storeTimelineReady = usePlayerStore((s) => s.timelineReady);
+ const playbackRate = usePlayerStore((s) => s.playbackRate);
+ const setPlaybackRate = usePlayerStore.getState().setPlaybackRate;
+ const [showSpeedMenu, setShowSpeedMenu] = useState(false);
+
+ const isPlaying = overrides.isPlaying ?? storeIsPlaying;
+ const duration = overrides.duration ?? storeDuration;
+ const timelineReady = overrides.timelineReady ?? storeTimelineReady;
+
+ const progressFillRef = useRef<HTMLDivElement>(null);
+ const progressThumbRef = useRef<HTMLDivElement>(null);
+ const timeDisplayRef = useRef<HTMLSpanElement>(null);
+ const seekBarRef = useRef<HTMLDivElement>(null);
+ const isDraggingRef = useRef(false);
+ const currentTimeRef = useRef(0);
+
+ const durationRef = useRef(duration);
+ durationRef.current = duration;
+ useMountEffect(() => {
+ const unsub = liveTime.subscribe((t) => {
+ currentTimeRef.current = t;
+ const dur = durationRef.current;
+ const pct = dur > 0 ? (t / dur) * 100 : 0;
+ if (progressFillRef.current) progressFillRef.current.style.width = `${pct}%`;
+ if (progressThumbRef.current) progressThumbRef.current.style.left = `${pct}%`;
+ if (timeDisplayRef.current) timeDisplayRef.current.textContent = formatTime(t);
+ });
+ return unsub;
+ });
+
+ const seekFromClientX = useCallback(
+ (clientX: number) => {
+ const bar = seekBarRef.current;
+ if (!bar || duration <= 0) return;
+ const rect = bar.getBoundingClientRect();
+ const percent = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
+ onSeek(percent * duration);
+ },
+ [duration, onSeek],
+ );
+
+ const handleMouseDown = useCallback(
+ (e: React.MouseEvent) => {
+ e.preventDefault();
+ isDraggingRef.current = true;
+ seekFromClientX(e.clientX);
+
+ const onMouseMove = (me: MouseEvent) => {
+ if (isDraggingRef.current) seekFromClientX(me.clientX);
+ };
+ const onMouseUp = () => {
+ isDraggingRef.current = false;
+ window.removeEventListener("mousemove", onMouseMove);
+ window.removeEventListener("mouseup", onMouseUp);
+ };
+
+ window.addEventListener("mousemove", onMouseMove);
+ window.addEventListener("mouseup", onMouseUp);
+ },
+ [seekFromClientX],
+ );
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (!timelineReady || duration <= 0) return;
+ const step = e.shiftKey ? 5 : 1;
+ if (e.key === "ArrowLeft") {
+ e.preventDefault();
+ onSeek(Math.max(0, currentTimeRef.current - step));
+ } else if (e.key === "ArrowRight") {
+ e.preventDefault();
+ onSeek(Math.min(duration, currentTimeRef.current + step));
+ }
+ },
+ [timelineReady, duration, onSeek],
+ );
+
+ return (
+ <div className="px-3 py-2 flex items-center gap-3">
+ <button
+ type="button"
+ aria-label={isPlaying ? "Pause" : "Play"}
+ onClick={onTogglePlay}
+ disabled={!timelineReady}
+ className="flex-shrink-0 w-7 h-7 flex items-center justify-center rounded-md text-neutral-300 hover:text-white hover:bg-neutral-800 disabled:opacity-40 disabled:pointer-events-none transition-colors"
+ >
+ {isPlaying ? (
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <rect x="6" y="4" width="4" height="16" rx="1" />
+ <rect x="14" y="4" width="4" height="16" rx="1" />
+ </svg>
+ ) : (
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <path d="M8 5v14l11-7z" />
+ </svg>
+ )}
+ </button>
+
+ <span className="text-neutral-500 font-mono text-xs tabular-nums flex-shrink-0 min-w-[80px]">
+ <span ref={timeDisplayRef}>{formatTime(0)}</span>
+ <span className="text-neutral-700 mx-0.5">/</span>
+ <span className="text-neutral-600">{formatTime(duration)}</span>
+ </span>
+
+ <div
+ ref={seekBarRef}
+ role="slider"
+ tabIndex={0}
+ aria-label="Seek"
+ aria-valuemin={0}
+ aria-valuemax={Math.round(duration)}
+ aria-valuenow={0}
+ className="flex-1 h-6 flex items-center cursor-pointer group"
+ style={{ touchAction: "manipulation" }}
+ onMouseDown={handleMouseDown}
+ onKeyDown={handleKeyDown}
+ >
+ <div className="w-full h-[3px] bg-neutral-800 rounded-full relative">
+ <div
+ ref={progressFillRef}
+ className="absolute inset-y-0 left-0 bg-white/80 rounded-full"
+ style={{ width: 0 }}
+ />
+ <div
+ ref={progressThumbRef}
+ className="absolute top-1/2 w-2 h-2 bg-white rounded-full -translate-y-1/2 -translate-x-1/2 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity"
+ style={{ left: 0 }}
+ />
+ </div>
+ </div>
+
+ {/* Speed control */}
+ <div className="relative flex-shrink-0">
+ <button
+ type="button"
+ onClick={() => setShowSpeedMenu((v) => !v)}
+ className="px-1.5 py-0.5 rounded text-[11px] font-mono tabular-nums text-neutral-500 hover:text-neutral-200 hover:bg-neutral-800 transition-colors"
+ >
+ {playbackRate === 1 ? "1x" : `${playbackRate}x`}
+ </button>
+ {showSpeedMenu && (
+ <div className="absolute bottom-full right-0 mb-1 py-1 bg-neutral-900 border border-neutral-700 rounded-lg shadow-xl z-50 min-w-[60px]">
+ {SPEED_OPTIONS.map((rate) => (
+ <button
+ key={rate}
+ onClick={() => { setPlaybackRate(rate); setShowSpeedMenu(false); }}
+ className={`block w-full px-3 py-1 text-xs text-left font-mono tabular-nums transition-colors ${
+ rate === playbackRate ? "text-white bg-neutral-800" : "text-neutral-400 hover:text-white hover:bg-neutral-800"
+ }`}
+ >
+ {rate}x
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+});
diff --git a/packages/studio/src/player/components/PreviewPanel.tsx b/packages/studio/src/player/components/PreviewPanel.tsx
new file mode 100644
index 0000000000..c176286689
--- /dev/null
+++ b/packages/studio/src/player/components/PreviewPanel.tsx
@@ -0,0 +1,149 @@
+import type { ReactNode, Ref } from "react";
+import { Player } from "./Player";
+import { PlayerControls } from "./PlayerControls";
+import { Timeline } from "./Timeline";
+
+interface RenderStatus {
+ state: "idle" | "rendering" | "complete" | "error";
+ stage?: string;
+ progress?: number;
+ error?: string;
+ onRender?: () => void;
+}
+
+interface PreviewPanelProps {
+ projectId: string | null;
+ hasProject: boolean;
+ portrait: boolean;
+ iframeRef: Ref<HTMLIFrameElement>;
+ onIframeLoad: () => void;
+ onTogglePlay: () => void;
+ onSeek: (t: number) => void;
+ /** Optional render status — pass to show rendering progress/state */
+ renderStatus?: RenderStatus;
+ /** Optional slot for custom content below the timeline */
+ children?: ReactNode;
+}
+
+export function PreviewPanel({
+ projectId,
+ hasProject,
+ portrait,
+ iframeRef,
+ onIframeLoad,
+ onTogglePlay,
+ onSeek,
+ renderStatus,
+ children,
+}: PreviewPanelProps) {
+
+ const renderState = renderStatus?.state ?? "idle";
+
+ return (
+ <div
+ className="min-w-0 overflow-hidden"
+ style={{
+ display: "grid",
+ gridTemplateRows: hasProject && projectId ? "1fr auto auto auto" : "1fr",
+ height: "100%",
+ minHeight: 0,
+ }}
+ >
+ {hasProject && projectId ? (
+ <>
+ {/* Player — takes all remaining space, constrained for portrait */}
+ <div className="flex items-center justify-center p-2 overflow-hidden" style={{ minHeight: 0, minWidth: 0 }}>
+ <Player ref={iframeRef} projectId={projectId} onLoad={onIframeLoad} portrait={portrait} />
+ </div>
+
+ {/* Controls — fixed height */}
+ <div className="bg-neutral-950 border-t border-neutral-800 flex-shrink-0">
+ <PlayerControls
+ onTogglePlay={onTogglePlay}
+ onSeek={onSeek}
+ />
+ </div>
+
+ {/* Timeline — capped height, internal scroll */}
+ <div className="bg-neutral-950 flex-shrink-0 overflow-y-auto" style={{ maxHeight: "100px" }}>
+ <Timeline onSeek={onSeek} />
+ </div>
+
+ {/* Render status — only shown when actively rendering, complete, or error */}
+ {renderStatus && (renderState === "rendering" || renderState === "complete" || renderState === "error") && (
+ <div className="bg-neutral-950 border-t border-neutral-800 px-4 py-2 flex items-center justify-end gap-2 flex-shrink-0">
+ {renderState === "rendering" && (
+ <div className="flex-1">
+ <div className="flex items-center gap-2">
+ <div className="flex-1 h-1.5 bg-neutral-800 rounded-full overflow-hidden">
+ <div
+ className="h-full bg-blue-500 rounded-full transition-[width] duration-200"
+ style={{ width: `${renderStatus.progress ?? 0}%` }}
+ />
+ </div>
+ <span className="text-xs text-neutral-400 flex-shrink-0">
+ {renderStatus.stage || "Rendering..."}
+ </span>
+ </div>
+ </div>
+ )}
+ {renderState === "complete" && (
+ <div className="flex items-center gap-1.5 text-xs text-green-400">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
+ <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
+ <polyline points="22 4 12 14.01 9 11.01" />
+ </svg>
+ <span>Complete</span>
+ </div>
+ )}
+ {renderState === "error" && (
+ <div className="flex items-center gap-2 text-xs text-red-400">
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
+ <circle cx="12" cy="12" r="10" />
+ <line x1="12" y1="8" x2="12" y2="12" />
+ <line x1="12" y1="16" x2="12.01" y2="16" />
+ </svg>
+ <span className="truncate">{renderStatus.error}</span>
+ {renderStatus.onRender && (
+ <button
+ type="button"
+ onClick={renderStatus.onRender}
+ className="flex-shrink-0 px-2 py-0.5 text-xs text-neutral-300 hover:text-white hover:bg-neutral-800 rounded transition-colors"
+ >
+ Retry
+ </button>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Optional custom slot */}
+ {children}
+ </>
+ ) : (
+ <div className="flex items-center justify-center w-full min-w-0">
+ <div className="text-center w-full">
+ <div className="w-16 h-16 mx-auto mb-4 rounded-card bg-neutral-900 flex items-center justify-center">
+ <svg
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="text-neutral-600"
+ >
+ <polygon points="5 3 19 12 5 21 5 3" />
+ </svg>
+ </div>
+ <p className="text-sm text-neutral-600">Preview will appear here</p>
+ <p className="text-xs text-neutral-700 mt-1">Send a message to generate a video composition</p>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/studio/src/player/components/Timeline.tsx b/packages/studio/src/player/components/Timeline.tsx
new file mode 100644
index 0000000000..a8834a9be5
--- /dev/null
+++ b/packages/studio/src/player/components/Timeline.tsx
@@ -0,0 +1,431 @@
+import { useRef, useMemo, useCallback, useState, memo, type ReactNode } from "react";
+import { usePlayerStore, liveTime } from "../store/playerStore";
+import { useMountEffect } from "../lib/useMountEffect";
+
+/* ── Layout ─────────────────────────────────────────────────────── */
+const GUTTER = 32;
+const TRACK_H = 28;
+const RULER_H = 24;
+const CLIP_Y = 2; // vertical inset inside track
+
+/* ── Vibrant Color System (Figma-inspired, dark-mode adapted) ──── */
+interface TrackStyle {
+ /** Clip solid background */
+ clip: string;
+ /** Dark text color for label on clip */
+ label: string;
+ /** Track row tint (very subtle) */
+ row: string;
+ /** Gutter icon circle background */
+ gutter: string;
+ /** SVG icon paths (viewBox 0 0 24 24) */
+ icon: ReactNode;
+}
+
+/* ── Icons from Figma HyperFrames design system ── */
+const ICON_BASE = "/icons/timeline";
+function TimelineIcon({ src }: { src: string }) {
+ return <img src={src} alt="" width={12} height={12} style={{ filter: "brightness(0) invert(1)" }} draggable={false} />;
+}
+const IconCaptions = <TimelineIcon src={`${ICON_BASE}/captions.svg`} />;
+const IconImage = <TimelineIcon src={`${ICON_BASE}/image.svg`} />;
+const IconMusic = <TimelineIcon src={`${ICON_BASE}/music.svg`} />;
+const IconText = <TimelineIcon src={`${ICON_BASE}/text.svg`} />;
+const IconComposition = <TimelineIcon src={`${ICON_BASE}/composition.svg`} />;
+const IconAudio = <TimelineIcon src={`${ICON_BASE}/audio.svg`} />;
+
+const STYLES: Record<string, TrackStyle> = {
+ video: {
+ clip: "#1F6AFF",
+ label: "#DBEAFE",
+ row: "rgba(31,106,255,0.04)",
+ gutter: "#1F6AFF",
+ icon: IconImage,
+ },
+ audio: {
+ clip: "#00C4FF",
+ label: "#013A4B",
+ row: "rgba(0,196,255,0.04)",
+ gutter: "#00C4FF",
+ icon: IconMusic,
+ },
+ img: {
+ clip: "#8B5CF6",
+ label: "#EDE9FE",
+ row: "rgba(139,92,246,0.04)",
+ gutter: "#8B5CF6",
+ icon: IconImage,
+ },
+ div: {
+ clip: "#68B200",
+ label: "#1A2B03",
+ row: "rgba(104,178,0,0.04)",
+ gutter: "#68B200",
+ icon: IconComposition,
+ },
+ span: {
+ clip: "#F3A6FF",
+ label: "#8D00A3",
+ row: "rgba(243,166,255,0.04)",
+ gutter: "#F3A6FF",
+ icon: IconCaptions,
+ },
+ p: {
+ clip: "#35C838",
+ label: "#024A03",
+ row: "rgba(53,200,56,0.04)",
+ gutter: "#35C838",
+ icon: IconText,
+ },
+ h1: {
+ clip: "#35C838",
+ label: "#024A03",
+ row: "rgba(53,200,56,0.04)",
+ gutter: "#35C838",
+ icon: IconText,
+ },
+ section: {
+ clip: "#68B200",
+ label: "#1A2B03",
+ row: "rgba(104,178,0,0.04)",
+ gutter: "#68B200",
+ icon: IconComposition,
+ },
+ sfx: {
+ clip: "#FF8C42",
+ label: "#512000",
+ row: "rgba(255,140,66,0.04)",
+ gutter: "#FF8C42",
+ icon: IconAudio,
+ },
+};
+
+const DEFAULT: TrackStyle = {
+ clip: "#6B7280",
+ label: "#F3F4F6",
+ row: "rgba(107,114,128,0.03)",
+ gutter: "#6B7280",
+ icon: IconComposition,
+};
+
+function getStyle(tag: string): TrackStyle {
+ const t = tag.toLowerCase();
+ if (t.startsWith("h") && t.length === 2 && "123456".includes(t[1])) return STYLES.h1;
+ return STYLES[t] ?? DEFAULT;
+}
+
+/* ── Tick Generation ────────────────────────────────────────────── */
+function generateTicks(duration: number): { major: number[]; minor: number[] } {
+ if (duration <= 0) return { major: [], minor: [] };
+ const intervals = [0.5, 1, 2, 5, 10, 15, 30, 60];
+ const target = duration / 6;
+ const majorInterval = intervals.find((i) => i >= target) ?? 60;
+ const minorInterval = majorInterval / 2;
+ const major: number[] = [];
+ const minor: number[] = [];
+ for (let t = 0; t <= duration + 0.001; t += minorInterval) {
+ const rounded = Math.round(t * 100) / 100;
+ const isMajor = Math.abs(rounded % majorInterval) < 0.01 || Math.abs(rounded % majorInterval - majorInterval) < 0.01;
+ if (isMajor) major.push(rounded);
+ else minor.push(rounded);
+ }
+ return { major, minor };
+}
+
+function formatTick(s: number): string {
+ const m = Math.floor(s / 60);
+ const sec = Math.floor(s % 60);
+ return `${m}:${sec.toString().padStart(2, "0")}`;
+}
+
+/* ── Component ──────────────────────────────────────────────────── */
+interface TimelineProps {
+ /** Called when user seeks via ruler/track click or playhead drag */
+ onSeek?: (time: number) => void;
+ /** Called when user double-clicks a composition clip to drill into it */
+ onDrillDown?: (element: import("../store/playerStore").TimelineElement) => void;
+}
+
+export const Timeline = memo(function Timeline({ onSeek, onDrillDown }: TimelineProps = {}) {
+ const elements = usePlayerStore((s) => s.elements);
+ const duration = usePlayerStore((s) => s.duration);
+ const timelineReady = usePlayerStore((s) => s.timelineReady);
+ const selectedElementId = usePlayerStore((s) => s.selectedElementId);
+ const setSelectedElementId = usePlayerStore((s) => s.setSelectedElementId);
+ const activeEdits = usePlayerStore((s) => s.activeEdits);
+ const playheadRef = useRef<HTMLDivElement>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [hoveredClip, setHoveredClip] = useState<string | null>(null);
+ const isDragging = useRef(false);
+
+ const durationRef = useRef(duration);
+ durationRef.current = duration;
+ useMountEffect(() => {
+ const unsub = liveTime.subscribe((t) => {
+ const dur = durationRef.current;
+ if (!playheadRef.current || dur <= 0) return;
+ const pct = (t / dur) * 100;
+ playheadRef.current.style.left = `calc(${GUTTER}px + (100% - ${GUTTER}px) * ${pct / 100})`;
+ });
+ return unsub;
+ });
+
+ const seekFromX = useCallback(
+ (clientX: number) => {
+ const el = containerRef.current;
+ if (!el || duration <= 0) return;
+ const rect = el.getBoundingClientRect();
+ const start = rect.left + GUTTER;
+ const w = rect.width - GUTTER;
+ if (w <= 0) return;
+ const pct = Math.max(0, Math.min(1, (clientX - start) / w));
+ const time = pct * duration;
+ // Notify liveTime for instant visual update (direct DOM, no re-render)
+ liveTime.notify(time);
+ // Call parent's onSeek to actually seek the iframe/player
+ onSeek?.(time);
+ },
+ [duration, onSeek],
+ );
+
+ const handlePointerDown = useCallback(
+ (e: React.PointerEvent) => {
+ if ((e.target as HTMLElement).closest("[data-clip]")) return;
+ isDragging.current = true;
+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
+ seekFromX(e.clientX);
+ },
+ [seekFromX],
+ );
+ const handlePointerMove = useCallback(
+ (e: React.PointerEvent) => { if (isDragging.current) seekFromX(e.clientX); },
+ [seekFromX],
+ );
+ const handlePointerUp = useCallback(() => { isDragging.current = false; }, []);
+
+ const tracks = useMemo(() => {
+ const map = new Map<number, typeof elements>();
+ for (const el of elements) {
+ const list = map.get(el.track) ?? [];
+ list.push(el);
+ map.set(el.track, list);
+ }
+ return Array.from(map.entries()).sort(([a], [b]) => a - b);
+ }, [elements]);
+
+ // Determine dominant style per track (from first element)
+ const trackStyles = useMemo(() => {
+ const map = new Map<number, TrackStyle>();
+ for (const [trackNum, els] of tracks) {
+ map.set(trackNum, getStyle(els[0]?.tag ?? ""));
+ }
+ return map;
+ }, [tracks]);
+
+ const { major, minor } = useMemo(() => generateTicks(duration), [duration]);
+
+ if (!timelineReady) return null;
+ if (elements.length === 0) {
+ return <div className="px-3 py-3 text-2xs text-neutral-600 border-t border-neutral-800/50">No timeline elements</div>;
+ }
+
+ const totalH = RULER_H + tracks.length * TRACK_H;
+
+ return (
+ <div
+ ref={containerRef}
+ aria-label="Timeline"
+ className="border-t border-neutral-800/50 bg-[#0a0a0b] select-none overflow-x-hidden cursor-crosshair"
+ style={{ touchAction: "none" }}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ >
+ <div className="relative" style={{ height: totalH }}>
+ {/* Grid lines */}
+ <svg className="absolute pointer-events-none" style={{ left: GUTTER }} width={`calc(100% - ${GUTTER}px)`} height={totalH}>
+ {major.map((t) => (
+ <line key={`g-${t}`} x1={`${(t / duration) * 100}%`} y1={RULER_H} x2={`${(t / duration) * 100}%`} y2={totalH} stroke="rgba(255,255,255,0.035)" strokeWidth="1" />
+ ))}
+ </svg>
+
+ {/* Ruler */}
+ <div className="relative border-b border-neutral-800/40" style={{ height: RULER_H, marginLeft: GUTTER }}>
+ {minor.map((t) => (
+ <div key={`m-${t}`} className="absolute bottom-0" style={{ left: `${(t / duration) * 100}%` }}>
+ <div className="w-px h-[3px] bg-neutral-700/40" />
+ </div>
+ ))}
+ {major.map((t) => (
+ <div key={`M-${t}`} className="absolute bottom-0 flex flex-col items-center" style={{ left: `${(t / duration) * 100}%` }}>
+ <span className="text-[9px] text-neutral-500 font-mono tabular-nums leading-none mb-0.5">{formatTick(t)}</span>
+ <div className="w-px h-[5px] bg-neutral-600/60" />
+ </div>
+ ))}
+ </div>
+
+ {/* Tracks */}
+ {tracks.map(([trackNum, els]) => {
+ const ts = trackStyles.get(trackNum) ?? DEFAULT;
+ return (
+ <div key={trackNum} className="relative flex" style={{ height: TRACK_H, backgroundColor: ts.row }}>
+ {/* Gutter: colored icon badge (Figma HyperFrames style) */}
+ <div className="flex-shrink-0 flex items-center justify-center" style={{ width: GUTTER }}>
+ <div
+ className="flex items-center justify-center"
+ style={{
+ width: 20,
+ height: 20,
+ borderRadius: 6,
+ backgroundColor: ts.gutter,
+ border: "1px solid rgba(255,255,255,0.35)",
+ color: "#fff",
+ }}
+ >
+ {ts.icon}
+ </div>
+ </div>
+
+ {/* Clips */}
+ <div className="flex-1 relative">
+ {els.map((el, i) => {
+ const leftPct = (el.start / duration) * 100;
+ const widthPct = (el.duration / duration) * 100;
+ const style = getStyle(el.tag);
+ const isSelected = selectedElementId === el.id;
+ const isComposition = !!el.compositionSrc;
+ const clipKey = `${el.id}-${i}`;
+ const isHovered = hoveredClip === clipKey;
+ const activeEdit = activeEdits[el.id];
+ const isBeingEdited = !!activeEdit;
+
+ return (
+ <div
+ key={clipKey}
+ data-clip="true"
+ className="absolute flex items-center overflow-hidden"
+ style={{
+ left: `${leftPct}%`,
+ width: `${Math.max(widthPct, 1)}%`,
+ top: CLIP_Y,
+ bottom: CLIP_Y,
+ borderRadius: 5,
+ backgroundColor: style.clip,
+ backgroundImage: isComposition
+ ? `repeating-linear-gradient(135deg, transparent, transparent 3px, rgba(255,255,255,0.08) 3px, rgba(255,255,255,0.08) 6px)`
+ : undefined,
+ border: isSelected ? `2px solid rgba(255,255,255,0.9)` : `1px solid rgba(255,255,255,${isHovered ? 0.3 : 0.15})`,
+ boxShadow: isSelected
+ ? `0 0 0 1px ${style.clip}, 0 2px 8px rgba(0,0,0,0.4)`
+ : isBeingEdited
+ ? `0 0 0 1px ${activeEdit.agentColor}80, 0 0 8px ${activeEdit.agentColor}40`
+ : isHovered
+ ? "0 1px 4px rgba(0,0,0,0.3)"
+ : "none",
+ cursor: "pointer",
+ transition: "border-color 120ms, box-shadow 120ms, transform 80ms",
+ transform: isHovered && !isSelected ? "scaleY(1.04)" : "scaleY(1)",
+ zIndex: isSelected ? 10 : isHovered ? 5 : 1,
+ }}
+ title={isComposition
+ ? `${el.compositionSrc} \u2022 Double-click to open`
+ : `${el.id || el.tag} \u2022 ${el.start.toFixed(1)}s \u2013 ${(el.start + el.duration).toFixed(1)}s`}
+ onPointerEnter={() => setHoveredClip(clipKey)}
+ onPointerLeave={() => setHoveredClip(null)}
+ onPointerDown={(e) => e.stopPropagation()}
+ onClick={(e) => {
+ e.stopPropagation();
+ setSelectedElementId(isSelected ? null : el.id);
+ }}
+ onDoubleClick={(e) => {
+ e.stopPropagation();
+ if (isComposition && onDrillDown) {
+ onDrillDown(el);
+ }
+ }}
+ >
+ {/* Agent ownership dot */}
+ {el.agentColor && (
+ <div
+ className="flex-shrink-0 w-1.5 h-1.5 rounded-full ml-1"
+ style={{ backgroundColor: el.agentColor }}
+ title={el.agentId ? `Agent: ${el.agentId}` : undefined}
+ />
+ )}
+ {/* Editing glow pulse */}
+ {/* Agent editing indicator — cursor on the clip */}
+ {isBeingEdited && (
+ <>
+ <div
+ className="absolute inset-0 rounded-[5px] animate-pulse pointer-events-none"
+ style={{ boxShadow: `inset 0 0 0 1px ${activeEdit.agentColor}60` }}
+ />
+ {/* Agent name badge above clip */}
+ <div
+ className="absolute pointer-events-none flex items-center gap-1"
+ style={{
+ top: -16,
+ left: 2,
+ zIndex: 30,
+ }}
+ >
+ {/* Mini cursor arrow */}
+ <svg width="8" height="10" viewBox="0 0 12 16" fill="none" style={{ flexShrink: 0 }}>
+ <path d="M1 1L11 7L6 8L4 14L1 1Z" fill={activeEdit.agentColor} stroke="white" strokeWidth="0.8" />
+ </svg>
+ <span
+ className="text-[8px] font-semibold px-1 py-px rounded whitespace-nowrap"
+ style={{
+ backgroundColor: activeEdit.agentColor,
+ color: "white",
+ boxShadow: `0 1px 4px ${activeEdit.agentColor}40`,
+ }}
+ >
+ {activeEdit.agentId}
+ </span>
+ </div>
+ </>
+ )}
+ <span
+ className="text-[10px] font-semibold truncate px-1.5 leading-none"
+ style={{ color: style.label }}
+ >
+ {el.id || el.tag}
+ </span>
+ {widthPct > 10 && (
+ <span
+ className="text-[9px] font-mono tabular-nums pr-1.5 ml-auto flex-shrink-0 leading-none opacity-70"
+ style={{ color: style.label }}
+ >
+ {el.duration.toFixed(1)}s
+ </span>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+ })}
+
+ {/* Playhead */}
+ <div
+ ref={playheadRef}
+ className="absolute top-0 bottom-0 z-20 pointer-events-none"
+ style={{ left: `${GUTTER}px` }}
+ >
+ <div className="absolute top-0 bottom-0 left-1/2 -translate-x-1/2 w-px bg-white/90" />
+ <div className="absolute left-1/2 -translate-x-1/2" style={{ top: 0 }}>
+ <div style={{
+ width: 0,
+ height: 0,
+ borderLeft: "5px solid transparent",
+ borderRight: "5px solid transparent",
+ borderTop: "7px solid rgba(255,255,255,0.95)",
+ }} />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+});
diff --git a/packages/studio/src/player/hooks/useTimelinePlayer.ts b/packages/studio/src/player/hooks/useTimelinePlayer.ts
new file mode 100644
index 0000000000..cb9e649c8c
--- /dev/null
+++ b/packages/studio/src/player/hooks/useTimelinePlayer.ts
@@ -0,0 +1,465 @@
+import { useRef, useCallback } from "react";
+import { usePlayerStore, liveTime, type TimelineElement } from "../store/playerStore";
+import { useMountEffect } from "../lib/useMountEffect";
+
+interface PlayerAPI {
+ play: () => void;
+ pause: () => void;
+ seek: (time: number) => void;
+ getTime: () => number;
+ getDuration: () => number;
+ isPlaying: () => boolean;
+}
+
+interface TimelineLike {
+ play: () => void;
+ pause: () => void;
+ seek: (time: number) => void;
+ time: () => number;
+ duration: () => number;
+ isActive: () => boolean;
+}
+
+interface ClipManifestClip {
+ id: string | null;
+ label: string;
+ start: number;
+ duration: number;
+ track: number;
+ kind: "video" | "audio" | "image" | "element" | "composition";
+ tagName: string | null;
+ compositionId: string | null;
+ parentCompositionId: string | null;
+ compositionSrc: string | null;
+ assetUrl: string | null;
+}
+
+interface ClipManifest {
+ clips: ClipManifestClip[];
+ scenes: Array<{ id: string; label: string; start: number; duration: number }>;
+ durationInFrames: number;
+}
+
+type IframeWindow = Window & {
+ __player?: PlayerAPI;
+ __timeline?: TimelineLike;
+ __timelines?: Record<string, TimelineLike>;
+ __clipManifest?: ClipManifest;
+};
+
+interface PlaybackAdapter {
+ play: () => void;
+ pause: () => void;
+ seek: (time: number) => void;
+ getTime: () => number;
+ getDuration: () => number;
+ isPlaying: () => boolean;
+}
+
+function wrapPlayer(p: PlayerAPI): PlaybackAdapter {
+ return {
+ play: () => p.play(),
+ pause: () => p.pause(),
+ seek: (t) => p.seek(t),
+ getTime: () => p.getTime(),
+ getDuration: () => p.getDuration(),
+ isPlaying: () => p.isPlaying(),
+ };
+}
+
+function wrapTimeline(tl: TimelineLike): PlaybackAdapter {
+ return {
+ play: () => tl.play(),
+ pause: () => tl.pause(),
+ seek: (t) => {
+ tl.pause();
+ tl.seek(t);
+ },
+ getTime: () => tl.time(),
+ getDuration: () => tl.duration(),
+ isPlaying: () => tl.isActive(),
+ };
+}
+
+function normalizePreviewViewport(doc: Document, win: Window): void {
+ if (doc.documentElement) {
+ doc.documentElement.style.overflow = "hidden";
+ doc.documentElement.style.margin = "0";
+ }
+ if (doc.body) {
+ doc.body.style.overflow = "hidden";
+ doc.body.style.margin = "0";
+ }
+ win.scrollTo({ top: 0, left: 0, behavior: "auto" });
+}
+
+function autoHealMissingCompositionIds(doc: Document): void {
+ const compositionIdRe = /data-composition-id=["']([^"']+)["']/gi;
+ const referencedIds = new Set<string>();
+ const scopedNodes = Array.from(doc.querySelectorAll("style, script"));
+ for (const node of scopedNodes) {
+ const text = node.textContent || "";
+ if (!text) continue;
+ let match: RegExpExecArray | null;
+ while ((match = compositionIdRe.exec(text)) !== null) {
+ const id = (match[1] || "").trim();
+ if (id) referencedIds.add(id);
+ }
+ }
+
+ if (referencedIds.size === 0) return;
+
+ const existingIds = new Set<string>();
+ const existingNodes = Array.from(doc.querySelectorAll<HTMLElement>("[data-composition-id]"));
+ for (const node of existingNodes) {
+ const id = node.getAttribute("data-composition-id");
+ if (id) existingIds.add(id);
+ }
+
+ for (const compId of referencedIds) {
+ if (compId === "root" || existingIds.has(compId)) continue;
+ const host =
+ doc.getElementById(`${compId}-layer`) || doc.getElementById(`${compId}-comp`) || doc.getElementById(compId);
+ if (!host) continue;
+ if (!host.getAttribute("data-composition-id")) {
+ host.setAttribute("data-composition-id", compId);
+ }
+ }
+}
+
+function unmutePreviewMedia(iframe: HTMLIFrameElement | null): void {
+ if (!iframe) return;
+ try {
+ iframe.contentWindow?.postMessage(
+ { source: "hf-parent", type: "control", action: "set-muted", muted: false },
+ "*",
+ );
+ // Fallback for CDN runtime that still uses the old source name
+ iframe.contentWindow?.postMessage(
+ { source: "hf-parent", type: "control", action: "set-muted", muted: false },
+ "*",
+ );
+ } catch {
+ /* ignore */
+ }
+}
+
+export function useTimelinePlayer() {
+ const iframeRef = useRef<HTMLIFrameElement>(null);
+ const rafRef = useRef<number>(0);
+ const probeIntervalRef = useRef<ReturnType<typeof setInterval> | undefined>(undefined);
+ const pendingSeekRef = useRef<number | null>(null);
+ const isRefreshingRef = useRef(false);
+
+ // ZERO store subscriptions — this hook never causes re-renders.
+ // All reads use getState() (point-in-time), all writes use the stable setters.
+ const { setIsPlaying, setCurrentTime, setDuration, setTimelineReady, setElements, reset } =
+ usePlayerStore.getState();
+
+ const getAdapter = useCallback((): PlaybackAdapter | null => {
+ try {
+ const win = iframeRef.current?.contentWindow as IframeWindow | null;
+ if (!win) return null;
+
+ if (win.__player && typeof win.__player.play === "function") {
+ return wrapPlayer(win.__player);
+ }
+
+ if (win.__timeline) return wrapTimeline(win.__timeline);
+
+ if (win.__timelines) {
+ const keys = Object.keys(win.__timelines);
+ if (keys.length > 0) return wrapTimeline(win.__timelines[keys[keys.length - 1]]);
+ }
+
+ return null;
+ } catch {
+ return null;
+ }
+ }, []);
+
+ const startRAFLoop = useCallback(() => {
+ const tick = () => {
+ const adapter = getAdapter();
+ if (adapter) {
+ const time = adapter.getTime();
+ const dur = adapter.getDuration();
+ liveTime.notify(time); // direct DOM updates, no React re-render
+ if (time >= dur && !adapter.isPlaying()) {
+ setCurrentTime(time); // sync Zustand once at end
+ setIsPlaying(false);
+ cancelAnimationFrame(rafRef.current);
+ return;
+ }
+ }
+ rafRef.current = requestAnimationFrame(tick);
+ };
+ rafRef.current = requestAnimationFrame(tick);
+ }, [getAdapter, setCurrentTime, setIsPlaying]);
+
+ const stopRAFLoop = useCallback(() => {
+ cancelAnimationFrame(rafRef.current);
+ }, []);
+
+ const applyPlaybackRate = useCallback((rate: number) => {
+ const iframe = iframeRef.current;
+ if (!iframe) return;
+ // Send to runtime via bridge (works with both new and CDN runtime)
+ iframe.contentWindow?.postMessage({ source: "hf-parent", type: "control", action: "set-playback-rate", playbackRate: rate }, "*");
+ iframe.contentWindow?.postMessage({ source: "hf-parent", type: "control", action: "set-playback-rate", playbackRate: rate }, "*");
+ // Also set directly on GSAP timeline if accessible
+ try {
+ const win = iframe.contentWindow as IframeWindow | null;
+ if (win?.__timelines) {
+ for (const tl of Object.values(win.__timelines)) {
+ if (tl && typeof (tl as unknown as { timeScale?: (v: number) => void }).timeScale === "function") {
+ (tl as unknown as { timeScale: (v: number) => void }).timeScale(rate);
+ }
+ }
+ }
+ } catch { /* cross-origin */ }
+ }, []);
+
+ const play = useCallback(() => {
+ const adapter = getAdapter();
+ if (!adapter) return;
+ if (adapter.getTime() >= adapter.getDuration()) {
+ adapter.seek(0);
+ }
+ unmutePreviewMedia(iframeRef.current);
+ applyPlaybackRate(usePlayerStore.getState().playbackRate);
+ adapter.play();
+ setIsPlaying(true);
+ startRAFLoop();
+ }, [getAdapter, setIsPlaying, startRAFLoop, applyPlaybackRate]);
+
+ const pause = useCallback(() => {
+ const adapter = getAdapter();
+ if (!adapter) return;
+ adapter.pause();
+ setIsPlaying(false);
+ stopRAFLoop();
+ }, [getAdapter, setIsPlaying, stopRAFLoop]);
+
+ const togglePlay = useCallback(() => {
+ if (usePlayerStore.getState().isPlaying) {
+ pause();
+ } else {
+ play();
+ }
+ }, [play, pause]);
+
+ const seek = useCallback(
+ (time: number) => {
+ const adapter = getAdapter();
+ if (!adapter) return;
+ adapter.seek(time);
+ liveTime.notify(time); // Direct DOM updates (playhead, timecode, progress) — no re-render
+ stopRAFLoop();
+ // Only update store if state actually changes (avoids unnecessary re-renders)
+ if (usePlayerStore.getState().isPlaying) setIsPlaying(false);
+ },
+ [getAdapter, setIsPlaying, stopRAFLoop],
+ );
+
+ // Convert a runtime timeline message (from iframe postMessage) into TimelineElements
+ const processTimelineMessage = useCallback(
+ (data: { clips: ClipManifestClip[]; durationInFrames: number }) => {
+ if (!data.clips || data.clips.length === 0) return;
+
+ // Show only root-level clips: those with no parentCompositionId (direct children of root).
+ // Sub-composition children (parentCompositionId !== null) belong to the drill-down view.
+ const els: TimelineElement[] = data.clips
+ .filter((clip) => !clip.parentCompositionId)
+ .map((clip) => {
+ const entry: TimelineElement = {
+ id: clip.id || clip.label || clip.tagName || "element",
+ tag: clip.tagName || clip.kind,
+ start: clip.start,
+ duration: clip.duration,
+ track: clip.track,
+ };
+ if (clip.assetUrl) entry.src = clip.assetUrl;
+ if (clip.kind === "composition" && clip.compositionId) {
+ entry.compositionSrc = clip.compositionSrc || `compositions/${clip.compositionId}.html`;
+ }
+ return entry;
+ });
+ setElements(els);
+ },
+ [setElements],
+ );
+
+ const onIframeLoad = useCallback(() => {
+ unmutePreviewMedia(iframeRef.current);
+
+ let attempts = 0;
+ const maxAttempts = 25;
+
+ if (probeIntervalRef.current) clearInterval(probeIntervalRef.current);
+
+ probeIntervalRef.current = setInterval(() => {
+ attempts++;
+ const adapter = getAdapter();
+ if (adapter && adapter.getDuration() > 0) {
+ clearInterval(probeIntervalRef.current);
+ adapter.pause();
+
+ const seekTo = pendingSeekRef.current;
+ pendingSeekRef.current = null;
+ const startTime = seekTo != null ? Math.min(seekTo, adapter.getDuration()) : 0;
+
+ adapter.seek(startTime);
+ setDuration(adapter.getDuration());
+ setCurrentTime(startTime);
+ if (!isRefreshingRef.current) {
+ setTimelineReady(true);
+ }
+ isRefreshingRef.current = false;
+ setIsPlaying(false);
+
+ try {
+ const doc = iframeRef.current?.contentDocument;
+ const iframeWin = iframeRef.current?.contentWindow as IframeWindow | null;
+ if (doc && iframeWin) {
+ normalizePreviewViewport(doc, iframeWin);
+ autoHealMissingCompositionIds(doc);
+ }
+
+ // Try reading __clipManifest if already available (fast path)
+ const manifest = iframeWin?.__clipManifest;
+ if (manifest && manifest.clips.length > 0) {
+ processTimelineMessage(manifest);
+ } else if (doc) {
+ // Fallback: parse data-start elements directly from DOM (raw HTML without runtime)
+ const rootComp = doc.querySelector("[data-composition-id]");
+ const nodes = doc.querySelectorAll("[data-start]");
+ const els: TimelineElement[] = [];
+ let trackCounter = 0;
+ const rootDuration = adapter.getDuration();
+ nodes.forEach((node) => {
+ if (node === rootComp) return;
+ const el = node as HTMLElement;
+ const startStr = el.getAttribute("data-start");
+ if (startStr == null) return;
+ const start = parseFloat(startStr);
+ if (isNaN(start)) return;
+
+ const tagLower = el.tagName.toLowerCase();
+ let dur = 0;
+ const durStr = el.getAttribute("data-duration");
+ if (durStr != null) dur = parseFloat(durStr);
+ if (isNaN(dur) || dur <= 0) dur = Math.max(0, rootDuration - start);
+
+ const trackStr = el.getAttribute("data-track-index");
+ const track = trackStr != null ? parseInt(trackStr, 10) : trackCounter++;
+ const entry: TimelineElement = {
+ id: el.id || el.className?.split(" ")[0] || tagLower,
+ tag: tagLower,
+ start,
+ duration: dur,
+ track: isNaN(track) ? 0 : track,
+ };
+ if (tagLower === "video" || tagLower === "audio" || tagLower === "img") {
+ const src = el.getAttribute("src");
+ if (src) entry.src = src;
+ }
+ // Detect sub-compositions
+ const compSrc = el.getAttribute("data-composition-src");
+ const compId = el.getAttribute("data-composition-id");
+ if (compSrc || (compId && compId !== rootComp?.getAttribute("data-composition-id"))) {
+ entry.compositionSrc = compSrc || `compositions/${compId}.html`;
+ }
+ els.push(entry);
+ });
+ if (els.length > 0) setElements(els);
+ }
+ // The runtime will also postMessage the full timeline after all compositions load.
+ // That message is handled by the window listener below, which will update elements
+ // with the complete data (including async-loaded compositions).
+ } catch {
+ // Cross-origin or DOM access error
+ }
+
+ return;
+ }
+ if (attempts >= maxAttempts) {
+ clearInterval(probeIntervalRef.current);
+ console.warn("Could not find __player, __timeline, or __timelines on iframe after 5s");
+ }
+ }, 200);
+ }, [getAdapter, setDuration, setCurrentTime, setTimelineReady, setIsPlaying, processTimelineMessage]);
+
+ /** Save the current playback time so the next onIframeLoad restores it. */
+ const saveSeekPosition = useCallback(() => {
+ const adapter = getAdapter();
+ pendingSeekRef.current = adapter ? adapter.getTime() : (usePlayerStore.getState().currentTime ?? 0);
+ isRefreshingRef.current = true;
+ stopRAFLoop();
+ setIsPlaying(false);
+ }, [getAdapter, stopRAFLoop, setIsPlaying]);
+
+ const refreshPlayer = useCallback(() => {
+ const iframe = iframeRef.current;
+ if (!iframe) return;
+
+ saveSeekPosition();
+
+ const src = iframe.src;
+ const url = new URL(src, window.location.origin);
+ url.searchParams.set("_t", String(Date.now()));
+ iframe.src = url.toString();
+ }, [saveSeekPosition]);
+
+ const togglePlayRef = useRef(togglePlay);
+ togglePlayRef.current = togglePlay;
+ const processTimelineMessageRef = useRef(processTimelineMessage);
+ processTimelineMessageRef.current = processTimelineMessage;
+
+ useMountEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.code === "Space" && e.target === document.body) {
+ e.preventDefault();
+ togglePlayRef.current();
+ }
+ };
+
+ // Listen for timeline messages from the iframe runtime.
+ // The runtime sends this AFTER all external compositions load,
+ // so we get the complete clip list (not just the first few).
+ const handleMessage = (e: MessageEvent) => {
+ const data = e.data;
+ if ((data?.source === "hf-preview" || data?.source === "hf-preview") && data?.type === "timeline" && Array.isArray(data.clips)) {
+ processTimelineMessageRef.current(data);
+ // Update duration only if the new value is longer (don't downgrade during generation)
+ if (data.durationInFrames > 0) {
+ const fps = 30;
+ const dur = data.durationInFrames / fps;
+ const currentDur = usePlayerStore.getState().duration;
+ if (dur > currentDur) usePlayerStore.getState().setDuration(dur);
+ }
+ }
+ };
+
+ window.addEventListener("keydown", handleKeyDown);
+ window.addEventListener("message", handleMessage);
+ return () => {
+ window.removeEventListener("keydown", handleKeyDown);
+ window.removeEventListener("message", handleMessage);
+ stopRAFLoop();
+ if (probeIntervalRef.current) clearInterval(probeIntervalRef.current);
+ reset();
+ };
+ });
+
+ return {
+ iframeRef,
+ play,
+ pause,
+ togglePlay,
+ seek,
+ onIframeLoad,
+ refreshPlayer,
+ saveSeekPosition,
+ };
+}
diff --git a/packages/studio/src/player/index.ts b/packages/studio/src/player/index.ts
new file mode 100644
index 0000000000..f179285670
--- /dev/null
+++ b/packages/studio/src/player/index.ts
@@ -0,0 +1,17 @@
+// Components
+export { Player } from "./components/Player";
+export { PlayerControls } from "./components/PlayerControls";
+export { Timeline } from "./components/Timeline";
+export { PreviewPanel } from "./components/PreviewPanel";
+export { AgentActivityTrack } from "./components/AgentActivityTrack";
+export type { AgentActivity } from "./components/AgentActivityTrack";
+
+// Hooks
+export { useTimelinePlayer } from "./hooks/useTimelinePlayer";
+
+// Store
+export { usePlayerStore, liveTime } from "./store/playerStore";
+export type { TimelineElement, ActiveEdits } from "./store/playerStore";
+
+// Utils
+export { formatTime } from "./lib/time";
diff --git a/packages/studio/src/player/lib/time.ts b/packages/studio/src/player/lib/time.ts
new file mode 100644
index 0000000000..e41594ab4d
--- /dev/null
+++ b/packages/studio/src/player/lib/time.ts
@@ -0,0 +1,5 @@
+export function formatTime(time: number): string {
+ const mins = Math.floor(time / 60);
+ const secs = Math.floor(time % 60);
+ return `${mins}:${secs.toString().padStart(2, "0")}`;
+}
diff --git a/packages/studio/src/player/lib/useMountEffect.ts b/packages/studio/src/player/lib/useMountEffect.ts
new file mode 100644
index 0000000000..75bb7f23b1
--- /dev/null
+++ b/packages/studio/src/player/lib/useMountEffect.ts
@@ -0,0 +1,10 @@
+import { useEffect } from "react";
+
+/**
+ * Run an effect exactly once on mount (and optional cleanup on unmount).
+ * This is the ONLY sanctioned way to call useEffect in this package.
+ */
+export function useMountEffect(effect: () => void | (() => void)) {
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ useEffect(effect, []);
+}
diff --git a/packages/studio/src/player/store/playerStore.ts b/packages/studio/src/player/store/playerStore.ts
new file mode 100644
index 0000000000..811cea5549
--- /dev/null
+++ b/packages/studio/src/player/store/playerStore.ts
@@ -0,0 +1,93 @@
+import { create } from "zustand";
+
+export interface TimelineElement {
+ id: string;
+ tag: string;
+ start: number;
+ duration: number;
+ track: number;
+ src?: string;
+ playbackStart?: number;
+ volume?: number;
+ /** Path from data-composition-src — identifies sub-composition elements */
+ compositionSrc?: string;
+ /** Agent that created/last edited this element */
+ agentId?: string;
+ /** Agent's color for ownership visualization */
+ agentColor?: string;
+}
+
+/** Map of elementId → agentColor for clips currently being edited */
+export interface ActiveEdits {
+ [elementId: string]: { agentId: string; agentColor: string };
+}
+
+interface PlayerState {
+ isPlaying: boolean;
+ currentTime: number;
+ duration: number;
+ timelineReady: boolean;
+ elements: TimelineElement[];
+ selectedElementId: string | null;
+ /** Clips currently being edited by agents — for glow animation */
+ activeEdits: ActiveEdits;
+ playbackRate: number;
+
+ setIsPlaying: (playing: boolean) => void;
+ setCurrentTime: (time: number) => void;
+ setDuration: (duration: number) => void;
+ setPlaybackRate: (rate: number) => void;
+ setTimelineReady: (ready: boolean) => void;
+ setElements: (elements: TimelineElement[]) => void;
+ setSelectedElementId: (id: string | null) => void;
+ setActiveEdits: (edits: ActiveEdits) => void;
+ updateElementStart: (elementId: string, newStart: number) => void;
+ reset: () => void;
+}
+
+// Lightweight pub-sub for current time during playback.
+// Bypasses React state so the RAF loop can update the playhead/time display
+// without triggering re-renders on every frame.
+type TimeListener = (time: number) => void;
+const _timeListeners = new Set<TimeListener>();
+export const liveTime = {
+ notify: (t: number) => _timeListeners.forEach((cb) => cb(t)),
+ subscribe: (cb: TimeListener) => {
+ _timeListeners.add(cb);
+ return () => _timeListeners.delete(cb);
+ },
+};
+
+export const usePlayerStore = create<PlayerState>((set) => ({
+ isPlaying: false,
+ currentTime: 0,
+ duration: 0,
+ timelineReady: false,
+ elements: [],
+ selectedElementId: null,
+ activeEdits: {},
+ playbackRate: 1,
+
+ setIsPlaying: (playing) => set({ isPlaying: playing }),
+ setPlaybackRate: (rate) => set({ playbackRate: rate }),
+ setCurrentTime: (time) => set({ currentTime: time }),
+ setDuration: (duration) => set({ duration }),
+ setTimelineReady: (ready) => set({ timelineReady: ready }),
+ setElements: (elements) => set({ elements }),
+ setSelectedElementId: (id) => set({ selectedElementId: id }),
+ setActiveEdits: (edits) => set({ activeEdits: edits }),
+ updateElementStart: (elementId, newStart) =>
+ set((state) => ({
+ elements: state.elements.map((el) => (el.id === elementId ? { ...el, start: newStart } : el)),
+ })),
+ reset: () =>
+ set({
+ isPlaying: false,
+ currentTime: 0,
+ duration: 0,
+ timelineReady: false,
+ elements: [],
+ selectedElementId: null,
+ activeEdits: {},
+ }),
+}));
diff --git a/packages/studio/src/styles/studio.css b/packages/studio/src/styles/studio.css
new file mode 100644
index 0000000000..9d06073375
--- /dev/null
+++ b/packages/studio/src/styles/studio.css
@@ -0,0 +1,31 @@
+@tailwind base;
+@tailwind components;
+@tailwind utilities;
+
+body {
+ margin: 0;
+ padding: 0;
+ background: #0a0a0a;
+ color: #e5e5e5;
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
+ overflow: hidden;
+}
+
+#root {
+ width: 100vw;
+ height: 100vh;
+}
+
+/* CodeMirror overrides */
+.cm-editor {
+ height: 100%;
+ font-size: 13px;
+}
+
+.cm-editor .cm-scroller {
+ font-family: "JetBrains Mono", "Fira Code", "SF Mono", monospace;
+}
+
+.cm-editor.cm-focused {
+ outline: none;
+}
diff --git a/packages/studio/src/utils/sourcePatcher.ts b/packages/studio/src/utils/sourcePatcher.ts
new file mode 100644
index 0000000000..1b2c22e2be
--- /dev/null
+++ b/packages/studio/src/utils/sourcePatcher.ts
@@ -0,0 +1,149 @@
+/**
+ * Source Patcher — Maps visual property edits back to source HTML files.
+ * Handles inline style updates, attribute changes, and text content.
+ */
+
+function escapeRegex(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+export interface PatchOperation {
+ type: "inline-style" | "attribute" | "text-content";
+ property: string;
+ value: string;
+}
+
+/**
+ * Find which source file contains an element by its ID.
+ */
+export function resolveSourceFile(
+ elementId: string | null,
+ selector: string,
+ files: Record<string, string>,
+): string | null {
+ if (!elementId && !selector) return null;
+
+ // Strategy 1: Search by id attribute
+ if (elementId) {
+ for (const [path, content] of Object.entries(files)) {
+ if (content.includes(`id="${elementId}"`) || content.includes(`id='${elementId}'`)) {
+ return path;
+ }
+ }
+ }
+
+ // Strategy 2: Search by data-composition-id from the selector
+ const compIdMatch = selector.match(/data-composition-id="([^"]+)"/);
+ if (compIdMatch) {
+ const compId = compIdMatch[1];
+ for (const [path, content] of Object.entries(files)) {
+ if (content.includes(`data-composition-id="${compId}"`)) {
+ return path;
+ }
+ }
+ }
+
+ // Strategy 3: Search by class from the selector
+ const classMatch = selector.match(/^\.([a-zA-Z0-9_-]+)/);
+ if (classMatch) {
+ const cls = classMatch[1];
+ for (const [path, content] of Object.entries(files)) {
+ if (content.includes(`class="${cls}"`) || content.includes(`class="${cls} `) || content.includes(` ${cls}"`)) {
+ return path;
+ }
+ }
+ }
+
+ // Fallback: index.html
+ if ("index.html" in files) return "index.html";
+ return null;
+}
+
+/**
+ * Apply a style property change to an element's inline style in the HTML source.
+ */
+function patchInlineStyle(html: string, elementId: string, prop: string, value: string): string {
+ // Find the element tag with this id
+ const idPattern = new RegExp(`(<[^>]*\\bid="${escapeRegex(elementId)}"[^>]*)>`, "i");
+ const match = idPattern.exec(html);
+ if (!match) return html;
+
+ const tag = match[1];
+
+ // Check if there's an existing style attribute
+ const styleMatch = /\bstyle="([^"]*)"/.exec(tag);
+ if (styleMatch) {
+ const existingStyle = styleMatch[1];
+ // Parse existing properties
+ const props = new Map<string, string>();
+ for (const part of existingStyle.split(";")) {
+ const colon = part.indexOf(":");
+ if (colon < 0) continue;
+ const key = part.slice(0, colon).trim();
+ const val = part.slice(colon + 1).trim();
+ if (key) props.set(key, val);
+ }
+ // Update/add the property
+ props.set(prop, value);
+ // Rebuild style string
+ const newStyle = Array.from(props.entries())
+ .map(([k, v]) => `${k}: ${v}`)
+ .join("; ");
+ const newTag = tag.replace(/\bstyle="[^"]*"/, `style="${newStyle}"`);
+ return html.replace(tag, newTag);
+ } else {
+ // No existing style — add one
+ const newTag = tag.replace(/>$/, "") + ` style="${prop}: ${value}"`;
+ return html.replace(tag, newTag);
+ }
+}
+
+/**
+ * Apply an attribute change to an element in the HTML source.
+ */
+function patchAttribute(html: string, elementId: string, attr: string, value: string): string {
+ const idPattern = new RegExp(`(<[^>]*\\bid="${escapeRegex(elementId)}"[^>]*)>`, "i");
+ const match = idPattern.exec(html);
+ if (!match) return html;
+
+ const tag = match[1];
+ const fullAttr = attr.startsWith("data-") ? attr : `data-${attr}`;
+ const attrPattern = new RegExp(`\\b${fullAttr}="[^"]*"`);
+
+ if (attrPattern.test(tag)) {
+ // Update existing attribute
+ const newTag = tag.replace(attrPattern, `${fullAttr}="${value}"`);
+ return html.replace(tag, newTag);
+ } else {
+ // Add new attribute
+ const newTag = tag + ` ${fullAttr}="${value}"`;
+ return html.replace(tag, newTag);
+ }
+}
+
+/**
+ * Apply a text content change to an element.
+ */
+function patchTextContent(html: string, elementId: string, value: string): string {
+ // Match the element and its content: <tagname id="elementId"...>content</tagname>
+ const pattern = new RegExp(`(<[^>]*\\bid="${elementId}"[^>]*>)([\\s\\S]*?)(<\\/[a-z]+>)`, "i");
+ const match = pattern.exec(html);
+ if (!match) return html;
+ return html.replace(pattern, `${match[1]}${value}${match[3]}`);
+}
+
+/**
+ * Apply a patch operation to an HTML source file.
+ */
+export function applyPatch(html: string, elementId: string, op: PatchOperation): string {
+ switch (op.type) {
+ case "inline-style":
+ return patchInlineStyle(html, elementId, op.property, op.value);
+ case "attribute":
+ return patchAttribute(html, elementId, op.property, op.value);
+ case "text-content":
+ return patchTextContent(html, elementId, op.value);
+ default:
+ return html;
+ }
+}
diff --git a/packages/studio/tailwind.config.js b/packages/studio/tailwind.config.js
new file mode 100644
index 0000000000..a0a1891915
--- /dev/null
+++ b/packages/studio/tailwind.config.js
@@ -0,0 +1,27 @@
+import { resolve, dirname } from "path";
+import { fileURLToPath } from "url";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+/** @type {import('tailwindcss').Config} */
+export default {
+ content: [
+ resolve(__dirname, "./src/**/*.{ts,tsx}"),
+ resolve(__dirname, "./index.html"),
+ ],
+ theme: {
+ extend: {
+ colors: {
+ studio: {
+ bg: "#0a0a0a",
+ surface: "#141414",
+ border: "#262626",
+ text: "#e5e5e5",
+ muted: "#737373",
+ accent: "#00E3FF",
+ },
+ },
+ },
+ },
+ plugins: [],
+};
diff --git a/packages/studio/tsconfig.json b/packages/studio/tsconfig.json
new file mode 100644
index 0000000000..81fdba5a34
--- /dev/null
+++ b/packages/studio/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "jsx": "react-jsx",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true,
+ "outDir": "dist",
+ "rootDir": "src",
+ "types": ["vite/client"]
+ },
+ "include": ["src"],
+ "exclude": ["dist", "node_modules", "src/dev-server.ts"]
+}
diff --git a/packages/studio/vite.config.ts b/packages/studio/vite.config.ts
new file mode 100644
index 0000000000..73ccccbf84
--- /dev/null
+++ b/packages/studio/vite.config.ts
@@ -0,0 +1,291 @@
+import { defineConfig, type Plugin } from "vite";
+import react from "@vitejs/plugin-react";
+import { readFileSync, readdirSync, existsSync, statSync, writeFileSync, lstatSync, realpathSync } from "node:fs";
+import { join, resolve, sep } from "node:path";
+
+/** Reject paths that escape the project directory. */
+function isSafePath(base: string, resolved: string): boolean {
+ const norm = resolve(base) + sep;
+ return resolved.startsWith(norm) || resolved === resolve(base);
+}
+
+// Lazy-load the bundler via Vite's SSR module loader (resolves .ts imports correctly)
+let _bundler: ((dir: string) => Promise<string>) | null = null;
+
+/** Minimal project API for standalone dev mode */
+function devProjectApi(): Plugin {
+ const dataDir = resolve(__dirname, "data/projects");
+
+ return {
+ name: "studio-dev-api",
+ configureServer(server): void {
+ // Load the bundler via Vite's SSR module loader (resolves .ts imports)
+ const getBundler = async () => {
+ if (!_bundler) {
+ try {
+ const mod = await server.ssrLoadModule("@hyperframes/core/compiler");
+ _bundler = (dir: string) => mod.bundleToSingleHtml(dir);
+ } catch (err) {
+ console.warn("[Studio] Failed to load compiler, previews will use raw HTML:", err);
+ _bundler = null as never;
+ }
+ }
+ return _bundler;
+ };
+
+ server.middlewares.use(async (req, res, next) => {
+ if (!req.url?.startsWith("/api/")) return next();
+
+ // Render endpoints — not yet wired up in standalone studio
+ if (req.url.startsWith("/api/render/") || (req.method === "POST" && req.url.match(/\/api\/projects\/[^/]+\/render/))) {
+ res.writeHead(501, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ error: "Render not available in standalone studio mode" }));
+ return;
+ }
+
+ // GET /api/projects — list all projects with session metadata
+ if (req.method === "GET" && (req.url === "/api/projects" || req.url === "/api/projects/")) {
+ // Build session → project mapping for titles
+ const sessionsDir = resolve(dataDir, "../sessions");
+ const sessionMap = new Map<string, { sessionId: string; title: string }>();
+ if (existsSync(sessionsDir)) {
+ for (const file of readdirSync(sessionsDir).filter((f) => f.endsWith(".json"))) {
+ try {
+ const raw = JSON.parse(readFileSync(join(sessionsDir, file), "utf-8"));
+ if (raw.projectId) {
+ sessionMap.set(raw.projectId, { sessionId: file.replace(".json", ""), title: raw.title || "Untitled" });
+ }
+ } catch { /* skip corrupt */ }
+ }
+ }
+
+ const projects = readdirSync(dataDir, { withFileTypes: true })
+ .filter((d) => (d.isDirectory() || d.isSymbolicLink()) && existsSync(join(dataDir, d.name, "index.html")))
+ .map((d) => {
+ const session = sessionMap.get(d.name);
+ return { id: d.name, title: session?.title ?? d.name, sessionId: session?.sessionId };
+ })
+ .sort((a, b) => a.title.localeCompare(b.title));
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ projects }));
+ return;
+ }
+
+ // GET /api/resolve-session/:sessionId — resolve session ID to project ID
+ const sessionMatch = req.url.match(/^\/api\/resolve-session\/([^/]+)/);
+ if (req.method === "GET" && sessionMatch) {
+ const sessionsDir = resolve(dataDir, "../sessions");
+ const sessionFile = join(sessionsDir, `${sessionMatch[1]}.json`);
+ if (existsSync(sessionFile)) {
+ try {
+ const raw = JSON.parse(readFileSync(sessionFile, "utf-8"));
+ if (raw.projectId) {
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ projectId: raw.projectId, title: raw.title }));
+ return;
+ }
+ } catch { /* ignore */ }
+ }
+ res.writeHead(404, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ error: "Session not found" }));
+ return;
+ }
+
+ const match = req.url.match(/^\/api\/projects\/([^/]+)(.*)/);
+ if (!match) return next();
+
+ let [, projectId, rest] = match;
+ let projectDir = join(dataDir, projectId);
+
+ // If project ID not found, try resolving it as a session ID
+ if (!existsSync(projectDir)) {
+ const sessionsDir = resolve(dataDir, "../sessions");
+ const sessionFile = join(sessionsDir, `${projectId}.json`);
+ if (existsSync(sessionFile)) {
+ try {
+ const session = JSON.parse(readFileSync(sessionFile, "utf-8"));
+ if (session.projectId) {
+ projectId = session.projectId;
+ projectDir = join(dataDir, projectId);
+ }
+ } catch { /* ignore */ }
+ }
+ }
+
+ if (!existsSync(projectDir)) {
+ res.writeHead(404, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ error: "not found" }));
+ return;
+ }
+
+ // GET /api/projects/:id
+ if (req.method === "GET" && !rest) {
+ const files: string[] = [];
+ function walk(d: string, prefix: string) {
+ for (const entry of readdirSync(d, { withFileTypes: true })) {
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) walk(join(d, entry.name), rel);
+ else files.push(rel);
+ }
+ }
+ walk(projectDir, "");
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ id: projectId, files }));
+ return;
+ }
+
+ // GET /api/projects/:id/preview — bundle and serve the full composition
+ if (req.method === "GET" && rest === "/preview") {
+ try {
+ const bundler = await getBundler();
+ const bundled = bundler ? await bundler(projectDir) : readFileSync(join(projectDir, "index.html"), "utf-8");
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
+ res.end(bundled);
+ } catch (err) {
+ // Fallback to raw HTML if bundling fails
+ const file = join(projectDir, "index.html");
+ if (existsSync(file)) {
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
+ res.end(readFileSync(file, "utf-8"));
+ } else {
+ res.writeHead(404); res.end("not found");
+ }
+ }
+ return;
+ }
+
+ // GET /api/projects/:id/preview/comp/* — serve sub-composition as standalone playable page
+ if (req.method === "GET" && rest.startsWith("/preview/comp/")) {
+ const compPath = decodeURIComponent(rest.replace("/preview/comp/", "").split("?")[0]);
+ const compFile = resolve(projectDir, compPath);
+ if (!isSafePath(projectDir, compFile) || !existsSync(compFile) || !statSync(compFile).isFile()) { res.writeHead(404); res.end("not found"); return; }
+
+ let rawComp = readFileSync(compFile, "utf-8");
+
+ // Extract content from <template> if present
+ const templateMatch = rawComp.match(/<template>([\s\S]*)<\/template>/i);
+ let content = templateMatch ? templateMatch[1] : rawComp;
+
+ // Inline nested data-composition-src references (keep the attr for drill-down navigation)
+ content = content.replace(
+ /(<[^>]*?)(data-composition-src=["']([^"']+)["'])([^>]*>)/g,
+ (_match, before, srcAttr, src, after) => {
+ const nestedFile = join(projectDir, src);
+ if (!existsSync(nestedFile)) return before + srcAttr + after;
+ const nestedRaw = readFileSync(nestedFile, "utf-8");
+ const nestedTemplate = nestedRaw.match(/<template>([\s\S]*)<\/template>/i);
+ const nestedContent = nestedTemplate ? nestedTemplate[1] : nestedRaw;
+ // Extract styles, scripts, and body from nested content
+ const styles: string[] = [];
+ const scripts: string[] = [];
+ let body = nestedContent
+ .replace(/<style[^>]*>([\s\S]*?)<\/style>/gi, (_, css) => { styles.push(css); return ""; })
+ .replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, (_, js) => { scripts.push(js); return ""; });
+ // Find the inner root with data-composition-id and use its children
+ const innerRootMatch = body.match(/<([a-z][a-z0-9]*)\b[^>]*data-composition-id[^>]*>([\s\S]*)<\/\1>/i);
+ const innerHTML = innerRootMatch ? innerRootMatch[2] : body;
+ // Keep data-composition-src on the host for drill-down URL resolution
+ return before + srcAttr + after.replace(/>$/, ">") + innerHTML +
+ (styles.length ? `<style>${styles.join("\n")}</style>` : "") +
+ (scripts.length ? `<script>${scripts.map(s => `(function(){try{${s}}catch(e){}})();`).join("\n")}</script>` : "");
+ }
+ );
+
+ // Build a standalone HTML page with GSAP + runtime
+ const runtimeUrl = (process.env.HYPERFRAME_RUNTIME_URL || "").trim() || "";
+ const standalone = `<!DOCTYPE html>
+<html>
+<head>
+<script src="https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.min.js"></script>
+<script data-hyperframes-preview-runtime="1" src="${runtimeUrl}"></script>
+</head>
+<body>
+${content}
+</body>
+</html>`;
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
+ res.end(standalone);
+ return;
+ }
+
+ // GET /api/projects/:id/preview/* — serve static assets (images, audio, etc.)
+ if (req.method === "GET" && rest.startsWith("/preview/")) {
+ const subPath = decodeURIComponent(rest.replace("/preview/", "").split("?")[0]);
+ const file = resolve(projectDir, subPath);
+ if (!isSafePath(projectDir, file) || !existsSync(file) || !statSync(file).isFile()) { res.writeHead(404); res.end("not found"); return; }
+ const isText = /\.(html|css|js|json|svg|txt)$/i.test(subPath);
+ const contentType = subPath.endsWith(".html") ? "text/html" : subPath.endsWith(".js") ? "text/javascript" : subPath.endsWith(".css") ? "text/css" : "application/octet-stream";
+ res.writeHead(200, { "Content-Type": contentType });
+ res.end(readFileSync(file, isText ? "utf-8" : undefined));
+ return;
+ }
+
+ // GET /api/projects/:id/files/:path — returns JSON { filename, content }
+ if (req.method === "GET" && rest.startsWith("/files/")) {
+ const filePath = decodeURIComponent(rest.replace("/files/", ""));
+ const file = resolve(projectDir, filePath);
+ if (!isSafePath(projectDir, file) || !existsSync(file)) { res.writeHead(404); res.end("not found"); return; }
+ const content = readFileSync(file, "utf-8");
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ filename: filePath, content }));
+ return;
+ }
+
+ // PUT /api/projects/:id/files/:path
+ if (req.method === "PUT" && rest.startsWith("/files/")) {
+ const filePath = decodeURIComponent(rest.replace("/files/", ""));
+ const file = resolve(projectDir, filePath);
+ if (!isSafePath(projectDir, file)) {
+ res.writeHead(403, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ error: "forbidden" }));
+ return;
+ }
+ let body = "";
+ req.on("data", (chunk: Buffer) => { body += chunk.toString(); });
+ req.on("end", () => {
+ writeFileSync(file, body, "utf-8");
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ next();
+ });
+
+ // Watch project directories for external file changes (user editing HTML outside the editor).
+ // Resolve symlinks so the watcher sees the real file paths.
+ const realProjectPaths: string[] = [];
+ try {
+ for (const entry of readdirSync(dataDir, { withFileTypes: true })) {
+ const full = join(dataDir, entry.name);
+ try {
+ const real = lstatSync(full).isSymbolicLink() ? realpathSync(full) : full;
+ realProjectPaths.push(real);
+ server.watcher.add(real);
+ } catch { /* skip broken symlinks */ }
+ }
+ } catch { /* dataDir doesn't exist yet */ }
+
+ // When a project file changes, send HMR event to refresh the preview
+ server.watcher.on("change", (filePath: string) => {
+ const isProjectFile = realProjectPaths.some((p) => filePath.startsWith(p));
+ if (isProjectFile && (filePath.endsWith(".html") || filePath.endsWith(".css") || filePath.endsWith(".js"))) {
+ console.log(`[Studio] File changed: ${filePath}`);
+ server.ws.send({ type: "custom", event: "hf:file-change", data: {} });
+ }
+ });
+ },
+ };
+}
+
+export default defineConfig({
+ plugins: [react(), devProjectApi()],
+ build: {
+ outDir: "dist",
+ emptyOutDir: true,
+ },
+ server: {
+ port: 5190,
+ },
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
new file mode 100644
index 0000000000..0682128b98
--- /dev/null
+++ b/pnpm-lock.yaml
@@ -0,0 +1,5143 @@
+lockfileVersion: '9.0'
+
+settings:
+ autoInstallPeers: true
+ excludeLinksFromLockfile: false
+
+importers:
+
+ .:
+ devDependencies:
+ '@types/node':
+ specifier: ^25.0.10
+ version: 25.5.0
+ concurrently:
+ specifier: ^8.2.0
+ version: 8.2.2
+ tsx:
+ specifier: ^4.21.0
+ version: 4.21.0
+ typescript:
+ specifier: ^5.0.0
+ version: 5.9.3
+
+ packages/cli:
+ dependencies:
+ '@hono/node-server':
+ specifier: ^1.8.0
+ version: 1.19.11([email protected])
+ '@puppeteer/browsers':
+ specifier: ^2.13.0
+ version: 2.13.0
+ adm-zip:
+ specifier: ^0.5.16
+ version: 0.5.16
+ cheerio:
+ specifier: ^1.2.0
+ version: 1.2.0
+ citty:
+ specifier: ^0.2.1
+ version: 0.2.1
+ esbuild:
+ specifier: ^0.25.0
+ version: 0.25.12
+ hono:
+ specifier: ^4.0.0
+ version: 4.12.8
+ mime-types:
+ specifier: ^3.0.2
+ version: 3.0.2
+ open:
+ specifier: ^10.0.0
+ version: 10.2.0
+ puppeteer-core:
+ specifier: ^24.39.1
+ version: 24.40.0
+ devDependencies:
+ '@clack/prompts':
+ specifier: ^1.1.0
+ version: 1.1.0
+ '@hyperframes/core':
+ specifier: workspace:*
+ version: link:../core
+ '@hyperframes/engine':
+ specifier: workspace:*
+ version: link:../engine
+ '@hyperframes/producer':
+ specifier: workspace:*
+ version: link:../producer
+ '@types/adm-zip':
+ specifier: ^0.5.7
+ version: 0.5.8
+ '@types/mime-types':
+ specifier: ^3.0.1
+ version: 3.0.1
+ '@types/node':
+ specifier: ^22.0.0
+ version: 22.19.15
+ linkedom:
+ specifier: ^0.18.12
+ version: 0.18.12
+ picocolors:
+ specifier: ^1.1.1
+ version: 1.1.1
+ tsup:
+ specifier: ^8.0.0
+ tsx:
+ specifier: ^4.0.0
+ version: 4.21.0
+ typescript:
+ specifier: ^5.0.0
+ version: 5.9.3
+
+ packages/core:
+ devDependencies:
+ '@types/jsdom':
+ specifier: ^28.0.0
+ version: 28.0.1
+ '@types/node':
+ specifier: ^24.10.13
+ version: 24.12.0
+ '@vitest/coverage-v8':
+ specifier: ^3.2.4
+ jsdom:
+ specifier: ^29.0.0
+ version: 29.0.1
+ tsx:
+ specifier: ^4.21.0
+ version: 4.21.0
+ typescript:
+ specifier: ^5.0.0
+ version: 5.9.3
+ vitest:
+ specifier: ^3.2.4
+ version: 3.2.4(@types/[email protected])([email protected])
+ optionalDependencies:
+ cheerio:
+ specifier: ^1.2.0
+ version: 1.2.0
+ esbuild:
+ specifier: ^0.25.12
+ version: 0.25.12
+
+ packages/engine:
+ dependencies:
+ '@hono/node-server':
+ specifier: ^1.13.0
+ version: 1.19.11([email protected])
+ '@hyperframes/core':
+ specifier: workspace:*
+ version: link:../core
+ hono:
+ specifier: ^4.6.0
+ version: 4.12.8
+ linkedom:
+ specifier: ^0.18.12
+ version: 0.18.12
+ puppeteer:
+ specifier: ^24.0.0
+ version: 24.40.0([email protected])
+ puppeteer-core:
+ specifier: ^24.39.1
+ version: 24.40.0
+ devDependencies:
+ '@types/node':
+ specifier: ^22.10.1
+ version: 22.19.15
+ typescript:
+ specifier: ^5.7.2
+ version: 5.9.3
+
+ packages/producer:
+ dependencies:
+ '@fontsource/archivo-black':
+ specifier: ^5.2.8
+ version: 5.2.8
+ '@fontsource/eb-garamond':
+ specifier: ^5.2.7
+ version: 5.2.7
+ '@fontsource/ibm-plex-mono':
+ specifier: ^5.2.7
+ version: 5.2.7
+ '@fontsource/inter':
+ specifier: ^5.2.8
+ version: 5.2.8
+ '@fontsource/jetbrains-mono':
+ specifier: ^5.2.8
+ version: 5.2.8
+ '@fontsource/league-gothic':
+ specifier: ^5.2.8
+ version: 5.2.8
+ '@fontsource/montserrat':
+ specifier: ^5.2.8
+ version: 5.2.8
+ '@fontsource/nunito':
+ specifier: ^5.2.7
+ version: 5.2.7
+ '@fontsource/oswald':
+ specifier: ^5.2.8
+ version: 5.2.8
+ '@fontsource/outfit':
+ specifier: ^5.2.8
+ version: 5.2.8
+ '@fontsource/space-mono':
+ specifier: ^5.2.9
+ version: 5.2.9
+ '@hono/node-server':
+ specifier: ^1.13.0
+ version: 1.19.11([email protected])
+ '@hyperframes/core':
+ specifier: workspace:*
+ version: link:../core
+ '@hyperframes/engine':
+ specifier: workspace:*
+ version: link:../engine
+ hono:
+ specifier: ^4.6.0
+ version: 4.12.8
+ linkedom:
+ specifier: ^0.18.12
+ version: 0.18.12
+ puppeteer:
+ specifier: ^24.0.0
+ version: 24.40.0([email protected])
+ puppeteer-core:
+ specifier: ^24.39.1
+ version: 24.40.0
+ devDependencies:
+ '@types/node':
+ specifier: ^22.10.1
+ version: 22.19.15
+ esbuild:
+ specifier: ^0.27.2
+ version: 0.27.4
+ tsx:
+ specifier: ^4.7.0
+ version: 4.21.0
+ typescript:
+ specifier: ^5.7.2
+ version: 5.9.3
+
+ packages/studio:
+ dependencies:
+ '@codemirror/autocomplete':
+ specifier: ^6.20.1
+ version: 6.20.1
+ '@codemirror/commands':
+ specifier: ^6.10.3
+ version: 6.10.3
+ '@codemirror/lang-css':
+ specifier: ^6.3.1
+ version: 6.3.1
+ '@codemirror/lang-html':
+ specifier: ^6.4.9
+ version: 6.4.11
+ '@codemirror/lang-javascript':
+ specifier: ^6.2.2
+ version: 6.2.5
+ '@codemirror/language':
+ specifier: ^6.12.2
+ version: 6.12.2
+ '@codemirror/search':
+ specifier: ^6.6.0
+ version: 6.6.0
+ '@codemirror/state':
+ specifier: ^6.6.0
+ version: 6.6.0
+ '@codemirror/theme-one-dark':
+ specifier: ^6.1.2
+ version: 6.1.3
+ '@codemirror/view':
+ specifier: ^6.40.0
+ version: 6.40.0
+ '@hyperframes/core':
+ specifier: workspace:*
+ version: link:../core
+ '@phosphor-icons/react':
+ specifier: ^2.1.10
+ codemirror:
+ specifier: ^6.0.1
+ version: 6.0.2
+ react:
+ specifier: ^18.0.0 || ^19.0.0
+ version: 18.3.1
+ react-dom:
+ specifier: ^18.0.0 || ^19.0.0
+ version: 18.3.1([email protected])
+ zustand:
+ specifier: ^4.0.0 || ^5.0.0
+ version: 4.5.7(@types/[email protected])([email protected])
+ devDependencies:
+ '@types/react':
+ specifier: ^19.0.0
+ version: 19.2.14
+ '@types/react-dom':
+ specifier: ^19.0.0
+ version: 19.2.3(@types/[email protected])
+ '@vitejs/plugin-react':
+ specifier: ^4.0.0
+ version: 4.7.0([email protected](@types/[email protected]))
+ autoprefixer:
+ specifier: ^10.4.0
+ version: 10.4.27([email protected])
+ postcss:
+ specifier: ^8.4.0
+ version: 8.5.8
+ tailwindcss:
+ specifier: ^3.4.0
+ version: 3.4.19([email protected])
+ typescript:
+ specifier: ^5.0.0
+ version: 5.9.3
+ vite:
+ specifier: ^5.0.0
+ version: 5.4.21(@types/[email protected])
+
+packages:
+
+ '@alloc/[email protected]':
+ resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}
+ engines: {node: '>=10'}
+
+ '@ampproject/[email protected]':
+ resolution: {integrity: sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==}
+ engines: {node: '>=6.0.0'}
+
+ '@asamuzakjp/[email protected]':
+ resolution: {integrity: sha512-2SZFvqMyvboVV1d15lMf7XiI3m7SDqXUuKaTymJYLN6dSGadqp+fVojqJlVoMlbZnlTmu3S0TLwLTJpvBMO1Aw==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+
+ '@asamuzakjp/[email protected]':
+ resolution: {integrity: sha512-jXR6x4AcT3eIrS2fSNAwJpwirOkGcd+E7F7CP3zjdTqz9B/2huHOL8YJZBgekKwLML+u7qB/6P1LXQuMScsx0w==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+
+ '@asamuzakjp/[email protected]':
+ resolution: {integrity: sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==}
+ engines: {node: '>=6.9.0'}
+ peerDependencies:
+ '@babel/core': ^7.0.0
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==}
+ engines: {node: '>=6.0.0'}
+ hasBin: true
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw==}
+ engines: {node: '>=6.9.0'}
+ peerDependencies:
+ '@babel/core': ^7.0.0-0
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw==}
+ engines: {node: '>=6.9.0'}
+ peerDependencies:
+ '@babel/core': ^7.0.0-0
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==}
+ engines: {node: '>=6.9.0'}
+
+ resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
+ engines: {node: '>=18'}
+
+ '@bramus/[email protected]':
+ resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==}
+ hasBin: true
+
+ '@clack/[email protected]':
+ resolution: {integrity: sha512-SVcm4Dqm2ukn64/8Gub2wnlA5nS2iWJyCkdNHcvNHPIeBTGojpdJ+9cZKwLfmqy7irD4N5qLteSilJlE0WLAtA==}
+
+ '@clack/[email protected]':
+ resolution: {integrity: sha512-pkqbPGtohJAvm4Dphs2M8xE29ggupihHdy1x84HNojZuMtFsHiUlRvqD24tM2+XmI+61LlfNceM3Wr7U5QES5g==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-1cvg3Vz1dSSToCNlJfRA2WSI4ht3K+WplO0UMOgmUYPivCyy2oueZY6Lx7M9wThm7SDUBViRmuT+OG/i8+ON9A==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-JFRiqhKu+bvSkDLI+rUhJwSxQxYb759W5GBezE8Uc8mHLqC9aV/9aTC7yJSqCtB3F00pylrLCwnyS91Ap5ej4Q==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-jEPmz2nGGDxhRTg3lTpzmIyGKxz3Gp3SJES4b0nAuE5SWQoKdT5GoQ69cwMmFd+wvFUhYirtDTr0/DRHpQAyWg==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-GElsbU9G7QT9xXhpUg1zWGmftA/7jamh+7+ydKRuT0ORpWS3wOSP0yT1FOlIZa7mIJjpVPipErsyvVqB9cfTFA==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-koFuNXcDvyyotWcgOnZGmY7LZqEOXZaaxD/j6n18TCLx2/9HieZJ5H6hs1g8FiRxBD0DNfs0nXn17g872RmYdw==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-WA0zdU7xfF10+5I3HhUUq3kqOx3KjqmtQ9lqZjfK7jtYk4G72YW9rezcSywpaUMCWOMlq+6E0pO1IWg1TNIhtg==}
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-LMGQLS9EuADloEFkcTBR3BwV/CGHV7zyDxVRtVDTwdI2Ca4it0CCVTT9wCkxSgokjE5Ho41hEPgb8OEUwoXr6Q==}
+ engines: {node: '>=20.19.0'}
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-HJ26Z/vmsZQqs/o3a6bgKslXGFAungXGbinULZO3eMsOyNJHeBBZfup5FiZInOghgoM4Hwnmw+OgbJCNg1wwUQ==}
+ engines: {node: '>=20.19.0'}
+ peerDependencies:
+ '@csstools/css-parser-algorithms': ^4.0.0
+ '@csstools/css-tokenizer': ^4.0.0
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-0GEfbBLmTFf0dJlpsNU7zwxRIH0/BGEMuXLTCvFYxuL1tNhqzTbtnFICyJLTNK4a+RechKP75e7w42ClXSnJQw==}
+ engines: {node: '>=20.19.0'}
+ peerDependencies:
+ '@csstools/css-parser-algorithms': ^4.0.0
+ '@csstools/css-tokenizer': ^4.0.0
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==}
+ engines: {node: '>=20.19.0'}
+ peerDependencies:
+ '@csstools/css-tokenizer': ^4.0.0
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-BvqN0AMWNAnLk9G8jnUT77D+mUbY/H2b3uDTvg2isJkHaOufUE2R3AOwxWo7VBQKT1lOdwdvorddo2B/lk64+w==}
+ peerDependencies:
+ css-tree: ^3.2.1
+ peerDependenciesMeta:
+ css-tree:
+ optional: true
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==}
+ engines: {node: '>=20.19.0'}
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==}
+ engines: {node: '>=12'}
+ cpu: [ppc64]
+ os: [aix]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [aix]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [aix]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [android]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [android]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [android]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==}
+ engines: {node: '>=12'}
+ cpu: [arm]
+ os: [android]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [android]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [android]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [android]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [android]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [android]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [darwin]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [darwin]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [darwin]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [freebsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [freebsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [freebsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==}
+ engines: {node: '>=12'}
+ cpu: [arm]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==}
+ engines: {node: '>=12'}
+ cpu: [ia32]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==}
+ engines: {node: '>=12'}
+ cpu: [loong64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==}
+ engines: {node: '>=18'}
+ cpu: [loong64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==}
+ engines: {node: '>=18'}
+ cpu: [loong64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==}
+ engines: {node: '>=12'}
+ cpu: [mips64el]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==}
+ engines: {node: '>=18'}
+ cpu: [mips64el]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==}
+ engines: {node: '>=18'}
+ cpu: [mips64el]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==}
+ engines: {node: '>=12'}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==}
+ engines: {node: '>=12'}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==}
+ engines: {node: '>=18'}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==}
+ engines: {node: '>=18'}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==}
+ engines: {node: '>=12'}
+ cpu: [s390x]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==}
+ engines: {node: '>=18'}
+ cpu: [s390x]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==}
+ engines: {node: '>=18'}
+ cpu: [s390x]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [netbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [netbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [netbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [netbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [netbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-JkTZrl6VbyO8lDQO3yv26nNr2RM2yZzNrNHEsj9bm6dOwwu9OYN28CjzZkH57bh4w0I2F7IodpQvUAEd1mbWXg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [sunos]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [sunos]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [sunos]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [win32]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [win32]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [win32]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==}
+ engines: {node: '>=12'}
+ cpu: [ia32]
+ os: [win32]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [win32]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [win32]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [win32]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [win32]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [win32]
+
+ '@exodus/[email protected]':
+ resolution: {integrity: sha512-UY0nlA+feH81UGSHv92sLEPLCeZFjXOuHhrIo0HQydScuQc8s0A7kL/UdgwgDq8g8ilksmuoF35YVTNphV2aBQ==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+ peerDependencies:
+ '@noble/hashes': ^1.8.0 || ^2.0.0
+ peerDependenciesMeta:
+ '@noble/hashes':
+ optional: true
+
+ '@fontsource/[email protected]':
+ resolution: {integrity: sha512-3zNj/o9LzWyDl/UEpY5IOHpAQyUtFr3hQaFS7NSKwCLLkXOfH/CMCt1L2b2Z+OF25OURtOYenCadgAebALz7/A==}
+
+ '@fontsource/[email protected]':
+ resolution: {integrity: sha512-V42tTlHDbnDo0+lENnXKWMx63Llq6Gfl2l7ozkoeRQN60S0jm6hEgCLlOT/5YyKAN9QZ0e2ofpy0rGKlz9jBrw==}
+
+ '@fontsource/[email protected]':
+ resolution: {integrity: sha512-MKAb8qV+CaiMQn2B0dIi1OV3565NYzp3WN5b4oT6LTkk+F0jR6j0ZN+5BKJiIhffDC3rtBULsYZE65+0018z9w==}
+
+ '@fontsource/[email protected]':
+ resolution: {integrity: sha512-P6r5WnJoKiNVV+zvW2xM13gNdFhAEpQ9dQJHt3naLvfg+LkF2ldgSLiF4T41lf1SQCM9QmkqPTn4TH568IRagg==}
+
+ '@fontsource/[email protected]':
+ resolution: {integrity: sha512-6w8/SG4kqvIMu7xd7wt6x3idn1Qux3p9N62s6G3rfldOUYHpWcc2FKrqf+Vo44jRvqWj2oAtTHrZXEP23oSKwQ==}
+
+ '@fontsource/[email protected]':
+ resolution: {integrity: sha512-xxu2kSPrZZZG2Gq+M75/4J5q0PWUshfgk4tH09mvMrmNzS6izlDRWVU4W+OFCf+3Hb22PswB4vJOr/PUUDpWCw==}
+
+ '@fontsource/[email protected]':
+ resolution: {integrity: sha512-xTjLxSbSfCycDB0pwmNsfNvdfWPaDaRQ2LC6yt/ZI7SdvXG52zHnzNYC/09mzuAuWNJyShkteutfCoDgym56hQ==}
+
+ '@fontsource/[email protected]':
+ resolution: {integrity: sha512-pmtBq0H9ex9nk+RtJYEJOD9pag393iHETnl/PVKleF4i06cd0ttngK5ZCTgYb5eOqR3Xdlrjtev8m7bmgYprew==}
+
+ '@fontsource/[email protected]':
+ resolution: {integrity: sha512-DFoPK1BqsFIQhVjs2xgO/oL9veF9oUJgFojEWIU+nazUrfqsBDtAMI4n9L9CZFX3kQNDLcCyzKx1xoEDvQT4WQ==}
+
+ '@fontsource/[email protected]':
+ resolution: {integrity: sha512-rXC6g0MqD7cOBjht0bMqc43qM6lRqDLML9KXsmg9uykz0wLQhy8Z/ajrMG6iyoT3NJR+MYgU+OEHp7uHoTb+Yw==}
+
+ '@fontsource/[email protected]':
+ resolution: {integrity: sha512-b61faFOHEISQ/pD25G+cfGY9o/WW6lRv6hBQQfpWvEJ4y1V+S4gmth95EVyBE2VL3qDYHeVQ8nBzrplzdXTDDg==}
+
+ resolution: {integrity: sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g==}
+ engines: {node: '>=18.14.1'}
+ peerDependencies:
+ hono: ^4
+
+ '@isaacs/[email protected]':
+ resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}
+ engines: {node: '>=12'}
+
+ '@istanbuljs/[email protected]':
+ resolution: {integrity: sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==}
+ engines: {node: '>=8'}
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==}
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}
+ engines: {node: '>=6.0.0'}
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
+
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-6YRVG9vBkaY7p1IVxL4s44n5nUnaNnGM2/AckNgYOnxTG2kWh1vR8BMxPseWPjRNpb5VtXnMpeYAEAADoRV1Iw==}
+
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-tRZAPl1j0pkmPL/pGG85GAbyQYnYv0j6UEdEt5e4ZYvp+OxDu2zVp2c/YddiuO8ZTa2CHsVELqRd/fGWjlISrg==}
+
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==}
+
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==}
+
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==}
+
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-bPWa0Pgx69ylNlMlPvBPryqeLYQjyJjqPx+Aupm5zydLIF3NE+6MMLT8Yi23Bd9cif9VS00aUebn+6fDIGBcDA==}
+
+ '@marijn/[email protected]':
+ resolution: {integrity: sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==}
+
+ '@nodelib/[email protected]':
+ resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
+ engines: {node: '>= 8'}
+
+ '@nodelib/[email protected]':
+ resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==}
+ engines: {node: '>= 8'}
+
+ '@nodelib/[email protected]':
+ resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==}
+ engines: {node: '>= 8'}
+
+ '@phosphor-icons/[email protected]':
+ resolution: {integrity: sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==}
+ engines: {node: '>=10'}
+ peerDependencies:
+ react: '>= 16.8'
+ react-dom: '>= 16.8'
+
+ '@pkgjs/[email protected]':
+ resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
+ engines: {node: '>=14'}
+
+ '@puppeteer/[email protected]':
+ resolution: {integrity: sha512-46BZJYJjc/WwmKjsvDFykHtXrtomsCIrwYQPOP7VfMJoZY2bsDF9oROBABR3paDjDcmkUye1Pb1BqdcdiipaWA==}
+ engines: {node: '>=18'}
+ hasBin: true
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==}
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==}
+ cpu: [arm]
+ os: [android]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==}
+ cpu: [arm64]
+ os: [android]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==}
+ cpu: [x64]
+ os: [darwin]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==}
+ cpu: [arm64]
+ os: [freebsd]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==}
+ cpu: [arm]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==}
+ cpu: [arm]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==}
+ cpu: [arm64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==}
+ cpu: [arm64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==}
+ cpu: [loong64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==}
+ cpu: [loong64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==}
+ cpu: [s390x]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==}
+ cpu: [x64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==}
+ cpu: [x64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==}
+ cpu: [arm64]
+ os: [win32]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==}
+ cpu: [ia32]
+ os: [win32]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==}
+ cpu: [x64]
+ os: [win32]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==}
+ cpu: [x64]
+ os: [win32]
+
+ '@tootallnate/[email protected]':
+ resolution: {integrity: sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-RVVH7QvZYbN+ihqZ4kX/dMiowf6o+Jk1fNwiSdx0NahBJLU787zkULhGhJM8mf/obmLGmgdMM0bXsQTmyfbR7Q==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-GJq2QE4TAZ5ajSoCasn5DOFm8u1mI3tIFvM5tIq3W5U/RTB6gsHwc6Yhpl91X9VSDOUVblgXmG+2+sSvFQrdlw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-xRMsfuQbnRq1Ef+C+RKaENOxXX87Ygl38W1vDfPHRku02TgQr+Qd8iivLtAMcR0KF5/29xlnFihkTlbqFrGOVQ==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-GYDxsZi3ChgmckRT9HPU0WEhKLP08ev/Yfcq2AstjrDASOYCSXeyjDsHg4v5t4jOj7cyDX3vmprafKlWIG9MXQ==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==}
+ peerDependencies:
+ '@types/react': ^19.2.0
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==}
+
+ '@vitejs/[email protected]':
+ resolution: {integrity: sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==}
+ engines: {node: ^14.18.0 || >=16.0.0}
+ peerDependencies:
+ vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-EyF9SXU6kS5Ku/U82E259WSnvg6c8KTjppUncuNdm5QHpe17mwREHnjDzozC8x9MZ0xfBUFSaLkRv4TMA75ALQ==}
+ peerDependencies:
+ '@vitest/browser': 3.2.4
+ vitest: 3.2.4
+ peerDependenciesMeta:
+ '@vitest/browser':
+ optional: true
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==}
+ peerDependencies:
+ msw: ^2.4.9
+ vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0
+ peerDependenciesMeta:
+ msw:
+ optional: true
+ vite:
+ optional: true
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==}
+
+ resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==}
+ engines: {node: '>=0.4.0'}
+ hasBin: true
+
+ resolution: {integrity: sha512-TGw5yVi4saajsSEgz25grObGHEUaDrniwvA2qwSC060KfqGPdglhvPMA2lPIoxs3PQIItj2iag35fONcQqgUaQ==}
+ engines: {node: '>=12.0'}
+
+ resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}
+ engines: {node: '>= 14'}
+
+ resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==}
+
+ resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==}
+ engines: {node: '>= 8'}
+
+ resolution: {integrity: sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==}
+
+ resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
+
+ resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==}
+ engines: {node: '>=4'}
+
+ resolution: {integrity: sha512-BRRC8VRZY2R4Z4lFIL35MwNXmwVqBityvOIwETtsCSwvjl0IdgFsy9NhdaA6j74nUdtJJlIypeRhpDam19Wq3g==}
+
+ resolution: {integrity: sha512-NP9APE+tO+LuJGn7/9+cohklunJsXWiaWEfV3si4Gi/XHDwVNgkwr1J3RQYFIvPy76GmJ9/bW8vyoU1LcxwKHA==}
+ engines: {node: ^10 || ^12 || >=14}
+ hasBin: true
+ peerDependencies:
+ postcss: ^8.1.0
+
+ resolution: {integrity: sha512-qRuSmNSkGQaHwNbM7J78Wwy+ghLEYF1zNrSeMxj4Kgw6y33O3mXcQ6Ie9fRvfU/YnxWkOchPXbaLb73TkIsfdg==}
+ peerDependencies:
+ react-native-b4a: '*'
+ peerDependenciesMeta:
+ react-native-b4a:
+ optional: true
+
+ resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
+
+ resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
+ engines: {node: 18 || 20 || >=22}
+
+ resolution: {integrity: sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ==}
+ peerDependencies:
+ bare-abort-controller: '*'
+ peerDependenciesMeta:
+ bare-abort-controller:
+ optional: true
+
+ resolution: {integrity: sha512-1QovqDrR80Pmt5HPAsMsXTCFcDYr+NSUKW6nd6WO5v0JBmnItc/irNRzm2KOQ5oZ69P37y+AMujNyNtG+1Rggw==}
+ engines: {bare: '>=1.16.0'}
+ peerDependencies:
+ bare-buffer: '*'
+ peerDependenciesMeta:
+ bare-buffer:
+ optional: true
+
+ resolution: {integrity: sha512-Dc9/SlwfxkXIGYhvMQNUtKaXCaGkZYGcd1vuNUUADVqzu4/vQfvnMkYYOUnt2VwQ2AqKr/8qAVFRtwETljgeFg==}
+ engines: {bare: '>=1.14.0'}
+
+ resolution: {integrity: sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==}
+
+ resolution: {integrity: sha512-DOPZF/DDcDruKDA43cOw6e9Quq5daua7ygcAwJE/pKJsRWhgSSemi7qVNGE5kyDIxIeN1533G/zfbvWX7Wcb9w==}
+ peerDependencies:
+ bare-buffer: '*'
+ bare-events: '*'
+ peerDependenciesMeta:
+ bare-buffer:
+ optional: true
+ bare-events:
+ optional: true
+
+ resolution: {integrity: sha512-NSTU5WN+fy/L0DDenfE8SXQna4voXuW0FHM7wH8i3/q9khUSchfPbPezO4zSFMnDGIf9YE+mt/RWhZgNRKRIXA==}
+
+ resolution: {integrity: sha512-OZd0e2mU11ClX8+IdXe3r0dbqMEznRiT4TfbhYIbcRPZkqJ7Qwer8ij3GZAmLsRKa+II9V1v5czCkvmHH3XZBg==}
+ engines: {node: '>=6.0.0'}
+ hasBin: true
+
+ resolution: {integrity: sha512-VoMINM2rqJwJgfdHq6RiUudKt2BV+FY5ZFezP/ypmwayk68+NzzAQy4XXLlqsGD4MCzq3DrmNFD/uUmBJuGoXw==}
+ engines: {node: '>=10.0.0'}
+
+ resolution: {integrity: sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==}
+
+ resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}
+
+ resolution: {integrity: sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==}
+
+ resolution: {integrity: sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==}
+ engines: {node: 18 || 20 || >=22}
+
+ resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==}
+ engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
+ hasBin: true
+
+ resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==}
+
+ resolution: {integrity: sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==}
+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+ peerDependencies:
+ esbuild: '>=0.18'
+
+ resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==}
+ engines: {node: '>= 6'}
+
+ resolution: {integrity: sha512-llngX0E7nQci5BPJDqoZSbuZ5Bcs9F5db7EtgfwBerX9XGtkkiO4NwfDDIRzHTTwcYC8vC7bmeUEPGrKlR/TkQ==}
+
+ resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}
+ engines: {node: '>= 16'}
+
+ resolution: {integrity: sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==}
+
+ resolution: {integrity: sha512-WDrybc/gKFpTYQutKIK6UvfcuxijIZfMfXaYm8NMsPQxSYvf+13fXUJ4rztGGbJcBQ/GF55gvrZ0Bc0bj/mqvg==}
+ engines: {node: '>=20.18.1'}
+
+ resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==}
+ engines: {node: '>= 8.10.0'}
+
+ resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==}
+ engines: {node: '>= 14.16.0'}
+
+ resolution: {integrity: sha512-9gYlLtS6tStdRWzrtXaTMnqcM4dudNegMXJxkR0I/CXObHalYeYcAMPrL19eroNZHtJ8DQmu1E+ZNOYu/IXMXw==}
+ peerDependencies:
+ devtools-protocol: '*'
+
+ resolution: {integrity: sha512-kEV95lFBhQgtogAPlQfJJ0WGVSokvLr/UEoFPiKKOXF7pl98HfUVUD0ejsuTCld/9xH9vogSywZ5KqHzXrZpqg==}
+
+ resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==}
+
+ resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}
+ engines: {node: '>=7.0.0'}
+
+ resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
+
+ resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==}
+ engines: {node: '>= 6'}
+
+ resolution: {integrity: sha512-1dP4gpXFhei8IOtlXRE/T/4H88ElHgTiUzh71YUmtjTEHMSRS2Z/fgOxHSxxusGHogsRfxNq1vyAwxSC+EVyDg==}
+ engines: {node: ^14.13.0 || >=16.0.0}
+ hasBin: true
+
+ resolution: {integrity: sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==}
+
+ resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==}
+ engines: {node: ^14.18.0 || >=16.10.0}
+
+ resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
+
+ resolution: {integrity: sha512-hr4ihw+DBqcvrsEDioRO31Z17x71pUYoNe/4h6Z0wB72p7MU7/9gH8Q3s12NFhHPfYBBOV3qyfUxmr/Yn3shnQ==}
+ engines: {node: '>=14'}
+ peerDependencies:
+ typescript: '>=4.9.5'
+ peerDependenciesMeta:
+ typescript:
+ optional: true
+
+ resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==}
+
+ resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
+ engines: {node: '>= 8'}
+
+ resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==}
+
+ resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==}
+ engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}
+
+ resolution: {integrity: sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==}
+ engines: {node: '>= 6'}
+
+ resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}
+ engines: {node: '>=4'}
+ hasBin: true
+
+ resolution: {integrity: sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==}
+
+ resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
+
+ resolution: {integrity: sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==}
+ engines: {node: '>= 14'}
+
+ resolution: {integrity: sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+
+ resolution: {integrity: sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==}
+ engines: {node: '>=0.11'}
+
+ resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
+ engines: {node: '>=6.0'}
+ peerDependencies:
+ supports-color: '*'
+ peerDependenciesMeta:
+ supports-color:
+ optional: true
+
+ resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==}
+
+ resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==}
+ engines: {node: '>= 14'}
+
+ resolution: {integrity: sha512-nv7iKtNZQshSW2hKzYNr46nM/Cfh5SEvE2oV0/SEGgc9XupIY5ggf84Cz8eJIkBce7S3bmTAauFD6aysMpnqsQ==}
+
+ resolution: {integrity: sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==}
+
+ resolution: {integrity: sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==}
+
+ resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}
+
+ resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==}
+
+ resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}
+ engines: {node: '>= 4'}
+
+ resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}
+
+ resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}
+
+ resolution: {integrity: sha512-L2C7Q279W2D/J4PLZLk7sebOILDSWos7bMsMNN06rK482umHUrh/3lM8G7IlHFOYip2oAg5nha1rCMxr/rs6ZQ==}
+
+ resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}
+
+ resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==}
+
+ resolution: {integrity: sha512-5gvq20T6vfpekVtqrYQsSCFZ1wEg5+wW0/QaZMWkFr6BqD3NfKs0rLCx4rrVlSWJeZb5NBJgVLswK/w2MWU+Gw==}
+
+ resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==}
+
+ resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}
+ engines: {node: '>=0.12'}
+
+ resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}
+ engines: {node: '>=0.12'}
+
+ resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
+ engines: {node: '>=0.12'}
+
+ resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==}
+
+ resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}
+
+ resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==}
+ engines: {node: '>=12'}
+ hasBin: true
+
+ resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==}
+ engines: {node: '>=18'}
+ hasBin: true
+
+ resolution: {integrity: sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==}
+ engines: {node: '>=18'}
+ hasBin: true
+
+ resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==}
+ engines: {node: '>=6.0'}
+ hasBin: true
+
+ resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==}
+ engines: {node: '>=4'}
+ hasBin: true
+
+ resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==}
+ engines: {node: '>=4.0'}
+
+ resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
+
+ resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==}
+
+ resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}
+ engines: {node: '>=12.0.0'}
+
+ resolution: {integrity: sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==}
+ engines: {node: '>= 10.17.0'}
+ hasBin: true
+
+ resolution: {integrity: sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==}
+
+ resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==}
+ engines: {node: '>=8.6.0'}
+
+ resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==}
+
+ resolution: {integrity: sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==}
+
+ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
+ engines: {node: '>=12.0.0'}
+ peerDependencies:
+ picomatch: ^3 || ^4
+ peerDependenciesMeta:
+ picomatch:
+ optional: true
+
+ resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==}
+
+ resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==}
+ engines: {node: '>=14'}
+
+ resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==}
+
+ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
+ os: [darwin]
+
+ resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}
+
+ resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}
+ engines: {node: '>=6.9.0'}
+
+ resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}
+ engines: {node: 6.* || 8.* || >= 10.*}
+
+ resolution: {integrity: sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw==}
+
+ resolution: {integrity: sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==}
+ engines: {node: '>= 14'}
+
+ resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==}
+ engines: {node: '>= 6'}
+
+ resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==}
+ engines: {node: '>=10.13.0'}
+
+ resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==}
+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
+ hasBin: true
+
+ resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-VJCEvtrezO1IAR+kqEYnxUOoStaQPGrCmX3j4wDTNOcD1uRPFpGlwQUIW8niPuvHXaTUxeOUl5MMDGrl+tmO9A==}
+ engines: {node: '>=16.9.0'}
+
+ resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+
+ resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
+
+ resolution: {integrity: sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==}
+
+ resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==}
+
+ resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==}
+ engines: {node: '>= 14'}
+
+ resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}
+ engines: {node: '>= 14'}
+
+ resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==}
+ engines: {node: '>= 12'}
+
+ resolution: {integrity: sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==}
+
+ resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==}
+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+ hasBin: true
+
+ resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==}
+ engines: {node: '>=14.16'}
+ hasBin: true
+
+ resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==}
+ engines: {node: '>=0.12.0'}
+
+ resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}
+
+ resolution: {integrity: sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==}
+ engines: {node: '>=16'}
+
+ resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
+
+ resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==}
+
+ resolution: {integrity: sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==}
+ hasBin: true
+
+ resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}
+
+ resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
+
+ resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==}
+
+ resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==}
+ hasBin: true
+
+ resolution: {integrity: sha512-z6JOK5gRO7aMybVq/y/MlIpKh8JIi68FBKMUtKkK2KH/wMSRlCxQ682d08LB9fYXplyY/UXG8P4XXTScmdjApg==}
+ engines: {node: ^20.19.0 || ^22.13.0 || >=24.0.0}
+ peerDependencies:
+ canvas: ^3.0.0
+ peerDependenciesMeta:
+ canvas:
+ optional: true
+
+ resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}
+ engines: {node: '>=6'}
+ hasBin: true
+
+ resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==}
+
+ resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==}
+ engines: {node: '>=6'}
+ hasBin: true
+
+ resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==}
+ engines: {node: '>=14'}
+
+ resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
+
+ resolution: {integrity: sha512-jalJsOwIKuQJSeTvsgzPe9iJzyfVaEJiEXl+25EkKevsULHvMJzpNqwvj1jOESWdmgKDiXObyjOYwlUqG7wo1Q==}
+ engines: {node: '>=16'}
+ peerDependencies:
+ canvas: '>= 2'
+ peerDependenciesMeta:
+ canvas:
+ optional: true
+
+ resolution: {integrity: sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==}
+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+
+ resolution: {integrity: sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==}
+
+ resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
+ hasBin: true
+
+ resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==}
+
+ resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==}
+
+ resolution: {integrity: sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA==}
+ engines: {node: 20 || >=22}
+
+ resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
+
+ resolution: {integrity: sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+
+ resolution: {integrity: sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==}
+
+ resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==}
+
+ resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}
+ engines: {node: '>= 8'}
+
+ resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==}
+ engines: {node: '>=8.6'}
+
+ resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==}
+ engines: {node: '>= 0.6'}
+
+ resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==}
+ engines: {node: 18 || 20 || >=22}
+
+ resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==}
+ engines: {node: '>=16 || 14 >=14.17'}
+
+ resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==}
+ engines: {node: '>=16 || 14 >=14.17'}
+
+ resolution: {integrity: sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==}
+
+ resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==}
+
+ resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
+
+ resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}
+
+ resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==}
+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
+ hasBin: true
+
+ resolution: {integrity: sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg==}
+ engines: {node: '>= 0.4.0'}
+
+ resolution: {integrity: sha512-TdC8FSgHz8Mwtw9g5L4gR/Sh9XhSP/0DEkQxfEFXOpiul5IiHgHan2VhYYb6agDSfp4KuvltmGApc8HMgUrIkA==}
+
+ resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}
+
+ resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==}
+ engines: {node: '>= 6'}
+
+ resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
+
+ resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==}
+ engines: {node: '>= 14'}
+
+ resolution: {integrity: sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==}
+ engines: {node: '>= 14'}
+
+ resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==}
+
+ resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g==}
+
+ resolution: {integrity: sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==}
+
+ resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}
+
+ resolution: {integrity: sha512-9m4m5GSgXjL4AjumKzq1Fgfp3Z8rsvjRNbnkVwfu2ImRqE5D0LnY2QfDen18FSY9C573YU5XxSapdHZTZ2WolA==}
+
+ resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==}
+
+ resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==}
+ engines: {node: '>=16 || 14 >=14.18'}
+
+ resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
+
+ resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}
+ engines: {node: '>= 14.16'}
+
+ resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}
+
+ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
+
+ resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==}
+ engines: {node: '>=8.6'}
+
+ resolution: {integrity: sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==}
+ engines: {node: '>= 6'}
+
+ resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==}
+
+ resolution: {integrity: sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==}
+ engines: {node: '>=14.0.0'}
+ peerDependencies:
+ postcss: ^8.0.0
+
+ resolution: {integrity: sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==}
+ engines: {node: ^12 || ^14 || >= 16}
+ peerDependencies:
+ postcss: ^8.4.21
+
+ resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==}
+ engines: {node: '>= 18'}
+ peerDependencies:
+ jiti: '>=1.21.0'
+ postcss: '>=8.0.9'
+ tsx: ^4.8.1
+ yaml: ^2.4.2
+ peerDependenciesMeta:
+ jiti:
+ optional: true
+ postcss:
+ optional: true
+ tsx:
+ optional: true
+ yaml:
+ optional: true
+
+ resolution: {integrity: sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==}
+ engines: {node: '>=12.0'}
+ peerDependencies:
+ postcss: ^8.2.14
+
+ resolution: {integrity: sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==}
+ engines: {node: '>=4'}
+
+ resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==}
+
+ resolution: {integrity: sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==}
+ engines: {node: ^10 || ^12 || >=14}
+
+ resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==}
+ engines: {node: '>=0.4.0'}
+
+ resolution: {integrity: sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A==}
+ engines: {node: '>= 14'}
+
+ resolution: {integrity: sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==}
+
+ resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==}
+
+ resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-MWL3XbUCfVgGR0gRsidzT6oKJT2QydPLhMITU6HoVWiiv4gkb6gJi3pcdAa8q4HwjBTbqISOWVP4aJiiyUJvag==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-IxQbDq93XHVVLWHrAkFP7F7iHvb9o0mgfsSIMlhHb+JM+JjM1V4v4MNSQfcRWJopx9dsNOr9adYv0U5fm9BJBQ==}
+ engines: {node: '>=18'}
+ hasBin: true
+
+ resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
+
+ resolution: {integrity: sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==}
+ peerDependencies:
+ react: ^18.3.1
+
+ resolution: {integrity: sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==}
+
+ resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==}
+ engines: {node: '>=8.10.0'}
+
+ resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==}
+ engines: {node: '>= 14.18.0'}
+
+ resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==}
+ engines: {node: '>=4'}
+
+ resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==}
+
+ resolution: {integrity: sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==}
+ engines: {node: '>= 0.4'}
+ hasBin: true
+
+ resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}
+ engines: {iojs: '>=1.0.0', node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==}
+ engines: {node: '>=18.0.0', npm: '>=8.0.0'}
+ hasBin: true
+
+ resolution: {integrity: sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}
+
+ resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==}
+
+ resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
+
+ resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}
+ engines: {node: '>=v12.22.7'}
+
+ resolution: {integrity: sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==}
+
+ resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
+ hasBin: true
+
+ resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==}
+ engines: {node: '>=10'}
+ hasBin: true
+
+ resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
+
+ resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
+ engines: {node: '>=14'}
+
+ resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==}
+
+ resolution: {integrity: sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==}
+ engines: {node: '>= 6.0.0', npm: '>= 3.0.0'}
+
+ resolution: {integrity: sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==}
+ engines: {node: '>= 14'}
+
+ resolution: {integrity: sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==}
+ engines: {node: '>= 10.0.0', npm: '>= 3.0.0'}
+
+ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==}
+ engines: {node: '>= 12'}
+
+ resolution: {integrity: sha512-zC8zGoGkmc8J9ndvml8Xksr1Amk9qBujgbF0JAIWO7kXr43w0h/0GJNM/Vustixu+YE8N/MTrQ7N31FvHUACxQ==}
+
+ resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
+
+ resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
+
+ resolution: {integrity: sha512-0nQuG6jf1w+wddNEEXCF4nTg3LtufWINB5eFEN+5TNZW7KWJp6x87+JFL43vaAUPyCfH1wID+mNVyW6OHtFamg==}
+
+ resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==}
+
+ resolution: {integrity: sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==}
+
+ resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==}
+ engines: {node: '>=16 || 14 >=14.17'}
+ hasBin: true
+
+ resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}
+
+ resolution: {integrity: sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==}
+ engines: {node: '>=14.0.0'}
+ hasBin: true
+
+ resolution: {integrity: sha512-QGxxTxxyleAdyM3kpFs14ymbYmNFrfY+pHj7Z8FgtbZ7w2//VAgLMac7sT6nRpIHjppXO2AwwEOg0bPFVRcmXw==}
+
+ resolution: {integrity: sha512-U6QpVRyCGHva435KoNWy9PRoi2IFYCgtEhq9nmrPPpbRacPs9IH4aJ3gbrFC8dPcXvdSZ4XXfXT5Fshbp2MtlQ==}
+
+ resolution: {integrity: sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==}
+
+ resolution: {integrity: sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==}
+
+ resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==}
+ engines: {node: '>=0.8'}
+
+ resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==}
+
+ resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
+
+ resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}
+
+ resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==}
+ engines: {node: '>=12.0.0'}
+
+ resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}
+ engines: {node: ^18.0.0 || >=20.0.0}
+
+ resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==}
+ engines: {node: '>=14.0.0'}
+
+ resolution: {integrity: sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==}
+ engines: {node: '>=14.0.0'}
+
+ resolution: {integrity: sha512-YQ7uPjgWUibIK6DW5lrKujGwUKhLevU4hcGbP5O6TcIUb+oTjJYJVWPS4nZsIHrEEEG6myk/oqAJUEQmpZrHsg==}
+
+ resolution: {integrity: sha512-I4FZcVFcqCRuT0ph6dCDpPuO4Xgzvh+spkcTr1gK7peIvxWauoloVO0vuy1FQnijT63ss6AsHB6+OIM4aXHbPg==}
+ hasBin: true
+
+ resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}
+ engines: {node: '>=8.0'}
+
+ resolution: {integrity: sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==}
+ engines: {node: '>=16'}
+
+ resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==}
+ engines: {node: '>=20'}
+
+ resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}
+ hasBin: true
+
+ resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==}
+
+ resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
+
+ resolution: {integrity: sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==}
+ engines: {node: '>=18'}
+ hasBin: true
+ peerDependencies:
+ '@microsoft/api-extractor': ^7.36.0
+ '@swc/core': ^1
+ postcss: ^8.4.12
+ typescript: '>=4.5.0'
+ peerDependenciesMeta:
+ '@microsoft/api-extractor':
+ optional: true
+ '@swc/core':
+ optional: true
+ postcss:
+ optional: true
+ typescript:
+ optional: true
+
+ resolution: {integrity: sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==}
+ engines: {node: '>=18.0.0'}
+ hasBin: true
+
+ resolution: {integrity: sha512-uzR+FzI8qrUEIu96oaeBJmd9E7CFEiQ3goA5qCVgc4s5llSubcfGHq9yUstZx/k4s9dXHVKsE35YWoFyvEqEHA==}
+
+ resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
+ engines: {node: '>=14.17'}
+ hasBin: true
+
+ resolution: {integrity: sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q==}
+
+ resolution: {integrity: sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA==}
+
+ resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
+
+ resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==}
+
+ resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==}
+
+ resolution: {integrity: sha512-kNh333UBSbgK35OIW7FwJTr9tTfVIG51Fm1tSVT7m8foPHfDVjsb7OIee/q/rs3bB2aV/3qOPgG5mHNWl1odiA==}
+
+ resolution: {integrity: sha512-3IWdCpjgxp15CbJnsi/Y9TCDE7HWVN19j1hmzVhoAkY/+CJx449tVxT5wZc1Gwg8J+P0LWvzlBzxYRnHJ+1i7Q==}
+ engines: {node: '>=20.18.1'}
+
+ resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}
+ hasBin: true
+ peerDependencies:
+ browserslist: '>= 4.21.0'
+
+ resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==}
+ peerDependencies:
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
+ resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
+
+ resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==}
+ engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
+ hasBin: true
+
+ resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==}
+ engines: {node: ^18.0.0 || >=20.0.0}
+ hasBin: true
+ peerDependencies:
+ '@types/node': ^18.0.0 || >=20.0.0
+ less: '*'
+ lightningcss: ^1.21.0
+ sass: '*'
+ sass-embedded: '*'
+ stylus: '*'
+ sugarss: '*'
+ terser: ^5.4.0
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+ less:
+ optional: true
+ lightningcss:
+ optional: true
+ sass:
+ optional: true
+ sass-embedded:
+ optional: true
+ stylus:
+ optional: true
+ sugarss:
+ optional: true
+ terser:
+ optional: true
+
+ resolution: {integrity: sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==}
+ engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
+ hasBin: true
+ peerDependencies:
+ '@edge-runtime/vm': '*'
+ '@types/debug': ^4.1.12
+ '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0
+ '@vitest/browser': 3.2.4
+ '@vitest/ui': 3.2.4
+ happy-dom: '*'
+ jsdom: '*'
+ peerDependenciesMeta:
+ '@edge-runtime/vm':
+ optional: true
+ '@types/debug':
+ optional: true
+ '@types/node':
+ optional: true
+ '@vitest/browser':
+ optional: true
+ '@vitest/ui':
+ optional: true
+ happy-dom:
+ optional: true
+ jsdom:
+ optional: true
+
+ resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
+
+ resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw==}
+
+ resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==}
+ engines: {node: '>=20'}
+
+ resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==}
+ engines: {node: '>=18'}
+ deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation
+
+ resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==}
+ engines: {node: '>=20'}
+
+ resolution: {integrity: sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+
+ resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}
+ engines: {node: '>= 8'}
+ hasBin: true
+
+ resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
+ engines: {node: '>=8'}
+ hasBin: true
+
+ resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
+
+ resolution: {integrity: sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==}
+ engines: {node: '>=10.0.0'}
+ peerDependencies:
+ bufferutil: ^4.0.1
+ utf-8-validate: '>=5.0.2'
+ peerDependenciesMeta:
+ bufferutil:
+ optional: true
+ utf-8-validate:
+ optional: true
+
+ resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}
+
+ resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
+
+ resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==}
+
+ resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}
+
+ resolution: {integrity: sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==}
+ engines: {node: '>=12.7.0'}
+ peerDependencies:
+ '@types/react': '>=16.8'
+ immer: '>=9.0.6'
+ react: '>=16.8'
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ immer:
+ optional: true
+ react:
+ optional: true
+
+snapshots:
+
+ '@alloc/[email protected]': {}
+
+ '@ampproject/[email protected]':
+ dependencies:
+ '@jridgewell/gen-mapping': 0.3.13
+ '@jridgewell/trace-mapping': 0.3.31
+
+ '@asamuzakjp/[email protected]':
+ dependencies:
+ '@csstools/css-calc': 3.1.1(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
+ '@csstools/css-color-parser': 4.0.2(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
+ '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])
+ '@csstools/css-tokenizer': 4.0.0
+ lru-cache: 11.2.7
+
+ '@asamuzakjp/[email protected]':
+ dependencies:
+ '@asamuzakjp/nwsapi': 2.3.9
+ bidi-js: 1.0.3
+ css-tree: 3.2.1
+ is-potential-custom-element-name: 1.0.1
+ lru-cache: 11.2.7
+
+ '@asamuzakjp/[email protected]': {}
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/helper-validator-identifier': 7.28.5
+ js-tokens: 4.0.0
+ picocolors: 1.1.1
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/code-frame': 7.29.0
+ '@babel/generator': 7.29.1
+ '@babel/helper-compilation-targets': 7.28.6
+ '@babel/helper-module-transforms': 7.28.6(@babel/[email protected])
+ '@babel/helpers': 7.29.2
+ '@babel/parser': 7.29.2
+ '@babel/template': 7.28.6
+ '@babel/traverse': 7.29.0
+ '@babel/types': 7.29.0
+ '@jridgewell/remapping': 2.3.5
+ convert-source-map: 2.0.0
+ debug: 4.4.3
+ gensync: 1.0.0-beta.2
+ json5: 2.2.3
+ semver: 6.3.1
+ transitivePeerDependencies:
+ - supports-color
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/parser': 7.29.2
+ '@babel/types': 7.29.0
+ '@jridgewell/gen-mapping': 0.3.13
+ '@jridgewell/trace-mapping': 0.3.31
+ jsesc: 3.1.0
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/compat-data': 7.29.0
+ '@babel/helper-validator-option': 7.27.1
+ browserslist: 4.28.1
+ lru-cache: 5.1.1
+ semver: 6.3.1
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/traverse': 7.29.0
+ '@babel/types': 7.29.0
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@babel/core': 7.29.0
+ '@babel/helper-module-imports': 7.28.6
+ '@babel/helper-validator-identifier': 7.28.5
+ '@babel/traverse': 7.29.0
+ transitivePeerDependencies:
+ - supports-color
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/template': 7.28.6
+ '@babel/types': 7.29.0
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/types': 7.29.0
+
+ dependencies:
+ '@babel/core': 7.29.0
+ '@babel/helper-plugin-utils': 7.28.6
+
+ dependencies:
+ '@babel/core': 7.29.0
+ '@babel/helper-plugin-utils': 7.28.6
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/code-frame': 7.29.0
+ '@babel/parser': 7.29.2
+ '@babel/types': 7.29.0
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/code-frame': 7.29.0
+ '@babel/generator': 7.29.1
+ '@babel/helper-globals': 7.28.0
+ '@babel/parser': 7.29.2
+ '@babel/template': 7.28.6
+ '@babel/types': 7.29.0
+ debug: 4.4.3
+ transitivePeerDependencies:
+ - supports-color
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/helper-string-parser': 7.27.1
+ '@babel/helper-validator-identifier': 7.28.5
+
+ '@bcoe/[email protected]': {}
+
+ '@bramus/[email protected]':
+ dependencies:
+ css-tree: 3.2.1
+
+ '@clack/[email protected]':
+ dependencies:
+ sisteransi: 1.0.5
+
+ '@clack/[email protected]':
+ dependencies:
+ '@clack/core': 1.1.0
+ sisteransi: 1.0.5
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/language': 6.12.2
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.40.0
+ '@lezer/common': 1.5.1
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/language': 6.12.2
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.40.0
+ '@lezer/common': 1.5.1
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/autocomplete': 6.20.1
+ '@codemirror/language': 6.12.2
+ '@codemirror/state': 6.6.0
+ '@lezer/common': 1.5.1
+ '@lezer/css': 1.3.2
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/autocomplete': 6.20.1
+ '@codemirror/lang-css': 6.3.1
+ '@codemirror/lang-javascript': 6.2.5
+ '@codemirror/language': 6.12.2
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.40.0
+ '@lezer/common': 1.5.1
+ '@lezer/css': 1.3.2
+ '@lezer/html': 1.3.13
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/autocomplete': 6.20.1
+ '@codemirror/language': 6.12.2
+ '@codemirror/lint': 6.9.5
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.40.0
+ '@lezer/common': 1.5.1
+ '@lezer/javascript': 1.5.4
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.40.0
+ '@lezer/common': 1.5.1
+ '@lezer/highlight': 1.2.3
+ '@lezer/lr': 1.4.8
+ style-mod: 4.1.3
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.40.0
+ crelt: 1.0.6
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.40.0
+ crelt: 1.0.6
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@marijn/find-cluster-break': 1.0.2
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/language': 6.12.2
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.40.0
+ '@lezer/highlight': 1.2.3
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/state': 6.6.0
+ crelt: 1.0.6
+ style-mod: 4.1.3
+ w3c-keyname: 2.2.8
+
+ '@csstools/[email protected]': {}
+
+ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':
+ dependencies:
+ '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])
+ '@csstools/css-tokenizer': 4.0.0
+
+ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':
+ dependencies:
+ '@csstools/color-helpers': 6.0.2
+ '@csstools/css-calc': 3.1.1(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
+ '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])
+ '@csstools/css-tokenizer': 4.0.0
+
+ '@csstools/[email protected](@csstools/[email protected])':
+ dependencies:
+ '@csstools/css-tokenizer': 4.0.0
+
+ optionalDependencies:
+ css-tree: 3.2.1
+
+ '@csstools/[email protected]': {}
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@exodus/[email protected]': {}
+
+ '@fontsource/[email protected]': {}
+
+ '@fontsource/[email protected]': {}
+
+ '@fontsource/[email protected]': {}
+
+ '@fontsource/[email protected]': {}
+
+ '@fontsource/[email protected]': {}
+
+ '@fontsource/[email protected]': {}
+
+ '@fontsource/[email protected]': {}
+
+ '@fontsource/[email protected]': {}
+
+ '@fontsource/[email protected]': {}
+
+ '@fontsource/[email protected]': {}
+
+ '@fontsource/[email protected]': {}
+
+ dependencies:
+ hono: 4.12.8
+
+ '@isaacs/[email protected]':
+ dependencies:
+ string-width: 5.1.2
+ string-width-cjs: [email protected]
+ strip-ansi: 7.2.0
+ strip-ansi-cjs: [email protected]
+ wrap-ansi: 8.1.0
+ wrap-ansi-cjs: [email protected]
+
+ '@istanbuljs/[email protected]': {}
+
+ '@jridgewell/[email protected]':
+ dependencies:
+ '@jridgewell/sourcemap-codec': 1.5.5
+ '@jridgewell/trace-mapping': 0.3.31
+
+ '@jridgewell/[email protected]':
+ dependencies:
+ '@jridgewell/gen-mapping': 0.3.13
+ '@jridgewell/trace-mapping': 0.3.31
+
+ '@jridgewell/[email protected]': {}
+
+ '@jridgewell/[email protected]': {}
+
+ '@jridgewell/[email protected]':
+ dependencies:
+ '@jridgewell/resolve-uri': 3.1.2
+ '@jridgewell/sourcemap-codec': 1.5.5
+
+ '@lezer/[email protected]': {}
+
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.5.1
+ '@lezer/highlight': 1.2.3
+ '@lezer/lr': 1.4.8
+
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.5.1
+
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.5.1
+ '@lezer/highlight': 1.2.3
+ '@lezer/lr': 1.4.8
+
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.5.1
+ '@lezer/highlight': 1.2.3
+ '@lezer/lr': 1.4.8
+
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.5.1
+
+ '@marijn/[email protected]': {}
+
+ '@nodelib/[email protected]':
+ dependencies:
+ '@nodelib/fs.stat': 2.0.5
+ run-parallel: 1.2.0
+
+ '@nodelib/[email protected]': {}
+
+ '@nodelib/[email protected]':
+ dependencies:
+ '@nodelib/fs.scandir': 2.1.5
+ fastq: 1.20.1
+
+ dependencies:
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+
+ '@pkgjs/[email protected]':
+ optional: true
+
+ '@puppeteer/[email protected]':
+ dependencies:
+ debug: 4.4.3
+ extract-zip: 2.0.1
+ progress: 2.0.3
+ proxy-agent: 6.5.0
+ semver: 7.7.4
+ tar-fs: 3.1.2
+ yargs: 17.7.2
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - bare-buffer
+ - react-native-b4a
+ - supports-color
+
+ '@rolldown/[email protected]': {}
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@tootallnate/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.19.15
+
+ '@types/[email protected]':
+ dependencies:
+ '@babel/parser': 7.29.2
+ '@babel/types': 7.29.0
+ '@types/babel__generator': 7.27.0
+ '@types/babel__template': 7.4.4
+ '@types/babel__traverse': 7.28.0
+
+ '@types/[email protected]':
+ dependencies:
+ '@babel/types': 7.29.0
+
+ '@types/[email protected]':
+ dependencies:
+ '@babel/parser': 7.29.2
+ '@babel/types': 7.29.0
+
+ '@types/[email protected]':
+ dependencies:
+ '@babel/types': 7.29.0
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/deep-eql': 4.0.2
+ assertion-error: 2.0.1
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 24.12.0
+ '@types/tough-cookie': 4.0.5
+ parse5: 7.3.0
+ undici-types: 7.24.5
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ undici-types: 6.21.0
+
+ '@types/[email protected]':
+ dependencies:
+ undici-types: 7.16.0
+
+ '@types/[email protected]':
+ dependencies:
+ undici-types: 7.18.2
+
+ dependencies:
+ '@types/react': 19.2.14
+
+ '@types/[email protected]':
+ dependencies:
+ csstype: 3.2.3
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.19.15
+ optional: true
+
+ dependencies:
+ '@babel/core': 7.29.0
+ '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-react-jsx-source': 7.27.1(@babel/[email protected])
+ '@rolldown/pluginutils': 1.0.0-beta.27
+ '@types/babel__core': 7.20.5
+ react-refresh: 0.17.0
+ vite: 5.4.21(@types/[email protected])
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@ampproject/remapping': 2.3.0
+ '@bcoe/v8-coverage': 1.0.2
+ ast-v8-to-istanbul: 0.3.12
+ debug: 4.4.3
+ istanbul-lib-coverage: 3.2.2
+ istanbul-lib-report: 3.0.1
+ istanbul-lib-source-maps: 5.0.6
+ istanbul-reports: 3.2.0
+ magic-string: 0.30.21
+ magicast: 0.3.5
+ std-env: 3.10.0
+ test-exclude: 7.0.2
+ tinyrainbow: 2.0.0
+ vitest: 3.2.4(@types/[email protected])([email protected])
+ transitivePeerDependencies:
+ - supports-color
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@types/chai': 5.2.3
+ '@vitest/spy': 3.2.4
+ '@vitest/utils': 3.2.4
+ chai: 5.3.3
+ tinyrainbow: 2.0.0
+
+ dependencies:
+ '@vitest/spy': 3.2.4
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+ vite: 5.4.21(@types/[email protected])
+
+ '@vitest/[email protected]':
+ dependencies:
+ tinyrainbow: 2.0.0
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/utils': 3.2.4
+ pathe: 2.0.3
+ strip-literal: 3.1.0
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/pretty-format': 3.2.4
+ magic-string: 0.30.21
+ pathe: 2.0.3
+
+ '@vitest/[email protected]':
+ dependencies:
+ tinyspy: 4.0.4
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/pretty-format': 3.2.4
+ loupe: 3.2.1
+ tinyrainbow: 2.0.0
+
+
+
+
+
+
+ dependencies:
+ color-convert: 2.0.1
+
+
+
+ dependencies:
+ normalize-path: 3.0.0
+ picomatch: 2.3.1
+
+
+
+
+ dependencies:
+ tslib: 2.8.1
+
+ dependencies:
+ '@jridgewell/trace-mapping': 0.3.31
+ estree-walker: 3.0.3
+ js-tokens: 10.0.0
+
+ dependencies:
+ browserslist: 4.28.1
+ caniuse-lite: 1.0.30001780
+ fraction.js: 5.3.4
+ picocolors: 1.1.1
+ postcss: 8.5.8
+ postcss-value-parser: 4.2.0
+
+
+
+
+
+ dependencies:
+ bare-events: 2.8.2
+ bare-path: 3.0.0
+ bare-stream: 2.10.0([email protected])
+ bare-url: 2.4.0
+ fast-fifo: 1.3.2
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - react-native-b4a
+
+
+ dependencies:
+ bare-os: 3.8.0
+
+ dependencies:
+ streamx: 2.25.0
+ teex: 1.0.1
+ optionalDependencies:
+ bare-events: 2.8.2
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - react-native-b4a
+
+ dependencies:
+ bare-path: 3.0.0
+
+
+
+ dependencies:
+ require-from-string: 2.0.2
+
+
+
+ dependencies:
+ balanced-match: 1.0.2
+
+ dependencies:
+ balanced-match: 4.0.4
+
+ dependencies:
+ fill-range: 7.1.1
+
+ dependencies:
+ baseline-browser-mapping: 2.10.9
+ caniuse-lite: 1.0.30001780
+ electron-to-chromium: 1.5.321
+ node-releases: 2.0.36
+ update-browserslist-db: 1.2.3([email protected])
+
+
+ dependencies:
+ run-applescript: 7.1.0
+
+ dependencies:
+ esbuild: 0.27.4
+ load-tsconfig: 0.2.5
+
+
+
+
+
+ dependencies:
+ assertion-error: 2.0.1
+ check-error: 2.1.3
+ deep-eql: 5.0.2
+ loupe: 3.2.1
+ pathval: 2.0.1
+
+ dependencies:
+ ansi-styles: 4.3.0
+ supports-color: 7.2.0
+
+
+ dependencies:
+ boolbase: 1.0.0
+ css-select: 5.2.2
+ css-what: 6.2.2
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+ domutils: 3.2.2
+
+ dependencies:
+ cheerio-select: 2.1.0
+ dom-serializer: 2.0.0
+ domhandler: 5.0.3
+ domutils: 3.2.2
+ encoding-sniffer: 0.2.1
+ htmlparser2: 10.1.0
+ parse5: 7.3.0
+ parse5-htmlparser2-tree-adapter: 7.1.0
+ parse5-parser-stream: 7.1.2
+ undici: 7.24.5
+ whatwg-mimetype: 4.0.0
+
+ dependencies:
+ anymatch: 3.1.3
+ braces: 3.0.3
+ glob-parent: 5.1.2
+ is-binary-path: 2.1.0
+ is-glob: 4.0.3
+ normalize-path: 3.0.0
+ readdirp: 3.6.0
+ optionalDependencies:
+ fsevents: 2.3.3
+
+ dependencies:
+ readdirp: 4.1.2
+
+ dependencies:
+ devtools-protocol: 0.0.1581282
+ mitt: 3.0.1
+ zod: 3.25.76
+
+
+ dependencies:
+ string-width: 4.2.3
+ strip-ansi: 6.0.1
+ wrap-ansi: 7.0.0
+
+ dependencies:
+ '@codemirror/autocomplete': 6.20.1
+ '@codemirror/commands': 6.10.3
+ '@codemirror/language': 6.12.2
+ '@codemirror/lint': 6.9.5
+ '@codemirror/search': 6.6.0
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.40.0
+
+ dependencies:
+ color-name: 1.1.4
+
+
+
+ dependencies:
+ chalk: 4.1.2
+ date-fns: 2.30.0
+ lodash: 4.17.23
+ rxjs: 7.8.2
+ shell-quote: 1.8.3
+ spawn-command: 0.0.2
+ supports-color: 8.1.1
+ tree-kill: 1.2.2
+ yargs: 17.7.2
+
+
+
+
+ dependencies:
+ env-paths: 2.2.1
+ import-fresh: 3.3.1
+ js-yaml: 4.1.1
+ parse-json: 5.2.0
+ optionalDependencies:
+ typescript: 5.9.3
+
+
+ dependencies:
+ path-key: 3.1.1
+ shebang-command: 2.0.0
+ which: 2.0.2
+
+ dependencies:
+ boolbase: 1.0.0
+ css-what: 6.2.2
+ domhandler: 5.0.3
+ domutils: 3.2.2
+ nth-check: 2.1.1
+
+ dependencies:
+ mdn-data: 2.27.1
+ source-map-js: 1.2.1
+
+
+
+
+
+
+ dependencies:
+ whatwg-mimetype: 5.0.0
+ whatwg-url: 16.0.1
+ transitivePeerDependencies:
+ - '@noble/hashes'
+
+ dependencies:
+ '@babel/runtime': 7.29.2
+
+ dependencies:
+ ms: 2.1.3
+
+
+
+
+ dependencies:
+ bundle-name: 4.1.0
+ default-browser-id: 5.0.1
+
+
+ dependencies:
+ ast-types: 0.13.4
+ escodegen: 2.1.0
+ esprima: 4.0.1
+
+
+
+
+ dependencies:
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+ entities: 4.5.0
+
+
+ dependencies:
+ domelementtype: 2.3.0
+
+ dependencies:
+ dom-serializer: 2.0.0
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+
+
+
+
+
+ dependencies:
+ iconv-lite: 0.6.3
+ whatwg-encoding: 3.1.1
+
+ dependencies:
+ once: 1.4.0
+
+
+
+
+
+ dependencies:
+ is-arrayish: 0.2.1
+
+
+ optionalDependencies:
+ '@esbuild/aix-ppc64': 0.21.5
+ '@esbuild/android-arm': 0.21.5
+ '@esbuild/android-arm64': 0.21.5
+ '@esbuild/android-x64': 0.21.5
+ '@esbuild/darwin-arm64': 0.21.5
+ '@esbuild/darwin-x64': 0.21.5
+ '@esbuild/freebsd-arm64': 0.21.5
+ '@esbuild/freebsd-x64': 0.21.5
+ '@esbuild/linux-arm': 0.21.5
+ '@esbuild/linux-arm64': 0.21.5
+ '@esbuild/linux-ia32': 0.21.5
+ '@esbuild/linux-loong64': 0.21.5
+ '@esbuild/linux-mips64el': 0.21.5
+ '@esbuild/linux-ppc64': 0.21.5
+ '@esbuild/linux-riscv64': 0.21.5
+ '@esbuild/linux-s390x': 0.21.5
+ '@esbuild/linux-x64': 0.21.5
+ '@esbuild/netbsd-x64': 0.21.5
+ '@esbuild/openbsd-x64': 0.21.5
+ '@esbuild/sunos-x64': 0.21.5
+ '@esbuild/win32-arm64': 0.21.5
+ '@esbuild/win32-ia32': 0.21.5
+ '@esbuild/win32-x64': 0.21.5
+
+ optionalDependencies:
+ '@esbuild/aix-ppc64': 0.25.12
+ '@esbuild/android-arm': 0.25.12
+ '@esbuild/android-arm64': 0.25.12
+ '@esbuild/android-x64': 0.25.12
+ '@esbuild/darwin-arm64': 0.25.12
+ '@esbuild/darwin-x64': 0.25.12
+ '@esbuild/freebsd-arm64': 0.25.12
+ '@esbuild/freebsd-x64': 0.25.12
+ '@esbuild/linux-arm': 0.25.12
+ '@esbuild/linux-arm64': 0.25.12
+ '@esbuild/linux-ia32': 0.25.12
+ '@esbuild/linux-loong64': 0.25.12
+ '@esbuild/linux-mips64el': 0.25.12
+ '@esbuild/linux-ppc64': 0.25.12
+ '@esbuild/linux-riscv64': 0.25.12
+ '@esbuild/linux-s390x': 0.25.12
+ '@esbuild/linux-x64': 0.25.12
+ '@esbuild/netbsd-arm64': 0.25.12
+ '@esbuild/netbsd-x64': 0.25.12
+ '@esbuild/openbsd-arm64': 0.25.12
+ '@esbuild/openbsd-x64': 0.25.12
+ '@esbuild/openharmony-arm64': 0.25.12
+ '@esbuild/sunos-x64': 0.25.12
+ '@esbuild/win32-arm64': 0.25.12
+ '@esbuild/win32-ia32': 0.25.12
+ '@esbuild/win32-x64': 0.25.12
+
+ optionalDependencies:
+ '@esbuild/aix-ppc64': 0.27.4
+ '@esbuild/android-arm': 0.27.4
+ '@esbuild/android-arm64': 0.27.4
+ '@esbuild/android-x64': 0.27.4
+ '@esbuild/darwin-arm64': 0.27.4
+ '@esbuild/darwin-x64': 0.27.4
+ '@esbuild/freebsd-arm64': 0.27.4
+ '@esbuild/freebsd-x64': 0.27.4
+ '@esbuild/linux-arm': 0.27.4
+ '@esbuild/linux-arm64': 0.27.4
+ '@esbuild/linux-ia32': 0.27.4
+ '@esbuild/linux-loong64': 0.27.4
+ '@esbuild/linux-mips64el': 0.27.4
+ '@esbuild/linux-ppc64': 0.27.4
+ '@esbuild/linux-riscv64': 0.27.4
+ '@esbuild/linux-s390x': 0.27.4
+ '@esbuild/linux-x64': 0.27.4
+ '@esbuild/netbsd-arm64': 0.27.4
+ '@esbuild/netbsd-x64': 0.27.4
+ '@esbuild/openbsd-arm64': 0.27.4
+ '@esbuild/openbsd-x64': 0.27.4
+ '@esbuild/openharmony-arm64': 0.27.4
+ '@esbuild/sunos-x64': 0.27.4
+ '@esbuild/win32-arm64': 0.27.4
+ '@esbuild/win32-ia32': 0.27.4
+ '@esbuild/win32-x64': 0.27.4
+
+
+ dependencies:
+ esprima: 4.0.1
+ estraverse: 5.3.0
+ esutils: 2.0.3
+ optionalDependencies:
+ source-map: 0.6.1
+
+
+
+ dependencies:
+ '@types/estree': 1.0.8
+
+
+ dependencies:
+ bare-events: 2.8.2
+ transitivePeerDependencies:
+ - bare-abort-controller
+
+
+ dependencies:
+ debug: 4.4.3
+ get-stream: 5.2.0
+ yauzl: 2.10.0
+ optionalDependencies:
+ '@types/yauzl': 2.10.3
+ transitivePeerDependencies:
+ - supports-color
+
+
+ dependencies:
+ '@nodelib/fs.stat': 2.0.5
+ '@nodelib/fs.walk': 1.2.8
+ glob-parent: 5.1.2
+ merge2: 1.4.1
+ micromatch: 4.0.8
+
+ dependencies:
+ reusify: 1.1.0
+
+ dependencies:
+ pend: 1.2.0
+
+ optionalDependencies:
+ picomatch: 4.0.3
+
+ dependencies:
+ to-regex-range: 5.0.1
+
+ dependencies:
+ magic-string: 0.30.21
+ mlly: 1.8.2
+ rollup: 4.59.0
+
+ dependencies:
+ cross-spawn: 7.0.6
+ signal-exit: 4.1.0
+
+
+ optional: true
+
+
+
+
+ dependencies:
+ pump: 3.0.4
+
+ dependencies:
+ resolve-pkg-maps: 1.0.0
+
+ dependencies:
+ basic-ftp: 5.2.0
+ data-uri-to-buffer: 6.0.2
+ debug: 4.4.3
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ is-glob: 4.0.3
+
+ dependencies:
+ is-glob: 4.0.3
+
+ dependencies:
+ foreground-child: 3.3.1
+ jackspeak: 3.4.3
+ minimatch: 9.0.9
+ minipass: 7.1.3
+ package-json-from-dist: 1.0.1
+ path-scurry: 1.11.1
+
+
+ dependencies:
+ function-bind: 1.1.2
+
+
+ dependencies:
+ '@exodus/bytes': 1.15.0
+ transitivePeerDependencies:
+ - '@noble/hashes'
+
+
+
+ dependencies:
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+ domutils: 3.2.2
+ entities: 7.0.1
+
+ dependencies:
+ agent-base: 7.1.4
+ debug: 4.4.3
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ agent-base: 7.1.4
+ debug: 4.4.3
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ safer-buffer: 2.1.2
+
+ dependencies:
+ parent-module: 1.0.1
+ resolve-from: 4.0.0
+
+
+
+ dependencies:
+ binary-extensions: 2.3.0
+
+ dependencies:
+ hasown: 2.0.2
+
+
+
+
+ dependencies:
+ is-extglob: 2.1.1
+
+ dependencies:
+ is-docker: 3.0.0
+
+
+
+ dependencies:
+ is-inside-container: 1.0.0
+
+
+
+ dependencies:
+ istanbul-lib-coverage: 3.2.2
+ make-dir: 4.0.0
+ supports-color: 7.2.0
+
+ dependencies:
+ '@jridgewell/trace-mapping': 0.3.31
+ debug: 4.4.3
+ istanbul-lib-coverage: 3.2.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ html-escaper: 2.0.2
+ istanbul-lib-report: 3.0.1
+
+ dependencies:
+ '@isaacs/cliui': 8.0.2
+ optionalDependencies:
+ '@pkgjs/parseargs': 0.11.0
+
+
+
+
+
+
+ dependencies:
+ argparse: 2.0.1
+
+ dependencies:
+ '@asamuzakjp/css-color': 5.0.1
+ '@asamuzakjp/dom-selector': 7.0.4
+ '@bramus/specificity': 2.4.2
+ '@csstools/css-syntax-patches-for-csstree': 1.1.1([email protected])
+ '@exodus/bytes': 1.15.0
+ css-tree: 3.2.1
+ data-urls: 7.0.0
+ decimal.js: 10.6.0
+ html-encoding-sniffer: 6.0.0
+ is-potential-custom-element-name: 1.0.1
+ lru-cache: 11.2.7
+ parse5: 8.0.0
+ saxes: 6.0.0
+ symbol-tree: 3.2.4
+ tough-cookie: 6.0.1
+ undici: 7.24.5
+ w3c-xmlserializer: 5.0.0
+ webidl-conversions: 8.0.1
+ whatwg-mimetype: 5.0.0
+ whatwg-url: 16.0.1
+ xml-name-validator: 5.0.0
+ transitivePeerDependencies:
+ - '@noble/hashes'
+
+
+
+
+
+
+ dependencies:
+ css-select: 5.2.2
+ cssom: 0.5.0
+ html-escaper: 3.0.3
+ htmlparser2: 10.1.0
+ uhyphen: 0.2.0
+
+
+
+ dependencies:
+ js-tokens: 4.0.0
+
+
+
+
+ dependencies:
+ yallist: 3.1.1
+
+
+ dependencies:
+ '@jridgewell/sourcemap-codec': 1.5.5
+
+ dependencies:
+ '@babel/parser': 7.29.2
+ '@babel/types': 7.29.0
+ source-map-js: 1.2.1
+
+ dependencies:
+ semver: 7.7.4
+
+
+
+ dependencies:
+ braces: 3.0.3
+ picomatch: 2.3.1
+
+
+ dependencies:
+ mime-db: 1.54.0
+
+ dependencies:
+ brace-expansion: 5.0.4
+
+ dependencies:
+ brace-expansion: 2.0.2
+
+
+
+ dependencies:
+ acorn: 8.16.0
+ pathe: 2.0.3
+ pkg-types: 1.3.1
+ ufo: 1.6.3
+
+
+ dependencies:
+ any-promise: 1.3.0
+ object-assign: 4.1.1
+ thenify-all: 1.6.0
+
+
+
+
+
+ dependencies:
+ boolbase: 1.0.0
+
+
+
+ dependencies:
+ wrappy: 1.0.2
+
+ dependencies:
+ default-browser: 5.5.0
+ define-lazy-prop: 3.0.0
+ is-inside-container: 1.0.0
+ wsl-utils: 0.1.0
+
+ dependencies:
+ '@tootallnate/quickjs-emscripten': 0.23.0
+ agent-base: 7.1.4
+ debug: 4.4.3
+ get-uri: 6.0.5
+ http-proxy-agent: 7.0.2
+ https-proxy-agent: 7.0.6
+ pac-resolver: 7.0.1
+ socks-proxy-agent: 8.0.5
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ degenerator: 5.0.1
+ netmask: 2.0.2
+
+
+ dependencies:
+ callsites: 3.1.0
+
+ dependencies:
+ '@babel/code-frame': 7.29.0
+ error-ex: 1.3.4
+ json-parse-even-better-errors: 2.3.1
+ lines-and-columns: 1.2.4
+
+ dependencies:
+ domhandler: 5.0.3
+ parse5: 7.3.0
+
+ dependencies:
+ parse5: 7.3.0
+
+ dependencies:
+ entities: 6.0.1
+
+ dependencies:
+ entities: 6.0.1
+
+
+
+ dependencies:
+ lru-cache: 10.4.3
+ minipass: 7.1.3
+
+
+
+
+
+
+
+
+
+ dependencies:
+ confbox: 0.1.8
+ mlly: 1.8.2
+ pathe: 2.0.3
+
+ dependencies:
+ postcss: 8.5.8
+ postcss-value-parser: 4.2.0
+ read-cache: 1.0.0
+ resolve: 1.22.11
+
+ dependencies:
+ camelcase-css: 2.0.1
+ postcss: 8.5.8
+
+ dependencies:
+ lilconfig: 3.1.3
+ optionalDependencies:
+ jiti: 1.21.7
+ postcss: 8.5.8
+ tsx: 4.21.0
+
+ dependencies:
+ postcss: 8.5.8
+ postcss-selector-parser: 6.1.2
+
+ dependencies:
+ cssesc: 3.0.0
+ util-deprecate: 1.0.2
+
+
+ dependencies:
+ nanoid: 3.3.11
+ picocolors: 1.1.1
+ source-map-js: 1.2.1
+
+
+ dependencies:
+ agent-base: 7.1.4
+ debug: 4.4.3
+ http-proxy-agent: 7.0.2
+ https-proxy-agent: 7.0.6
+ lru-cache: 7.18.3
+ pac-proxy-agent: 7.2.0
+ proxy-from-env: 1.1.0
+ socks-proxy-agent: 8.0.5
+ transitivePeerDependencies:
+ - supports-color
+
+
+ dependencies:
+ end-of-stream: 1.4.5
+ once: 1.4.0
+
+
+ dependencies:
+ '@puppeteer/browsers': 2.13.0
+ chromium-bidi: 14.0.0([email protected])
+ debug: 4.4.3
+ devtools-protocol: 0.0.1581282
+ typed-query-selector: 2.12.1
+ webdriver-bidi-protocol: 0.4.1
+ ws: 8.19.0
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - bare-buffer
+ - bufferutil
+ - react-native-b4a
+ - supports-color
+ - utf-8-validate
+
+ dependencies:
+ '@puppeteer/browsers': 2.13.0
+ chromium-bidi: 14.0.0([email protected])
+ cosmiconfig: 9.0.1([email protected])
+ devtools-protocol: 0.0.1581282
+ puppeteer-core: 24.40.0
+ typed-query-selector: 2.12.1
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - bare-buffer
+ - bufferutil
+ - react-native-b4a
+ - supports-color
+ - typescript
+ - utf-8-validate
+
+
+ dependencies:
+ loose-envify: 1.4.0
+ react: 18.3.1
+ scheduler: 0.23.2
+
+
+ dependencies:
+ loose-envify: 1.4.0
+
+ dependencies:
+ pify: 2.3.0
+
+ dependencies:
+ picomatch: 2.3.1
+
+
+
+
+
+
+
+ dependencies:
+ is-core-module: 2.16.1
+ path-parse: 1.0.7
+ supports-preserve-symlinks-flag: 1.0.0
+
+
+ dependencies:
+ '@types/estree': 1.0.8
+ optionalDependencies:
+ '@rollup/rollup-android-arm-eabi': 4.59.0
+ '@rollup/rollup-android-arm64': 4.59.0
+ '@rollup/rollup-darwin-arm64': 4.59.0
+ '@rollup/rollup-darwin-x64': 4.59.0
+ '@rollup/rollup-freebsd-arm64': 4.59.0
+ '@rollup/rollup-freebsd-x64': 4.59.0
+ '@rollup/rollup-linux-arm-gnueabihf': 4.59.0
+ '@rollup/rollup-linux-arm-musleabihf': 4.59.0
+ '@rollup/rollup-linux-arm64-gnu': 4.59.0
+ '@rollup/rollup-linux-arm64-musl': 4.59.0
+ '@rollup/rollup-linux-loong64-gnu': 4.59.0
+ '@rollup/rollup-linux-loong64-musl': 4.59.0
+ '@rollup/rollup-linux-ppc64-gnu': 4.59.0
+ '@rollup/rollup-linux-ppc64-musl': 4.59.0
+ '@rollup/rollup-linux-riscv64-gnu': 4.59.0
+ '@rollup/rollup-linux-riscv64-musl': 4.59.0
+ '@rollup/rollup-linux-s390x-gnu': 4.59.0
+ '@rollup/rollup-linux-x64-gnu': 4.59.0
+ '@rollup/rollup-linux-x64-musl': 4.59.0
+ '@rollup/rollup-openbsd-x64': 4.59.0
+ '@rollup/rollup-openharmony-arm64': 4.59.0
+ '@rollup/rollup-win32-arm64-msvc': 4.59.0
+ '@rollup/rollup-win32-ia32-msvc': 4.59.0
+ '@rollup/rollup-win32-x64-gnu': 4.59.0
+ '@rollup/rollup-win32-x64-msvc': 4.59.0
+ fsevents: 2.3.3
+
+
+ dependencies:
+ queue-microtask: 1.2.3
+
+ dependencies:
+ tslib: 2.8.1
+
+
+ dependencies:
+ xmlchars: 2.2.0
+
+ dependencies:
+ loose-envify: 1.4.0
+
+
+
+ dependencies:
+ shebang-regex: 3.0.0
+
+
+
+
+
+
+
+ dependencies:
+ agent-base: 7.1.4
+ debug: 4.4.3
+ socks: 2.8.7
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ ip-address: 10.1.0
+ smart-buffer: 4.2.0
+
+
+ optional: true
+
+
+
+
+
+ dependencies:
+ events-universal: 1.0.1
+ fast-fifo: 1.3.2
+ text-decoder: 1.2.7
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - react-native-b4a
+
+ dependencies:
+ emoji-regex: 8.0.0
+ is-fullwidth-code-point: 3.0.0
+ strip-ansi: 6.0.1
+
+ dependencies:
+ eastasianwidth: 0.2.0
+ emoji-regex: 9.2.2
+ strip-ansi: 7.2.0
+
+ dependencies:
+ ansi-regex: 5.0.1
+
+ dependencies:
+ ansi-regex: 6.2.2
+
+ dependencies:
+ js-tokens: 9.0.1
+
+
+ dependencies:
+ '@jridgewell/gen-mapping': 0.3.13
+ commander: 4.1.1
+ lines-and-columns: 1.2.4
+ mz: 2.7.0
+ pirates: 4.0.7
+ tinyglobby: 0.2.15
+ ts-interface-checker: 0.1.13
+
+ dependencies:
+ has-flag: 4.0.0
+
+ dependencies:
+ has-flag: 4.0.0
+
+
+
+ dependencies:
+ '@alloc/quick-lru': 5.2.0
+ arg: 5.0.2
+ chokidar: 3.6.0
+ didyoumean: 1.2.2
+ dlv: 1.1.3
+ fast-glob: 3.3.3
+ glob-parent: 6.0.2
+ is-glob: 4.0.3
+ jiti: 1.21.7
+ lilconfig: 3.1.3
+ micromatch: 4.0.8
+ normalize-path: 3.0.0
+ object-hash: 3.0.0
+ picocolors: 1.1.1
+ postcss: 8.5.8
+ postcss-import: 15.1.0([email protected])
+ postcss-js: 4.1.0([email protected])
+ postcss-nested: 6.2.0([email protected])
+ postcss-selector-parser: 6.1.2
+ resolve: 1.22.11
+ sucrase: 3.35.1
+ transitivePeerDependencies:
+ - tsx
+ - yaml
+
+ dependencies:
+ pump: 3.0.4
+ tar-stream: 3.1.8
+ optionalDependencies:
+ bare-fs: 4.5.6
+ bare-path: 3.0.0
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - bare-buffer
+ - react-native-b4a
+
+ dependencies:
+ b4a: 1.8.0
+ bare-fs: 4.5.6
+ fast-fifo: 1.3.2
+ streamx: 2.25.0
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - bare-buffer
+ - react-native-b4a
+
+ dependencies:
+ streamx: 2.25.0
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - react-native-b4a
+
+ dependencies:
+ '@istanbuljs/schema': 0.1.3
+ glob: 10.5.0
+ minimatch: 10.2.4
+
+ dependencies:
+ b4a: 1.8.0
+ transitivePeerDependencies:
+ - react-native-b4a
+
+ dependencies:
+ thenify: 3.3.1
+
+ dependencies:
+ any-promise: 1.3.0
+
+
+
+ dependencies:
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.3
+
+
+
+
+
+ dependencies:
+ tldts-core: 7.0.27
+
+ dependencies:
+ is-number: 7.0.0
+
+ dependencies:
+ tldts: 7.0.27
+
+ dependencies:
+ punycode: 2.3.1
+
+
+
+
+ dependencies:
+ bundle-require: 5.1.0([email protected])
+ cac: 6.7.14
+ chokidar: 4.0.3
+ consola: 3.4.2
+ debug: 4.4.3
+ esbuild: 0.27.4
+ fix-dts-default-cjs-exports: 1.0.1
+ joycon: 3.1.1
+ picocolors: 1.1.1
+ resolve-from: 5.0.0
+ rollup: 4.59.0
+ source-map: 0.7.6
+ sucrase: 3.35.1
+ tinyexec: 0.3.2
+ tinyglobby: 0.2.15
+ tree-kill: 1.2.2
+ optionalDependencies:
+ postcss: 8.5.8
+ typescript: 5.9.3
+ transitivePeerDependencies:
+ - jiti
+ - supports-color
+ - tsx
+ - yaml
+
+ dependencies:
+ esbuild: 0.27.4
+ get-tsconfig: 4.13.6
+ optionalDependencies:
+ fsevents: 2.3.3
+
+
+
+
+
+
+
+
+
+
+ dependencies:
+ browserslist: 4.28.1
+ escalade: 3.2.0
+ picocolors: 1.1.1
+
+ dependencies:
+ react: 18.3.1
+
+
+ dependencies:
+ cac: 6.7.14
+ debug: 4.4.3
+ es-module-lexer: 1.7.0
+ pathe: 2.0.3
+ vite: 5.4.21(@types/[email protected])
+ transitivePeerDependencies:
+ - '@types/node'
+ - less
+ - lightningcss
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+
+ dependencies:
+ esbuild: 0.21.5
+ postcss: 8.5.8
+ rollup: 4.59.0
+ optionalDependencies:
+ '@types/node': 24.12.0
+ fsevents: 2.3.3
+
+ dependencies:
+ esbuild: 0.21.5
+ postcss: 8.5.8
+ rollup: 4.59.0
+ optionalDependencies:
+ '@types/node': 25.5.0
+ fsevents: 2.3.3
+
+ dependencies:
+ '@types/chai': 5.2.3
+ '@vitest/expect': 3.2.4
+ '@vitest/mocker': 3.2.4([email protected](@types/[email protected]))
+ '@vitest/pretty-format': 3.2.4
+ '@vitest/runner': 3.2.4
+ '@vitest/snapshot': 3.2.4
+ '@vitest/spy': 3.2.4
+ '@vitest/utils': 3.2.4
+ chai: 5.3.3
+ debug: 4.4.3
+ expect-type: 1.3.0
+ magic-string: 0.30.21
+ pathe: 2.0.3
+ picomatch: 4.0.3
+ std-env: 3.10.0
+ tinybench: 2.9.0
+ tinyexec: 0.3.2
+ tinyglobby: 0.2.15
+ tinypool: 1.1.1
+ tinyrainbow: 2.0.0
+ vite: 5.4.21(@types/[email protected])
+ vite-node: 3.2.4(@types/[email protected])
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@types/node': 24.12.0
+ jsdom: 29.0.1
+ transitivePeerDependencies:
+ - less
+ - lightningcss
+ - msw
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+
+
+ dependencies:
+ xml-name-validator: 5.0.0
+
+
+
+ dependencies:
+ iconv-lite: 0.6.3
+
+
+
+ dependencies:
+ '@exodus/bytes': 1.15.0
+ tr46: 6.0.0
+ webidl-conversions: 8.0.1
+ transitivePeerDependencies:
+ - '@noble/hashes'
+
+ dependencies:
+ isexe: 2.0.0
+
+ dependencies:
+ siginfo: 2.0.0
+ stackback: 0.0.2
+
+ dependencies:
+ ansi-styles: 4.3.0
+ string-width: 4.2.3
+ strip-ansi: 6.0.1
+
+ dependencies:
+ ansi-styles: 6.2.3
+ string-width: 5.1.2
+ strip-ansi: 7.2.0
+
+
+
+ dependencies:
+ is-wsl: 3.1.1
+
+
+
+
+
+
+ dependencies:
+ cliui: 8.0.1
+ escalade: 3.2.0
+ get-caller-file: 2.0.5
+ require-directory: 2.1.1
+ string-width: 4.2.3
+ y18n: 5.0.8
+ yargs-parser: 21.1.1
+
+ dependencies:
+ buffer-crc32: 0.2.13
+ fd-slicer: 1.1.0
+
+
+ dependencies:
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ '@types/react': 19.2.14
+ react: 18.3.1