@open-take/runtime 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cdp-capture-0qW8oOct.js +3 -0
  3. package/dist/cdp-capture-CWFbnK9C.js +1078 -0
  4. package/dist/cdp-capture-CWFbnK9C.js.map +1 -0
  5. package/dist/index.d.ts +345 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +986 -0
  8. package/dist/index.js.map +1 -0
  9. package/editor-dist/assets/geist-mono-cyrillic-400-normal-C51Di1Mf.woff2 +0 -0
  10. package/editor-dist/assets/geist-mono-cyrillic-400-normal-CPJFfJgk.woff +0 -0
  11. package/editor-dist/assets/geist-mono-cyrillic-500-normal-D2cXvDHF.woff2 +0 -0
  12. package/editor-dist/assets/geist-mono-cyrillic-500-normal-DfuvdVgn.woff +0 -0
  13. package/editor-dist/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
  14. package/editor-dist/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
  15. package/editor-dist/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
  16. package/editor-dist/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
  17. package/editor-dist/assets/geist-mono-latin-ext-400-normal-CfzLURNc.woff +0 -0
  18. package/editor-dist/assets/geist-mono-latin-ext-400-normal-DI-rJ0UV.woff2 +0 -0
  19. package/editor-dist/assets/geist-mono-latin-ext-500-normal-Buglb9-a.woff2 +0 -0
  20. package/editor-dist/assets/geist-mono-latin-ext-500-normal-CrWEgvU_.woff +0 -0
  21. package/editor-dist/assets/geist-mono-symbols2-400-normal-DjbiTEEA.woff +0 -0
  22. package/editor-dist/assets/geist-mono-symbols2-500-normal-CmnCPGa0.woff +0 -0
  23. package/editor-dist/assets/geist-mono-vietnamese-400-normal-CZEPLOgu.woff +0 -0
  24. package/editor-dist/assets/geist-mono-vietnamese-500-normal-Dx9-epDo.woff +0 -0
  25. package/editor-dist/assets/index-W0-YQO1h.js +49 -0
  26. package/editor-dist/assets/index-vf4XvOcQ.css +1 -0
  27. package/editor-dist/assets/instrument-sans-latin-ext-wght-normal-B5bTHO_g.woff2 +0 -0
  28. package/editor-dist/assets/instrument-sans-latin-wght-normal-BbzFLZTg.woff2 +0 -0
  29. package/editor-dist/index.html +15 -0
  30. package/editor-dist/sample/capture.json +113 -0
  31. package/editor-dist/sample/capture.mp4 +0 -0
  32. package/editor-dist/sample/composition.json +233 -0
  33. package/package.json +55 -0
package/dist/index.js ADDED
@@ -0,0 +1,986 @@
1
+ import { captureTake, captureTakeCDP, ensureChrome, inspectPage, resolveChrome } from "./cdp-capture-CWFbnK9C.js";
2
+ import { appendFile, copyFile, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { basename, dirname, extname, join, normalize, resolve } from "node:path";
5
+ import { FINISH, LOOKS, MOTION, ZOOM_LEVELS, finishName, formatIssues, formatIssues as formatIssues$1, lookName, motionName, planComposition, renderTake, resolveFfmpeg, validateComposition, validateComposition as validateComposition$1, zoomLevelName } from "@open-take/compositor";
6
+ import { spawn } from "node:child_process";
7
+ import { createReadStream, statSync } from "node:fs";
8
+ import { createServer } from "node:http";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ //#region src/take.ts
12
+ async function isFile(p) {
13
+ return (await stat(p).catch(() => null))?.isFile() ?? false;
14
+ }
15
+ /** Strip any known take suffix to get the shared base, then derive the family.
16
+ * A directory picks the `*.composition.json` that has a sibling capture. */
17
+ async function resolveTakePaths(input) {
18
+ let p = resolve(input);
19
+ const s = await stat(p).catch(() => null);
20
+ if (s?.isDirectory()) {
21
+ const comps = (await readdir(p)).filter((e) => /\.composition\.json$/i.test(e));
22
+ if (comps.length === 0) throw new Error(`no *.composition.json found in ${p}`);
23
+ let pick = comps[0];
24
+ for (const c of comps) {
25
+ const base$1 = join(p, c.replace(/\.composition\.json$/i, ""));
26
+ if (await isFile(`${base$1}.capture.mp4`)) {
27
+ pick = c;
28
+ break;
29
+ }
30
+ }
31
+ p = join(p, pick);
32
+ }
33
+ const base = p.replace(/\.composition\.json$/i, "").replace(/\.capture\.json$/i, "").replace(/\.capture\.mp4$/i, "").replace(/\.review\.mp4$/i, "").replace(/\.ab\.mp4$/i, "").replace(/\.prev\.mp4$/i, "").replace(/\.mp4$/i, "");
34
+ return {
35
+ base,
36
+ name: basename(base),
37
+ mp4Path: `${base}.mp4`,
38
+ compositionPath: `${base}.composition.json`,
39
+ capturePath: `${base}.capture.mp4`,
40
+ captureLogPath: `${base}.capture.json`,
41
+ reviewPath: `${base}.review.mp4`,
42
+ abPath: `${base}.ab.mp4`,
43
+ prevPath: `${base}.prev.mp4`
44
+ };
45
+ }
46
+ /** Friendly preflight: verbs die with a clear message instead of a raw ffmpeg
47
+ * ENOENT when a take is missing the files they need. Old takes (or cleaned
48
+ * ones) may have a composition + mp4 but no kept capture — those can be
49
+ * watched but not re-rendered. */
50
+ async function requireTakeFiles(take, opts = {}) {
51
+ if (!await isFile(take.compositionPath)) throw new Error(`missing ${take.compositionPath} — not a take produced by \`make\` (or the wrong path)`);
52
+ if (opts.capture && !await isFile(take.capturePath)) throw new Error(`this take has no kept capture (${take.capturePath}) — re-rendering needs the frozen recording.\nTakes made before capture-keeping (or cleaned up) can't be re-rendered; run \`make\` again for a refinable take.`);
53
+ }
54
+ /** Stage a copy of the current master so it becomes `<base>.prev.mp4` only
55
+ * AFTER the next render succeeds. A refused (validator) or crashed render
56
+ * must NOT clobber the existing revert point — that would make "keep the old
57
+ * one" replay the wrong version. No-op when there is no master yet. This is
58
+ * what makes "A" (keep the old one) a mechanical revert instead of a memory. */
59
+ async function stagePrev(mp4Path, prevPath) {
60
+ if (!await isFile(mp4Path)) return {
61
+ commit: async () => {},
62
+ abort: async () => {}
63
+ };
64
+ const pending = `${prevPath}.pending`;
65
+ await copyFile(mp4Path, pending);
66
+ return {
67
+ commit: () => rename(pending, prevPath),
68
+ abort: () => rm(pending, { force: true })
69
+ };
70
+ }
71
+
72
+ //#endregion
73
+ //#region src/edit-server.ts
74
+ const CONTENT_TYPE = {
75
+ ".html": "text/html; charset=utf-8",
76
+ ".js": "text/javascript; charset=utf-8",
77
+ ".mjs": "text/javascript; charset=utf-8",
78
+ ".css": "text/css; charset=utf-8",
79
+ ".json": "application/json; charset=utf-8",
80
+ ".svg": "image/svg+xml",
81
+ ".png": "image/png",
82
+ ".jpg": "image/jpeg",
83
+ ".ico": "image/x-icon",
84
+ ".woff2": "font/woff2",
85
+ ".woff": "font/woff",
86
+ ".map": "application/json; charset=utf-8"
87
+ };
88
+ /** Locate the built editor SPA: a bundled copy (published package) first, then
89
+ * the monorepo build. */
90
+ function resolveEditorDist() {
91
+ const here = fileURLToPath(import.meta.url);
92
+ const pkgRoot = resolve(here, "..", "..");
93
+ const candidates = [resolve(pkgRoot, "editor-dist"), resolve(pkgRoot, "..", "..", "apps", "editor", "dist")];
94
+ return candidates.find((c) => existsHtml(c)) ?? null;
95
+ }
96
+ function existsHtml(dir) {
97
+ return existsFile(join(dir, "index.html"));
98
+ }
99
+ function existsFile(path) {
100
+ try {
101
+ return statSync(path).isFile();
102
+ } catch {
103
+ return false;
104
+ }
105
+ }
106
+ const sendJson = (res, status, obj) => {
107
+ const body = JSON.stringify(obj);
108
+ res.writeHead(status, {
109
+ "Content-Type": "application/json; charset=utf-8",
110
+ "Content-Length": Buffer.byteLength(body)
111
+ });
112
+ res.end(body);
113
+ };
114
+ async function readBody(req, capBytes = 32 * 1024 * 1024) {
115
+ const chunks = [];
116
+ let size = 0;
117
+ for await (const c of req) {
118
+ size += c.length;
119
+ if (size > capBytes) throw new Error("request body too large");
120
+ chunks.push(c);
121
+ }
122
+ return Buffer.concat(chunks).toString("utf8");
123
+ }
124
+ /** Stream a file with HTTP Range support (206) — required for <video> seeking. */
125
+ async function serveFile(req, res, filePath) {
126
+ const st = await stat(filePath).catch(() => null);
127
+ if (!st?.isFile()) {
128
+ sendJson(res, 404, { error: "not found" });
129
+ return;
130
+ }
131
+ const type = CONTENT_TYPE[extname(filePath).toLowerCase()] ?? "application/octet-stream";
132
+ const range = req.headers.range;
133
+ if (range) {
134
+ const m = /bytes=(\d*)-(\d*)/.exec(range);
135
+ const start = m?.[1] ? Number(m[1]) : 0;
136
+ const end = m?.[2] ? Number(m[2]) : st.size - 1;
137
+ if (start >= st.size || end >= st.size || start > end) {
138
+ res.writeHead(416, { "Content-Range": `bytes */${st.size}` });
139
+ res.end();
140
+ return;
141
+ }
142
+ res.writeHead(206, {
143
+ "Content-Range": `bytes ${start}-${end}/${st.size}`,
144
+ "Accept-Ranges": "bytes",
145
+ "Content-Length": end - start + 1,
146
+ "Content-Type": type
147
+ });
148
+ createReadStream(filePath, {
149
+ start,
150
+ end
151
+ }).pipe(res);
152
+ } else {
153
+ res.writeHead(200, {
154
+ "Content-Length": st.size,
155
+ "Accept-Ranges": "bytes",
156
+ "Content-Type": type
157
+ });
158
+ createReadStream(filePath).pipe(res);
159
+ }
160
+ }
161
+ function openBrowser(url) {
162
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
163
+ try {
164
+ spawn(cmd, [url], {
165
+ stdio: "ignore",
166
+ detached: true,
167
+ shell: process.platform === "win32"
168
+ }).unref();
169
+ } catch {}
170
+ }
171
+ async function startEditServer(opts) {
172
+ const take = await resolveTakePaths(opts.takePath);
173
+ for (const f of [take.compositionPath, take.capturePath]) if (!(await stat(f).catch(() => null))?.isFile()) throw new Error(`missing take file: ${f}`);
174
+ const dist = resolveEditorDist();
175
+ if (!dist) throw new Error("editor build not found — run `pnpm --filter @open-take/editor build` first");
176
+ const loadCaptureLog = async () => {
177
+ try {
178
+ return JSON.parse(await readFile(take.captureLogPath, "utf8"));
179
+ } catch {
180
+ return null;
181
+ }
182
+ };
183
+ let job = null;
184
+ let jobSeq = 0;
185
+ /** Atomic write (tmp + rename) — agents read this file concurrently. */
186
+ const persistComposition = async (comp) => {
187
+ const tmp = `${take.compositionPath}.tmp`;
188
+ await writeFile(tmp, JSON.stringify(comp, null, 2));
189
+ await rename(tmp, take.compositionPath);
190
+ };
191
+ const server = createServer(async (req, res) => {
192
+ try {
193
+ const url$1 = new URL(req.url ?? "/", "http://localhost");
194
+ const path = url$1.pathname;
195
+ const method = req.method ?? "GET";
196
+ if (method === "POST") {
197
+ const host = req.headers.host ?? "";
198
+ const origin = req.headers.origin;
199
+ const sameOrigin = !origin || origin === `http://${host}`;
200
+ const isJson = (req.headers["content-type"] ?? "").includes("application/json");
201
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) || !sameOrigin || !isJson) {
202
+ sendJson(res, 403, { error: "forbidden" });
203
+ return;
204
+ }
205
+ }
206
+ if (path === "/api/take" && method === "GET") {
207
+ const composition = JSON.parse(await readFile(take.compositionPath, "utf8"));
208
+ const captureLog = await loadCaptureLog();
209
+ sendJson(res, 200, {
210
+ composition,
211
+ captureLog,
212
+ source: { name: take.name },
213
+ videoUrl: "/api/take/video",
214
+ mp4Url: "/api/take/output"
215
+ });
216
+ return;
217
+ }
218
+ if (path === "/api/take/video" && method === "GET") {
219
+ await serveFile(req, res, take.capturePath);
220
+ return;
221
+ }
222
+ if (path === "/api/take/mtime" && method === "GET") {
223
+ const st = await stat(take.compositionPath).catch(() => null);
224
+ sendJson(res, 200, { mtime: st ? st.mtimeMs : 0 });
225
+ return;
226
+ }
227
+ if (path === "/api/notes" && method === "POST") {
228
+ const { text } = JSON.parse(await readBody(req));
229
+ if (!text?.trim()) {
230
+ sendJson(res, 400, { error: "empty note" });
231
+ return;
232
+ }
233
+ const line = text.trim().replace(/\s+/g, " ").slice(0, 2e3);
234
+ await appendFile(`${take.base}.notes.md`, `- ${line}\n`);
235
+ process.stdout.write(`NOTE ${JSON.stringify({
236
+ take: take.name,
237
+ text: line
238
+ })}\n`);
239
+ sendJson(res, 200, { ok: true });
240
+ return;
241
+ }
242
+ if (path === "/api/take/output" && method === "GET") {
243
+ await serveFile(req, res, take.mp4Path);
244
+ return;
245
+ }
246
+ if (path === "/api/composition" && method === "POST") {
247
+ const comp = JSON.parse(await readBody(req));
248
+ const captureLog = await loadCaptureLog();
249
+ const issues = validateComposition$1(comp, captureLog ? { captureLog } : {});
250
+ const errors = issues.filter((i) => i.severity === "error");
251
+ if (errors.length) {
252
+ sendJson(res, 400, { issues });
253
+ return;
254
+ }
255
+ await persistComposition(comp);
256
+ sendJson(res, 200, {
257
+ ok: true,
258
+ issues
259
+ });
260
+ return;
261
+ }
262
+ if (path === "/api/render" && method === "POST") {
263
+ if (job?.status === "running") {
264
+ sendJson(res, 409, { error: "a render is already in progress" });
265
+ return;
266
+ }
267
+ const comp = JSON.parse(await readBody(req));
268
+ const captureLog = await loadCaptureLog() ?? void 0;
269
+ const issues = validateComposition$1(comp, captureLog ? { captureLog } : {});
270
+ const errors = issues.filter((i) => i.severity === "error");
271
+ if (errors.length) {
272
+ sendJson(res, 400, { issues });
273
+ return;
274
+ }
275
+ await persistComposition(comp);
276
+ const id = `${Date.now().toString(36)}-${++jobSeq}`;
277
+ job = {
278
+ id,
279
+ progress: 0,
280
+ status: "running",
281
+ clients: new Set()
282
+ };
283
+ sendJson(res, 200, { jobId: id });
284
+ runRender(job, comp, captureLog);
285
+ return;
286
+ }
287
+ const ev = /^\/api\/render\/([^/]+)\/events$/.exec(path);
288
+ if (ev && method === "GET") {
289
+ const id = ev[1];
290
+ if (!job || job.id !== id) {
291
+ sendJson(res, 404, { error: "unknown job" });
292
+ return;
293
+ }
294
+ res.writeHead(200, {
295
+ "Content-Type": "text/event-stream",
296
+ "Cache-Control": "no-cache",
297
+ Connection: "keep-alive"
298
+ });
299
+ emit(res, "progress", { progress: job.progress });
300
+ if (job.status === "done") {
301
+ emit(res, "done", { mp4Url: job.mp4Url });
302
+ res.end();
303
+ return;
304
+ }
305
+ if (job.status === "error") {
306
+ emit(res, "failed", { message: job.error });
307
+ res.end();
308
+ return;
309
+ }
310
+ job.clients.add(res);
311
+ req.on("close", () => job?.clients.delete(res));
312
+ return;
313
+ }
314
+ if (path.startsWith("/api/")) {
315
+ sendJson(res, 404, { error: "no such endpoint" });
316
+ return;
317
+ }
318
+ if (method !== "GET") {
319
+ sendJson(res, 405, { error: "method not allowed" });
320
+ return;
321
+ }
322
+ const rel = normalize(decodeURIComponent(path)).replace(/^(\.\.[/\\])+/, "");
323
+ let filePath = join(dist, rel === "/" ? "index.html" : rel);
324
+ if (!filePath.startsWith(dist)) {
325
+ sendJson(res, 403, { error: "forbidden" });
326
+ return;
327
+ }
328
+ const fst = await stat(filePath).catch(() => null);
329
+ if (!fst?.isFile()) filePath = join(dist, "index.html");
330
+ await serveFile(req, res, filePath);
331
+ } catch (err) {
332
+ sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });
333
+ }
334
+ });
335
+ async function runRender(j, comp, captureLog) {
336
+ try {
337
+ await renderComposition({
338
+ composition: comp,
339
+ capturePath: take.capturePath,
340
+ outPath: take.mp4Path,
341
+ captureLog,
342
+ chromePath: opts.chromePath,
343
+ onProgress: (p) => {
344
+ j.progress = p;
345
+ for (const c of j.clients) emit(c, "progress", { progress: p });
346
+ }
347
+ });
348
+ j.status = "done";
349
+ j.progress = 1;
350
+ j.mp4Url = `/api/take/output?v=${Date.now().toString(36)}`;
351
+ for (const c of j.clients) {
352
+ emit(c, "done", { mp4Url: j.mp4Url });
353
+ c.end();
354
+ }
355
+ } catch (err) {
356
+ j.status = "error";
357
+ j.error = err instanceof Error ? err.message : String(err);
358
+ for (const c of j.clients) {
359
+ emit(c, "failed", { message: j.error });
360
+ c.end();
361
+ }
362
+ } finally {
363
+ j.clients.clear();
364
+ }
365
+ }
366
+ const port = await listen(server, opts.port ?? 4178);
367
+ const url = `http://127.0.0.1:${port}/`;
368
+ process.stdout.write(`open-take editor → ${url}\n(serving take "${take.name}"; Ctrl-C to stop)\n`);
369
+ if (opts.open !== false) openBrowser(url);
370
+ return {
371
+ url,
372
+ close: () => new Promise((r) => server.close(() => r()))
373
+ };
374
+ }
375
+ function emit(res, event, data) {
376
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
377
+ }
378
+ /** Bind to 127.0.0.1 only; if the port is taken, try the next few. */
379
+ function listen(server, startPort) {
380
+ return new Promise((res, rej) => {
381
+ let port = startPort;
382
+ const tryOne = () => {
383
+ server.once("error", (e) => {
384
+ if (e.code === "EADDRINUSE" && port < startPort + 20) {
385
+ port++;
386
+ tryOne();
387
+ } else rej(e);
388
+ });
389
+ server.listen(port, "127.0.0.1", () => res(port));
390
+ };
391
+ tryOne();
392
+ });
393
+ }
394
+
395
+ //#endregion
396
+ //#region src/review.ts
397
+ /** Sibling capture log (`<capture>.json`), if present — enables the
398
+ * capture-lock check; silently absent otherwise (matches index.ts). */
399
+ async function loadLogSibling(capturePath) {
400
+ try {
401
+ return JSON.parse(await readFile(resolve(capturePath).replace(/\.mp4$/i, ".json"), "utf8"));
402
+ } catch {
403
+ return void 0;
404
+ }
405
+ }
406
+ const KIND_LABEL = {
407
+ click: "click",
408
+ type: "type",
409
+ drag: "drag",
410
+ scroll: "scroll",
411
+ hover: "hover",
412
+ press: "key"
413
+ };
414
+ function beatTitle(e) {
415
+ if (e.label) return e.label;
416
+ if (e.kind === "type" && e.text) return `"${e.text}"`;
417
+ if (e.kind === "press" && e.keys) return e.keys;
418
+ return e.kind;
419
+ }
420
+ const trunc = (s, n) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
421
+ function fmtTime(ms) {
422
+ const s = Math.max(0, Math.round(ms / 1e3));
423
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
424
+ }
425
+ /** "zoom medium (×1.5)" | "zoom ×1.85 (custom)" | "wide" */
426
+ function zoomText(e) {
427
+ if (!e.zoom.enabled) return "wide";
428
+ const name = zoomLevelName(e.zoom.scale);
429
+ const x = `×${Number(e.zoom.scale.toFixed(2))}`;
430
+ return name ? `zoom ${name} (${x})` : `zoom ${x} (custom)`;
431
+ }
432
+ function buildBeatSheet(comp, name) {
433
+ const n = comp.events.length;
434
+ const look = lookName(comp.framing) ?? "custom";
435
+ const pace = motionName(comp.cursor) ?? "custom";
436
+ const finish = finishName(comp.motionBlur) ?? "custom";
437
+ const lines = [`${name} · ${(comp.durationMs / 1e3).toFixed(1)}s · ${n} beat${n === 1 ? "" : "s"} · look ${look} · pace ${pace} · finish ${finish}`];
438
+ const first = comp.events[0];
439
+ if (!first || first.zoom.inAtMs > 400) lines.push(` in 0:00 full view, cursor glides in`);
440
+ comp.events.forEach((e, i) => {
441
+ const num = String(i + 1).padStart(2, " ");
442
+ const kind = KIND_LABEL[e.kind].padEnd(6, " ");
443
+ const title = trunc(beatTitle(e), 24).padEnd(25, " ");
444
+ lines.push(` ${num} ${fmtTime(e.tMs)} ${kind} ${title} ${zoomText(e)}`);
445
+ });
446
+ const last = comp.events[n - 1];
447
+ if (last) {
448
+ const endMs = last.tMs + (last.durationMs ?? 0) + comp.cursor.holdMs;
449
+ lines.push(` out ${fmtTime(endMs)} zoom releases, holds to ${fmtTime(comp.durationMs)}`);
450
+ }
451
+ lines.push(`say it like: "beat 2: no zoom" · "tighter on beat 3" · "look: slate" · "pace: brisk"`);
452
+ return lines.join("\n");
453
+ }
454
+ const SAY_IT_CARD = `SAY IT, I'LL CUT IT
455
+ instant (~10s) zoom off / tighter / looser on a beat · re-center a beat (name the
456
+ element) · hold longer · pace: calm / natural / brisk · look:
457
+ midnight / ink / slate / ocean / plum / ember / paper / plain ·
458
+ finish: smooth / crisp / heavy · quicker intro · shorter tail
459
+ re-shoot (~1m) change what's clicked or typed · add / cut / reorder beats ·
460
+ retime an action
461
+ compare taste questions come back as an A/B reel — answer with a letter
462
+ ("B"), or "between A and B", or "none, go darker"`;
463
+ /** Badge windows: each beat owns [its zoom.inAtMs, the next beat's) — the pill
464
+ * swaps as the camera starts moving toward the beat. INTRO/TAIL bracket them. */
465
+ function buildBadges(comp) {
466
+ const n = comp.events.length;
467
+ const badges = [];
468
+ let prevStart = 0;
469
+ const starts = comp.events.map((e) => {
470
+ const s = Math.max(e.zoom.inAtMs, prevStart + 1);
471
+ prevStart = s;
472
+ return s;
473
+ });
474
+ if (n === 0 || starts[0] > 400) badges.push({
475
+ fromMs: 0,
476
+ toMs: starts[0] ?? comp.durationMs,
477
+ text: "INTRO"
478
+ });
479
+ comp.events.forEach((e, i) => {
480
+ const last = i === n - 1;
481
+ const endOwn = e.tMs + (e.durationMs ?? 0) + comp.cursor.holdMs;
482
+ const to = last ? Math.min(endOwn, comp.durationMs) : starts[i + 1];
483
+ badges.push({
484
+ fromMs: starts[i],
485
+ toMs: to,
486
+ text: `BEAT ${i + 1}/${n} · ${KIND_LABEL[e.kind]} ${trunc(beatTitle(e), 24)} · ${zoomText(e)}`
487
+ });
488
+ if (last && to < comp.durationMs + 1e3) badges.push({
489
+ fromMs: to,
490
+ toMs: comp.durationMs + 1500,
491
+ text: "TAIL"
492
+ });
493
+ });
494
+ return badges;
495
+ }
496
+ /** Draft-quality transform: 30fps cap + motion blur OFF — up to ~12× faster
497
+ * than a blurred 60fps master, close enough for composition-level notes.
498
+ * (2 blur samples would render 2× the frames for a tmix window that rounds to
499
+ * 1 — all cost, zero blur.) FEEL questions (blur, pace, zoom silkiness) must
500
+ * be judged on full quality — use `ab`. */
501
+ function toDraft(comp) {
502
+ const { motionBlur: _mb,...rest } = comp;
503
+ return {
504
+ ...rest,
505
+ output: {
506
+ ...comp.output,
507
+ fps: Math.min(30, comp.output.fps)
508
+ }
509
+ };
510
+ }
511
+ async function renderReview(take, opts = {}) {
512
+ await requireTakeFiles(take, { capture: true });
513
+ const comp = JSON.parse(await readFile(take.compositionPath, "utf8"));
514
+ const captureLog = await loadLogSibling(take.capturePath);
515
+ const chromePath = await ensureChrome(opts.chromePath);
516
+ const decorated = {
517
+ ...toDraft(comp),
518
+ review: {
519
+ watermark: "REVIEW",
520
+ badges: buildBadges(comp)
521
+ }
522
+ };
523
+ await renderTake({
524
+ composition: decorated,
525
+ videoPath: take.capturePath,
526
+ outPath: take.reviewPath,
527
+ captureLog,
528
+ logProgress: opts.logProgress ?? true,
529
+ chromePath,
530
+ writeCompositionSibling: false
531
+ });
532
+ return {
533
+ reviewPath: take.reviewPath,
534
+ sheet: buildBeatSheet(comp, take.name)
535
+ };
536
+ }
537
+ function parseSetFlag(set, beat) {
538
+ const eq = set.indexOf("=");
539
+ if (eq < 1) throw new Error(`ab: --set expects <knob>=<v1>,<v2>[,<v3>] (got "${set}")`);
540
+ const key = set.slice(0, eq).trim();
541
+ const values = set.slice(eq + 1).split(",").map((v) => v.trim()).filter(Boolean);
542
+ if (values.length < 1) throw new Error(`ab: --set ${key}= needs at least one value`);
543
+ if (values.length > 3) throw new Error(`ab: at most 3 requested values (plus current) per reel`);
544
+ if (key === "zoom") {
545
+ if (!beat) throw new Error(`ab: --set zoom=… needs --beat <n> (which beat to reframe)`);
546
+ return {
547
+ knob: {
548
+ kind: "zoom",
549
+ beat
550
+ },
551
+ values
552
+ };
553
+ }
554
+ if (key === "look" || key === "pace" || key === "finish") return {
555
+ knob: { kind: key },
556
+ values
557
+ };
558
+ if (key.includes(".")) return {
559
+ knob: {
560
+ kind: "path",
561
+ path: key
562
+ },
563
+ values
564
+ };
565
+ throw new Error(`ab: unknown knob "${key}" — use zoom (with --beat), look, pace, finish, or a raw dot-path like cursor.holdMs`);
566
+ }
567
+ function setPath(comp, path, raw) {
568
+ const t = raw.trim();
569
+ const value = t === "true" ? true : t === "false" ? false : t === "null" ? null : Number.isFinite(Number(raw)) && t !== "" ? Number(raw) : raw;
570
+ const parts = path.split(".");
571
+ const next = structuredClone(comp);
572
+ let node = next;
573
+ for (const p of parts.slice(0, -1)) {
574
+ const child = node[p];
575
+ if (typeof child !== "object" || child == null) throw new Error(`ab: path "${path}" — "${p}" is not an object`);
576
+ node = child;
577
+ }
578
+ node[parts[parts.length - 1]] = value;
579
+ return next;
580
+ }
581
+ /** Current-state description for a knob (the implicit "keep it" variant). */
582
+ function currentDesc(comp, knob) {
583
+ if (knob.kind === "zoom") {
584
+ const e = comp.events[knob.beat - 1];
585
+ return e ? zoomText(e) : "?";
586
+ }
587
+ if (knob.kind === "look") return lookName(comp.framing) ?? "custom look";
588
+ if (knob.kind === "pace") return motionName(comp.cursor) ?? "custom pace";
589
+ if (knob.kind === "finish") return finishName(comp.motionBlur) ?? "custom finish";
590
+ const parts = knob.path.split(".");
591
+ let node = comp;
592
+ for (const p of parts) node = node?.[p];
593
+ return `${knob.path}=${JSON.stringify(node)}`;
594
+ }
595
+ function applyKnob(comp, knob, value) {
596
+ if (knob.kind === "zoom") {
597
+ const i = knob.beat - 1;
598
+ const e = comp.events[i];
599
+ if (!e) throw new Error(`ab: --beat ${knob.beat} out of range (1-${comp.events.length})`);
600
+ const events = comp.events.slice();
601
+ if (value === "off" || value === "wide") events[i] = {
602
+ ...e,
603
+ zoom: {
604
+ ...e.zoom,
605
+ enabled: false
606
+ }
607
+ };
608
+ else {
609
+ const scale = value in ZOOM_LEVELS ? ZOOM_LEVELS[value] : Number(value);
610
+ if (!Number.isFinite(scale)) throw new Error(`ab: zoom value "${value}" — use off/light/medium/tight/close or a number`);
611
+ events[i] = {
612
+ ...e,
613
+ zoom: {
614
+ ...e.zoom,
615
+ enabled: true,
616
+ scale
617
+ }
618
+ };
619
+ }
620
+ return {
621
+ ...comp,
622
+ events
623
+ };
624
+ }
625
+ if (knob.kind === "look") {
626
+ const look = LOOKS[value];
627
+ if (!look) throw new Error(`ab: unknown look "${value}" — one of ${Object.keys(LOOKS).join("/")}`);
628
+ return {
629
+ ...comp,
630
+ framing: {
631
+ ...comp.framing,
632
+ ...structuredClone(look)
633
+ }
634
+ };
635
+ }
636
+ if (knob.kind === "pace") {
637
+ const pace = MOTION[value];
638
+ if (!pace) throw new Error(`ab: unknown pace "${value}" — one of ${Object.keys(MOTION).join("/")}`);
639
+ const oldZoomInMs = comp.cursor.zoomInMs;
640
+ const events = comp.events.map((e) => e.zoom.inAtMs === Math.max(0, e.tMs - oldZoomInMs) ? {
641
+ ...e,
642
+ zoom: {
643
+ ...e.zoom,
644
+ inAtMs: Math.max(0, e.tMs - pace.zoomInMs)
645
+ }
646
+ } : e);
647
+ return {
648
+ ...comp,
649
+ events,
650
+ cursor: {
651
+ ...comp.cursor,
652
+ ...pace
653
+ }
654
+ };
655
+ }
656
+ if (knob.kind === "finish") {
657
+ if (!(value in FINISH)) throw new Error(`ab: unknown finish "${value}" — one of ${Object.keys(FINISH).join("/")}`);
658
+ const mb = FINISH[value];
659
+ const { motionBlur: _mb,...rest } = comp;
660
+ return mb ? {
661
+ ...rest,
662
+ motionBlur: { ...mb }
663
+ } : rest;
664
+ }
665
+ return setPath(comp, knob.path, value);
666
+ }
667
+ function variantDesc(knob, value, comp) {
668
+ if (knob.kind === "zoom") {
669
+ const e = comp.events[knob.beat - 1];
670
+ return e ? zoomText(e) : value;
671
+ }
672
+ if (knob.kind === "path") return `${knob.path}=${value}`;
673
+ return value;
674
+ }
675
+ /** The reel's time window (ms): a beat's zoom arc with lead-in/out padding, so
676
+ * a taste question costs a ~4s render per variant, not the whole take. The
677
+ * window is the UNION across all variant compositions — a variant with a
678
+ * longer hold/zoom-out (or a rebased inAtMs) must not be cut mid-settle, since
679
+ * the settle is exactly what the reel exists to judge. */
680
+ function abWindow(comps, beat, full) {
681
+ if (full) return void 0;
682
+ const base = comps[0];
683
+ if (!base || base.events.length === 0) return void 0;
684
+ if (beat != null && (beat < 1 || beat > base.events.length)) throw new Error(`ab: --beat ${beat} out of range (1-${base.events.length})`);
685
+ let i = beat != null ? beat - 1 : base.events.findIndex((e) => e.zoom.enabled);
686
+ if (i < 0) i = 0;
687
+ let from = Number.POSITIVE_INFINITY;
688
+ let to = 0;
689
+ for (const c of comps) {
690
+ const e = c.events[i];
691
+ if (!e) continue;
692
+ from = Math.min(from, Math.max(0, e.zoom.inAtMs - 1200));
693
+ const next = c.events[i + 1];
694
+ const ownEnd = e.tMs + (e.durationMs ?? 0) + c.cursor.holdMs + c.cursor.zoomOutMs;
695
+ to = Math.max(to, (next ? next.zoom.inAtMs : ownEnd) + 400);
696
+ }
697
+ if (!Number.isFinite(from)) return void 0;
698
+ return [from, Math.max(to, from + 1500)];
699
+ }
700
+ const LETTERS = [
701
+ "A",
702
+ "B",
703
+ "C",
704
+ "D"
705
+ ];
706
+ async function renderAbReel(take, opts) {
707
+ await requireTakeFiles(take, { capture: true });
708
+ const comp = JSON.parse(await readFile(take.compositionPath, "utf8"));
709
+ const captureLog = await loadLogSibling(take.capturePath);
710
+ const chromePath = await ensureChrome(opts.chromePath);
711
+ const { knob, values } = parseSetFlag(opts.set, opts.beat);
712
+ const cur = currentDesc(comp, knob);
713
+ const variants = [{
714
+ letter: "A",
715
+ desc: `current (${cur})`,
716
+ comp
717
+ }];
718
+ for (const v of values) {
719
+ const applied = applyKnob(comp, knob, v);
720
+ const desc = variantDesc(knob, v, applied);
721
+ if (desc === cur || variants.some((x) => x.desc === desc)) continue;
722
+ variants.push({
723
+ letter: LETTERS[variants.length],
724
+ desc,
725
+ comp: applied
726
+ });
727
+ }
728
+ if (variants.length < 2) throw new Error(`ab: every requested value matches the current state — nothing to compare`);
729
+ for (const v of variants) {
730
+ const issues = validateComposition$1(v.comp, captureLog ? { captureLog } : {});
731
+ const errors = issues.filter((i) => i.severity === "error");
732
+ if (errors.length) throw new Error(`ab: variant ${v.letter} (${v.desc}) is invalid:\n${formatIssues$1(errors)}`);
733
+ }
734
+ const windowMs = abWindow(variants.map((v) => v.comp), opts.beat, opts.full ?? false);
735
+ const rangeSec = windowMs ? [windowMs[0] / 1e3, windowMs[1] / 1e3] : void 0;
736
+ const clips = [];
737
+ try {
738
+ for (const v of variants) {
739
+ const base = opts.draft ? toDraft(v.comp) : v.comp;
740
+ const decorated = {
741
+ ...base,
742
+ review: { label: `${v.letter} · ${v.desc}` }
743
+ };
744
+ const clip = `${take.base}.ab.${v.letter}.mp4`;
745
+ if (opts.logProgress !== false) process.stderr.write(`variant ${v.letter} · ${v.desc}${rangeSec ? ` · window ${rangeSec[0].toFixed(1)}–${rangeSec[1].toFixed(1)}s` : ""}\n`);
746
+ await renderTake({
747
+ composition: decorated,
748
+ videoPath: take.capturePath,
749
+ outPath: clip,
750
+ captureLog,
751
+ logProgress: opts.logProgress ?? true,
752
+ chromePath,
753
+ rangeSec,
754
+ writeCompositionSibling: false
755
+ });
756
+ clips.push(clip);
757
+ }
758
+ await concatWithGaps([...clips, ...clips], take.abPath, {
759
+ width: comp.output.width,
760
+ height: comp.output.height,
761
+ fps: opts.draft ? Math.min(30, comp.output.fps) : comp.output.fps
762
+ });
763
+ } finally {
764
+ await Promise.all(clips.map((c) => rm(c, { force: true })));
765
+ }
766
+ const legend = [
767
+ `A/B reel: ${take.abPath} (${knobLabel(knob)})`,
768
+ ...variants.map((v) => ` ${v.letter} ${v.desc}`),
769
+ `answer with a letter — or "between A and B" / "none, try …"`
770
+ ].join("\n");
771
+ return {
772
+ abPath: take.abPath,
773
+ legend
774
+ };
775
+ }
776
+ function knobLabel(knob) {
777
+ if (knob.kind === "zoom") return `beat ${knob.beat} · zoom`;
778
+ if (knob.kind === "path") return knob.path;
779
+ return knob.kind;
780
+ }
781
+ /** before/after reel from the existing prev + current masters — no render at
782
+ * all, pure ffmpeg trims. Order convention: BEFORE then AFTER, twice. */
783
+ async function renderBeforeAfter(take, opts = {}) {
784
+ await requireTakeFiles(take);
785
+ if (!await stat(take.prevPath).catch(() => null)) throw new Error(`ab --before-after: no ${take.prevPath} yet (it appears after a re-render)`);
786
+ const comp = JSON.parse(await readFile(take.compositionPath, "utf8"));
787
+ const win = abWindow([comp], opts.beat, opts.full ?? false);
788
+ const cut = async (src, out) => {
789
+ const args = [
790
+ "-y",
791
+ "-loglevel",
792
+ "error",
793
+ "-i",
794
+ src
795
+ ];
796
+ if (win) args.push("-ss", String(win[0] / 1e3), "-t", String((win[1] - win[0]) / 1e3));
797
+ args.push("-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", "-an", out);
798
+ await ffmpeg(args);
799
+ };
800
+ const before = `${take.base}.ab.before.mp4`;
801
+ const after = `${take.base}.ab.after.mp4`;
802
+ await cut(take.prevPath, before);
803
+ await cut(take.mp4Path, after);
804
+ await concatWithGaps([
805
+ before,
806
+ after,
807
+ before,
808
+ after
809
+ ], take.abPath, {
810
+ width: comp.output.width,
811
+ height: comp.output.height,
812
+ fps: comp.output.fps
813
+ });
814
+ await Promise.all([rm(before, { force: true }), rm(after, { force: true })]);
815
+ const legend = [`before/after reel: ${take.abPath}`, ` plays BEFORE then AFTER, twice — say "keep the old one" to revert`].join("\n");
816
+ return {
817
+ abPath: take.abPath,
818
+ legend
819
+ };
820
+ }
821
+ async function ffmpeg(args) {
822
+ const bin = await resolveFfmpeg();
823
+ return new Promise((res, rej) => {
824
+ const c = spawn(bin, args, { stdio: [
825
+ "ignore",
826
+ "ignore",
827
+ "pipe"
828
+ ] });
829
+ let err = "";
830
+ c.stderr.on("data", (d) => err += d);
831
+ c.on("error", rej);
832
+ c.on("close", (code) => code === 0 ? res() : rej(new Error(`ffmpeg exited ${code}: ${err}`)));
833
+ });
834
+ }
835
+ /** Concat clips with a 0.35s black gap between each, re-encoding via the concat
836
+ * FILTER (robust to per-clip encoder variance; everything shares WxH/fps). The
837
+ * gap comes from a lavfi color source — no font/text filters needed. */
838
+ async function concatWithGaps(clips, outPath, v) {
839
+ const args = [
840
+ "-y",
841
+ "-loglevel",
842
+ "error"
843
+ ];
844
+ for (const c of clips) args.push("-i", resolve(c));
845
+ args.push("-f", "lavfi", "-t", "0.35", "-i", `color=c=black:s=${v.width}x${v.height}:r=${v.fps}`);
846
+ const gapIdx = clips.length;
847
+ const seq = [];
848
+ const gapUses = clips.length - 1;
849
+ const split = gapUses > 1 ? `[${gapIdx}:v]split=${gapUses}${Array.from({ length: gapUses }, (_, i) => `[g${i}]`).join("")};` : "";
850
+ clips.forEach((_, i) => {
851
+ seq.push(`[${i}:v]`);
852
+ if (i < clips.length - 1) seq.push(gapUses > 1 ? `[g${i}]` : `[${gapIdx}:v]`);
853
+ });
854
+ const filter = `${split}${seq.join("")}concat=n=${seq.length}:v=1:a=0[v]`;
855
+ args.push("-filter_complex", filter, "-map", "[v]", "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", "-r", String(v.fps), "-an", resolve(outPath));
856
+ await ffmpeg(args);
857
+ }
858
+ /** Spawn a fire-and-forget opener. spawn ENOENT arrives ASYNCHRONOUSLY on the
859
+ * child's "error" event (a try/catch around spawn never sees it and the
860
+ * process would die with an unhandled error) — so degrade via the listener. */
861
+ function spawnOpener(cmd, args, fallbackLine, useShell = false) {
862
+ try {
863
+ const c = spawn(cmd, args, {
864
+ stdio: "ignore",
865
+ detached: true,
866
+ shell: useShell
867
+ });
868
+ c.on("error", () => process.stdout.write(fallbackLine));
869
+ c.unref();
870
+ } catch {
871
+ process.stdout.write(fallbackLine);
872
+ }
873
+ }
874
+ /** Open a file with the OS default player; degrade to printing the path. */
875
+ function openPath(p) {
876
+ const abs = resolve(p);
877
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
878
+ spawnOpener(cmd, [abs], `open: ${abs}\n`, process.platform === "win32");
879
+ }
880
+ /** Reveal a file in Finder/Explorer; degrade to printing the path. */
881
+ function revealPath(p) {
882
+ const abs = resolve(p);
883
+ if (process.platform === "darwin") spawnOpener("open", ["-R", abs], `at: ${abs}\n`);
884
+ else if (process.platform === "win32") spawnOpener("explorer", [`/select,${abs}`], `at: ${abs}\n`, true);
885
+ else spawnOpener("xdg-open", [dirname(abs)], `at: ${abs}\n`);
886
+ }
887
+
888
+ //#endregion
889
+ //#region src/index.ts
890
+ /** `<out>.mp4` → `<out>.capture.mp4` — the raw recording kept beside the
891
+ * polished output so the composition can be re-rendered (refined) later. */
892
+ const capturePathFor = (outPath) => `${resolve(outPath).replace(/\.mp4$/i, "")}.capture.mp4`;
893
+ /** `<x>.capture.mp4` → `<x>.capture.json` — the capture log sits beside the
894
+ * video. Deriving it by convention lets `render` find the ground-truth timing
895
+ * from just the `--video` path. */
896
+ const captureLogPathFor = (capturePath) => resolve(capturePath).replace(/\.mp4$/i, ".json");
897
+ /** Load the capture log that sits beside a capture video, if present. Returns
898
+ * undefined when there's no sibling (e.g. an old capture, or a hand-supplied
899
+ * video) — the capture-lock check is then skipped, not an error. */
900
+ async function loadCaptureLogSibling(capturePath) {
901
+ const p = captureLogPathFor(capturePath);
902
+ try {
903
+ return JSON.parse(await readFile(p, "utf8"));
904
+ } catch {
905
+ return void 0;
906
+ }
907
+ }
908
+ async function makeTake(plan, opts) {
909
+ const work = await mkdtemp(join(tmpdir(), "open-take-"));
910
+ const tmpVideo = join(work, "capture.mp4");
911
+ const chromePath = await ensureChrome(opts.capture?.chromePath);
912
+ const log = await captureTake(plan, {
913
+ ...opts.capture,
914
+ chromePath,
915
+ videoPath: tmpVideo
916
+ });
917
+ const capturePath = capturePathFor(opts.outPath);
918
+ const captureLogPath = captureLogPathFor(capturePath);
919
+ await mkdir(dirname(capturePath), { recursive: true });
920
+ await copyFile(tmpVideo, capturePath);
921
+ await writeFile(captureLogPath, JSON.stringify(log, null, 2));
922
+ const captureFps = opts.capture?.fps ?? 60;
923
+ const planOpts = opts.planOpts?.output?.fps == null ? {
924
+ ...opts.planOpts,
925
+ output: {
926
+ ...opts.planOpts?.output,
927
+ fps: captureFps
928
+ }
929
+ } : opts.planOpts;
930
+ const composition = planComposition(log, planOpts);
931
+ const { mp4Path, compositionPath } = await renderTake({
932
+ composition,
933
+ videoPath: capturePath,
934
+ outPath: resolve(opts.outPath),
935
+ logProgress: opts.logProgress ?? false,
936
+ chromePath,
937
+ captureLog: log
938
+ });
939
+ return {
940
+ mp4Path,
941
+ compositionPath,
942
+ capturePath,
943
+ captureLogPath,
944
+ composition
945
+ };
946
+ }
947
+ /** Refine: re-render an EDITED composition over a saved capture — no app
948
+ * drive. This is the talk-to-edit loop's render step. Deterministic: the
949
+ * capture is frozen, so only your edits change the output. Validation runs at
950
+ * the render boundary (renderTake) and throws on a malformed edit — including a
951
+ * capture-locked tMs drift when `captureLog` is supplied. */
952
+ async function renderComposition(opts) {
953
+ const chromePath = await ensureChrome(opts.chromePath);
954
+ return renderTake({
955
+ composition: opts.composition,
956
+ videoPath: resolve(opts.capturePath),
957
+ outPath: resolve(opts.outPath),
958
+ logProgress: opts.logProgress ?? false,
959
+ chromePath,
960
+ captureLog: opts.captureLog,
961
+ onProgress: opts.onProgress
962
+ });
963
+ }
964
+ /** Convenience: load a `*.composition.json` and re-render over a saved capture.
965
+ * Auto-loads the sibling capture log (`<video>`.json) so the capture-lock check
966
+ * is enforced in the CLI refine loop — pass `captureLogPath` to override, or
967
+ * set it to `null` to skip. Validation (incl. the lock) runs at the renderTake
968
+ * boundary, which throws on any error BEFORE the expensive render. */
969
+ async function renderCompositionFile(opts) {
970
+ const composition = JSON.parse(await readFile(resolve(opts.compositionPath), "utf8"));
971
+ const captureLog = opts.captureLogPath === null ? void 0 : opts.captureLogPath ? JSON.parse(await readFile(resolve(opts.captureLogPath), "utf8")) : await loadCaptureLogSibling(opts.capturePath);
972
+ if (opts.logProgress) process.stderr.write(captureLog ? "capture-lock: on (loaded capture log)\n" : "capture-lock: off (no capture log)\n");
973
+ return renderComposition({
974
+ composition,
975
+ capturePath: opts.capturePath,
976
+ outPath: opts.outPath,
977
+ captureLog,
978
+ logProgress: opts.logProgress,
979
+ chromePath: opts.chromePath,
980
+ onProgress: opts.onProgress
981
+ });
982
+ }
983
+
984
+ //#endregion
985
+ export { SAY_IT_CARD, buildBadges, buildBeatSheet, captureLogPathFor, captureTake, captureTakeCDP, ensureChrome, formatIssues, inspectPage, loadCaptureLogSibling, makeTake, openPath, renderAbReel, renderBeforeAfter, renderComposition, renderCompositionFile, renderReview, requireTakeFiles, resolveChrome, resolveTakePaths, revealPath, stagePrev, startEditServer, validateComposition };
986
+ //# sourceMappingURL=index.js.map