@open-take/compositor 0.4.4 → 0.5.1

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.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { __export } from "./chunk-Cl8Af3a2.js";
2
2
  import { spawn, spawnSync } from "node:child_process";
3
- import { chmod, mkdir, mkdtemp, readFile, readdir, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
4
- import { existsSync, realpathSync } from "node:fs";
3
+ import { chmod, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
4
+ import { existsSync, realpathSync, statSync } from "node:fs";
5
5
  import { createRequire } from "node:module";
6
6
  import { tmpdir } from "node:os";
7
- import { dirname, join, resolve, sep } from "node:path";
7
+ import { basename, dirname, extname, join, resolve, sep } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { renderVideo } from "@open-take/revideo-renderer";
10
10
 
@@ -199,13 +199,13 @@ function gradientEndpoints(angleDeg, oW, oH) {
199
199
  y1: cy + dy * L / 2
200
200
  };
201
201
  }
202
- function keyvalN(t, kfs, ease = smoother) {
202
+ function keyvalN(t, kfs, ease$1 = smoother) {
203
203
  if (t <= kfs[0][0]) return kfs[0][1];
204
204
  if (t >= kfs[kfs.length - 1][0]) return kfs[kfs.length - 1][1];
205
205
  for (let i = 0; i < kfs.length - 1; i++) {
206
206
  const [t0, v0] = kfs[i];
207
207
  const [t1, v1] = kfs[i + 1];
208
- if (t0 <= t && t <= t1) return v0 + (v1 - v0) * ease((t - t0) / (t1 - t0));
208
+ if (t0 <= t && t <= t1) return v0 + (v1 - v0) * ease$1((t - t0) / (t1 - t0));
209
209
  }
210
210
  return kfs[kfs.length - 1][1];
211
211
  }
@@ -251,14 +251,14 @@ function clampCenter(center, scale, videoW, videoH, outW, outH) {
251
251
  * a straight line, so the screen-space path of the zoom target is strictly
252
252
  * monotone toward frame centre — no wrong-way "bounce" for ANY scale pair,
253
253
  * which scale+centre lerp can't guarantee (it hooks when scale > 2×rest). */
254
- function keyvalR(t, kfs, ease) {
254
+ function keyvalR(t, kfs, ease$1) {
255
255
  if (t <= kfs[0][0]) return kfs[0][1];
256
256
  if (t >= kfs[kfs.length - 1][0]) return kfs[kfs.length - 1][1];
257
257
  for (let i = 0; i < kfs.length - 1; i++) {
258
258
  const [t0, v0] = kfs[i];
259
259
  const [t1, v1] = kfs[i + 1];
260
260
  if (t0 <= t && t <= t1) {
261
- const p = ease((t - t0) / (t1 - t0));
261
+ const p = ease$1((t - t0) / (t1 - t0));
262
262
  return {
263
263
  cx: v0.cx + (v1.cx - v0.cx) * p,
264
264
  cy: v0.cy + (v1.cy - v0.cy) * p,
@@ -517,14 +517,14 @@ function settleRectAt(kfs, decay, t) {
517
517
  * consume THIS, so preview and export can never drift. */
518
518
  function stageCamera(comp) {
519
519
  const stage = buildStageKeyframes(comp);
520
- const ease = stageEasing(comp.cursor);
520
+ const ease$1 = stageEasing(comp.cursor);
521
521
  const oW = comp.output.width;
522
522
  const rest = restStageScale(comp.source.videoWidth, comp.source.videoHeight, oW, comp.output.height, comp.framing.insetFrac);
523
523
  const frac = comp.cursor.zoomSettleFrac ?? 0;
524
524
  const useSettle = frac > 0 && comp.cursor.zoomSpring == null && !comp.cursor.zoomEase;
525
525
  const decay = useSettle ? settleDecay(frac) : void 0;
526
526
  const at = (t) => {
527
- const r = decay ? settleRectAt(stage.r, decay, t) : keyvalR(t, stage.r, ease);
527
+ const r = decay ? settleRectAt(stage.r, decay, t) : keyvalR(t, stage.r, ease$1);
528
528
  return {
529
529
  scale: oW / r.w,
530
530
  center: {
@@ -1320,6 +1320,2851 @@ function directCamera(beats, video, out, cam, rest, endMs) {
1320
1320
  return framings;
1321
1321
  }
1322
1322
 
1323
+ //#endregion
1324
+ //#region src/launch-evaluate.ts
1325
+ const clamp$1 = (n, lo = 0, hi = 1) => Math.max(lo, Math.min(hi, n));
1326
+ const launchEase = (x) => {
1327
+ const p = clamp$1(x);
1328
+ return 1 - (1 - p) ** 3;
1329
+ };
1330
+ const launchSmooth = (x) => {
1331
+ const p = clamp$1(x);
1332
+ return p * p * (3 - 2 * p);
1333
+ };
1334
+ const mix = (a, b, t) => a + (b - a) * t;
1335
+ const uiStateDurationS = (state) => Math.max(state.transitionS, state.typeDelayS + state.typeS) + state.holdS;
1336
+ const uiMorphDurationS = (scene) => scene.states.reduce((sum, state) => sum + uiStateDurationS(state), 0);
1337
+ const launchSceneDurationS = (scene) => scene.type === "ui-morph" ? uiMorphDurationS(scene) : scene.durationS;
1338
+ function launchSceneWindows(comp) {
1339
+ let cursor = 0;
1340
+ return comp.scenes.map((scene, index) => {
1341
+ const out = {
1342
+ scene,
1343
+ index,
1344
+ startS: cursor,
1345
+ endS: cursor + launchSceneDurationS(scene)
1346
+ };
1347
+ cursor = out.endS;
1348
+ return out;
1349
+ });
1350
+ }
1351
+ const launchDurationS = (comp) => comp.scenes.reduce((sum, scene) => sum + launchSceneDurationS(scene), 0);
1352
+ function launchAudioAtS(comp, track) {
1353
+ if (track.atS != null) return track.atS;
1354
+ const win = launchSceneWindows(comp).find((x) => x.scene.id === track.afterSceneId);
1355
+ return (win?.endS ?? 0) + (track.offsetS ?? 0);
1356
+ }
1357
+ function evaluateUiMorph(scene, localS) {
1358
+ const states = scene.states;
1359
+ let index = 0;
1360
+ let stateStart = 0;
1361
+ for (let i = 0, cursor = 0; i < states.length; i++) {
1362
+ const end = cursor + uiStateDurationS(states[i]);
1363
+ if (localS < end || i === states.length - 1) {
1364
+ index = i;
1365
+ stateStart = cursor;
1366
+ break;
1367
+ }
1368
+ cursor = end;
1369
+ }
1370
+ const to = states[index];
1371
+ const from = states[Math.max(0, index - 1)];
1372
+ const transitionS = to.transitionS;
1373
+ const p = index === 0 ? launchEase((localS - stateStart) / transitionS) : launchSmooth((localS - stateStart) / transitionS);
1374
+ const base = scene.panel ?? {
1375
+ width: 1100,
1376
+ compactHeight: 112,
1377
+ expandedHeight: 218,
1378
+ radius: 34
1379
+ };
1380
+ const fromW = from.panelWidth ?? base.width;
1381
+ const toW = to.panelWidth ?? base.width;
1382
+ const fromH = from.panelHeight ?? (index <= 1 ? base.compactHeight : base.expandedHeight);
1383
+ const toH = to.panelHeight ?? (index === 0 ? base.compactHeight : base.expandedHeight);
1384
+ const typeStart = stateStart + to.typeDelayS;
1385
+ const typed = clamp$1((localS - typeStart) / Math.max(.05, to.typeS));
1386
+ const width = mix(index === 0 ? fromW * .82 : fromW, toW, p);
1387
+ const height = mix(index === 0 ? fromH * .82 : fromH, toH, p);
1388
+ const fromChip = 132 + from.label.length * 11;
1389
+ const toChip = 132 + to.label.length * 11;
1390
+ const emphasizeStart = stateStart + Math.max(to.transitionS, to.typeDelayS + to.typeS);
1391
+ const emphasize = index === states.length - 1 ? Math.sin(clamp$1((localS - emphasizeStart) / Math.min(.55, Math.max(.1, to.holdS))) * Math.PI) : 0;
1392
+ const sameChip = index > 0 && from.icon === to.icon && from.label === to.label;
1393
+ return {
1394
+ from,
1395
+ to,
1396
+ progress: p,
1397
+ panelWidth: width,
1398
+ panelHeight: height,
1399
+ chipWidth: mix(fromChip, toChip, p),
1400
+ oldOpacity: index === 0 || sameChip ? 0 : 1 - clamp$1(p / .42),
1401
+ oldY: -32 * clamp$1(p / .5),
1402
+ newOpacity: index === 0 ? p : sameChip ? 1 : clamp$1((p - .35) / .65),
1403
+ newY: index === 0 || sameChip ? 0 : 32 * (1 - clamp$1((p - .25) / .75)),
1404
+ promptChars: Math.round(to.prompt.length * typed),
1405
+ plusX: -width / 2 - 64,
1406
+ sendX: width / 2 - 58,
1407
+ sendScale: 1 + .06 * emphasize,
1408
+ iconRotation: to.icon === "style" ? 12 * (1 - p) : 0
1409
+ };
1410
+ }
1411
+
1412
+ //#endregion
1413
+ //#region src/motion-evaluate.ts
1414
+ /** Same explicit color syntax as launch themes; no browser-dependent named colors. */
1415
+ function parseMotionColor(value) {
1416
+ if (typeof value !== "string") return void 0;
1417
+ if (/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(value)) return [
1418
+ Number.parseInt(value.slice(1, 3), 16),
1419
+ Number.parseInt(value.slice(3, 5), 16),
1420
+ Number.parseInt(value.slice(5, 7), 16),
1421
+ value.length === 9 ? Number.parseInt(value.slice(7, 9), 16) / 255 : 1
1422
+ ];
1423
+ const m = value.match(/^(rgb|rgba)\(\s*(\d+(?:\.\d+)?|\.\d+)\s*,\s*(\d+(?:\.\d+)?|\.\d+)\s*,\s*(\d+(?:\.\d+)?|\.\d+)(?:\s*,\s*(\d+(?:\.\d+)?|\.\d+))?\s*\)$/i);
1424
+ if (!m || m[1].toLowerCase() === "rgba" !== (m[5] !== void 0)) return void 0;
1425
+ const rgba = [
1426
+ Number(m[2]),
1427
+ Number(m[3]),
1428
+ Number(m[4]),
1429
+ m[5] === void 0 ? 1 : Number(m[5])
1430
+ ];
1431
+ return rgba.every((n, i) => Number.isFinite(n) && n >= 0 && n <= (i === 3 ? 1 : 255)) ? rgba : void 0;
1432
+ }
1433
+ const clamp = (value) => Math.max(0, Math.min(1, value));
1434
+ function ease(t, easing = "linear") {
1435
+ const p = clamp(t);
1436
+ switch (easing) {
1437
+ case "ease-in": return p ** 3;
1438
+ case "ease-out": return 1 - (1 - p) ** 3;
1439
+ case "ease-in-out": return p < .5 ? 4 * p ** 3 : 1 - (-2 * p + 2) ** 3 / 2;
1440
+ case "step": return p < 1 ? 0 : 1;
1441
+ default: return p;
1442
+ }
1443
+ }
1444
+ function evaluateMotionTrack(track, localS) {
1445
+ const frames = track.keyframes;
1446
+ if (localS <= frames[0].atS) return frames[0].value;
1447
+ for (let i = 1; i < frames.length; i++) {
1448
+ const to = frames[i], from = frames[i - 1];
1449
+ if (localS > to.atS) continue;
1450
+ const p = ease((localS - from.atS) / (to.atS - from.atS), to.easing);
1451
+ if (p === 0) return from.value;
1452
+ if (p === 1) return to.value;
1453
+ if (typeof from.value === "number" && typeof to.value === "number") return from.value + (to.value - from.value) * p;
1454
+ const a = parseMotionColor(from.value), b = parseMotionColor(to.value);
1455
+ const rgba = a.map((n, j) => n + (b[j] - n) * p);
1456
+ return `rgba(${rgba.slice(0, 3).map((n) => Number(n.toFixed(4))).join(",")},${Number(rgba[3].toFixed(6))})`;
1457
+ }
1458
+ return frames.at(-1).value;
1459
+ }
1460
+ const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
1461
+ function motionGraphemes(text) {
1462
+ return Array.from(segmenter.segment(text), (part) => part.segment);
1463
+ }
1464
+ /** Input must have passed validation. Evaluation is pure and shared by Node and the browser. */
1465
+ function evaluateMotionScene(scene, localS) {
1466
+ const evaluate = (layer) => {
1467
+ const { animations,...authored } = layer;
1468
+ const result = {
1469
+ x: 0,
1470
+ y: 0,
1471
+ opacity: 1,
1472
+ scaleX: 1,
1473
+ scaleY: 1,
1474
+ rotation: 0,
1475
+ ...authored
1476
+ };
1477
+ if (scene.motion !== "off") for (const track of animations ?? []) result[track.property] = evaluateMotionTrack(track, localS);
1478
+ if (layer.type === "group") {
1479
+ result.children = layer.children.map(evaluate);
1480
+ result.clip = layer.clip ?? false;
1481
+ result.radius ??= 0;
1482
+ }
1483
+ if (layer.type === "rect" || layer.type === "image" || layer.type === "video") result.radius ??= 0;
1484
+ if ((layer.type === "rect" || layer.type === "image" || layer.type === "video") && layer.shadow) result.shadow = { ...layer.shadow };
1485
+ if (layer.type === "rect" || layer.type === "ellipse") result.strokeWidth ??= 0;
1486
+ if (layer.type === "line") {
1487
+ result.end ??= 1;
1488
+ result.strokeWidth ??= 2;
1489
+ result.points = layer.points.map((point) => [...point]);
1490
+ }
1491
+ if (layer.type === "image") {
1492
+ result.fit ??= "contain";
1493
+ if (layer.crop) result.crop = { ...layer.crop };
1494
+ }
1495
+ if (layer.type === "video") {
1496
+ result.fit ??= "contain";
1497
+ result.trimStartS ??= 0;
1498
+ result.startS ??= 0;
1499
+ result.mediaTimeS = result.trimStartS + Math.max(0, Math.min(layer.durationS, localS - result.startS));
1500
+ }
1501
+ if (layer.type === "text") {
1502
+ result.fullText = layer.text;
1503
+ result.reveal ??= 1;
1504
+ result.align ??= "center";
1505
+ result.fontWeight ??= 500;
1506
+ result.lineHeight = layer.lineHeight ?? result.fontSize * 1.2;
1507
+ const graphemes = motionGraphemes(layer.text);
1508
+ result.text = graphemes.slice(0, Math.floor(graphemes.length * clamp(result.reveal) + 1e-9)).join("");
1509
+ }
1510
+ return result;
1511
+ };
1512
+ return {
1513
+ designSize: { ...scene.designSize ?? {
1514
+ width: 1920,
1515
+ height: 1080
1516
+ } },
1517
+ layers: scene.layers.map(evaluate)
1518
+ };
1519
+ }
1520
+ /** Visit validated layers in paint order, including nested image assets. */
1521
+ function walkMotionLayers(layers) {
1522
+ return layers.flatMap((layer) => layer.type === "group" ? [layer, ...walkMotionLayers(layer.children)] : [layer]);
1523
+ }
1524
+
1525
+ //#endregion
1526
+ //#region src/motion-quality.ts
1527
+ /** Heuristic reading time: roughly three words or six CJK/fullwidth glyphs per second.
1528
+ * The character-rate floor also accounts for unusually long unbroken words. */
1529
+ function estimateMotionReadingSeconds(copy, minimum = .8) {
1530
+ const glyphs = motionGraphemes(copy);
1531
+ const fullwidth = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Extended_Pictographic}\uFF01-\uFF60]/u;
1532
+ let wide = 0;
1533
+ const remaining = glyphs.map((glyph) => {
1534
+ if (!fullwidth.test(glyph)) return glyph;
1535
+ wide++;
1536
+ return " ";
1537
+ }).join("");
1538
+ const words = remaining.match(/[\p{L}\p{N}]+(?:['’][\p{L}\p{N}]+)*/gu)?.length ?? 0;
1539
+ const narrow = motionGraphemes(remaining.replace(/\s/g, "")).length;
1540
+ return Math.max(minimum, wide / 6 + Math.max(words / 3, narrow / 18));
1541
+ }
1542
+ const identity = [
1543
+ 1,
1544
+ 0,
1545
+ 0,
1546
+ 1,
1547
+ 0,
1548
+ 0
1549
+ ];
1550
+ function transform(parent, layer) {
1551
+ const angle = (layer.rotation ?? 0) * Math.PI / 180, c = Math.cos(angle), s = Math.sin(angle), sx = layer.scaleX ?? 1, sy = layer.scaleY ?? 1;
1552
+ const a = c * sx, b = s * sx, d = -s * sy, e = c * sy, x = layer.x ?? 0, y = layer.y ?? 0;
1553
+ return [
1554
+ parent[0] * a + parent[2] * b,
1555
+ parent[1] * a + parent[3] * b,
1556
+ parent[0] * d + parent[2] * e,
1557
+ parent[1] * d + parent[3] * e,
1558
+ parent[0] * x + parent[2] * y + parent[4],
1559
+ parent[1] * x + parent[3] * y + parent[5]
1560
+ ];
1561
+ }
1562
+ function boxOf(layer, m) {
1563
+ const points = layer.type === "line" ? layer.points : "width" in layer && "height" in layer && layer.width !== void 0 && layer.height !== void 0 ? [
1564
+ [-layer.width / 2, -layer.height / 2],
1565
+ [layer.width / 2, -layer.height / 2],
1566
+ [layer.width / 2, layer.height / 2],
1567
+ [-layer.width / 2, layer.height / 2]
1568
+ ] : void 0;
1569
+ if (!points) return void 0;
1570
+ const x = points.map((p) => m[0] * p[0] + m[2] * p[1] + m[4]), y = points.map((p) => m[1] * p[0] + m[3] * p[1] + m[5]);
1571
+ return {
1572
+ left: Math.min(...x),
1573
+ right: Math.max(...x),
1574
+ top: Math.min(...y),
1575
+ bottom: Math.max(...y)
1576
+ };
1577
+ }
1578
+ const intersects = (a, b) => a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top;
1579
+ const contains = (a, b) => a.left <= b.left && a.right >= b.right && a.top <= b.top && a.bottom >= b.bottom;
1580
+ function intersect(a, b) {
1581
+ return {
1582
+ left: Math.max(a.left, b.left),
1583
+ right: Math.min(a.right, b.right),
1584
+ top: Math.max(a.top, b.top),
1585
+ bottom: Math.min(a.bottom, b.bottom)
1586
+ };
1587
+ }
1588
+ function flatten(scene, prefix) {
1589
+ const out = [];
1590
+ const visit = (layers, path, parent, opacity, parents, clip) => {
1591
+ layers.forEach((layer, i) => {
1592
+ const matrix = transform(parent, layer), nextOpacity = opacity * (layer.opacity ?? 1), rawBox = boxOf(layer, matrix), box = rawBox && clip ? intersect(rawBox, clip) : rawBox;
1593
+ const item = {
1594
+ layer,
1595
+ path: `${path}[${i}]`,
1596
+ matrix,
1597
+ opacity: nextOpacity,
1598
+ parents,
1599
+ box
1600
+ };
1601
+ out.push(item);
1602
+ if (layer.type === "group") visit(layer.children, `${item.path}.children`, matrix, nextOpacity, [...parents, layer], layer.clip && box ? box : clip);
1603
+ });
1604
+ };
1605
+ visit(scene.layers, `${prefix}.layers`, identity, 1, []);
1606
+ return out;
1607
+ }
1608
+ function trackValue(layer, property, time, fallback) {
1609
+ const track = layer.animations?.find((x) => x.property === property);
1610
+ return track ? evaluateMotionTrack(track, time) : layer[property] ?? fallback;
1611
+ }
1612
+ function commonWindows(left, right) {
1613
+ const result = [];
1614
+ let i = 0, j = 0;
1615
+ while (i < left.length && j < right.length) {
1616
+ const a = left[i], b = right[j], start = Math.max(a.start, b.start), end = Math.min(a.end, b.end);
1617
+ if (end > start) result.push({
1618
+ start,
1619
+ end
1620
+ });
1621
+ if (a.end <= b.end) i++;
1622
+ else j++;
1623
+ }
1624
+ return result;
1625
+ }
1626
+ function usefulHold(scene, item) {
1627
+ if (item.layer.type !== "text") return 0;
1628
+ const chain = [...item.parents, item.layer];
1629
+ if (scene.motion === "off") return (item.layer.reveal ?? 1) >= .999 && item.opacity >= .5 && Math.hypot(item.matrix[0], item.matrix[1]) > .01 && Math.hypot(item.matrix[2], item.matrix[3]) > .01 ? scene.durationS : 0;
1630
+ const transition = scene.transition?.type && scene.transition.type !== "cut" ? Math.min(scene.transition.durationS ?? .45, scene.durationS / 2) : 0;
1631
+ const end = scene.durationS - transition;
1632
+ let available = [{
1633
+ start: transition,
1634
+ end
1635
+ }];
1636
+ for (const layer of chain) for (const track of layer.animations ?? []) {
1637
+ const stationary = [];
1638
+ const add = (start, finish, value) => {
1639
+ const last$1 = stationary.at(-1);
1640
+ if (finish <= start) return;
1641
+ if (last$1 && last$1.end === start && last$1.value === value) last$1.end = finish;
1642
+ else stationary.push({
1643
+ start,
1644
+ end: finish,
1645
+ value
1646
+ });
1647
+ };
1648
+ for (let i = 1; i < track.keyframes.length; i++) {
1649
+ const from = track.keyframes[i - 1], to = track.keyframes[i];
1650
+ if (from.value === to.value || to.easing === "step") add(from.atS, to.atS, from.value);
1651
+ }
1652
+ const last = track.keyframes.at(-1);
1653
+ add(last.atS, end, last.value);
1654
+ available = commonWindows(available, stationary);
1655
+ if (!available.length) return 0;
1656
+ }
1657
+ let longest = 0;
1658
+ for (const window of available) {
1659
+ const middle = (window.start + window.end) / 2;
1660
+ const visible = chain.reduce((opacity, layer) => opacity * trackValue(layer, "opacity", middle, 1), 1) >= .5;
1661
+ const revealed = trackValue(item.layer, "reveal", middle, 1) >= .999;
1662
+ const scaled = chain.every((layer) => trackValue(layer, "scaleX", middle, 1) > .01 && trackValue(layer, "scaleY", middle, 1) > .01);
1663
+ if (visible && revealed && scaled) longest = Math.max(longest, window.end - window.start);
1664
+ }
1665
+ return longest;
1666
+ }
1667
+ function luminance(rgb) {
1668
+ const values = rgb.slice(0, 3).map((x) => {
1669
+ const n = x / 255;
1670
+ return n <= .04045 ? n / 12.92 : ((n + .055) / 1.055) ** 2.4;
1671
+ });
1672
+ return values[0] * .2126 + values[1] * .7152 + values[2] * .0722;
1673
+ }
1674
+ function textContrast(item, index, items, theme, scene) {
1675
+ if (item.layer.type !== "text" || !item.box || item.opacity < .999) return void 0;
1676
+ const ink = parseMotionColor(item.layer.fill ?? theme.ink), canvas = parseMotionColor(scene.background === "dark" ? theme.dark : theme.canvas);
1677
+ if (!ink || ink[3] < .999 || !canvas || canvas[3] < .999) return void 0;
1678
+ let background = canvas;
1679
+ for (let i = 0; i < index; i++) {
1680
+ const prior = items[i];
1681
+ if (prior.layer.type === "group" || !prior.box || prior.opacity < .001 || !intersects(prior.box, item.box)) continue;
1682
+ if (prior.layer.type !== "rect" || Math.abs(prior.matrix[1]) + Math.abs(prior.matrix[2]) > 1e-6) {
1683
+ background = void 0;
1684
+ continue;
1685
+ }
1686
+ const radius = (prior.layer.radius ?? 0) * Math.max(Math.abs(prior.matrix[0]), Math.abs(prior.matrix[3]));
1687
+ const inner = {
1688
+ left: prior.box.left + radius,
1689
+ right: prior.box.right - radius,
1690
+ top: prior.box.top + radius,
1691
+ bottom: prior.box.bottom - radius
1692
+ };
1693
+ const paint = parseMotionColor(prior.layer.fill ?? theme.surface);
1694
+ if (!contains(inner, item.box) || !paint) {
1695
+ background = void 0;
1696
+ continue;
1697
+ }
1698
+ const alpha = paint[3] * prior.opacity;
1699
+ if (alpha >= .999) background = paint;
1700
+ else if (background) background = paint.slice(0, 3).map((n, j) => n * alpha + background[j] * (1 - alpha));
1701
+ }
1702
+ if (items.slice(index + 1).some((x) => x.layer.type !== "group" && x.box && x.opacity > .001 && intersects(x.box, item.box))) return void 0;
1703
+ if (!background) return void 0;
1704
+ const a = luminance(ink), b = luminance(background);
1705
+ return (Math.max(a, b) + .05) / (Math.min(a, b) + .05);
1706
+ }
1707
+ function denseAnimation(scene, items) {
1708
+ if (scene.motion === "off") return 0;
1709
+ const events = [];
1710
+ for (const item of items) for (const track of item.layer.animations ?? []) for (let i = 1; i < track.keyframes.length; i++) {
1711
+ const a = track.keyframes[i - 1], b = track.keyframes[i];
1712
+ if (a.value !== b.value && b.easing !== "step") events.push({
1713
+ time: a.atS,
1714
+ delta: 1,
1715
+ id: item.path
1716
+ }, {
1717
+ time: b.atS,
1718
+ delta: -1,
1719
+ id: item.path
1720
+ });
1721
+ }
1722
+ events.sort((a, b) => a.time - b.time || a.delta - b.delta);
1723
+ const active = new Map();
1724
+ let peak = 0;
1725
+ for (let i = 0; i < events.length;) {
1726
+ const time = events[i].time;
1727
+ while (i < events.length && events[i].time === time) {
1728
+ const event = events[i++], count = (active.get(event.id) ?? 0) + event.delta;
1729
+ if (count > 0) active.set(event.id, count);
1730
+ else active.delete(event.id);
1731
+ }
1732
+ if (i < events.length) peak = Math.max(peak, active.size);
1733
+ }
1734
+ return peak;
1735
+ }
1736
+ const connectorProperties = new Set([
1737
+ "x",
1738
+ "y",
1739
+ "scaleX",
1740
+ "scaleY",
1741
+ "rotation",
1742
+ "opacity",
1743
+ "width",
1744
+ "height",
1745
+ "radius",
1746
+ "end",
1747
+ "stroke",
1748
+ "strokeWidth",
1749
+ "fill"
1750
+ ]);
1751
+ function pointAt(m, p) {
1752
+ return [m[0] * p[0] + m[2] * p[1] + m[4], m[1] * p[0] + m[3] * p[1] + m[5]];
1753
+ }
1754
+ function clipBounds(matrix, width, height, radius = 0) {
1755
+ const [a, b, c, d, x, y] = matrix, determinant = a * d - b * c;
1756
+ if (Math.abs(determinant) < 1e-8) return void 0;
1757
+ const inset = Math.min(radius, width / 2, height / 2) * (1 - Math.SQRT1_2) + .5;
1758
+ if (width / 2 <= inset || height / 2 <= inset) return void 0;
1759
+ return {
1760
+ inverse: [
1761
+ d / determinant,
1762
+ -b / determinant,
1763
+ -c / determinant,
1764
+ a / determinant,
1765
+ (c * y - d * x) / determinant,
1766
+ (b * x - a * y) / determinant
1767
+ ],
1768
+ halfWidth: width / 2 - inset,
1769
+ halfHeight: height / 2 - inset
1770
+ };
1771
+ }
1772
+ /** Clip the actual segment, not its bounding box, against transformed rectangles. */
1773
+ function segmentInterval(from, to, bounds) {
1774
+ let low = 0, high = 1;
1775
+ for (const bound of bounds) {
1776
+ const a = pointAt(bound.inverse, from), b = pointAt(bound.inverse, to);
1777
+ for (const [axis, half] of [[0, bound.halfWidth], [1, bound.halfHeight]]) {
1778
+ const delta = b[axis] - a[axis];
1779
+ if (Math.abs(delta) < 1e-10) {
1780
+ if (Math.abs(a[axis]) >= half) return void 0;
1781
+ } else {
1782
+ const first = (-half - a[axis]) / delta, last = (half - a[axis]) / delta;
1783
+ low = Math.max(low, Math.min(first, last));
1784
+ high = Math.min(high, Math.max(first, last));
1785
+ if (high - low < 1e-7) return void 0;
1786
+ }
1787
+ }
1788
+ }
1789
+ return high > low ? [low, high] : void 0;
1790
+ }
1791
+ function revealedSegments(layer, matrix) {
1792
+ const lengths = layer.points.slice(1).map((point, i) => Math.hypot(point[0] - layer.points[i][0], point[1] - layer.points[i][1]));
1793
+ let remaining = lengths.reduce((a, b) => a + b, 0) * (layer.end ?? 1);
1794
+ const segments = [];
1795
+ for (let i = 0; i < lengths.length && remaining > 0; i++) {
1796
+ const length = lengths[i];
1797
+ if (!length) continue;
1798
+ const from = layer.points[i], to = layer.points[i + 1], fraction = Math.min(1, remaining / length);
1799
+ segments.push([pointAt(matrix, from), pointAt(matrix, [from[0] + (to[0] - from[0]) * fraction, from[1] + (to[1] - from[1]) * fraction])]);
1800
+ remaining -= length;
1801
+ }
1802
+ return segments;
1803
+ }
1804
+ function connectorWarnings(scene, items, theme) {
1805
+ const lines = items.filter((item) => item.layer.type === "line");
1806
+ const media = items.filter((item) => item.layer.type === "image" || item.layer.type === "video");
1807
+ if (!lines.length || !media.length) return [];
1808
+ const relevant = new Set();
1809
+ for (const item of [
1810
+ ...lines,
1811
+ ...media,
1812
+ ...items.filter((x) => x.layer.type === "rect")
1813
+ ]) for (const layer of [...item.parents, item.layer]) relevant.add(layer);
1814
+ const transition = scene.motion !== "off" && scene.transition?.type && scene.transition.type !== "cut" ? Math.min(scene.transition.durationS ?? .45, scene.durationS / 2) : 0;
1815
+ const first = transition, last = scene.durationS - transition, halfHold = .175;
1816
+ if (last - first < halfHold * 2) return [];
1817
+ const times = Array.from({ length: 32 }, (_, i) => first + halfHold + (last - first - halfHold * 2) * (i + .5) / 32);
1818
+ const keyed = [];
1819
+ let candidates = 0, random = 20958;
1820
+ const consider = (time) => {
1821
+ if (time < first + halfHold || time > last - halfHold) return;
1822
+ candidates++;
1823
+ if (keyed.length < 32) keyed.push(time);
1824
+ else {
1825
+ random = Math.imul(random, 1664525) + 1013904223 >>> 0;
1826
+ const index = random % candidates;
1827
+ if (index < 32) keyed[index] = time;
1828
+ }
1829
+ };
1830
+ if (scene.motion !== "off") for (const layer of relevant) for (const track of layer.animations ?? []) {
1831
+ if (!connectorProperties.has(track.property)) continue;
1832
+ for (let i = 0; i < track.keyframes.length; i++) {
1833
+ const a = track.keyframes[i].atS, b = track.keyframes[i + 1]?.atS ?? last;
1834
+ if (b - a >= halfHold * 2) consider((a + b) / 2);
1835
+ }
1836
+ }
1837
+ times.push(...keyed);
1838
+ const warnings = [], warned = new Set();
1839
+ const design = scene.designSize ?? {
1840
+ width: 1920,
1841
+ height: 1080
1842
+ };
1843
+ const frame = clipBounds(identity, design.width, design.height);
1844
+ let budget = 4e4;
1845
+ for (const time of [...new Set(times)].sort((a, b) => a - b)) {
1846
+ const states = new Map();
1847
+ for (const [order, item] of items.entries()) {
1848
+ if (!relevant.has(item.layer)) continue;
1849
+ const layer = { ...item.layer };
1850
+ let stable = true;
1851
+ if (scene.motion !== "off") for (const track of layer.animations ?? []) {
1852
+ if (!connectorProperties.has(track.property)) continue;
1853
+ layer[track.property] = evaluateMotionTrack(track, time);
1854
+ for (let i = 1; i < track.keyframes.length; i++) {
1855
+ const a = track.keyframes[i - 1], b = track.keyframes[i];
1856
+ if (a.value === b.value) continue;
1857
+ if (b.easing === "step") {
1858
+ if (b.atS > time - halfHold && b.atS < time + halfHold) stable = false;
1859
+ } else if (a.atS < time + halfHold && b.atS > time - halfHold) stable = false;
1860
+ }
1861
+ }
1862
+ const parent = states.get(item.parents.at(-1));
1863
+ const matrix = transform(parent?.matrix ?? identity, layer);
1864
+ const clips = [...parent?.clips ?? [frame]];
1865
+ if (layer.type === "group" && layer.clip) {
1866
+ const bounds = clipBounds(matrix, layer.width, layer.height, layer.radius);
1867
+ if (bounds) clips.push(bounds);
1868
+ else stable = false;
1869
+ }
1870
+ states.set(item.layer, {
1871
+ ...item,
1872
+ layer,
1873
+ matrix,
1874
+ order,
1875
+ clips,
1876
+ box: boxOf(layer, matrix),
1877
+ stable: stable && (parent?.stable ?? true),
1878
+ opacity: (parent?.opacity ?? 1) * (layer.opacity ?? 1)
1879
+ });
1880
+ }
1881
+ const sampleMedia = media.map((item) => states.get(item.layer)).filter((x) => x.stable && x.opacity >= .5);
1882
+ const occluders = [...states.values()].flatMap((item) => {
1883
+ if (item.layer.type !== "rect" || !item.stable || item.opacity < .999 || (parseMotionColor(item.layer.fill ?? theme.surface)?.[3] ?? 0) < .999) return [];
1884
+ const bounds = clipBounds(item.matrix, item.layer.width, item.layer.height, item.layer.radius);
1885
+ return bounds ? [{
1886
+ order: item.order,
1887
+ bounds: [...item.clips, bounds]
1888
+ }] : [];
1889
+ });
1890
+ for (const authored of lines) {
1891
+ if (warned.has(authored.path)) continue;
1892
+ const item = states.get(authored.layer);
1893
+ if (item.layer.type !== "line" || !item.stable || item.opacity < .1 || Math.abs(item.matrix[0] * item.matrix[3] - item.matrix[1] * item.matrix[2]) < 1e-8 || (item.layer.strokeWidth ?? 2) <= 0 || item.opacity * (parseMotionColor(item.layer.stroke ?? theme.accent)?.[3] ?? 0) < .1) continue;
1894
+ const segments = revealedSegments(item.layer, item.matrix);
1895
+ if (!segments.length) continue;
1896
+ for (const target of sampleMedia) {
1897
+ if (target.order >= item.order || !target.box || !item.box || !intersects(item.box, target.box)) continue;
1898
+ if (target.layer.type !== "image" && target.layer.type !== "video") continue;
1899
+ const bounds = clipBounds(target.matrix, target.layer.width, target.layer.height, target.layer.radius);
1900
+ if (!bounds) continue;
1901
+ let crossing = false;
1902
+ for (const [from, to] of segments) {
1903
+ if (--budget < 0) return warnings;
1904
+ const hit = segmentInterval(from, to, [
1905
+ ...item.clips,
1906
+ ...target.clips,
1907
+ bounds
1908
+ ]);
1909
+ if (!hit) continue;
1910
+ const hidden = occluders.some((occluder) => {
1911
+ if (occluder.order <= target.order) return false;
1912
+ const covered = segmentInterval(from, to, occluder.bounds);
1913
+ return covered && covered[0] <= hit[0] && covered[1] >= hit[1];
1914
+ });
1915
+ if (!hidden) {
1916
+ crossing = true;
1917
+ break;
1918
+ }
1919
+ }
1920
+ if (!crossing) continue;
1921
+ warnings.push({
1922
+ severity: "warn",
1923
+ path: authored.path,
1924
+ message: `Possible obscuring or ambiguous connector: foreground line "${item.layer.id}" enters media "${target.layer.id}" bounds at scene-local ${time.toFixed(2)}s during a sampled visible hold. Inspect the actual media and omit or reposition the line if this is not intentional; geometry does not establish text or semantic overlap.`
1925
+ });
1926
+ warned.add(authored.path);
1927
+ break;
1928
+ }
1929
+ }
1930
+ }
1931
+ return warnings;
1932
+ }
1933
+ /** Heuristics for validated compositions, not a guarantee of aesthetics or measured font layout. */
1934
+ function analyzeMotionQuality(composition) {
1935
+ const issues = [];
1936
+ const warn = (path, message) => issues.push({
1937
+ severity: "warn",
1938
+ path,
1939
+ message
1940
+ });
1941
+ composition.scenes.forEach((scene, index) => {
1942
+ if (scene.type !== "motion") return;
1943
+ const prefix = `scenes[${index}]`, design = scene.designSize ?? {
1944
+ width: 1920,
1945
+ height: 1080
1946
+ }, short = Math.min(design.width, design.height), theme = {
1947
+ ...composition.theme,
1948
+ ...scene.colors
1949
+ };
1950
+ const frame = {
1951
+ left: -design.width / 2,
1952
+ right: design.width / 2,
1953
+ top: -design.height / 2,
1954
+ bottom: design.height / 2
1955
+ }, items = flatten(scene, prefix);
1956
+ items.forEach((item, i) => {
1957
+ if (item.layer.type !== "group" && item.box && item.opacity > .001 && item.box.left < item.box.right && item.box.top < item.box.bottom && !contains(frame, item.box)) warn(item.path, "Resting bounds extend outside the design frame; check the authored base position and size. Entrance keyframes are deliberately excluded.");
1958
+ if (item.layer.type !== "text") return;
1959
+ const text = item.layer, scale = Math.min(Math.hypot(item.matrix[0], item.matrix[1]), Math.hypot(item.matrix[2], item.matrix[3]));
1960
+ if (item.opacity > .001 && text.fontSize * scale < short * .022) warn(`${item.path}.fontSize`, "Text is small relative to the design's short edge; consider a larger font or a simpler message.");
1961
+ const ratio = textContrast(item, i, items, theme, scene);
1962
+ if (ratio !== void 0 && ratio < 4.5) warn(`${item.path}.fill`, `Text contrast is only ${ratio.toFixed(2)}:1 against a known flat background; aim for at least 4.5:1.`);
1963
+ const required = estimateMotionReadingSeconds(text.text), hold = usefulHold(scene, item);
1964
+ if (hold + .001 < required) warn(`${item.path}.animations`, `Text has only ${hold.toFixed(2)}s of stable, fully revealed hold; allow about ${required.toFixed(2)}s for this copy. This reading-time estimate is heuristic.`);
1965
+ });
1966
+ const density = denseAnimation(scene, items);
1967
+ if (density > 8) warn(`${prefix}.layers`, `${density} layers animate simultaneously; stagger or simplify the movement to keep attention on the message.`);
1968
+ issues.push(...connectorWarnings(scene, items, theme));
1969
+ });
1970
+ return issues;
1971
+ }
1972
+
1973
+ //#endregion
1974
+ //#region src/launch-story.ts
1975
+ const record$3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
1976
+ const finite$2 = (value) => typeof value === "number" && Number.isFinite(value);
1977
+ const roles = [
1978
+ "context",
1979
+ "promise",
1980
+ "proof",
1981
+ "payoff",
1982
+ "action"
1983
+ ];
1984
+ function layerIndex(scene) {
1985
+ const result = new Map();
1986
+ const visit = (layers, parents) => {
1987
+ for (const layer of layers) {
1988
+ result.set(layer.id, {
1989
+ layer,
1990
+ parents
1991
+ });
1992
+ if (layer.type === "group") visit(layer.children, [...parents, layer]);
1993
+ }
1994
+ };
1995
+ if (scene.type === "motion") visit(scene.layers, []);
1996
+ return result;
1997
+ }
1998
+ /** Validate unknown story JSON. Supply structurally validated scenes to check
1999
+ * references and scene-local windows; omission checks the metadata shape only. */
2000
+ function validateLaunchStory(value, scenes) {
2001
+ if (value === void 0) return [];
2002
+ const issues = [];
2003
+ const error$1 = (path, message) => issues.push({
2004
+ severity: "error",
2005
+ path,
2006
+ message
2007
+ });
2008
+ if (!record$3(value)) return [{
2009
+ severity: "error",
2010
+ path: "story",
2011
+ message: "must be an object"
2012
+ }];
2013
+ const fields$1 = (obj, allowed, path) => {
2014
+ for (const key of Object.keys(obj)) if (!allowed.includes(key)) error$1(`${path}.${key}`, "unsupported story field");
2015
+ };
2016
+ const text = (v, path, limit) => {
2017
+ if (typeof v !== "string" || !v.trim() || v.length > limit) {
2018
+ error$1(path, `must be a non-empty string of at most ${limit} characters`);
2019
+ return false;
2020
+ }
2021
+ return true;
2022
+ };
2023
+ fields$1(value, [
2024
+ "intent",
2025
+ "audience",
2026
+ "takeaway",
2027
+ "beats"
2028
+ ], "story");
2029
+ if (typeof value.intent !== "string" || ![
2030
+ "teaser",
2031
+ "launch",
2032
+ "walkthrough"
2033
+ ].includes(value.intent)) error$1("story.intent", "must be teaser, launch, or walkthrough");
2034
+ text(value.audience, "story.audience", 1e3);
2035
+ text(value.takeaway, "story.takeaway", 2e3);
2036
+ if (!Array.isArray(value.beats)) {
2037
+ error$1("story.beats", "must be an array");
2038
+ return issues;
2039
+ }
2040
+ const ids = new Set();
2041
+ const byId = scenes && new Map(scenes.map((scene) => [scene.id, scene]));
2042
+ const indexes = new Map();
2043
+ for (const [i, raw] of value.beats.entries()) {
2044
+ const path = `story.beats[${i}]`;
2045
+ if (!record$3(raw)) {
2046
+ error$1(path, "must be an object");
2047
+ continue;
2048
+ }
2049
+ fields$1(raw, [
2050
+ "id",
2051
+ "sceneId",
2052
+ "startS",
2053
+ "endS",
2054
+ "role",
2055
+ "message",
2056
+ "evidence"
2057
+ ], path);
2058
+ if (text(raw.id, `${path}.id`, 200)) {
2059
+ const id = raw.id;
2060
+ if (ids.has(id)) error$1(`${path}.id`, "duplicate story beat id");
2061
+ ids.add(id);
2062
+ }
2063
+ text(raw.sceneId, `${path}.sceneId`, 200);
2064
+ const scene = typeof raw.sceneId === "string" ? byId?.get(raw.sceneId) : void 0;
2065
+ if (byId && typeof raw.sceneId === "string" && !scene) error$1(`${path}.sceneId`, "does not name a scene in this composition");
2066
+ if (typeof raw.role !== "string" || !roles.includes(raw.role)) error$1(`${path}.role`, "must be context, promise, proof, payoff, or action");
2067
+ text(raw.message, `${path}.message`, 4e3);
2068
+ for (const key of ["startS", "endS"]) if (raw[key] !== void 0 && (!finite$2(raw[key]) || raw[key] < 0)) error$1(`${path}.${key}`, "must be finite, nonnegative scene-local seconds");
2069
+ const duration = scene ? launchSceneDurationS(scene) : void 0;
2070
+ const start = raw.startS === void 0 ? 0 : raw.startS;
2071
+ const end = raw.endS === void 0 ? duration : raw.endS;
2072
+ if (finite$2(start) && finite$2(end) && end <= start) error$1(`${path}.endS`, "must be after the resolved startS");
2073
+ if (duration !== void 0) {
2074
+ if (finite$2(start) && start >= duration) error$1(`${path}.startS`, "must start within the referenced scene");
2075
+ if (finite$2(end) && end > duration + 1e-6) error$1(`${path}.endS`, "extends past the referenced scene; beat times are scene-local");
2076
+ }
2077
+ if (raw.evidence === void 0) continue;
2078
+ if (!Array.isArray(raw.evidence)) {
2079
+ error$1(`${path}.evidence`, "must be an array");
2080
+ continue;
2081
+ }
2082
+ let layers = scene && indexes.get(scene.id);
2083
+ if (scene && !layers) {
2084
+ layers = layerIndex(scene);
2085
+ indexes.set(scene.id, layers);
2086
+ }
2087
+ for (const [j, entry] of raw.evidence.entries()) {
2088
+ const p = `${path}.evidence[${j}]`;
2089
+ if (!record$3(entry)) {
2090
+ error$1(p, "must be an object");
2091
+ continue;
2092
+ }
2093
+ fields$1(entry, ["kind", "layerId"], p);
2094
+ if (typeof entry.kind !== "string" || ![
2095
+ "recording",
2096
+ "screenshot",
2097
+ "illustration"
2098
+ ].includes(entry.kind)) error$1(`${p}.kind`, "must be recording, screenshot, or illustration");
2099
+ if (entry.layerId !== void 0) text(entry.layerId, `${p}.layerId`, 200);
2100
+ if (!scene) continue;
2101
+ if (entry.layerId === void 0) {
2102
+ if (entry.kind === "screenshot" || entry.kind === "recording" && scene.type !== "footage") error$1(`${p}.layerId`, "must name an image/video layer in the same motion scene; only footage recordings or illustrations may omit layerId");
2103
+ continue;
2104
+ }
2105
+ const target = typeof entry.layerId === "string" ? layers?.get(entry.layerId)?.layer : void 0;
2106
+ if (!target || target.type !== "image" && target.type !== "video") error$1(`${p}.layerId`, "must name an image or video layer in this same motion scene");
2107
+ else if (entry.kind === "recording" && target.type !== "video" || entry.kind === "screenshot" && target.type !== "image") error$1(`${p}.kind`, `${entry.kind} does not match the referenced ${target.type} layer; recordings require video and screenshots require image`);
2108
+ }
2109
+ }
2110
+ return issues;
2111
+ }
2112
+ function maximum(layer, property, fallback, scene, start, end) {
2113
+ const track = scene.motion !== "off" ? layer.animations?.find((t) => t.property === property) : void 0;
2114
+ if (!track) return Number(layer[property] ?? fallback);
2115
+ return Math.max(Number(evaluateMotionTrack(track, start)), Number(evaluateMotionTrack(track, end)), ...track.keyframes.filter((f) => f.atS > start && f.atS < end).map((f) => Number(f.value)));
2116
+ }
2117
+ /** Proves only zero/near-zero opacity or scale for the complete interval.
2118
+ * It does not establish visible pixels, occlusion, framing, or semantic truth. */
2119
+ function definitelyHidden(ref, scene, start, end) {
2120
+ return [...ref.parents, ref.layer].some((layer) => maximum(layer, "opacity", 1, scene, start, end) <= .001 || maximum(layer, "scaleX", 1, scene, start, end) <= .001 || maximum(layer, "scaleY", 1, scene, start, end) <= .001);
2121
+ }
2122
+ /** Editorial heuristics for structurally validated compositions. These are
2123
+ * warnings, never an aesthetic score or verification of an evidence claim. */
2124
+ function analyzeLaunchStory(composition) {
2125
+ const story = composition.story;
2126
+ if (!story) return [];
2127
+ const issues = [];
2128
+ const warn = (path, message) => issues.push({
2129
+ severity: "warn",
2130
+ path,
2131
+ message
2132
+ });
2133
+ const required = story.intent === "teaser" ? ["promise"] : story.intent === "launch" ? [
2134
+ "context",
2135
+ "promise",
2136
+ "action"
2137
+ ] : ["context", "action"];
2138
+ for (const role of required) if (!story.beats.some((beat) => beat.role === role)) warn("story.beats", `No ${role} beat is declared for this ${story.intent}. Consider ${role === "promise" ? "stating the main message" : role === "context" ? "orienting the intended audience" : "giving the audience a useful next step"}; intentional omissions are allowed.`);
2139
+ const promises = story.beats.filter((beat) => beat.role === "promise");
2140
+ if (new Set(promises.map((beat) => beat.message.trim().replace(/\s+/g, " ").toLowerCase())).size > 1) warn("story.beats", "Several promise beats declare different messages. Check whether they support one main takeaway or compete for attention; this is an editorial prompt, not a semantic judgment.");
2141
+ const scenes = new Map(composition.scenes.map((scene) => [scene.id, scene]));
2142
+ const indexes = new Map();
2143
+ let actualEvidence = false;
2144
+ story.beats.forEach((beat, i) => {
2145
+ const scene = scenes.get(beat.sceneId);
2146
+ const path = `story.beats[${i}]`, start = beat.startS ?? 0, end = beat.endS ?? launchSceneDurationS(scene);
2147
+ const reading = estimateMotionReadingSeconds(beat.message);
2148
+ if (end - start + .001 < reading) warn(`${path}.endS`, `The ${(end - start).toFixed(2)}s editorial window is shorter than the roughly ${reading.toFixed(2)}s reading estimate for its message. Shorten the intended message or allow more time; this does not assert that the message is on-screen copy.`);
2149
+ let layers = indexes.get(scene.id);
2150
+ if (!layers) {
2151
+ layers = layerIndex(scene);
2152
+ indexes.set(scene.id, layers);
2153
+ }
2154
+ let beatActual = false;
2155
+ (beat.evidence ?? []).forEach((evidence, j) => {
2156
+ const p = `${path}.evidence[${j}]`, ref = evidence.layerId ? layers.get(evidence.layerId) : void 0;
2157
+ const hidden = ref && scene.type === "motion" && definitelyHidden(ref, scene, start, end);
2158
+ if (hidden) warn(p, "The referenced evidence has zero or near-zero opacity/scale throughout this beat, including its ancestors. It cannot supply visible evidence in this window.");
2159
+ if (evidence.kind !== "illustration" && !hidden) beatActual = true;
2160
+ if (evidence.kind === "recording" && ref?.layer.type === "video") {
2161
+ const activeStart = ref.layer.startS ?? 0, activeEnd = activeStart + ref.layer.durationS;
2162
+ if (Math.min(end, activeEnd) <= Math.max(start, activeStart)) warn(p, "This beat does not overlap the recording layer's active playback span; the renderer holds an endpoint frame here. It may show a real still, but does not demonstrate recorded motion in this window.");
2163
+ }
2164
+ });
2165
+ actualEvidence ||= beatActual;
2166
+ if (beat.role === "proof" && !beatActual) warn(`${path}.evidence`, `This ${story.intent} declares a proof beat without potentially visible recording/screenshot evidence. An illustration can explain an idea but is not actual UI proof.`);
2167
+ });
2168
+ if (story.intent !== "teaser" && !actualEvidence) warn("story.beats", "No potentially visible recording/screenshot evidence is declared. Add a relevant actual source for the main claim; illustrations do not count as actual UI proof. References alone cannot verify what an asset depicts or whether a claim is true.");
2169
+ return issues;
2170
+ }
2171
+
2172
+ //#endregion
2173
+ //#region src/motion-validate.ts
2174
+ const record$2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
2175
+ const finite$1 = (v) => typeof v === "number" && Number.isFinite(v);
2176
+ const transforms = [
2177
+ "x",
2178
+ "y",
2179
+ "opacity",
2180
+ "scaleX",
2181
+ "scaleY",
2182
+ "rotation"
2183
+ ];
2184
+ const fields = {
2185
+ group: [
2186
+ "children",
2187
+ "width",
2188
+ "height",
2189
+ "clip",
2190
+ "radius"
2191
+ ],
2192
+ rect: [
2193
+ "width",
2194
+ "height",
2195
+ "fill",
2196
+ "stroke",
2197
+ "strokeWidth",
2198
+ "radius",
2199
+ "shadow"
2200
+ ],
2201
+ ellipse: [
2202
+ "width",
2203
+ "height",
2204
+ "fill",
2205
+ "stroke",
2206
+ "strokeWidth"
2207
+ ],
2208
+ text: [
2209
+ "text",
2210
+ "width",
2211
+ "height",
2212
+ "fontSize",
2213
+ "fontFamily",
2214
+ "fontWeight",
2215
+ "fill",
2216
+ "align",
2217
+ "lineHeight",
2218
+ "reveal"
2219
+ ],
2220
+ image: [
2221
+ "asset",
2222
+ "width",
2223
+ "height",
2224
+ "fit",
2225
+ "radius",
2226
+ "crop",
2227
+ "shadow"
2228
+ ],
2229
+ video: [
2230
+ "asset",
2231
+ "width",
2232
+ "height",
2233
+ "fit",
2234
+ "radius",
2235
+ "trimStartS",
2236
+ "startS",
2237
+ "durationS",
2238
+ "shadow"
2239
+ ],
2240
+ line: [
2241
+ "points",
2242
+ "stroke",
2243
+ "strokeWidth",
2244
+ "end"
2245
+ ]
2246
+ };
2247
+ const animated = new Set([
2248
+ ...transforms,
2249
+ "width",
2250
+ "height",
2251
+ "radius",
2252
+ "fill",
2253
+ "stroke",
2254
+ "strokeWidth",
2255
+ "fontSize",
2256
+ "reveal",
2257
+ "end"
2258
+ ]);
2259
+ const ranges = {
2260
+ x: [-1e6, 1e6],
2261
+ y: [-1e6, 1e6],
2262
+ rotation: [-36e3, 36e3],
2263
+ opacity: [0, 1],
2264
+ scaleX: [0, 100],
2265
+ scaleY: [0, 100],
2266
+ reveal: [0, 1],
2267
+ end: [0, 1],
2268
+ width: [.001, 32768],
2269
+ height: [.001, 32768],
2270
+ radius: [0, 16384],
2271
+ strokeWidth: [0, 4096],
2272
+ fontSize: [8, 512],
2273
+ lineHeight: [8, 4096],
2274
+ fontWeight: [100, 1e3],
2275
+ trimStartS: [0, 86400],
2276
+ startS: [0, 86400],
2277
+ durationS: [.001, 86400]
2278
+ };
2279
+ /** Structural validation only; media streams, dimensions and clip bounds are probed asynchronously. */
2280
+ function validateMotionScene(value, path = "$", baseDir) {
2281
+ const issues = [];
2282
+ const add = (p, message) => issues.push({
2283
+ severity: "error",
2284
+ path: p,
2285
+ message
2286
+ });
2287
+ if (!record$2(value)) return [{
2288
+ severity: "error",
2289
+ path,
2290
+ message: "must be an object"
2291
+ }];
2292
+ const rejectUnknown = (obj, allowed, p) => {
2293
+ for (const key of Object.keys(obj)) if (!allowed.includes(key)) add(`${p}.${key}`, "unsupported field");
2294
+ };
2295
+ const range = (v, p, min, max) => {
2296
+ if (!finite$1(v) || v < min || v > max) {
2297
+ add(p, `must be finite and between ${min} and ${max}`);
2298
+ return false;
2299
+ }
2300
+ return true;
2301
+ };
2302
+ const numeric = (v, p, key) => range(v, p, ...ranges[key]);
2303
+ const text = (v, p, limit) => {
2304
+ if (typeof v !== "string" || !v.trim() || v.length > limit) {
2305
+ add(p, `must be a non-empty string of at most ${limit} characters`);
2306
+ return false;
2307
+ }
2308
+ return true;
2309
+ };
2310
+ const enumValue = (v, p, choices) => {
2311
+ if (typeof v !== "string" || !choices.includes(v)) add(p, `must be ${choices.join(", ")}`);
2312
+ };
2313
+ rejectUnknown(value, [
2314
+ "id",
2315
+ "type",
2316
+ "durationS",
2317
+ "transition",
2318
+ "background",
2319
+ "colors",
2320
+ "motion",
2321
+ "designSize",
2322
+ "layers"
2323
+ ], path);
2324
+ if (value.type !== "motion") add(`${path}.type`, "must be motion");
2325
+ if (!finite$1(value.durationS) || value.durationS <= 0) add(`${path}.durationS`, "must be finite and positive");
2326
+ if (value.designSize !== void 0) if (!record$2(value.designSize)) add(`${path}.designSize`, "must be an object");
2327
+ else {
2328
+ rejectUnknown(value.designSize, ["width", "height"], `${path}.designSize`);
2329
+ for (const key of ["width", "height"]) range(value.designSize[key], `${path}.designSize.${key}`, 1, 32768);
2330
+ }
2331
+ const ids = new Set();
2332
+ let count = 0, videoCount = 0;
2333
+ const visit = (rawLayers, p, depth) => {
2334
+ if (!Array.isArray(rawLayers)) {
2335
+ add(p, "must be an array of layers");
2336
+ return;
2337
+ }
2338
+ for (const [i, raw] of rawLayers.entries()) {
2339
+ const q = `${p}[${i}]`;
2340
+ if (++count > 256) {
2341
+ if (count === 257) add(q, "scene exceeds the 256-layer limit including nested groups");
2342
+ return;
2343
+ }
2344
+ if (!record$2(raw)) {
2345
+ add(q, "must be an object");
2346
+ continue;
2347
+ }
2348
+ const layer = raw;
2349
+ if (text(layer.id, `${q}.id`, 200)) {
2350
+ const id = layer.id;
2351
+ if (ids.has(id)) add(`${q}.id`, `duplicate layer id ${JSON.stringify(id)}`);
2352
+ ids.add(id);
2353
+ }
2354
+ if (typeof layer.type !== "string" || !Object.hasOwn(fields, layer.type)) {
2355
+ add(`${q}.type`, "unsupported layer type");
2356
+ continue;
2357
+ }
2358
+ const kind = layer.type, own = fields[kind];
2359
+ if (kind === "video" && ++videoCount > 8 && videoCount === 9) add(q, "scene exceeds the 8-video layer limit including nested groups");
2360
+ rejectUnknown(layer, [
2361
+ "id",
2362
+ "type",
2363
+ "animations",
2364
+ ...transforms,
2365
+ ...own
2366
+ ], q);
2367
+ for (const key of [...transforms, ...own]) {
2368
+ if (ranges[key] && layer[key] !== void 0) numeric(layer[key], `${q}.${key}`, key);
2369
+ if ((key === "fill" || key === "stroke") && layer[key] !== void 0 && !parseMotionColor(layer[key])) add(`${q}.${key}`, "must be a valid #RRGGBB/#RRGGBBAA/rgb()/rgba() color");
2370
+ }
2371
+ const extremes = new Map();
2372
+ for (const key of [
2373
+ "width",
2374
+ "height",
2375
+ "fontSize"
2376
+ ]) if (finite$1(layer[key])) extremes.set(key, [layer[key]]);
2377
+ if (layer.animations !== void 0 && !Array.isArray(layer.animations)) add(`${q}.animations`, "must be an array");
2378
+ const seen = new Set();
2379
+ for (const [j, track] of (Array.isArray(layer.animations) ? layer.animations : []).entries()) {
2380
+ const a = `${q}.animations[${j}]`;
2381
+ if (!record$2(track)) {
2382
+ add(a, "must be an object");
2383
+ continue;
2384
+ }
2385
+ rejectUnknown(track, ["property", "keyframes"], a);
2386
+ const property = track.property;
2387
+ if (typeof property !== "string" || !animated.has(property) || !transforms.includes(property) && !own.includes(property)) {
2388
+ add(`${a}.property`, "unsupported animation property for this layer type");
2389
+ continue;
2390
+ }
2391
+ if (kind === "group" && property === "radius" && layer.clip !== true) add(`${a}.property`, "group radius animation requires clip: true");
2392
+ if (seen.has(property)) add(`${a}.property`, "only one track per property is allowed");
2393
+ seen.add(property);
2394
+ if (!Array.isArray(track.keyframes) || track.keyframes.length < 1 || track.keyframes.length > 128) {
2395
+ add(`${a}.keyframes`, "must contain between 1 and 128 keyframes");
2396
+ continue;
2397
+ }
2398
+ let previous = -1;
2399
+ for (const [k, frame] of track.keyframes.entries()) {
2400
+ const f = `${a}.keyframes[${k}]`;
2401
+ if (!record$2(frame)) {
2402
+ add(f, "must be an object");
2403
+ continue;
2404
+ }
2405
+ rejectUnknown(frame, [
2406
+ "atS",
2407
+ "value",
2408
+ "easing"
2409
+ ], f);
2410
+ if (!finite$1(frame.atS) || frame.atS < 0 || finite$1(value.durationS) && frame.atS > value.durationS) add(`${f}.atS`, "must be finite and inside the scene duration");
2411
+ else {
2412
+ if (k === 0 && frame.atS !== 0) add(`${f}.atS`, "first keyframe must be at 0");
2413
+ if (frame.atS <= previous) add(`${f}.atS`, "keyframe times must strictly increase");
2414
+ previous = frame.atS;
2415
+ }
2416
+ if (frame.easing !== void 0) enumValue(frame.easing, `${f}.easing`, [
2417
+ "linear",
2418
+ "ease-in",
2419
+ "ease-out",
2420
+ "ease-in-out",
2421
+ "step"
2422
+ ]);
2423
+ if (property === "fill" || property === "stroke") {
2424
+ if (!parseMotionColor(frame.value)) add(`${f}.value`, "must be a supported color");
2425
+ } else if (numeric(frame.value, `${f}.value`, property) && [
2426
+ "width",
2427
+ "height",
2428
+ "fontSize"
2429
+ ].includes(property)) extremes.set(property, [...extremes.get(property) ?? [], frame.value]);
2430
+ }
2431
+ }
2432
+ if (kind === "group") {
2433
+ if (layer.clip !== void 0 && typeof layer.clip !== "boolean") add(`${q}.clip`, "must be a boolean");
2434
+ if (layer.clip !== true && layer.radius !== void 0) add(`${q}.radius`, "group radius requires clip: true");
2435
+ if (layer.clip === true) {
2436
+ for (const key of ["width", "height"]) if (layer[key] === void 0) add(`${q}.${key}`, "clipping requires a positive base dimension");
2437
+ }
2438
+ if (depth >= 8) add(q, "group nesting exceeds the maximum depth of 8");
2439
+ else visit(layer.children, `${q}.children`, depth + 1);
2440
+ } else if (kind === "line") if (!Array.isArray(layer.points) || layer.points.length < 2 || layer.points.length > 1024) add(`${q}.points`, "must contain between 2 and 1024 coordinate pairs");
2441
+ else for (const [j, point] of layer.points.entries()) if (!Array.isArray(point) || point.length !== 2) add(`${q}.points[${j}]`, "must be an [x,y] pair");
2442
+ else point.forEach((v, k) => {
2443
+ range(v, `${q}.points[${j}][${k}]`, -1e6, 1e6);
2444
+ });
2445
+ else for (const key of ["width", "height"]) if (layer[key] === void 0) add(`${q}.${key}`, "is required and must be positive");
2446
+ if (kind === "text") {
2447
+ const validText = text(layer.text, `${q}.text`, 4e3);
2448
+ if (layer.fontSize === void 0) add(`${q}.fontSize`, "is required");
2449
+ if (layer.fontFamily !== void 0) text(layer.fontFamily, `${q}.fontFamily`, 300);
2450
+ if (layer.align !== void 0) enumValue(layer.align, `${q}.align`, [
2451
+ "left",
2452
+ "center",
2453
+ "right"
2454
+ ]);
2455
+ const width = Math.min(...extremes.get("width") ?? [NaN]), height = Math.min(...extremes.get("height") ?? [NaN]), font = Math.max(...extremes.get("fontSize") ?? [NaN]);
2456
+ if (validText && width > 0 && height > 0 && font >= 8) {
2457
+ const lineHeight = finite$1(layer.lineHeight) ? layer.lineHeight : font * 1.2;
2458
+ if (lineHeight < font) add(`${q}.lineHeight`, "must not be smaller than the largest animated fontSize");
2459
+ if (estimateMotionTextLines(layer.text, width, font) * lineHeight > height + .001) add(`${q}.text`, "copy cannot fit the text box at its narrowest/smallest dimensions and largest fontSize; enlarge the box or shorten the copy");
2460
+ }
2461
+ }
2462
+ if (kind === "image" || kind === "video") {
2463
+ if (text(layer.asset, `${q}.asset`, 4096)) {
2464
+ const asset = layer.asset;
2465
+ const extensions = kind === "image" ? [
2466
+ ".png",
2467
+ ".jpg",
2468
+ ".jpeg",
2469
+ ".webp"
2470
+ ] : [
2471
+ ".mp4",
2472
+ ".webm",
2473
+ ".mov"
2474
+ ];
2475
+ if (asset.includes("\0") || /^[a-z][a-z\d+.-]*:/i.test(asset) && !/^[a-z]:[\\/]/i.test(asset)) add(`${q}.asset`, kind === "image" ? "must be a local PNG/JPEG/WebP path" : "must be a local MP4/WebM/MOV path");
2476
+ else if (!extensions.includes(extname(asset).toLowerCase())) add(`${q}.asset`, kind === "image" ? "only PNG/JPEG/WebP image assets are supported" : "only MP4/WebM/MOV video assets are supported");
2477
+ else if (baseDir) try {
2478
+ if (!statSync(resolve(baseDir, asset)).isFile()) add(`${q}.asset`, "asset is not a regular file");
2479
+ } catch {
2480
+ add(`${q}.asset`, `missing asset: ${asset}`);
2481
+ }
2482
+ }
2483
+ if (layer.fit !== void 0) enumValue(layer.fit, `${q}.fit`, ["contain", "cover"]);
2484
+ if (kind === "image" && layer.crop !== void 0) if (!record$2(layer.crop)) add(`${q}.crop`, "must be an object");
2485
+ else {
2486
+ rejectUnknown(layer.crop, [
2487
+ "x",
2488
+ "y",
2489
+ "width",
2490
+ "height"
2491
+ ], `${q}.crop`);
2492
+ for (const key of [
2493
+ "x",
2494
+ "y",
2495
+ "width",
2496
+ "height"
2497
+ ]) {
2498
+ range(layer.crop[key], `${q}.crop.${key}`, key === "x" || key === "y" ? 0 : 1, 32768);
2499
+ if (finite$1(layer.crop[key]) && !Number.isInteger(layer.crop[key])) add(`${q}.crop.${key}`, "must be an integer source-pixel coordinate or size");
2500
+ }
2501
+ }
2502
+ }
2503
+ if (kind === "video") {
2504
+ if (layer.durationS === void 0) add(`${q}.durationS`, "is required and must be positive");
2505
+ const start = layer.startS === void 0 ? 0 : layer.startS;
2506
+ if (finite$1(start) && finite$1(value.durationS) && start > value.durationS) add(`${q}.startS`, "must be inside the scene duration");
2507
+ if (finite$1(start) && finite$1(layer.durationS) && finite$1(value.durationS) && start + layer.durationS > value.durationS + 1e-9) add(`${q}.durationS`, "video active span (startS + durationS) must stay inside the scene duration");
2508
+ }
2509
+ if (kind === "rect" || kind === "image" || kind === "video") {
2510
+ if (layer.shadow !== void 0) {
2511
+ const shadowPath = `${q}.shadow`;
2512
+ if (!record$2(layer.shadow)) add(shadowPath, "must be an object");
2513
+ else {
2514
+ rejectUnknown(layer.shadow, [
2515
+ "color",
2516
+ "blur",
2517
+ "offsetX",
2518
+ "offsetY"
2519
+ ], shadowPath);
2520
+ if (!parseMotionColor(layer.shadow.color)) add(`${shadowPath}.color`, "must be a valid #RRGGBB/#RRGGBBAA/rgb()/rgba() color");
2521
+ range(layer.shadow.blur, `${shadowPath}.blur`, 0, 256);
2522
+ for (const key of ["offsetX", "offsetY"]) if (layer.shadow[key] !== void 0) range(layer.shadow[key], `${shadowPath}.${key}`, -512, 512);
2523
+ }
2524
+ }
2525
+ }
2526
+ }
2527
+ };
2528
+ if (Array.isArray(value.layers) && !value.layers.length) add(`${path}.layers`, "must contain at least one layer");
2529
+ visit(value.layers, `${path}.layers`, 0);
2530
+ return issues;
2531
+ }
2532
+ /** Conservative grapheme-aware wrapping estimate; it never splits a Unicode grapheme. */
2533
+ function estimateMotionTextLines(text, width, fontSize) {
2534
+ let lines = 1, used = 0;
2535
+ for (const grapheme of motionGraphemes(text)) {
2536
+ if (grapheme === "\n" || grapheme === "\r\n") {
2537
+ lines++;
2538
+ used = 0;
2539
+ continue;
2540
+ }
2541
+ const advance = fontSize * (grapheme.length === 1 && grapheme.charCodeAt(0) <= 255 ? /[MW@%]/.test(grapheme) ? .95 : .62 : 1);
2542
+ if (advance > width) return Infinity;
2543
+ if (used + advance > width + .001) {
2544
+ lines++;
2545
+ used = 0;
2546
+ }
2547
+ used += advance;
2548
+ }
2549
+ return lines;
2550
+ }
2551
+
2552
+ //#endregion
2553
+ //#region src/launch-validate.ts
2554
+ const record$1 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2555
+ const number = (value) => typeof value === "number" && Number.isFinite(value);
2556
+ const issue = (path, message) => ({
2557
+ severity: "error",
2558
+ path,
2559
+ message
2560
+ });
2561
+ const colorKeys = [
2562
+ "canvas",
2563
+ "ink",
2564
+ "surface",
2565
+ "accent",
2566
+ "dark"
2567
+ ];
2568
+ const validColor = (value) => {
2569
+ if (typeof value !== "string") return false;
2570
+ if (/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(value)) return true;
2571
+ const match = value.match(/^(rgb|rgba)\(\s*(\d+(?:\.\d+)?|\.\d+)\s*,\s*(\d+(?:\.\d+)?|\.\d+)\s*,\s*(\d+(?:\.\d+)?|\.\d+)(?:\s*,\s*(\d+(?:\.\d+)?|\.\d+))?\s*\)$/i);
2572
+ return !!match && match[1].toLowerCase() === "rgba" === (match[5] !== void 0) && match.slice(2, 5).every((x) => Number(x) <= 255) && (match[5] === void 0 || Number(match[5]) <= 1);
2573
+ };
2574
+ /** Validate untrusted JSON before any timing/layout evaluator can access it. */
2575
+ function validateLaunchComposition(value, baseDir) {
2576
+ const out = [];
2577
+ if (!record$1(value)) return [issue("$", "must be a JSON object")];
2578
+ const add = (path, message) => out.push(issue(path, message));
2579
+ const bounded = (v, p, min, max = Number.MAX_SAFE_INTEGER) => {
2580
+ if (!number(v) || v < min || v > max) {
2581
+ add(p, `must be finite and between ${min} and ${max}`);
2582
+ return false;
2583
+ }
2584
+ return true;
2585
+ };
2586
+ const text = (v, p, max = 200, empty = false) => {
2587
+ if (typeof v !== "string" || !empty && !v.trim()) {
2588
+ add(p, "must be a non-empty string");
2589
+ return false;
2590
+ }
2591
+ if (v.length > max) add(p, `exceeds the readable ${max}-character bound`);
2592
+ return true;
2593
+ };
2594
+ const optionalText = (obj, key, p, max) => {
2595
+ if (obj[key] !== void 0) text(obj[key], `${p}.${key}`, max);
2596
+ };
2597
+ const enumValue = (v, p, choices) => {
2598
+ if (typeof v !== "string" || !choices.includes(v)) add(p, `must be ${choices.join(", ")}`);
2599
+ };
2600
+ const theme = (v, p, partial) => {
2601
+ if (!record$1(v)) {
2602
+ add(p, "must be an object");
2603
+ return;
2604
+ }
2605
+ for (const key of colorKeys) if ((!partial || v[key] !== void 0) && !validColor(v[key])) add(`${p}.${key}`, "must be a valid #RRGGBB/#RRGGBBAA/rgb()/rgba() color");
2606
+ if (!partial || v.fontFamily !== void 0) text(v.fontFamily, `${p}.fontFamily`, 300);
2607
+ };
2608
+ const asset = (v, p) => {
2609
+ if (!text(v, p, 4096)) return;
2610
+ if (v.includes("\0")) {
2611
+ add(p, "must be a local path without NUL characters");
2612
+ return;
2613
+ }
2614
+ if (baseDir) try {
2615
+ if (!statSync(resolve(baseDir, v)).isFile()) add(p, `asset is not a regular file: ${v}`);
2616
+ } catch {
2617
+ add(p, `missing asset: ${v}`);
2618
+ }
2619
+ };
2620
+ if (value.version !== 1) add("version", "must be the supported launch composition version 1");
2621
+ const output = record$1(value.output) ? value.output : {};
2622
+ for (const key of ["width", "height"]) if (bounded(output[key], `output.${key}`, 2, 16384) && output[key] % 2 !== 0) add(`output.${key}`, "must be an even integer");
2623
+ bounded(output.fps, "output.fps", 1, 120);
2624
+ theme(value.theme, "theme", false);
2625
+ if (!Array.isArray(value.scenes) || value.scenes.length === 0) add("scenes", "must contain at least one scene");
2626
+ const scenes = Array.isArray(value.scenes) ? value.scenes : [];
2627
+ const ids = new Set(), ends = new Map();
2628
+ let total = 0;
2629
+ for (const [i, raw] of scenes.entries()) {
2630
+ const p = `scenes[${i}]`;
2631
+ if (!record$1(raw)) {
2632
+ add(p, "must be an object");
2633
+ continue;
2634
+ }
2635
+ const scene = raw;
2636
+ if (text(scene.id, `${p}.id`, 200)) {
2637
+ if (ids.has(scene.id)) add(`${p}.id`, `duplicate id ${JSON.stringify(scene.id)}`);
2638
+ ids.add(scene.id);
2639
+ }
2640
+ enumValue(scene.type, `${p}.type`, [
2641
+ "title",
2642
+ "footage",
2643
+ "ui-morph",
2644
+ "end-card",
2645
+ "motion"
2646
+ ]);
2647
+ if (scene.background !== void 0) enumValue(scene.background, `${p}.background`, ["canvas", "dark"]);
2648
+ if (scene.motion !== void 0) enumValue(scene.motion, `${p}.motion`, ["on", "off"]);
2649
+ if (scene.colors !== void 0) theme(scene.colors, `${p}.colors`, true);
2650
+ let duration = 0;
2651
+ if (scene.type !== "ui-morph" || scene.durationS !== void 0) {
2652
+ if (bounded(scene.durationS, `${p}.durationS`, Number.MIN_VALUE, 86400)) duration = scene.durationS;
2653
+ }
2654
+ if (scene.type === "motion") out.push(...validateMotionScene(scene, p, baseDir));
2655
+ else if (scene.type === "title") {
2656
+ const lines = Array.isArray(scene.lines) ? scene.lines : [];
2657
+ if (!lines.length || lines.length > 6) add(`${p}.lines`, "must contain between 1 and 6 non-empty string lines");
2658
+ for (const [j, line] of lines.entries()) if (text(line, `${p}.lines[${j}]`, 90) && estimatedTextWidth(line, lines.length > 2 ? 92 : 112) > 1760) add(`${p}.lines[${j}]`, "is too wide for the title region; split it into more lines");
2659
+ optionalText(scene, "brand", p, 60);
2660
+ if (scene.staggerS !== void 0) bounded(scene.staggerS, `${p}.staggerS`, 0, 86400);
2661
+ if (scene.motion !== "off" && .18 + Math.max(0, lines.length - 1) * (number(scene.staggerS) ? scene.staggerS : .36) + .45 > duration) add(`${p}.durationS`, "last line cannot finish entering within scene duration; increase duration or set motion to off");
2662
+ } else if (scene.type === "footage") {
2663
+ asset(scene.asset, `${p}.asset`);
2664
+ if (scene.trimStartS !== void 0) bounded(scene.trimStartS, `${p}.trimStartS`, 0);
2665
+ if (scene.fit !== void 0) enumValue(scene.fit, `${p}.fit`, ["contain", "cover"]);
2666
+ optionalText(scene, "caption", p, 80);
2667
+ if (typeof scene.caption === "string" && estimatedTextWidth(scene.caption, 34) > 1720) add(`${p}.caption`, "is too wide for the caption region");
2668
+ if (scene.frame !== void 0) if (!record$1(scene.frame)) add(`${p}.frame`, "must be an object");
2669
+ else {
2670
+ bounded(scene.frame.inset, `${p}.frame.inset`, 0, 500);
2671
+ bounded(scene.frame.radius, `${p}.frame.radius`, 0, number(scene.frame.inset) ? Math.max(0, 540 - scene.frame.inset) : 540);
2672
+ }
2673
+ } else if (scene.type === "ui-morph") {
2674
+ let width = 1100, compact = 112, expanded = 218, radius = 34;
2675
+ if (scene.panel !== void 0) if (!record$1(scene.panel)) add(`${p}.panel`, "must be an object");
2676
+ else {
2677
+ if (bounded(scene.panel.width, `${p}.panel.width`, 400, 1700)) width = scene.panel.width;
2678
+ if (bounded(scene.panel.compactHeight, `${p}.panel.compactHeight`, 112, 680)) compact = scene.panel.compactHeight;
2679
+ if (bounded(scene.panel.expandedHeight, `${p}.panel.expandedHeight`, 180, 680)) expanded = scene.panel.expandedHeight;
2680
+ if (bounded(scene.panel.radius, `${p}.panel.radius`, 0, Math.min(width, compact, expanded) / 2)) radius = scene.panel.radius;
2681
+ }
2682
+ optionalText(scene, "eyebrow", p, 60);
2683
+ const states = Array.isArray(scene.states) ? scene.states : [];
2684
+ if (!states.length) add(`${p}.states`, "must contain at least one state");
2685
+ let derived = 0;
2686
+ for (const [j, rawState] of states.entries()) {
2687
+ const q = `${p}.states[${j}]`;
2688
+ if (!record$1(rawState)) {
2689
+ add(q, "must be an object");
2690
+ continue;
2691
+ }
2692
+ const state = rawState;
2693
+ enumValue(state.icon, `${q}.icon`, [
2694
+ "record",
2695
+ "style",
2696
+ "refine",
2697
+ "camera",
2698
+ "spark",
2699
+ "target"
2700
+ ]);
2701
+ text(state.label, `${q}.label`, 24);
2702
+ text(state.prompt, `${q}.prompt`, 90, j === 0);
2703
+ for (const key of [
2704
+ "transitionS",
2705
+ "typeS",
2706
+ "typeDelayS",
2707
+ "holdS"
2708
+ ]) bounded(state[key], `${q}.${key}`, key === "transitionS" || key === "typeS" ? Number.MIN_VALUE : 0, 86400);
2709
+ if ([
2710
+ state.transitionS,
2711
+ state.typeS,
2712
+ state.typeDelayS,
2713
+ state.holdS
2714
+ ].every(number)) derived += Math.max(state.transitionS, state.typeDelayS + state.typeS) + state.holdS;
2715
+ if (state.panelWidth !== void 0) bounded(state.panelWidth, `${q}.panelWidth`, 400, 1700);
2716
+ if (state.panelHeight !== void 0) bounded(state.panelHeight, `${q}.panelHeight`, j === 0 && state.prompt === "" ? 112 : 180, 680);
2717
+ const pw = number(state.panelWidth) ? state.panelWidth : width, ph = number(state.panelHeight) ? state.panelHeight : j === 0 ? compact : expanded;
2718
+ if (radius > Math.min(pw, ph) / 2) add(`${q}.panelHeight`, "panel dimensions must fit the configured corner radius");
2719
+ if (typeof state.prompt === "string" && estimatedTextWidth(state.prompt, 46) > pw - 150) add(`${q}.prompt`, `is too wide for its ${pw}px panel; shorten it or increase panelWidth`);
2720
+ if (typeof state.label === "string" && (132 + state.label.length * 11 > pw - 100 || estimatedTextWidth(state.label, 30) > 50 + state.label.length * 11)) add(`${q}.label`, "is too wide for its chip; shorten the label");
2721
+ if (j === 0 && typeof state.prompt === "string" && state.prompt.trim() && ph < 180) add(`${q}.panelHeight`, "a visible prompt needs an expanded panel of at least 180px");
2722
+ }
2723
+ if (number(scene.durationS) && Math.abs(scene.durationS - derived) > 1e-6) add(`${p}.durationS`, `must equal the ${derived.toFixed(3)}s derived from state timings`);
2724
+ duration = derived;
2725
+ } else if (scene.type === "end-card") {
2726
+ text(scene.headline, `${p}.headline`, 110);
2727
+ if (scene.motion !== "off" && duration < 1.3) add(`${p}.durationS`, "CTA cannot finish entering before 1.3s; increase duration or set motion to off");
2728
+ if (typeof scene.headline === "string") {
2729
+ const wrapped = [];
2730
+ for (const authored of scene.headline.split("\n")) {
2731
+ let line = "";
2732
+ for (const word of authored.split(" ")) if ((line + " " + word).trim().length > 30 && line) {
2733
+ wrapped.push(line);
2734
+ line = word;
2735
+ } else line = (line + " " + word).trim();
2736
+ if (line) wrapped.push(line);
2737
+ }
2738
+ if (wrapped.length > 3 || wrapped.some((line) => estimatedTextWidth(line, 92) > 1760)) add(`${p}.headline`, "cannot fit the three-line headline region; shorten copy or add suitable line breaks");
2739
+ }
2740
+ text(scene.brand, `${p}.brand`, 60);
2741
+ text(scene.cta, `${p}.cta`, 100);
2742
+ if (typeof scene.cta === "string" && estimatedTextWidth(scene.cta, 28) > 1700) add(`${p}.cta`, "is too wide for the CTA region");
2743
+ if (typeof scene.brand === "string" && estimatedTextWidth(scene.brand, 30) + scene.brand.length * 4 > 1760) add(`${p}.brand`, "is too wide for the brand region");
2744
+ }
2745
+ if (scene.transition !== void 0) if (!record$1(scene.transition)) add(`${p}.transition`, "must be an object");
2746
+ else {
2747
+ enumValue(scene.transition.type, `${p}.transition.type`, [
2748
+ "cut",
2749
+ "fade",
2750
+ "slide"
2751
+ ]);
2752
+ if (scene.transition.durationS !== void 0) bounded(scene.transition.durationS, `${p}.transition.durationS`, Number.MIN_VALUE, duration / 2);
2753
+ }
2754
+ total += duration;
2755
+ if (typeof scene.id === "string") ends.set(scene.id, total);
2756
+ }
2757
+ if (!Number.isFinite(total) || total > 86400) add("scenes", "total duration must be finite and no more than 86400s");
2758
+ if (value.audio !== void 0 && !Array.isArray(value.audio)) add("audio", "must be an array");
2759
+ const audio = Array.isArray(value.audio) ? value.audio : [], audioIds = new Set();
2760
+ for (const [i, raw] of audio.entries()) {
2761
+ const p = `audio[${i}]`;
2762
+ if (!record$1(raw)) {
2763
+ add(p, "must be an object");
2764
+ continue;
2765
+ }
2766
+ const track = raw;
2767
+ if (text(track.id, `${p}.id`, 200)) {
2768
+ if (audioIds.has(track.id)) add(`${p}.id`, "duplicate audio id");
2769
+ audioIds.add(track.id);
2770
+ }
2771
+ enumValue(track.kind, `${p}.kind`, [
2772
+ "music",
2773
+ "narration",
2774
+ "sfx"
2775
+ ]);
2776
+ asset(track.asset, `${p}.asset`);
2777
+ if (track.atS === void 0 === (track.afterSceneId === void 0)) add(p, "set exactly one of atS or afterSceneId");
2778
+ if (track.atS !== void 0) bounded(track.atS, `${p}.atS`, 0);
2779
+ if (track.afterSceneId !== void 0 && (typeof track.afterSceneId !== "string" || !ends.has(track.afterSceneId))) add(`${p}.afterSceneId`, "does not name a scene");
2780
+ if (track.offsetS !== void 0) {
2781
+ bounded(track.offsetS, `${p}.offsetS`, -86400, 86400);
2782
+ if (track.atS !== void 0) add(`${p}.offsetS`, "requires afterSceneId; use atS for absolute placement");
2783
+ }
2784
+ for (const key of [
2785
+ "trimStartS",
2786
+ "fadeInS",
2787
+ "fadeOutS",
2788
+ "durationS"
2789
+ ]) if (track[key] !== void 0) bounded(track[key], `${p}.${key}`, key === "durationS" ? Number.MIN_VALUE : 0);
2790
+ if (track.gain !== void 0) bounded(track.gain, `${p}.gain`, 0, 8);
2791
+ for (const key of ["loop", "duckMusic"]) if (track[key] !== void 0 && typeof track[key] !== "boolean") add(`${p}.${key}`, "must be a boolean");
2792
+ if (track.loop === true && track.kind !== "music") add(`${p}.loop`, "is supported only for music");
2793
+ if (track.duckMusic === true && track.kind !== "narration") add(`${p}.duckMusic`, "is supported only for narration");
2794
+ const at = number(track.atS) ? track.atS : (typeof track.afterSceneId === "string" ? ends.get(track.afterSceneId) ?? 0 : 0) + (number(track.offsetS) ? track.offsetS : 0);
2795
+ const duration = number(track.durationS) ? track.durationS : total - at;
2796
+ if (at < 0 || at >= total) add(`${p}.atS`, "resolved position must be within the composition duration");
2797
+ if (at + duration > total + 1e-6) add(`${p}.durationS`, "extends past the composition duration");
2798
+ const fades = (number(track.fadeInS) ? track.fadeInS : 0) + (number(track.fadeOutS) ? track.fadeOutS : 0);
2799
+ if (fades > duration) add(`${p}.fadeOutS`, "fade-in plus fade-out exceeds the resolved track duration");
2800
+ }
2801
+ out.push(...validateLaunchStory(value.story, out.some((item) => item.path.startsWith("scenes")) ? void 0 : scenes));
2802
+ return out;
2803
+ }
2804
+ function estimatedTextWidth(text, size) {
2805
+ let units = 0;
2806
+ for (const char of text) units += (char.codePointAt(0) ?? 0) > 255 ? 1 : .58;
2807
+ return units * size;
2808
+ }
2809
+ function formatLaunchIssues(issues) {
2810
+ return issues.map((x) => `${x.severity}: ${x.path}: ${x.message}`).join("\n");
2811
+ }
2812
+
2813
+ //#endregion
2814
+ //#region src/render-lock.ts
2815
+ let renderQueue = Promise.resolve();
2816
+ /** Revideo changes process.cwd(), so all compositor renders share one lock. */
2817
+ function withRenderLock(operation) {
2818
+ const run$2 = renderQueue.then(operation, operation);
2819
+ renderQueue = run$2.catch(() => {});
2820
+ return run$2;
2821
+ }
2822
+
2823
+ //#endregion
2824
+ //#region src/launch-render.ts
2825
+ const PKG_ROOT$1 = resolve(dirname(fileURLToPath(import.meta.url)), "..");
2826
+ /** Media subprocesses must not hang or retain unbounded corrupt-file diagnostics. */
2827
+ async function run$1(bin, args, capture = false, timeoutMs = 12e4) {
2828
+ return new Promise((ok, fail) => {
2829
+ const child = spawn(bin, args, { stdio: [
2830
+ "ignore",
2831
+ capture ? "pipe" : "ignore",
2832
+ "pipe"
2833
+ ] });
2834
+ let out = "", err = "", settled = false;
2835
+ const finish = (error$1) => {
2836
+ if (settled) return;
2837
+ settled = true;
2838
+ clearTimeout(timer);
2839
+ if (error$1) fail(error$1);
2840
+ else ok(out);
2841
+ };
2842
+ const timer = setTimeout(() => {
2843
+ child.kill("SIGKILL");
2844
+ finish(new Error(`${basename(bin)} exceeded the ${timeoutMs / 1e3}s media-operation limit`));
2845
+ }, timeoutMs);
2846
+ child.stdout?.on("data", (data) => {
2847
+ out += data.toString();
2848
+ if (out.length > 1e6) {
2849
+ child.kill("SIGKILL");
2850
+ finish(new Error(`${basename(bin)} exceeded the media-output limit`));
2851
+ }
2852
+ });
2853
+ child.stderr?.on("data", (data) => {
2854
+ err = (err + data.toString()).slice(-12e3);
2855
+ });
2856
+ child.on("error", (error$1) => finish(error$1));
2857
+ child.on("close", (code) => finish(code === 0 ? void 0 : new Error(`${basename(bin)} exited ${code}: ${err.trim()}`)));
2858
+ });
2859
+ }
2860
+ async function probeMedia(path) {
2861
+ try {
2862
+ const raw = await run$1(await resolveFfprobe(), [
2863
+ "-v",
2864
+ "error",
2865
+ "-show_entries",
2866
+ "format=duration:stream=codec_type,duration,width,height",
2867
+ "-of",
2868
+ "json",
2869
+ path
2870
+ ], true);
2871
+ const data = JSON.parse(raw);
2872
+ const duration = Number(data.format?.duration);
2873
+ if (!Number.isFinite(duration) || duration <= 0) throw new Error("media has no finite positive duration");
2874
+ const video = data.streams?.find((x) => x.codec_type === "video"), audio = data.streams?.find((x) => x.codec_type === "audio");
2875
+ const streamDuration = (stream) => {
2876
+ const n = Number(stream?.duration);
2877
+ return Number.isFinite(n) && n > 0 ? n : duration;
2878
+ };
2879
+ return {
2880
+ duration,
2881
+ video: !!video,
2882
+ audio: !!audio,
2883
+ videoDuration: streamDuration(video),
2884
+ audioDuration: streamDuration(audio),
2885
+ width: video?.width ?? 0,
2886
+ height: video?.height ?? 0
2887
+ };
2888
+ } catch (error$1) {
2889
+ throw new Error(`could not probe ${path}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`);
2890
+ }
2891
+ }
2892
+ const imageInputOptions = [
2893
+ "-max_alloc",
2894
+ "268435456",
2895
+ "-protocol_whitelist",
2896
+ "file,pipe",
2897
+ "-format_whitelist",
2898
+ "image2,png_pipe,jpeg_pipe,webp_pipe"
2899
+ ];
2900
+ async function probeMotionImage(path) {
2901
+ if (statSync(path).size > 64 * 1024 * 1024) throw new Error("image exceeds the 64 MiB source-file limit");
2902
+ const raw = await run$1(await resolveFfprobe(), [
2903
+ "-v",
2904
+ "error",
2905
+ ...imageInputOptions,
2906
+ "-show_entries",
2907
+ "stream=codec_name,codec_type,width,height",
2908
+ "-of",
2909
+ "json",
2910
+ path
2911
+ ], true, 3e4);
2912
+ const data = JSON.parse(raw);
2913
+ const stream = data.streams?.[0];
2914
+ if (data.streams?.length !== 1 || stream?.codec_type !== "video" || ![
2915
+ "png",
2916
+ "mjpeg",
2917
+ "webp"
2918
+ ].includes(stream.codec_name ?? "")) throw new Error("asset must decode as a single PNG, JPEG or WebP image");
2919
+ const width = stream.width ?? 0, height = stream.height ?? 0;
2920
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 16384 || height > 16384 || width * height > 32e6) throw new Error("image dimensions must be positive, at most 16384px per side and at most 32 megapixels");
2921
+ await run$1(await resolveFfmpeg(), [
2922
+ "-v",
2923
+ "error",
2924
+ "-xerror",
2925
+ ...imageInputOptions,
2926
+ "-i",
2927
+ path,
2928
+ "-frames:v",
2929
+ "1",
2930
+ "-f",
2931
+ "null",
2932
+ "-"
2933
+ ], false, 3e4);
2934
+ return {
2935
+ width,
2936
+ height
2937
+ };
2938
+ }
2939
+ function cropError(layer, image) {
2940
+ const crop = layer.crop;
2941
+ if (crop && (crop.x + crop.width > image.width || crop.y + crop.height > image.height)) return `crop must stay inside the ${image.width}x${image.height} source image`;
2942
+ return void 0;
2943
+ }
2944
+ function motionMedia(comp) {
2945
+ const media = [];
2946
+ const visit = (layers, prefix, scene, parents) => {
2947
+ layers.forEach((layer, i) => {
2948
+ const path = `${prefix}[${i}]`;
2949
+ if (layer.type === "image" || layer.type === "video") media.push({
2950
+ layer,
2951
+ path,
2952
+ scene,
2953
+ parents
2954
+ });
2955
+ else if (layer.type === "group") visit(layer.children, `${path}.children`, scene, [...parents, layer]);
2956
+ });
2957
+ };
2958
+ comp.scenes.forEach((scene, i) => {
2959
+ if (scene.type === "motion") visit(scene.layers, `scenes[${i}].layers`, scene, []);
2960
+ });
2961
+ return media;
2962
+ }
2963
+ function motionImages(comp) {
2964
+ return motionMedia(comp).filter((item) => item.layer.type === "image");
2965
+ }
2966
+ /** Largest pixel stretch. Static matrix products are exact; animated extrema form
2967
+ * a conservative bound because each supported easing stays between its keyframes. */
2968
+ function mediaStretch(item, output, source) {
2969
+ const { layer, parents, scene } = item;
2970
+ const max = (node, property, fallback) => {
2971
+ const track = scene.motion !== "off" ? node.animations?.find((t) => t.property === property) : void 0;
2972
+ return track ? Math.max(...track.keyframes.map((f) => Number(f.value))) : Number(node[property] ?? fallback);
2973
+ };
2974
+ const chain = [...parents, layer];
2975
+ const animated$1 = scene.motion !== "off" && chain.some((node) => node.animations?.some((t) => [
2976
+ "scaleX",
2977
+ "scaleY",
2978
+ "rotation",
2979
+ "width",
2980
+ "height"
2981
+ ].includes(t.property)));
2982
+ let stretch = 1;
2983
+ if (animated$1) for (const node of chain) stretch *= Math.max(max(node, "scaleX", 1), max(node, "scaleY", 1));
2984
+ else {
2985
+ let a = 1, b = 0, c = 0, d = 1;
2986
+ for (const node of chain) {
2987
+ const angle = (node.rotation ?? 0) * Math.PI / 180, cos = Math.cos(angle), sin = Math.sin(angle), sx = node.scaleX ?? 1, sy = node.scaleY ?? 1;
2988
+ [a, b, c, d] = [
2989
+ (a * cos + c * sin) * sx,
2990
+ (b * cos + d * sin) * sx,
2991
+ (-a * sin + c * cos) * sy,
2992
+ (-b * sin + d * cos) * sy
2993
+ ];
2994
+ }
2995
+ const sum = a * a + b * b + c * c + d * d, determinant = a * d - b * c;
2996
+ stretch = Math.sqrt((sum + Math.sqrt(Math.max(0, sum * sum - 4 * determinant * determinant))) / 2);
2997
+ }
2998
+ const design = scene.designSize ?? {
2999
+ width: 1920,
3000
+ height: 1080
3001
+ };
3002
+ const fit = layer.fit === "cover" ? Math.max : Math.min;
3003
+ const factor = fit(max(layer, "width", layer.width) / source.width, max(layer, "height", layer.height) / source.height) * stretch * Math.min(output.width / design.width, output.height / design.height);
3004
+ return {
3005
+ factor,
3006
+ animated: animated$1
3007
+ };
3008
+ }
3009
+ function warnEnlargement(issues, path, source, factor, animated$1 = false) {
3010
+ if (factor <= 1.01 || !Number.isFinite(factor)) return;
3011
+ issues.push({
3012
+ severity: "warn",
3013
+ path,
3014
+ message: `Asset enlargement ${factor.toFixed(2)}x: ${source.width}x${source.height} source pixels ${animated$1 ? "may be enlarged under conservative animation bounds" : "are enlarged at the authored size"}. Capture/export a higher-resolution source (at least ${Math.ceil(source.width * factor)}x${Math.ceil(source.height * factor)} for this footprint), reduce the displayed size, or choose a tighter source with enough pixels. Encoding bitrate cannot restore missing detail.`
3015
+ });
3016
+ }
3017
+ /** Internal preparation seam: call only on a validated clone, never authored composition data. */
3018
+ async function prepareMotionImages(comp, compositionPath, assetsDir) {
3019
+ const base = dirname(resolve(compositionPath)), cache = new Map();
3020
+ const ffmpeg = await resolveFfmpeg();
3021
+ let count = 0;
3022
+ for (const { layer } of motionImages(comp)) {
3023
+ const source = resolve(base, layer.asset), key = JSON.stringify([realpathSync(source), layer.crop]);
3024
+ let asset = cache.get(key);
3025
+ if (!asset) {
3026
+ const info = await probeMotionImage(source), invalidCrop = cropError(layer, info);
3027
+ if (invalidCrop) throw new Error(invalidCrop);
3028
+ const name = `motion-image-${count++}.png`, crop = layer.crop;
3029
+ const filters = [crop ? `crop=w=${crop.width}:h=${crop.height}:x=${crop.x}:y=${crop.y}:exact=1` : "null", "format=rgba"];
3030
+ await run$1(ffmpeg, [
3031
+ "-y",
3032
+ "-v",
3033
+ "error",
3034
+ "-xerror",
3035
+ ...imageInputOptions,
3036
+ "-i",
3037
+ source,
3038
+ "-vf",
3039
+ filters.join(","),
3040
+ "-frames:v",
3041
+ "1",
3042
+ "-update",
3043
+ "1",
3044
+ join(assetsDir, name)
3045
+ ], false, 3e4);
3046
+ asset = `/assets/${name}`;
3047
+ cache.set(key, asset);
3048
+ }
3049
+ layer.asset = asset;
3050
+ delete layer.crop;
3051
+ }
3052
+ }
3053
+ async function validateLaunchAssets(value, compositionPath) {
3054
+ const base = dirname(resolve(compositionPath));
3055
+ const issues = validateLaunchComposition(value, base);
3056
+ if (issues.some((x) => x.severity === "error")) return issues;
3057
+ const comp = value;
3058
+ const probes = new Map();
3059
+ const inspect = async (asset, path, kind, trim, duration, loop = false) => {
3060
+ const full = resolve(base, asset);
3061
+ let pending = probes.get(full);
3062
+ if (!pending) {
3063
+ pending = probeMedia(full);
3064
+ probes.set(full, pending);
3065
+ }
3066
+ try {
3067
+ const got = await pending;
3068
+ if (!got[kind]) {
3069
+ issues.push({
3070
+ severity: "error",
3071
+ path,
3072
+ message: `asset has no ${kind} stream`
3073
+ });
3074
+ return;
3075
+ }
3076
+ const available = kind === "video" ? got.videoDuration : got.audioDuration;
3077
+ if (trim >= available || !loop && trim + duration > available + .001) issues.push({
3078
+ severity: "error",
3079
+ path,
3080
+ message: `needs ${loop ? `a trim before ${trim.toFixed(3)}s` : `${(trim + duration).toFixed(3)}s`} but ${kind} media is ${available.toFixed(3)}s`
3081
+ });
3082
+ return got;
3083
+ } catch (error$1) {
3084
+ issues.push({
3085
+ severity: "error",
3086
+ path,
3087
+ message: error$1 instanceof Error ? error$1.message : String(error$1)
3088
+ });
3089
+ }
3090
+ };
3091
+ for (const [i, scene] of comp.scenes.entries()) if (scene.type === "footage") {
3092
+ const info = await inspect(scene.asset, `scenes[${i}].asset`, "video", scene.trimStartS ?? 0, scene.durationS);
3093
+ if (info?.width && info.height) {
3094
+ const inset = (scene.frame?.inset ?? 86) * Math.min(comp.output.width / 1920, comp.output.height / 1080);
3095
+ const fit = scene.fit === "cover" ? Math.max : Math.min;
3096
+ warnEnlargement(issues, `scenes[${i}].asset`, info, fit((comp.output.width - 2 * inset) / info.width, (comp.output.height - 2 * inset) / info.height));
3097
+ }
3098
+ }
3099
+ for (const [i, track] of (comp.audio ?? []).entries()) await inspect(track.asset, `audio[${i}].asset`, "audio", track.trimStartS ?? 0, track.durationS ?? launchDurationS(comp) - launchAudioAtS(comp, track), !!track.loop);
3100
+ const imageProbes = new Map();
3101
+ for (const item of motionMedia(comp)) {
3102
+ const { layer, path } = item;
3103
+ if (layer.type === "video") {
3104
+ const info = await inspect(layer.asset, `${path}.asset`, "video", layer.trimStartS ?? 0, layer.durationS);
3105
+ if (info?.width && info.height) {
3106
+ const { factor, animated: animated$1 } = mediaStretch(item, comp.output, info);
3107
+ warnEnlargement(issues, `${path}.asset`, info, factor, animated$1);
3108
+ }
3109
+ continue;
3110
+ }
3111
+ const source = resolve(base, layer.asset);
3112
+ let pending = imageProbes.get(source);
3113
+ if (!pending) {
3114
+ pending = probeMotionImage(source);
3115
+ imageProbes.set(source, pending);
3116
+ }
3117
+ try {
3118
+ const image = await pending, invalid = cropError(layer, image);
3119
+ if (invalid) issues.push({
3120
+ severity: "error",
3121
+ path: `${path}.crop`,
3122
+ message: invalid
3123
+ });
3124
+ else {
3125
+ const source$1 = layer.crop ?? image;
3126
+ const { factor, animated: animated$1 } = mediaStretch(item, comp.output, source$1);
3127
+ warnEnlargement(issues, `${path}.asset`, source$1, factor, animated$1);
3128
+ }
3129
+ } catch (error$1) {
3130
+ issues.push({
3131
+ severity: "error",
3132
+ path: `${path}.asset`,
3133
+ message: `could not decode image: ${error$1 instanceof Error ? error$1.message : String(error$1)}`
3134
+ });
3135
+ }
3136
+ }
3137
+ return issues;
3138
+ }
3139
+ /** Internal preparation seam: lossless VP9 is decoded by the scene's explicit
3140
+ * HTMLVideoElement (slow) decoder. Color conversion and fitting happen once;
3141
+ * the codec adds no quantization before the final delivery encode. */
3142
+ async function prepareLaunchVideo(source, target, opts) {
3143
+ const { frame } = opts;
3144
+ const color = "flags=lanczos:out_range=tv:out_color_matrix=bt709";
3145
+ const scale = frame ? frame.fit === "cover" ? `scale=${frame.width}:${frame.height}:force_original_aspect_ratio=increase:${color},crop=${frame.width}:${frame.height}` : `scale=${frame.width}:${frame.height}:force_original_aspect_ratio=decrease:${color},pad=${frame.width}:${frame.height}:(ow-iw)/2:(oh-ih)/2:color=#0b1714` : `scale=trunc(iw/2)*2:trunc(ih/2)*2:${color}`;
3146
+ await run$1(await resolveFfmpeg(), [
3147
+ "-y",
3148
+ "-loglevel",
3149
+ "error",
3150
+ "-ss",
3151
+ String(opts.trimStartS),
3152
+ "-i",
3153
+ source,
3154
+ "-t",
3155
+ String(opts.durationS + 1 / opts.fps),
3156
+ "-map",
3157
+ "0:v:0",
3158
+ "-vf",
3159
+ `${scale},setsar=1,format=yuv420p,setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=bt709,tpad=stop_mode=clone:stop_duration=${1 / opts.fps}`,
3160
+ "-c:v",
3161
+ "libvpx-vp9",
3162
+ "-lossless",
3163
+ "1",
3164
+ "-b:v",
3165
+ "0",
3166
+ "-cpu-used",
3167
+ "4",
3168
+ "-row-mt",
3169
+ "1",
3170
+ "-g",
3171
+ String(Math.ceil(opts.fps)),
3172
+ "-pix_fmt",
3173
+ "yuv420p",
3174
+ "-r",
3175
+ String(opts.fps),
3176
+ "-an",
3177
+ target
3178
+ ], false, 6e5);
3179
+ }
3180
+ /** Trim each nested video independently; authored scene timing stays unchanged. */
3181
+ async function prepareMotionVideos(comp, compositionPath, assetsDir) {
3182
+ let count = 0;
3183
+ for (const { layer } of motionMedia(comp)) {
3184
+ if (layer.type !== "video") continue;
3185
+ const name = `motion-video-${count++}.webm`;
3186
+ await prepareLaunchVideo(resolve(dirname(resolve(compositionPath)), layer.asset), join(assetsDir, name), {
3187
+ trimStartS: layer.trimStartS ?? 0,
3188
+ durationS: layer.durationS,
3189
+ fps: comp.output.fps
3190
+ });
3191
+ layer.asset = `/assets/${name}`;
3192
+ layer.trimStartS = 0;
3193
+ }
3194
+ }
3195
+ function hostNodeModules$1() {
3196
+ let dir = PKG_ROOT$1;
3197
+ for (;;) {
3198
+ const p = join(dir, "node_modules");
3199
+ if (existsSync(p)) return p;
3200
+ const up = dirname(dir);
3201
+ if (up === dir) return null;
3202
+ dir = up;
3203
+ }
3204
+ }
3205
+ function depsRoot$1() {
3206
+ try {
3207
+ const parts = realpathSync(createRequire(import.meta.url).resolve("@revideo/core")).split(sep);
3208
+ const i = parts.indexOf("node_modules");
3209
+ return i < 0 ? null : parts.slice(0, i + 1).join(sep);
3210
+ } catch {
3211
+ return null;
3212
+ }
3213
+ }
3214
+ async function copyWritable$1(from, to) {
3215
+ await mkdir(to, { recursive: true });
3216
+ for (const e of await readdir(from, { withFileTypes: true })) {
3217
+ const a = join(from, e.name), b = join(to, e.name);
3218
+ if (e.isDirectory()) await copyWritable$1(a, b);
3219
+ else if (e.isFile()) await writeFile(b, await readFile(a));
3220
+ }
3221
+ }
3222
+ async function cleanup(dir) {
3223
+ await unlink(join(dir, "node_modules")).catch(() => {});
3224
+ if (process.env.OPEN_TAKE_KEEP_SCRATCH) process.stderr.write(`launch render scratch kept: ${dir}\n`);
3225
+ else await rm(dir, {
3226
+ recursive: true,
3227
+ force: true
3228
+ });
3229
+ }
3230
+ async function prepare(comp, compositionPath, draft) {
3231
+ const dir = await mkdtemp(join(tmpdir(), "open-take-launch-"));
3232
+ const base = dirname(resolve(compositionPath));
3233
+ try {
3234
+ await copyWritable$1(join(PKG_ROOT$1, "src"), join(dir, "src"));
3235
+ await mkdir(join(dir, "public", "assets"), { recursive: true });
3236
+ const nm = hostNodeModules$1();
3237
+ if (!nm) throw new Error("launch render: could not locate node_modules");
3238
+ await symlink(nm, join(dir, "node_modules"), "junction");
3239
+ const draftScale = Math.min(1, 960 / Math.max(comp.output.width, comp.output.height));
3240
+ const even = (value) => Math.max(2, Math.round(value / 2) * 2);
3241
+ const output = draft ? {
3242
+ width: even(comp.output.width * draftScale),
3243
+ height: even(comp.output.height * draftScale),
3244
+ fps: Math.min(30, comp.output.fps)
3245
+ } : comp.output;
3246
+ const rendered = structuredClone(comp);
3247
+ rendered.output = output;
3248
+ let n = 0;
3249
+ for (const scene of rendered.scenes) if (scene.type === "footage") {
3250
+ const name = `footage-${n++}.webm`;
3251
+ const scale = Math.min(output.width / 1920, output.height / 1080);
3252
+ const inset = (scene.frame?.inset ?? 86) * scale;
3253
+ const width = even(output.width - inset * 2), height = even(output.height - inset * 2);
3254
+ const fit = scene.fit ?? "contain";
3255
+ await prepareLaunchVideo(resolve(base, scene.asset), join(dir, "public", "assets", name), {
3256
+ trimStartS: scene.trimStartS ?? 0,
3257
+ durationS: scene.durationS,
3258
+ fps: output.fps,
3259
+ frame: {
3260
+ width,
3261
+ height,
3262
+ fit
3263
+ }
3264
+ });
3265
+ scene.asset = `/assets/${name}`;
3266
+ scene.trimStartS = 0;
3267
+ }
3268
+ await prepareMotionImages(rendered, compositionPath, join(dir, "public", "assets"));
3269
+ await prepareMotionVideos(rendered, compositionPath, join(dir, "public", "assets"));
3270
+ await writeFile(join(dir, "src", "scene", ".launch-composition.json"), JSON.stringify(rendered, null, 2));
3271
+ return {
3272
+ dir,
3273
+ rendered
3274
+ };
3275
+ } catch (error$1) {
3276
+ await cleanup(dir);
3277
+ throw error$1;
3278
+ }
3279
+ }
3280
+ function fadeFilter(track, index, at, total, duck, loopSamples) {
3281
+ const trim = track.trimStartS ?? 0, duration = track.durationS ?? Math.max(0, total - at);
3282
+ const parts = [`[${index + 1}:a]aresample=48000,atrim=start=${trim}:duration=${duration}`, "asetpts=PTS-STARTPTS"];
3283
+ if (loopSamples !== void 0) parts.push(`aloop=loop=-1:size=${loopSamples}`, `atrim=duration=${duration}`, "asetpts=PTS-STARTPTS");
3284
+ let volume = String(track.gain ?? 1);
3285
+ if (track.kind === "music" && duck.length) {
3286
+ const expr = duck.filter(([a, b]) => b > at && a < at + duration).map(([a, b]) => `between(t,${Math.max(0, a - at)},${Math.min(duration, b - at)})`).join("+");
3287
+ if (expr) volume = `(${volume})*if(${expr},0.34,1)`;
3288
+ }
3289
+ parts.push(`volume='${volume}':eval=frame`);
3290
+ if ((track.fadeInS ?? 0) > 0) parts.push(`afade=t=in:st=0:d=${track.fadeInS}`);
3291
+ if ((track.fadeOutS ?? 0) > 0) parts.push(`afade=t=out:st=${Math.max(0, duration - (track.fadeOutS ?? 0))}:d=${track.fadeOutS}`);
3292
+ parts.push(`adelay=${Math.round(at * 48e3)}S:all=1`, `apad=whole_dur=${total}`);
3293
+ return `${parts.join(",")}[a${index}]`;
3294
+ }
3295
+ async function deliverLaunchMedia(raw, target, comp, compositionPath) {
3296
+ const ffmpeg = await resolveFfmpeg(), base = dirname(resolve(compositionPath)), total = launchDurationS(comp), tracks = comp.audio ?? [];
3297
+ const rawMedia = await probeMedia(raw);
3298
+ if (!rawMedia.video) throw new Error("launch render: renderer output has no video stream");
3299
+ const frameDuration = 1 / comp.output.fps;
3300
+ if (Math.abs(rawMedia.videoDuration - total) > frameDuration + .001) throw new Error(`launch render: renderer produced ${rawMedia.videoDuration.toFixed(6)}s of video for an authored ${total.toFixed(6)}s film; only one output frame (${frameDuration.toFixed(6)}s) of rounding is allowed. Re-render the complete composition before delivery.`);
3301
+ const videoFilter = `tpad=stop_mode=clone:stop_duration=${frameDuration},scale=in_color_matrix=bt601:out_color_matrix=bt709,format=yuv420p,setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=bt709`;
3302
+ const args = [
3303
+ "-y",
3304
+ "-loglevel",
3305
+ "error",
3306
+ "-i",
3307
+ raw
3308
+ ];
3309
+ const loopSamples = [];
3310
+ for (const track of tracks) {
3311
+ const source = resolve(base, track.asset);
3312
+ const duration = track.durationS ?? total - launchAudioAtS(comp, track);
3313
+ args.push("-t", String((track.trimStartS ?? 0) + duration), "-i", source);
3314
+ if (track.loop) {
3315
+ const media = await probeMedia(source);
3316
+ loopSamples.push(Math.max(1, Math.round(Math.min(duration, media.audioDuration - (track.trimStartS ?? 0)) * 48e3)));
3317
+ } else loopSamples.push(void 0);
3318
+ }
3319
+ if (!tracks.length) {
3320
+ args.push("-vf", videoFilter, "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", "-movflags", "+faststart", "-an", "-t", String(total), target);
3321
+ await run$1(ffmpeg, args);
3322
+ return;
3323
+ }
3324
+ const duck = tracks.filter((x) => x.kind === "narration" && x.duckMusic).map((x) => {
3325
+ const at = launchAudioAtS(comp, x);
3326
+ return [at, at + (x.durationS ?? Math.max(0, total - at))];
3327
+ });
3328
+ const filters = tracks.map((x, i) => fadeFilter(x, i, launchAudioAtS(comp, x), total, duck, loopSamples[i]));
3329
+ filters.push(`${tracks.map((_, i) => `[a${i}]`).join("")}amix=inputs=${tracks.length}:duration=longest:normalize=0,atrim=duration=${total}[mix]`);
3330
+ args.push("-filter_complex", filters.join(";"), "-map", "0:v:0", "-map", "[mix]", "-vf", videoFilter, "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", "-t", String(total), target);
3331
+ await run$1(ffmpeg, args);
3332
+ }
3333
+ /** Stage beside the destination so failed encoding never replaces a good master. */
3334
+ async function publishLaunchMedia(raw, target, comp, compositionPath) {
3335
+ const stageDir = await mkdtemp(join(dirname(target), `.open-take-launch-${basename(target, extname(target))}-`));
3336
+ try {
3337
+ const staged = join(stageDir, "delivery.mp4");
3338
+ await deliverLaunchMedia(raw, staged, comp, compositionPath);
3339
+ await rename(staged, target);
3340
+ } finally {
3341
+ await rm(stageDir, {
3342
+ recursive: true,
3343
+ force: true
3344
+ });
3345
+ }
3346
+ }
3347
+ /** Internal filesystem preflight, shared by rendering and focused regression tests. */
3348
+ function assertLaunchOutputSafe(comp, compositionPath, outPath) {
3349
+ const out = resolve(outPath), base = dirname(resolve(compositionPath));
3350
+ const canonical = (path) => {
3351
+ if (existsSync(path)) return realpathSync(path);
3352
+ const parent = dirname(path);
3353
+ return parent === path ? path : join(canonical(parent), basename(path));
3354
+ };
3355
+ const forbidden = [
3356
+ resolve(compositionPath),
3357
+ ...comp.scenes.filter((x) => x.type === "footage").map((x) => resolve(base, x.asset)),
3358
+ ...(comp.audio ?? []).map((x) => resolve(base, x.asset)),
3359
+ ...comp.scenes.flatMap((scene) => scene.type === "motion" ? walkMotionLayers(scene.layers).filter((layer) => layer.type === "image" || layer.type === "video").map((layer) => resolve(base, layer.asset)) : [])
3360
+ ];
3361
+ const target = canonical(out), outStat = existsSync(out) ? statSync(out) : void 0;
3362
+ for (const source of forbidden) {
3363
+ const sourceStat = existsSync(source) ? statSync(source) : void 0;
3364
+ if (canonical(source) === target || outStat && sourceStat && outStat.dev === sourceStat.dev && outStat.ino === sourceStat.ino) throw new Error("launch render: output must not overwrite the JSON or a required asset");
3365
+ }
3366
+ }
3367
+ async function renderLaunch(opts) {
3368
+ return withRenderLock(() => renderExclusive(opts));
3369
+ }
3370
+ async function renderExclusive(opts) {
3371
+ if (!opts.chromePath) throw new Error("renderLaunch: chromePath is required");
3372
+ const issues = await validateLaunchAssets(opts.composition, opts.compositionPath);
3373
+ const errors = issues.filter((x) => x.severity === "error");
3374
+ if (errors.length) throw new Error(`launch composition has ${errors.length} error(s):\n${formatLaunchIssues(errors)}`);
3375
+ const out = resolve(opts.outPath);
3376
+ await mkdir(dirname(out), { recursive: true });
3377
+ assertLaunchOutputSafe(opts.composition, opts.compositionPath, out);
3378
+ await repairBundledMediaPermissions();
3379
+ const { dir, rendered } = await prepare(opts.composition, opts.compositionPath, !!opts.draft);
3380
+ const deps = depsRoot$1();
3381
+ const prev = process.cwd();
3382
+ try {
3383
+ process.chdir(dir);
3384
+ const produced = await renderVideo({
3385
+ projectFile: "/src/scene/launch-project.ts",
3386
+ settings: {
3387
+ outFile: "launch.mov",
3388
+ outDir: "out-render",
3389
+ workers: 1,
3390
+ projectSettings: {
3391
+ range: [0, Math.max(0, (Math.ceil(launchDurationS(rendered) * rendered.output.fps - 1e-9) - 1) / rendered.output.fps)],
3392
+ exporter: {
3393
+ name: "@revideo/core/ffmpeg",
3394
+ options: { format: "proRes" }
3395
+ }
3396
+ },
3397
+ logProgress: opts.logProgress ?? false,
3398
+ progressCallback: (_w, p) => opts.onProgress?.(p),
3399
+ viteConfig: { server: { fs: { allow: [dir, ...deps ? [deps] : []] } } },
3400
+ puppeteer: {
3401
+ args: [
3402
+ "--no-sandbox",
3403
+ "--disable-setuid-sandbox",
3404
+ "--password-store=basic",
3405
+ "--use-mock-keychain"
3406
+ ],
3407
+ executablePath: opts.chromePath
3408
+ }
3409
+ }
3410
+ });
3411
+ process.chdir(prev);
3412
+ await publishLaunchMedia(resolve(dir, produced), out, rendered, opts.compositionPath);
3413
+ return {
3414
+ mp4Path: out,
3415
+ durationS: launchDurationS(rendered),
3416
+ warnings: issues.filter((x) => x.severity === "warn")
3417
+ };
3418
+ } finally {
3419
+ process.chdir(prev);
3420
+ await cleanup(dir);
3421
+ }
3422
+ }
3423
+
3424
+ //#endregion
3425
+ //#region src/launch-starter.ts
3426
+ /** A recording-led starting point. Scene lengths and styling remain editable.
3427
+ * Output fps follows the recording so the footage keeps every captured frame;
3428
+ * the default matches `make`'s 60. */
3429
+ function launchStarter(videoAsset = "assets/capture.mp4", clipDurationS = 12, fps = 60) {
3430
+ if (!Number.isFinite(clipDurationS) || clipDurationS <= 0) throw new Error("launch starter: clip duration must be a finite positive number");
3431
+ if (!Number.isInteger(fps) || fps < 1 || fps > 120) throw new Error("launch starter: fps must be an integer between 1 and 120");
3432
+ return {
3433
+ version: 1,
3434
+ output: {
3435
+ width: 1920,
3436
+ height: 1080,
3437
+ fps
3438
+ },
3439
+ theme: {
3440
+ canvas: "#F5F2EA",
3441
+ ink: "#172E28",
3442
+ surface: "#DCE5D8",
3443
+ accent: "#214F41",
3444
+ dark: "#10231E",
3445
+ fontFamily: "Avenir Next, Avenir, Helvetica Neue, Noto Sans, sans-serif"
3446
+ },
3447
+ scenes: [
3448
+ {
3449
+ id: "opening",
3450
+ type: "title",
3451
+ durationS: 2,
3452
+ lines: ["Your product. In action."],
3453
+ motion: "off",
3454
+ transition: { type: "cut" }
3455
+ },
3456
+ {
3457
+ id: "product",
3458
+ type: "footage",
3459
+ durationS: clipDurationS,
3460
+ asset: videoAsset,
3461
+ trimStartS: 0,
3462
+ fit: "contain",
3463
+ frame: {
3464
+ inset: 64,
3465
+ radius: 20
3466
+ },
3467
+ transition: { type: "cut" }
3468
+ },
3469
+ {
3470
+ id: "end",
3471
+ type: "end-card",
3472
+ durationS: 2,
3473
+ headline: "See what you can do.",
3474
+ brand: "Your product",
3475
+ cta: "Explore your product",
3476
+ motion: "off",
3477
+ transition: { type: "cut" }
3478
+ }
3479
+ ]
3480
+ };
3481
+ }
3482
+
3483
+ //#endregion
3484
+ //#region src/launch-template.ts
3485
+ function launchTemplate(videoAsset = "assets/capture.mp4", clipDurationS = 12) {
3486
+ const firstDuration = Math.min(5, Math.max(.5, clipDurationS / 2));
3487
+ const secondStart = firstDuration;
3488
+ const secondDuration = Math.min(6, Math.max(.5, clipDurationS - secondStart));
3489
+ return {
3490
+ version: 1,
3491
+ output: {
3492
+ width: 1920,
3493
+ height: 1080,
3494
+ fps: 30
3495
+ },
3496
+ theme: {
3497
+ canvas: "#F5F2EA",
3498
+ ink: "#172E28",
3499
+ surface: "#DCE5D8",
3500
+ accent: "#214F41",
3501
+ dark: "#10231E",
3502
+ fontFamily: "Avenir Next, Avenir, Helvetica Neue, Noto Sans, sans-serif"
3503
+ },
3504
+ scenes: [
3505
+ {
3506
+ id: "opening",
3507
+ type: "title",
3508
+ durationS: 3,
3509
+ lines: ["Real clicks.", "Ready for launch."],
3510
+ brand: "Open Take",
3511
+ staggerS: .38,
3512
+ transition: {
3513
+ type: "fade",
3514
+ durationS: .45
3515
+ }
3516
+ },
3517
+ {
3518
+ id: "capture",
3519
+ type: "footage",
3520
+ durationS: firstDuration,
3521
+ asset: videoAsset,
3522
+ trimStartS: 0,
3523
+ fit: "contain",
3524
+ frame: {
3525
+ inset: 92,
3526
+ radius: 28
3527
+ },
3528
+ caption: "Capture the real thing.",
3529
+ transition: {
3530
+ type: "slide",
3531
+ durationS: Math.min(.5, firstDuration / 3)
3532
+ }
3533
+ },
3534
+ {
3535
+ id: "compose",
3536
+ type: "ui-morph",
3537
+ states: [
3538
+ {
3539
+ icon: "record",
3540
+ label: "Record",
3541
+ prompt: "",
3542
+ transitionS: .55,
3543
+ typeDelayS: .54,
3544
+ typeS: .01,
3545
+ holdS: 0
3546
+ },
3547
+ {
3548
+ icon: "record",
3549
+ label: "Record",
3550
+ prompt: "Record the real app.",
3551
+ transitionS: .55,
3552
+ typeDelayS: .18,
3553
+ typeS: .7,
3554
+ holdS: .32,
3555
+ panelWidth: 1100,
3556
+ panelHeight: 218
3557
+ },
3558
+ {
3559
+ icon: "style",
3560
+ label: "Style",
3561
+ prompt: "Make it cinematic.",
3562
+ transitionS: .6,
3563
+ typeDelayS: .6,
3564
+ typeS: .7,
3565
+ holdS: .5,
3566
+ panelWidth: 1040,
3567
+ panelHeight: 218
3568
+ },
3569
+ {
3570
+ icon: "refine",
3571
+ label: "Refine",
3572
+ prompt: "Tighten the focus.",
3573
+ transitionS: .6,
3574
+ typeDelayS: .6,
3575
+ typeS: .7,
3576
+ holdS: 1.15,
3577
+ panelWidth: 1060,
3578
+ panelHeight: 218
3579
+ }
3580
+ ],
3581
+ eyebrow: "Make it yours.",
3582
+ panel: {
3583
+ width: 1100,
3584
+ compactHeight: 112,
3585
+ expandedHeight: 218,
3586
+ radius: 34
3587
+ },
3588
+ transition: {
3589
+ type: "fade",
3590
+ durationS: .35
3591
+ }
3592
+ },
3593
+ {
3594
+ id: "editable",
3595
+ type: "footage",
3596
+ durationS: secondDuration,
3597
+ asset: videoAsset,
3598
+ trimStartS: secondStart,
3599
+ fit: "contain",
3600
+ background: "dark",
3601
+ frame: {
3602
+ inset: 84,
3603
+ radius: 28
3604
+ },
3605
+ caption: "Keep every detail editable.",
3606
+ transition: {
3607
+ type: "slide",
3608
+ durationS: Math.min(.5, secondDuration / 3)
3609
+ }
3610
+ },
3611
+ {
3612
+ id: "payoff",
3613
+ type: "title",
3614
+ durationS: 3,
3615
+ background: "dark",
3616
+ lines: [
3617
+ "Record.",
3618
+ "Compose.",
3619
+ "Refine."
3620
+ ],
3621
+ staggerS: .42,
3622
+ transition: {
3623
+ type: "fade",
3624
+ durationS: .4
3625
+ }
3626
+ },
3627
+ {
3628
+ id: "end",
3629
+ type: "end-card",
3630
+ durationS: 3,
3631
+ headline: "Your next release. In motion.",
3632
+ brand: "Open Take",
3633
+ cta: "npm create open-take@latest",
3634
+ transition: {
3635
+ type: "fade",
3636
+ durationS: .45
3637
+ }
3638
+ }
3639
+ ]
3640
+ };
3641
+ }
3642
+
3643
+ //#endregion
3644
+ //#region src/motion-recipes.ts
3645
+ const record = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
3646
+ const finite = (v) => typeof v === "number" && Number.isFinite(v);
3647
+ const error = (path, message) => ({
3648
+ severity: "error",
3649
+ path,
3650
+ message
3651
+ });
3652
+ function parseRecipe(raw, path, issues) {
3653
+ const start = issues.length;
3654
+ const add = (p, message) => issues.push(error(p, message));
3655
+ const fields$1 = (obj, keys, p) => {
3656
+ for (const key of Object.keys(obj)) if (!keys.includes(key)) add(`${p}.${key}`, "unsupported recipe field");
3657
+ };
3658
+ const text = (v, p, max) => {
3659
+ if (typeof v !== "string" || !v.trim() || motionGraphemes(v).length > max) add(p, `must be non-empty copy of at most ${max} graphemes; shorter copy may be required to fit the chosen layout`);
3660
+ };
3661
+ const image = (v, p) => {
3662
+ if (!record(v)) {
3663
+ add(p, "must be an image object with a local asset path");
3664
+ return;
3665
+ }
3666
+ fields$1(v, ["asset", "crop"], p);
3667
+ if (typeof v.asset !== "string" || !v.asset.trim() || v.asset.length > 4096 || v.asset.includes("\0") || !/\.(png|jpe?g|webp)$/i.test(v.asset) || /^[a-z][a-z\d+.-]*:/i.test(v.asset) && !/^[a-z]:[\\/]/i.test(v.asset)) add(`${p}.asset`, "must be a local PNG/JPEG/WebP path; use the asset checker to verify the actual file");
3668
+ if (v.crop !== void 0) if (!record(v.crop)) add(`${p}.crop`, "must be an object");
3669
+ else {
3670
+ fields$1(v.crop, [
3671
+ "x",
3672
+ "y",
3673
+ "width",
3674
+ "height"
3675
+ ], `${p}.crop`);
3676
+ for (const key of [
3677
+ "x",
3678
+ "y",
3679
+ "width",
3680
+ "height"
3681
+ ]) if (!finite(v.crop[key]) || !Number.isInteger(v.crop[key]) || v.crop[key] < (key === "x" || key === "y" ? 0 : 1) || v.crop[key] > 32768) add(`${p}.crop.${key}`, "must be an integer source-pixel value in the supported range");
3682
+ }
3683
+ };
3684
+ const common = [
3685
+ "id",
3686
+ "recipe",
3687
+ "title",
3688
+ "style",
3689
+ "durationS",
3690
+ "motion",
3691
+ "transition"
3692
+ ];
3693
+ if (typeof raw.recipe !== "string" || ![
3694
+ "focus",
3695
+ "compare",
3696
+ "steps"
3697
+ ].includes(raw.recipe)) {
3698
+ add(`${path}.recipe`, "must be focus, compare, or steps");
3699
+ return;
3700
+ }
3701
+ fields$1(raw, [...common, ...raw.recipe === "focus" ? ["image", "body"] : raw.recipe === "compare" ? [
3702
+ "before",
3703
+ "after",
3704
+ "body"
3705
+ ] : ["steps"]], path);
3706
+ text(raw.id, `${path}.id`, 200);
3707
+ text(raw.title, `${path}.title`, 160);
3708
+ if (raw.style !== void 0 && raw.style !== "editorial" && raw.style !== "product" && raw.style !== "technical") add(`${path}.style`, "must be editorial, product, or technical");
3709
+ if (raw.durationS !== void 0 && (!finite(raw.durationS) || raw.durationS <= 0 || raw.durationS > 86400)) add(`${path}.durationS`, "must be finite, positive and no more than 86400s");
3710
+ if (raw.motion !== void 0 && raw.motion !== "on" && raw.motion !== "off") add(`${path}.motion`, "must be on or off");
3711
+ if (raw.transition !== void 0) if (!record(raw.transition)) add(`${path}.transition`, "must be an object");
3712
+ else {
3713
+ fields$1(raw.transition, ["type", "durationS"], `${path}.transition`);
3714
+ if (typeof raw.transition.type !== "string" || ![
3715
+ "cut",
3716
+ "fade",
3717
+ "slide"
3718
+ ].includes(raw.transition.type)) add(`${path}.transition.type`, "must be cut, fade, or slide");
3719
+ if (raw.transition.durationS !== void 0 && (!finite(raw.transition.durationS) || raw.transition.durationS <= 0)) add(`${path}.transition.durationS`, "must be finite and positive");
3720
+ }
3721
+ if (raw.recipe === "focus") image(raw.image, `${path}.image`);
3722
+ if (raw.recipe === "focus" || raw.recipe === "compare") {
3723
+ if (raw.body !== void 0) text(raw.body, `${path}.body`, 360);
3724
+ }
3725
+ if (raw.recipe === "compare") for (const side of ["before", "after"]) {
3726
+ const item = raw[side];
3727
+ if (!record(item)) add(`${path}.${side}`, "must contain a label and image");
3728
+ else {
3729
+ fields$1(item, ["label", "image"], `${path}.${side}`);
3730
+ text(item.label, `${path}.${side}.label`, 80);
3731
+ image(item.image, `${path}.${side}.image`);
3732
+ }
3733
+ }
3734
+ if (raw.recipe === "steps") if (!Array.isArray(raw.steps) || raw.steps.length < 2 || raw.steps.length > 5) add(`${path}.steps`, "must contain 2 to 5 steps");
3735
+ else raw.steps.forEach((step, i) => {
3736
+ const p = `${path}.steps[${i}]`;
3737
+ if (!record(step)) {
3738
+ add(p, "must contain a label and optional body");
3739
+ return;
3740
+ }
3741
+ fields$1(step, ["label", "body"], p);
3742
+ text(step.label, `${p}.label`, 80);
3743
+ if (step.body !== void 0) text(step.body, `${p}.body`, 200);
3744
+ });
3745
+ return issues.length === start ? raw : void 0;
3746
+ }
3747
+ function buildRecipe(recipe, path, output, theme, issues) {
3748
+ const W = output.width, H = output.height, S = Math.min(W, H), style = recipe.style, portrait = H > W || H === W && (recipe.recipe === "focus" || recipe.recipe === "steps" && recipe.steps.length <= 3), margin = S * (style === "editorial" ? .085 : style === "product" ? .05 : style === "technical" ? .055 : .07), gap = S * (style === "editorial" ? .055 : style === "product" ? .032 : style === "technical" ? .028 : .045), pad = S * (style === "editorial" ? .01 : style === "product" ? .007 : style === "technical" ? .009 : .012);
3749
+ const innerW = W - 2 * margin, innerH = H - 2 * margin, left = -W / 2 + margin, top = -H / 2 + margin;
3750
+ const fonts = {
3751
+ title: Math.min(512, Math.max(24, S * (style === "editorial" ? .072 : style === "product" ? .056 : style === "technical" ? .052 : .06))),
3752
+ label: Math.min(512, Math.max(14, S * (style === "editorial" ? .034 : style === "product" ? .038 : style === "technical" ? .031 : .037))),
3753
+ body: Math.min(512, Math.max(14, S * (style === "editorial" ? .027 : style === "product" ? .029 : style === "technical" ? .025 : .03))),
3754
+ number: Math.min(512, Math.max(14, S * (style === "editorial" ? .026 : style === "product" ? .03 : style === "technical" ? .024 : .03)))
3755
+ };
3756
+ const layers = [], texts = [];
3757
+ let latestEntrance = 0;
3758
+ const text = (id, copy, box, role, sourcePath, fill = theme.ink, padding = pad) => {
3759
+ const size = fonts[role], width = box.width - padding * 2, height = box.height - padding * 2, lineHeight = size * 1.28;
3760
+ if (width <= 0 || height <= 0 || estimateMotionTextLines(copy, width, size) * lineHeight > height + .001) issues.push(error(sourcePath, `copy does not fit the ${recipe.recipe} ${W === H ? "square" : portrait ? "portrait" : "landscape"} ${role} region; shorten it or use a custom motion scene with a larger text box`));
3761
+ texts.push(copy);
3762
+ return {
3763
+ id,
3764
+ type: "text",
3765
+ text: copy,
3766
+ x: box.x,
3767
+ y: box.y,
3768
+ width: Math.max(.001, width),
3769
+ height: Math.max(.001, height),
3770
+ fontSize: size,
3771
+ lineHeight,
3772
+ fontFamily: theme.fontFamily,
3773
+ fontWeight: role === "title" ? style === "product" ? 700 : style === "technical" ? 600 : 650 : role === "label" ? style === "technical" ? 550 : 600 : style === "editorial" ? 400 : 450,
3774
+ fill,
3775
+ align: "left"
3776
+ };
3777
+ };
3778
+ const group = (id, children, delay) => {
3779
+ const animated$1 = recipe.motion !== "off" && id !== "heading" && id !== "message";
3780
+ const entranceS = style === "editorial" ? .68 : style === "product" ? .62 : style === "technical" ? .42 : .55, finish = delay + entranceS;
3781
+ if (animated$1) latestEntrance = Math.max(latestEntrance, finish);
3782
+ const keyframes = (a, b) => [
3783
+ {
3784
+ atS: 0,
3785
+ value: a
3786
+ },
3787
+ ...delay > 0 ? [{
3788
+ atS: delay,
3789
+ value: a
3790
+ }] : [],
3791
+ {
3792
+ atS: finish,
3793
+ value: b,
3794
+ easing: "ease-out"
3795
+ }
3796
+ ];
3797
+ return {
3798
+ id,
3799
+ type: "group",
3800
+ children,
3801
+ ...!animated$1 ? {} : { animations: [
3802
+ {
3803
+ property: "opacity",
3804
+ keyframes: keyframes(0, 1)
3805
+ },
3806
+ ...style === "technical" ? [{
3807
+ property: "x",
3808
+ keyframes: keyframes(-S * .018, 0)
3809
+ }] : [{
3810
+ property: "y",
3811
+ keyframes: keyframes(S * (style === "editorial" ? .014 : style === "product" ? .018 : .024), 0)
3812
+ }],
3813
+ ...style === "product" ? [{
3814
+ property: "scaleX",
3815
+ keyframes: keyframes(.965, 1)
3816
+ }, {
3817
+ property: "scaleY",
3818
+ keyframes: keyframes(.965, 1)
3819
+ }] : []
3820
+ ] }
3821
+ };
3822
+ };
3823
+ const rule = (id, points, delay = .08) => {
3824
+ const finish = delay + (style === "technical" ? .34 : .52), animated$1 = recipe.motion !== "off";
3825
+ if (animated$1) latestEntrance = Math.max(latestEntrance, finish);
3826
+ return {
3827
+ id,
3828
+ type: "line",
3829
+ points,
3830
+ stroke: theme.accent,
3831
+ strokeWidth: Math.max(1, S * (style === "technical" ? .0015 : .001)),
3832
+ end: 1,
3833
+ ...animated$1 ? { animations: [{
3834
+ property: "end",
3835
+ keyframes: [
3836
+ {
3837
+ atS: 0,
3838
+ value: 0
3839
+ },
3840
+ ...delay > 0 ? [{
3841
+ atS: delay,
3842
+ value: 0
3843
+ }] : [],
3844
+ {
3845
+ atS: finish,
3846
+ value: 1,
3847
+ easing: "ease-out"
3848
+ }
3849
+ ]
3850
+ }] } : {}
3851
+ };
3852
+ };
3853
+ const picturePad = style === "editorial" ? S * .022 : pad;
3854
+ const picture = (id, image, box) => {
3855
+ const radius = S * (style === "editorial" ? 0 : style === "product" ? .026 : style === "technical" ? .003 : .016), imageRadius = S * (style === "editorial" ? 0 : style === "product" ? .021 : style === "technical" ? .002 : .008);
3856
+ return [{
3857
+ id: `${id}-surface`,
3858
+ type: "rect",
3859
+ ...box,
3860
+ fill: theme.surface,
3861
+ radius,
3862
+ ...style === "product" ? { shadow: {
3863
+ color: "#00000024",
3864
+ blur: Math.min(256, S * .032),
3865
+ offsetY: Math.min(512, S * .011)
3866
+ } } : style === "technical" ? {
3867
+ stroke: theme.accent,
3868
+ strokeWidth: Math.max(1, S * .0015)
3869
+ } : {}
3870
+ }, {
3871
+ id,
3872
+ type: "image",
3873
+ ...box,
3874
+ width: box.width - 2 * picturePad,
3875
+ height: box.height - 2 * picturePad,
3876
+ asset: image.asset,
3877
+ ...image.crop ? { crop: { ...image.crop } } : {},
3878
+ fit: "contain",
3879
+ radius: imageRadius
3880
+ }];
3881
+ };
3882
+ const fittedFocusBox = (image, box) => {
3883
+ if (!style || !image.crop) return box;
3884
+ const mediaAspect = image.crop.width / image.crop.height, availableWidth = Math.max(.001, box.width - 2 * picturePad), availableHeight = Math.max(.001, box.height - 2 * picturePad);
3885
+ if (availableWidth / availableHeight > mediaAspect) {
3886
+ const innerWidth = availableHeight * mediaAspect;
3887
+ return {
3888
+ ...box,
3889
+ width: innerWidth + 2 * picturePad,
3890
+ height: availableHeight + 2 * picturePad
3891
+ };
3892
+ }
3893
+ const innerHeight = availableWidth / mediaAspect;
3894
+ return {
3895
+ ...box,
3896
+ width: availableWidth + 2 * picturePad,
3897
+ height: innerHeight + 2 * picturePad
3898
+ };
3899
+ };
3900
+ const stepSurface = (id, box) => {
3901
+ if (style !== "product" && style !== "technical") return void 0;
3902
+ return {
3903
+ id: `${id}-surface`,
3904
+ type: "rect",
3905
+ ...box,
3906
+ fill: theme.surface,
3907
+ radius: style === "product" ? S * .02 : S * .002,
3908
+ ...style === "product" ? { shadow: {
3909
+ color: "#0000001F",
3910
+ blur: Math.min(256, S * .022),
3911
+ offsetY: Math.min(512, S * .008)
3912
+ } } : {
3913
+ stroke: theme.accent,
3914
+ strokeWidth: Math.max(1, S * .0015)
3915
+ }
3916
+ };
3917
+ };
3918
+ if (recipe.recipe === "focus") if (!portrait) {
3919
+ const copyW = (innerW - gap) * (style === "editorial" ? .44 : style === "product" ? .29 : style === "technical" ? .34 : .36), imageW = innerW - gap - copyW, titleH = S * (style === "editorial" ? .32 : style === "technical" ? .22 : .26), bodyH = recipe.body ? S * (style === "editorial" ? .27 : style === "technical" ? .25 : .31) : 0, total = titleH + (recipe.body ? gap + bodyH : 0), x = left + copyW / 2;
3920
+ const content = [text("title", recipe.title, {
3921
+ x,
3922
+ y: -total / 2 + titleH / 2,
3923
+ width: copyW,
3924
+ height: titleH
3925
+ }, "title", `${path}.title`)];
3926
+ if (recipe.body) content.push(text("body", recipe.body, {
3927
+ x,
3928
+ y: total / 2 - bodyH / 2,
3929
+ width: copyW,
3930
+ height: bodyH
3931
+ }, "body", `${path}.body`));
3932
+ const visualBox = fittedFocusBox(recipe.image, {
3933
+ x: left + copyW + gap + imageW / 2,
3934
+ y: 0,
3935
+ width: imageW,
3936
+ height: innerH
3937
+ });
3938
+ layers.push(group("message", content, 0), ...style === "editorial" || style === "technical" ? [rule(`${style}-divider`, [[left + copyW + gap / 2, -innerH * .42], [left + copyW + gap / 2, innerH * .42]], .06)] : [], group("visual", picture("image", recipe.image, visualBox), .12));
3939
+ } else {
3940
+ const titleH = S * (style === "editorial" ? .26 : style === "technical" ? .19 : .22), bodyH = recipe.body ? S * (style === "editorial" ? .2 : style === "technical" ? .21 : .24) : 0, imageH = innerH - titleH - bodyH - gap * (recipe.body ? 2 : 1), sourceAware = style !== void 0 && recipe.image.crop !== void 0, fitted = fittedFocusBox(recipe.image, {
3941
+ x: 0,
3942
+ y: 0,
3943
+ width: innerW,
3944
+ height: imageH
3945
+ }), stackH = titleH + gap + fitted.height + (recipe.body ? gap + bodyH : 0), stackTop = sourceAware ? -stackH / 2 : top, imageTop = stackTop + titleH + gap, bodyY = sourceAware ? imageTop + fitted.height + gap + bodyH / 2 : H / 2 - margin - bodyH / 2;
3946
+ layers.push(group("heading", [text("title", recipe.title, {
3947
+ x: 0,
3948
+ y: stackTop + titleH / 2,
3949
+ width: innerW,
3950
+ height: titleH
3951
+ }, "title", `${path}.title`)], 0));
3952
+ if (style === "editorial" || style === "technical") layers.push(rule(`${style}-divider`, [[left, stackTop + titleH + gap * .38], [left + innerW, stackTop + titleH + gap * .38]], .06));
3953
+ layers.push(group("visual", picture("image", recipe.image, {
3954
+ ...fitted,
3955
+ y: imageTop + fitted.height / 2
3956
+ }), .12));
3957
+ if (recipe.body) layers.push(group("message", [text("body", recipe.body, {
3958
+ x: 0,
3959
+ y: bodyY,
3960
+ width: innerW,
3961
+ height: bodyH
3962
+ }, "body", `${path}.body`)], .2));
3963
+ }
3964
+ else if (recipe.recipe === "compare") {
3965
+ const titleH = S * (style === "editorial" ? .22 : style === "technical" ? .15 : .18), bodyH = recipe.body ? S * (style === "editorial" ? .11 : style === "technical" ? .1 : .13) : 0, headH = titleH + (recipe.body ? gap * .45 + bodyH : 0), contentTop = top + headH + gap, contentH = innerH - headH - gap, labelH = S * (style === "editorial" ? .09 : style === "technical" ? .075 : .11);
3966
+ const header = [text("title", recipe.title, {
3967
+ x: 0,
3968
+ y: top + titleH / 2,
3969
+ width: innerW,
3970
+ height: titleH
3971
+ }, "title", `${path}.title`)];
3972
+ if (recipe.body) header.push(text("body", recipe.body, {
3973
+ x: 0,
3974
+ y: top + titleH + gap * .45 + bodyH / 2,
3975
+ width: innerW,
3976
+ height: bodyH
3977
+ }, "body", `${path}.body`));
3978
+ layers.push(group("heading", header, 0));
3979
+ if (style === "editorial") layers.push(rule("editorial-heading-rule", [[left, contentTop - gap * .48], [left + innerW, contentTop - gap * .48]], .06));
3980
+ if (style === "technical" && !portrait) layers.push(rule("technical-centerline", [[0, contentTop], [0, contentTop + contentH]], .08));
3981
+ ["before", "after"].forEach((side, i) => {
3982
+ const item = recipe[side], width = portrait ? innerW : (innerW - gap) / 2, height = portrait ? (contentH - gap) / 2 : contentH, x = portrait ? 0 : left + i * (width + gap) + width / 2, y = contentTop + (portrait ? i * (height + gap) : 0);
3983
+ const children = [text(`${side}-label`, item.label, {
3984
+ x,
3985
+ y: y + labelH / 2,
3986
+ width,
3987
+ height: labelH
3988
+ }, "label", `${path}.${side}.label`), ...picture(`${side}-image`, item.image, {
3989
+ x,
3990
+ y: y + labelH + gap * .35 + (height - labelH - gap * .35) / 2,
3991
+ width,
3992
+ height: height - labelH - gap * .35
3993
+ })];
3994
+ layers.push(group(side, children, .15 + i * .12));
3995
+ });
3996
+ } else {
3997
+ const compactRows = W === H && recipe.steps.length >= 4, titleH = compactRows ? estimateMotionTextLines(recipe.title, innerW - 2 * pad, fonts.title) * fonts.title * 1.28 + 2 * pad : S * .21, headingGap = compactRows ? S * .025 : gap, contentTop = top + titleH + headingGap, contentH = innerH - titleH - headingGap, n = recipe.steps.length, stepGap = compactRows ? S * .01 : gap * .65, rowSteps = portrait || style === "technical";
3998
+ if (compactRows && contentH < stepGap * (n - 1) + n * (fonts.label * 1.28 + S * .006)) issues.push(error(`${path}.title`, "title leaves too little room for the square step rows; shorten it or use a custom motion scene with more room"));
3999
+ layers.push(group("heading", [text("title", recipe.title, {
4000
+ x: 0,
4001
+ y: top + titleH / 2,
4002
+ width: innerW,
4003
+ height: titleH
4004
+ }, "title", `${path}.title`)], 0));
4005
+ if (style === "editorial") layers.push(rule("editorial-heading-rule", [[left, contentTop - headingGap * .48], [left + innerW, contentTop - headingGap * .48]], .06));
4006
+ recipe.steps.forEach((step, i) => {
4007
+ if (compactRows) {
4008
+ const rowH = (contentH - stepGap * (n - 1)) / n, rowY = contentTop + i * (rowH + stepGap), inset = S * .003, numberW$1 = Math.max(S * .06, fonts.number * 1.4 + 2 * inset), copyX$1 = left + numberW$1 + S * .018, copyW$1 = innerW - numberW$1 - S * .018, labelH$1 = estimateMotionTextLines(step.label, copyW$1 - 2 * inset, fonts.label) * fonts.label * 1.28 + 2 * inset, bodyGap = S * .005, bodyH$1 = rowH - labelH$1 - bodyGap;
4009
+ if (labelH$1 > rowH + .001) {
4010
+ issues.push(error(`${path}.steps[${i}].label`, "copy does not fit its square step row; shorten the label or use a custom motion scene with a taller row"));
4011
+ return;
4012
+ }
4013
+ const children$1 = [text(`step-${i + 1}-number`, String(i + 1).padStart(2, "0"), {
4014
+ x: left + numberW$1 / 2,
4015
+ y: rowY + labelH$1 / 2,
4016
+ width: numberW$1,
4017
+ height: labelH$1
4018
+ }, "number", `${path}.steps[${i}].label`, theme.accent, inset), text(`step-${i + 1}-label`, step.label, {
4019
+ x: copyX$1 + copyW$1 / 2,
4020
+ y: rowY + labelH$1 / 2,
4021
+ width: copyW$1,
4022
+ height: labelH$1
4023
+ }, "label", `${path}.steps[${i}].label`, theme.ink, inset)];
4024
+ const surface$1 = stepSurface(`step-${i + 1}`, {
4025
+ x: 0,
4026
+ y: rowY + rowH / 2,
4027
+ width: innerW,
4028
+ height: rowH
4029
+ });
4030
+ if (surface$1) children$1.unshift(surface$1);
4031
+ if (style === "editorial") children$1.unshift(rule(`step-${i + 1}-rule`, [[left, rowY], [left + innerW, rowY]], .08 + i * .1));
4032
+ if (step.body) children$1.push(text(`step-${i + 1}-body`, step.body, {
4033
+ x: copyX$1 + copyW$1 / 2,
4034
+ y: rowY + labelH$1 + bodyGap + bodyH$1 / 2,
4035
+ width: copyW$1,
4036
+ height: bodyH$1
4037
+ }, "body", `${path}.steps[${i}].body`, theme.ink, inset));
4038
+ layers.push(group(`step-${i + 1}`, children$1, .12 * (i + 1)));
4039
+ return;
4040
+ }
4041
+ const width = rowSteps ? innerW : (innerW - stepGap * (n - 1)) / n, height = rowSteps ? (contentH - stepGap * (n - 1)) / n : contentH, x = rowSteps ? left : left + i * (width + stepGap), y = contentTop + (rowSteps ? i * (height + stepGap) : 0), numberW = Math.max(S * .08, fonts.number * 1.4 + 2 * pad), numberH = Math.max(S * .07, fonts.number * 1.28 + 2 * pad);
4042
+ const labelH = style === "editorial" ? Math.min(S * .11, height * .4) : Math.min(S * .13, height * .42), bodyH = height - (rowSteps ? labelH + pad : labelH + S * .09 + gap * .5), copyX = rowSteps ? x + numberW + pad : x, copyW = rowSteps ? width - numberW - pad : width;
4043
+ const children = [text(`step-${i + 1}-number`, String(i + 1).padStart(2, "0"), {
4044
+ x: x + numberW / 2,
4045
+ y: y + numberH / 2,
4046
+ width: numberW,
4047
+ height: numberH
4048
+ }, "number", `${path}.steps[${i}].label`, theme.accent), text(`step-${i + 1}-label`, step.label, {
4049
+ x: copyX + copyW / 2,
4050
+ y: y + (rowSteps ? 0 : S * .09) + labelH / 2,
4051
+ width: copyW,
4052
+ height: labelH
4053
+ }, "label", `${path}.steps[${i}].label`)];
4054
+ const surface = stepSurface(`step-${i + 1}`, {
4055
+ x: x + width / 2,
4056
+ y: y + height / 2,
4057
+ width,
4058
+ height
4059
+ });
4060
+ if (surface) children.unshift(surface);
4061
+ if (style === "editorial") children.unshift(rule(`step-${i + 1}-rule`, [[x, y], [x + width, y]], .08 + i * .1));
4062
+ if (step.body) children.push(text(`step-${i + 1}-body`, step.body, {
4063
+ x: copyX + copyW / 2,
4064
+ y: y + height - bodyH / 2,
4065
+ width: copyW,
4066
+ height: bodyH
4067
+ }, "body", `${path}.steps[${i}].body`));
4068
+ layers.push(group(`step-${i + 1}`, children, .12 * (i + 1)));
4069
+ });
4070
+ }
4071
+ const transition = recipe.transition ?? { type: "cut" };
4072
+ const exit = recipe.motion === "off" || transition.type === "cut" ? 0 : transition.durationS ?? .45;
4073
+ const reading = Math.max(1.2, texts.reduce((sum, value) => sum + estimateMotionReadingSeconds(value, 0), 0) + .4);
4074
+ const minimum = (recipe.motion === "off" ? 0 : Math.max(latestEntrance, exit)) + reading + exit;
4075
+ const derived = Math.ceil(minimum * output.fps - 1e-8) / output.fps;
4076
+ const durationS = recipe.durationS ?? derived;
4077
+ if (recipe.durationS !== void 0 && durationS + .001 < minimum) issues.push(error(`${path}.durationS`, `too short for this copy and motion; allow at least ${derived.toFixed(3)}s, shorten the copy, or disable motion`));
4078
+ return {
4079
+ id: recipe.id,
4080
+ type: "motion",
4081
+ durationS,
4082
+ designSize: {
4083
+ width: W,
4084
+ height: H
4085
+ },
4086
+ motion: recipe.motion ?? "on",
4087
+ transition,
4088
+ layers
4089
+ };
4090
+ }
4091
+ /** Expand guided recipes into ordinary editable layers. No asset I/O, capture or rendering. */
4092
+ function composeMotionStory(value) {
4093
+ const issues = [];
4094
+ if (!record(value)) return { issues: [error("$", "must be a motion story JSON object")] };
4095
+ for (const key of Object.keys(value)) if (![
4096
+ "version",
4097
+ "output",
4098
+ "theme",
4099
+ "scenes",
4100
+ "audio",
4101
+ "story"
4102
+ ].includes(key)) issues.push(error(key, "unsupported motion story field"));
4103
+ issues.push(...validateLaunchComposition({
4104
+ version: value.version,
4105
+ output: value.output,
4106
+ theme: value.theme,
4107
+ scenes: [{
4108
+ id: "header-check",
4109
+ type: "title",
4110
+ durationS: 1,
4111
+ lines: ["Check"],
4112
+ motion: "off"
4113
+ }]
4114
+ }));
4115
+ if (!Array.isArray(value.scenes) || !value.scenes.length) issues.push(error("scenes", "must contain at least one scene or recipe"));
4116
+ if (issues.length) return { issues };
4117
+ const output = value.output, theme = value.theme;
4118
+ const generated = new Set();
4119
+ const scenes = value.scenes.map((raw, i) => {
4120
+ if (!record(raw) || !Object.hasOwn(raw, "recipe")) return raw;
4121
+ generated.add(i);
4122
+ const path = `scenes[${i}]`, recipe = parseRecipe(raw, path, issues);
4123
+ if (!recipe) return raw;
4124
+ if (Math.min(output.width, output.height) < 320) {
4125
+ issues.push(error("output", "guided recipes require a short edge of at least 320px; use a custom motion scene for smaller output"));
4126
+ return raw;
4127
+ }
4128
+ return buildRecipe(recipe, path, output, theme, issues);
4129
+ });
4130
+ if (issues.some((x) => x.severity === "error")) return { issues };
4131
+ const candidate = {
4132
+ version: value.version,
4133
+ output,
4134
+ theme,
4135
+ scenes,
4136
+ ...value.audio !== void 0 ? { audio: value.audio } : {},
4137
+ ...value.story !== void 0 ? { story: value.story } : {}
4138
+ };
4139
+ issues.push(...validateLaunchComposition(candidate));
4140
+ if (issues.some((x) => x.severity === "error")) return { issues };
4141
+ let composition;
4142
+ try {
4143
+ composition = structuredClone(candidate);
4144
+ } catch {
4145
+ return { issues: [error("$", "must contain only JSON-compatible data")] };
4146
+ }
4147
+ for (const finding of analyzeMotionQuality(composition)) {
4148
+ const sceneIndex = Number(finding.path.match(/^scenes\[(\d+)\]/)?.[1]);
4149
+ const provable = generated.has(sceneIndex) && (finding.message.startsWith("Resting bounds") || finding.message.startsWith("Text contrast") || finding.message.startsWith("Text is small"));
4150
+ if (provable) {
4151
+ const contrast = finding.message.startsWith("Text contrast");
4152
+ const recipe = value.scenes[sceneIndex]?.recipe;
4153
+ issues.push({
4154
+ ...finding,
4155
+ severity: "error",
4156
+ path: contrast ? "theme" : `scenes[${sceneIndex}]`,
4157
+ message: `${finding.message} In ${recipe} recipe scenes[${sceneIndex}], ${contrast ? "adjust brief theme.ink, theme.canvas, theme.surface or theme.accent to improve contrast" : "adjust the brief copy or output dimensions"}.`
4158
+ });
4159
+ } else issues.push(finding);
4160
+ }
4161
+ issues.push(...analyzeLaunchStory(composition));
4162
+ return issues.some((x) => x.severity === "error") ? { issues } : {
4163
+ composition,
4164
+ issues
4165
+ };
4166
+ }
4167
+
1323
4168
  //#endregion
1324
4169
  //#region src/types.ts
1325
4170
  const DEFAULT_CAMERA = {
@@ -1438,7 +4283,7 @@ function planComposition(log, opts = {}) {
1438
4283
  y: c.y
1439
4284
  }, c.to] : void 0;
1440
4285
  const path = rawPath?.map(mapPt);
1441
- const ease = carries ? c.ease : void 0;
4286
+ const ease$1 = carries ? c.ease : void 0;
1442
4287
  const bbox = carries && path ? pathBBox(path) : c.box ? mapBox(c.box) : void 0;
1443
4288
  const effectBox = c.effectBox ? mapBox(c.effectBox) : void 0;
1444
4289
  const label = c.sel ?? c.note;
@@ -1465,7 +4310,7 @@ function planComposition(log, opts = {}) {
1465
4310
  ...kind === "press" ? { keys: c.keys } : {},
1466
4311
  ...to ? { to } : {},
1467
4312
  ...path ? { path } : {},
1468
- ...ease ? { ease } : {},
4313
+ ...ease$1 ? { ease: ease$1 } : {},
1469
4314
  ...kind === "dropFiles" ? { files: c.files } : {}
1470
4315
  };
1471
4316
  return {
@@ -2131,16 +4976,13 @@ async function prepareScratch(composition, videoPath) {
2131
4976
  await symlink(nm, join(dir, "node_modules"), "junction");
2132
4977
  await toMp4(videoPath, join(dir, "public", "capture.mp4"), composition.output.fps, "h264");
2133
4978
  return dir;
2134
- } catch (error) {
4979
+ } catch (error$1) {
2135
4980
  await cleanupScratch(dir);
2136
- throw error;
4981
+ throw error$1;
2137
4982
  }
2138
4983
  }
2139
- let renderQueue = Promise.resolve();
2140
4984
  async function renderTake(opts) {
2141
- const run$1 = renderQueue.then(() => renderTakeExclusive(opts), () => renderTakeExclusive(opts));
2142
- renderQueue = run$1.catch(() => {});
2143
- return run$1;
4985
+ return withRenderLock(() => renderTakeExclusive(opts));
2144
4986
  }
2145
4987
  async function renderTakeExclusive(opts) {
2146
4988
  if (!opts.chromePath) throw new Error("renderTake: `chromePath` is required; use @open-take/runtime to resolve managed Chrome automatically");
@@ -2210,10 +5052,10 @@ async function renderTakeExclusive(opts) {
2210
5052
  try {
2211
5053
  try {
2212
5054
  produced = await renderOnce();
2213
- } catch (error) {
2214
- if (!isCaptureUndecodable(error)) throw error;
2215
- const detail = error instanceof Error ? error.message : String(error);
2216
- if (!await ffmpegHasEncoder("libvpx-vp9")) throw new Error(`render: the browser at ${opts.chromePath} cannot decode the capture (${detail}) — point OPEN_TAKE_CHROME at a full Chrome/Chrome-for-Testing build, or install an ffmpeg with libvpx-vp9 to enable the VP9 fallback`, { cause: error });
5055
+ } catch (error$1) {
5056
+ if (!isCaptureUndecodable(error$1)) throw error$1;
5057
+ const detail = error$1 instanceof Error ? error$1.message : String(error$1);
5058
+ if (!await ffmpegHasEncoder("libvpx-vp9")) throw new Error(`render: the browser at ${opts.chromePath} cannot decode the capture (${detail}) — point OPEN_TAKE_CHROME at a full Chrome/Chrome-for-Testing build, or install an ffmpeg with libvpx-vp9 to enable the VP9 fallback`, { cause: error$1 });
2217
5059
  process.stderr.write("open-take: the render browser cannot decode the H.264 capture — retrying with a VP9 intermediate (output unchanged)\n");
2218
5060
  await toMp4(videoAbs, join(scratch, "public", "capture.mp4"), composition.output.fps, "vp9");
2219
5061
  try {
@@ -2248,5 +5090,5 @@ async function renderTakeExclusive(opts) {
2248
5090
  }
2249
5091
 
2250
5092
  //#endregion
2251
- export { CLAMP_TOL_MS, DEFAULT_CAMERA, DEFAULT_CURSOR, DEFAULT_FRAMING, DEFAULT_MOTION_BLUR, FINISH, LOOKS, MOTION, ZOOM_LEVELS, auditCursor, auditIssues, directCamera, finishName, formatIssues, lookName, math_exports as math, motionBlurActive, motionName, planComposition, predictCursorTips, renderTake, resolveFfmpeg, resolveFfprobe, validateComposition, zoomLevelName };
5093
+ export { CLAMP_TOL_MS, DEFAULT_CAMERA, DEFAULT_CURSOR, DEFAULT_FRAMING, DEFAULT_MOTION_BLUR, FINISH, LOOKS, MOTION, ZOOM_LEVELS, analyzeLaunchStory, analyzeMotionQuality, auditCursor, auditIssues, composeMotionStory, directCamera, evaluateMotionScene, evaluateMotionTrack, evaluateUiMorph, finishName, formatIssues, formatLaunchIssues, launchAudioAtS, launchDurationS, launchSceneDurationS, launchSceneWindows, launchStarter, launchTemplate, lookName, math_exports as math, motionBlurActive, motionGraphemes, motionName, planComposition, predictCursorTips, renderLaunch, renderTake, resolveFfmpeg, resolveFfprobe, uiMorphDurationS, uiStateDurationS, validateComposition, validateLaunchAssets, validateLaunchComposition, validateLaunchStory, validateMotionScene, zoomLevelName };
2252
5094
  //# sourceMappingURL=index.js.map