trace-avatar-render 0.1.2 → 0.1.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.4 (unreleased)
4
+
5
+ - `--canvas 9:16|4:5|1:1|16:9|WxH` (`canvas` in `render()` and `finish()`): the app is composed onto a picture of that
6
+ shape, between safe margins on the background, for Reels, Stories and feeds.
7
+ - `--width` scales the whole canvas.
8
+ - A phone capture is scaled up to fill a tall canvas, so capture it at `--scale 2`.
9
+ - Burned-in captions are sized to the canvas and sit below the app (above it with `--captions-at top`).
10
+ - `--watermark <text>` and `--watermark-at <corner>` (`watermark: text | { text, at, opacity, logo }`): a small
11
+ badge on every frame, the title and end cards included.
12
+ - It is drawn after the camera, so it never zooms.
13
+ - A burned-in caption that would touch it moves clear of it.
14
+ - **Cards** take `url` (large, in the card's colour) and `logo` (an image file above the title), e.g.
15
+ `{ "title": "For more info visit", "url": "naijaprices.com" }`.
16
+ - `--brand <file.json>` (`brandOf`, `brandFile`): the look in one checked file.
17
+ - It covers canvas, watermark, frame, background, camera, captions, captionsAt, titleCard and endCard.
18
+ - Logo paths resolve beside the file.
19
+ - Flags given on the command line win over it.
20
+
21
+ ## 0.1.3 (11 Nov 2026)
22
+
23
+ - `--captions-at top|bottom` (`captionsAt` in `render()` and `finish()`): burned-in captions can sit at the top. At
24
+ the bottom they covered the app's own UI when it is low on the page: trace-avatar's Fix this step card, found
25
+ making traceavatar.com's Repair clip.
26
+ - Needs trace-avatar ^0.1.14 (was ^0.1.13): `--value` and `--security` are 0.1.14's `values` and `security`. With
27
+ 0.1.13 a `--value` was silently ignored, and Do it for me skipped the field (found making a SpeedyMessaging clip).
28
+
3
29
  ## 0.1.2 (10 Nov 2026)
4
30
 
5
31
  - `--navigate` (`navigate: true` in `render()`): when a step is on another page, the renderer loads that page, as the
package/README.md CHANGED
@@ -60,15 +60,36 @@ Because the guide is known before it plays, the render can do what a screen reco
60
60
  | `--camera` | zoom in on each click and typing step before it happens, pan between close ones, back out between bursts; never on scrolls, at most one zoom change per 1.5 s. Pair with `--scale 2` for crisp zooms |
61
61
  | `--zoom <n>` | how far the camera goes in (default 1.6); implies `--camera` |
62
62
  | `--captions burn\|vtt\|both` | `burn` draws the steps' words low in the picture (the player's own bubble is then off); `vtt` writes `<out>.vtt` and `<out>.chapters.vtt` beside the first output |
63
+ | `--captions-at top\|bottom` | where burned-in captions sit (default `bottom`); `top` when the app's own UI is low on the page (a toolbar, a card, a cookie bar) |
63
64
  | `--poster [file]` | a PNG at the first click (default `<out>.png`) |
64
65
  | `--title-card [title]` | 1.5 s first: the trace's title and the avatar, or your title; fades into the guide |
65
66
  | `--end-card [title]` | 2 s last: "Done", or your text (e.g. a URL) |
67
+ | `--canvas <shape>` | compose onto `9:16` (1080×1920), `4:5`, `1:1`, `16:9` or `WxH`: the app between safe margins on the background, captions sized to the canvas and below the app; `--width` scales the canvas. For a phone-shaped clip, capture at `--viewport 390x844 --scale 2` |
68
+ | `--watermark <text>` | a small badge on every frame, cards included (never zoomed by the camera; captions keep clear of it) |
69
+ | `--watermark-at <corner>` | `top-left`, `top-right`, `bottom-left` or `bottom-right` (default) |
70
+ | `--brand <file.json>` | the look in one file (below); flags given on the command line win over it |
66
71
 
67
72
  ```sh
68
73
  trace-avatar-render invoice.trace.json --url http://localhost:3000/app --out invoice.mp4 \
69
74
  --scale 2 --frame browser --camera --captions both --poster --title-card --end-card "acme.com/invoices"
70
75
  ```
71
76
 
77
+ **A brand** keeps every clip of a product looking the same, in every shape:
78
+
79
+ ```json
80
+ {
81
+ "frame": "browser",
82
+ "background": "linear-gradient(135deg, #e6eefc, #e9f6f1)",
83
+ "watermark": { "text": "Made by Acme", "at": "bottom-right", "logo": "acme-mark.svg" },
84
+ "endCard": { "title": "For more info visit", "url": "acme.com", "logo": "acme-logo.png", "color": "#2456d8" }
85
+ }
86
+ ```
87
+
88
+ ```sh
89
+ trace-avatar-render invoice.trace.json --url http://localhost:3000/app --brand acme.json --canvas 9:16 \
90
+ --viewport 390x844 --scale 2 --captions burn --out invoice-reel.mp4
91
+ ```
92
+
72
93
  Exit codes: 0 rendered, 1 the render failed, 2 wrong usage.
73
94
 
74
95
  **MP4 needs ffmpeg** on the PATH (or `FFMPEG=/path/to/ffmpeg`): `brew install ffmpeg`, `apt install ffmpeg`. GIF
@@ -283,9 +283,9 @@ async function findPlayer(explicit, env = process.env) {
283
283
  if (explicit) return explicit;
284
284
  if (env.TRACE_AVATAR_PLAYER) return env.TRACE_AVATAR_PLAYER;
285
285
  const { createRequire } = await import("module");
286
- const { dirname: dirname3, join: join4 } = await import("path");
286
+ const { dirname: dirname4, join: join4 } = await import("path");
287
287
  const req = createRequire(import.meta.url);
288
- return join4(dirname3(req.resolve("trace-avatar/package.json")), "dist", "trace-perform.min.js");
288
+ return join4(dirname4(req.resolve("trace-avatar/package.json")), "dist", "trace-perform.min.js");
289
289
  }
290
290
 
291
291
  // src/compose.ts
@@ -467,7 +467,16 @@ function same(a, b) {
467
467
  }
468
468
 
469
469
  // src/layers.ts
470
+ import { readFileSync as readFileSync2 } from "fs";
471
+ import { extname } from "path";
470
472
  import { PNG } from "pngjs";
473
+ var MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".svg": "image/svg+xml", ".webp": "image/webp", ".gif": "image/gif" };
474
+ function dataUri(file) {
475
+ if (/^data:/.test(file)) return file;
476
+ const type = MIME[extname(file).toLowerCase()];
477
+ if (!type) throw new Error(`a logo is a PNG, JPEG, SVG, WebP or GIF file (got ${file})`);
478
+ return `data:${type};base64,${readFileSync2(file).toString("base64")}`;
479
+ }
471
480
  var DEFAULT_BACKGROUND = "linear-gradient(135deg, #dfe7fb 0%, #eef0f6 50%, #f6e9f1 100%)";
472
481
  var esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
473
482
  var FONT = "system-ui,-apple-system,'Segoe UI',Roboto,sans-serif";
@@ -491,6 +500,7 @@ async function createLayers(browser) {
491
500
  const bar = l.bar;
492
501
  const r = Math.round(l.width * 0.012);
493
502
  const dot = bar ? Math.round(bar.h * 0.36) : 0;
503
+ const plate = !bar && l.canvas ? `<div style="position:absolute;left:${win.x}px;top:${win.y}px;width:${win.w}px;height:${win.h}px;border-radius:${r}px;background:#fff;box-shadow:0 ${Math.round(r * 1.5)}px ${r * 5}px rgb(15 23 42/.22),0 0 0 1px rgb(15 23 42/.08)"></div>` : "";
494
504
  const chrome = bar ? `
495
505
  <div style="position:absolute;left:${win.x}px;top:${win.y}px;width:${win.w}px;height:${win.h}px;border-radius:${r}px;background:#fff;box-shadow:0 ${Math.round(r * 1.5)}px ${r * 5}px rgb(15 23 42/.22),0 0 0 1px rgb(15 23 42/.08)"></div>
496
506
  <div style="position:absolute;left:${bar.x}px;top:${bar.y}px;width:${bar.w}px;height:${bar.h}px;border-radius:${r}px ${r}px 0 0;background:#eef0f4;border-bottom:1px solid #d9dde5;box-sizing:border-box;display:flex;align-items:center;gap:${Math.round(dot * 0.6)}px;padding:0 ${Math.round(dot * 1.2)}px;font:${Math.round(bar.h * 0.42)}px/1 ${FONT};color:#475569">
@@ -500,7 +510,7 @@ async function createLayers(browser) {
500
510
  <span style="flex:1;display:flex;justify-content:center;min-width:0"><span style="background:#fff;border-radius:${Math.round(bar.h * 0.3)}px;padding:${Math.round(bar.h * 0.12)}px ${Math.round(bar.h * 0.6)}px;max-width:70%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${esc(o.path ?? "/")}</span></span>
501
511
  <span style="flex:none;max-width:22%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:600">${esc(o.title ?? "")}</span>
502
512
  </div>` : "";
503
- return shoot(l.width, l.height, `<div style="position:relative;width:100%;height:100%;background:${o.background}">${chrome}</div>`);
513
+ return shoot(l.width, l.height, `<div style="position:relative;width:100%;height:100%;background:${o.background}">${plate}${chrome}</div>`);
504
514
  },
505
515
  async caption(text, o) {
506
516
  const pad = Math.round(o.fontPx * 0.6);
@@ -511,11 +521,18 @@ async function createLayers(browser) {
511
521
  const initial = esc((o.sub ?? o.title).trim().charAt(0).toUpperCase() || "\u2022");
512
522
  return shoot(l.width, l.height, `<div style="width:100%;height:100%;background:${o.background};display:flex;align-items:center;justify-content:center;font-family:${FONT}">
513
523
  <div style="max-width:76%;box-sizing:border-box;padding:${Math.round(s * 0.8)}px ${Math.round(s * 1.2)}px;border-radius:${Math.round(s * 0.5)}px;background:#fff;box-shadow:0 ${Math.round(s * 0.3)}px ${s}px rgb(15 23 42/.25);display:flex;flex-direction:column;align-items:center;gap:${Math.round(s * 0.45)}px;color:#0f172a;text-align:center">
524
+ ${o.logo ? `<img src="${dataUri(o.logo)}" alt="" style="max-height:${Math.round(s * 2)}px;max-width:${Math.round(l.width * 0.4)}px">` : ""}
514
525
  <div style="font:700 ${s}px/1.2 ${FONT}">${esc(o.title)}</div>
526
+ ${o.url ? `<div style="font:800 ${Math.round(s * 0.9)}px/1.15 ${FONT};color:${o.color ?? "#2456d8"};overflow-wrap:anywhere">${esc(o.url)}</div>` : ""}
515
527
  ${o.sub ? `<div style="display:flex;align-items:center;gap:${Math.round(s * 0.25)}px;font:500 ${Math.round(s * 0.45)}px/1 ${FONT};color:#334155"><span style="width:${Math.round(s * 0.7)}px;height:${Math.round(s * 0.7)}px;border-radius:50%;background:${o.color ?? "#2456d8"};color:#fff;display:inline-flex;align-items:center;justify-content:center;font-weight:700">${initial}</span>${esc(o.sub)}</div>` : ""}
516
528
  </div>
517
529
  </div>`);
518
530
  },
531
+ async badge(text, o) {
532
+ const f = o.fontPx;
533
+ const logo = o.logo ? `<img src="${dataUri(o.logo)}" alt="" style="height:${Math.round(f * 1.25)}px;width:auto;flex:none">` : "";
534
+ return shoot(f * 40, f * 4, `<div style="display:flex"><div id="b" style="display:inline-flex;align-items:center;gap:${Math.round(f * 0.45)}px;padding:${Math.round(f * 0.4)}px ${Math.round(f * 0.7)}px;border-radius:${Math.round(f * 0.6)}px;background:rgb(15 23 42/.72);color:#fff;font:600 ${f}px/1.1 ${FONT};white-space:nowrap">${logo}<span>${esc(text)}</span></div></div>`, true, "#b");
535
+ },
519
536
  close: () => ctx.close()
520
537
  };
521
538
  }
@@ -578,7 +595,8 @@ function pixel(img, x, y) {
578
595
 
579
596
  // src/layout.ts
580
597
  var even = (n) => Math.max(2, Math.round(n / 2) * 2);
581
- function layoutOf(srcW, srcH, width, frame = "none") {
598
+ function layoutOf(srcW, srcH, width, frame = "none", canvas) {
599
+ if (canvas) return onCanvas(srcW, srcH, width, frame, canvas);
582
600
  if (frame === "none") {
583
601
  const { width: W2, height: H2 } = fitWidth(srcW, srcH, width);
584
602
  const r = { x: 0, y: 0, w: W2, h: H2 };
@@ -599,6 +617,131 @@ function layoutOf(srcW, srcH, width, frame = "none") {
599
617
  window: { x: pad, y: top, w: cw, h: barH + ch }
600
618
  };
601
619
  }
620
+ function onCanvas(srcW, srcH, width, frame, canvas) {
621
+ const W = even(width ? Math.min(width, canvas.width) : canvas.width);
622
+ const H = even(canvas.height * W / canvas.width);
623
+ const tall = H / W > 1.2;
624
+ const padX = Math.round(W * 0.05);
625
+ const top = Math.round(H * (tall ? 0.1 : 0.07));
626
+ const bottom = Math.round(H * (tall ? 0.16 : 0.09));
627
+ const boxW = W - 2 * padX;
628
+ const boxH = H - top - bottom;
629
+ const barK = frame === "browser" ? 0.039 : 0;
630
+ const cw = Math.max(2, Math.floor(Math.min(boxW, boxH / (srcH / srcW + barK))));
631
+ const ch = Math.max(2, Math.round(srcH * cw / srcW));
632
+ const barH = frame === "browser" ? Math.max(18, Math.round(cw * barK)) : 0;
633
+ const x = Math.round((W - cw) / 2);
634
+ const y = top + Math.max(0, Math.round((boxH - ch - barH) / 2));
635
+ return {
636
+ width: W,
637
+ height: H,
638
+ bar: frame === "browser" ? { x, y, w: cw, h: barH } : null,
639
+ content: { x, y: y + barH, w: cw, h: ch },
640
+ window: { x, y, w: cw, h: barH + ch },
641
+ canvas: true
642
+ };
643
+ }
644
+
645
+ // src/brand.ts
646
+ import { readFileSync as readFileSync3 } from "fs";
647
+ import { dirname, isAbsolute, resolve } from "path";
648
+ var CANVASES = {
649
+ "9:16": { width: 1080, height: 1920 },
650
+ "4:5": { width: 1080, height: 1350 },
651
+ "1:1": { width: 1080, height: 1080 },
652
+ "16:9": { width: 1920, height: 1080 }
653
+ };
654
+ var CORNERS = ["top-left", "top-right", "bottom-left", "bottom-right"];
655
+ function canvasOf(v) {
656
+ if (typeof v === "object" && v) {
657
+ if (!(Number.isInteger(v.width) && Number.isInteger(v.height) && v.width >= 16 && v.height >= 16)) throw new Error("a canvas is { width, height } in whole pixels, at least 16");
658
+ return { width: v.width, height: v.height };
659
+ }
660
+ if (CANVASES[v]) return CANVASES[v];
661
+ const m = /^(\d+)x(\d+)$/i.exec(String(v));
662
+ if (!m || Number(m[1]) < 16 || Number(m[2]) < 16) throw new Error(`a canvas is ${Object.keys(CANVASES).join(", ")} or WIDTHxHEIGHT (got ${String(v)})`);
663
+ return { width: Number(m[1]), height: Number(m[2]) };
664
+ }
665
+ function watermarkOf(v) {
666
+ const w = typeof v === "string" ? { text: v } : v;
667
+ if (!w || typeof w.text !== "string" || !w.text.trim()) throw new Error("a watermark needs its text");
668
+ if (w.at !== void 0 && !CORNERS.includes(w.at)) throw new Error(`a watermark sits at ${CORNERS.join(", ")}`);
669
+ if (w.opacity !== void 0 && !(w.opacity > 0 && w.opacity <= 1)) throw new Error("a watermark's opacity is above 0, up to 1");
670
+ return { ...w, text: w.text.trim() };
671
+ }
672
+ var KEYS = ["$comment", "name", "canvas", "watermark", "frame", "background", "camera", "captions", "captionsAt", "titleCard", "endCard"];
673
+ function brandOf(json, dir = ".") {
674
+ if (!json || typeof json !== "object" || Array.isArray(json)) throw new Error("a brand is a JSON object");
675
+ const b = json;
676
+ const problems = [];
677
+ for (const k of Object.keys(b)) if (!KEYS.includes(k)) problems.push(`unknown key ${k}`);
678
+ const out = {};
679
+ const at = (p) => p && !isAbsolute(p) && !/^data:/.test(p) ? resolve(dir, p) : p;
680
+ const card = (v, name) => {
681
+ if (typeof v === "boolean" || typeof v === "string") return v;
682
+ if (v && typeof v === "object" && typeof v.title === "string") {
683
+ const c = v;
684
+ return { ...c, ...c.logo ? { logo: at(c.logo) } : {} };
685
+ }
686
+ problems.push(`${name} is true, a title, or { title, sub?, url?, logo?, color? }`);
687
+ return void 0;
688
+ };
689
+ const tryIt = (f) => {
690
+ try {
691
+ f();
692
+ } catch (e) {
693
+ problems.push(e.message);
694
+ }
695
+ };
696
+ if (b.canvas !== void 0) tryIt(() => {
697
+ canvasOf(b.canvas);
698
+ out.canvas = b.canvas;
699
+ });
700
+ if (b.watermark !== void 0) tryIt(() => {
701
+ const w = watermarkOf(b.watermark);
702
+ out.watermark = { ...w, ...w.logo ? { logo: at(w.logo) } : {} };
703
+ });
704
+ if (b.frame !== void 0) {
705
+ if (b.frame === "none" || b.frame === "browser") out.frame = b.frame;
706
+ else problems.push("frame is none or browser");
707
+ }
708
+ if (b.background !== void 0) {
709
+ if (typeof b.background === "string") out.background = b.background;
710
+ else problems.push("background is a CSS colour or gradient");
711
+ }
712
+ if (b.camera !== void 0) {
713
+ const z = b.camera?.zoom;
714
+ if (typeof b.camera === "boolean" || typeof b.camera === "object" && b.camera && (z === void 0 || typeof z === "number" && z >= 1)) out.camera = b.camera;
715
+ else problems.push("camera is true, false or { zoom \u2265 1 }");
716
+ }
717
+ if (b.captions !== void 0) {
718
+ if (["burn", "vtt", "both"].includes(b.captions)) out.captions = b.captions;
719
+ else problems.push("captions is burn, vtt or both");
720
+ }
721
+ if (b.captionsAt !== void 0) {
722
+ if (b.captionsAt === "top" || b.captionsAt === "bottom") out.captionsAt = b.captionsAt;
723
+ else problems.push("captionsAt is top or bottom");
724
+ }
725
+ if (b.titleCard !== void 0) {
726
+ const c = card(b.titleCard, "titleCard");
727
+ if (c !== void 0) out.titleCard = c;
728
+ }
729
+ if (b.endCard !== void 0) {
730
+ const c = card(b.endCard, "endCard");
731
+ if (c !== void 0) out.endCard = c;
732
+ }
733
+ if (problems.length) throw new Error(`brand: ${problems.join("; ")}`);
734
+ return out;
735
+ }
736
+ function brandFile(file) {
737
+ let json;
738
+ try {
739
+ json = JSON.parse(readFileSync3(file, "utf8"));
740
+ } catch (e) {
741
+ throw new Error(`brand ${file}: ${e.message}`);
742
+ }
743
+ return brandOf(json, dirname(resolve(file)));
744
+ }
602
745
 
603
746
  // src/mp4.ts
604
747
  import { spawn, spawnSync } from "child_process";
@@ -652,9 +795,9 @@ async function encodeMp4(frames, o) {
652
795
  p.stderr.on("data", (d) => {
653
796
  err += String(d);
654
797
  });
655
- const done = new Promise((resolve3, reject) => {
798
+ const done = new Promise((resolve4, reject) => {
656
799
  p.on("error", reject);
657
- p.on("close", (code) => code === 0 ? resolve3() : reject(new Error(`ffmpeg exited with ${code}: ${err.trim()}`)));
800
+ p.on("close", (code) => code === 0 ? resolve4() : reject(new Error(`ffmpeg exited with ${code}: ${err.trim()}`)));
658
801
  });
659
802
  p.stdin.on("error", () => {
660
803
  });
@@ -1031,16 +1174,16 @@ async function suggestScript(ai, trace) {
1031
1174
  }
1032
1175
 
1033
1176
  // src/repair.ts
1034
- import { existsSync, readFileSync as readFileSync2 } from "fs";
1035
- import { dirname, join } from "path";
1177
+ import { existsSync, readFileSync as readFileSync4 } from "fs";
1178
+ import { dirname as dirname2, join } from "path";
1036
1179
  import { applyRaw, chooseRepair, chooseWait, guessWait, repairSuggestion, typedOf, waitSuggestion } from "trace-avatar/assist";
1037
1180
  function repairScriptOf(playerFile) {
1038
- const file = join(dirname(playerFile), "trace-repair.min.js");
1181
+ const file = join(dirname2(playerFile), "trace-repair.min.js");
1039
1182
  if (!existsSync(file)) throw new RenderError(`--repair needs trace-avatar 0.1.7 or later (no ${file})`);
1040
1183
  return file;
1041
1184
  }
1042
1185
  function stallInspector(o) {
1043
- const code = `${readFileSync2(o.script, "utf8")}
1186
+ const code = `${readFileSync4(o.script, "utf8")}
1044
1187
  ;window.__taRepair = TraceAvatarRepair;`;
1045
1188
  return async (page, stall) => {
1046
1189
  if (stall.reason === "until-timeout") return waitInspect(page, stall.index);
@@ -1164,7 +1307,7 @@ function chapterCues(starts, endMs) {
1164
1307
  }
1165
1308
 
1166
1309
  // src/ai.ts
1167
- import { resolve } from "path";
1310
+ import { resolve as resolve2 } from "path";
1168
1311
  import { pathToFileURL } from "url";
1169
1312
  import { gateway, openAiCompatible } from "trace-avatar/assist";
1170
1313
  async function providerOf(spec, env = process.env, o = {}) {
@@ -1185,7 +1328,7 @@ async function providerOf(spec, env = process.env, o = {}) {
1185
1328
  return openAiCompatible({ baseUrl: env.OPENAI_BASE_URL || "https://api.openai.com/v1", ...env.OPENAI_API_KEY ? { key: env.OPENAI_API_KEY } : {}, model: m[1], ...vision });
1186
1329
  }
1187
1330
  if (/\.(m?js|cjs)$/.test(spec)) {
1188
- const mod = await import(pathToFileURL(resolve(spec)).href);
1331
+ const mod = await import(pathToFileURL(resolve2(spec)).href);
1189
1332
  const fn = mod.default ?? mod.ai;
1190
1333
  if (typeof fn !== "function") throw new Error(`${spec} must export a default function (task, input, schema, { instructions, images }) \u2192 JSON`);
1191
1334
  return fn;
@@ -1221,14 +1364,14 @@ async function runQa(ai, frames, context) {
1221
1364
  }
1222
1365
 
1223
1366
  // src/render.ts
1224
- import { readFileSync as readFileSync3, writeFileSync, mkdirSync, mkdtempSync, rmSync } from "fs";
1367
+ import { readFileSync as readFileSync5, writeFileSync, mkdirSync, mkdtempSync, rmSync } from "fs";
1225
1368
  import { tmpdir } from "os";
1226
- import { dirname as dirname2, extname, join as join2 } from "path";
1369
+ import { dirname as dirname3, extname as extname2, join as join2 } from "path";
1227
1370
  import { chromium as chromium2 } from "playwright";
1228
1371
  import { PNG as PNG2 } from "pngjs";
1229
1372
  import { describe as describeGuide } from "trace-avatar/assist";
1230
1373
  var formatOf = (file) => {
1231
- const ext = extname(file).toLowerCase();
1374
+ const ext = extname2(file).toLowerCase();
1232
1375
  if (ext === ".gif") return "gif";
1233
1376
  if (ext === ".mp4") return "mp4";
1234
1377
  throw new RenderError(`unknown output "${file}": use .gif or .mp4`);
@@ -1244,7 +1387,7 @@ function cardOf(v, fallback) {
1244
1387
  return { ...fallback, ...v };
1245
1388
  }
1246
1389
  async function render(o) {
1247
- const trace = typeof o.trace === "string" ? JSON.parse(readFileSync3(o.trace, "utf8")) : o.trace;
1390
+ const trace = typeof o.trace === "string" ? JSON.parse(readFileSync5(o.trace, "utf8")) : o.trace;
1248
1391
  if (!trace || typeof trace !== "object") throw new RenderError("the trace must be an object or a .trace.json path");
1249
1392
  const mode = o.mode ?? "overlay";
1250
1393
  if (mode === "perform" && !o.allowPerform) {
@@ -1259,7 +1402,7 @@ async function render(o) {
1259
1402
  const burn = o.captions === "burn" || o.captions === "both";
1260
1403
  if ((o.qa || o.alt) && !o.ai) throw new RenderError("qa and alt need an AI: pass ai (--ai)");
1261
1404
  if (o.voice && !outs.some((x) => x.format === "mp4")) throw new RenderError("narration is for video: add an .mp4 output (a GIF has no sound)");
1262
- const spoken = o.voice ? linesOf(trace.steps ?? [], o.script === void 0 ? void 0 : parseScript(typeof o.script === "string" ? JSON.parse(readFileSync3(o.script, "utf8")) : o.script)) : null;
1405
+ const spoken = o.voice ? linesOf(trace.steps ?? [], o.script === void 0 ? void 0 : parseScript(typeof o.script === "string" ? JSON.parse(readFileSync5(o.script, "utf8")) : o.script)) : null;
1263
1406
  if (spoken && !spoken.size) throw new RenderError("nothing to say: no step has a caption (say), and no script was given");
1264
1407
  if (o.repairVision && !(o.repair && o.ai)) throw new RenderError("repairVision needs repair and an AI");
1265
1408
  const capOpts = {
@@ -1293,7 +1436,7 @@ async function render(o) {
1293
1436
  if (!(o.repair && e instanceof RenderError && e.stall)) throw e;
1294
1437
  const outcome = await repairGuide({ trace, capture: capOpts, ...o.ai ? { ai: o.ai } : {}, ...o.repairVision ? { vision: true } : {}, first: e });
1295
1438
  const file = `${base(outs[0].file)}.repair.json`;
1296
- mkdirSync(dirname2(file) || ".", { recursive: true });
1439
+ mkdirSync(dirname3(file) || ".", { recursive: true });
1297
1440
  writeFileSync(file, `${JSON.stringify({ task: "repair", suggestions: outcome.suggestions, unresolved: outcome.unresolved, passed: outcome.passed }, null, 2)}
1298
1441
  `);
1299
1442
  const n = outcome.suggestions.length;
@@ -1384,6 +1527,8 @@ async function finish(cap, outs, o = {}) {
1384
1527
  const srcH = first.height;
1385
1528
  const scale = cap.viewport ? srcW / cap.viewport.w : 1;
1386
1529
  const frameStyle = o.frame ?? "none";
1530
+ const canvas = o.canvas !== void 0 ? canvasOf(o.canvas) : void 0;
1531
+ const mark = o.watermark !== void 0 ? watermarkOf(o.watermark) : void 0;
1387
1532
  const background = o.background ?? DEFAULT_BACKGROUND;
1388
1533
  const burn = o.captions === "burn" || o.captions === "both";
1389
1534
  const variant = (sg) => {
@@ -1402,7 +1547,7 @@ async function finish(cap, outs, o = {}) {
1402
1547
  const titleMs = o.cards?.title ? TITLE_MS : 0;
1403
1548
  const endMs = o.cards?.end ? END_MS : 0;
1404
1549
  const full = { x: 0, y: 0, w: srcW, h: srcH };
1405
- const needLayers = frameStyle !== "none" || burn && (cues.length > 0 || plain.cues.length > 0) || !!o.cards?.title || !!o.cards?.end;
1550
+ const needLayers = frameStyle !== "none" || !!canvas || !!mark || burn && (cues.length > 0 || plain.cues.length > 0) || !!o.cards?.title || !!o.cards?.end;
1406
1551
  const browser = needLayers ? await chromium2.launch() : null;
1407
1552
  let layers = null;
1408
1553
  const outputs = [];
@@ -1413,15 +1558,15 @@ async function finish(cap, outs, o = {}) {
1413
1558
  try {
1414
1559
  layers = browser ? await createLayers(browser) : null;
1415
1560
  for (const [n, out] of outs.entries()) {
1416
- mkdirSync(dirname2(out.file) || ".", { recursive: true });
1561
+ mkdirSync(dirname3(out.file) || ".", { recursive: true });
1417
1562
  const fps = out.fps ?? (out.format === "gif" ? 12 : 30);
1418
- const layout = layoutOf(srcW, srcH, out.width ?? (out.format === "gif" ? 800 : void 0), frameStyle);
1563
+ const layout = layoutOf(srcW, srcH, out.width ?? (out.format === "gif" ? 800 : void 0), frameStyle, canvas);
1419
1564
  const v = out.format === "gif" ? plain : main;
1420
1565
  const { cam, segs: segs2, contentMs: contentMs2 } = v;
1421
1566
  const cues2 = v.cues;
1422
1567
  const times = frameTimes(segs2, fps);
1423
1568
  const picks = pickFrames(stamps, times);
1424
- const art = await artFor(layers, layout, { frameStyle, background, cues: burn ? cues2 : [], urls: [...new Set(cap.events.map((e) => e.url).filter(Boolean))], titles: cap.titles ?? {}, cards: o.cards });
1569
+ const art = await artFor(layers, layout, { frameStyle, background, cues: burn ? cues2 : [], urls: [...new Set(cap.events.map((e) => e.url).filter(Boolean))], titles: cap.titles ?? {}, cards: o.cards, mark });
1425
1570
  const nTitle = Math.round(titleMs * fps / 1e3);
1426
1571
  const nEnd = Math.round(endMs * fps / 1e3);
1427
1572
  const nFade = Math.max(1, Math.round(FADE_MS * fps / 1e3));
@@ -1440,8 +1585,23 @@ async function finish(cap, outs, o = {}) {
1440
1585
  drawRegion(dst, layout.content, source(i), rect);
1441
1586
  if (c && alpha > 0) {
1442
1587
  const img = art.captions.get(c.cue.text);
1443
- if (img) overlay(dst, img, layout.content.x + (layout.content.w - img.width) / 2, layout.content.y + layout.content.h - img.height - Math.round(layout.content.h * 0.05), alpha);
1588
+ const gap = Math.round(layout.content.h * 0.05);
1589
+ let y = img && (o.captionsAt === "top" ? layout.content.y + gap : layout.content.y + layout.content.h - img.height - gap);
1590
+ if (img && layout.canvas) {
1591
+ const g2 = Math.round(layout.height * 0.02);
1592
+ const below = layout.window.y + layout.window.h + g2;
1593
+ const above = layout.window.y - g2 - img.height;
1594
+ if (o.captionsAt === "top" ? above >= g2 : below + img.height <= layout.height - g2) y = o.captionsAt === "top" ? above : below;
1595
+ }
1596
+ const x = img ? layout.canvas ? (layout.width - img.width) / 2 : layout.content.x + (layout.content.w - img.width) / 2 : 0;
1597
+ if (img && y !== void 0 && art.badge) {
1598
+ const b = art.badge;
1599
+ const touches = x < b.x + b.img.width && x + img.width > b.x && y < b.y + b.img.height && y + img.height > b.y;
1600
+ if (touches) y = b.y < layout.height / 2 ? b.y + b.img.height + Math.round(gap / 2) : b.y - img.height - Math.round(gap / 2);
1601
+ }
1602
+ if (img && y !== void 0) overlay(dst, img, x, y, alpha);
1444
1603
  }
1604
+ if (art.badge) overlay(dst, art.badge.img, art.badge.x, art.badge.y, art.badge.alpha);
1445
1605
  last = { key, img: dst };
1446
1606
  return dst;
1447
1607
  };
@@ -1473,13 +1633,13 @@ async function finish(cap, outs, o = {}) {
1473
1633
  audio = join2(tmp, `${n}.wav`);
1474
1634
  writeFileSync(audio, toWav(track, TRACK_RATE));
1475
1635
  if (narr.out && !wav) {
1476
- mkdirSync(dirname2(narr.out) || ".", { recursive: true });
1636
+ mkdirSync(dirname3(narr.out) || ".", { recursive: true });
1477
1637
  writeFileSync(narr.out, toWav(track, TRACK_RATE));
1478
1638
  wav = narr.out;
1479
1639
  }
1480
1640
  }
1481
1641
  await encodeMp4(all(), { file: out.file, fps, width: layout.width, height: layout.height, ...audio ? { audio } : {} });
1482
- outputs.push({ file: out.file, format: "mp4", width: layout.width, height: layout.height, fps, frames: total, bytes: readFileSync3(out.file).length, durationMs: Math.round(total * 1e3 / fps) });
1642
+ outputs.push({ file: out.file, format: "mp4", width: layout.width, height: layout.height, fps, frames: total, bytes: readFileSync5(out.file).length, durationMs: Math.round(total * 1e3 / fps) });
1483
1643
  }
1484
1644
  if (n === 0 && o.poster) {
1485
1645
  const click = cap.events.find((e) => e.type === "step" && (e.stepType === "click" || e.stepType === "dblclick"));
@@ -1490,7 +1650,7 @@ async function finish(cap, outs, o = {}) {
1490
1650
  const png = new PNG2({ width: img.width, height: img.height });
1491
1651
  png.data.set(img.data);
1492
1652
  poster = typeof o.poster === "string" ? o.poster : `${base(out.file)}.png`;
1493
- mkdirSync(dirname2(poster) || ".", { recursive: true });
1653
+ mkdirSync(dirname3(poster) || ".", { recursive: true });
1494
1654
  writeFileSync(poster, PNG2.sync.write(png));
1495
1655
  }
1496
1656
  if (n === 0 && o.qa) {
@@ -1549,7 +1709,7 @@ async function finish(cap, outs, o = {}) {
1549
1709
  ...warnings.length ? { warnings } : {}
1550
1710
  };
1551
1711
  if (o.timeline) {
1552
- mkdirSync(dirname2(o.timeline) || ".", { recursive: true });
1712
+ mkdirSync(dirname3(o.timeline) || ".", { recursive: true });
1553
1713
  writeFileSync(o.timeline, JSON.stringify(result, null, 2));
1554
1714
  }
1555
1715
  return result;
@@ -1562,28 +1722,46 @@ function namedChapters(names, events, segs, endMs) {
1562
1722
  }).sort((a, b) => a.t - b.t);
1563
1723
  return starts.map((c, k) => ({ start: c.t, end: starts[k + 1]?.t ?? endMs, text: c.text }));
1564
1724
  }
1725
+ function badgeAt(W, H, w, h, at = "bottom-right") {
1726
+ const m = Math.round(Math.min(W, H) * 0.025);
1727
+ return { x: at.endsWith("left") ? m : W - w - m, y: at.startsWith("top") ? m : H - h - m };
1728
+ }
1565
1729
  async function artFor(layers, layout, o) {
1566
1730
  const art = { base: null, captions: /* @__PURE__ */ new Map() };
1567
1731
  if (!layers) return art;
1568
- if (o.frameStyle !== "none") {
1732
+ if (o.frameStyle !== "none" || layout.canvas) {
1569
1733
  art.base = /* @__PURE__ */ new Map();
1570
1734
  for (const url of o.urls.length ? o.urls : ["/"]) art.base.set(url, await layers.base(layout, { background: o.background, path: url, title: o.titles[url] }));
1571
1735
  }
1572
- const fontPx = Math.max(12, Math.round(layout.content.w * 0.026));
1736
+ const fontPx = layout.canvas ? Math.max(12, Math.round(layout.width * 0.034)) : Math.max(12, Math.round(layout.content.w * 0.026));
1737
+ const maxWidth = Math.round(layout.canvas ? layout.width * 0.9 : layout.content.w * 0.8);
1573
1738
  for (const c of o.cues) {
1574
- if (!art.captions.has(c.text)) art.captions.set(c.text, await layers.caption(c.text, { maxWidth: Math.round(layout.content.w * 0.8), fontPx }));
1739
+ if (!art.captions.has(c.text)) art.captions.set(c.text, await layers.caption(c.text, { maxWidth, fontPx }));
1575
1740
  }
1576
1741
  if (o.cards?.title) art.title = await layers.card(layout, { ...o.cards.title, background: o.background });
1577
1742
  if (o.cards?.end) art.end = await layers.card(layout, { ...o.cards.end, background: o.background });
1743
+ if (o.mark) {
1744
+ const img = await layers.badge(o.mark.text, { fontPx: Math.max(11, Math.round(Math.min(layout.width, layout.height) * 0.024)), ...o.mark.logo ? { logo: o.mark.logo } : {} });
1745
+ const { x, y } = badgeAt(layout.width, layout.height, img.width, img.height, o.mark.at);
1746
+ art.badge = { img, x, y, alpha: o.mark.opacity ?? 0.9 };
1747
+ for (const k of ["title", "end"]) {
1748
+ const c = art[k];
1749
+ if (c) {
1750
+ const d = copy(c);
1751
+ overlay(d, img, x, y, art.badge.alpha);
1752
+ art[k] = d;
1753
+ }
1754
+ }
1755
+ }
1578
1756
  return art;
1579
1757
  }
1580
1758
 
1581
1759
  // src/voice.ts
1582
1760
  import { spawnSync as spawnSync2 } from "child_process";
1583
1761
  import { createHash } from "crypto";
1584
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, mkdtempSync as mkdtempSync2, readFileSync as readFileSync4, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
1762
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, mkdtempSync as mkdtempSync2, readFileSync as readFileSync6, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
1585
1763
  import { tmpdir as tmpdir2 } from "os";
1586
- import { join as join3, resolve as resolve2 } from "path";
1764
+ import { join as join3, resolve as resolve3 } from "path";
1587
1765
  import { pathToFileURL as pathToFileURL2 } from "url";
1588
1766
  var GEMINI_TTS = { model: "gemini-2.5-flash-preview-tts", voice: "Kore" };
1589
1767
  var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -1649,7 +1827,7 @@ function sayVoice(o = {}) {
1649
1827
  const file = join3(dir, "line.wav");
1650
1828
  const r = spawnSync2("say", [...o.voice ? ["-v", o.voice] : [], "-o", file, "--file-format=WAVE", "--data-format=LEI16@24000", text], { encoding: "utf8" });
1651
1829
  if (r.error || r.status !== 0) throw new Error(`say failed${r.error ? ` (${r.error.message})` : `: ${r.stderr}`}; --voice say needs macOS`);
1652
- return fromWav(new Uint8Array(readFileSync4(file)));
1830
+ return fromWav(new Uint8Array(readFileSync6(file)));
1653
1831
  } finally {
1654
1832
  rmSync2(dir, { recursive: true, force: true });
1655
1833
  }
@@ -1661,7 +1839,7 @@ function cached(voice, id, dir) {
1661
1839
  ${text}`).digest("hex").slice(0, 32)}.wav`);
1662
1840
  if (existsSync2(file)) {
1663
1841
  v.hits += 1;
1664
- return fromWav(new Uint8Array(readFileSync4(file)));
1842
+ return fromWav(new Uint8Array(readFileSync6(file)));
1665
1843
  }
1666
1844
  const p = await voice(text);
1667
1845
  v.misses += 1;
@@ -1674,7 +1852,7 @@ ${text}`).digest("hex").slice(0, 32)}.wav`);
1674
1852
  return v;
1675
1853
  }
1676
1854
  async function voiceOf(spec, env = process.env, o = {}) {
1677
- const cacheDir = o.cacheDir === void 0 ? resolve2(".trace-avatar-cache", "voice") : o.cacheDir;
1855
+ const cacheDir = o.cacheDir === void 0 ? resolve3(".trace-avatar-cache", "voice") : o.cacheDir;
1678
1856
  const wrap = (v) => cacheDir ? cached(v, spec, cacheDir) : v;
1679
1857
  const g = /^gateway(?::gemini(?:\/([^:]+))?(?::(.+))?)?$/.exec(spec);
1680
1858
  if (g) {
@@ -1697,7 +1875,7 @@ async function voiceOf(spec, env = process.env, o = {}) {
1697
1875
  const s = /^say(?::(.+))?$/.exec(spec);
1698
1876
  if (s) return wrap(sayVoice(s[1] ? { voice: s[1] } : {}));
1699
1877
  if (/\.(m?js|cjs)$/.test(spec)) {
1700
- const mod = await import(pathToFileURL2(resolve2(spec)).href);
1878
+ const mod = await import(pathToFileURL2(resolve3(spec)).href);
1701
1879
  const fn = mod.default ?? mod.voice;
1702
1880
  if (typeof fn !== "function") throw new Error(`${spec} must export a default function (text) \u2192 { pcm: Int16Array, sampleRate }`);
1703
1881
  return wrap(fn);
@@ -1719,6 +1897,7 @@ export {
1719
1897
  paletteOf,
1720
1898
  encodeGif,
1721
1899
  createGifWriter,
1900
+ dataUri,
1722
1901
  DEFAULT_BACKGROUND,
1723
1902
  createLayers,
1724
1903
  fitWidth,
@@ -1726,6 +1905,12 @@ export {
1726
1905
  crop,
1727
1906
  pixel,
1728
1907
  layoutOf,
1908
+ CANVASES,
1909
+ CORNERS,
1910
+ canvasOf,
1911
+ watermarkOf,
1912
+ brandOf,
1913
+ brandFile,
1729
1914
  findFfmpeg,
1730
1915
  mp4Args,
1731
1916
  encodeMp4,
@@ -1767,6 +1952,7 @@ export {
1767
1952
  cardOf,
1768
1953
  render,
1769
1954
  finish,
1955
+ badgeAt,
1770
1956
  GEMINI_TTS,
1771
1957
  geminiVoice,
1772
1958
  openAiVoice,
@@ -1774,4 +1960,4 @@ export {
1774
1960
  cached,
1775
1961
  voiceOf
1776
1962
  };
1777
- //# sourceMappingURL=chunk-VTXIXGG4.js.map
1963
+ //# sourceMappingURL=chunk-2ASNE3WF.js.map