popost 4.6.15 → 4.6.16

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
@@ -265,7 +265,7 @@ var VERSION;
265
265
  var init_version = __esm({
266
266
  "src/version.ts"() {
267
267
  "use strict";
268
- VERSION = "4.6.15";
268
+ VERSION = "4.6.16";
269
269
  }
270
270
  });
271
271
 
@@ -939,6 +939,11 @@ var init_api_errors = __esm({
939
939
  "The video model does not take these settings (resolution, seconds, aspect ratio or references; popost video generate --models lists what each model takes); nothing was charged",
940
940
  "\u8BE5\u89C6\u9891\u6A21\u578B\u4E0D\u652F\u6301\u8FD9\u4E9B\u8BBE\u7F6E\uFF08\u5206\u8FA8\u7387\u3001\u65F6\u957F\u3001\u753B\u5E45\u6216\u53C2\u8003\u7D20\u6750\uFF1Bpopost video generate --models \u5217\u51FA\u5404\u6A21\u578B\u652F\u6301\u7684\u8BBE\u7F6E\uFF09\uFF0C\u672A\u6263\u8D39"
941
941
  );
942
+ case "VIDEO_REQUEST_REJECTED":
943
+ return msg(
944
+ "The video model does not take this request as it is (a reference picture or frame of a shape or size it does not take, a reference sound or clip it does not take, or a setting it does not have); sent again unchanged it fails again, and nothing is charged for it",
945
+ "\u8BE5\u89C6\u9891\u6A21\u578B\u4E0D\u63A5\u53D7\u8FD9\u4E2A\u8BF7\u6C42\uFF08\u53C2\u8003\u56FE\u6216\u9996\u5C3E\u5E27\u7684\u6BD4\u4F8B\u6216\u5C3A\u5BF8\u3001\u53C2\u8003\u97F3\u9891\u6216\u89C6\u9891\uFF0C\u6216\u67D0\u9879\u8BBE\u7F6E\u4E0D\u88AB\u652F\u6301\uFF09\uFF1B\u539F\u6837\u91CD\u53D1\u4ECD\u4F1A\u5931\u8D25\uFF0C\u4E0D\u6263\u8D39"
946
+ );
942
947
  case "GENERATION_FAILED":
943
948
  return msg("popost.ai could not make it", "popost.ai \u672A\u80FD\u751F\u6210");
944
949
  case "QUOTE_EXPIRED":
@@ -2788,7 +2793,7 @@ var init_install = __esm({
2788
2793
  await rt.fs.writeFile(rt.path.join(target2, name), data);
2789
2794
  return data.byteLength;
2790
2795
  });
2791
- const total2 = sizes.reduce((sum2, size) => sum2 + size, 0);
2796
+ const total2 = sizes.reduce((sum2, size2) => sum2 + size2, 0);
2792
2797
  if (names.length !== role.fileCount || total2 !== role.totalBytes)
2793
2798
  throw new FontError(msg(`font role ${role.id} is incomplete: ${names.length} files, ${total2} bytes`, `\u5B57\u4F53\u89D2\u8272 ${role.id} \u4E0D\u5B8C\u6574\uFF1A${names.length} \u4E2A\u6587\u4EF6\uFF0C${total2} \u5B57\u8282`));
2794
2799
  const license = await readFontAsset(rt, lib, `${role.id}/LICENSE`, role.license.sha256);
@@ -2888,7 +2893,7 @@ var init_project_fonts = __esm({
2888
2893
  if (body) return body.index;
2889
2894
  const root = /<html\b[^>]*>/i.exec(html2);
2890
2895
  if (root) return root.index + root[0].length;
2891
- for (const tag3 of html2.matchAll(/<!--[\s\S]*?-->|<(?![!?/])/g)) if (!tag3[0].startsWith("<!--")) return tag3.index;
2896
+ for (const tag4 of html2.matchAll(/<!--[\s\S]*?-->|<(?![!?/])/g)) if (!tag4[0].startsWith("<!--")) return tag4.index;
2892
2897
  return 0;
2893
2898
  };
2894
2899
  withFontLinks = (html2, links2) => {
@@ -4792,8 +4797,8 @@ var init_device_login = __esm({
4792
4797
  };
4793
4798
  startDevice = async (rt, target2, previous) => {
4794
4799
  if (previous && previous.expiresAt > Date.now()) return previous;
4795
- const pair4 = generateKeyPairSync("ed25519");
4796
- const publicKey = pair4.publicKey.export({ format: "jwk" }).x;
4800
+ const pair5 = generateKeyPairSync("ed25519");
4801
+ const publicKey = pair5.publicKey.export({ format: "jwk" }).x;
4797
4802
  const agent = target2.profile === "terminal" ? "CLI" : agentLabel(target2.profile);
4798
4803
  const label2 = [agent, rt.deviceName].filter(Boolean).join(" \xB7 ").slice(0, 80);
4799
4804
  const start = await deviceApi(rt.fetch, target2.baseUrl, "start", { label: label2, publicKey });
@@ -4802,7 +4807,7 @@ var init_device_login = __esm({
4802
4807
  publicKey,
4803
4808
  deviceCode: start.deviceCode,
4804
4809
  userCode: start.userCode,
4805
- privateKey: pair4.privateKey.export({ format: "der", type: "pkcs8" }).toString("base64url"),
4810
+ privateKey: pair5.privateKey.export({ format: "der", type: "pkcs8" }).toString("base64url"),
4806
4811
  expiresAt: Date.now() + Math.min(600, start.expiresIn) * 1e3,
4807
4812
  interval: Math.max(1, start.interval)
4808
4813
  };
@@ -5406,8 +5411,8 @@ failure: {"ok": false, "error", ...} \u76EE\u5F55\u5199\u4E0D\u8FDB\u53BB\u65F6\
5406
5411
  byDirectory = (rt, agents, homeDir2) => {
5407
5412
  const dirs = [...new Set(agents.map((agent) => agent.skillsDir(rt, homeDir2)))];
5408
5413
  return dirs.map((skillsDir) => {
5409
- const [first, ...rest] = agents.filter((agent) => agent.skillsDir(rt, homeDir2) === skillsDir).map((agent) => agent.id);
5410
- return { agent: first, skillsDir, alsoFor: rest };
5414
+ const [first2, ...rest] = agents.filter((agent) => agent.skillsDir(rt, homeDir2) === skillsDir).map((agent) => agent.id);
5415
+ return { agent: first2, skillsDir, alsoFor: rest };
5411
5416
  });
5412
5417
  };
5413
5418
  ownerOf = (rt, homeDir2, skillsDir) => {
@@ -5424,9 +5429,9 @@ failure: {"ok": false, "error", ...} \u76EE\u5F55\u5199\u4E0D\u8FDB\u53BB\u65F6\
5424
5429
  const readers = AGENTS.filter((agent) => agent.skillsDir(rt, homeDir2) === skillsDir);
5425
5430
  const here = [];
5426
5431
  for (const agent of readers) if (await present(rt, agent, homeDir2)) here.push(agent.id);
5427
- const [first, ...rest] = here;
5432
+ const [first2, ...rest] = here;
5428
5433
  const fallback = recorded2.find((entry2) => entry2.skillsDir === skillsDir)?.agent ?? (readers.length === 1 ? readers[0].id : SHARED);
5429
- targets.push({ agent: first ?? fallback, skillsDir, alsoFor: rest });
5434
+ targets.push({ agent: first2 ?? fallback, skillsDir, alsoFor: rest });
5430
5435
  }
5431
5436
  }
5432
5437
  for (const entry2 of recorded2)
@@ -5937,10 +5942,10 @@ ${OUTPUT2}`
5937
5942
  };
5938
5943
  busy = async (rt, paths) => othersRunning(rt, paths);
5939
5944
  busyMessage = (others) => {
5940
- const first = others[0];
5945
+ const first2 = others[0];
5941
5946
  return msg(
5942
- `another popost process of this installation is running (popost ${first.command}, process ${first.pid}${others.length > 1 ? `, and ${others.length - 1} more` : ""}): an open editor or Studio, or a render, would lose the files it has not loaded yet. Close it and run popost update again, or pass --force to update anyway`,
5943
- `\u8FD9\u4EFD\u5B89\u88C5\u8FD8\u6709\u5176\u4ED6 popost \u8FDB\u7A0B\u5728\u8FD0\u884C\uFF08popost ${first.command}\uFF0C\u8FDB\u7A0B ${first.pid}${others.length > 1 ? `\uFF0C\u53E6\u6709 ${others.length - 1} \u4E2A` : ""}\uFF09\uFF1A\u6253\u5F00\u7740\u7684\u7F16\u8F91\u5668\u3001Studio \u6216\u6E32\u67D3\u4F1A\u4E22\u5931\u5C1A\u672A\u52A0\u8F7D\u7684\u6587\u4EF6\u3002\u8BF7\u5148\u5173\u95ED\u5B83\u518D\u8FD0\u884C popost update\uFF0C\u6216\u52A0 --force \u5F3A\u5236\u66F4\u65B0`
5947
+ `another popost process of this installation is running (popost ${first2.command}, process ${first2.pid}${others.length > 1 ? `, and ${others.length - 1} more` : ""}): an open editor or Studio, or a render, would lose the files it has not loaded yet. Close it and run popost update again, or pass --force to update anyway`,
5948
+ `\u8FD9\u4EFD\u5B89\u88C5\u8FD8\u6709\u5176\u4ED6 popost \u8FDB\u7A0B\u5728\u8FD0\u884C\uFF08popost ${first2.command}\uFF0C\u8FDB\u7A0B ${first2.pid}${others.length > 1 ? `\uFF0C\u53E6\u6709 ${others.length - 1} \u4E2A` : ""}\uFF09\uFF1A\u6253\u5F00\u7740\u7684\u7F16\u8F91\u5668\u3001Studio \u6216\u6E32\u67D3\u4F1A\u4E22\u5931\u5C1A\u672A\u52A0\u8F7D\u7684\u6587\u4EF6\u3002\u8BF7\u5148\u5173\u95ED\u5B83\u518D\u8FD0\u884C popost update\uFF0C\u6216\u52A0 --force \u5F3A\u5236\u66F4\u65B0`
5944
5949
  );
5945
5950
  };
5946
5951
  lostLock = () => msg("another popost update took over while this one was downloading", "\u4E0B\u8F7D\u671F\u95F4\u53E6\u4E00\u4E2A popost \u66F4\u65B0\u63A5\u624B\u4E86");
@@ -6070,8 +6075,8 @@ var init_references = __esm({
6070
6075
  explicitPath = async (project, given2) => {
6071
6076
  const { rt } = project;
6072
6077
  if (await isFile(rt, rt.path.resolve(rt.cwd, given2))) return given2;
6073
- const inProject3 = rt.path.isAbsolute(given2) ? null : project.abs(given2);
6074
- if (inProject3 && await isFile(rt, inProject3)) return inProject3;
6078
+ const inProject5 = rt.path.isAbsolute(given2) ? null : project.abs(given2);
6079
+ if (inProject5 && await isFile(rt, inProject5)) return inProject5;
6075
6080
  throw unknownReference(project, given2);
6076
6081
  };
6077
6082
  noRegistered = (token, role) => {
@@ -7016,11 +7021,11 @@ var init_popost_validate = __esm({
7016
7021
  if (!stat?.isFile) throw new CapabilityError(msg(`the local reference image does not exist: ${path2}`, `\u672C\u5730\u53C2\u8003\u56FE\u4E0D\u5B58\u5728: ${path2}`));
7017
7022
  const name = rt.path.basename(path2);
7018
7023
  if (stat.size > MAX_REF_BYTES) {
7019
- const [size, limit] = [(stat.size / 1048576).toFixed(1), MAX_REF_BYTES / 1048576];
7024
+ const [size2, limit] = [(stat.size / 1048576).toFixed(1), MAX_REF_BYTES / 1048576];
7020
7025
  throw new CapabilityError(
7021
7026
  msg(
7022
- `the reference image ${name} is ${size} MiB, more than the ${limit} MiB limit per image; compress it or use an https URL instead`,
7023
- `\u53C2\u8003\u56FE ${name} \u4E3A ${size} MiB\uFF0C\u8D85\u8FC7\u5355\u5F20 ${limit} MiB \u4E0A\u9650\uFF1B\u8BF7\u538B\u7F29\u6216\u6539\u7528 https URL`
7027
+ `the reference image ${name} is ${size2} MiB, more than the ${limit} MiB limit per image; compress it or use an https URL instead`,
7028
+ `\u53C2\u8003\u56FE ${name} \u4E3A ${size2} MiB\uFF0C\u8D85\u8FC7\u5355\u5F20 ${limit} MiB \u4E0A\u9650\uFF1B\u8BF7\u538B\u7F29\u6216\u6539\u7528 https URL`
7024
7029
  )
7025
7030
  );
7026
7031
  }
@@ -7045,8 +7050,8 @@ var init_popost_validate = __esm({
7045
7050
  total2 += await checkLocalRef(rt, ref.value);
7046
7051
  }
7047
7052
  if (total2 > MAX_REF_TOTAL_BYTES) {
7048
- const [size, limit2] = [(total2 / 1048576).toFixed(1), MAX_REF_TOTAL_BYTES / 1048576];
7049
- throw new CapabilityError(msg(`the local reference images add up to ${size} MiB, more than the ${limit2} MiB limit`, `\u672C\u5730\u53C2\u8003\u56FE\u5408\u8BA1 ${size} MiB\uFF0C\u8D85\u8FC7 ${limit2} MiB \u4E0A\u9650`));
7053
+ const [size2, limit2] = [(total2 / 1048576).toFixed(1), MAX_REF_TOTAL_BYTES / 1048576];
7054
+ throw new CapabilityError(msg(`the local reference images add up to ${size2} MiB, more than the ${limit2} MiB limit`, `\u672C\u5730\u53C2\u8003\u56FE\u5408\u8BA1 ${size2} MiB\uFF0C\u8D85\u8FC7 ${limit2} MiB \u4E0A\u9650`));
7050
7055
  }
7051
7056
  };
7052
7057
  }
@@ -7612,8 +7617,8 @@ var init_context = __esm({
7612
7617
  return { existing, add: add2, final: [...existing, ...add2] };
7613
7618
  };
7614
7619
  pageSize = (ctx) => {
7615
- const first = ctx.project?.manifest.pages[0];
7616
- return { width: ctx.spec.width ?? first?.width ?? 1080, height: ctx.spec.height ?? first?.height ?? 1350 };
7620
+ const first2 = ctx.project?.manifest.pages[0];
7621
+ return { width: ctx.spec.width ?? first2?.width ?? 1080, height: ctx.spec.height ?? first2?.height ?? 1350 };
7617
7622
  };
7618
7623
  }
7619
7624
  });
@@ -9503,11 +9508,11 @@ var init_steps = __esm({
9503
9508
  const project = await Project.create(rt, ctx.dir, spec10.brief, mode, spec10.width, spec10.height);
9504
9509
  await project.appendDesignNote(initDesignNote());
9505
9510
  ctx.project = project;
9506
- const first = project.manifest.pages[0];
9511
+ const first2 = project.manifest.pages[0];
9507
9512
  return done(
9508
9513
  msg(
9509
- `created the project (${mode} mode) with page p1 (${first.width}x${first.height})`,
9510
- `\u5DF2\u521B\u5EFA\u9879\u76EE\uFF08${mode} \u6A21\u5F0F\uFF09\uFF0C\u542B\u9875 p1\uFF08${first.width}x${first.height}\uFF09`
9514
+ `created the project (${mode} mode) with page p1 (${first2.width}x${first2.height})`,
9515
+ `\u5DF2\u521B\u5EFA\u9879\u76EE\uFF08${mode} \u6A21\u5F0F\uFF09\uFF0C\u542B\u9875 p1\uFF08${first2.width}x${first2.height}\uFF09`
9511
9516
  )
9512
9517
  );
9513
9518
  };
@@ -10849,13 +10854,13 @@ var init_push = __esm({
10849
10854
  };
10850
10855
  };
10851
10856
  syncBody = (project, html2, pictures, ids3, options) => {
10852
- const first = project.manifest.pages[0];
10857
+ const first2 = project.manifest.pages[0];
10853
10858
  const brief3 = Array.from(String(project.manifest.brief ?? "").replace(/\s+/g, " ").trim()).slice(0, TITLE_CHARS).join("");
10854
10859
  return {
10855
10860
  projectId: project.manifest.projectId,
10856
10861
  title: brief3 || "Popost",
10857
- width: first.width,
10858
- height: first.height,
10862
+ width: first2.width,
10863
+ height: first2.height,
10859
10864
  platform: typeof project.manifest.platform === "string" && project.manifest.platform ? project.manifest.platform : null,
10860
10865
  html: html2,
10861
10866
  assets: pictures.map((p) => ({ url: p.url, uploadId: ids3.get(p.sha) })),
@@ -11343,12 +11348,12 @@ var init_handoff = __esm({
11343
11348
  await writeJson(rt, serviceState(rt, root), { url, ...pid !== void 0 ? { pid } : {}, version: EDITOR_VERSION });
11344
11349
  };
11345
11350
  editorInfo = (project) => {
11346
- const identity = sha256(project.rt.path.resolve(project.root));
11351
+ const identity2 = sha256(project.rt.path.resolve(project.root));
11347
11352
  return {
11348
11353
  schema: "popost-editor-info.v1",
11349
11354
  version: EDITOR_VERSION,
11350
- projectId: project.manifest.projectId || identity.slice(0, 32),
11351
- projectIdentity: identity,
11355
+ projectId: project.manifest.projectId || identity2.slice(0, 32),
11356
+ projectIdentity: identity2,
11352
11357
  capabilities: ["edit-text", "edit-layout", "save-local", "export-png", "export-formats", "compare-reference", "export-project", "cloud-save"]
11353
11358
  };
11354
11359
  };
@@ -12041,8 +12046,8 @@ var init_routes_post = __esm({
12041
12046
  staleFonts = () => msg("The project was changed by another window or by the agent. Reload it, then choose the fonts.", "\u5DE5\u7A0B\u5DF2\u88AB\u53E6\u4E00\u7A97\u53E3\u6216 Agent \u4FEE\u6539\uFF0C\u8BF7\u91CD\u65B0\u52A0\u8F7D\u540E\u9009\u62E9\u5B57\u4F53\u3002");
12042
12047
  failure = (ctx, error2, kind = "bad-or-server") => jsonResponse(ctx.req, isBadRequest(error2) || kind === "bad-only" ? 400 : 500, { ok: false, error: errorMessage(error2) });
12043
12048
  canvasPreview = async (ctx) => {
12044
- const size = ctx.req.body.byteLength;
12045
- if (!(size > 0 && size <= MAX_PREVIEW_BYTES))
12049
+ const size2 = ctx.req.body.byteLength;
12050
+ if (!(size2 > 0 && size2 <= MAX_PREVIEW_BYTES))
12046
12051
  return jsonResponse(ctx.req, 413, { ok: false, error: msg("preview is empty or too large", "\u9884\u89C8\u5185\u5BB9\u4E3A\u7A7A\u6216\u8FC7\u5927") });
12047
12052
  try {
12048
12053
  const data = parseJsonObject(ctx.req);
@@ -12192,10 +12197,10 @@ var init_server = __esm({
12192
12197
  const declared = Number(req.headers["content-length"] ?? 0);
12193
12198
  if (declared > limit) return resolve2(null);
12194
12199
  const chunks = [];
12195
- let size = 0;
12200
+ let size2 = 0;
12196
12201
  req.on("data", (chunk) => {
12197
- size += chunk.byteLength;
12198
- if (size > limit) {
12202
+ size2 += chunk.byteLength;
12203
+ if (size2 > limit) {
12199
12204
  chunks.length = 0;
12200
12205
  req.pause();
12201
12206
  return resolve2(null);
@@ -12203,7 +12208,7 @@ var init_server = __esm({
12203
12208
  chunks.push(chunk);
12204
12209
  });
12205
12210
  req.on("end", () => {
12206
- const body = new Uint8Array(size);
12211
+ const body = new Uint8Array(size2);
12207
12212
  let offset = 0;
12208
12213
  for (const chunk of chunks) {
12209
12214
  body.set(chunk, offset);
@@ -12368,13 +12373,13 @@ var init_render = __esm({
12368
12373
  };
12369
12374
  };
12370
12375
  syncDelivered = async (rt, project) => !commandSyncs(rt) ? void 0 : deliverToCloud(new CloudService(rt, () => project.root), project.manifest.language?.toLowerCase().startsWith("zh") ? "zh" : "en");
12371
- rendering = (spec10, prepare4 = false) => ({
12376
+ rendering = (spec10, prepare5 = false) => ({
12372
12377
  spec: { ...spec10, options: [DIR3, ...spec10.options ?? []] },
12373
12378
  run: async (args, rt) => {
12374
12379
  const project = await Project.load(rt, args.req("dir"));
12375
12380
  let before = {};
12376
12381
  try {
12377
- if (prepare4) before = await prepareRender(project, args);
12382
+ if (prepare5) before = await prepareRender(project, args);
12378
12383
  const final = args.flag("final");
12379
12384
  if (final) await requireReadyToDeliver(project);
12380
12385
  const exported = await exportPages(project, args, rt);
@@ -12551,9 +12556,9 @@ var init_sheet_layout = __esm({
12551
12556
  let bestCost = Infinity;
12552
12557
  for (let columns = 1; columns <= Math.min(count5, widest); columns++) {
12553
12558
  const rows3 = Math.ceil(count5 / columns);
12554
- const size = sheetSize(columns, rows3, cellFor(columns, aspect));
12559
+ const size2 = sheetSize(columns, rows3, cellFor(columns, aspect));
12555
12560
  const empty = (rows3 * columns - count5) / (rows3 * columns);
12556
- const cost = Math.abs(Math.log(size.width / size.height / TARGET_ASPECT)) + EMPTY_CELL_PENALTY * empty;
12561
+ const cost = Math.abs(Math.log(size2.width / size2.height / TARGET_ASPECT)) + EMPTY_CELL_PENALTY * empty;
12557
12562
  if (cost < bestCost - 1e-9) {
12558
12563
  best = columns;
12559
12564
  bestCost = cost;
@@ -12568,7 +12573,7 @@ var init_sheet_layout = __esm({
12568
12573
  const budget = (widthPx - fontPx * 1.2) / fontPx;
12569
12574
  if (emSum(chars) <= budget) return label2;
12570
12575
  const room = Math.max(1, budget - 1);
12571
- const take = (source2, limit) => {
12576
+ const take2 = (source2, limit) => {
12572
12577
  const taken = [];
12573
12578
  let used = 0;
12574
12579
  for (const char of source2) {
@@ -12578,8 +12583,8 @@ var init_sheet_layout = __esm({
12578
12583
  }
12579
12584
  return taken;
12580
12585
  };
12581
- const head = take(chars, room * 0.6);
12582
- const tail4 = take([...chars].reverse(), room * 0.4).reverse();
12586
+ const head = take2(chars, room * 0.6);
12587
+ const tail4 = take2([...chars].reverse(), room * 0.4).reverse();
12583
12588
  return `${head.join("")}\u2026${tail4.join("")}`;
12584
12589
  };
12585
12590
  layoutSheet = (bands) => {
@@ -12740,8 +12745,8 @@ var init_sheet2 = __esm({
12740
12745
  const only = bands.length === 1 ? bands[0] : void 0;
12741
12746
  if (!only || only.length <= MAX_SHEET_IMAGES) return [bands];
12742
12747
  const count5 = Math.ceil(only.length / MAX_SHEET_IMAGES);
12743
- const size = Math.ceil(only.length / count5);
12744
- return Array.from({ length: count5 }, (_, k) => [only.slice(k * size, (k + 1) * size)]);
12748
+ const size2 = Math.ceil(only.length / count5);
12749
+ return Array.from({ length: count5 }, (_, k) => [only.slice(k * size2, (k + 1) * size2)]);
12745
12750
  };
12746
12751
  partPath = (path2, k) => k === 0 ? path2 : path2.replace(/(\.jpe?g)$/i, `-${k + 1}$1`);
12747
12752
  drawSheets = async (rt, parts, target2, shown3) => {
@@ -13069,8 +13074,8 @@ var init_image_info = __esm({
13069
13074
  SVG_HEAD_BYTES = 65536;
13070
13075
  SVG_ROOT = /^\uFEFF?\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*(?:<!DOCTYPE[^>[]*(?:\[[^\]]*\])?\s*>\s*)?(?:<!--[\s\S]*?-->\s*)*(<svg\b(?:[^>"']|"[^"]*"|'[^']*')*>)/i;
13071
13076
  UNIT_PX = { "": 1, px: 1, pt: 4 / 3, pc: 16, mm: 96 / 25.4, cm: 96 / 2.54, in: 96 };
13072
- attribute = (tag3, name) => {
13073
- const match = new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, "i").exec(tag3);
13077
+ attribute = (tag4, name) => {
13078
+ const match = new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, "i").exec(tag4);
13074
13079
  return match ? match[1] ?? match[2] : void 0;
13075
13080
  };
13076
13081
  lengthPx = (value) => {
@@ -13079,18 +13084,18 @@ var init_image_info = __esm({
13079
13084
  const px2 = Number(match[1]) * UNIT_PX[(match[2] ?? "").toLowerCase()];
13080
13085
  return px2 > 0 ? Math.round(px2 * 100) / 100 : void 0;
13081
13086
  };
13082
- viewBoxSize = (tag3) => {
13083
- const numbers3 = (attribute(tag3, "viewBox") ?? "").trim().split(/[\s,]+/).map(Number);
13087
+ viewBoxSize = (tag4) => {
13088
+ const numbers3 = (attribute(tag4, "viewBox") ?? "").trim().split(/[\s,]+/).map(Number);
13084
13089
  const [width, height] = [numbers3[2], numbers3[3]];
13085
13090
  return numbers3.length === 4 && width > 0 && height > 0 ? { width, height } : void 0;
13086
13091
  };
13087
13092
  svgOf = (bytes) => {
13088
13093
  const root = SVG_ROOT.exec(new TextDecoder().decode(bytes.subarray(0, SVG_HEAD_BYTES)));
13089
13094
  if (!root) return null;
13090
- const tag3 = root[1];
13091
- const box2 = viewBoxSize(tag3);
13092
- const width = lengthPx(attribute(tag3, "width")) ?? box2?.width;
13093
- const height = lengthPx(attribute(tag3, "height")) ?? box2?.height;
13095
+ const tag4 = root[1];
13096
+ const box2 = viewBoxSize(tag4);
13097
+ const width = lengthPx(attribute(tag4, "width")) ?? box2?.width;
13098
+ const height = lengthPx(attribute(tag4, "height")) ?? box2?.height;
13094
13099
  return { format: "svg", ...width !== void 0 && height !== void 0 ? { width, height } : {} };
13095
13100
  };
13096
13101
  describePicture = (bytes, name) => {
@@ -13181,11 +13186,11 @@ var init_edit = __esm({
13181
13186
  const page2 = await context.newPage();
13182
13187
  await page2.setContent(sourceHtml(source2), { waitUntil: "load", timeout: 3e4 });
13183
13188
  await settlePage(page2);
13184
- const size = await callInPage(page2, SIZE_SCRIPT);
13185
- if (!size.width || !size.height) throw new ValueError(msg("the picture could not be decoded", "\u56FE\u7247\u65E0\u6CD5\u89E3\u7801"));
13186
- const planned = plan4(size.width, size.height);
13189
+ const size2 = await callInPage(page2, SIZE_SCRIPT);
13190
+ if (!size2.width || !size2.height) throw new ValueError(msg("the picture could not be decoded", "\u56FE\u7247\u65E0\u6CD5\u89E3\u7801"));
13191
+ const planned = plan4(size2.width, size2.height);
13187
13192
  const url = await callInPage(page2, DRAW_SCRIPT, { plan: planned, output });
13188
- return { bytes: decodeDataUrl(url, output.format), plan: planned, source: size };
13193
+ return { bytes: decodeDataUrl(url, output.format), plan: planned, source: size2 };
13189
13194
  } finally {
13190
13195
  await context.close();
13191
13196
  }
@@ -13410,8 +13415,8 @@ var init_info = __esm({
13410
13415
  init_io();
13411
13416
  locate = async (rt, file, dir) => {
13412
13417
  if (dir === void 0 || rt.path.isAbsolute(file) || await isFile(rt, rt.path.resolve(rt.cwd, file))) return file;
13413
- const inProject3 = rt.path.resolve(rt.cwd, dir, file);
13414
- return await isFile(rt, inProject3) ? inProject3 : file;
13418
+ const inProject5 = rt.path.resolve(rt.cwd, dir, file);
13419
+ return await isFile(rt, inProject5) ? inProject5 : file;
13415
13420
  };
13416
13421
  describeFile = async (rt, file, dir) => {
13417
13422
  try {
@@ -13988,8 +13993,8 @@ var init_inspiration_plan = __esm({
13988
13993
  tagsOf = (raw) => {
13989
13994
  const out2 = [];
13990
13995
  for (const item2 of Array.isArray(raw) ? raw : []) {
13991
- const tag3 = String(item2).trim().replace(/^#+/, "").trim();
13992
- if (tag3 && !out2.includes(tag3)) out2.push(tag3);
13996
+ const tag4 = String(item2).trim().replace(/^#+/, "").trim();
13997
+ if (tag4 && !out2.includes(tag4)) out2.push(tag4);
13993
13998
  }
13994
13999
  if (out2.length > LIMITS.tags) throw new InputError(msg(`more than ${LIMITS.tags} tags`, `tags \u8D85\u8FC7 ${LIMITS.tags} \u4E2A`));
13995
14000
  return out2;
@@ -14262,15 +14267,15 @@ var init_link_bundle = __esm({
14262
14267
  tagsOf2 = (raw) => {
14263
14268
  const out2 = [];
14264
14269
  for (const item2 of Array.isArray(raw) ? raw : []) {
14265
- const tag3 = typeof item2 === "string" ? item2.trim().replace(/^#+/, "").trim() : "";
14266
- if (tag3 && !out2.includes(tag3)) out2.push(tag3);
14270
+ const tag4 = typeof item2 === "string" ? item2.trim().replace(/^#+/, "").trim() : "";
14271
+ if (tag4 && !out2.includes(tag4)) out2.push(tag4);
14267
14272
  }
14268
14273
  return out2.slice(0, LIMITS.tags);
14269
14274
  };
14270
14275
  imageOf = (raw, index) => {
14271
14276
  if (!isRecord(raw) || typeof raw.url !== "string" || !raw.url) throw badResponse(msg(`picture ${index + 1} of the parsed result has no address`, `\u89E3\u6790\u7ED3\u679C\u7684\u7B2C ${index + 1} \u5F20\u56FE\u7247\u7F3A\u5C11\u5730\u5740`));
14272
- const size = (key2) => isInt(raw[key2]) && raw[key2] > 0 ? { [key2]: raw[key2] } : {};
14273
- return { url: raw.url, ...typeof raw.mimeType === "string" ? { mimeType: raw.mimeType } : {}, ...size("width"), ...size("height"), ...text3(raw.alt) ? { alt: [...text3(raw.alt)].slice(0, 500).join("") } : {} };
14277
+ const size2 = (key2) => isInt(raw[key2]) && raw[key2] > 0 ? { [key2]: raw[key2] } : {};
14278
+ return { url: raw.url, ...typeof raw.mimeType === "string" ? { mimeType: raw.mimeType } : {}, ...size2("width"), ...size2("height"), ...text3(raw.alt) ? { alt: [...text3(raw.alt)].slice(0, 500).join("") } : {} };
14274
14279
  };
14275
14280
  validPublishedAt = (value) => {
14276
14281
  try {
@@ -14368,7 +14373,7 @@ var init_link_bundle = __esm({
14368
14373
  });
14369
14374
  videoResource = (v) => ({ id: "video", kind: "video", path: v.file, mimeType: v.mimeType, sha256: v.sha256, bytes: v.bytes });
14370
14375
  buildBundle = (rt, plan4, saved, video) => {
14371
- const first = saved[0];
14376
+ const first2 = saved[0];
14372
14377
  const complete3 = saved.length > 0;
14373
14378
  return {
14374
14379
  schema: "postbundle.v1",
@@ -14379,7 +14384,7 @@ var init_link_bundle = __esm({
14379
14384
  tags: plan4.tags,
14380
14385
  music: { title: "", url: "" },
14381
14386
  pageOrder: saved.map((s) => s.index),
14382
- ratio: first?.width && first.height ? ratioOf(first.width, first.height) : null,
14387
+ ratio: first2?.width && first2.height ? ratioOf(first2.width, first2.height) : null,
14383
14388
  resources: [...saved.map(pictureResource), ...video ? [videoResource(video)] : []],
14384
14389
  parseStatus: complete3 ? "ready" : "missing_resources",
14385
14390
  auth: {
@@ -14512,17 +14517,17 @@ var init_link_resolve = __esm({
14512
14517
  const code = Number.parseInt(hex3 ?? dec ?? "", hex3 ? 16 : 10);
14513
14518
  return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : whole2;
14514
14519
  });
14515
- attributeOf = (tag3, name) => {
14516
- const match = new RegExp(`[\\s"']${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`, "i").exec(tag3);
14520
+ attributeOf = (tag4, name) => {
14521
+ const match = new RegExp(`[\\s"']${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`, "i").exec(tag4);
14517
14522
  const value = match?.[1] ?? match?.[2] ?? match?.[3];
14518
14523
  return value === void 0 ? null : decodeEntities(value).trim();
14519
14524
  };
14520
14525
  REFRESH_CONTENT = /^\s*\d+(?:\.\d+)?\s*[;,]\s*(?:url\s*=\s*)?(["']?)(.+?)\1\s*$/i;
14521
14526
  JS_LOCATION = /\blocation(?:\.replace\(\s*|(?:\.href)?\s*=\s*)(?:"((?:[^"\\\n]|\\.)*)"|'((?:[^'\\\n]|\\.)*)')/;
14522
14527
  metaRefreshOf = (html2) => {
14523
- for (const [tag3] of html2.matchAll(/<meta\b[^>]*>/gi)) {
14524
- if (attributeOf(tag3, "http-equiv")?.toLowerCase() !== "refresh") continue;
14525
- const target2 = REFRESH_CONTENT.exec(attributeOf(tag3, "content") ?? "")?.[2];
14528
+ for (const [tag4] of html2.matchAll(/<meta\b[^>]*>/gi)) {
14529
+ if (attributeOf(tag4, "http-equiv")?.toLowerCase() !== "refresh") continue;
14530
+ const target2 = REFRESH_CONTENT.exec(attributeOf(tag4, "content") ?? "")?.[2];
14526
14531
  if (target2) return target2;
14527
14532
  }
14528
14533
  return null;
@@ -14709,12 +14714,12 @@ var init_link_task = __esm({
14709
14714
  throw new PopostApiError(msg("the GET /links/parse answer has an unexpected format (no task, or a different id)", "GET /links/parse \u54CD\u5E94\u683C\u5F0F\u4E0D\u7B26\uFF08\u7F3A\u5C11 task \u6216 id \u4E0D\u4E00\u81F4\uFF09"), { code: "BAD_RESPONSE" });
14710
14715
  return task;
14711
14716
  };
14712
- waitForTask2 = async (rt, client2, id2, first, timeoutSec) => {
14717
+ waitForTask2 = async (rt, client2, id2, first2, timeoutSec) => {
14713
14718
  const timeoutMs = timeoutSec * 1e3;
14714
14719
  const started = rt.now().getTime();
14715
- let last = first;
14720
+ let last = first2;
14716
14721
  let failures = 0;
14717
- let pauseMs = first !== null ? POLL_INTERVAL_MS : 0;
14722
+ let pauseMs = first2 !== null ? POLL_INTERVAL_MS : 0;
14718
14723
  for (; ; ) {
14719
14724
  if (last && isTerminal(last)) return { kind: "done", task: last };
14720
14725
  const elapsed = rt.now().getTime() - started;
@@ -14899,9 +14904,9 @@ var init_link = __esm({
14899
14904
  const post = { platform: plan4.platform, ...plan4.kind ? { kind: plan4.kind } : {}, title: plan4.title, sourceUrl: plan4.sourceUrl, imageCount: saved.length, ...plan4.inspirationId ? { inspirationId: plan4.inspirationId } : {} };
14900
14905
  return { exit: 0, body: { ok: true, task: info, bundle: bundlePath, images, ...video.fields, post, next: `popost validate --file ${file} && popost import --file ${file}`, note: note + video.note } };
14901
14906
  };
14902
- finish2 = async (rt, client2, state2, first, call2, fallback) => {
14907
+ finish2 = async (rt, client2, state2, first2, call2, fallback) => {
14903
14908
  const id2 = state2.id;
14904
- const waited = await waitForTask2(rt, client2, id2, first, call2.timeoutSec);
14909
+ const waited = await waitForTask2(rt, client2, id2, first2, call2.timeoutSec);
14905
14910
  if (waited.task) state2.task = waited.task;
14906
14911
  if (waited.kind === "timeout")
14907
14912
  return unfinishedOutcome("WAIT_TIMEOUT", msg(`The task had not finished after ${call2.timeoutSec} seconds.`, `\u7B49\u5F85 ${call2.timeoutSec} \u79D2\u540E\u4EFB\u52A1\u4ECD\u672A\u7ED3\u675F\u3002`), id2, waited.task, call2);
@@ -15899,8 +15904,8 @@ var init_import_deck = __esm({
15899
15904
  noSlide = () => msg("the document has no .slide page: nothing to import", "\u6587\u6863\u91CC\u6CA1\u6709 .slide \u9875\u9762\uFF1A\u6CA1\u6709\u53EF\u5BFC\u5165\u7684\u5185\u5BB9");
15900
15905
  FALLBACK_SIZE = { width: 1080, height: 1350 };
15901
15906
  defaultSizeOf = (project) => {
15902
- const first = project.manifest.pages[0];
15903
- return first ? { width: Number(first.width), height: Number(first.height) } : FALLBACK_SIZE;
15907
+ const first2 = project.manifest.pages[0];
15908
+ return first2 ? { width: Number(first2.width), height: Number(first2.height) } : FALLBACK_SIZE;
15904
15909
  };
15905
15910
  validSize2 = (n) => Number.isInteger(n) && n >= 1 && n <= MAX_CANVAS;
15906
15911
  checkSizes = (pages) => {
@@ -16350,9 +16355,9 @@ var init_camera = __esm({
16350
16355
  return { scale: s, translate: [(1 - s) * (m.focus[0] - 0.5) + (shift[0] ?? 0), (1 - s) * (m.focus[1] - 0.5) + (shift[1] ?? 0)] };
16351
16356
  };
16352
16357
  movesAt = (moves, n) => {
16353
- const first = moves[0];
16354
- if (!first) return STILL_CAMERA;
16355
- const current = [...moves].reverse().find((m) => n >= m.from) ?? first;
16358
+ const first2 = moves[0];
16359
+ if (!first2) return STILL_CAMERA;
16360
+ const current = [...moves].reverse().find((m) => n >= m.from) ?? first2;
16356
16361
  const t = n < current.from ? 0 : clamp01((n - current.from) / Math.max(1, current.to - current.from));
16357
16362
  return moveState(current, ease(current.ease, t));
16358
16363
  };
@@ -16413,9 +16418,9 @@ var init_frame = __esm({
16413
16418
  const into = seg?.transition;
16414
16419
  const next = r.segments[k + 1]?.transition;
16415
16420
  if (!seg) return [0, 0];
16416
- const first = into && (into.side ?? "both") === "both" ? into.a : seg.start;
16421
+ const first2 = into && (into.side ?? "both") === "both" ? into.a : seg.start;
16417
16422
  const last = next && (next.side ?? "both") === "both" ? next.a + next.frames - 1 : seg.end - 1;
16418
- return [first, last];
16423
+ return [first2, last];
16419
16424
  };
16420
16425
  cameraAt = (r, k, n) => {
16421
16426
  const base = r.segments[k]?.base;
@@ -16480,18 +16485,18 @@ var init_footage = __esm({
16480
16485
  playsOf = (r) => [
16481
16486
  ...r.segments.flatMap((s, k) => {
16482
16487
  if (s.base.kind !== "video") return [];
16483
- const [first, last] = visibleRange(r, k);
16484
- return [{ play: s.base.play, first, last }];
16488
+ const [first2, last] = visibleRange(r, k);
16489
+ return [{ play: s.base.play, first: first2, last }];
16485
16490
  }),
16486
16491
  ...r.items.flatMap((it) => it.play && it.end > it.start ? [{ play: it.play, first: it.start, last: it.end - 1 }] : [])
16487
16492
  ];
16488
16493
  usedFrames = (r) => {
16489
16494
  const sets = /* @__PURE__ */ new Map();
16490
- for (const { play, first, last } of playsOf(r)) {
16495
+ for (const { play, first: first2, last } of playsOf(r)) {
16491
16496
  const f = r.footage?.[play.material];
16492
16497
  if (!f) continue;
16493
16498
  const set2 = sets.get(play.material) ?? /* @__PURE__ */ new Set();
16494
- for (let n = Math.max(0, first); n <= Math.min(last, r.frames - 1); n++) set2.add(sourceFrame(play, f, r.canvas.fps, n));
16499
+ for (let n = Math.max(0, first2); n <= Math.min(last, r.frames - 1); n++) set2.add(sourceFrame(play, f, r.canvas.fps, n));
16495
16500
  sets.set(play.material, set2);
16496
16501
  }
16497
16502
  return new Map([...sets].map(([id2, set2]) => [id2, [...set2].sort((a, b) => a - b)]));
@@ -16730,14 +16735,14 @@ var init_project2 = __esm({
16730
16735
  const frames = await sweepFrames(rt, root, { started: Infinity, drop: true, capBytes: Infinity, ...o.dryRun ? { dryRun: true } : {} });
16731
16736
  if (frames.removed.length < all.length) kept3.push(FOOTAGE_CACHE + ": " + (all.length - frames.removed.length) + " in use by a running " + (holds.kinds.includes("preview") ? "preview" : "render"));
16732
16737
  const busy3 = (f) => holds.kinds.length > 0 || holds.unknown || f.used > now - HOLD_TTL_MS;
16733
- const take = async (found, rel2) => {
16738
+ const take2 = async (found, rel2) => {
16734
16739
  const free = found.filter((f) => !busy3(f));
16735
16740
  if (free.length < found.length) kept3.push(rel2 + ": " + (found.length - free.length) + " in use or just written");
16736
16741
  if (!o.dryRun) for (const f of free) await rt.fs.rm(rt.path.join(root, rel2, f.name));
16737
16742
  return free;
16738
16743
  };
16739
- const chunks = await take(await chunkSets(rt, root), CHUNK_DIR);
16740
- const made = await take(await drafts(rt, root), DRAFTS);
16744
+ const chunks = await take2(await chunkSets(rt, root), CHUNK_DIR);
16745
+ const made = await take2(await drafts(rt, root), DRAFTS);
16741
16746
  if (!o.dryRun) {
16742
16747
  for (const rel2 of [FOOTAGE_CACHE + "/" + HOLDS_DIR, FOOTAGE_CACHE, CHUNK_DIR, ".cache", DRAFTS]) if (await isPlainInside(rt, root, rt.path.join(root, rel2))) await removeEmpty(rt, rt.path.join(root, rel2));
16743
16748
  }
@@ -16855,22 +16860,22 @@ var init_ffmpeg = __esm({
16855
16860
  const rows3 = crc.split("\n").filter((line) => line.trim() && !line.startsWith("#"));
16856
16861
  const tb = crc.match(/^#tb\s+0:\s*(\d+\/\d+)/m)?.[1];
16857
16862
  const ticks = tb ? rational(tb) : 0;
16858
- let first = Infinity, end = -Infinity;
16863
+ let first2 = Infinity, end = -Infinity;
16859
16864
  for (const row of rows3) {
16860
16865
  const parts = row.split(",").map((s) => s.trim());
16861
16866
  const pts = Number(parts[2]), duration2 = Number(parts[3]);
16862
16867
  if (parts.length < 4 || !Number.isFinite(pts) || !Number.isFinite(duration2) || duration2 <= 0) return { frames: rows3.length };
16863
- first = Math.min(first, pts);
16868
+ first2 = Math.min(first2, pts);
16864
16869
  end = Math.max(end, pts + duration2);
16865
16870
  }
16866
- const duration = (end - first) * ticks;
16871
+ const duration = (end - first2) * ticks;
16867
16872
  return duration > 0 && Number.isFinite(duration) ? { frames: rows3.length, duration, fps: rows3.length / duration } : { frames: rows3.length };
16868
16873
  };
16869
16874
  probe2 = async (rt, file) => {
16870
16875
  const r = await runFfmpeg(rt, ["-i", file, "-map", "0:v:0", "-c", "copy", "-f", "framecrc", "-"]);
16871
16876
  const video = r.stderr.match(/Stream #0:\d+[^\n]*: Video: [^\n]*/);
16872
16877
  if (!video) throw new FfmpegError("No video stream found in " + file, r.stderr);
16873
- const size = video[0].match(/, (\d{2,5})x(\d{2,5})[ ,[]/);
16878
+ const size2 = video[0].match(/, (\d{2,5})x(\d{2,5})[ ,[]/);
16874
16879
  const fpsText = video[0].match(/, ([\d.]+) fps/)?.[1] ?? video[0].match(/, ([\d.]+) tbr/)?.[1];
16875
16880
  const reportedAverage = video[0].match(/, ([\d.]+) fps/)?.[1];
16876
16881
  const rate = r.stderr.match(/r_frame_rate=(\d+\/\d+)/)?.[1];
@@ -16878,11 +16883,11 @@ var init_ffmpeg = __esm({
16878
16883
  const frames = clock4.frames;
16879
16884
  const d = r.stderr.match(/Duration: (\d+):(\d+):([\d.]+)/);
16880
16885
  const duration = d ? Number(d[1]) * 3600 + Number(d[2]) * 60 + Number(d[3]) : 0;
16881
- if (!size || !fpsText) throw new FfmpegError("Could not read the size or frame rate of " + file, r.stderr);
16886
+ if (!size2 || !fpsText) throw new FfmpegError("Could not read the size or frame rate of " + file, r.stderr);
16882
16887
  const precision = reportedAverage ? Math.min(5e-3, 0.5 / 10 ** (reportedAverage.split(".")[1]?.length ?? 0)) : Infinity;
16883
16888
  const edited = clock4.fps !== void 0 && reportedAverage !== void 0 && Math.abs(clock4.fps - Number(reportedAverage)) > precision + 1e-9;
16884
16889
  const fps = edited ? Number(reportedAverage) : clock4.fps ?? (rate ? rational(rate) : Number(fpsText));
16885
- return { width: Number(size[1]), height: Number(size[2]), fps, frames, duration: frames && fps ? frames / fps : duration, hasAudio: /Stream #0:\d+[^\n]*: Audio:/.test(r.stderr) };
16890
+ return { width: Number(size2[1]), height: Number(size2[2]), fps, frames, duration: frames && fps ? frames / fps : duration, hasAudio: /Stream #0:\d+[^\n]*: Audio:/.test(r.stderr) };
16886
16891
  };
16887
16892
  }
16888
16893
  });
@@ -17113,9 +17118,9 @@ var init_words = __esm({
17113
17118
  for (let k = 0; k + units2.length <= tokens3.length; k++) if (units2.every((u, q) => tokens3[k + q]?.key === u)) out2.push(k);
17114
17119
  return out2;
17115
17120
  };
17116
- placeAt = (tokens3, first, count5) => {
17117
- const part = tokens3.slice(first, first + count5);
17118
- return { first, last: first + count5 - 1, start: part[0]?.start ?? 0, end: part[part.length - 1]?.end ?? 0, confidence: Math.min(...part.map((t) => t.confidence)) };
17121
+ placeAt = (tokens3, first2, count5) => {
17122
+ const part = tokens3.slice(first2, first2 + count5);
17123
+ return { first: first2, last: first2 + count5 - 1, start: part[0]?.start ?? 0, end: part[part.length - 1]?.end ?? 0, confidence: Math.min(...part.map((t) => t.confidence)) };
17119
17124
  };
17120
17125
  phraseFrames = (tl, place4, span2) => framesOf(tl, place4.start - (span2.lead ?? 0), place4.end + (span2.hold ?? 0));
17121
17126
  findPhrase = (tokens3, span2) => {
@@ -17840,12 +17845,12 @@ var init_check3 = __esm({
17840
17845
  init_check_words();
17841
17846
  init_lint();
17842
17847
  duplicates = (list7, name, what) => {
17843
- const first = /* @__PURE__ */ new Map();
17848
+ const first2 = /* @__PURE__ */ new Map();
17844
17849
  list7.forEach((x2, i) => {
17845
- if (!first.has(x2.id)) first.set(x2.id, i);
17850
+ if (!first2.has(x2.id)) first2.set(x2.id, i);
17846
17851
  });
17847
17852
  return list7.flatMap((x2, i) => {
17848
- const j = first.get(x2.id) ?? i;
17853
+ const j = first2.get(x2.id) ?? i;
17849
17854
  return j === i ? [] : [error(name + "[" + i + "].id", what + ' id "' + x2.id + '" is already used by ' + name + "[" + j + "].", 'Give it its own id, for example "' + x2.id + "-" + (i + 1) + '".')];
17850
17855
  });
17851
17856
  };
@@ -18671,7 +18676,7 @@ var init_decode = __esm({
18671
18676
  const h = Math.max(2, Math.round(srcH * w / srcW / 2) * 2);
18672
18677
  return { width: w, height: h };
18673
18678
  };
18674
- filterChain2 = (o, size) => {
18679
+ filterChain2 = (o, size2) => {
18675
18680
  const parts = [];
18676
18681
  const start = o.startFrame ?? 0;
18677
18682
  if (start > 0 || o.frameCount !== void 0) {
@@ -18680,7 +18685,7 @@ var init_decode = __esm({
18680
18685
  if (o.every !== void 0 && o.every > 1) parts.push("select='not(mod(n," + o.every + "))'");
18681
18686
  if (o.fps !== void 0) parts.push("fps=" + o.fps);
18682
18687
  const colour2 = o.colour ? ":in_color_matrix=" + o.colour.matrix + ":in_range=" + o.colour.range : "";
18683
- parts.push("scale=" + size.width + ":" + size.height + colour2 + ":flags=area+accurate_rnd", "format=" + (o.gray ? "gray" : "rgb24"));
18688
+ parts.push("scale=" + size2.width + ":" + size2.height + colour2 + ":flags=area+accurate_rnd", "format=" + (o.gray ? "gray" : "rgb24"));
18684
18689
  return parts.join(",");
18685
18690
  };
18686
18691
  readColour = async (rt, file, p) => colourOf((await runFfmpeg(rt, ["-i", file])).stderr, p.width, p.height);
@@ -18717,18 +18722,18 @@ var init_decode = __esm({
18717
18722
  if (!(opts.width >= 2)) throw new Error("decodeFrames: width must be at least 2 pixels (got " + opts.width + "). Pass a thumbnail width such as 96.");
18718
18723
  const p = opts.probe ?? await probe2(rt, file);
18719
18724
  const colour2 = opts.colour ?? await readColour(rt, file, p);
18720
- const size = thumbSize(p.width, p.height, opts.width);
18721
- const frameBytes = size.width * size.height * (opts.gray ? 1 : 3);
18725
+ const size2 = thumbSize(p.width, p.height, opts.width);
18726
+ const frameBytes = size2.width * size2.height * (opts.gray ? 1 : 3);
18722
18727
  const expected2 = expectedFrames(opts, p);
18723
18728
  const limit = opts.maxBytes ?? MAX_DECODE_BYTES;
18724
18729
  if (expected2 * frameBytes > limit) {
18725
18730
  const mb = Math.round(expected2 * frameBytes / 1048576);
18726
- throw new Error("decodeFrames(" + file + "): " + expected2 + " frames of " + size.width + "x" + size.height + " would take about " + mb + " MB, more than the limit of " + Math.round(limit / 1048576) + " MB. Lower width, set gray: true, or decode a part with frameCount (or a lower fps / a larger every).");
18731
+ throw new Error("decodeFrames(" + file + "): " + expected2 + " frames of " + size2.width + "x" + size2.height + " would take about " + mb + " MB, more than the limit of " + Math.round(limit / 1048576) + " MB. Lower width, set gray: true, or decode a part with frameCount (or a lower fps / a larger every).");
18727
18732
  }
18728
- const args = ["-i", file, "-map", "0:v:0", "-an", "-sn", "-vf", filterChain2({ ...opts, colour: colour2 }, size), "-fps_mode", "passthrough", "-f", "rawvideo", "pipe:1"];
18733
+ const args = ["-i", file, "-map", "0:v:0", "-an", "-sn", "-vf", filterChain2({ ...opts, colour: colour2 }, size2), "-fps_mode", "passthrough", "-f", "rawvideo", "pipe:1"];
18729
18734
  const frames = await readFrames(rt, args, frameBytes, Math.max(expected2 * 2, 1));
18730
18735
  const fps = opts.fps ?? p.fps / Math.max(1, opts.every ?? 1);
18731
- return { width: size.width, height: size.height, fps, frames };
18736
+ return { width: size2.width, height: size2.height, fps, frames };
18732
18737
  };
18733
18738
  extractFrame = async (rt, file, frame2, out2, width) => {
18734
18739
  const ext = out2.toLowerCase().split(".").pop() ?? "";
@@ -19637,45 +19642,45 @@ var init_fits = __esm({
19637
19642
  orient = (img, dir) => {
19638
19643
  const { w, h, data } = img;
19639
19644
  const horizontal = dir === "left" || dir === "right";
19640
- const size = horizontal ? w : h, across = horizontal ? h : w;
19641
- const out2 = new Float32Array(size * across * 3);
19645
+ const size2 = horizontal ? w : h, across = horizontal ? h : w;
19646
+ const out2 = new Float32Array(size2 * across * 3);
19642
19647
  for (let v = 0; v < across; v++) {
19643
- for (let u = 0; u < size; u++) {
19648
+ for (let u = 0; u < size2; u++) {
19644
19649
  const x2 = dir === "left" ? u : dir === "right" ? w - 1 - u : v;
19645
19650
  const y = dir === "up" ? u : dir === "down" ? h - 1 - u : v;
19646
- for (let c = 0; c < 3; c++) out2[(v * size + u) * 3 + c] = data[(y * w + x2) * 3 + c];
19651
+ for (let c = 0; c < 3; c++) out2[(v * size2 + u) * 3 + c] = data[(y * w + x2) * 3 + c];
19647
19652
  }
19648
19653
  }
19649
- return { size, across, data: out2 };
19654
+ return { size: size2, across, data: out2 };
19650
19655
  };
19651
19656
  compose = (mode, A, B, k) => {
19652
- const { size, across } = A;
19653
- const cut3 = size - k;
19657
+ const { size: size2, across } = A;
19658
+ const cut3 = size2 - k;
19654
19659
  const oldShift = mode === "push" || mode === "reveal" ? k : 0;
19655
19660
  const newShift = mode === "push" || mode === "cover" ? -cut3 : 0;
19656
19661
  const out2 = new Float32Array(A.data.length);
19657
19662
  for (let v = 0; v < across; v++) {
19658
- for (let u = 0; u < size; u++) {
19659
- const src = u < cut3 ? (v * size + u + oldShift) * 3 : (v * size + u + newShift) * 3;
19663
+ for (let u = 0; u < size2; u++) {
19664
+ const src = u < cut3 ? (v * size2 + u + oldShift) * 3 : (v * size2 + u + newShift) * 3;
19660
19665
  const pic = u < cut3 ? A.data : B.data;
19661
- for (let c = 0; c < 3; c++) out2[(v * size + u) * 3 + c] = pic[src + c];
19666
+ for (let c = 0; c < 3; c++) out2[(v * size2 + u) * 3 + c] = pic[src + c];
19662
19667
  }
19663
19668
  }
19664
19669
  return out2;
19665
19670
  };
19666
- smearAlong = (P, size, across, r) => {
19671
+ smearAlong = (P, size2, across, r) => {
19667
19672
  let cur = P;
19668
19673
  for (let pass = 0; pass < 2; pass++) {
19669
19674
  const out2 = new Float32Array(cur.length);
19670
19675
  for (let v = 0; v < across; v++) {
19671
- for (let u = 0; u < size; u++) {
19676
+ for (let u = 0; u < size2; u++) {
19672
19677
  for (let c = 0; c < 3; c++) {
19673
19678
  let s = 0, n = 0;
19674
- for (let q = Math.max(0, u - r); q <= Math.min(size - 1, u + r); q++) {
19675
- s += cur[(v * size + q) * 3 + c];
19679
+ for (let q = Math.max(0, u - r); q <= Math.min(size2 - 1, u + r); q++) {
19680
+ s += cur[(v * size2 + q) * 3 + c];
19676
19681
  n++;
19677
19682
  }
19678
- out2[(v * size + u) * 3 + c] = s / n;
19683
+ out2[(v * size2 + u) * 3 + c] = s / n;
19679
19684
  }
19680
19685
  }
19681
19686
  }
@@ -19695,22 +19700,22 @@ var init_fits = __esm({
19695
19700
  return quantile(ratios, 0.25);
19696
19701
  };
19697
19702
  edgeError = (mode, A, B, M, k) => {
19698
- const { size, across } = A;
19699
- const cut3 = size - k;
19703
+ const { size: size2, across } = A;
19704
+ const cut3 = size2 - k;
19700
19705
  const oldShift = mode === "push" || mode === "reveal" ? k : 0;
19701
19706
  const newShift = mode === "push" || mode === "cover" ? -cut3 : 0;
19702
19707
  const a = A.data, b = B.data, m = M.data;
19703
19708
  let err3 = 0;
19704
19709
  for (let v = 0; v < across; v++) {
19705
- const row = v * size;
19706
- for (let u = 0; u < size; u++) {
19710
+ const row = v * size2;
19711
+ for (let u = 0; u < size2; u++) {
19707
19712
  const src = u < cut3 ? (row + u + oldShift) * 3 : (row + u + newShift) * 3;
19708
19713
  const pic = u < cut3 ? a : b;
19709
19714
  const at7 = (row + u) * 3;
19710
19715
  err3 += Math.abs(m[at7] - pic[src]) + Math.abs(m[at7 + 1] - pic[src + 1]) + Math.abs(m[at7 + 2] - pic[src + 2]);
19711
19716
  }
19712
19717
  }
19713
- return err3 / (size * across * 3);
19718
+ return err3 / (size2 * across * 3);
19714
19719
  };
19715
19720
  DIRS = ["left", "right", "up", "down"];
19716
19721
  MODES2 = ["wipe", "push", "cover", "reveal"];
@@ -19946,9 +19951,9 @@ var init_robust = __esm({
19946
19951
  }
19947
19952
  let left = KEEP * a.length, s = 0;
19948
19953
  for (let k = 0; k < 256 && left > 0; k++) {
19949
- const take = Math.min(left, hist[k]);
19950
- if (take > 0) s += sums[k] / hist[k] * take;
19951
- left -= take;
19954
+ const take2 = Math.min(left, hist[k]);
19955
+ if (take2 > 0) s += sums[k] / hist[k] * take2;
19956
+ left -= take2;
19952
19957
  }
19953
19958
  return [all / Math.max(1, a.length), s / Math.max(1, KEEP * a.length)];
19954
19959
  };
@@ -20612,10 +20617,10 @@ var init_boundaries = __esm({
20612
20617
  return chains;
20613
20618
  };
20614
20619
  widen = (sg, chains, ramps2) => chains.map((chain, i) => {
20615
- const first = chain[0].frame, last = chain[chain.length - 1].frame;
20616
- const lo = Math.max(i > 0 ? chains[i - 1].at(-1).frame : 0, ...ramps2.filter((r) => r.e < first - 1).map((r) => r.e));
20620
+ const first2 = chain[0].frame, last = chain[chain.length - 1].frame;
20621
+ const lo = Math.max(i > 0 ? chains[i - 1].at(-1).frame : 0, ...ramps2.filter((r) => r.e < first2 - 1).map((r) => r.e));
20617
20622
  const hi = Math.min(i + 1 < chains.length ? chains[i + 1][0].frame - 1 : sg.n - 1, ...ramps2.filter((r) => r.s > last).map((r) => r.s));
20618
- return { s: activeSpan(sg, first, lo, hi).start, e: activeSpan(sg, last, lo, hi).end, cuts: chain, ramp: false };
20623
+ return { s: activeSpan(sg, first2, lo, hi).start, e: activeSpan(sg, last, lo, hi).end, cuts: chain, ramp: false };
20619
20624
  });
20620
20625
  mergeAll = (sg, cands) => {
20621
20626
  const sorted = [...cands].sort((a, b) => a.s - b.s || a.e - b.e);
@@ -20689,11 +20694,11 @@ var init_bars = __esm({
20689
20694
  MIN_LIVE = 0.1;
20690
20695
  SAMPLES = 120;
20691
20696
  rangeOf = (t) => {
20692
- const n = t.gray.length, k = Math.min(SAMPLES, n), size = t.width * t.height;
20693
- const lo = new Uint8Array(size).fill(255), hi = new Uint8Array(size);
20697
+ const n = t.gray.length, k = Math.min(SAMPLES, n), size2 = t.width * t.height;
20698
+ const lo = new Uint8Array(size2).fill(255), hi = new Uint8Array(size2);
20694
20699
  for (let s = 0; s < k; s++) {
20695
20700
  const g = t.gray[Math.floor(s * (n - 1) / Math.max(1, k - 1))];
20696
- for (let p = 0; p < size; p++) {
20701
+ for (let p = 0; p < size2; p++) {
20697
20702
  const v = g[p];
20698
20703
  if (v < lo[p]) lo[p] = v;
20699
20704
  if (v > hi[p]) hi[p] = v;
@@ -20800,8 +20805,8 @@ var init_moves = __esm({
20800
20805
  return n ? s / n : void 0;
20801
20806
  };
20802
20807
  fitAt = (fr, L, s, e, bound = Infinity) => {
20803
- const first = fr[0], last = fr[fr.length - 1];
20804
- const base = meanIn(fr, L, first, s) ?? L[0];
20808
+ const first2 = fr[0], last = fr[fr.length - 1];
20809
+ const base = meanIn(fr, L, first2, s) ?? L[0];
20805
20810
  const top2 = meanIn(fr, L, e, last) ?? L[L.length - 1];
20806
20811
  const ratio3 = Math.exp(top2 - base);
20807
20812
  const holdTerm = (i, x2) => (L[i] - (base + Math.log(1 + (ratio3 - 1) * (x2 <= 0 ? 0 : 1)))) ** 2;
@@ -20831,11 +20836,11 @@ var init_moves = __esm({
20831
20836
  return best;
20832
20837
  };
20833
20838
  fitMove = (fr, L, minFrames) => {
20834
- const first = fr[0], last = fr[fr.length - 1], gap = Math.max(1, Math.round((last - first) / Math.max(1, fr.length - 1)));
20839
+ const first2 = fr[0], last = fr[fr.length - 1], gap = Math.max(1, Math.round((last - first2) / Math.max(1, fr.length - 1)));
20835
20840
  const minLen = Math.max(2, minFrames);
20836
20841
  let best;
20837
20842
  const consider = (s, e) => {
20838
- if (s < first || e > last || e - s < minLen) return;
20843
+ if (s < first2 || e > last || e - s < minLen) return;
20839
20844
  const f = fitAt(fr, L, s, e, best ? best.err - 1e-12 : Infinity);
20840
20845
  if (f && (!best || f.err < best.err - 1e-12)) best = f;
20841
20846
  };
@@ -20929,10 +20934,10 @@ var init_camera2 = __esm({
20929
20934
  STILL_PAN = 5e-3;
20930
20935
  MIN_TEXTURE = 1.5;
20931
20936
  UNKNOWN = { kind: "unknown", zoomPerS: 0, panPerS: [0, 0], confidence: 0 };
20932
- fitStep = (c, i, j, init4, first) => {
20937
+ fitStep = (c, i, j, init4, first2) => {
20933
20938
  const a = c.gray[i], b = c.gray[j];
20934
20939
  const near3 = align(a, b, c.width, c.height, { init: init4 });
20935
- if (!first) return near3;
20940
+ if (!first2) return near3;
20936
20941
  const searched = align(a, b, c.width, c.height, { init: init4, search: true });
20937
20942
  return searched.residual < near3.residual ? searched : near3;
20938
20943
  };
@@ -21162,10 +21167,10 @@ var init_profile2 = __esm({
21162
21167
  }
21163
21168
  return { outline: on ? os / on : 0, ground: gn ? gs / gn : 0 };
21164
21169
  };
21165
- kindOf2 = (first, last, w, h, thr) => {
21170
+ kindOf2 = (first2, last, w, h, thr) => {
21166
21171
  const changed2 = new Uint8Array(w * h);
21167
- for (let p = 0; p < w * h; p++) changed2[p] = pixDiff(first, last, p * 3) > thr ? 1 : 0;
21168
- const c0 = contrasts(first, changed2, w, h), c1 = contrasts(last, changed2, w, h);
21172
+ for (let p = 0; p < w * h; p++) changed2[p] = pixDiff(first2, last, p * 3) > thr ? 1 : 0;
21173
+ const c0 = contrasts(first2, changed2, w, h), c1 = contrasts(last, changed2, w, h);
21169
21174
  const e0 = Math.max(0, c0.outline - c0.ground), e1 = Math.max(0, c1.outline - c1.ground);
21170
21175
  if (e1 > 1.5 * e0 + 5) return "appear";
21171
21176
  if (e0 > 1.5 * e1 + 5) return "disappear";
@@ -21196,8 +21201,8 @@ var init_profile2 = __esm({
21196
21201
  const dx = F.cx - f.cx, dy = F.cy - f.cy;
21197
21202
  const horizontal = Math.abs(dx) / fw >= Math.abs(dy) / fh;
21198
21203
  const travel2 = horizontal ? Math.abs(dx) : Math.abs(dy);
21199
- const size = horizontal ? (f.x1 - f.x0 + 1) / fw : (f.y1 - f.y0 + 1) / fh;
21200
- if (travel2 < Math.max(1.5, 0.12 * (horizontal ? fw : fh)) || size < 0.6) return void 0;
21204
+ const size2 = horizontal ? (f.x1 - f.x0 + 1) / fw : (f.y1 - f.y0 + 1) / fh;
21205
+ if (travel2 < Math.max(1.5, 0.12 * (horizontal ? fw : fh)) || size2 < 0.6) return void 0;
21201
21206
  const direction2 = horizontal ? dx > 0 ? "right" : "left" : dy > 0 ? "down" : "up";
21202
21207
  return { how: "slide", direction: direction2, q: vis.map((s) => clamp2(1 - Math.hypot(F.cx - s.cx, F.cy - s.cy) / Math.hypot(dx, dy), 0, 1)) };
21203
21208
  };
@@ -21214,10 +21219,10 @@ var init_profile2 = __esm({
21214
21219
  profileCrop = (c) => {
21215
21220
  const n = c.frames.length;
21216
21221
  if (n < 2) return void 0;
21217
- const first = c.frames[0], last = c.frames[n - 1];
21218
- const total2 = meanDiff(first, last);
21222
+ const first2 = c.frames[0], last = c.frames[n - 1];
21223
+ const total2 = meanDiff(first2, last);
21219
21224
  if (total2 < 0.5) return void 0;
21220
- const kind = kindOf2(first, last, c.w, c.h, 12);
21225
+ const kind = kindOf2(first2, last, c.w, c.h, 12);
21221
21226
  const seq = kind === "disappear" ? [...c.frames].reverse() : [...c.frames];
21222
21227
  const ref = seq[0], target2 = seq[n - 1];
21223
21228
  const tol = Math.max(0.7, 0.02 * total2);
@@ -21921,14 +21926,14 @@ var init_tracks = __esm({
21921
21926
  later = m.mask;
21922
21927
  live.unshift(m);
21923
21928
  }
21924
- const first = live[0];
21929
+ const first2 = live[0];
21925
21930
  const covers = live.map((m) => m.fresh / m.total);
21926
21931
  const fallen = covers.reduce((s, c, i) => s + (i > 0 ? Math.max(0, covers[i - 1] - c) : 0), 0);
21927
21932
  if ((covers[covers.length - 1] ?? 0) < REACHES || fallen > FALLS) return void 0;
21928
21933
  const middle = live.filter((m) => m.fresh / m.total >= 0.2 && m.fresh / m.total <= 0.8);
21929
- if (!first || live.length < 3 || median2(live.map((m) => m.foreign / m.total)) > MOST_FOREIGN || median2((middle.length ? middle : live).map((m) => m.mixed)) > MOST_MIXED) return void 0;
21934
+ if (!first2 || live.length < 3 || median2(live.map((m) => m.foreign / m.total)) > MOST_FOREIGN || median2((middle.length ? middle : live).map((m) => m.mixed)) > MOST_MIXED) return void 0;
21930
21935
  let ox = 0, oy = 0, on = 0;
21931
- first.mask.forEach((v, p) => {
21936
+ first2.mask.forEach((v, p) => {
21932
21937
  if (v === NEW) {
21933
21938
  ox += p % w;
21934
21939
  oy += Math.floor(p / w);
@@ -21973,7 +21978,7 @@ var init_tracks = __esm({
21973
21978
  samples,
21974
21979
  path: pathOf2(samples, w, h, t.fps),
21975
21980
  size: medianSize(samples),
21976
- reveal: { start: first.frame, end: done2.frame, edge },
21981
+ reveal: { start: first2.frame, end: done2.frame, edge },
21977
21982
  confidence: round(clamp2(calm * (edge.shape === "irregular" ? 0.6 : edge.fit) * (0.5 + 0.5 * edge.share), 0, 1), 2)
21978
21983
  };
21979
21984
  };
@@ -22080,8 +22085,8 @@ var init_signature = __esm({
22080
22085
  };
22081
22086
  signatureFrames = (s) => {
22082
22087
  const all = new Uint8Array(Buffer.from(s.data, "base64"));
22083
- const size = s.width * s.height;
22084
- return Array.from({ length: s.count }, (_, k) => all.subarray(k * size, (k + 1) * size));
22088
+ const size2 = s.width * s.height;
22089
+ return Array.from({ length: s.count }, (_, k) => all.subarray(k * size2, (k + 1) * size2));
22085
22090
  };
22086
22091
  }
22087
22092
  });
@@ -22386,6 +22391,14 @@ var init_wallet = __esm({
22386
22391
  settle(reserved, charged) {
22387
22392
  this.spent += Math.max(0, charged) - Math.max(0, reserved);
22388
22393
  }
22394
+ /**
22395
+ * Credits this command paid and the platform gave back (a clip paid when it was sent, then failed and was refunded):
22396
+ * the command may spend them again. What it spends net never passes max: the caller gives back only what it paid
22397
+ * itself and the platform refunded.
22398
+ */
22399
+ refund(credits2) {
22400
+ this.spent = Math.max(0, this.spent - Math.max(0, credits2));
22401
+ }
22389
22402
  };
22390
22403
  NOTHING = () => new Wallet(0);
22391
22404
  }
@@ -22705,8 +22718,8 @@ var init_hosted = __esm({
22705
22718
  };
22706
22719
  downloadVoiceAudio = async (rt, url, out2, again = "Run the same command again.") => {
22707
22720
  const bytes = await downloadPaid(rt, url, { what: "the voice audio", again, maxBytes: 50 * 1024 * 1024 });
22708
- const tag3 = (a, b) => String.fromCharCode(...bytes.subarray(a, b));
22709
- if (tag3(0, 4) !== "RIFF" || tag3(8, 12) !== "WAVE" || bytes.length <= 44) throw new Error("The speech service did not return a WAV recording.");
22721
+ const tag4 = (a, b) => String.fromCharCode(...bytes.subarray(a, b));
22722
+ if (tag4(0, 4) !== "RIFF" || tag4(8, 12) !== "WAVE" || bytes.length <= 44) throw new Error("The speech service did not return a WAV recording.");
22710
22723
  await rt.fs.writeFile(out2, bytes);
22711
22724
  };
22712
22725
  hostedOperationKey = (voiceId, text13, speed, out2) => operationKeyOf({ voiceId, text: text13, speed, out: out2 });
@@ -22850,9 +22863,9 @@ var init_voice = __esm({
22850
22863
  const raw = await rt.fs.readText(file).then((t) => JSON.parse(t), () => void 0);
22851
22864
  await rt.fs.rm(file);
22852
22865
  const list7 = Array.isArray(raw?.words) ? raw.words.filter((w) => typeof w.text === "string" && typeof w.start === "number" && typeof w.end === "number") : [];
22853
- const first = list7[0];
22854
- if (!first) return void 0;
22855
- return list7.map((w) => ({ text: w.text, start: Math.max(0, w.start - first.start), end: Math.max(0, w.end - first.start) }));
22866
+ const first2 = list7[0];
22867
+ if (!first2) return void 0;
22868
+ return list7.map((w) => ({ text: w.text, start: Math.max(0, w.start - first2.start), end: Math.max(0, w.end - first2.start) }));
22856
22869
  };
22857
22870
  TRIM = "silenceremove=start_periods=1:start_threshold=-45dB:detection=peak,areverse,silenceremove=start_periods=1:start_threshold=-45dB:detection=peak,areverse";
22858
22871
  speakLines = async (rt, o) => {
@@ -22975,11 +22988,11 @@ var init_dialogue = __esm({
22975
22988
  TAG = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
22976
22989
  WIDE_LANGUAGES = ["zh", "yue", "ja", "ko"];
22977
22990
  WIDE = /[\u{3040}-\u{30ff}\u{3400}-\u{9fff}\u{ac00}-\u{d7af}]/u;
22978
- languageName = (tag3) => {
22979
- const t = tag3.trim().toLowerCase();
22980
- return NAMES2[t] ?? NAMES2[t.split("-")[0] ?? ""] ?? tag3.trim();
22991
+ languageName = (tag4) => {
22992
+ const t = tag4.trim().toLowerCase();
22993
+ return NAMES2[t] ?? NAMES2[t.split("-")[0] ?? ""] ?? tag4.trim();
22981
22994
  };
22982
- wideLanguage = (tag3) => WIDE_LANGUAGES.includes(tag3.trim().toLowerCase().split("-")[0] ?? "");
22995
+ wideLanguage = (tag4) => WIDE_LANGUAGES.includes(tag4.trim().toLowerCase().split("-")[0] ?? "");
22983
22996
  wideText = (text13) => {
22984
22997
  const chars = spokenChars(text13);
22985
22998
  return chars.filter((c) => WIDE.test(c)).length * 2 >= chars.length;
@@ -23210,7 +23223,7 @@ var init_revision = __esm({
23210
23223
  });
23211
23224
 
23212
23225
  // src/video/replication/check.ts
23213
- var problem, BIND, sameHash, validSource, hasMedia, mediaEvidence, VISUAL, AUDIBLE, DYNAMIC, checkReplicationSource, checkReplicationReadiness, checkReplicationAudio, frameKeys, assessReplication;
23226
+ var problem, BIND, sameHash, validSource, hasMedia, mediaEvidence, VISUAL, AUDIBLE, DYNAMIC, checkReplicationSource, checkReplicationReadiness, checkReplicationAudio, LENGTH_SLACK, frameKeys, assessReplication;
23214
23227
  var init_check4 = __esm({
23215
23228
  "src/video/replication/check.ts"() {
23216
23229
  "use strict";
@@ -23300,6 +23313,7 @@ var init_check4 = __esm({
23300
23313
  });
23301
23314
  return out2;
23302
23315
  };
23316
+ LENGTH_SLACK = { near: 0.03, far: 0.1 };
23303
23317
  frameKeys = (evidence3) => new Set(evidence3.flatMap((e) => {
23304
23318
  if (!hasMedia(e, VISUAL)) return [];
23305
23319
  if (e.media === "frame") return [e.sha256.toLowerCase()];
@@ -23338,8 +23352,18 @@ var init_check4 = __esm({
23338
23352
  const span2 = c.scope?.span ?? [0, c.source.frames];
23339
23353
  const expected2 = (span2[1] - span2[0]) / c.source.fps;
23340
23354
  const duration = actualArtifact.frames / actualArtifact.fps;
23341
- const tolerance = Math.max(1 / c.source.fps, 1 / actualArtifact.fps) + 1e-6;
23342
- if (Math.abs(duration - expected2) > tolerance) fail2("review.target", "Final duration does not match the retained reference interval; equal frame counts are not enough.");
23355
+ const frame2 = Math.max(1 / c.source.fps, 1 / actualArtifact.fps) + 1e-6;
23356
+ const off2 = Math.abs(duration - expected2), share2 = Math.round(off2 / expected2 * 1e3) / 10;
23357
+ const lengths = duration.toFixed(2) + " s against the retained reference interval's " + expected2.toFixed(2) + " s (" + share2 + "%)";
23358
+ if (off2 > Math.max(frame2, LENGTH_SLACK.far * expected2))
23359
+ fail2("review.target", "Final duration is " + lengths + ", more than " + LENGTH_SLACK.far * 100 + "% off; equal frame counts are not enough.");
23360
+ else if (off2 > Math.max(frame2, LENGTH_SLACK.near * expected2))
23361
+ out2.push(problem(
23362
+ "review.target",
23363
+ "Final duration is " + lengths + ": accepted, as within " + LENGTH_SLACK.far * 100 + "%; say it in the delivery notes.",
23364
+ "warning",
23365
+ "Say the length difference in the delivery notes; re-time only when the user asks for the exact length."
23366
+ ));
23343
23367
  }
23344
23368
  const inspect = (name, f, media) => {
23345
23369
  if (f?.status === "failed") {
@@ -23480,12 +23504,12 @@ var init_footage3 = __esm({
23480
23504
  }
23481
23505
  return dir;
23482
23506
  };
23483
- keyOf3 = async (rt, projectDir, src, size) => {
23507
+ keyOf3 = async (rt, projectDir, src, size2) => {
23484
23508
  const file = rt.path.resolve(rt.cwd, projectDir, src);
23485
23509
  const info = await rt.fs.stat(file);
23486
23510
  if (!info) throw new Error("The video material " + src + " disappeared while the page was built. Build it again.");
23487
23511
  return {
23488
- key: sha256(JSON.stringify([EXTRACT_VERSION, src, info.size, info.mtimeMs, size.width, size.height])).slice(0, 16),
23512
+ key: sha256(JSON.stringify([EXTRACT_VERSION, src, info.size, info.mtimeMs, size2.width, size2.height])).slice(0, 16),
23489
23513
  source: sha256(JSON.stringify([EXTRACT_VERSION, src, info.size, info.mtimeMs])).slice(0, 16)
23490
23514
  };
23491
23515
  };
@@ -23498,8 +23522,8 @@ var init_footage3 = __esm({
23498
23522
  const facts = probed.info[id2];
23499
23523
  const colour2 = probed.colour[id2];
23500
23524
  if (!facts || "error" in facts || !colour2) throw new Error('extractFootage: video material "' + id2 + '" was not probed. Pass the result of probeFootage for this project.');
23501
- const size = extractSize(r, id2, facts, opts.scale);
23502
- return { id: id2, f, size, colour: colour2, ...await keyOf3(rt, projectDir, f.src, size) };
23525
+ const size2 = extractSize(r, id2, facts, opts.scale);
23526
+ return { id: id2, f, size: size2, colour: colour2, ...await keyOf3(rt, projectDir, f.src, size2) };
23503
23527
  }));
23504
23528
  const dirs = /* @__PURE__ */ new Map();
23505
23529
  for (const j of jobs2) dirs.set(j.key, await cacheDir(rt, projectDir, FOOTAGE_CACHE + "/" + j.key));
@@ -24563,19 +24587,19 @@ var init_measure2 = __esm({
24563
24587
  return rms > 0 ? Math.max(FLOOR_DB, 20 * Math.log10(rms)) : FLOOR_DB;
24564
24588
  };
24565
24589
  levelCurve = (pcm, rate, step2 = 0.5) => {
24566
- const size = Math.max(1, Math.round(step2 * rate));
24567
- return Array.from({ length: Math.ceil(pcm.length / size) }, (_, i) => r1(rmsDb(pcm, i * size, (i + 1) * size)));
24590
+ const size2 = Math.max(1, Math.round(step2 * rate));
24591
+ return Array.from({ length: Math.ceil(pcm.length / size2) }, (_, i) => r1(rmsDb(pcm, i * size2, (i + 1) * size2)));
24568
24592
  };
24569
24593
  silencesOf = (pcm, rate, db = SILENCE_DB, least = SILENCE_SECONDS) => {
24570
- const size = Math.max(1, Math.round(0.05 * rate));
24594
+ const size2 = Math.max(1, Math.round(0.05 * rate));
24571
24595
  const out2 = [];
24572
24596
  let start = -1;
24573
- const n = Math.ceil(pcm.length / size);
24597
+ const n = Math.ceil(pcm.length / size2);
24574
24598
  for (let i = 0; i <= n; i++) {
24575
- const quiet = i < n && rmsDb(pcm, i * size, (i + 1) * size) < db;
24599
+ const quiet = i < n && rmsDb(pcm, i * size2, (i + 1) * size2) < db;
24576
24600
  if (quiet && start < 0) start = i;
24577
24601
  if (!quiet && start >= 0) {
24578
- const a = start * size / rate, b = Math.min(pcm.length, i * size) / rate;
24602
+ const a = start * size2 / rate, b = Math.min(pcm.length, i * size2) / rate;
24579
24603
  if (b - a >= least) out2.push([r22(a), r22(b)]);
24580
24604
  start = -1;
24581
24605
  }
@@ -24603,9 +24627,9 @@ var init_measure2 = __esm({
24603
24627
  re[reverse[i]] = (pcm[at7 + i] ?? 0) * hann[i];
24604
24628
  im[i] = 0;
24605
24629
  }
24606
- for (let size = 2; size <= n; size *= 2) {
24607
- const half2 = size / 2, step2 = n / size;
24608
- for (let i = 0; i < n; i += size) {
24630
+ for (let size2 = 2; size2 <= n; size2 *= 2) {
24631
+ const half2 = size2 / 2, step2 = n / size2;
24632
+ for (let i = 0; i < n; i += size2) {
24609
24633
  for (let j = 0; j < half2; j++) {
24610
24634
  const c = cos[j * step2], s = sin[j * step2];
24611
24635
  const a = i + j, b = a + half2;
@@ -24713,12 +24737,12 @@ var init_measure2 = __esm({
24713
24737
  phase = p;
24714
24738
  }
24715
24739
  }
24716
- const first = (phase * HOP + ONSET_AT * FRAME) / rate;
24740
+ const first2 = (phase * HOP + ONSET_AT * FRAME) / rate;
24717
24741
  return {
24718
24742
  bpm: r1(60 / period),
24719
24743
  confidence: r22(Math.max(0, Math.min(1, best.value))),
24720
24744
  period: r3(period),
24721
- first: r3(first % period),
24745
+ first: r3(first2 % period),
24722
24746
  others: peaks.slice(1, 3).map((p) => ({ bpm: r1(60 * fps / p.lag), confidence: r22(Math.max(0, Math.min(1, p.value))) }))
24723
24747
  };
24724
24748
  };
@@ -24820,11 +24844,11 @@ var init_sample = __esm({
24820
24844
  const length2 = Math.min(want, best[1] - best[0]);
24821
24845
  return { at: Math.round(best[0] * 100) / 100, seconds: Math.round(length2 * 100) / 100 };
24822
24846
  };
24823
- VOICE_NAMED = (speakers, first) => pl(
24824
- VOICE_NAMED_EN(speakers, first),
24825
- " " + speakers.map((s, i) => s + "\u7684\u58F0\u97F3\u662F @audio" + (first + i)).join("\uFF1B") + "\uFF1A" + (speakers.length === 1 ? "\u5B83" : "\u6BCF\u4E00\u6BB5") + "\u53EA\u786E\u5B9A\u58F0\u97F3\u7684\u8EAB\u4EFD\u548C\u97F3\u8272\u3002\u53F0\u8BCD\u7528" + (speakers.length === 1 ? "\u8FD9\u4E2A\u58F0\u97F3" : "\u8FD9\u4E9B\u58F0\u97F3") + "\u8BF4\u51FA\uFF0C\u7EDD\u4E0D\u8BF4\u53C2\u8003\u5F55\u97F3\u91CC\u7684\u8BDD\uFF0C\u5E76\u4E14\u8FD9\u4E2A\u58F0\u97F3\u5728\u6BCF\u4E2A\u7247\u6BB5\u91CC\u4FDD\u6301\u4E00\u81F4\u3002"
24847
+ VOICE_NAMED = (speakers, first2) => pl(
24848
+ VOICE_NAMED_EN(speakers, first2),
24849
+ " " + speakers.map((s, i) => s + "\u7684\u58F0\u97F3\u662F @audio" + (first2 + i)).join("\uFF1B") + "\uFF1A" + (speakers.length === 1 ? "\u5B83" : "\u6BCF\u4E00\u6BB5") + "\u53EA\u786E\u5B9A\u58F0\u97F3\u7684\u8EAB\u4EFD\u548C\u97F3\u8272\u3002\u53F0\u8BCD\u7528" + (speakers.length === 1 ? "\u8FD9\u4E2A\u58F0\u97F3" : "\u8FD9\u4E9B\u58F0\u97F3") + "\u8BF4\u51FA\uFF0C\u7EDD\u4E0D\u8BF4\u53C2\u8003\u5F55\u97F3\u91CC\u7684\u8BDD\uFF0C\u5E76\u4E14\u8FD9\u4E2A\u58F0\u97F3\u5728\u6BCF\u4E2A\u7247\u6BB5\u91CC\u4FDD\u6301\u4E00\u81F4\u3002"
24826
24850
  );
24827
- VOICE_NAMED_EN = (speakers, first) => " " + speakers.map((s, i) => "The voice of " + s + " is @audio" + (first + i)).join("; ") + ": " + (speakers.length === 1 ? "it defines" : "each defines") + " the voice's identity and timbre only. The lines are spoken with " + (speakers.length === 1 ? "that voice" : "those voices") + ", never with the words of the reference recording, and the voice stays the same through every clip.";
24851
+ VOICE_NAMED_EN = (speakers, first2) => " " + speakers.map((s, i) => "The voice of " + s + " is @audio" + (first2 + i)).join("; ") + ": " + (speakers.length === 1 ? "it defines" : "each defines") + " the voice's identity and timbre only. The lines are spoken with " + (speakers.length === 1 ? "that voice" : "those voices") + ", never with the words of the reference recording, and the voice stays the same through every clip.";
24828
24852
  readRecord = (rt, file) => rt.fs.readText(file + ".json").then((t) => JSON.parse(t), () => void 0);
24829
24853
  cutSample = async (rt, dir, profile, o) => {
24830
24854
  const out2 = rt.path.join(dir, sampleFile(profile.id));
@@ -24906,6 +24930,60 @@ var init_clip_sound = __esm({
24906
24930
  }
24907
24931
  });
24908
24932
 
24933
+ // src/video/generate/voice-clips.ts
24934
+ var nativeSpeakers, planVoiceClips, clipVoices, voiceClipsAwaited, adoptClipVoice;
24935
+ var init_voice_clips = __esm({
24936
+ "src/video/generate/voice-clips.ts"() {
24937
+ "use strict";
24938
+ init_profile3();
24939
+ init_sample();
24940
+ init_speech();
24941
+ nativeSpeakers = (r) => r.speech?.mode === "native" ? speakersOf(r.speech) : [];
24942
+ planVoiceClips = (order, registered, canCarry) => {
24943
+ const clipOf = /* @__PURE__ */ new Map(), waits = /* @__PURE__ */ new Map();
24944
+ const speakers = [...new Set(order.flatMap(nativeSpeakers))].filter((s) => !registered.has(s));
24945
+ for (const speaker of speakers) {
24946
+ const at7 = order.findIndex((r) => {
24947
+ const who = nativeSpeakers(r);
24948
+ return who.length === 1 && who[0] === speaker;
24949
+ });
24950
+ if (at7 < 0) continue;
24951
+ const later = order.slice(at7 + 1).filter((r) => nativeSpeakers(r).includes(speaker) && canCarry(r));
24952
+ if (!later.length) continue;
24953
+ clipOf.set(speaker, order[at7].file);
24954
+ for (const r of later) waits.set(r.file, [...waits.get(r.file) ?? [], speaker]);
24955
+ }
24956
+ return { clipOf, waits };
24957
+ };
24958
+ clipVoices = async (rt, dir, r, fromFrames, notes2) => {
24959
+ const refs = [];
24960
+ for (const id2 of nativeSpeakers(r)) {
24961
+ const profile = await voiceProfile(rt, dir, id2).catch(() => void 0);
24962
+ if (profile) refs.push({ id: id2, profile });
24963
+ }
24964
+ if (!refs.length || !fromFrames) return refs;
24965
+ notes2.push(r.file + ": " + refs.map((v) => v.id).join(", ") + " speak" + (refs.length === 1 ? "s" : "") + " with the video model's own voice; the voice registered for the project is not passed as a reference (this clip starts from a frame, and a clip made from frames takes no references). Listen to the clip beside the others.");
24966
+ return [];
24967
+ };
24968
+ voiceClipsAwaited = (plan4, file, settled2) => [...new Set((plan4.waits.get(file) ?? []).filter((s) => !settled2.has(s)).map((s) => plan4.clipOf.get(s)))];
24969
+ adoptClipVoice = async (rt, dir, plan4, file, notes2) => {
24970
+ const registered = new Set((await readVoices(rt, dir)).speakers.map((v) => v.id));
24971
+ const speakers = [...plan4.clipOf].filter(([s, f]) => f === file && !registered.has(s)).map(([s]) => s);
24972
+ for (const speaker of speakers) {
24973
+ const clip11 = rt.path.resolve(dir, file);
24974
+ try {
24975
+ const profile = await registerVoice(rt, dir, speaker, clip11, "native-reference");
24976
+ await cutSample(rt, dir, profile, { file: clip11, from: "clip" });
24977
+ notes2.push(file + ": the voice " + speaker + " speaks with here is now theirs: a sample of it (assets/voices/" + speaker + ".sample.wav) goes to their later clips as the reference sound, so they keep one voice.");
24978
+ } catch (e) {
24979
+ notes2.push(file + ": no voice sample could be cut from it for " + speaker + " (" + (e instanceof Error ? e.message : String(e)) + "); their later clips speak with the video model's own voice. To keep one voice, cut a sample from a clip in which they speak clearly: popost video voice sample <project> --speaker " + speaker + " --from <that clip>, after registering it from the same clip (popost video voice add <project> --speaker " + speaker + " --file <that clip> --mode native-reference).");
24980
+ }
24981
+ }
24982
+ return speakers;
24983
+ };
24984
+ }
24985
+ });
24986
+
24909
24987
  // src/video/product/sheet.ts
24910
24988
  var PRODUCT_FILE, PRODUCT_DIR, FACT_SOURCES, REQUIRED_FACTS, OPTIONAL_FACTS, FACTS, FACT_HELP, NO_LABEL, PICTURE_EXT, ID, tidy, clause, inferredFacts, inferredHash, confirmationOf, confirmLine, productBody, imageNames, productBlock, isFact, FIX_FACT, factProblems, lines, fileProblems, FACE_FIX, pictureProblems, productProblems, crossProblems, readProductSheet, blank2, skeleton;
24911
24989
  var init_sheet3 = __esm({
@@ -25118,7 +25196,7 @@ var init_sheet3 = __esm({
25118
25196
  });
25119
25197
 
25120
25198
  // src/video/product/requests.ts
25121
- var VIDEO, usesFrames, escape, mentions, shownProducts, picturesOf2, receiptFile, withProducts, DECLARE, INSTEAD, SEVERAL, LONG_PRODUCT_CLIP, shownProblems, PRODUCT_WORDS, PRODUCT_FILES, unsheeted, productRequestProblems, castPictureCount;
25199
+ var VIDEO, usesFrames, escape, mentions, shownProducts, picturesOf2, receiptFile, withProducts, DECLARE, INSTEAD, ASK_MODEL, SEVERAL, LONG_PRODUCT_CLIP, shownProblems, PRODUCT_WORDS, PRODUCT_FILES, unsheeted, productRequestProblems, castPictureCount;
25122
25200
  var init_requests = __esm({
25123
25201
  "src/video/product/requests.ts"() {
25124
25202
  "use strict";
@@ -25150,6 +25228,7 @@ var init_requests = __esm({
25150
25228
  };
25151
25229
  DECLARE = 'Add "products": ["<id>"] with the id(s) from ' + PRODUCT_FILE + ` to every request that shows the product (the user's pictures and the product block then go with it), and "products": [] to a request that shows none.`;
25152
25230
  INSTEAD = `make the shot from the real picture instead: a scene that moves the user's picture (a packshot, a close-up, a label shot), or a clip whose "firstFrame" is the user's picture or a still composed from it and listed under "stills" in ` + PRODUCT_FILE;
25231
+ ASK_MODEL = "set POPOST_VIDEO_MODEL only to a model the user names";
25153
25232
  SEVERAL = /\bthen\b|\bafter that\b|hard cuts?|然后|接着|随后/gi;
25154
25233
  LONG_PRODUCT_CLIP = 10;
25155
25234
  shownProblems = async (rt, dir, r, at7, products, policy) => {
@@ -25164,7 +25243,7 @@ var init_requests = __esm({
25164
25243
  if (r.continues !== void 0)
25165
25244
  out2.push(warning(at7 + ".continues", "This clip shows the product (" + ids3 + ") and starts from the last frame of " + JSON.stringify(r.continues) + ", a generated frame: the product's pictures cannot go with it, and whatever that frame got wrong is carried on.", "Run the product check on " + JSON.stringify(r.continues) + " first and continue it only when its last frame shows the product as in the user's picture; otherwise make this part as its own clip with the pictures as references."));
25166
25245
  if (policy.limits?.frames === false)
25167
- out2.push(error(at7 + ".firstFrame", "The video model in use" + (policy.limits.model ? " (" + policy.limits.model + ")" : "") + " takes no first frame, and a clip from frames is the only way this request shows the product.", `Remove the frames so that the product's pictures go as references, or choose a model that popost video generate --models lists with "frames": true (POPOST_VIDEO_MODEL).`));
25246
+ out2.push(error(at7 + ".firstFrame", "The video model in use" + (policy.limits.model ? " (" + policy.limits.model + ")" : "") + " takes no first frame, and a clip from frames is the only way this request shows the product.", `Remove the frames so that the product's pictures go as references, or ask the user whether to use a model that popost video generate --models lists with "frames": true (` + ASK_MODEL + ")."));
25168
25247
  } else if (clip11 && policy.limits?.maxReferenceImages !== void 0) {
25169
25248
  const max = policy.limits.maxReferenceImages;
25170
25249
  const model = "The video model in use" + (policy.limits.model ? " (" + policy.limits.model + ")" : "");
@@ -25172,11 +25251,11 @@ var init_requests = __esm({
25172
25251
  const cast = (r.cast ?? []).reduce((n, id2) => n + (policy.castPictures?.(id2) ?? 0), 0);
25173
25252
  const all = picturesOf2(r, products).length + cast;
25174
25253
  if (max === 0)
25175
- out2.push(error(at7 + ".products", model + " takes no reference pictures, so it cannot be shown the product (" + ids3 + "): it would draw one from words.", 'Choose a model that takes reference pictures (popost video generate --models lists "maxReferenceImages"; POPOST_VIDEO_MODEL), or ' + INSTEAD + "."));
25254
+ out2.push(error(at7 + ".products", model + " takes no reference pictures, so it cannot be shown the product (" + ids3 + "): it would draw one from words.", INSTEAD.charAt(0).toUpperCase() + INSTEAD.slice(1) + ', or ask the user whether to use a model that takes reference pictures (popost video generate --models lists "maxReferenceImages"; ' + ASK_MODEL + ")."));
25176
25255
  else if (mine > max)
25177
- out2.push(error(at7 + ".products", model + " takes " + max + " reference picture" + (max === 1 ? "" : "s") + ", and the user gave " + mine + " of the product (" + ids3 + "): every one of them goes with every clip that shows it.", "Choose a model that takes at least " + mine + " (popost video generate --models), or ask the user which pictures to leave out and remove those from " + PRODUCT_FILE + " with their words; never choose for them."));
25256
+ out2.push(error(at7 + ".products", model + " takes " + max + " reference picture" + (max === 1 ? "" : "s") + ", and the user gave " + mine + " of the product (" + ids3 + "): every one of them goes with every clip that shows it.", "Ask the user: which pictures to leave out (remove those from " + PRODUCT_FILE + " with their words; never choose for them), or a model that takes at least " + mine + " (popost video generate --models; " + ASK_MODEL + ")."));
25178
25257
  else if (all > max)
25179
- out2.push(error(at7 + ".images", model + " takes " + max + " reference picture" + (max === 1 ? "" : "s") + "; this request has " + all + ": " + mine + " of the product, " + cast + " of the cast and " + (all - mine - cast) + " of its own. The product's pictures always go.", 'Make room below them, in this order: remove pictures from "images" (' + (all - mine - cast) + "), then show fewer people with identity pictures in this clip, or split it so the product and the person are in separate clips; or choose a model that takes " + all + " (popost video generate --models)."));
25258
+ out2.push(error(at7 + ".images", model + " takes " + max + " reference picture" + (max === 1 ? "" : "s") + "; this request has " + all + ": " + mine + " of the product, " + cast + " of the cast and " + (all - mine - cast) + " of its own. The product's pictures always go.", 'Make room below them, in this order: remove pictures from "images" (' + (all - mine - cast) + "), then show fewer people with identity pictures in this clip, or split it so the product and the person are in separate clips; or ask the user whether to use a model that takes " + all + " (popost video generate --models; " + ASK_MODEL + ")."));
25180
25259
  }
25181
25260
  const text13 = (r.prompt ?? "").match(SEVERAL)?.length ?? 0;
25182
25261
  if (clip11 && (r.seconds ?? 0) >= LONG_PRODUCT_CLIP && text13 >= 1)
@@ -25239,8 +25318,219 @@ var init_requests = __esm({
25239
25318
  }
25240
25319
  });
25241
25320
 
25321
+ // src/video/generate/failure.ts
25322
+ var GenerationFailed, REASON_CHARS, failureOf6, REFUSED_REQUEST, SOUND_WORDS, OTHER_WORDS, refusedSound, withSound, failureKind, KEEP_MODEL, NEXT, nextAfter, WHAT, failureLine, KNOWN_FAILURE, failedProblem;
25323
+ var init_failure = __esm({
25324
+ "src/video/generate/failure.ts"() {
25325
+ "use strict";
25326
+ GenerationFailed = class extends Error {
25327
+ constructor(failure4, message2) {
25328
+ super(message2);
25329
+ this.failure = failure4;
25330
+ }
25331
+ failure;
25332
+ name = "GenerationFailed";
25333
+ };
25334
+ REASON_CHARS = 400;
25335
+ failureOf6 = (value) => {
25336
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
25337
+ const v = value;
25338
+ if (typeof v.code !== "string" || !v.code.trim()) return void 0;
25339
+ const refunded = typeof v.refundedCredits === "number" && v.refundedCredits > 0 ? v.refundedCredits : void 0;
25340
+ const reason2 = typeof v.reason === "string" && v.reason.trim() ? v.reason.trim().slice(0, REASON_CHARS) : void 0;
25341
+ return {
25342
+ code: v.code.trim(),
25343
+ ...typeof v.retryable === "boolean" ? { retryable: v.retryable } : {},
25344
+ ...reason2 ? { reason: reason2 } : {},
25345
+ ...refunded !== void 0 ? { refundedCredits: refunded } : {},
25346
+ ...v.sound === true ? { sound: true } : {}
25347
+ };
25348
+ };
25349
+ REFUSED_REQUEST = /* @__PURE__ */ new Set(["VIDEO_REQUEST_REJECTED", "VIDEO_OPTION_UNSUPPORTED"]);
25350
+ SOUND_WORDS = /\b(?:audio|sound|voice|speech)s?\b|audio_url|音频|声音|语音|音色|配音/i;
25351
+ OTHER_WORDS = /\b(?:image|picture|photo|frame|prompt|text)s?\b|image_url|video_url|图片|图像|画面|提示词|文本|文字/i;
25352
+ refusedSound = (f, hadSound) => f.code === "CONTENT_REJECTED" && (!!f.reason && SOUND_WORDS.test(f.reason) || hadSound && !(f.reason && OTHER_WORDS.test(f.reason)));
25353
+ withSound = (f, hadSound) => refusedSound(f, hadSound) ? { ...f, sound: true } : f;
25354
+ failureKind = (f) => {
25355
+ if (REFUSED_REQUEST.has(f.code)) return "request";
25356
+ if (f.code === "CONTENT_REJECTED") return f.sound ? "sound" : "content";
25357
+ if (f.code === "UPSTREAM_ERROR" || f.retryable === true) return "later";
25358
+ return f.retryable === false ? "request" : "other";
25359
+ };
25360
+ KEEP_MODEL = "Keep the model: another one is used only when the user names it.";
25361
+ NEXT = {
25362
+ request: "Running it again unchanged fails again. First change what the reason names: a reference picture or frame of a shape or size the model does not take, a reference sound or clip it does not take, or a setting it does not have (seconds, aspect ratio, resolution; popost video generate --models lists what the model takes). " + KEEP_MODEL,
25363
+ sound: "The model's content check refused the reference sound: the voice sample that keeps the speaker's voice the same in every clip. That changes how the video sounds, so stop and ask the user which they want: another voice sample (popost video voice sample with another stretch, or another recording of theirs) or another model (one they name). Do not leave the voice reference out or change the voice on your own: the clips would speak with different voices.",
25364
+ content: "The same request would be refused again. Change the wording of the prompt (for example, leave out the names of brands, characters and well-known works); ask the user before changing or leaving out a picture of theirs.",
25365
+ later: "It was a failure of the service, not of the request: the same request may pass when it is run again later (a new attempt, priced again).",
25366
+ other: "Read the reason; running the command again makes a new attempt, priced again."
25367
+ };
25368
+ nextAfter = (f) => NEXT[failureKind(f)];
25369
+ WHAT = {
25370
+ VIDEO_REQUEST_REJECTED: "the video model does not take this request as it is",
25371
+ VIDEO_OPTION_UNSUPPORTED: "the video model does not take this request as it is",
25372
+ CONTENT_REJECTED: "the model's content check refused it",
25373
+ UPSTREAM_ERROR: "the generation service failed for now"
25374
+ };
25375
+ failureLine = (f, o) => {
25376
+ const why = f.reason ?? (o.message?.trim().slice(0, REASON_CHARS) || void 0);
25377
+ const what = WHAT[f.code] ? WHAT[f.code] + (why ? " (" + why + ")" : "") + " [" + f.code + "]" : o.other;
25378
+ const money = o.charged === "refunded" ? "Its credits were refunded, so nothing was charged." : "Nothing was charged.";
25379
+ return "The clip could not be made: " + what + ". " + money + " " + nextAfter(f);
25380
+ };
25381
+ KNOWN_FAILURE = /\[(CONTENT_REJECTED|VIDEO_REQUEST_REJECTED|VIDEO_OPTION_UNSUPPORTED|UPSTREAM_ERROR)\]/;
25382
+ failedProblem = (m, hadSound) => {
25383
+ const named = m.error?.match(KNOWN_FAILURE)?.[1];
25384
+ const f = m.failure ?? (named ? withSound({ code: named }, hadSound) : void 0);
25385
+ const money = m.failure?.refundedCredits ? " Its " + m.failure.refundedCredits + " credits were refunded." : "";
25386
+ const message2 = m.failure?.reason ? "It could not be made [" + m.failure.code + "]: " + m.failure.reason + "." + money : "It could not be made: " + m.error;
25387
+ return { message: message2, fix: f ? nextAfter(f) : "Read the message; a request that was refused cost nothing. Run the command again to make only what is missing." };
25388
+ };
25389
+ }
25390
+ });
25391
+
25392
+ // src/video/generate/picture-fit.ts
25393
+ var DEFAULT_PICTURE_LIMITS, positive2, isBag, first, pair2, HOLDERS, MIN_RATIO2, MAX_RATIO, MIN_SIDE, MAX_SIDE2, statedIn, pictureLimitsOf, fitPlan, jpegOrientation, tiffOrientation, shownSize, size, ratioText, rangeText, fitText, fittedList, fitKey, BLUR_SHARE, FILL_BRIGHTNESS, fitArgs, decodedSize, fitPicture;
25394
+ var init_picture_fit = __esm({
25395
+ "src/video/generate/picture-fit.ts"() {
25396
+ "use strict";
25397
+ init_image();
25398
+ init_util();
25399
+ init_host();
25400
+ init_ffmpeg();
25401
+ DEFAULT_PICTURE_LIMITS = { minRatio: 0.4, maxRatio: 2.5, minSide: 300, maxSide: 6e3 };
25402
+ positive2 = (v) => {
25403
+ if (typeof v === "number" && Number.isFinite(v) && v > 0) return v;
25404
+ const m = typeof v === "string" ? /^\s*(\d+(?:\.\d+)?)\s*(?:[:/]\s*(\d+(?:\.\d+)?))?\s*$/.exec(v) : null;
25405
+ if (!m) return void 0;
25406
+ const value = m[2] === void 0 ? Number(m[1]) : Number(m[1]) / Number(m[2]);
25407
+ return Number.isFinite(value) && value > 0 ? value : void 0;
25408
+ };
25409
+ isBag = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
25410
+ first = (bag, names) => names.map((n) => positive2(bag[n])).find((v) => v !== void 0);
25411
+ pair2 = (v) => Array.isArray(v) && v.length === 2 ? [positive2(v[0]), positive2(v[1])] : isBag(v) ? [positive2(v.min), positive2(v.max)] : [void 0, void 0];
25412
+ HOLDERS = ["imageSize", "pictureLimits", "imageLimits", "referenceImageLimits", "pictures", "images"];
25413
+ MIN_RATIO2 = ["minRatio", "minAspectRatio", "minPictureRatio", "minImageRatio"];
25414
+ MAX_RATIO = ["maxRatio", "maxAspectRatio", "maxPictureRatio", "maxImageRatio"];
25415
+ MIN_SIDE = ["minSide", "minEdge", "minDimension", "minPictureSide", "minImageSide"];
25416
+ MAX_SIDE2 = ["maxSide", "maxEdge", "maxDimension", "maxPictureSide", "maxImageSide"];
25417
+ statedIn = (bag) => {
25418
+ const [ratioLow, ratioHigh] = pair2(bag.ratio ?? bag.aspectRatio ?? bag.ratioRange ?? bag.aspectRatioRange);
25419
+ const [sideLow, sideHigh] = pair2(bag.side ?? bag.sides ?? bag.sideRange);
25420
+ const minSide = first(bag, MIN_SIDE) ?? sideLow ?? (positive2(bag.minWidth) && positive2(bag.minHeight) ? Math.max(positive2(bag.minWidth) ?? 0, positive2(bag.minHeight) ?? 0) : void 0);
25421
+ const maxSide = first(bag, MAX_SIDE2) ?? sideHigh ?? (positive2(bag.maxWidth) && positive2(bag.maxHeight) ? Math.min(positive2(bag.maxWidth) ?? Infinity, positive2(bag.maxHeight) ?? Infinity) : void 0);
25422
+ const found = { minRatio: first(bag, MIN_RATIO2) ?? ratioLow, maxRatio: first(bag, MAX_RATIO) ?? ratioHigh, minSide, maxSide };
25423
+ return Object.fromEntries(Object.entries(found).filter(([, v]) => v !== void 0));
25424
+ };
25425
+ pictureLimitsOf = (model) => {
25426
+ if (!isBag(model)) return DEFAULT_PICTURE_LIMITS;
25427
+ const stated = [model, ...HOLDERS.map((h) => model[h]).filter(isBag)].reduce((acc, bag) => ({ ...statedIn(bag), ...acc }), {});
25428
+ const limits = { ...DEFAULT_PICTURE_LIMITS, ...stated };
25429
+ return limits.minRatio <= limits.maxRatio && limits.minSide <= limits.maxSide ? limits : DEFAULT_PICTURE_LIMITS;
25430
+ };
25431
+ fitPlan = (width, height, limits) => {
25432
+ const ratio3 = width / height;
25433
+ const wide = ratio3 < limits.minRatio ? height * limits.minRatio : width;
25434
+ const tall = ratio3 > limits.maxRatio ? width / limits.maxRatio : height;
25435
+ const [short3, long] = [Math.min(wide, tall), Math.max(wide, tall)];
25436
+ const scale = long > limits.maxSide ? limits.maxSide / long : short3 < limits.minSide ? limits.minSide / short3 : 1;
25437
+ if (scale === 1 && wide === width && tall === height) return void 0;
25438
+ const pw = Math.max(1, Math.round(width * scale));
25439
+ const ph = Math.max(1, Math.round(height * scale));
25440
+ let cw = pw / ph < limits.minRatio ? Math.ceil(ph * limits.minRatio - 1e-9) : pw;
25441
+ let ch = pw / ph > limits.maxRatio ? Math.ceil(pw / limits.maxRatio - 1e-9) : ph;
25442
+ if (cw < limits.minSide && cw >= limits.minSide - 1) cw = limits.minSide;
25443
+ if (ch < limits.minSide && ch >= limits.minSide - 1) ch = limits.minSide;
25444
+ return { from: [width, height], picture: [pw, ph], canvas: [cw, ch] };
25445
+ };
25446
+ jpegOrientation = (b) => {
25447
+ if (b[0] !== 255 || b[1] !== 216) return 1;
25448
+ for (let o = 2; o + 4 < b.length && b[o] === 255; ) {
25449
+ const marker = b[o + 1] ?? 0;
25450
+ const length2 = (b[o + 2] ?? 0) << 8 | (b[o + 3] ?? 0);
25451
+ if (marker === 218 || marker === 217) return 1;
25452
+ if (marker === 225 && String.fromCharCode(...b.subarray(o + 4, o + 10)) === "Exif\0\0") return tiffOrientation(b.subarray(o + 10, o + 2 + length2));
25453
+ o += 2 + length2;
25454
+ }
25455
+ return 1;
25456
+ };
25457
+ tiffOrientation = (t) => {
25458
+ const little = t[0] === 73;
25459
+ const u16 = (o) => little ? (t[o] ?? 0) | (t[o + 1] ?? 0) << 8 : (t[o] ?? 0) << 8 | (t[o + 1] ?? 0);
25460
+ const u322 = (o) => little ? u16(o) + u16(o + 2) * 65536 : u16(o) * 65536 + u16(o + 2);
25461
+ const ifd = u322(4);
25462
+ for (let i = 0, n = u16(ifd); i < n && ifd + 2 + i * 12 + 12 <= t.length; i++) {
25463
+ const entry2 = ifd + 2 + i * 12;
25464
+ if (u16(entry2) === 274) {
25465
+ const value = u16(entry2 + 8);
25466
+ return value >= 1 && value <= 8 ? value : 1;
25467
+ }
25468
+ }
25469
+ return 1;
25470
+ };
25471
+ shownSize = (bytes) => {
25472
+ try {
25473
+ const info = sniffImage(bytes);
25474
+ return info.format === "jpeg" && jpegOrientation(bytes) >= 5 ? [info.height, info.width] : [info.width, info.height];
25475
+ } catch (e) {
25476
+ if (e instanceof ImageError) return void 0;
25477
+ throw e;
25478
+ }
25479
+ };
25480
+ size = (s) => s[0] + "x" + s[1];
25481
+ ratioText = (s) => String(Math.round(s[0] / s[1] * 1e3) / 1e3);
25482
+ rangeText = (limits) => "the video model takes width/height from " + limits.minRatio + " to " + limits.maxRatio + " and sides of " + limits.minSide + " to " + limits.maxSide + " px";
25483
+ fitText = (plan4, limits) => {
25484
+ const [from, picture3, canvas] = [plan4.from, plan4.picture, plan4.canvas];
25485
+ const scaled2 = picture3[0] === from[0] && picture3[1] === from[1] ? "" : (picture3[0] > from[0] ? "scaled up" : "scaled down") + " to " + size(picture3);
25486
+ const padded = canvas[0] === picture3[0] && canvas[1] === picture3[1] ? "" : "padded " + (canvas[0] > picture3[0] ? "left and right" : "above and below") + " to " + size(canvas) + " (width/height " + ratioText(canvas) + "; it was " + ratioText(from) + ") with a blurred, darkened copy of the picture";
25487
+ return [scaled2, padded].filter(Boolean).join(", then ") + "; nothing of the picture was cut (" + rangeText(limits) + ")";
25488
+ };
25489
+ fittedList = (value) => {
25490
+ if (!Array.isArray(value)) return void 0;
25491
+ const text13 = (v) => typeof v === "string" ? v.slice(0, 600) : void 0;
25492
+ const list7 = value.flatMap((v) => {
25493
+ if (!isBag(v)) return [];
25494
+ const [file, was, now, how] = [text13(v.file), text13(v.was), text13(v.now), text13(v.how)];
25495
+ return file && was && now && how ? [{ file, was, now, how }] : [];
25496
+ });
25497
+ return list7.length ? list7 : void 0;
25498
+ };
25499
+ fitKey = (plan4) => "fit1:" + size(plan4.picture) + "@" + size(plan4.canvas);
25500
+ BLUR_SHARE = 1 / 24;
25501
+ FILL_BRIGHTNESS = 0.5;
25502
+ fitArgs = (src, out2, plan4) => {
25503
+ const [[w, h], [pw, ph], [cw, ch]] = [plan4.from, plan4.picture, plan4.canvas];
25504
+ const quality = out2.endsWith(".png") ? [] : ["-q:v", "2"];
25505
+ if (cw === pw && ch === ph) return ["-y", "-loglevel", "error", "-i", src, "-vf", "scale=" + pw + ":" + ph + ":flags=lanczos", "-frames:v", "1", ...quality, out2];
25506
+ const cover = Math.max(cw / w, ch / h);
25507
+ const [bw, bh] = [Math.max(cw, Math.ceil(w * cover)), Math.max(ch, Math.ceil(h * cover))];
25508
+ const sigma = Math.min(1024, Math.max(4, Math.round(Math.max(cw, ch) * BLUR_SHARE)));
25509
+ const dim = "colorchannelmixer=rr=" + FILL_BRIGHTNESS + ":gg=" + FILL_BRIGHTNESS + ":bb=" + FILL_BRIGHTNESS;
25510
+ const graph = "[0:v]split=2[a][b];[a]format=rgb24,scale=" + bw + ":" + bh + ":flags=bilinear,crop=" + cw + ":" + ch + ",gblur=sigma=" + sigma + "," + dim + "[bg];[b]scale=" + pw + ":" + ph + ":flags=lanczos[fg];[bg][fg]overlay=" + Math.floor((cw - pw) / 2) + ":" + Math.floor((ch - ph) / 2) + ":format=rgb,format=rgb24[out]";
25511
+ return ["-y", "-loglevel", "error", "-i", src, "-filter_complex", graph, "-map", "[out]", "-frames:v", "1", ...quality, out2];
25512
+ };
25513
+ decodedSize = async (rt, src) => {
25514
+ const r = await runFfmpegOk(rt, ["-i", src, "-vf", "showinfo", "-frames:v", "1", "-f", "null", "-"]);
25515
+ const m = /\bs:(\d+)x(\d+)\b/.exec(r.stderr);
25516
+ return m ? [Number(m[1]), Number(m[2])] : void 0;
25517
+ };
25518
+ fitPicture = async (rt, src, mimeType2, plan4, limits) => {
25519
+ const decoded = await decodedSize(rt, src);
25520
+ const used = decoded && (decoded[0] !== plan4.from[0] || decoded[1] !== plan4.from[1]) ? fitPlan(decoded[0], decoded[1], limits) ?? plan4 : plan4;
25521
+ const png2 = mimeType2 === "image/png";
25522
+ return withTempDir(rt, "popost-fit-", async (dir) => {
25523
+ const out2 = rt.path.join(dir, png2 ? "fitted.png" : "fitted.jpg");
25524
+ await runFfmpegOk(rt, fitArgs(src, out2, used));
25525
+ const bytes = await rt.fs.readFile(out2);
25526
+ return { bytes, mimeType: png2 ? "image/png" : "image/jpeg", sha256: sha256(bytes) };
25527
+ });
25528
+ };
25529
+ }
25530
+ });
25531
+
25242
25532
  // src/video/generate/index.ts
25243
- var ConfirmNeeded, CONFIRM_EXIT2, StillMaking, PENDING_EXIT2, run3, lastObject, isPrice, isPending, commandGenerator, VIDEOS, PICTURES, NOTES, REFERENCES, LISTS, ASPECT5, extOf, inputKey, kindOf3, FRAME_FIX, frameProblems, SHORT_CLIP, MANY_SHORT, groupingAdvice, checkRequests, beatsSaid, saidBefore, ANCHOR_FILE, CLOSE, usesFrames2, takesAnchor, anchorIndex, grabAnchor, NOTHING_ADDED, anchorSentence, anchored, readNotes, inOrder, lastFrameFile, lastFrameOf, afterFailure, makeMaterials, makeMaterialsIn;
25533
+ var ConfirmNeeded, CONFIRM_EXIT2, StillMaking, PENDING_EXIT2, run3, lastObject, isPrice, isPending, withFitted, commandGenerator, VIDEOS, PICTURES, NOTES, REFERENCES, LISTS, ASPECT5, extOf, inputKey, kindOf3, FRAME_FIX, frameProblems, SHORT_CLIP, MANY_SHORT, groupingAdvice, checkRequests, beatsSaid, saidBefore, ANCHOR_FILE, CLOSE, usesFrames2, takesAnchor, anchorIndex, grabAnchor, NOTHING_ADDED, anchorSentence, anchored, readNotes, inOrder, inProject2, lastFrameFile, lastFrameOf, makeMaterials, makeMaterialsIn;
25244
25534
  var init_generate = __esm({
25245
25535
  "src/video/generate/index.ts"() {
25246
25536
  "use strict";
@@ -25265,8 +25555,11 @@ var init_generate = __esm({
25265
25555
  init_modes();
25266
25556
  init_sample();
25267
25557
  init_clip_sound();
25558
+ init_voice_clips();
25268
25559
  init_requests();
25269
25560
  init_sheet3();
25561
+ init_failure();
25562
+ init_picture_fit();
25270
25563
  ConfirmNeeded = class extends Error {
25271
25564
  constructor(confirm4, message2) {
25272
25565
  super(message2);
@@ -25301,6 +25594,10 @@ var init_generate = __esm({
25301
25594
  };
25302
25595
  isPrice = (value) => value !== null && typeof value === "object" && typeof value.credits === "number";
25303
25596
  isPending = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
25597
+ withFitted = ({ fitted: listed3, ...rest }) => {
25598
+ const fitted = fittedList(listed3);
25599
+ return { ...rest, ...fitted ? { fitted } : {} };
25600
+ };
25304
25601
  commandGenerator = (rt) => {
25305
25602
  const words = toolCommand(rt, "POPOST_GEN_CMD");
25306
25603
  if (!words) return void 0;
@@ -25312,11 +25609,13 @@ var init_generate = __esm({
25312
25609
  const said = lastObject(r.stdout);
25313
25610
  const why = r.stderr.trim().split("\n").slice(-2).join(" | ");
25314
25611
  if (r.code === CONFIRM_EXIT2 && isPrice(said.confirm)) throw new ConfirmNeeded(said.confirm, why || "It costs " + said.confirm.credits + " credits and needs the user's agreement first; nothing was charged.");
25315
- if (r.code === PENDING_EXIT2 && isPending(said.pending)) throw new StillMaking(said.pending, why || "It is still being made.");
25612
+ if (r.code === PENDING_EXIT2 && isPending(said.pending)) throw new StillMaking(withFitted(said.pending), why || "It is still being made.");
25613
+ const failure4 = r.code !== 0 ? failureOf6(said.error) : void 0;
25614
+ if (failure4) throw new GenerationFailed(failure4, why || "The generator exited with " + r.code + " [" + failure4.code + "].");
25316
25615
  if (r.code !== 0) throw new Error(why || "The generator exited with " + r.code + ".");
25317
25616
  const count5 = (v) => typeof v === "number" ? v : void 0;
25318
- const [credits2, chargedCredits] = [count5(said.credits), count5(said.chargedCredits)];
25319
- return { ...credits2 !== void 0 ? { credits: credits2 } : {}, ...chargedCredits !== void 0 ? { chargedCredits } : {}, ...typeof said.key === "string" ? { key: said.key } : {}, ...typeof said.task === "string" ? { task: said.task } : {} };
25617
+ const [credits2, chargedCredits, fitted] = [count5(said.credits), count5(said.chargedCredits), fittedList(said.fitted)];
25618
+ return { ...credits2 !== void 0 ? { credits: credits2 } : {}, ...chargedCredits !== void 0 ? { chargedCredits } : {}, ...typeof said.key === "string" ? { key: said.key } : {}, ...typeof said.task === "string" ? { task: said.task } : {}, ...fitted ? { fitted } : {} };
25320
25619
  })
25321
25620
  };
25322
25621
  };
@@ -25497,11 +25796,11 @@ var init_generate = __esm({
25497
25796
  return { ...r, images, prompt: r.prompt.trim() + " " + anchorSentence(images.length, source2, person) + (product ? pl(" The product follows its own pictures named above, not @image" + images.length + ".", "\u5546\u54C1\u4EE5\u4E0A\u9762\u6307\u660E\u7684\u5546\u54C1\u56FE\u7247\u4E3A\u51C6\uFF0C\u4E0D\u4EE5 @image" + images.length + " \u4E3A\u51C6\u3002") : "") };
25498
25797
  };
25499
25798
  readNotes = (rt, dir) => rt.fs.readText(rt.path.join(dir, NOTES)).then((t) => JSON.parse(t), () => ({}));
25500
- inOrder = (requests, first) => {
25501
- const out2 = first >= 0 ? [requests[first]] : [];
25799
+ inOrder = (requests, first2) => {
25800
+ const out2 = first2 >= 0 ? [requests[first2]] : [];
25502
25801
  const listed3 = new Set(requests.map((r) => r.file));
25503
25802
  const placed2 = new Set(out2.map((r) => r.file));
25504
- let left = requests.filter((_r, i) => i !== first);
25803
+ let left = requests.filter((_r, i) => i !== first2);
25505
25804
  while (left.length) {
25506
25805
  const ready = left.filter((r) => !r.continues || placed2.has(r.continues) || !listed3.has(r.continues));
25507
25806
  for (const r of ready.length ? ready : left) {
@@ -25512,6 +25811,10 @@ var init_generate = __esm({
25512
25811
  }
25513
25812
  return out2;
25514
25813
  };
25814
+ inProject2 = (rt, dir, fitted) => fitted.map((f) => {
25815
+ const inside6 = rt.path.relative(dir, f.file);
25816
+ return inside6 && !inside6.startsWith("..") && !rt.path.isAbsolute(inside6) ? { ...f, file: inside6.split(rt.path.sep).join("/") } : f;
25817
+ });
25515
25818
  lastFrameFile = (clip11) => clip11.slice(0, clip11.length - extOf(clip11).length) + ".last.png";
25516
25819
  lastFrameOf = async (rt, dir, clip11, frame2) => {
25517
25820
  const from = rt.path.resolve(dir, clip11);
@@ -25522,7 +25825,6 @@ var init_generate = __esm({
25522
25825
  await extractFrame(rt, from, index, to);
25523
25826
  return to;
25524
25827
  };
25525
- afterFailure = (message2) => message2.includes("[CONTENT_REJECTED]") ? "Its content was refused, and the same request would be refused again (it cost nothing). Change the prompt or the reference pictures of this request (for example, leave out the names of brands, characters and well-known works, and pictures of them), then run the command again." : "Read the message; a request that was refused cost nothing. Run the command again to make only what is missing.";
25526
25828
  makeMaterials = async (rt, o) => withPromptLang(o.lang ?? await readProjectLang(rt, o.dir), o.policy ?? "user", () => makeMaterialsIn(rt, o));
25527
25829
  makeMaterialsIn = async (rt, o) => {
25528
25830
  const replication = await materialReplicationProblems(rt, o.dir, o.requests);
@@ -25540,7 +25842,6 @@ var init_generate = __esm({
25540
25842
  said.push(...sound2.notes);
25541
25843
  const locked = /* @__PURE__ */ new Map();
25542
25844
  const voices = /* @__PURE__ */ new Map();
25543
- const spoken = /* @__PURE__ */ new Map();
25544
25845
  const uses = /* @__PURE__ */ new Map();
25545
25846
  for (const r of o.requests) for (const id2 of r.cast ?? []) uses.set(id2, (uses.get(id2) ?? 0) + 1);
25546
25847
  for (const r of o.requests) if (r.cast?.length) {
@@ -25557,23 +25858,8 @@ var init_generate = __esm({
25557
25858
  problems2.push(error(r.file + ".cast", String(e), "Complete every identity image before generating any clip."));
25558
25859
  }
25559
25860
  }
25560
- for (const r of o.requests) if (r.speech) {
25861
+ for (const r of o.requests) if (r.speech && r.speech.mode !== "native") {
25561
25862
  const speaker = speakersOf(r.speech)[0] ?? "";
25562
- if (r.speech.mode === "native") {
25563
- const refs = [];
25564
- for (const id2 of speakersOf(r.speech)) {
25565
- const profile = await voiceProfile(rt, o.dir, id2).catch(() => void 0);
25566
- if (profile) refs.push({ id: id2, profile });
25567
- }
25568
- if (!refs.length) continue;
25569
- if (!usesFrames2(r)) {
25570
- spoken.set(r.file, refs);
25571
- if (refs[0]?.id === speaker) voices.set(r.file, refs[0].profile);
25572
- continue;
25573
- }
25574
- said.push(r.file + ": " + refs.map((v) => v.id).join(", ") + " speak" + (refs.length === 1 ? "s" : "") + " with the video model's own voice; the voice registered for the project is not passed as a reference (this clip starts from a frame, and a clip made from frames takes no references). Listen to the clip beside the voice-over.");
25575
- continue;
25576
- }
25577
25863
  try {
25578
25864
  const profile = await voiceProfile(rt, o.dir, speaker);
25579
25865
  if (!profile) continue;
@@ -25598,19 +25884,21 @@ var init_generate = __esm({
25598
25884
  const materials2 = [];
25599
25885
  const takers = o.requests.filter(takesAnchor).length;
25600
25886
  const fromClip = !o.picture && o.anchor !== false && takers >= (o.anchor ? 1 : 2);
25601
- const first = fromClip ? anchorIndex(o.requests) : -1;
25602
- const order = inOrder(o.requests, first);
25603
- const anchorFile = first >= 0 ? o.requests[first].file : void 0;
25887
+ const first2 = fromClip ? anchorIndex(o.requests) : -1;
25888
+ const order = inOrder(o.requests, first2);
25889
+ const anchorFile = first2 >= 0 ? o.requests[first2].file : void 0;
25890
+ const voicePlan = planVoiceClips(order, new Set((await readVoices(rt, o.dir).catch(() => ({ speakers: [] }))).speakers.map((v) => v.id)), (r) => kindOf3(r.file) === "video" && !usesFrames2(r));
25891
+ const settled2 = /* @__PURE__ */ new Set(), voiceClipFiles = new Set(voicePlan.clipOf.values());
25604
25892
  const source2 = o.picture ? o.picture.person ? "character" : "image" : fromClip ? "clip" : void 0;
25605
25893
  let picture3 = o.picture?.file;
25606
25894
  const absent2 = /* @__PURE__ */ new Map();
25607
25895
  for (const [i, original] of order.entries()) {
25608
25896
  const cast = locked.get(original.file);
25609
- const voice2 = voices.get(original.file);
25897
+ const refs = original.speech?.mode === "native" ? await clipVoices(rt, o.dir, original, usesFrames2(original), said) : [];
25898
+ const voice2 = voices.get(original.file) ?? (original.speech && refs[0]?.id === speakersOf(original.speech)[0] ? refs[0]?.profile : void 0);
25610
25899
  const shown3 = withProducts(original, sheet4.sheet);
25611
25900
  const base = shown3?.request ?? original;
25612
25901
  const withCast = cast ? { ...base, ...!usesFrames2(base) ? { images: [...base.images ?? [], ...cast.images] } : {}, prompt: base.prompt + " " + cast.instruction } : base;
25613
- const refs = original.speech?.mode === "native" ? spoken.get(original.file) ?? [] : [];
25614
25902
  const { ids: ids3, samples } = await speakerSamples(rt, o.dir, original.file, refs, said);
25615
25903
  const asked3 = ids3.length ? { ...withCast, audios: [...withCast.audios ?? [], ...samples], prompt: withCast.prompt + VOICE_NAMED(ids3, (withCast.audios?.length ?? 0) + 1) } : withCast;
25616
25904
  const sent = isDialogue(original.speech) ? timedDialogue(original.speech, o.times) : original.speech;
@@ -25623,20 +25911,20 @@ var init_generate = __esm({
25623
25911
  cast?.legacyInstructions?.map((instruction) => ({ ...signed(asked3), prompt: original.prompt + " " + instruction + (ids3.length ? VOICE_NAMED(ids3, (withCast.audios?.length ?? 0) + 1) : "") })) ?? []
25624
25912
  );
25625
25913
  if (refs.length) {
25626
- const first2 = refs[0].profile;
25627
- const before2 = { ...withCast, audios: [...withCast.audios ?? [], first2.reference], prompt: withCast.prompt + " @audio" + ((withCast.audios?.length ?? 0) + 1) + " defines the voice identity and timbre only. Speak the exact new dialogue with that voice, never the reference recording\u2019s words. Keep the speaker\u2019s voice stable across all shots." };
25914
+ const first3 = refs[0].profile;
25915
+ const before2 = { ...withCast, audios: [...withCast.audios ?? [], first3.reference], prompt: withCast.prompt + " @audio" + ((withCast.audios?.length ?? 0) + 1) + " defines the voice identity and timbre only. Speak the exact new dialogue with that voice, never the reference recording\u2019s words. Keep the speaker\u2019s voice stable across all shots." };
25628
25916
  signatures.push(
25629
25917
  ...materialSignatures(
25630
- { request: signed(before2), voiceHash: first2.sha256, dependencies: await dependenciesOf(before2), ...rest },
25918
+ { request: signed(before2), voiceHash: first3.sha256, dependencies: await dependenciesOf(before2), ...rest },
25631
25919
  cast?.legacyInstructions?.map((instruction) => ({ ...signed(before2), prompt: original.prompt + " " + instruction + before2.prompt.slice(withCast.prompt.length) })) ?? []
25632
25920
  ),
25633
25921
  ...materialSignatures({ request: signed(withCast), dependencies: await dependenciesOf(withCast), ...rest }, cast?.legacyInstructions?.map((instruction) => ({ ...signed(withCast), prompt: original.prompt + " " + instruction })) ?? [])
25634
25922
  );
25635
25923
  }
25636
25924
  const signature2 = signatures[0];
25637
- const isAnchor = first >= 0 && i === 0;
25925
+ const isAnchor = first2 >= 0 && i === 0;
25638
25926
  const takes = source2 !== void 0 && takesAnchor(asked3) && !isAnchor;
25639
- const needs = [...takes && anchorFile ? [anchorFile] : [], ...asked3.continues ? [asked3.continues] : []];
25927
+ const needs = [...takes && anchorFile ? [anchorFile] : [], ...asked3.continues ? [asked3.continues] : [], ...voiceClipsAwaited(voicePlan, asked3.file, settled2)];
25640
25928
  const kind = kindOf3(asked3.file);
25641
25929
  const mode = sound2.modeOf(original);
25642
25930
  const basis = mode ? sound2.basisOf(original) : void 0;
@@ -25711,6 +25999,7 @@ var init_generate = __esm({
25711
25999
  entry2 = { ...entry2, receipt };
25712
26000
  }
25713
26001
  if (made.task) entry2 = { ...entry2, task: made.task };
26002
+ if (made.fitted) entry2 = { ...entry2, fitted: inProject2(rt, o.dir, made.fitted) };
25714
26003
  if (mode) await writeModeReceipt(rt, target2, { sound: mode, ...basis ? { clipMusic: basis } : {}, ...stripped ? { stripped: true } : {} });
25715
26004
  if (asked3.speech) {
25716
26005
  for (const ext of [".speech.wav", ".speech.json"]) if (await exists4(partial + ext)) await rt.fs.rename(partial + ext, target2 + ext);
@@ -25724,11 +26013,11 @@ var init_generate = __esm({
25724
26013
  if (e instanceof StillMaking) {
25725
26014
  absent2.set(asked3.file, "pending");
25726
26015
  const charged = e.pending.chargedCredits;
25727
- materials2.push({ ...entry2, pending: true, ...e.pending.task ? { task: e.pending.task } : {}, ...charged !== void 0 ? { chargedCredits: charged } : {} });
26016
+ materials2.push({ ...entry2, pending: true, ...e.pending.task ? { task: e.pending.task } : {}, ...charged !== void 0 ? { chargedCredits: charged } : {}, ...e.pending.fitted ? { fitted: inProject2(rt, o.dir, e.pending.fitted) } : {} });
25728
26017
  continue;
25729
26018
  }
25730
26019
  absent2.set(asked3.file, e instanceof ConfirmNeeded ? "priced" : "failed");
25731
- materials2.push({ ...entry2, error: e instanceof Error ? e.message : String(e), ...e instanceof ConfirmNeeded ? { confirm: e.confirm } : {}, ...priceOnly ? { waiting: true, waitsFor: priced } : {} });
26020
+ materials2.push({ ...entry2, error: e instanceof Error ? e.message : String(e), ...e instanceof ConfirmNeeded ? { confirm: e.confirm } : {}, ...e instanceof GenerationFailed ? { failure: withSound(e.failure, (asked3.audios?.length ?? 0) > 0) } : {}, ...priceOnly ? { waiting: true, waitsFor: priced } : {} });
25732
26021
  continue;
25733
26022
  }
25734
26023
  }
@@ -25747,18 +26036,24 @@ var init_generate = __esm({
25747
26036
  else absent2.set(asked3.file, "failed");
25748
26037
  entry2 = { ...entry2, anchor: true };
25749
26038
  }
26039
+ if (voiceClipFiles.has(asked3.file)) for (const s of await adoptClipVoice(rt, o.dir, voicePlan, asked3.file, said)) settled2.add(s);
25750
26040
  notes2[asked3.file] = asked3.note ?? asked3.prompt;
25751
26041
  await rt.fs.writeFile(rt.path.join(o.dir, NOTES), JSON.stringify(notes2, null, 1) + "\n");
25752
26042
  materials2.push(entry2);
25753
26043
  }
25754
- const why = (m) => m.waitsFor === anchorFile && !o.requests.some((r) => r.file === m.file && r.continues === m.waitsFor) ? "a frame of it goes to this clip as a reference picture, so that the clips show the same person, product and place" : "this clip starts from its last frame";
26044
+ const failedError = (m) => {
26045
+ const request = o.requests.find((r) => r.file === m.file);
26046
+ const { message: message2, fix: fix2 } = failedProblem(m, (request?.audios?.length ?? 0) > 0);
26047
+ return error(m.file, message2, fix2 + (source2 && m.file !== anchorFile && request && takesAnchor(request) ? " It was sent with the anchor picture as a reference picture: a generator that takes none needs --no-anchor." : ""));
26048
+ };
26049
+ const why = (m) => m.waitsFor === anchorFile && !o.requests.some((r) => r.file === m.file && r.continues === m.waitsFor) ? "a frame of it goes to this clip as a reference picture, so that the clips show the same person, product and place" : voiceClipFiles.has(m.waitsFor ?? "") ? "the voice its speaker has there goes to this clip as the reference sound, so that the speaker keeps one voice" : "this clip starts from its last frame";
25755
26050
  const failed4 = materials2.filter((m) => m.error).map(
25756
- (m) => m.confirm ? m.confirm.reason === "unplanned" ? error(m.file, "It was not made: it is outside the recorded clip plan and costs " + m.confirm.credits + " credits. Nothing was charged for it.", unplannedNext(m.confirm.clip?.key)) : error(m.file, "It was not made: it costs " + m.confirm.credits + " credits, and the user has not agreed to that price. Nothing was charged.", "Show the user the price with what it buys (confirm has the total and each clip's model, resolution, seconds and aspect ratio). Only after they agree, or when it fits what is left of the agreed budget, run again with --confirm --max-credits N.") : error(m.file, "It could not be made: " + m.error, afterFailure(m.error ?? "") + (source2 && m.file !== anchorFile && takesAnchor(o.requests.find((r) => r.file === m.file)) ? " It was sent with the anchor picture as a reference picture: a generator that takes none needs --no-anchor." : ""))
26051
+ (m) => m.confirm ? m.confirm.reason === "unplanned" ? error(m.file, "It was not made: it is outside the recorded clip plan and costs " + m.confirm.credits + " credits. Nothing was charged for it.", unplannedNext(m.confirm.clip?.key)) : error(m.file, "It was not made: it costs " + m.confirm.credits + " credits, and the user has not agreed to that price. Nothing was charged.", "Show the user the price with what it buys (confirm has the total and each clip's model, resolution, seconds and aspect ratio). Only after they agree, or when it fits what is left of the agreed budget, run again with --confirm --max-credits N.") : failedError(m)
25757
26052
  );
25758
26053
  const held = materials2.filter((m) => m.waiting && !m.confirm && !m.queued).map((m) => error(
25759
26054
  m.file,
25760
26055
  "It was not sent: it waits for " + m.waitsFor + " (" + why(m) + "), and that clip is not there" + (materials2.some((x2) => x2.file === m.waitsFor && !x2.error && !x2.waiting) ? " as a file a frame can be read from" : "") + ". Nothing was charged for it.",
25761
- "Get " + m.waitsFor + " made first (its own problem says how; a file no frame can be read from is deleted and made again), then run the command again." + (m.waitsFor === anchorFile ? " --no-anchor makes the clips now, without a shared picture." : "")
26056
+ "Get " + m.waitsFor + " made first (its own problem says how; a file no frame can be read from is deleted and made again), then run the command again." + (m.waitsFor === anchorFile ? " --no-anchor makes the clips now, without a shared picture." : "") + (voiceClipFiles.has(m.waitsFor ?? "") ? " Or give the speaker a voice first (popost video voice add <project> --speaker <id> --file <a recording or a clip of theirs> --mode native-reference)." : "")
25762
26057
  ));
25763
26058
  const loose = materials2.filter((m) => m.unanchored).map((m) => warning(m.file, "It was made without " + (o.requests.some((r) => r.file === m.file && r.continues) ? "the frame it should start from" : "the anchor picture") + ': the generator was asked for its price only ("priceOnly": true in the request) while ' + m.waitsFor + " waited for the user's agreement, and made the clip.", "Look at it beside the other clips; when it does not match them, delete the file and run the command again once " + m.waitsFor + " exists."));
25764
26059
  const asked2 = materials2.filter((m) => m.confirm);
@@ -25875,8 +26170,8 @@ var init_record2 = __esm({
25875
26170
  block;
25876
26171
  name = "InputsPending";
25877
26172
  };
25878
- holdVoice = async (rt, dir, project, paying, o) => {
25879
- if (!paying) return;
26173
+ holdVoice = async (rt, dir, project, paying2, o) => {
26174
+ if (!paying2) return;
25880
26175
  const held = await voicePending(rt, dir, o);
25881
26176
  if (!held) return;
25882
26177
  const block = confirmBlock(rt, dir, await readInputs(rt, dir), held.pending, project);
@@ -25956,8 +26251,8 @@ var init_shared = __esm({
25956
26251
  const file = args.string(option);
25957
26252
  const data = file ? JSON.parse(await rt.fs.readText(userPath(rt, file))) : void 0;
25958
26253
  const captions = data !== null && typeof data === "object" ? data.captions : void 0;
25959
- const first = Array.isArray(captions) ? captions.find((c) => typeof c === "string" && c.trim()) : void 0;
25960
- return typeof first === "string" ? firstWords(first.replace(/\*/g, "")) : void 0;
26254
+ const first2 = Array.isArray(captions) ? captions.find((c) => typeof c === "string" && c.trim()) : void 0;
26255
+ return typeof first2 === "string" ? firstWords(first2.replace(/\*/g, "")) : void 0;
25961
26256
  };
25962
26257
  userPath = (rt, p) => rt.path.resolve(rt.cwd, p);
25963
26258
  }
@@ -26744,10 +27039,10 @@ var init_carry = __esm({
26744
27039
  const whole2 = numbered2.shots[j];
26745
27040
  const r = e.shots.find((s) => s.shot === j + 1);
26746
27041
  if (!x2 || !whole2 || !r) return shot;
26747
- const first = x2.start === whole2.start;
26748
- const effect = first ? shotEffect(e, numbered2, j, ratio3, picture3) : void 0;
27042
+ const first2 = x2.start === whole2.start;
27043
+ const effect = first2 ? shotEffect(e, numbered2, j, ratio3, picture3) : void 0;
26749
27044
  const { in: _measured, ...rest } = shot;
26750
- const read2 = first ? r.transitionIn : void 0;
27045
+ const read2 = first2 ? r.transitionIn : void 0;
26751
27046
  const corrected = read2 && read2.kind !== "custom" ? read2.kind === "cut" ? rest : {
26752
27047
  ...rest,
26753
27048
  in: {
@@ -26833,15 +27128,15 @@ var init_wav = __esm({
26833
27128
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
26834
27129
  let fmt;
26835
27130
  for (let at7 = 12; at7 + 8 <= bytes.length; ) {
26836
- const id2 = tag2(bytes, at7), size = view.getUint32(at7 + 4, true), body = at7 + 8;
26837
- if (id2 === "fmt " && size >= 16 && body + 16 <= bytes.length)
27131
+ const id2 = tag2(bytes, at7), size2 = view.getUint32(at7 + 4, true), body = at7 + 8;
27132
+ if (id2 === "fmt " && size2 >= 16 && body + 16 <= bytes.length)
26838
27133
  fmt = { format: view.getUint16(body, true), channels: view.getUint16(body + 2, true), sampleRate: view.getUint32(body + 4, true), byteRate: view.getUint32(body + 8, true), bitsPerSample: view.getUint16(body + 14, true) };
26839
27134
  if (id2 === "data") {
26840
27135
  if (!fmt || !fmt.byteRate) break;
26841
- const data = bytes.subarray(body, Math.min(bytes.length, body + size));
27136
+ const data = bytes.subarray(body, Math.min(bytes.length, body + size2));
26842
27137
  return { ...fmt, data, seconds: data.length / fmt.byteRate };
26843
27138
  }
26844
- at7 = body + size + size % 2;
27139
+ at7 = body + size2 + size2 % 2;
26845
27140
  }
26846
27141
  throw new Error("The WAV file has no format or no sound.");
26847
27142
  };
@@ -27123,10 +27418,10 @@ var init_speech2 = __esm({
27123
27418
  const out2 = [];
27124
27419
  for (const r of runs4) {
27125
27420
  const prev = out2[out2.length - 1];
27126
- const last = prev?.words[prev.words.length - 1], first = r.words[0], start = prev?.words[0], end = r.words[r.words.length - 1];
27127
- const crosses = boundaries.some((f) => f > mid(last) && f <= mid(first));
27421
+ const last = prev?.words[prev.words.length - 1], first2 = r.words[0], start = prev?.words[0], end = r.words[r.words.length - 1];
27422
+ const crosses = boundaries.some((f) => f > mid(last) && f <= mid(first2));
27128
27423
  const together2 = (end?.end ?? 0) - (start?.start ?? 0);
27129
- const paused = (first?.start ?? 0) - (last?.end ?? 0) >= pauseFrames;
27424
+ const paused = (first2?.start ?? 0) - (last?.end ?? 0) >= pauseFrames;
27130
27425
  if (prev && (span(prev) < min || span(r) < min) && !crosses && !paused && together2 <= max) out2[out2.length - 1] = { words: [...prev.words, ...r.words], pauses: [...prev.pauses, ...r.pauses] };
27131
27426
  else out2.push(r);
27132
27427
  }
@@ -27711,7 +28006,7 @@ var init_issues = __esm({
27711
28006
 
27712
28007
  // src/video/project/schema.ts
27713
28008
  import { z as z6 } from "zod";
27714
- var NAMED_COLORS, COLOR_RE, isColor, color, id, fraction, ease2, direction, pair2, GradientSchema, fill, shadowSchema, CanvasSchema, MaterialSchema, TransitionSchema, CameraMoveSchema, CameraObjectSchema, CameraSchema, footage, BaseObjectSchema, FOOTAGE_KEYS2, BaseSchema, SegmentSchema, MotionSchema, SHIFT, SpanObjectSchema, SpanSchema, StrokeSchema, BackgroundSchema, TextShadowSchema, TextSpanSchema, textSpans, SpokenPastSchema, SpokenSchema, TextStyleSchema, BorderSchema, ItemShadowSchema, LoopSchema, box, itemCommon, textStyle2, mask, TextTrackSchema, ImageTrackSchema, ShapeTrackSchema, VideoTrackSchema, AudioTrackSchema, CueSchema, CaptionTrackSchema, TrackSchema, ProjectSchema, keys, KEY_TABLE, asProject, parseProject;
28009
+ var NAMED_COLORS, COLOR_RE, isColor, color, id, fraction, ease2, direction, pair3, GradientSchema, fill, shadowSchema, CanvasSchema, MaterialSchema, TransitionSchema, CameraMoveSchema, CameraObjectSchema, CameraSchema, footage, BaseObjectSchema, FOOTAGE_KEYS2, BaseSchema, SegmentSchema, MotionSchema, SHIFT, SpanObjectSchema, SpanSchema, StrokeSchema, BackgroundSchema, TextShadowSchema, TextSpanSchema, textSpans, SpokenPastSchema, SpokenSchema, TextStyleSchema, BorderSchema, ItemShadowSchema, LoopSchema, box, itemCommon, textStyle2, mask, TextTrackSchema, ImageTrackSchema, ShapeTrackSchema, VideoTrackSchema, AudioTrackSchema, CueSchema, CaptionTrackSchema, TrackSchema, ProjectSchema, keys, KEY_TABLE, asProject, parseProject;
27715
28010
  var init_schema = __esm({
27716
28011
  "src/video/project/schema.ts"() {
27717
28012
  "use strict";
@@ -27729,7 +28024,7 @@ var init_schema = __esm({
27729
28024
  fraction = z6.number().min(0).max(1);
27730
28025
  ease2 = z6.enum(["linear", "in", "out", "in-out"]);
27731
28026
  direction = z6.enum(["left", "right", "up", "down"]);
27732
- pair2 = z6.tuple([z6.number().min(-1).max(1), z6.number().min(-1).max(1)]);
28027
+ pair3 = z6.tuple([z6.number().min(-1).max(1), z6.number().min(-1).max(1)]);
27733
28028
  GradientSchema = z6.object({
27734
28029
  type: z6.enum(["linear", "radial"]),
27735
28030
  angle: z6.number().min(-360).max(360).optional(),
@@ -27771,12 +28066,12 @@ var init_schema = __esm({
27771
28066
  to: z6.number().int().min(1),
27772
28067
  scale: z6.tuple([z6.number().gt(0).max(20), z6.number().gt(0).max(20)]),
27773
28068
  focus: z6.tuple([fraction, fraction]).optional(),
27774
- shift: z6.tuple([pair2, pair2]).optional(),
28069
+ shift: z6.tuple([pair3, pair3]).optional(),
27775
28070
  ease: ease2.optional()
27776
28071
  });
27777
28072
  CameraObjectSchema = z6.object({
27778
28073
  zoom: z6.number().min(-1).max(1).optional(),
27779
- pan: pair2.optional(),
28074
+ pan: pair3.optional(),
27780
28075
  moves: z6.array(CameraMoveSchema).min(1).max(64).optional()
27781
28076
  });
27782
28077
  CameraSchema = CameraObjectSchema.refine((c) => c.moves === void 0 || c.zoom === void 0 && c.pan === void 0, {
@@ -28057,8 +28352,8 @@ var init_words2 = __esm({
28057
28352
  const voice2 = parsed.success ? void 0 : VoiceWordsSchema.safeParse(json4);
28058
28353
  if (voice2?.success) return parseWordsFile({ fps: VOICE_FPS, tokens: voiceTokens(voice2.data.words) }, name);
28059
28354
  if (!parsed.success) {
28060
- const first = issueProblems(parsed.error.issues)[0];
28061
- return { error: 'The words file "' + name + '" is not a words file: ' + (first?.message ?? "wrong shape"), fix: (first?.fix ? first.fix + " " : "") + "The format is " + FORMAT3 + ' (as src/align writes it), or the { "words": [{ "text", "start", "end" }] } in seconds a voice writes beside its WAV.' };
28355
+ const first2 = issueProblems(parsed.error.issues)[0];
28356
+ return { error: 'The words file "' + name + '" is not a words file: ' + (first2?.message ?? "wrong shape"), fix: (first2?.fix ? first2.fix + " " : "") + "The format is " + FORMAT3 + ' (as src/align writes it), or the { "words": [{ "text", "start", "end" }] } in seconds a voice writes beside its WAV.' };
28062
28357
  }
28063
28358
  const file = parsed.data;
28064
28359
  for (let k = 0; k < file.tokens.length; k++) {
@@ -28133,15 +28428,15 @@ var init_speech_lock = __esm({
28133
28428
  continue;
28134
28429
  }
28135
28430
  for (const use2 of playsOf(r).filter((p) => p.play.material === id2)) {
28136
- const first = Math.max(0, use2.first, use2.play.start), last = Math.min(r.frames - 1, use2.last);
28137
- if (last < first) continue;
28431
+ const first2 = Math.max(0, use2.first, use2.play.start), last = Math.min(r.frames - 1, use2.last);
28432
+ if (last < first2) continue;
28138
28433
  const matched = r.audio.some((a) => {
28139
- if (a.src !== f.src || a.start > first || (a.end ?? r.frames) <= last || Math.abs((a.speed ?? 1) - use2.play.speed) > 1e-6) return false;
28140
- const audioTime = (a.from ? a.from.frame / a.from.fps : 0) + (first - a.start) / r.canvas.fps * (a.speed ?? 1);
28141
- const videoTime = sourceFrame(use2.play, f, r.canvas.fps, first) / f.fps;
28434
+ if (a.src !== f.src || a.start > first2 || (a.end ?? r.frames) <= last || Math.abs((a.speed ?? 1) - use2.play.speed) > 1e-6) return false;
28435
+ const audioTime = (a.from ? a.from.frame / a.from.fps : 0) + (first2 - a.start) / r.canvas.fps * (a.speed ?? 1);
28436
+ const videoTime = sourceFrame(use2.play, f, r.canvas.fps, first2) / f.fps;
28142
28437
  return Math.abs(audioTime - videoTime) <= 1 / f.fps;
28143
28438
  });
28144
- if (!matched) out2.push(error("materials." + id2, "Visible mouth motion has no matching locked audio at timeline frame " + first + ".", fix2));
28439
+ if (!matched) out2.push(error("materials." + id2, "Visible mouth motion has no matching locked audio at timeline frame " + first2 + ".", fix2));
28145
28440
  }
28146
28441
  }
28147
28442
  return out2;
@@ -29025,8 +29320,8 @@ var init_capacity = __esm({
29025
29320
  return Array.from(long).slice(0, n).join("").trimEnd();
29026
29321
  };
29027
29322
  linesOf = (b) => {
29028
- const size = b.style.size ?? 0.045;
29029
- return Math.max(0, Math.floor((b.box[3] + 1e-9) / (size * (b.style.lineHeight ?? DEFAULT_LINE_HEIGHT))));
29323
+ const size2 = b.style.size ?? 0.045;
29324
+ return Math.max(0, Math.floor((b.box[3] + 1e-9) / (size2 * (b.style.lineHeight ?? DEFAULT_LINE_HEIGHT))));
29030
29325
  };
29031
29326
  LATIN_ADVANCE = 0.55;
29032
29327
  WRAP_LOSS = 0.9;
@@ -29382,14 +29677,14 @@ var init_cues = __esm({
29382
29677
  return [...done2, ...open];
29383
29678
  };
29384
29679
  toCue = (run7, step2, total2) => {
29385
- const first = run7.frames[0] ?? 0, last = run7.frames[run7.frames.length - 1] ?? 0;
29680
+ const first2 = run7.frames[0] ?? 0, last = run7.frames[run7.frames.length - 1] ?? 0;
29386
29681
  const exact = run7.lines.filter((l) => !l.partial);
29387
29682
  const placed2 = exact.length ? exact : run7.lines;
29388
29683
  const box2 = union2(placed2.map((l) => l.box));
29389
29684
  const heights = placed2.map((l) => l.box[3]).sort((a, b) => a - b);
29390
29685
  return {
29391
29686
  text: bestText(run7.lines),
29392
- start: Math.max(0, first - Math.floor(step2 / 2)),
29687
+ start: Math.max(0, first2 - Math.floor(step2 / 2)),
29393
29688
  end: Math.min(total2, last + Math.ceil(step2 / 2)),
29394
29689
  box: box2,
29395
29690
  size: Math.round((heights[Math.floor(heights.length / 2)] ?? 0) * 1e4) / 1e4,
@@ -29626,8 +29921,8 @@ var init_speech3 = __esm({
29626
29921
  const around3 = (b) => [b - 1, b, b + 1].reduce((n, k) => n + (texts.get(k)?.size ?? 0), 0);
29627
29922
  const top2 = [...texts.keys()].sort((a, b) => around3(b) - around3(a) || a - b)[0];
29628
29923
  if (top2 === void 0) return () => false;
29629
- const size = median6(said.filter((c) => Math.abs(bandOf(c) - top2) <= 1).map((c) => c.size));
29630
- return (c) => Math.abs(bandOf(c) - top2) <= 1 && c.size <= SIZE_RATIO * size && c.size * SIZE_RATIO >= size;
29924
+ const size2 = median6(said.filter((c) => Math.abs(bandOf(c) - top2) <= 1).map((c) => c.size));
29925
+ return (c) => Math.abs(bandOf(c) - top2) <= 1 && c.size <= SIZE_RATIO * size2 && c.size * SIZE_RATIO >= size2;
29631
29926
  };
29632
29927
  notCaption = (s) => {
29633
29928
  if (s.said === void 0) return "shown while nothing is said, outside the band of the said captions";
@@ -29685,8 +29980,8 @@ var init_beats = __esm({
29685
29980
  const groups2 = [];
29686
29981
  for (const c of captions) {
29687
29982
  const g = groups2[groups2.length - 1];
29688
- const first = g?.[0];
29689
- if (g && first && c.start - first.start <= step2 && c.start < Math.max(...g.map((x2) => x2.end))) g.push(c);
29983
+ const first2 = g?.[0];
29984
+ if (g && first2 && c.start - first2.start <= step2 && c.start < Math.max(...g.map((x2) => x2.end))) g.push(c);
29690
29985
  else groups2.push([c]);
29691
29986
  }
29692
29987
  return groups2;
@@ -29726,10 +30021,10 @@ var init_beats = __esm({
29726
30021
  return runs4;
29727
30022
  };
29728
30023
  isStray = (run7, shown3, fps) => {
29729
- const first = run7[0], last = run7[run7.length - 1];
29730
- if (!first || !last || run7.reduce((n, w) => n + syllablesOf(w.text), 0) > STRAY_SYLLABLES) return false;
30024
+ const first2 = run7[0], last = run7[run7.length - 1];
30025
+ if (!first2 || !last || run7.reduce((n, w) => n + syllablesOf(w.text), 0) > STRAY_SYLLABLES) return false;
29731
30026
  const near3 = STRAY_SECONDS * fps;
29732
- return shown3.some((b) => Math.abs(first.start - b.end) <= near3 || Math.abs(b.start - last.end) <= near3);
30027
+ return shown3.some((b) => Math.abs(first2.start - b.end) <= near3 || Math.abs(b.start - last.end) <= near3);
29733
30028
  };
29734
30029
  ordered = (beats2) => {
29735
30030
  const sorted = [...beats2].sort((a, b) => a.start - b.start || Number(b.shown) - Number(a.shown)).map((b) => ({ ...b }));
@@ -29855,11 +30150,11 @@ var init_inset = __esm({
29855
30150
  return { width: d.width, height: d.height, frames: d.frames.map((rgb, i) => ({ frame: i * every, rgb })) };
29856
30151
  };
29857
30152
  medianOf = (pictures) => {
29858
- const first = pictures[0];
29859
- if (pictures.length === 1) return first;
29860
- const out2 = new Uint8Array(first.length);
30153
+ const first2 = pictures[0];
30154
+ if (pictures.length === 1) return first2;
30155
+ const out2 = new Uint8Array(first2.length);
29861
30156
  const values = new Array(pictures.length);
29862
- for (let i = 0; i < first.length; i++) {
30157
+ for (let i = 0; i < first2.length; i++) {
29863
30158
  for (let k = 0; k < pictures.length; k++) values[k] = pictures[k][i];
29864
30159
  values.sort((a, b) => a - b);
29865
30160
  out2[i] = values[pictures.length - 1 >> 1];
@@ -30196,11 +30491,11 @@ var init_move = __esm({
30196
30491
  round3 = (v, d = 3) => Math.round(v * 10 ** d) / 10 ** d;
30197
30492
  INK_THRESHOLD = 24;
30198
30493
  groundOf = (f, roi) => {
30199
- const first = f.frames[0];
30494
+ const first2 = f.frames[0];
30200
30495
  const border = [[], [], []];
30201
30496
  for (let y = roi.y; y < roi.y + roi.h; y++) for (let x2 = roi.x; x2 < roi.x + roi.w; x2++) {
30202
30497
  if (x2 - roi.x >= 2 && y - roi.y >= 2 && x2 < roi.x + roi.w - 2 && y < roi.y + roi.h - 2) continue;
30203
- for (let c = 0; c < 3; c++) border[c].push(first[(y * f.width + x2) * 3 + c] ?? 0);
30498
+ for (let c = 0; c < 3; c++) border[c].push(first2[(y * f.width + x2) * 3 + c] ?? 0);
30204
30499
  }
30205
30500
  const flat = border.map(median7);
30206
30501
  const off2 = border[0].filter((_v, i) => Math.max(...[0, 1, 2].map((c) => Math.abs((border[c][i] ?? 0) - flat[c]))) > INK_THRESHOLD / 2).length;
@@ -30320,19 +30615,19 @@ var init_move = __esm({
30320
30615
  const frac = (r) => [round3((r.x ?? 0) / f.width), round3((r.y ?? 0) / f.height)];
30321
30616
  const shift = { ...sc, startFrame: sc.startFrame + (seen[0] ?? 0) };
30322
30617
  if (seen.length >= 4) {
30323
- const first = at7(0), last = at7(seen.length - 1);
30324
- const dx = (last.x ?? 0) - (first.x ?? 0), dy = (last.y ?? 0) - (first.y ?? 0), len = Math.hypot(dx, dy);
30618
+ const first2 = at7(0), last = at7(seen.length - 1);
30619
+ const dx = (last.x ?? 0) - (first2.x ?? 0), dy = (last.y ?? 0) - (first2.y ?? 0), len = Math.hypot(dx, dy);
30325
30620
  const xs = seen.map((_s, i) => at7(i).x ?? 0), ys = seen.map((_s, i) => at7(i).y ?? 0);
30326
30621
  const rangeX = Math.max(...xs) - Math.min(...xs), rangeY = Math.max(...ys) - Math.min(...ys);
30327
- const along2 = len >= minPx ? seen.map((_s, i) => (((at7(i).x ?? 0) - (first.x ?? 0)) * dx + ((at7(i).y ?? 0) - (first.y ?? 0)) * dy) / len) : rangeY >= rangeX ? ys : xs;
30622
+ const along2 = len >= minPx ? seen.map((_s, i) => (((at7(i).x ?? 0) - (first2.x ?? 0)) * dx + ((at7(i).y ?? 0) - (first2.y ?? 0)) * dy) / len) : rangeY >= rangeX ? ys : xs;
30328
30623
  const prop = len >= minPx ? "path" : rangeY >= rangeX ? "y" : "x";
30329
30624
  for (const s of stretchesOf(along2, f.fps, minPx, 0.5)) {
30330
30625
  if (s.pulse) pulses.push({ prop, pulse: true, start: round3((shift.startFrame + s.a) / f.fps), duration: round3((s.b - s.a) / f.fps), frames: s.b - s.a, peak: round3(Math.abs(s.peak - along2[s.a]) / f.width) });
30331
30626
  else moves.push(describeMove(prop, along2, s, seen.map((i) => rows3[i]), shift, (i) => frac(at7(i)), Math.abs(along2[s.b] - along2[s.a])));
30332
30627
  }
30333
- for (const size of ["w", "h"]) {
30334
- const v = seen.map((_s, i) => at7(i)[size]);
30335
- for (const s of stretchesOf(v, f.fps, minPx, 1)) if (!s.pulse) moves.push(describeMove(size, v, s, [], shift, (i) => [round3(v[i] / (size === "w" ? f.width : f.height))]));
30628
+ for (const size2 of ["w", "h"]) {
30629
+ const v = seen.map((_s, i) => at7(i)[size2]);
30630
+ for (const s of stretchesOf(v, f.fps, minPx, 1)) if (!s.pulse) moves.push(describeMove(size2, v, s, [], shift, (i) => [round3(v[i] / (size2 === "w" ? f.width : f.height))]));
30336
30631
  }
30337
30632
  }
30338
30633
  if (!moves.length) {
@@ -30703,8 +30998,8 @@ var init_describe = __esm({
30703
30998
  const captions = text13.cues.filter((c) => c.role === "caption");
30704
30999
  if (captions.length) {
30705
31000
  const y = captions.map((c) => c.box[1] + c.box[3] / 2).sort((a, b) => a - b)[Math.floor(captions.length / 2)] ?? 0;
30706
- const size = captions.map((c) => c.size).sort((a, b) => a - b)[Math.floor(captions.length / 2)] ?? 0;
30707
- L.push("- Captions: " + captions.length + " lines in a band at " + pct6(y) + " of the height, line height " + pct6(size) + ", " + (captions.reduce((n, c) => n + c.end - c.start, 0) / captions.length / fps).toFixed(1) + " s each on average" + (text13.captionLook ? "; " + lookText(text13.captionLook) : ""));
31001
+ const size2 = captions.map((c) => c.size).sort((a, b) => a - b)[Math.floor(captions.length / 2)] ?? 0;
31002
+ L.push("- Captions: " + captions.length + " lines in a band at " + pct6(y) + " of the height, line height " + pct6(size2) + ", " + (captions.reduce((n, c) => n + c.end - c.start, 0) / captions.length / fps).toFixed(1) + " s each on average" + (text13.captionLook ? "; " + lookText(text13.captionLook) : ""));
30708
31003
  } else L.push("- Captions: none found");
30709
31004
  const marks = [...new Set(text13.cues.filter((c) => c.role === "watermark").map((c) => c.text))];
30710
31005
  if (marks.length) L.push("- Watermark text (not to be re-created): " + marks.slice(0, 4).map(quote6).join(", "));
@@ -30872,8 +31167,8 @@ var init_caption_look = __esm({
30872
31167
  stroke: { color: color2, width: 0.16 },
30873
31168
  shadow: cast?.blur !== void 0 ? { color: cast.color ?? color2, blur: cast.blur, x: cast.x ?? 0, y: cast.y ?? 0 } : { color: color2, blur: 0.3, x: 0, y: 0.05 }
30874
31169
  });
30875
- captionStyle = (look2, plan4, size) => {
30876
- const base = { size, weight: look2?.weight === "regular" ? 500 : 800, color: plan4.captionColor ?? look2?.color ?? "#ffffff", align: "center" };
31170
+ captionStyle = (look2, plan4, size2) => {
31171
+ const base = { size: size2, weight: look2?.weight === "regular" ? 500 : 800, color: plan4.captionColor ?? look2?.color ?? "#ffffff", align: "center" };
30877
31172
  const plate = look2?.kind === "plate" && look2.plate ? { background: plateStyle(look2.plate) } : {};
30878
31173
  if (plan4.captionOutline) return { ...base, ...outlined(plan4.captionOutline, look2?.shadow), ...plate };
30879
31174
  if (!look2 || look2.kind === "plain" && !look2.color) return { ...base, ...outlined("#111111") };
@@ -31021,20 +31316,20 @@ var init_titles = __esm({
31021
31316
  };
31022
31317
  wordBox = (p) => {
31023
31318
  const [x2, y, w, h] = p.box;
31024
- const size = r4(p.size * FONT_OF_BOX), cx = x2 + w / 2;
31025
- const height = Math.min(1, up4(Math.max(h, size * DEFAULT_LINE_HEIGHT)));
31319
+ const size2 = r4(p.size * FONT_OF_BOX), cx = x2 + w / 2;
31320
+ const height = Math.min(1, up4(Math.max(h, size2 * DEFAULT_LINE_HEIGHT)));
31026
31321
  const top2 = r4(Math.min(1 - height, Math.max(0, y + h / 2 - height / 2)));
31027
31322
  const align2 = Math.abs(cx - 0.5) <= 0.1 ? "center" : cx < 0.5 ? "left" : "right";
31028
31323
  if (align2 === "center") {
31029
31324
  const half2 = Math.max(w / 2, Math.min(cx - MARGIN, 1 - MARGIN - cx));
31030
- return { box: [r4(cx - half2), top2, r4(2 * half2), height], align: align2, size };
31325
+ return { box: [r4(cx - half2), top2, r4(2 * half2), height], align: align2, size: size2 };
31031
31326
  }
31032
- if (align2 === "left") return { box: [r4(x2), top2, r4(Math.max(w, 1 - MARGIN - x2)), height], align: align2, size };
31033
- return { box: [MARGIN, top2, r4(Math.max(w, x2 + w - MARGIN)), height], align: align2, size };
31327
+ if (align2 === "left") return { box: [r4(x2), top2, r4(Math.max(w, 1 - MARGIN - x2)), height], align: align2, size: size2 };
31328
+ return { box: [MARGIN, top2, r4(Math.max(w, x2 + w - MARGIN)), height], align: align2, size: size2 };
31034
31329
  };
31035
31330
  wordStyle = (p) => {
31036
- const { align: align2, size } = wordBox(p);
31037
- return { ...captionStyle(void 0, {}, size), align: align2 };
31331
+ const { align: align2, size: size2 } = wordBox(p);
31332
+ return { ...captionStyle(void 0, {}, size2), align: align2 };
31038
31333
  };
31039
31334
  wordTracks = (segment2, words, places, time, length2) => words.flatMap((raw, j) => {
31040
31335
  const p = places[j], line = unmark(raw);
@@ -31076,18 +31371,18 @@ var init_titles = __esm({
31076
31371
  const prev = places[j - 1]?.box, next = places[j + 1]?.box;
31077
31372
  const right = next ? (x2 + w + next[0]) / 2 : void 0, left = prev ? (prev[0] + prev[2] + x2) / 2 : void 0;
31078
31373
  const lo = Math.max(MARGIN, left ?? x2 - ((right ?? x2 + w) - (x2 + w))), hi = Math.min(1 - MARGIN, right ?? x2 + w + (x2 - (left ?? x2)));
31079
- const size = r4(p.size * FONT_OF_BOX);
31080
- const height = Math.min(1, up4(Math.max(h, size * DEFAULT_LINE_HEIGHT)));
31081
- return { box: [r4(Math.min(lo, x2)), r4(Math.min(1 - height, Math.max(0, y + h / 2 - height / 2))), r4(Math.max(w, hi - Math.min(lo, x2))), height], size };
31374
+ const size2 = r4(p.size * FONT_OF_BOX);
31375
+ const height = Math.min(1, up4(Math.max(h, size2 * DEFAULT_LINE_HEIGHT)));
31376
+ return { box: [r4(Math.min(lo, x2)), r4(Math.min(1 - height, Math.max(0, y + h / 2 - height / 2))), r4(Math.max(w, hi - Math.min(lo, x2))), height], size: size2 };
31082
31377
  };
31083
31378
  MARKED_STYLE = { weight: 800, color: "#111111", align: "center", background: { color: "#ffd84a", padding: 0.25, radius: 0.3 } };
31084
31379
  barTracks = (bar, words, segments2, total2) => words.flatMap((raw, j) => {
31085
31380
  const text13 = raw.trim();
31086
31381
  if (!text13 || !bar.places[j]) return [];
31087
- const { box: box2, size } = barBox(bar.places, j);
31088
- const first = segments2[0]?.id ?? "shot-01";
31089
- const plain2 = { id: "bar-" + (j + 1), type: "text", text: text13, box: box2, style: { ...captionStyle(void 0, {}, size), align: "center" }, during: { segment: first, from: 0, to: total2 } };
31090
- const lit = segments2.flatMap((s, k) => bar.marked[k] === j ? [{ id: "bar-" + (j + 1) + "-" + s.id, type: "text", text: text13, box: box2, style: { size, ...MARKED_STYLE }, during: { segment: s.id } }] : []);
31382
+ const { box: box2, size: size2 } = barBox(bar.places, j);
31383
+ const first2 = segments2[0]?.id ?? "shot-01";
31384
+ const plain2 = { id: "bar-" + (j + 1), type: "text", text: text13, box: box2, style: { ...captionStyle(void 0, {}, size2), align: "center" }, during: { segment: first2, from: 0, to: total2 } };
31385
+ const lit = segments2.flatMap((s, k) => bar.marked[k] === j ? [{ id: "bar-" + (j + 1) + "-" + s.id, type: "text", text: text13, box: box2, style: { size: size2, ...MARKED_STYLE }, during: { segment: s.id } }] : []);
31091
31386
  return [plain2, ...lit];
31092
31387
  });
31093
31388
  barProblems = (bar, places) => {
@@ -31212,10 +31507,10 @@ var init_retarget = __esm({
31212
31507
  return [{ level: "warning", at: "captions", message: has2 + " The last " + (n - lines2) + " beats stay without a caption.", fix: "Add lines, or leave it if the ending should be silent." }];
31213
31508
  };
31214
31509
  captionLayout = (cues) => {
31215
- const size = median8(cues.map((c) => c.size));
31510
+ const size2 = median8(cues.map((c) => c.size));
31216
31511
  const centre2 = median8(cues.map((c) => c.box[1] + c.box[3] / 2));
31217
- const half2 = Math.max(size * 0.6, Math.min(size * 1.4, centre2 - 0.01, 0.99 - centre2));
31218
- return { box: [0.08, r42(centre2 - half2), 0.84, r42(2 * half2)], size: r42(size * 0.92) };
31512
+ const half2 = Math.max(size2 * 0.6, Math.min(size2 * 1.4, centre2 - 0.01, 0.99 - centre2));
31513
+ return { box: [0.08, r42(centre2 - half2), 0.84, r42(2 * half2)], size: r42(size2 * 0.92) };
31219
31514
  };
31220
31515
  spokenForm = (line, say) => (say ?? []).reduce((s, x2) => s.split(x2.text).join(x2.as), line);
31221
31516
  LINE_TAIL = 4;
@@ -31343,7 +31638,7 @@ var init_retarget = __esm({
31343
31638
  const lines2 = plan4.captions ?? [];
31344
31639
  if (captionCues.length && lines2.some((l, i) => l.trim() && beats2[i]?.shown)) {
31345
31640
  const layout = captionLayout(captionCues);
31346
- const first = segments2[0]?.id ?? "shot-01";
31641
+ const first2 = segments2[0]?.id ?? "shot-01";
31347
31642
  const look2 = captionStyle(read2.text?.captionLook, plan4, layout.size);
31348
31643
  const lit = highlightColour(read2.text?.captionLook, look2.color);
31349
31644
  const cues = beats2.flatMap((b, i) => {
@@ -31356,7 +31651,7 @@ var init_retarget = __esm({
31356
31651
  const next = flow ? flow.starts[i + 1] ?? total2 : shift ? beats2[i + 1]?.start ?? total2 : total2;
31357
31652
  const to = Math.min(end, next, total2);
31358
31653
  const marks2 = marked2[i]?.marks ?? [];
31359
- return to > from ? [{ text: text13, during: { segment: first, from, to }, ...marks2.length ? { spans: markSpans(marks2, lit) } : {} }] : [];
31654
+ return to > from ? [{ text: text13, during: { segment: first2, from, to }, ...marks2.length ? { spans: markSpans(marks2, lit) } : {} }] : [];
31360
31655
  });
31361
31656
  const follows = Boolean(input.wordsFile && plan4.sound);
31362
31657
  const measured2 = read2.text?.captionLook?.reveal;
@@ -31377,8 +31672,8 @@ var init_retarget = __esm({
31377
31672
  }
31378
31673
  (plan4.beds ?? []).forEach((bed, i) => {
31379
31674
  const [a, b] = bed.shots;
31380
- const first = plan4.shots[a - 1];
31381
- const from = bed.in ?? (first && "footage" in first && first.footage === bed.footage ? first.in ?? 0 : 0);
31675
+ const first2 = plan4.shots[a - 1];
31676
+ const from = bed.in ?? (first2 && "footage" in first2 && first2.footage === bed.footage ? first2.in ?? 0 : 0);
31382
31677
  const frames = lengths.slice(a - 1, b).reduce((n, x2) => n + x2, 0);
31383
31678
  tracks.push({ id: "bed-" + (i + 1), type: "audio", material: use2(bed.footage, "video"), bed: true, ...from ? { in: from } : {}, ...bed.audio !== void 0 ? { gain: bed.audio } : {}, during: { segment: "shot-" + two8(a), from: 0, to: frames } });
31384
31679
  });
@@ -31812,7 +32107,7 @@ var init_card = __esm({
31812
32107
  const s = tpl.speech;
31813
32108
  if (!s) return [];
31814
32109
  const dialogue = (tpl.captions?.beats ?? []).flatMap((b, i) => b.speech === "on-camera" ? [i] : []);
31815
- const voice2 = s.kinds.includes("narration") ? 'the narration is re-made as a voice-over ("voice")' : 'no narration, so no "voice" and no --speak unless the user asks for one (--voice-asked "<their words>")';
32110
+ const voice2 = s.kinds.includes("narration") ? 'the narration is re-made as a voice-over ("voice"); in a video whose clips are generated and speak, those clips say it instead, as offscreen lines on its beats in the voice of the host (no "voice", no --speak: video-performers.md)' : 'no narration, so no "voice" and no --speak unless the user asks for one (--voice-asked "<their words>")';
31816
32111
  return [
31817
32112
  "- Speech of the source: " + s.kinds.join(", ") + ": " + voice2 + "." + (dialogue.length ? " Beats " + runsText(dialogue) + " are said on camera: the person of a generated clip says each line (its request's speech.lines names the beat); the voice-over never reads them." : "")
31818
32113
  ];
@@ -32002,8 +32297,8 @@ var init_slots = __esm({
32002
32297
  };
32003
32298
  });
32004
32299
  wordSlots = (tpl, s, k, texts = []) => (s.words ?? []).map((p, j) => {
32005
- const { box: box2, size } = wordBox(p);
32006
- const cap2 = estimateCapacity({ canvas: tpl.canvas, box: box2, style: { size } });
32300
+ const { box: box2, size: size2 } = wordBox(p);
32301
+ const cap2 = estimateCapacity({ canvas: tpl.canvas, box: box2, style: { size: size2 } });
32007
32302
  const was = texts[j]?.trim();
32008
32303
  return { at: "shots[" + k + "].words[" + j + "]", seconds: r28((p.to - p.from) / tpl.canvas.fps), max: { cjk: cap2.cjk, latin: cap2.latin }, ...was ? { example: { text: was, chars: charsOf(was).length } } : {} };
32009
32304
  });
@@ -32011,8 +32306,8 @@ var init_slots = __esm({
32011
32306
  const bar = tpl.bar;
32012
32307
  if (!bar) return void 0;
32013
32308
  const words = bar.places.map((_p, j) => {
32014
- const { box: box2, size } = barBox(bar.places, j);
32015
- const cap2 = estimateCapacity({ canvas: tpl.canvas, box: box2, style: { size } });
32309
+ const { box: box2, size: size2 } = barBox(bar.places, j);
32310
+ const cap2 = estimateCapacity({ canvas: tpl.canvas, box: box2, style: { size: size2 } });
32016
32311
  const was = texts[j]?.trim();
32017
32312
  return { max: { cjk: cap2.cjk, latin: cap2.latin }, ...was ? { example: { text: was, chars: charsOf(was).length } } : {} };
32018
32313
  });
@@ -32219,21 +32514,21 @@ var init_clips = __esm({
32219
32514
  let fill4;
32220
32515
  if (onto !== void 0) {
32221
32516
  const pkg = await loadTemplate(rt, userPath(rt, onto));
32222
- const first = (args.number("first") ?? 1) - 1;
32517
+ const first2 = (args.number("first") ?? 1) - 1;
32223
32518
  const lengths = fillLengths(pkg.template);
32224
- if (first < 0 || first + m.shots.length > pkg.template.shots.length)
32225
- throw new VideoCommandError("The clip has " + m.shots.length + " shots and the template " + pkg.template.shots.length + ": from shot " + (first + 1) + " they do not fit. Open the pictures (--out): a cut the clip does not have, or one too many, changes which shot goes where; give --first, or fill those shots by hand.");
32519
+ if (first2 < 0 || first2 + m.shots.length > pkg.template.shots.length)
32520
+ throw new VideoCommandError("The clip has " + m.shots.length + " shots and the template " + pkg.template.shots.length + ": from shot " + (first2 + 1) + " they do not fit. Open the pictures (--out): a cut the clip does not have, or one too many, changes which shot goes where; give --first, or fill those shots by hand.");
32226
32521
  const footage2 = fillPath(typed);
32227
32522
  const notes2 = [];
32228
32523
  const entries3 = m.shots.map((s, i) => {
32229
- const k = first + i;
32524
+ const k = first2 + i;
32230
32525
  const need2 = footageNeed(pkg.template, k, lengths) / pkg.template.canvas.fps;
32231
32526
  const have = Math.max(1, s.end - s.start - 2 * GUARD) / fps;
32232
32527
  const speed = Math.min(4, Math.max(0.25, r29(have / need2)));
32233
32528
  if (speed < SLOWED) notes2.push("shots[" + k + "]: the clip's shot " + (i + 1) + " is " + r29(have) + " s and the template's shot needs " + r29(need2) + " s, so it would play at " + speed + " of its speed. Ask for that shot longer when the group is made again, or fill it otherwise; do not slow it down.");
32234
32529
  return { shot: k + 1, fill: { footage: footage2, in: s.start + GUARD, ...speed !== 1 ? { speed } : {} } };
32235
32530
  });
32236
- fill4 = { shots: entries3, bed: { footage: footage2, shots: [first + 1, first + m.shots.length], in: (m.shots[0]?.start ?? 0) + GUARD }, ...notes2.length ? { notes: notes2 } : {} };
32531
+ fill4 = { shots: entries3, bed: { footage: footage2, shots: [first2 + 1, first2 + m.shots.length], in: (m.shots[0]?.start ?? 0) + GUARD }, ...notes2.length ? { notes: notes2 } : {} };
32237
32532
  }
32238
32533
  printJson(rt, {
32239
32534
  ok: true,
@@ -32318,7 +32613,7 @@ var init_cast2 = __esm({
32318
32613
  });
32319
32614
 
32320
32615
  // src/video/generate/cloud.ts
32321
- var GenerateError, MINUTE_MS, POLL_MS2, DEFAULT_WAIT_MIN, DEFAULT_SECONDS, CREATE_TRIES, CREATE_TIMEOUT_SEC, UPLOAD_TIMEOUT_MS, DOWNLOAD_TIMEOUT_SEC2, MAX_CLIP_BYTES, RETRY_HINT, setting, numberSetting, keysOf, cloudSettings, agreeToPrice, requestKey, LISTS2, has, mediaType, readReference3, readReferences, recordFile2, readRecord2, save2, keyOf4, stillValid, text6, putBytes, upload2, ensureUploads2, specOf, ensureQuote, taskOf3, createTask2, submit, getTask, findTask, ENDED, PASSING2, waitFor, NEXT_AFTER, ended, fetchClip, gateOf, modelFacts, wavSeconds, checkReferenceSounds, makeClip, priceClip, listModels;
32616
+ var GenerateError, MINUTE_MS, POLL_MS2, DEFAULT_WAIT_MIN, DEFAULT_SECONDS, CREATE_TRIES, CREATE_TIMEOUT_SEC, UPLOAD_TIMEOUT_MS, DOWNLOAD_TIMEOUT_SEC2, MAX_CLIP_BYTES, RETRY_HINT, setting, numberSetting, keysOf, cloudSettings, agreeToPrice, requestKey, LISTS2, has, mediaType, readReference3, identity, planFits, fittedOf, fitReferences, readReferences, recordFile2, readRecord2, save2, keyOf4, stillValid, text6, putBytes, upload2, ensureUploads2, specOf, ensureQuote, taskOf3, createTask2, submit, getTask, findTask, ENDED, PASSING2, waitFor, ended, unsupported2, fetchClip, gateOf, ASK_MODEL2, modelFacts, wavSeconds, checkReferenceSounds, prepare4, makeClip, priceClip, listModels;
32322
32617
  var init_cloud2 = __esm({
32323
32618
  "src/video/generate/cloud.ts"() {
32324
32619
  "use strict";
@@ -32334,12 +32629,16 @@ var init_cloud2 = __esm({
32334
32629
  init_submit_retry();
32335
32630
  init_approved();
32336
32631
  init_generate();
32632
+ init_failure();
32633
+ init_picture_fit();
32337
32634
  GenerateError = class extends Error {
32338
- constructor(message2, exitCode = 1) {
32635
+ constructor(message2, exitCode = 1, failure4) {
32339
32636
  super(message2);
32340
32637
  this.exitCode = exitCode;
32638
+ this.failure = failure4;
32341
32639
  }
32342
32640
  exitCode;
32641
+ failure;
32343
32642
  name = "GenerateError";
32344
32643
  };
32345
32644
  MINUTE_MS = 6e4;
@@ -32412,7 +32711,30 @@ var init_cloud2 = __esm({
32412
32711
  });
32413
32712
  const mimeType2 = mediaType(kind, bytes.subarray(0, 16));
32414
32713
  if (!mimeType2) throw new GenerateError(name + ' in "' + where3 + '" is not ' + what + "; nothing was sent.", 2);
32415
- return { kind, name, bytes, sha256: sha256(bytes), mimeType: mimeType2 };
32714
+ const hash5 = sha256(bytes);
32715
+ return { kind, path: path2, name, bytes, sha256: hash5, mimeType: mimeType2, source: hash5 };
32716
+ };
32717
+ identity = (r) => r.fit ? r.source + ":" + fitKey(r.fit) : r.source;
32718
+ planFits = (refs, limits) => refs.map((r) => {
32719
+ const shown3 = r.kind === "image" ? shownSize(r.bytes) : void 0;
32720
+ const fit = shown3 ? fitPlan(shown3[0], shown3[1], limits) : void 0;
32721
+ return fit ? { ...r, fit } : r;
32722
+ });
32723
+ fittedOf = (refs, limits) => refs.flatMap((r) => r.fit ? [{ file: r.path, was: r.fit.from.join("x"), now: r.fit.canvas.join("x"), how: fitText(r.fit, limits) }] : []);
32724
+ fitReferences = async (rt, refs, limits) => {
32725
+ const out2 = [];
32726
+ for (const r of refs) {
32727
+ if (!r.fit) {
32728
+ out2.push(r);
32729
+ continue;
32730
+ }
32731
+ const fitted = await fitPicture(rt, r.path, r.mimeType, r.fit, limits).catch((e) => {
32732
+ const why = e instanceof Error ? e.message : String(e);
32733
+ throw new GenerateError(r.name + " is " + r.fit?.from.join("x") + " and " + rangeText(limits) + ": it is fitted before it is sent (padded, never cut), which needs ffmpeg. " + why + " Nothing was sent.", 2);
32734
+ });
32735
+ out2.push({ ...r, ...fitted });
32736
+ }
32737
+ return out2;
32416
32738
  };
32417
32739
  readReferences = async (rt, request) => {
32418
32740
  const out2 = [];
@@ -32478,13 +32800,13 @@ var init_cloud2 = __esm({
32478
32800
  const idOf = (r) => sent.uploads[r?.sha256 ?? ""]?.uploadId ?? "";
32479
32801
  const ids3 = (kind) => refs.filter((r) => r.kind === kind && !r.frame).map(idOf);
32480
32802
  const references = Object.fromEntries(LISTS2.map(([kind, list7]) => [list7, ids3(kind)]).filter(([, list7]) => list7.length));
32481
- const [first, last] = [refs.find((r) => r.frame === "first"), refs.find((r) => r.frame === "last")];
32803
+ const [first2, last] = [refs.find((r) => r.frame === "first"), refs.find((r) => r.frame === "last")];
32482
32804
  return {
32483
32805
  ...s.videoModel ? { model: s.videoModel } : {},
32484
32806
  ...s.resolution ? { resolution: s.resolution } : {},
32485
32807
  seconds: seconds8,
32486
32808
  ...request.aspect ? { aspectRatio: request.aspect } : {},
32487
- ...first ? { frames: { first: idOf(first), ...last ? { last: idOf(last) } : {} } } : {},
32809
+ ...first2 ? { frames: { first: idOf(first2), ...last ? { last: idOf(last) } : {} } } : {},
32488
32810
  ...Object.keys(references).length ? { references } : {},
32489
32811
  // Only for a model that can make a clip without a sound track; the quote and the generation say the same.
32490
32812
  ...silent ? { generateAudio: false } : {}
@@ -32494,9 +32816,10 @@ var init_cloud2 = __esm({
32494
32816
  const json4 = JSON.stringify(body);
32495
32817
  if (sent.quote?.body === json4 && stillValid(rt, sent.quote.expiresAt, MINUTE_MS)) return sent;
32496
32818
  const data = await client2.request("POST", "/videos/quote", { body }).catch((error2) => {
32497
- if (body.frames && error2 instanceof PopostApiError && error2.code === "VIDEO_OPTION_UNSUPPORTED" && error2.details.field === "frames")
32498
- throw new GenerateError('This video model does not take a first or last frame (popost video generate --models lists "frames" for each model): choose another with POPOST_VIDEO_MODEL, or give the picture as a reference in "images" instead. Nothing was charged.');
32499
- throw error2;
32819
+ if (!(error2 instanceof PopostApiError) || error2.code !== "VIDEO_OPTION_UNSUPPORTED") throw error2;
32820
+ if (body.frames && error2.details.field === "frames")
32821
+ throw new GenerateError('This video model does not take a first or last frame (popost video generate --models lists "frames" for each model): give the picture as a reference in "images" instead, or ask the user whether to use a model that takes frames (' + ASK_MODEL2 + "). Nothing was charged.", 1, { code: "VIDEO_OPTION_UNSUPPORTED", retryable: false, reason: "frames" });
32822
+ throw unsupported2(error2);
32500
32823
  });
32501
32824
  if (!isRecord(data) || typeof data.quoteId !== "string" || typeof data.credits !== "number")
32502
32825
  throw new GenerateError("popost.ai answered the quote without a quote id or a price; nothing was charged. Try again later.");
@@ -32518,17 +32841,19 @@ var init_cloud2 = __esm({
32518
32841
  }, { tries: CREATE_TRIES, pauseMs: POLL_MS2 });
32519
32842
  submit = async (rt, client2, s, job, start) => {
32520
32843
  let sent = start;
32844
+ const refs = await fitReferences(rt, job.refs, job.limits);
32521
32845
  for (let round5 = 1; ; round5++) {
32522
- sent = await ensureUploads2(rt, client2, job.refs, sent, job.file);
32523
- const body = specOf(s, job.request, job.seconds, job.refs, sent, job.silent);
32846
+ sent = await ensureUploads2(rt, client2, refs, sent, job.file);
32847
+ const body = specOf(s, job.request, job.seconds, refs, sent, job.silent);
32524
32848
  sent = await ensureQuote(rt, client2, body, sent, job.file);
32525
32849
  const quote16 = sent.quote;
32526
32850
  if (job.request.priceOnly) throw new ConfirmNeeded(quote16.price, "This costs " + quote16.price.credits + " credits. Only its price was asked for: nothing was made or charged.");
32527
32851
  agreeToPrice(s, quote16.price, job.unplanned);
32528
32852
  try {
32529
32853
  const task = await createTask2(rt, client2, { ...body, prompt: job.request.prompt, quoteId: quote16.quoteId, idempotencyKey: keyOf4(sent) });
32530
- await save2(rt, job.file, { ...sent, taskId: task.id });
32531
- await job.onPaid(typeof task.credits === "number" ? task.credits : quote16.price.credits);
32854
+ const paid = typeof task.credits === "number" ? task.credits : quote16.price.credits;
32855
+ await save2(rt, job.file, { ...sent, taskId: task.id, paid });
32856
+ await job.onPaid(paid);
32532
32857
  return task;
32533
32858
  } catch (error2) {
32534
32859
  if (round5 > 1 || !(error2 instanceof PopostApiError) || error2.code !== "QUOTE_EXPIRED") throw error2;
@@ -32548,9 +32873,9 @@ var init_cloud2 = __esm({
32548
32873
  });
32549
32874
  ENDED = ["succeeded", "failed", "expired"];
32550
32875
  PASSING2 = /* @__PURE__ */ new Set(["NETWORK", "BAD_RESPONSE", "RATE_LIMITED", "SERVICE_UNAVAILABLE", "INTERNAL_ERROR", "TIMEOUT", "UPSTREAM_ERROR"]);
32551
- waitFor = async (rt, client2, first, minutes) => {
32876
+ waitFor = async (rt, client2, first2, minutes) => {
32552
32877
  const deadline2 = rt.now().getTime() + minutes * MINUTE_MS;
32553
- let task = first;
32878
+ let task = first2;
32554
32879
  while (!ENDED.includes(task.status)) {
32555
32880
  if (rt.now().getTime() >= deadline2)
32556
32881
  throw new GenerateError("The clip is still being made on popost.ai after " + minutes + " minutes (task " + task.id + ", " + task.status + "). Run the same command again later to pick it up: it is not paid twice. POPOST_GEN_WAIT_MIN waits longer.");
@@ -32563,15 +32888,23 @@ var init_cloud2 = __esm({
32563
32888
  }
32564
32889
  return task;
32565
32890
  };
32566
- NEXT_AFTER = {
32567
- CONTENT_REJECTED: "the same request would be refused again, so change its prompt or its reference pictures before asking for the clip again: for example, leave out the names of brands, characters and well-known works, and pictures of them."
32568
- };
32569
- ended = (task) => {
32891
+ ended = (task, sent, hadSound) => {
32570
32892
  if (task.status === "expired")
32571
32893
  return new GenerateError("The clip of task " + task.id + " was kept 7 days on popost.ai and has been deleted. Run the command again to make it again (it is priced again).");
32572
32894
  const code = text6(task.error?.code) ?? "GENERATION_FAILED";
32573
- const next = NEXT_AFTER[code] ?? "running the command again makes a new attempt, priced again.";
32574
- return new GenerateError("The clip could not be made: " + describeError(code, task.error?.message) + ". Its credits were refunded; " + next);
32895
+ const reason2 = text6(task.error?.reason)?.trim().slice(0, 400);
32896
+ const retryable = typeof task.error?.retryable === "boolean" ? task.error.retryable : void 0;
32897
+ const refunded = sent.taskId === task.id ? sent.paid ?? sent.quote?.price.credits : void 0;
32898
+ const failure4 = withSound({ code, ...retryable !== void 0 ? { retryable } : {}, ...reason2 ? { reason: reason2 } : {}, ...refunded !== void 0 && refunded > 0 ? { refundedCredits: refunded } : {} }, hadSound);
32899
+ const message2 = text6(task.error?.message);
32900
+ return new GenerateError(failureLine(failure4, { other: describeError(code, message2), ...message2 ? { message: message2 } : {}, charged: "refunded" }), 1, failure4);
32901
+ };
32902
+ unsupported2 = (error2) => {
32903
+ const field = text6(error2.details.field);
32904
+ const allowed = error2.details.allowed;
32905
+ const reason2 = [field, allowed === void 0 ? void 0 : "allowed: " + JSON.stringify(allowed).slice(0, 200)].filter(Boolean).join(", ");
32906
+ const failure4 = { code: "VIDEO_OPTION_UNSUPPORTED", retryable: false, ...reason2 ? { reason: reason2 } : {} };
32907
+ return new GenerateError(failureLine(failure4, { other: describeError(error2.code, error2.message), message: error2.message, charged: "nothing" }), 1, failure4);
32575
32908
  };
32576
32909
  fetchClip = async (rt, client2, done2, out2) => {
32577
32910
  const labels = { what: "the clip", retry: "run the same command again: it downloads the clip without paying again" };
@@ -32600,6 +32933,7 @@ var init_cloud2 = __esm({
32600
32933
  const file = s.gate.file ?? (inside6.startsWith("..") ? void 0 : inside6.split(rt.path.sep).join("/"));
32601
32934
  return { ...s.gate, project, ...file ? { file } : {} };
32602
32935
  };
32936
+ ASK_MODEL2 = "set POPOST_VIDEO_MODEL only to a model the user names";
32603
32937
  modelFacts = async (client2, id2) => {
32604
32938
  const data = await client2.request("GET", "/videos/models").catch(() => void 0);
32605
32939
  if (!isRecord(data) || !Array.isArray(data.models)) return void 0;
@@ -32608,7 +32942,7 @@ var init_cloud2 = __esm({
32608
32942
  if (!model) return void 0;
32609
32943
  const count5 = (v) => typeof v === "number" && v >= 0 ? v : void 0;
32610
32944
  const [sounds, seconds8] = [count5(model.maxReferenceAudios), count5(model.maxReferenceAudioSeconds)];
32611
- return { audioOptional: model.audioOptional === true, ...sounds !== void 0 ? { maxReferenceAudios: sounds } : {}, ...seconds8 !== void 0 ? { maxReferenceAudioSeconds: seconds8 } : {} };
32945
+ return { audioOptional: model.audioOptional === true, ...sounds !== void 0 ? { maxReferenceAudios: sounds } : {}, ...seconds8 !== void 0 ? { maxReferenceAudioSeconds: seconds8 } : {}, pictures: pictureLimitsOf(model) };
32612
32946
  };
32613
32947
  wavSeconds = (bytes) => {
32614
32948
  try {
@@ -32621,26 +32955,32 @@ var init_cloud2 = __esm({
32621
32955
  const sounds = refs.filter((r) => r.kind === "audio");
32622
32956
  if (!sounds.length || !facts) return;
32623
32957
  if (facts.maxReferenceAudios !== void 0 && sounds.length > facts.maxReferenceAudios)
32624
- throw new GenerateError(facts.maxReferenceAudios === 0 ? "This video model takes no reference sounds, and the request has " + sounds.length + ' in "audios" (a voice sample goes with every speaking clip of a registered voice). Choose a model that takes them with POPOST_VIDEO_MODEL (popost video generate --models lists "maxReferenceAudios"), or remove the sounds. Nothing was sent.' : "This video model takes at most " + facts.maxReferenceAudios + " reference sound" + (facts.maxReferenceAudios === 1 ? "" : "s") + ", and the request has " + sounds.length + ". Nothing was sent.", 2);
32958
+ throw new GenerateError(facts.maxReferenceAudios === 0 ? "This video model takes no reference sounds, and the request has " + sounds.length + ' in "audios" (a voice sample goes with every speaking clip of a registered voice, so that it speaks with the same voice in every clip). Ask the user whether to use a model that takes them (popost video generate --models lists "maxReferenceAudios"; ' + ASK_MODEL2 + ") or to go on without the voice sample; do not leave it out on your own. Nothing was sent." : "This video model takes at most " + facts.maxReferenceAudios + " reference sound" + (facts.maxReferenceAudios === 1 ? "" : "s") + ", and the request has " + sounds.length + ". Nothing was sent.", 2);
32625
32959
  const total2 = sounds.reduce((n, r) => n + (wavSeconds(r.bytes) ?? 0), 0);
32626
32960
  if (facts.maxReferenceAudioSeconds !== void 0 && facts.maxReferenceAudioSeconds > 0 && total2 > facts.maxReferenceAudioSeconds + 0.05)
32627
- throw new GenerateError("The reference sounds of this request are " + total2.toFixed(1) + " s together; this video model takes " + facts.maxReferenceAudioSeconds + " s in all. Cut each speaker's sample shorter (popost video voice sample <project> --speaker <id> --start S --end E), or choose a model that takes more (popost video generate --models). Nothing was sent.", 2);
32961
+ throw new GenerateError("The reference sounds of this request are " + total2.toFixed(1) + " s together; this video model takes " + facts.maxReferenceAudioSeconds + " s in all. Cut each speaker's sample shorter (popost video voice sample <project> --speaker <id> --start S --end E), or ask the user whether to use a model that takes more (popost video generate --models; " + ASK_MODEL2 + "). Nothing was sent.", 2);
32962
+ };
32963
+ prepare4 = async (rt, client2, s, request) => {
32964
+ const read2 = await readReferences(rt, request);
32965
+ const facts = request.audio === false || read2.some((r) => r.kind === "audio" || r.kind === "image") ? await modelFacts(client2, s.videoModel) : void 0;
32966
+ checkReferenceSounds(read2, facts);
32967
+ const limits = facts?.pictures ?? DEFAULT_PICTURE_LIMITS;
32968
+ const refs = planFits(read2, limits);
32969
+ const silent = request.audio === false && facts?.audioOptional === true;
32970
+ return { refs, limits, silent, seconds: request.seconds ?? DEFAULT_SECONDS, fitted: fittedOf(refs, limits) };
32628
32971
  };
32629
32972
  makeClip = async (rt, client2, s, request, out2) => {
32630
- const seconds8 = request.seconds ?? DEFAULT_SECONDS;
32631
- const refs = await readReferences(rt, request);
32632
- const facts = request.audio === false || refs.some((r) => r.kind === "audio") ? await modelFacts(client2, s.videoModel) : void 0;
32633
- checkReferenceSounds(refs, facts);
32634
- const silent = request.audio === false && facts?.audioOptional === true;
32635
- const byContent = Object.fromEntries(LISTS2.map(([kind, list7]) => [list7, refs.filter((r) => r.kind === kind && !r.frame).map((r) => r.sha256)]));
32636
- const frames = Object.fromEntries(refs.flatMap((r) => r.frame ? [[r.frame + "Frame", r.sha256]] : []));
32973
+ const { refs, limits, silent, seconds: seconds8, fitted } = await prepare4(rt, client2, s, request);
32974
+ const told = fitted.length ? { fitted } : {};
32975
+ const byContent = Object.fromEntries(LISTS2.map(([kind, list7]) => [list7, refs.filter((r) => r.kind === kind && !r.frame).map(identity)]));
32976
+ const frames = Object.fromEntries(refs.flatMap((r) => r.frame ? [[r.frame + "Frame", identity(r)]] : []));
32637
32977
  const key2 = requestKey("video", { model: s.videoModel ?? null, resolution: s.resolution ?? null, prompt: request.prompt, seconds: seconds8, aspect: request.aspect ?? null, ...byContent, ...frames, ...silent ? { generateAudio: false } : {} });
32638
32978
  const file = recordFile2(rt, key2);
32639
32979
  let sent = await readRecord2(rt, file, key2);
32640
32980
  let task = sent.taskId ? await findTask(client2, sent.taskId) : void 0;
32641
32981
  if (task && sent.taskId && sent.told !== sent.taskId && (task.status === "failed" || task.status === "expired")) {
32642
32982
  await save2(rt, file, { ...sent, told: sent.taskId });
32643
- throw ended(task);
32983
+ throw ended(task, sent, refs.some((r) => r.kind === "audio"));
32644
32984
  }
32645
32985
  if (sent.taskId && (!task || task.status === "failed" || task.status === "expired")) {
32646
32986
  sent = { key: key2, attempt: sent.attempt + 1, uploads: sent.uploads };
@@ -32656,26 +32996,24 @@ var init_cloud2 = __esm({
32656
32996
  charged = credits2;
32657
32997
  if (gate && (standing2 === "plan" || standing2 === "user")) await recordClip(rt, gate, { key: key2, ...gate.file ? { file: gate.file } : {}, what, seconds: seconds8, credits: credits2, by: standing2 });
32658
32998
  };
32659
- task = await submit(rt, client2, s, { request, seconds: seconds8, refs, file, silent, onPaid, ...unplanned ? { unplanned } : {} }, sent);
32999
+ task = await submit(rt, client2, s, { request, seconds: seconds8, refs, limits, file, silent, onPaid, ...unplanned ? { unplanned } : {} }, sent);
32660
33000
  }
32661
33001
  if (s.noWait && !ENDED.includes(task.status))
32662
- throw new StillMaking({ task: task.id, state: task.status, chargedCredits: charged }, "The clip is being made on popost.ai (task " + task.id + ", " + task.status + "); it takes a few minutes. Run the same command again later to pick it up: it is not paid twice.");
33002
+ throw new StillMaking({ task: task.id, state: task.status, chargedCredits: charged, ...told }, "The clip is being made on popost.ai (task " + task.id + ", " + task.status + "); it takes a few minutes. Run the same command again later to pick it up: it is not paid twice.");
32663
33003
  const done2 = await waitFor(rt, client2, task, s.waitMinutes);
32664
33004
  if (done2.status !== "succeeded") {
32665
- await save2(rt, file, { ...await readRecord2(rt, file, key2), told: done2.id });
32666
- throw ended(done2);
33005
+ const record2 = await readRecord2(rt, file, key2);
33006
+ await save2(rt, file, { ...record2, told: done2.id });
33007
+ throw ended(done2, record2, refs.some((r) => r.kind === "audio"));
32667
33008
  }
32668
33009
  await fetchClip(rt, client2, done2, out2);
32669
- return { ...typeof done2.credits === "number" ? { credits: done2.credits } : {}, chargedCredits: charged, key: key2, task: done2.id };
33010
+ return { ...typeof done2.credits === "number" ? { credits: done2.credits } : {}, chargedCredits: charged, key: key2, task: done2.id, ...told };
32670
33011
  };
32671
33012
  priceClip = async (rt, client2, s, request) => {
32672
- const seconds8 = request.seconds ?? DEFAULT_SECONDS;
32673
- const refs = await readReferences(rt, request);
32674
- const facts = request.audio === false || refs.some((r) => r.kind === "audio") ? await modelFacts(client2, s.videoModel) : void 0;
32675
- checkReferenceSounds(refs, facts);
32676
- const silent = request.audio === false && facts?.audioOptional === true;
32677
- const key2 = "price-" + sha256(JSON.stringify([s.videoModel ?? null, s.resolution ?? null, seconds8, request.aspect ?? null, silent, refs.map((r) => [r.kind, r.frame ?? "", r.sha256])]));
33013
+ const { refs: planned, limits, silent, seconds: seconds8 } = await prepare4(rt, client2, s, request);
33014
+ const key2 = "price-" + sha256(JSON.stringify([s.videoModel ?? null, s.resolution ?? null, seconds8, request.aspect ?? null, silent, planned.map((r) => [r.kind, r.frame ?? "", identity(r)])]));
32678
33015
  const file = recordFile2(rt, key2);
33016
+ const refs = await fitReferences(rt, planned, limits);
32679
33017
  const uploaded = await ensureUploads2(rt, client2, refs, await readRecord2(rt, file, key2), file);
32680
33018
  const sent = await ensureQuote(rt, client2, specOf(s, request, seconds8, refs, uploaded, silent), uploaded, file);
32681
33019
  return sent.quote.price;
@@ -32683,10 +33021,12 @@ var init_cloud2 = __esm({
32683
33021
  listModels = async (client2) => {
32684
33022
  const data = await client2.request("GET", "/videos/models");
32685
33023
  if (!isRecord(data) || !Array.isArray(data.models)) throw new GenerateError("popost.ai answered without a list of video models. Try again later.");
33024
+ const marked2 = data.models.find((m) => isRecord(m) && m.default === true && typeof m.id === "string");
33025
+ const byDefault = typeof data.default === "string" ? data.default : marked2 ? marked2.id : null;
32686
33026
  return {
32687
- models: data.models,
32688
- default: data.default ?? null,
32689
- note: `POPOST_VIDEO_MODEL takes an id, POPOST_VIDEO_RESOLUTION one of its resolutions. "frames": true is a model that takes "firstFrame" and "lastFrame". "audioOptional": true is a model that makes a clip without a sound track for a request whose "sound" is "silent" (any other model's track is taken out of the file). "maxReferenceAudios" and "maxReferenceAudioSeconds" are the reference sounds it takes (the voice sample of a speaking clip). Every clip costs credits, and popost.ai keeps it 7 days.`
33027
+ models: data.models.map((m) => isRecord(m) && byDefault !== null && m.id === byDefault ? { ...m, default: true } : m),
33028
+ default: byDefault,
33029
+ note: `The model marked "default": true is the platform's default: clips are made with it while POPOST_VIDEO_MODEL is unset, and it stays unset unless the user names another model (say in the plan which model is used). POPOST_VIDEO_MODEL takes an id, POPOST_VIDEO_RESOLUTION one of its resolutions. "frames": true is a model that takes "firstFrame" and "lastFrame". "audioOptional": true is a model that makes a clip without a sound track for a request whose "sound" is "silent" (any other model's track is taken out of the file). "maxReferenceAudios" and "maxReferenceAudioSeconds" are the reference sounds it takes (the voice sample of a speaking clip). A picture (a frame or a reference) outside what the model takes (its picture limits where it lists them, else width/height from ` + DEFAULT_PICTURE_LIMITS.minRatio + " to " + DEFAULT_PICTURE_LIMITS.maxRatio + " and sides of " + DEFAULT_PICTURE_LIMITS.minSide + " to " + DEFAULT_PICTURE_LIMITS.maxSide + ` px) is padded, never cut, before it is sent; the clip's result says so ("fitted"). Every clip costs credits, and popost.ai keeps it 7 days.`
32690
33030
  };
32691
33031
  };
32692
33032
  }
@@ -32829,14 +33169,14 @@ var init_cloud_image = __esm({
32829
33169
  place = async (rt, provider, taskId, out2, wanted) => {
32830
33170
  const dir = out2 + ".parts";
32831
33171
  try {
32832
- const [first] = await provider.materialize(taskId, dir);
32833
- const from = typeof first?.localPath === "string" ? first.localPath : void 0;
33172
+ const [first2] = await provider.materialize(taskId, dir);
33173
+ const from = typeof first2?.localPath === "string" ? first2.localPath : void 0;
32834
33174
  if (!from) throw new GenerateError("popost.ai made the picture (task " + taskId + ") but gave no file of it. Try again later.");
32835
- if (first?.mimeType === wanted) return await rt.fs.rename(from, out2);
33175
+ if (first2?.mimeType === wanted) return await rt.fs.rename(from, out2);
32836
33176
  const converted = rt.programs ? await runFfmpegOk(rt, ["-y", "-loglevel", "error", "-i", from, "-frames:v", "1", ...wanted === "image/jpeg" ? ["-q:v", "2"] : [], out2]).then(() => true, () => false) : false;
32837
33177
  if (converted) return;
32838
33178
  await rt.fs.rename(from, out2);
32839
- rt.stderr("note: popost.ai made a " + String(first?.mimeType) + " picture and it could not be converted here; " + rt.path.basename(out2) + " holds it as it was made.\n");
33179
+ rt.stderr("note: popost.ai made a " + String(first2?.mimeType) + " picture and it could not be converted here; " + rt.path.basename(out2) + " holds it as it was made.\n");
32840
33180
  } finally {
32841
33181
  await rt.fs.rm(dir);
32842
33182
  }
@@ -32930,7 +33270,7 @@ var init_cloud_image = __esm({
32930
33270
  });
32931
33271
 
32932
33272
  // src/video/commands/credits.ts
32933
- var CREDIT_OPTIONS, NEXT, OVER, ceilingOf, walletFor;
33273
+ var CREDIT_OPTIONS, NEXT2, OVER, ceilingOf, walletFor;
32934
33274
  var init_credits = __esm({
32935
33275
  "src/video/commands/credits.ts"() {
32936
33276
  "use strict";
@@ -32941,7 +33281,7 @@ var init_credits = __esm({
32941
33281
  { flag: "--confirm", kind: "flag", help: "the user agreed to the price this command printed without it (exit code 3), or it fits what is left of the budget they agreed to for this video: popost.ai may charge, within --max-credits" },
32942
33282
  { flag: "--max-credits", kind: "int", metavar: "N", help: "with --confirm: the most this whole command may spend, in credits (what is left of the budget of the video)" }
32943
33283
  ];
32944
- NEXT = "Nothing was charged. When these credits fit what is left of the budget the user agreed to for this video, run the same command again with --confirm --max-credits <what is left>; otherwise show the user the credits (and the balance) and run it so once they agree.";
33284
+ NEXT2 = "Nothing was charged. When these credits fit what is left of the budget the user agreed to for this video, run the same command again with --confirm --max-credits <what is left>; otherwise show the user the credits (and the balance) and run it so once they agree.";
32945
33285
  OVER = "This costs more than --max-credits, what is left of the agreed budget; nothing was charged. Show the user the credits (and the balance), and run the same command again with --confirm --max-credits N (N at least the credits) only once they agree to more.";
32946
33286
  ceilingOf = (args) => {
32947
33287
  const confirmed = args.flag("confirm");
@@ -32958,7 +33298,7 @@ var init_credits = __esm({
32958
33298
  if (balance !== void 0 && balance < credits2)
32959
33299
  throw new VideoCommandError("Not enough credits: this needs " + credits2 + " credits and the balance is " + balance + ". Nothing was charged; popost account shows the balance and where to buy more. [INSUFFICIENT_CREDITS]");
32960
33300
  const price = { credits: credits2, ...balance !== void 0 ? { balance } : {}, items: [...items] };
32961
- if (max === void 0) throw new PriceNotAgreed(price, NEXT);
33301
+ if (max === void 0) throw new PriceNotAgreed(price, NEXT2);
32962
33302
  if (credits2 > max) throw new PriceNotAgreed({ ...price, maxCredits: max }, OVER);
32963
33303
  return new Wallet(max);
32964
33304
  };
@@ -33062,6 +33402,8 @@ var init_generate2 = __esm({
33062
33402
  rt.stderr(oneLine(error2.message) + "\n");
33063
33403
  return PENDING_EXIT2;
33064
33404
  }
33405
+ const failure4 = error2 instanceof GenerateError ? error2.failure : void 0;
33406
+ if (failure4) printJson(rt, { error: { ...failure4, ...failure4.reason ? { reason: scrub(failure4.reason, secrets) } : {} } });
33065
33407
  rt.stderr(oneLine(scrub(errorText(error2), secrets)) + "\n");
33066
33408
  return exitOf(error2);
33067
33409
  }
@@ -33075,7 +33417,7 @@ var init_generate2 = __esm({
33075
33417
  { name: "out", required: false, help: "the file to write: .mp4 for a clip, .png, .jpg or .webp for a picture" }
33076
33418
  ],
33077
33419
  options: [
33078
- { flag: "--models", kind: "flag", help: "list the video models (id, resolutions, seconds, aspect ratios, reference limits, credits) and make nothing" },
33420
+ { flag: "--models", kind: "flag", help: `list the video models (id, resolutions, seconds, aspect ratios, reference limits, credits; the platform's default marked "default": true) and make nothing` },
33079
33421
  { flag: "--yes", kind: "flag", help: "the user agreed to the price this call was shown; a budget set in POPOST_GEN_MAX_CREDITS still holds" },
33080
33422
  { flag: "--no-wait", kind: "flag", help: 'send the clip or picture and return; while it is being made, prints {"pending": {...}} with exit code 4, and the same command later downloads it without paying again (POPOST_GEN_NO_WAIT=1 does the same). Without it the command waits for the file' },
33081
33423
  ...CREDIT_OPTIONS,
@@ -33231,9 +33573,9 @@ var init_product = __esm({
33231
33573
  const [bx, by2, width, height] = m.slice(1).map(Number);
33232
33574
  const original = x2.original ?? { file: x2.file, sha256: x2.sha256 };
33233
33575
  const from = rt.path.resolve(dir, original.file);
33234
- const size = await sizeOf2(rt, from);
33235
- if (width < MIN_CROP || height < MIN_CROP || bx + width > size.width || by2 + height > size.height)
33236
- throw new VideoCommandError("The box " + box2 + " does not fit: the picture is " + size.width + "x" + size.height + ", and a crop is at least " + MIN_CROP + " pixels on each side and lies inside it. Choose a box that holds the whole product.");
33576
+ const size2 = await sizeOf2(rt, from);
33577
+ if (width < MIN_CROP || height < MIN_CROP || bx + width > size2.width || by2 + height > size2.height)
33578
+ throw new VideoCommandError("The box " + box2 + " does not fit: the picture is " + size2.width + "x" + size2.height + ", and a crop is at least " + MIN_CROP + " pixels on each side and lies inside it. Choose a box that holds the whole product.");
33237
33579
  const file = PRODUCT_DIR + "/" + p.id + "-" + String(i + 1).padStart(2, "0") + ".crop.png";
33238
33580
  await rt.fs.mkdir(rt.path.join(dir, PRODUCT_DIR));
33239
33581
  await runFfmpegOk(rt, ["-y", "-loglevel", "error", "-i", from, "-vf", "crop=" + width + ":" + height + ":" + bx + ":" + by2 + ":exact=1", "-frames:v", "1", rt.path.join(dir, file)]);
@@ -34105,8 +34447,8 @@ var init_collect = __esm({
34105
34447
  const problems2 = (report4?.problems ?? []).filter((p) => !(p.level === "error" && /^It was not made: it costs/.test(p.message)));
34106
34448
  const sheet4 = (await readProductSheet(rt, dir)).sheet;
34107
34449
  const cast = await readCast(rt, dir).catch(() => void 0);
34108
- const productPictures = new Map((sheet4?.products ?? []).flatMap((p) => p.pictures.map((x2) => [x2.file, p.id])));
34109
- const castPictures = new Map((cast?.roles ?? []).flatMap((r) => r.image ? [[r.image, r.id]] : []));
34450
+ const productPictures2 = new Map((sheet4?.products ?? []).flatMap((p) => p.pictures.map((x2) => [x2.file, p.id])));
34451
+ const castPictures2 = new Map((cast?.roles ?? []).flatMap((r) => r.image ? [[r.image, r.id]] : []));
34110
34452
  const clips = [];
34111
34453
  const kept3 = [];
34112
34454
  for (const r of o.requests) {
@@ -34120,8 +34462,8 @@ var init_collect = __esm({
34120
34462
  const anchor = o.picture?.file;
34121
34463
  const pictures = (q.images ?? []).map((f, i) => {
34122
34464
  const file = rel(rt, dir, f);
34123
- const role = productPictures.has(file) ? "product" : castPictures.has(file) ? "cast" : file === anchor ? "anchor" : "reference";
34124
- return { file, role, name: "@image" + (i + 1) + (role === "product" ? " " + productPictures.get(file) : role === "cast" ? " " + castPictures.get(file) : "") };
34465
+ const role = productPictures2.has(file) ? "product" : castPictures2.has(file) ? "cast" : file === anchor ? "anchor" : "reference";
34466
+ return { file, role, name: "@image" + (i + 1) + (role === "product" ? " " + productPictures2.get(file) : role === "cast" ? " " + castPictures2.get(file) : "") };
34125
34467
  });
34126
34468
  for (const [k, role] of [["firstFrame", "first frame"], ["lastFrame", "last frame"]]) if (r[k]) pictures.push({ file: r[k], role, name: role });
34127
34469
  const notes2 = [
@@ -34189,7 +34531,7 @@ var init_sheet4 = __esm({
34189
34531
  FONTS2 = '"Helvetica Neue", Arial, "Noto Sans CJK SC", "PingFang SC", "Microsoft YaHei", sans-serif';
34190
34532
  CSS3 = "*{margin:0;padding:0;box-sizing:border-box}body{width:" + WIDTH2 + "px;background:#f4f4f2;color:#16181b;font-family:" + FONTS2 + ";font-size:20px;line-height:1.35;padding:28px}h1{font-size:30px;margin-bottom:6px}h2{font-size:22px;margin:22px 0 10px;border-bottom:2px solid #16181b;padding-bottom:4px}.sum{font-size:20px;color:#3b4046}.row{display:flex;gap:14px;flex-wrap:wrap;align-items:flex-start}.tile{width:236px}.tile .box{width:236px;height:236px;background:#fff;border:3px solid #9aa0a8;display:flex;align-items:center;justify-content:center}.tile img{max-width:100%;max-height:100%;display:block}.tile.product .box{border-color:#e8a020;border-width:5px}.tile.cast .box{border-color:#2f6fd0;border-width:5px}.tile .cap{font-size:16px;margin-top:4px;overflow-wrap:anywhere}.tile .role{font-weight:700}.card{background:#fff;border:1px solid #c9cdd3;padding:12px 14px;margin-bottom:12px}.card .head{font-weight:700;font-size:21px}.card .spec{color:#3b4046;margin:2px 0 6px}.card .what{margin-bottom:8px;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}.note{font-size:16px;color:#6a4b00}.none{font-size:16px;color:#6b7079}";
34191
34533
  short = (text13, n) => text13.length > n ? text13.slice(0, n - 1).trimEnd() + "\u2026" : text13;
34192
- sheetHtml2 = (s, rows3, first, page2, data) => {
34534
+ sheetHtml2 = (s, rows3, first2, page2, data) => {
34193
34535
  const img = (file) => {
34194
34536
  const bytes = data.get(file);
34195
34537
  const mime = bytes ? sniffImageMime(bytes.subarray(0, 16)) : void 0;
@@ -34201,18 +34543,18 @@ var init_sheet4 = __esm({
34201
34543
  "<h1>" + escapeHtml(msg("Inputs to confirm", "\u5F85\u786E\u8BA4\u7684\u8F93\u5165\u5185\u5BB9")) + " " + escapeHtml(page2) + "</h1>",
34202
34544
  '<div class="sum">' + escapeHtml(t.clips + msg(" clip(s), ", " \u4E2A\u89C6\u9891\u7247\u6BB5\uFF0C") + t.seconds + msg(" s", " \u79D2") + " \xB7 " + t.pictures + msg(" picture(s)", " \u5F20\u56FE\u7247") + " \xB7 " + s.voices.length + msg(" voice(s)", " \u4E2A\u914D\u97F3") + " \xB7 " + msg("total ", "\u5408\u8BA1 ") + t.credits + msg(" credits", " \u79EF\u5206") + (t.unpriced ? msg(" + " + t.unpriced + " unpriced", " + " + t.unpriced + " \u9879\u672A\u5B9A\u4EF7") : "") + (t.balance !== void 0 ? " \xB7 " + msg("balance ", "\u4F59\u989D ") + t.balance : "")) + "</div>"
34203
34545
  ];
34204
- if (first && s.products.length) {
34546
+ if (first2 && s.products.length) {
34205
34547
  out2.push("<h2>" + escapeHtml(msg("Product: the picture exactly as it is sent", "\u5546\u54C1\uFF1A\u5B9E\u9645\u53D1\u9001\u7684\u56FE\u7247")) + '</h2><div class="row">');
34206
34548
  for (const p of s.products) for (const x2 of p.pictures) out2.push(tile("product", x2.file, p.id, x2.original ? msg("crop of ", "\u88C1\u526A\u81EA ") + x2.original : msg("the user's picture, whole", "\u7528\u6237\u539F\u56FE\uFF0C\u672A\u88C1\u526A")));
34207
34549
  out2.push("</div>");
34208
34550
  }
34209
- if (first && (s.cast.length || s.anchor)) {
34551
+ if (first2 && (s.cast.length || s.anchor)) {
34210
34552
  out2.push("<h2>" + escapeHtml(msg("People", "\u51FA\u955C\u4EBA\u7269")) + '</h2><div class="row">');
34211
34553
  for (const c of s.cast) out2.push(c.picture ? tile("cast", c.picture, c.id, short(c.description, 90)) : '<div class="tile cast"><div class="box"><span class="none">' + escapeHtml(msg("described in the prompt, no picture", "\u4EC5\u5728\u63D0\u793A\u8BCD\u4E2D\u63CF\u8FF0\uFF0C\u65E0\u56FE\u7247")) + '</span></div><div class="cap"><span class="role">' + escapeHtml(c.id) + "</span> " + escapeHtml(short(c.description, 90)) + "</div></div>");
34212
34554
  if (s.anchor) out2.push(tile("cast", s.anchor.file, msg("anchor", "\u951A\u5B9A\u56FE"), s.anchor.note));
34213
34555
  out2.push("</div>");
34214
34556
  }
34215
- if (first && s.voices.length) {
34557
+ if (first2 && s.voices.length) {
34216
34558
  out2.push("<h2>" + escapeHtml(msg("Voice", "\u914D\u97F3")) + "</h2>");
34217
34559
  for (const v of s.voices) out2.push('<div class="card"><div class="head">' + escapeHtml(v.speaker + ": " + (v.name ?? v.voice)) + '</div><div class="spec">' + escapeHtml([v.language, msg("speed ", "\u8BED\u901F ") + v.speed, v.lines.length + msg(" line(s)", " \u53E5\u53F0\u8BCD"), v.credits === null ? "" : v.credits + msg(" credits", " \u79EF\u5206")].filter(Boolean).join(" \xB7 ")) + '</div><div class="what">' + escapeHtml(short(v.script.display ?? v.lines.join(" / "), 260)) + '</div><div class="note">' + escapeHtml(v.sample ? msg("listen: ", "\u8BD5\u542C\uFF1A") + v.sample.file : msg("no free sample", "\u6CA1\u6709\u514D\u8D39\u8BD5\u542C")) + "</div></div>");
34218
34560
  }
@@ -34471,8 +34813,8 @@ var init_takes = __esm({
34471
34813
  const spans = lines2.map((line) => {
34472
34814
  const part = a.tokens.slice(k, k + tokenize(line).length);
34473
34815
  k += part.length;
34474
- const first = part[0], end = part[part.length - 1];
34475
- const span2 = first && end ? { start: first.start / 1e3, end: end.end / 1e3 } : { start: last, end: last };
34816
+ const first2 = part[0], end = part[part.length - 1];
34817
+ const span2 = first2 && end ? { start: first2.start / 1e3, end: end.end / 1e3 } : { start: last, end: last };
34476
34818
  last = span2.end;
34477
34819
  return span2;
34478
34820
  });
@@ -34483,11 +34825,11 @@ var init_takes = __esm({
34483
34825
  const each = seconds8 / Math.max(1, units2.length);
34484
34826
  return units2.map((text13, k) => ({ text: text13, start: k * each, end: (k + 1) * each }));
34485
34827
  };
34486
- piecesOf = (take, spans, ref, fps, hold, keepPauses = false) => {
34828
+ piecesOf = (take2, spans, ref, fps, hold, keepPauses = false) => {
34487
34829
  const pieces = [];
34488
- let lines2 = [take.lines[0]], from = 0;
34489
- for (let j = 1; j < take.lines.length; j++) {
34490
- const a = take.lines[j - 1], b = take.lines[j];
34830
+ let lines2 = [take2.lines[0]], from = 0;
34831
+ for (let j = 1; j < take2.lines.length; j++) {
34832
+ const a = take2.lines[j - 1], b = take2.lines[j];
34491
34833
  const sa = spans[j - 1], sb = spans[j];
34492
34834
  const gap = (ref.starts[b] ?? 0) - ((ref.starts[a] ?? 0) + (ref.slots[a] ?? 0));
34493
34835
  const held = (ref.starts[b] ?? 0) - (ref.starts[a] ?? 0) > (sb.start - sa.start) * fps;
@@ -34710,14 +35052,14 @@ var init_speak = __esm({
34710
35052
  const clips = await speakLines(rt, { lines: takes.map((t) => t.text), dir: rt.path.join(o.outDir, "assets", "voice"), speaker: o.speaker, fps, name: "take", ...plan4.voice ? { voice: plan4.voice } : {}, ...plan4.speed ? { speed: plan4.speed } : {} });
34711
35053
  const said = [];
34712
35054
  let own3 = true;
34713
- for (const [k, take] of takes.entries()) {
34714
- const clip11 = clips[k], lines3 = take.lines.map((i) => spoken[i] ?? "");
35055
+ for (const [k, take2] of takes.entries()) {
35056
+ const clip11 = clips[k], lines3 = take2.lines.map((i) => spoken[i] ?? "");
34715
35057
  const got = await takeWords(rt, o, clip11, lines3, fps, notes2);
34716
35058
  const words2 = got.words;
34717
35059
  own3 = own3 && got.own;
34718
35060
  const { spans, matched } = lineSpans(lines3, words2);
34719
- if (matched < 0.6) notes2.push("Only " + Math.round(matched * 100) + "% of the words of the take of captions[" + take.lines[0] + ".." + take.lines[take.lines.length - 1] + "] were said as written: its lines are placed by the words around them.");
34720
- said.push({ take, clip: clip11, words: words2, spans, pieces: piecesOf(take, spans, ref, fps, o.hold === true, o.keepPauses === true) });
35061
+ if (matched < 0.6) notes2.push("Only " + Math.round(matched * 100) + "% of the words of the take of captions[" + take2.lines[0] + ".." + take2.lines[take2.lines.length - 1] + "] were said as written: its lines are placed by the words around them.");
35062
+ said.push({ take: take2, clip: clip11, words: words2, spans, pieces: piecesOf(take2, spans, ref, fps, o.hold === true, o.keepPauses === true) });
34721
35063
  }
34722
35064
  const lengthNotes = [];
34723
35065
  const fitted = await fitLength(rt, said, ref, fps, o, lengthNotes);
@@ -34752,10 +35094,10 @@ var init_speak = __esm({
34752
35094
  ...plan4.speed ? { speed: plan4.speed } : {}
34753
35095
  });
34754
35096
  const flow = (ls) => retarget({ ...o.input, plan: { ...plan4, sound: VOICE_FILE }, ...plan4.sound ? { music: plan4.sound } : {}, spoken: { frames: ls.map((l) => l.frames), ...o.hold ? { hold: true } : {} }, wordsFile: WORDS_FILE });
34755
- const first = flow(said);
34756
- const fit = o.fitTempo && first.timing ? await fitTempo(rt, { lines: said, captions, slots: first.timing.slots, max: o.fitTempo, fps }) : void 0;
35097
+ const first2 = flow(said);
35098
+ const fit = o.fitTempo && first2.timing ? await fitTempo(rt, { lines: said, captions, slots: first2.timing.slots, max: o.fitTempo, fps }) : void 0;
34757
35099
  const lines2 = fit?.lines ?? said;
34758
- const result = fit?.tempos.some((t2) => t2 > 1) ? flow(lines2) : first;
35100
+ const result = fit?.tempos.some((t2) => t2 > 1) ? flow(lines2) : first2;
34759
35101
  if (!result.project || !result.timing) return { result, lines: lines2, notes: notes2 };
34760
35102
  notes2.push(...fit?.notes ?? []);
34761
35103
  const t = result.timing;
@@ -35049,7 +35391,7 @@ var init_character = __esm({
35049
35391
  });
35050
35392
 
35051
35393
  // src/video/commands/materials.ts
35052
- var errorsIn, PICTURE_EXT2, givenAnchor, characterOf, budgeted, payingPending, LOOK_AGAIN_MS, waitLimitMs, pendingNext3, beingMade2, allRuns, PRICE_NEXT, specOf2, toAgree, materials;
35394
+ var errorsIn, PICTURE_EXT2, givenAnchor, characterOf, budgeted, newSpend, paying, LOOK_AGAIN_MS, waitLimitMs, pendingNext3, beingMade2, allRuns, PRICE_NEXT, specOf2, toAgree, materials;
35053
35395
  var init_materials = __esm({
35054
35396
  "src/video/commands/materials.ts"() {
35055
35397
  "use strict";
@@ -35063,6 +35405,7 @@ var init_materials = __esm({
35063
35405
  init_character();
35064
35406
  init_approved();
35065
35407
  init_generate();
35408
+ init_failure();
35066
35409
  init_time();
35067
35410
  init_wallet();
35068
35411
  init_credits();
@@ -35109,11 +35452,30 @@ var init_materials = __esm({
35109
35452
  return made;
35110
35453
  }
35111
35454
  });
35112
- payingPending = (generator, wallet) => ({
35113
- make: (kind, request, out2, env2) => generator.make(kind, request, out2, env2).catch((e) => {
35114
- if (e instanceof StillMaking) wallet?.pay(e.pending.chargedCredits ?? 0);
35115
- throw e;
35116
- })
35455
+ newSpend = () => ({ paid: /* @__PURE__ */ new Map(), refunded: 0, failed: /* @__PURE__ */ new Map() });
35456
+ paying = (generator, wallet, spend) => ({
35457
+ make: async (kind, request, out2, env2) => {
35458
+ const failed4 = spend.failed.get(out2);
35459
+ if (failed4) throw failed4;
35460
+ try {
35461
+ return await generator.make(kind, request, out2, env2);
35462
+ } catch (e) {
35463
+ if (e instanceof StillMaking) {
35464
+ const charged = Math.max(0, e.pending.chargedCredits ?? 0);
35465
+ wallet?.pay(charged);
35466
+ spend.paid.set(out2, (spend.paid.get(out2) ?? 0) + charged);
35467
+ }
35468
+ if (e instanceof GenerationFailed) {
35469
+ const paid = spend.paid.get(out2) ?? 0;
35470
+ const back = Math.min(paid, e.failure.refundedCredits ?? 0);
35471
+ wallet?.refund(back);
35472
+ spend.paid.set(out2, paid - back);
35473
+ spend.refunded += back;
35474
+ spend.failed.set(out2, e);
35475
+ }
35476
+ throw e;
35477
+ }
35478
+ }
35117
35479
  });
35118
35480
  LOOK_AGAIN_MS = 15e3;
35119
35481
  waitLimitMs = (rt) => (Number(rt.env.POPOST_GEN_WAIT_MIN) > 0 ? Number(rt.env.POPOST_GEN_WAIT_MIN) : 30) * 6e4;
@@ -35125,7 +35487,7 @@ var init_materials = __esm({
35125
35487
  };
35126
35488
  return [...count5("video", "clip"), ...count5("image", "picture")].join(" and ");
35127
35489
  };
35128
- allRuns = async (rt, once5, noWait) => {
35490
+ allRuns = async (rt, once5, noWait, spend) => {
35129
35491
  let r = await once5();
35130
35492
  const made = new Set(r.materials.filter((m) => m.made).map((m) => m.file));
35131
35493
  let charged = r.chargedCredits;
@@ -35138,7 +35500,8 @@ var init_materials = __esm({
35138
35500
  for (const m of r.materials) if (m.made) made.add(m.file);
35139
35501
  charged += r.chargedCredits;
35140
35502
  }
35141
- return { ...r, chargedCredits: charged, materials: r.materials.map((m) => made.has(m.file) && !m.made && !m.error ? { ...m, made: true } : m) };
35503
+ const refunded = spend.refunded > 0 ? { refundedCredits: spend.refunded } : {};
35504
+ return { ...r, chargedCredits: charged - spend.refunded, ...refunded, materials: r.materials.map((m) => made.has(m.file) && !m.made && !m.error ? { ...m, made: true } : m) };
35142
35505
  };
35143
35506
  PRICE_NEXT = "Nothing was charged for these files. When the credits fit what is left of the budget the user agreed to for this video, run the same command again with --confirm --max-credits <what is left>; otherwise show the user the model, resolution, seconds, aspect ratio and credits of every item (and the balance) and run it so once they agree.";
35144
35507
  specOf2 = (c) => ({
@@ -35233,10 +35596,12 @@ var init_materials = __esm({
35233
35596
  const lang = await readProjectLang(rt, dir);
35234
35597
  const policy = isChinese(lang) ? (await promptPolicy(rt)).policy : "user";
35235
35598
  const musicTrack = await hasMusicTrack(rt, dir);
35599
+ const spend = newSpend();
35600
+ const paid = paying(budgeted(generator, wallet, args.list("approve-unplanned")), wallet, spend);
35236
35601
  const r = await allRuns(rt, () => makeMaterials(rt, {
35237
35602
  requests,
35238
35603
  dir,
35239
- generator: payingPending(budgeted(generator, wallet, args.list("approve-unplanned")), wallet),
35604
+ generator: paid,
35240
35605
  plan: wallet !== void 0,
35241
35606
  submitOnly: true,
35242
35607
  product: { ...limits, paying: !pricedOnly },
@@ -35251,7 +35616,7 @@ var init_materials = __esm({
35251
35616
  ...picture3 ? { picture: picture3 } : {},
35252
35617
  // A clip takes minutes: a person watching sees which one, on stderr; stdout keeps the one JSON document.
35253
35618
  onStep: (file, done2, total2) => rt.stderr(file + " (" + (done2 + 1) + "/" + total2 + ")\n")
35254
- }), noWait);
35619
+ }), noWait, spend);
35255
35620
  const agree = toAgree(r.materials, r.clipMusic);
35256
35621
  printJson(rt, {
35257
35622
  ok: errorsIn(r.problems) === 0,
@@ -35268,6 +35633,7 @@ var init_materials = __esm({
35268
35633
  } : {},
35269
35634
  credits: r.credits,
35270
35635
  chargedCredits: r.chargedCredits,
35636
+ ...r.refundedCredits ? { refundedCredits: r.refundedCredits } : {},
35271
35637
  ...r.anchor ? { anchor: r.anchor } : {},
35272
35638
  ...r.toConfirm ? { toConfirm: r.toConfirm } : {},
35273
35639
  ...agree ?? {},
@@ -35783,8 +36149,8 @@ var init_readback = __esm({
35783
36149
  const unitsExpected = units(form), unitsHeard = units(heard);
35784
36150
  line.heard = heard;
35785
36151
  line.heardScore = Math.round(Math.max(closeness(form, heard), unitsExpected ? Math.min(1, unitsHeard / unitsExpected) * 0.6 : 0) * 100) / 100;
35786
- const first = words.find((w) => w.start < item2.end + 6 && w.end > item2.start - 6);
35787
- if (first) line.lag = item2.start - first.start;
36152
+ const first2 = words.find((w) => w.start < item2.end + 6 && w.end > item2.start - 6);
36153
+ if (first2) line.lag = item2.start - first2.start;
35788
36154
  }
35789
36155
  return line;
35790
36156
  });
@@ -36109,8 +36475,8 @@ var init_rings = __esm({
36109
36475
  const i = px2[j] ?? 0, x0 = i % f.w, y0 = Math.floor(i / f.w);
36110
36476
  for (const [dx, dy] of DIRS2) {
36111
36477
  if (!inside3(f, x0 + dx, y0 + dy)) continue;
36112
- const first = labOf(f, (y0 + dy) * f.w + x0 + dx);
36113
- if (dot2(sub2(first, lab), sub2(first, lab)) <= NEAR * NEAR) continue;
36478
+ const first2 = labOf(f, (y0 + dy) * f.w + x0 + dx);
36479
+ if (dot2(sub2(first2, lab), sub2(first2, lab)) <= NEAR * NEAR) continue;
36114
36480
  ends++;
36115
36481
  for (let k = 1; k <= reach && inside3(f, x0 + dx * k, y0 + dy * k); k++) {
36116
36482
  const a = along(lab, partner, labOf(f, (y0 + dy * k) * f.w + x0 + dx * k));
@@ -36352,18 +36718,18 @@ var init_letters = __esm({
36352
36718
  return lines2.length >= Math.max(2, 0.2 * n) ? [{ ...aggregate(s.group, s.px, s.perLine, lines2), ground: false, told: lines2 }] : [];
36353
36719
  });
36354
36720
  HUG_TIE = 0.1;
36355
- fillAmong = (frames, boxes2, first, own3, weight) => {
36356
- const mutual = (s) => along(first.group.lab, first.around, s.group.lab).t >= 0.5 && along(s.group.lab, s.around, first.group.lab).t >= 0.5;
36357
- const within = (s) => s.enclosed >= ENCLOSED && (dEdge(s.around, first.around) <= 15 || (() => {
36358
- const a = along(s.group.lab, first.around, s.around);
36721
+ fillAmong = (frames, boxes2, first2, own3, weight) => {
36722
+ const mutual = (s) => along(first2.group.lab, first2.around, s.group.lab).t >= 0.5 && along(s.group.lab, s.around, first2.group.lab).t >= 0.5;
36723
+ const within = (s) => s.enclosed >= ENCLOSED && (dEdge(s.around, first2.around) <= 15 || (() => {
36724
+ const a = along(s.group.lab, first2.around, s.around);
36359
36725
  return a.t >= 0.5 && a.off <= 15;
36360
36726
  })());
36361
- const rivals = own3.filter((s) => s === first || within(s) || mutual(s));
36362
- if (rivals.length < 2) return first;
36727
+ const rivals = own3.filter((s) => s === first2 || within(s) || mutual(s));
36728
+ if (rivals.length < 2) return first2;
36363
36729
  const told = rivals.flatMap((s) => s.told ? [s.told] : []);
36364
36730
  const hugs = rivals.map((s) => ({ s, hug: hugOf(frames, boxes2, s.px, s.group.at.map((l, k) => told.every((t) => t.includes(k)) ? l : void 0), s.around) }));
36365
36731
  const most = Math.max(...hugs.map((h) => h.hug));
36366
- return hugs.filter((h) => h.hug >= most - HUG_TIE).sort((a, b) => weight(b.s) - weight(a.s))[0]?.s ?? first;
36732
+ return hugs.filter((h) => h.hug >= most - HUG_TIE).sort((a, b) => weight(b.s) - weight(a.s))[0]?.s ?? first2;
36367
36733
  };
36368
36734
  lettersOf = (frames, boxes2, all, around3) => {
36369
36735
  const n = frames.length;
@@ -36610,20 +36976,20 @@ var init_reveal2 = __esm({
36610
36976
  return frames.map((f) => {
36611
36977
  const has2 = columns.map((ink) => ink.filter((i) => near2(f, i, colours)).length >= 0.5 * ink.length);
36612
36978
  const count5 = has2.filter(Boolean).length;
36613
- const last = has2.lastIndexOf(true), first = has2.indexOf(true);
36614
- const ordered3 = count5 > 0 && (count5 >= 0.85 * (last + 1) || count5 >= 0.85 * (has2.length - first));
36979
+ const last = has2.lastIndexOf(true), first2 = has2.indexOf(true);
36980
+ const ordered3 = count5 > 0 && (count5 >= 0.85 * (last + 1) || count5 >= 0.85 * (has2.length - first2));
36615
36981
  return { share: count5 / columns.length, ordered: ordered3 };
36616
36982
  });
36617
36983
  };
36618
36984
  lineReveal = (cover, chars, fps) => {
36619
- const first = cover.findIndex((c) => c.share >= 0.08);
36620
- if (first <= 0) return void 0;
36621
- if (cover.slice(0, first).some((c) => c.share >= 0.08)) return void 0;
36622
- const full = cover.findIndex((c, k) => k >= first && c.share >= 0.9);
36985
+ const first2 = cover.findIndex((c) => c.share >= 0.08);
36986
+ if (first2 <= 0) return void 0;
36987
+ if (cover.slice(0, first2).some((c) => c.share >= 0.08)) return void 0;
36988
+ const full = cover.findIndex((c, k) => k >= first2 && c.share >= 0.9);
36623
36989
  const wholeFrames = Math.max(2, Math.ceil(WHOLE_SECONDS * fps));
36624
- if (full >= 0 && full - first <= wholeFrames) return { kind: "whole" };
36990
+ if (full >= 0 && full - first2 <= wholeFrames) return { kind: "whole" };
36625
36991
  const end = full >= 0 ? full : cover.length - 1;
36626
- const span2 = cover.slice(first, end + 1);
36992
+ const span2 = cover.slice(first2, end + 1);
36627
36993
  if (full < 0 && span2.length < wholeFrames + 2) return void 0;
36628
36994
  if (span2.filter((c) => c.ordered).length < 0.7 * span2.length) return { kind: "whole" };
36629
36995
  let steps2 = 1, at7 = span2[0]?.share ?? 0;
@@ -36633,7 +36999,7 @@ var init_reveal2 = __esm({
36633
36999
  }
36634
37000
  const reached = Math.max(0.08, span2[span2.length - 1]?.share ?? 1);
36635
37001
  const perStep = chars * reached / steps2;
36636
- return { kind: perStep >= 1.6 ? "words" : "chars", ...full >= 0 ? { frames: full - first } : {} };
37002
+ return { kind: perStep >= 1.6 ? "words" : "chars", ...full >= 0 ? { frames: full - first2 } : {} };
36637
37003
  };
36638
37004
  revealOf = (lines2, fps) => {
36639
37005
  const seen = lines2.flatMap((l) => l ? [l] : []);
@@ -36656,8 +37022,8 @@ var init_reveal2 = __esm({
36656
37022
  const wanted = [...new Set(spans.flatMap((s) => [...Array.from({ length: s.to - s.from + 1 }, (_v, k) => s.from + k), s.mid]))].sort((a, b) => a - b);
36657
37023
  const scale = Math.min(1, MAX_WIDTH / info.width);
36658
37024
  const W = Math.round(info.width * scale / 2) * 2, H = Math.round(info.height * scale / 2) * 2;
36659
- const size = median10(cues.map((c) => c.box[3])) * H;
36660
- const top2 = Math.max(0, Math.floor(Math.min(...cues.map((c) => c.box[1])) * H - size)), bottom = Math.min(H, Math.ceil(Math.max(...cues.map((c) => c.box[1] + c.box[3])) * H + size));
37025
+ const size2 = median10(cues.map((c) => c.box[3])) * H;
37026
+ const top2 = Math.max(0, Math.floor(Math.min(...cues.map((c) => c.box[1])) * H - size2)), bottom = Math.min(H, Math.ceil(Math.max(...cues.map((c) => c.box[1] + c.box[3])) * H + size2));
36661
37027
  const h = bottom - top2;
36662
37028
  if (h <= 0) return void 0;
36663
37029
  const colour2 = await readColour(rt, video, info);
@@ -36952,9 +37318,9 @@ var init_look = __esm({
36952
37318
  if (picked2.length < MIN_SAMPLES) return { frames: [], boxes: [], texts: [] };
36953
37319
  const info = await probe2(rt, video);
36954
37320
  const W = info.width, H = info.height;
36955
- const size = median10(picked2.map((p) => p.cue.box[3])) * H;
36956
- const top2 = Math.max(0, Math.floor(Math.min(...picked2.map((p) => p.cue.box[1])) * H - 2.5 * size));
36957
- const bottom = Math.min(H, Math.ceil(Math.max(...picked2.map((p) => p.cue.box[1] + p.cue.box[3])) * H + 2.5 * size));
37321
+ const size2 = median10(picked2.map((p) => p.cue.box[3])) * H;
37322
+ const top2 = Math.max(0, Math.floor(Math.min(...picked2.map((p) => p.cue.box[1])) * H - 2.5 * size2));
37323
+ const bottom = Math.min(H, Math.ceil(Math.max(...picked2.map((p) => p.cue.box[1] + p.cue.box[3])) * H + 2.5 * size2));
36958
37324
  const h = bottom - top2;
36959
37325
  const frames = [...new Set(picked2.map((p) => p.frame))].sort((a, b) => a - b);
36960
37326
  const colour2 = await readColour(rt, video, info);
@@ -37040,9 +37406,9 @@ var init_text = __esm({
37040
37406
  captionBandOf = (track) => {
37041
37407
  const captions = track.cues.filter((c) => c.role === "caption");
37042
37408
  if (captions.length < 3) return void 0;
37043
- const size = captions.map((c) => c.size).sort((a, b) => a - b)[Math.floor(captions.length / 2)] ?? 0;
37044
- const top2 = Math.min(...captions.map((c) => c.box[1])) - 0.7 * size;
37045
- const bottom = Math.max(...captions.map((c) => c.box[1] + c.box[3])) + 0.7 * size;
37409
+ const size2 = captions.map((c) => c.size).sort((a, b) => a - b)[Math.floor(captions.length / 2)] ?? 0;
37410
+ const top2 = Math.min(...captions.map((c) => c.box[1])) - 0.7 * size2;
37411
+ const bottom = Math.max(...captions.map((c) => c.box[1] + c.box[3])) + 0.7 * size2;
37046
37412
  return { top: Math.max(0, Math.round(top2 * 1e3) / 1e3), bottom: Math.min(1, Math.round(bottom * 1e3) / 1e3) };
37047
37413
  };
37048
37414
  inBand = (l, band) => {
@@ -37079,11 +37445,11 @@ var init_text = __esm({
37079
37445
  const maxSide = opts.maxSide ?? 1280;
37080
37446
  const scale = Math.min(1, maxSide / Math.max(info.width, info.height));
37081
37447
  const width = Math.round(info.width * scale / 2) * 2;
37082
- const size = scale < 1 ? ",scale=" + width + ":-2" : "";
37448
+ const size2 = scale < 1 ? ",scale=" + width + ":-2" : "";
37083
37449
  return withTempDir(rt, "popost-video-frames-", async (root) => {
37084
37450
  const wholeFrames = Array.from({ length: Math.ceil(info.frames / coarse) }, (_, k) => k * coarse);
37085
37451
  opts.onStage?.("taking " + wholeFrames.length + " frames out");
37086
- await runFfmpegOk(rt, ["-y", "-i", video, "-vf", "select=not(mod(n\\," + coarse + "))" + size, "-fps_mode", "passthrough", "-q:v", "2", rt.path.join(root, "w%06d.jpg")]);
37452
+ await runFfmpegOk(rt, ["-y", "-i", video, "-vf", "select=not(mod(n\\," + coarse + "))" + size2, "-fps_mode", "passthrough", "-q:v", "2", rt.path.join(root, "w%06d.jpg")]);
37087
37453
  const listed3 = await numbered(rt, root, "w", wholeFrames);
37088
37454
  opts.onStage?.("the reader is reading " + listed3.length + " frames");
37089
37455
  const whole2 = (await reader.read(listed3)).sort((a, b) => a.frame - b.frame);
@@ -37092,7 +37458,7 @@ var init_text = __esm({
37092
37458
  if (!band) return { samples: whole2, step: coarse, total: info.frames, fps: info.fps, whole: whole2.length, strips: 0 };
37093
37459
  const stripFrames = Array.from({ length: Math.ceil(info.frames / step2) }, (_, k) => k * step2).filter((n) => n % coarse !== 0);
37094
37460
  const crop2 = ",crop=iw:trunc(ih*" + (band.bottom - band.top).toFixed(4) + "/2)*2:0:trunc(ih*" + band.top.toFixed(4) + ")";
37095
- await runFfmpegOk(rt, ["-y", "-i", video, "-vf", "select=not(mod(n\\," + step2 + "))*gt(mod(n\\," + coarse + ")\\,0)" + size + crop2, "-fps_mode", "passthrough", "-q:v", "2", rt.path.join(root, "s%06d.jpg")]);
37461
+ await runFfmpegOk(rt, ["-y", "-i", video, "-vf", "select=not(mod(n\\," + step2 + "))*gt(mod(n\\," + coarse + ")\\,0)" + size2 + crop2, "-fps_mode", "passthrough", "-q:v", "2", rt.path.join(root, "s%06d.jpg")]);
37096
37462
  const stripped = await numbered(rt, root, "s", stripFrames);
37097
37463
  opts.onStage?.("the reader is reading " + stripped.length + " caption strips");
37098
37464
  const strips = await reader.read(stripped);
@@ -37161,13 +37527,13 @@ var init_readback_frames = __esm({
37161
37527
  readFrames2 = async (rt, video, reader, frames, o) => {
37162
37528
  const info = await probe2(rt, video);
37163
37529
  const scale = Math.min(1, 1280 / Math.max(info.width, info.height));
37164
- const size = scale < 1 ? ",scale=" + Math.round(info.width * scale / 2) * 2 + ":-2" : "";
37530
+ const size2 = scale < 1 ? ",scale=" + Math.round(info.width * scale / 2) * 2 + ":-2" : "";
37165
37531
  const wanted = [...new Set(frames.filter((f) => Number.isInteger(f) && f >= 0 && f < info.frames))].sort((a, b) => a - b);
37166
37532
  if (!wanted.length) return { samples: [], step: o.step, total: info.frames, fps: info.fps, whole: 0, strips: 0 };
37167
37533
  return withTempDir(rt, "popost-video-frames-", async (root) => {
37168
37534
  o.onStage?.("taking " + wanted.length + " frames out");
37169
37535
  const select2 = "select='" + pickExpression(wanted) + "'";
37170
- await runFfmpegOk(rt, ["-y", "-i", video, "-vf", select2 + size, "-fps_mode", "passthrough", "-q:v", "2", rt.path.join(root, "r%06d.jpg")]);
37536
+ await runFfmpegOk(rt, ["-y", "-i", video, "-vf", select2 + size2, "-fps_mode", "passthrough", "-q:v", "2", rt.path.join(root, "r%06d.jpg")]);
37171
37537
  const files = (await rt.fs.readdir(root)).filter((f) => f.startsWith("r") && f.endsWith(".jpg")).sort();
37172
37538
  if (files.length !== wanted.length)
37173
37539
  throw new ToolError("readback: extracted " + files.length + " of " + wanted.length + " requested frames. Check the video decoder and frame count; an incomplete reading cannot verify the captions.");
@@ -37282,10 +37648,10 @@ var init_readback_run = __esm({
37282
37648
  if (looked || frames.length < 3 * FIRST_LOOK) return reader.read(frames);
37283
37649
  looked = true;
37284
37650
  const picked2 = new Set(Array.from({ length: FIRST_LOOK }, (_, k) => Math.floor((2 * k + 1) * frames.length / (2 * FIRST_LOOK))));
37285
- const first = await reader.read(frames.filter((_, i) => picked2.has(i)));
37286
- onFirst(first.reduce((n, s) => n + s.lines.length, 0) / FIRST_LOOK);
37651
+ const first2 = await reader.read(frames.filter((_, i) => picked2.has(i)));
37652
+ onFirst(first2.reduce((n, s) => n + s.lines.length, 0) / FIRST_LOOK);
37287
37653
  const rest = await reader.read(frames.filter((_, i) => !picked2.has(i)));
37288
- return [...first, ...rest].sort((a, b) => a.frame - b.frame);
37654
+ return [...first2, ...rest].sort((a, b) => a.frame - b.frame);
37289
37655
  }
37290
37656
  };
37291
37657
  };
@@ -37427,12 +37793,12 @@ var init_sheets = __esm({
37427
37793
  blit = (c, tile, tw, th, x2, y) => {
37428
37794
  for (let r = 0; r < th; r++) c.data.set(tile.subarray(r * tw * 3, (r + 1) * tw * 3), ((y + r) * c.width + x2) * 3);
37429
37795
  };
37430
- decodePicked = async (rt, video, frames, size, colour2, onFrame) => {
37431
- const bytes = size.width * size.height * 3;
37796
+ decodePicked = async (rt, video, frames, size2, colour2, onFrame) => {
37797
+ const bytes = size2.width * size2.height * 3;
37432
37798
  for (const part of frameChunks(frames)) {
37433
37799
  let k = 0, filled2 = 0;
37434
37800
  let current = new Uint8Array(bytes);
37435
- const vf = "select='" + pickExpression(part) + "',scale=" + size.width + ":" + size.height + ":in_color_matrix=" + colour2.matrix + ":in_range=" + colour2.range + ":flags=area+accurate_rnd,format=rgb24";
37801
+ const vf = "select='" + pickExpression(part) + "',scale=" + size2.width + ":" + size2.height + ":in_color_matrix=" + colour2.matrix + ":in_range=" + colour2.range + ":flags=area+accurate_rnd,format=rgb24";
37436
37802
  const r = await runFfmpeg(rt, ["-loglevel", "error", "-i", video, "-map", "0:v:0", "-an", "-sn", "-vf", vf, "-fps_mode", "passthrough", "-f", "rawvideo", "pipe:1"], void 0, (chunk) => {
37437
37803
  let off2 = 0;
37438
37804
  while (off2 < chunk.length) {
@@ -37477,14 +37843,14 @@ var init_sheets = __esm({
37477
37843
  writeSheets2 = async (rt, video, specs2, o) => {
37478
37844
  const p = o.probe ?? await probe2(rt, video);
37479
37845
  const colour2 = o.colour ?? await readColour(rt, video, p);
37480
- const size = thumbSize(p.width, p.height, Math.min(o.width, p.width));
37846
+ const size2 = thumbSize(p.width, p.height, Math.min(o.width, p.width));
37481
37847
  const fps = p.fps > 0 ? p.fps : 30;
37482
37848
  const secondsOf4 = o.secondsOf ?? ((f) => f / fps);
37483
37849
  const last = Math.max(0, sourceFrames(p) - 1);
37484
37850
  const drawings = specs2.map((spec10) => {
37485
37851
  const frames2 = spec10.frames.filter((f) => f >= 0 && f <= last);
37486
- const grid = gridOf(Math.max(1, frames2.length), size.width);
37487
- const drawn = { width: GAP2 + grid.columns * (size.width + GAP2), height: GAP2 + grid.rows * (size.height + BAND + GAP2) };
37852
+ const grid = gridOf(Math.max(1, frames2.length), size2.width);
37853
+ const drawn = { width: GAP2 + grid.columns * (size2.width + GAP2), height: GAP2 + grid.rows * (size2.height + BAND + GAP2) };
37488
37854
  const result = { file: rt.path.join(o.outDir, spec10.file), frames: frames2, seconds: frames2.map((f) => Math.round(secondsOf4(f) * 1e3) / 1e3), ...grid, ...lookSize(drawn.width, drawn.height) };
37489
37855
  return { spec: { ...spec10, frames: frames2 }, grid, drawn, left: frames2.length, result };
37490
37856
  });
@@ -37506,24 +37872,24 @@ var init_sheets = __esm({
37506
37872
  });
37507
37873
  };
37508
37874
  const frames = [.../* @__PURE__ */ new Set([...wanted.keys(), ...keep3])].sort((a, b) => a - b);
37509
- await decodePicked(rt, video, frames, size, colour2, (frame2, rgb) => {
37875
+ await decodePicked(rt, video, frames, size2, colour2, (frame2, rgb) => {
37510
37876
  if (keep3.has(frame2)) kept3.set(frame2, rgb);
37511
37877
  for (const { d, slot } of wanted.get(frame2) ?? []) {
37512
37878
  const marked2 = (d.spec.marked ?? []).some(([a, b]) => frame2 >= a && frame2 <= b);
37513
- place2(d, slot, rgb, size.width, size.height, timeLabel(secondsOf4(frame2)), marked2);
37879
+ place2(d, slot, rgb, size2.width, size2.height, timeLabel(secondsOf4(frame2)), marked2);
37514
37880
  if (--d.left === 0) finish3(d);
37515
37881
  }
37516
37882
  });
37517
37883
  for (const d of drawings) if (d.left > 0 && d.canvas) finish3(d);
37518
37884
  await written2;
37519
37885
  if (failed4) throw failed4.error;
37520
- return { sheets: drawings.filter((d) => d.written).map((d) => d.result), kept: kept3, size };
37886
+ return { sheets: drawings.filter((d) => d.written).map((d) => d.result), kept: kept3, size: size2 };
37521
37887
  };
37522
37888
  }
37523
37889
  });
37524
37890
 
37525
37891
  // src/video/look/index.ts
37526
- var two11, r36, clamp4, shotMoments, secondMoments, GLYPHS2, labelFilter, JPEG, pair3, sheet3, lookAt3;
37892
+ var two11, r36, clamp4, shotMoments, secondMoments, GLYPHS2, labelFilter, JPEG, pair4, sheet3, lookAt3;
37527
37893
  var init_look2 = __esm({
37528
37894
  "src/video/look/index.ts"() {
37529
37895
  "use strict";
@@ -37551,7 +37917,7 @@ var init_look2 = __esm({
37551
37917
  return [box2(s, s, 7 * s, 9 * s, "black@0.6"), ...cells].join(",");
37552
37918
  };
37553
37919
  JPEG = LOOK_JPEG;
37554
- pair3 = async (rt, a, b, height, out2) => {
37920
+ pair4 = async (rt, a, b, height, out2) => {
37555
37921
  const side = (i, letter) => "[" + i + ":v]scale=-2:" + height + "," + labelFilter(letter, height) + "[" + letter + "]";
37556
37922
  await runFfmpegOk(rt, ["-y", "-loglevel", "error", "-i", a, "-i", b, "-filter_complex", side(0, "A") + ";" + side(1, "B") + ";[A][B]hstack=inputs=2", "-frames:v", "1", ...JPEG, out2]);
37557
37923
  };
@@ -37581,7 +37947,7 @@ var init_look2 = __esm({
37581
37947
  continue;
37582
37948
  }
37583
37949
  const other = others[i];
37584
- await pair3(rt, left.get(m.frame), right?.get(other), height, file);
37950
+ await pair4(rt, left.get(m.frame), right?.get(other), height, file);
37585
37951
  pictures.push({ file, frame: m.frame, second: r36(m.frame / a.fps), ...where3, against: { frame: other, second: r36(other / b.fps) } });
37586
37952
  }
37587
37953
  });
@@ -38914,8 +39280,8 @@ var init_build2 = __esm({
38914
39280
  init_ffmpeg();
38915
39281
  even5 = (n) => Math.max(2, Math.round(n / 2) * 2);
38916
39282
  UNTAGGED = ",format=rgb24,setparams=color_primaries=unknown:color_trc=unknown:colorspace=unknown";
38917
- grab2 = async (rt, video, frame2, out2, size, box2) => {
38918
- const crop2 = box2 ? ",crop=" + [even5(box2[2] * size.width), even5(box2[3] * size.height), Math.round(box2[0] * size.width), Math.round(box2[1] * size.height)].join(":") : "";
39283
+ grab2 = async (rt, video, frame2, out2, size2, box2) => {
39284
+ const crop2 = box2 ? ",crop=" + [even5(box2[2] * size2.width), even5(box2[3] * size2.height), Math.round(box2[0] * size2.width), Math.round(box2[1] * size2.height)].join(":") : "";
38919
39285
  await runFfmpegOk(rt, ["-y", "-i", video, "-vf", "select=eq(n\\," + Math.max(0, frame2) + ")" + crop2 + UNTAGGED, "-frames:v", "1", "-fps_mode", "passthrough", out2]);
38920
39286
  };
38921
39287
  transitionSpec2 = (b, toFrames2) => {
@@ -38952,12 +39318,12 @@ var init_build2 = __esm({
38952
39318
  return w <= 0 || h <= 0 ? 0 : w * h / Math.min(a[2] * a[3], b[2] * b[3]);
38953
39319
  };
38954
39320
  cleanFrame = (shot, into, out2) => {
38955
- const first = into ? Math.max(shot.start, into.end) : shot.start;
39321
+ const first2 = into ? Math.max(shot.start, into.end) : shot.start;
38956
39322
  const last = out2 ? Math.min(shot.end - 1, out2.start) : shot.end - 1;
38957
39323
  const firstAppear = shot.events.filter((e) => e.kind === "appear").map((e) => e.start).sort((a, b) => a - b)[0];
38958
39324
  const limit = firstAppear === void 0 ? last : Math.min(last, firstAppear - 1);
38959
- if (shot.camera.kind === "move" && shot.camera.zoomPerS < 0) return Math.max(first, limit);
38960
- return Math.min(Math.max(first, shot.start), Math.max(first, limit));
39325
+ if (shot.camera.kind === "move" && shot.camera.zoomPerS < 0) return Math.max(first2, limit);
39326
+ return Math.min(Math.max(first2, shot.start), Math.max(first2, limit));
38961
39327
  };
38962
39328
  buildFootageDraft = async (rt, o) => {
38963
39329
  const m = o.measure;
@@ -38994,7 +39360,7 @@ var init_build2 = __esm({
38994
39360
  const fps = Math.max(1, Math.round(m.source.fps));
38995
39361
  const ratio3 = fps / m.source.fps;
38996
39362
  const toFrames2 = (n) => Math.round(n * ratio3);
38997
- const size = { width: m.source.width, height: m.source.height };
39363
+ const size2 = { width: m.source.width, height: m.source.height };
38998
39364
  const notes2 = [];
38999
39365
  if (Math.abs(ratio3 - 1) > 1e-6) notes2.push({ at: "canvas.fps", kind: "approximate", message: "The source runs at " + m.source.fps.toFixed(3) + " fps; the project uses " + fps + "." });
39000
39366
  await rt.fs.mkdir(rt.path.join(o.outDir, "assets"));
@@ -39010,7 +39376,7 @@ var init_build2 = __esm({
39010
39376
  const frames = Math.max(1, toFrames2(shot.end) - start);
39011
39377
  const file = "assets/" + id2 + ".png";
39012
39378
  materials2.push({ id: "pic-" + id2, kind: "image", file, note: "placeholder: a frame of the reference" });
39013
- jobs2.push(() => grab2(rt, o.video, cleanFrame(shot, into, out2), rt.path.join(o.outDir, file), size));
39379
+ jobs2.push(() => grab2(rt, o.video, cleanFrame(shot, into, out2), rt.path.join(o.outDir, file), size2));
39014
39380
  const cam = shot.camera;
39015
39381
  const moving = cam.kind === "move" && cam.confidence >= minConfidence;
39016
39382
  const camera3 = moving ? { ...Math.abs(cam.zoomPerS) >= 5e-3 ? { zoom: Number(cam.zoomPerS.toFixed(3)) } : {}, ...Math.hypot(...cam.panPerS) >= 5e-3 ? { pan: [Number(cam.panPerS[0].toFixed(3)), Number(cam.panPerS[1].toFixed(3))] } : {} } : void 0;
@@ -39032,7 +39398,7 @@ var init_build2 = __esm({
39032
39398
  const settled2 = Math.min((gone ? gone.start : shot.end) - 1, ev.end + 2);
39033
39399
  const pic = "assets/" + itemId + ".png";
39034
39400
  materials2.push({ id: "pic-" + itemId, kind: "image", file: pic, note: "placeholder: an element cut out of the reference" });
39035
- jobs2.push(() => grab2(rt, o.video, settled2, rt.path.join(o.outDir, pic), size, ev.box));
39401
+ jobs2.push(() => grab2(rt, o.video, settled2, rt.path.join(o.outDir, pic), size2, ev.box));
39036
39402
  const from = Math.max(0, toFrames2(ev.start) - start);
39037
39403
  const to = gone ? Math.max(from + 1, toFrames2(gone.end) - start) : frames;
39038
39404
  const room = Math.max(1, Math.floor((to - from) / 2));
@@ -39068,7 +39434,7 @@ var init_build2 = __esm({
39068
39434
  else segment2.in.frames = room;
39069
39435
  notes2.push({ at: "segments[" + k + "].in", kind: "approximate", message: "The measured " + (segment2.in?.transition ?? "transition") + " spans " + asked2 + " frames, longer than a neighbouring shot (" + room + " frames); " + (room < 2 ? "it became a hard cut." : "it was shortened to " + room + ".") });
39070
39436
  });
39071
- const project = { version: 1, canvas: { width: even5(size.width), height: even5(size.height), fps }, materials: materials2, segments: segments2, tracks, note: "draft built from a measurement, no model involved" };
39437
+ const project = { version: 1, canvas: { width: even5(size2.width), height: even5(size2.height), fps }, materials: materials2, segments: segments2, tracks, note: "draft built from a measurement, no model involved" };
39072
39438
  await rt.fs.writeFile(rt.path.join(o.outDir, "video.json"), JSON.stringify(project, null, 2) + "\n");
39073
39439
  await rt.fs.writeFile(rt.path.join(o.outDir, "draft-notes.json"), JSON.stringify(notes2, null, 2) + "\n");
39074
39440
  return { project, notes: notes2 };
@@ -39312,8 +39678,8 @@ var init_chunked = __esm({
39312
39678
  shotsIn = (r, ranges) => r.segments.filter((s) => ranges.some(([from, to]) => s.start < to && s.end > from)).map((s) => s.id);
39313
39679
  renderInChunks = async (rt, job) => {
39314
39680
  const started = Date.now();
39315
- const first = job.sessions[0], r = first.resolved;
39316
- const c = job.keep ? await keyContext(rt, job.root, first, { image: job.image, quality: job.quality, crf: job.crf }) : void 0;
39681
+ const first2 = job.sessions[0], r = first2.resolved;
39682
+ const c = job.keep ? await keyContext(rt, job.root, first2, { image: job.image, quality: job.quality, crf: job.crf }) : void 0;
39317
39683
  const dir = c ? chunkDir(rt, c) : job.out + ".chunks";
39318
39684
  await rt.fs.mkdir(dir);
39319
39685
  try {
@@ -39367,9 +39733,9 @@ var init_layout = __esm({
39367
39733
  const fitLines = lineH > 0 ? Math.floor((h + 1e-9) / lineH) : 0;
39368
39734
  const tall = needH > h;
39369
39735
  const how = tall ? "it needs " + fact.lines + " line" + (fact.lines === 1 ? "" : "s") + ", " + r37(needH) + " of the canvas height (" + Math.round(needH * canvas.height) + " px), but its box is " + r37(h) + " high (" + Math.round(h * canvas.height) + " px): " + Math.round((needH / h - 1) * 100) + "% too tall" : "its widest line is " + r37(needW) + " of the canvas width (" + Math.round(needW * canvas.width) + " px), but its box is " + r37(w) + " wide";
39370
- const size = r37(Math.max(w, needW) * MARGIN2) + " x " + r37(Math.max(h, needH) * MARGIN2);
39736
+ const size2 = r37(Math.max(w, needW) * MARGIN2) + " x " + r37(Math.max(h, needH) * MARGIN2);
39371
39737
  const shorten = tall && fitLines >= 1 && fact.lines > fitLines ? Math.max(1, Math.floor(chars * fitLines / fact.lines)) : 0;
39372
- const box2 = "enlarge the box (" + at7.box + ") to " + size + " (width x height, fractions of the canvas)";
39738
+ const box2 = "enlarge the box (" + at7.box + ") to " + size2 + " (width x height, fractions of the canvas)";
39373
39739
  const fix2 = shorten > 0 ? "Shorten the text (" + at7.text + ") to about " + shorten + " characters (it has " + chars + "), or " + box2 + "." : box2.charAt(0).toUpperCase() + box2.slice(1) + ', or use a smaller "size".';
39374
39740
  return { level: "error", at: shorten > 0 ? at7.text : at7.box, message: describe(item2) + " does not fit its box: " + how + ".", fix: fix2 };
39375
39741
  };
@@ -40445,11 +40811,11 @@ var init_truth = __esm({
40445
40811
  const base = segment2.base;
40446
40812
  if (base.kind === "color" || base.kind === "scene") return { kind: "static", zoomPerS: 0, panPerS: [0, 0], confidence: 1 };
40447
40813
  if (base.moves?.length) {
40448
- const first = base.moves[0]?.scale[0] ?? 1, last = base.moves[base.moves.length - 1]?.scale[1] ?? 1;
40814
+ const first2 = base.moves[0]?.scale[0] ?? 1, last = base.moves[base.moves.length - 1]?.scale[1] ?? 1;
40449
40815
  const seconds8 = (segment2.end - segment2.start) / fps;
40450
40816
  return {
40451
40817
  kind: "move",
40452
- zoomPerS: Math.round((last / first - 1) / seconds8 * 1e4) / 1e4,
40818
+ zoomPerS: Math.round((last / first2 - 1) / seconds8 * 1e4) / 1e4,
40453
40819
  panPerS: [0, 0],
40454
40820
  confidence: 1,
40455
40821
  moves: base.moves.map((mv) => ({ start: mv.from, end: mv.to, scale: mv.scale, focus: mv.focus }))
@@ -40504,20 +40870,20 @@ var init_write = __esm({
40504
40870
  return Array.from({ length: n }, (_, i) => "c" + i + "=0x" + [0, 0, 0].map(() => r.int(0, 255).toString(16).padStart(2, "0")).join("")).join(":");
40505
40871
  };
40506
40872
  lavfi = (recipe, width, height) => {
40507
- const size = "size=" + width + "x" + height;
40873
+ const size2 = "size=" + width + "x" + height;
40508
40874
  switch (recipe.source) {
40509
40875
  case "mandelbrot":
40510
- return { input: "mandelbrot=" + size + ":rate=10:start_scale=" + (1.5 + recipe.seed % 10 / 10).toFixed(1), seek: 1 + recipe.seed % 30 / 10 };
40876
+ return { input: "mandelbrot=" + size2 + ":rate=10:start_scale=" + (1.5 + recipe.seed % 10 / 10).toFixed(1), seek: 1 + recipe.seed % 30 / 10 };
40511
40877
  case "testsrc2":
40512
- return { input: "testsrc2=" + size + ":rate=10", seek: recipe.seed % 50 / 10 };
40878
+ return { input: "testsrc2=" + size2 + ":rate=10", seek: recipe.seed % 50 / 10 };
40513
40879
  case "cellauto":
40514
- return { input: "cellauto=" + size + ":rate=10:rule=" + [18, 30, 110, 150][recipe.seed % 4] + ":seed=" + recipe.seed, seek: 2 };
40880
+ return { input: "cellauto=" + size2 + ":rate=10:rule=" + [18, 30, 110, 150][recipe.seed % 4] + ":seed=" + recipe.seed, seek: 2 };
40515
40881
  case "gradients":
40516
- return { input: "gradients=" + size + ":rate=10:seed=" + recipe.seed + ":nb_colors=" + (3 + recipe.seed % 4) + ":" + gradientColours(recipe.seed, 3 + recipe.seed % 4), seek: recipe.seed % 40 / 10 };
40882
+ return { input: "gradients=" + size2 + ":rate=10:seed=" + recipe.seed + ":nb_colors=" + (3 + recipe.seed % 4) + ":" + gradientColours(recipe.seed, 3 + recipe.seed % 4), seek: recipe.seed % 40 / 10 };
40517
40883
  case "smptebars":
40518
- return { input: "smptebars=" + size + ":rate=10", seek: 0 };
40884
+ return { input: "smptebars=" + size2 + ":rate=10", seek: 0 };
40519
40885
  case "life":
40520
- return { input: "life=" + size + ":rate=10:seed=" + recipe.seed + ":ratio=0.3:mold=12:life_color=#40e0d0:death_color=#402010", seek: 1.5 };
40886
+ return { input: "life=" + size2 + ":rate=10:seed=" + recipe.seed + ":ratio=0.3:mold=12:life_color=#40e0d0:death_color=#402010", seek: 1.5 };
40521
40887
  }
40522
40888
  };
40523
40889
  makePicture2 = async (rt, recipe, out2, width, height) => {
@@ -40915,8 +41281,8 @@ var init_stage = __esm({
40915
41281
  const svg = document.createElementNS(NS, "svg");
40916
41282
  svg.setAttribute("style", "position:absolute;left:0;top:0;width:100%;height:100%;overflow:visible");
40917
41283
  root.appendChild(svg);
40918
- const shape = (tag3, attrs) => {
40919
- const el = document.createElementNS(NS, tag3);
41284
+ const shape = (tag4, attrs) => {
41285
+ const el = document.createElementNS(NS, tag4);
40920
41286
  for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);
40921
41287
  el.setAttribute("display", "none");
40922
41288
  svg.appendChild(el);
@@ -40980,11 +41346,11 @@ var init_stage = __esm({
40980
41346
  const selectorOf = (el) => {
40981
41347
  const own3 = anchor(el);
40982
41348
  if (own3 && own3 !== "body") return own3;
40983
- const tag3 = el.tagName.toLowerCase();
41349
+ const tag4 = el.tagName.toLowerCase();
40984
41350
  for (const attr2 of ["data-testid", "data-test", "aria-label", "name", "placeholder", "href"]) {
40985
41351
  const v = el.getAttribute(attr2);
40986
41352
  if (!v || v.length > 60 || /[",\\\n\]]/.test(v)) continue;
40987
- const sel = tag3 + "[" + attr2 + '="' + v + '"]';
41353
+ const sel = tag4 + "[" + attr2 + '="' + v + '"]';
40988
41354
  if (unique3(sel)) return sel;
40989
41355
  }
40990
41356
  if (unique3(part(el))) return part(el);
@@ -41066,8 +41432,8 @@ var init_stage = __esm({
41066
41432
  range2.selectNodeContents(n);
41067
41433
  const inView = Array.from(range2.getClientRects()).some((r) => r.width >= 2 && r.height >= 2 && r.right > cam.x && r.left < cam.x + cam.w && r.bottom > cam.y && r.top < cam.y + cam.h);
41068
41434
  if (!inView || !visible(el)) continue;
41069
- const size = Math.round(parseFloat(getComputedStyle(el).fontSize) * 4) / 4;
41070
- if (size > 0) counts.set(size, (counts.get(size) ?? 0) + chars);
41435
+ const size2 = Math.round(parseFloat(getComputedStyle(el).fontSize) * 4) / 4;
41436
+ if (size2 > 0) counts.set(size2, (counts.get(size2) ?? 0) + chars);
41071
41437
  }
41072
41438
  return Array.from(counts.entries());
41073
41439
  };
@@ -41075,9 +41441,9 @@ var init_stage = __esm({
41075
41441
  const el = document.activeElement;
41076
41442
  if (!el || el === document.body) return null;
41077
41443
  const cs = getComputedStyle(el);
41078
- const size = parseFloat(cs.fontSize) || 16;
41079
- const h = size * 1.15;
41080
- const w = Math.max(1, size / 14);
41444
+ const size2 = parseFloat(cs.fontSize) || 16;
41445
+ const h = size2 * 1.15;
41446
+ const w = Math.max(1, size2 / 14);
41081
41447
  const textual = el instanceof HTMLTextAreaElement || el instanceof HTMLInputElement && /^(text|search|email|url|tel|password|number|)$/.test(el.type);
41082
41448
  if (textual) {
41083
41449
  const input = el;
@@ -41424,12 +41790,12 @@ var init_steps2 = __esm({
41424
41790
  textSizes = (counts) => {
41425
41791
  const sizes = [...counts.entries()].filter(([, n]) => n > 0).sort((a, b) => a[0] - b[0]);
41426
41792
  const total2 = sizes.reduce((n, [, c]) => n + c, 0);
41427
- const first = sizes[0];
41428
- if (!first || !total2) return null;
41793
+ const first2 = sizes[0];
41794
+ if (!first2 || !total2) return null;
41429
41795
  let seen = 0;
41430
41796
  for (const [px2, n] of sizes) {
41431
41797
  seen += n;
41432
- if (seen >= total2 / 2) return { smallestPx: Math.round(first[0] * 10) / 10, medianPx: Math.round(px2 * 10) / 10 };
41798
+ if (seen >= total2 / 2) return { smallestPx: Math.round(first2[0] * 10) / 10, medianPx: Math.round(px2 * 10) / 10 };
41433
41799
  }
41434
41800
  return null;
41435
41801
  };
@@ -41519,7 +41885,7 @@ var init_director = __esm({
41519
41885
  const cdp = await createScreenshotSession(page2, o.view, o.pixels);
41520
41886
  await page2.evaluate(installStage, o.css);
41521
41887
  const { view } = o;
41522
- const size = pointerSize(view);
41888
+ const size2 = pointerSize(view);
41523
41889
  const line = lineWidth(view);
41524
41890
  let camera3 = WHOLE;
41525
41891
  let pointer;
@@ -41579,7 +41945,7 @@ var init_director = __esm({
41579
41945
  camera: camera3,
41580
41946
  sample: sampleNext || frames % SAMPLE_EVERY === 0,
41581
41947
  ...highlight ? { highlight: { ...highlight, line } } : {},
41582
- ...pointer ? { pointer: { ...pointer, dip, size } } : {},
41948
+ ...pointer ? { pointer: { ...pointer, dip, size: size2 } } : {},
41583
41949
  ...ring2 ? { ring: { ...ring2, line: Math.max(1.5, line * 0.75) } } : {}
41584
41950
  };
41585
41951
  sampleNext = false;
@@ -41757,7 +42123,7 @@ var init_director = __esm({
41757
42123
  for (let f = 0; f < DEFAULTS.pressFrames; f++) {
41758
42124
  const p = pressAt(f);
41759
42125
  dip = p.dip;
41760
- ring2 = { x: to.x, y: to.y, radius: p.ring * size, opacity: p.opacity };
42126
+ ring2 = { x: to.x, y: to.y, radius: p.ring * size2, opacity: p.opacity };
41761
42127
  yield await frame2();
41762
42128
  if (f === 1) await settleAfter(() => page2.mouse.click(to.x, to.y));
41763
42129
  }
@@ -42118,17 +42484,17 @@ var init_files = __esm({
42118
42484
  return file;
42119
42485
  }
42120
42486
  };
42121
- parseRange = (header2, size) => {
42487
+ parseRange = (header2, size2) => {
42122
42488
  const m = header2?.trim().match(/^bytes=(\d*)-(\d*)$/);
42123
42489
  if (!m || m[1] === "" && m[2] === "") return void 0;
42124
- const [first, last] = [m[1] ?? "", m[2] ?? ""];
42125
- if (first === "") {
42490
+ const [first2, last] = [m[1] ?? "", m[2] ?? ""];
42491
+ if (first2 === "") {
42126
42492
  const suffix = Number(last);
42127
- return suffix > 0 && size > 0 ? { start: Math.max(0, size - suffix), end: size - 1 } : "unsatisfiable";
42493
+ return suffix > 0 && size2 > 0 ? { start: Math.max(0, size2 - suffix), end: size2 - 1 } : "unsatisfiable";
42128
42494
  }
42129
- const start = Number(first);
42130
- const end = last === "" ? size - 1 : Math.min(Number(last), size - 1);
42131
- return start < size && start <= end ? { start, end } : "unsatisfiable";
42495
+ const start = Number(first2);
42496
+ const end = last === "" ? size2 - 1 : Math.min(Number(last), size2 - 1);
42497
+ return start < size2 && start <= end ? { start, end } : "unsatisfiable";
42132
42498
  };
42133
42499
  NO_STORE = { "cache-control": "no-store" };
42134
42500
  sendFile = async (rt, req, res, file) => {
@@ -42137,18 +42503,18 @@ var init_files = __esm({
42137
42503
  res.writeHead(404, { "content-type": "text/plain; charset=utf-8", ...NO_STORE }).end("Not found: " + rt.path.basename(file));
42138
42504
  return;
42139
42505
  }
42140
- const size = info.size;
42141
- const range2 = parseRange(req.headers.range, size);
42506
+ const size2 = info.size;
42507
+ const range2 = parseRange(req.headers.range, size2);
42142
42508
  const type = contentType(file);
42143
42509
  const headers = { "content-type": type, "accept-ranges": "bytes", ...NO_STORE, ...type.startsWith("text/html") ? { "content-security-policy": SCENE_POLICY2 } : {} };
42144
42510
  if (range2 === "unsatisfiable") {
42145
- res.writeHead(416, { ...headers, "content-range": "bytes */" + size }).end();
42511
+ res.writeHead(416, { ...headers, "content-range": "bytes */" + size2 }).end();
42146
42512
  return;
42147
42513
  }
42148
- const { start, end } = range2 ?? { start: 0, end: size - 1 };
42514
+ const { start, end } = range2 ?? { start: 0, end: size2 - 1 };
42149
42515
  const status2 = range2 ? 206 : 200;
42150
- res.writeHead(status2, { ...headers, "content-length": String(Math.max(0, end - start + 1)), ...range2 ? { "content-range": "bytes " + start + "-" + end + "/" + size } : {} });
42151
- if (req.method === "HEAD" || size === 0) {
42516
+ res.writeHead(status2, { ...headers, "content-length": String(Math.max(0, end - start + 1)), ...range2 ? { "content-range": "bytes " + start + "-" + end + "/" + size2 } : {} });
42517
+ if (req.method === "HEAD" || size2 === 0) {
42152
42518
  res.end();
42153
42519
  return;
42154
42520
  }
@@ -42269,8 +42635,8 @@ var init_extract = __esm({
42269
42635
  break;
42270
42636
  }
42271
42637
  }
42272
- const first = lv.slice(at7(t - EARLY), at7(t) + 1).findIndex((v) => v >= bed + MIN_CONTRAST_DB / 2);
42273
- const start = Math.max(0, (first >= 0 ? at7(t - EARLY) + first : at7(t)) * HOP2 - PRE);
42638
+ const first2 = lv.slice(at7(t - EARLY), at7(t) + 1).findIndex((v) => v >= bed + MIN_CONTRAST_DB / 2);
42639
+ const start = Math.max(0, (first2 >= 0 ? at7(t - EARLY) + first2 : at7(t)) * HOP2 - PRE);
42274
42640
  if (end - start < MIN_LEN) {
42275
42641
  passed.push({ at: r311(t), why: "short" });
42276
42642
  continue;
@@ -43449,11 +43815,11 @@ var init_routes = __esm({
43449
43815
  readBody2 = (req, limit = MAX_BODY) => new Promise((resolve2, reject) => {
43450
43816
  const declared = Number(req.headers["content-length"] ?? 0);
43451
43817
  const chunks = [];
43452
- let size = 0;
43818
+ let size2 = 0;
43453
43819
  let over = declared > limit;
43454
43820
  req.on("data", (c) => {
43455
- size += c.length;
43456
- if (size > limit) over = true;
43821
+ size2 += c.length;
43822
+ if (size2 > limit) over = true;
43457
43823
  if (!over) chunks.push(c);
43458
43824
  });
43459
43825
  req.on("end", () => resolve2(over ? "too-large" : Buffer.concat(chunks).toString("utf8")));
@@ -44592,7 +44958,7 @@ var init_preview = __esm({
44592
44958
  });
44593
44959
 
44594
44960
  // src/video/render/record.ts
44595
- var KEEP2, SIMILAR, HASH, ROUNDS2, SOUND2, SOUND_KINDS, PICTURE_DIRS, isString, isRender, isCompare, readRecord4, writeRecord, real, recordFile4, fileHash2, namedPictureFiles, pictureHash, shown, clock2, compareCommand, reviewRender, findRender, projectOf3, roundsOf, LOOK, roundNext, reviewCompare;
44961
+ var KEEP2, SIMILAR, HASH, ROUNDS2, roundsWord, SOUND2, SOUND_KINDS, PICTURE_DIRS, isString, isRender, isCompare, readRecord4, writeRecord, real, recordName, recordFile4, recordedRenders, fileHash2, namedPictureFiles, pictureHash, shown, clock2, compareCommand, reviewRender, findRender, projectOf3, roundsOf, LOOK, roundNext, reviewCompare;
44596
44962
  var init_record3 = __esm({
44597
44963
  "src/video/render/record.ts"() {
44598
44964
  "use strict";
@@ -44601,7 +44967,8 @@ var init_record3 = __esm({
44601
44967
  KEEP2 = 40;
44602
44968
  SIMILAR = 0.05;
44603
44969
  HASH = 16;
44604
- ROUNDS2 = { least: 2, most: 4 };
44970
+ ROUNDS2 = { least: 1, most: 3 };
44971
+ roundsWord = (n) => n + (n === 1 ? " round" : " rounds");
44605
44972
  SOUND2 = /\.(m4a|mp3|wav|aac|ogg|oga|opus|flac)$/i;
44606
44973
  SOUND_KINDS = /* @__PURE__ */ new Set(["audio", "voice", "speech"]);
44607
44974
  PICTURE_DIRS = ["assets", "scenes", "lib"];
@@ -44628,7 +44995,13 @@ var init_record3 = __esm({
44628
44995
  const abs = rt.path.resolve(rt.cwd, p);
44629
44996
  return rt.fs.realpath ? rt.fs.realpath(abs).catch(() => abs) : abs;
44630
44997
  };
44631
- recordFile4 = (rt, project) => rt.path.join(reviewsDir(rt), (rt.path.basename(project).replace(/[^\w.-]+/g, "-").slice(0, 40) || "project") + "-" + sha256(project).slice(0, 12) + ".json");
44998
+ recordName = (rt, project) => (rt.path.basename(project).replace(/[^\w.-]+/g, "-").slice(0, 40) || "project") + "-" + sha256(project).slice(0, 12) + ".json";
44999
+ recordFile4 = (rt, project) => rt.path.join(reviewsDir(rt), recordName(rt, project));
45000
+ recordedRenders = async (rt, work, projectDir) => {
45001
+ const project = await real(rt, projectDir);
45002
+ const found = await readRecord4(rt, rt.path.join(work, "reviews", recordName(rt, project)));
45003
+ return found?.project === project ? found.renders : [];
45004
+ };
44632
45005
  fileHash2 = async (rt, file) => sha256(await rt.fs.readFile(file)).slice(0, HASH);
44633
45006
  namedPictureFiles = async (rt, root) => {
44634
45007
  try {
@@ -44711,7 +45084,7 @@ var init_record3 = __esm({
44711
45084
  LOOK = "look at each worst shot at full size (its look command: popost video look \u2026 --at \u2026), fix it or write it down with its reason in the delivery notes";
44712
45085
  roundNext = (r) => {
44713
45086
  if (!r) {
44714
- return LOOK.charAt(0).toUpperCase() + LOOK.slice(1) + ", render again and compare again: at least " + ROUNDS2.least + " rounds. Rounds are counted only for a video popost video render wrote from this working directory (or with the same POPOST_VIDEO_WORK), and this one is not in its record.";
45087
+ return LOOK.charAt(0).toUpperCase() + LOOK.slice(1) + ", render again and compare again: at least " + roundsWord(ROUNDS2.least) + ". Rounds are counted only for a video popost video render wrote from this working directory (or with the same POPOST_VIDEO_WORK), and this one is not in its record.";
44715
45088
  }
44716
45089
  const again = r.again ? "Still round " + r.round + ": this render shows the project as it was when it was compared in round " + r.round + " (no file that changes the picture changed). " : "";
44717
45090
  const rounds = [...new Set(r.stillWorst.map((s) => s.since))];
@@ -44804,17 +45177,17 @@ var init_fill2 = __esm({
44804
45177
  }
44805
45178
  };
44806
45179
  cellsFrom = (width, height, channels, rowAt) => {
44807
- const size = Math.max(1, Math.round(Math.max(width, height) / CELLS));
44808
- const w = Math.ceil(width / size), h = Math.ceil(height / size);
45180
+ const size2 = Math.max(1, Math.round(Math.max(width, height) / CELLS));
45181
+ const w = Math.ceil(width / size2), h = Math.ceil(height / size2);
44809
45182
  const sum2 = new Float64Array(w * h * 3), count5 = new Float64Array(w * h);
44810
- const column = Int32Array.from({ length: width }, (_x, x2) => Math.floor(x2 / size));
45183
+ const column = Int32Array.from({ length: width }, (_x, x2) => Math.floor(x2 / size2));
44811
45184
  const offsets = channels < 3 ? [0, 0, 0] : [0, 1, 2];
44812
- const every = size >= 4 ? 2 : 1;
45185
+ const every = size2 >= 4 ? 2 : 1;
44813
45186
  for (let y = 0; y < height; y++) {
44814
45187
  const pixels = rowAt(y);
44815
45188
  if (!pixels) return void 0;
44816
45189
  if (y % every !== 0) continue;
44817
- const row = Math.floor(y / size) * w;
45190
+ const row = Math.floor(y / size2) * w;
44818
45191
  for (let x2 = 0; x2 < width; x2 += every) {
44819
45192
  const cell = row + (column[x2] ?? 0), p = x2 * channels;
44820
45193
  sum2[cell * 3] = (sum2[cell * 3] ?? 0) + (pixels[p + (offsets[0] ?? 0)] ?? 0);
@@ -44835,7 +45208,7 @@ var init_fill2 = __esm({
44835
45208
  }
44836
45209
  c.set([r / n, g / n, b / n], (y * w + x2) * 3);
44837
45210
  }
44838
- return { w, h, c, size, width, height };
45211
+ return { w, h, c, size: size2, width, height };
44839
45212
  };
44840
45213
  cellsOfPng = (png2) => {
44841
45214
  const open = openPng(png2);
@@ -44867,11 +45240,11 @@ var init_fill2 = __esm({
44867
45240
  const mean5 = [0, 1, 2].map((k) => common2.reduce((s, cell) => s + (c[cell * 3 + k] ?? 0), 0) / Math.max(1, common2.length));
44868
45241
  return edge.filter((cell) => [0, 1, 2].every((k) => Math.abs((c[cell * 3 + k] ?? 0) - (mean5[k] ?? 0)) <= SEED));
44869
45242
  };
44870
- regionCells = ({ w, h, size, width, height }, regions) => {
45243
+ regionCells = ({ w, h, size: size2, width, height }, regions) => {
44871
45244
  const marked2 = new Uint8Array(w * h);
44872
45245
  if (!regions.length) return marked2;
44873
45246
  for (let y = 0; y < h; y++) for (let x2 = 0; x2 < w; x2++) {
44874
- const px2 = Math.min(width, (x2 + 0.5) * size), py = Math.min(height, (y + 0.5) * size);
45247
+ const px2 = Math.min(width, (x2 + 0.5) * size2), py = Math.min(height, (y + 0.5) * size2);
44875
45248
  if (regions.some((r) => inRegion(r, px2, py, width, height))) marked2[y * w + x2] = 1;
44876
45249
  }
44877
45250
  return marked2;
@@ -45429,7 +45802,7 @@ var init_check8 = __esm({
45429
45802
  );
45430
45803
  };
45431
45804
  scriptFiles = (html2) => [...html2.matchAll(/<script\b[^>]*\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)].map((m) => (m[1] ?? m[2] ?? m[3] ?? "").trim()).filter((s) => s !== "" && !/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(s));
45432
- styleFiles = (html2) => [...html2.matchAll(/<link\b[^>]*>/gi)].filter(([tag3]) => /\brel\s*=\s*["']?stylesheet/i.test(tag3)).map(([tag3]) => /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(tag3)).map((m) => (m?.[1] ?? m?.[2] ?? m?.[3] ?? "").trim()).filter((s) => s !== "" && !/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(s));
45805
+ styleFiles = (html2) => [...html2.matchAll(/<link\b[^>]*>/gi)].filter(([tag4]) => /\brel\s*=\s*["']?stylesheet/i.test(tag4)).map(([tag4]) => /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(tag4)).map((m) => (m?.[1] ?? m?.[2] ?? m?.[3] ?? "").trim()).filter((s) => s !== "" && !/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(s));
45433
45806
  missingStylesheets = async (rt, projectDir, scenes) => {
45434
45807
  const root = rt.path.resolve(rt.cwd, projectDir);
45435
45808
  const roles = await libraryRoles(rt);
@@ -46309,22 +46682,22 @@ var init_examples = __esm({
46309
46682
  if (typed.trim() !== String(p.default) && !COLOUR2.test(typed.trim())) return { problem: error(at7, '"' + p.name + '" is a colour such as #ffffff, or "' + p.default + '": ' + p.what + '. Got "' + typed + '".', "Write for example --set " + p.name + "=#ffffff.") };
46310
46683
  return { value: typed.trim() };
46311
46684
  };
46312
- setExample = (ex, set2, size = [1280, 720]) => {
46685
+ setExample = (ex, set2, size2 = [1280, 720]) => {
46313
46686
  const problems2 = [];
46314
46687
  const given2 = {};
46315
- for (const pair4 of set2) {
46316
- const eq = pair4.indexOf("="), name = eq < 0 ? pair4 : pair4.slice(0, eq);
46688
+ for (const pair5 of set2) {
46689
+ const eq = pair5.indexOf("="), name = eq < 0 ? pair5 : pair5.slice(0, eq);
46317
46690
  const p = ex.params.find((x2) => x2.name === name);
46318
46691
  if (eq < 0 || !p) {
46319
- problems2.push(error("set." + name, eq < 0 ? '--set takes name=value; got "' + pair4 + '".' : 'The example "' + ex.name + '" has no parameter "' + name + '".', "Use one of its parameters, for example --set " + (ex.params[0]?.name ?? "name") + "=" + (ex.params[0]?.default ?? "value") + ".", ex.params.map((x2) => x2.name)));
46692
+ problems2.push(error("set." + name, eq < 0 ? '--set takes name=value; got "' + pair5 + '".' : 'The example "' + ex.name + '" has no parameter "' + name + '".', "Use one of its parameters, for example --set " + (ex.params[0]?.name ?? "name") + "=" + (ex.params[0]?.default ?? "value") + ".", ex.params.map((x2) => x2.name)));
46320
46693
  continue;
46321
46694
  }
46322
- const v = valueOf(p, pair4.slice(eq + 1));
46695
+ const v = valueOf(p, pair5.slice(eq + 1));
46323
46696
  if ("problem" in v) problems2.push(v.problem);
46324
46697
  else given2[name] = v.value;
46325
46698
  }
46326
46699
  const values = Object.fromEntries(ex.params.map((p) => [p.name, given2[p.name] ?? p.default]));
46327
- const html2 = ex.html.replace(VALUES, () => '"values": ' + JSON.stringify(given2)).replace(SIZE, "width: " + size[0] + "px; height: " + size[1] + "px;");
46700
+ const html2 = ex.html.replace(VALUES, () => '"values": ' + JSON.stringify(given2)).replace(SIZE, "width: " + size2[0] + "px; height: " + size2[1] + "px;");
46328
46701
  return { html: html2, values, problems: problems2 };
46329
46702
  };
46330
46703
  PREVIEW_FPS = 30;
@@ -46424,8 +46797,8 @@ var init_example = __esm({
46424
46797
  return 0;
46425
46798
  }
46426
46799
  const ex = await readExample(rt, name);
46427
- const size = sizeOf3(args.req("size"));
46428
- const set2 = setExample(ex, args.list("set"), size);
46800
+ const size2 = sizeOf3(args.req("size"));
46801
+ const set2 = setExample(ex, args.list("set"), size2);
46429
46802
  if (set2.problems.length) {
46430
46803
  printJson(rt, { ok: false, example: name, errors: set2.problems.length, problems: set2.problems, params: ex.params });
46431
46804
  return 2;
@@ -46435,7 +46808,7 @@ var init_example = __esm({
46435
46808
  const entry2 = (await readCatalogue(rt)).entries.find((e) => e.name === name);
46436
46809
  const length2 = entry2 ? entry2.seconds : (Number(set2.values.delay) || 0) + (Number(set2.values.duration) || 1) + 0.5;
46437
46810
  const libraries = librariesOf(set2.html), fonts = fontRolesOf(set2.html);
46438
- const drawn = sheet4 ? await previewScene(rt, { html: set2.html, out: userPath(rt, sheet4), seconds: args.number("seconds") ?? length2, frames: args.number("frames") ?? 12, size }) : void 0;
46811
+ const drawn = sheet4 ? await previewScene(rt, { html: set2.html, out: userPath(rt, sheet4), seconds: args.number("seconds") ?? length2, frames: args.number("frames") ?? 12, size: size2 }) : void 0;
46439
46812
  printJson(rt, {
46440
46813
  ok: true,
46441
46814
  example: name,
@@ -46885,17 +47258,17 @@ var init_see = __esm({
46885
47258
  init_pictures();
46886
47259
  init_ask();
46887
47260
  init_pictures();
46888
- ASK = (first, count5) => [
47261
+ ASK = (first2, count5) => [
46889
47262
  "These are frames of " + count5 + " shot" + (count5 === 1 ? "" : "s") + ' of one video, in order. Each shot is introduced by a line "Shot N".',
46890
47263
  "For every shot say in one English sentence what it shows: who or what, doing what, where, and how the camera moves if it does.",
46891
47264
  "Describe the same person or place with the same words in every shot (hair, clothes, setting), so that a reader knows it is the same one. Do not copy text that is written on the picture.",
46892
- 'Answer with one JSON object and nothing else: {"shots": ["...", "..."]} with exactly ' + count5 + " strings, for shots " + first + " to " + (first + count5 - 1) + " in order."
47265
+ 'Answer with one JSON object and nothing else: {"shots": ["...", "..."]} with exactly ' + count5 + " strings, for shots " + first2 + " to " + (first2 + count5 - 1) + " in order."
46893
47266
  ].join("\n");
46894
- askBatch = async (rt, o, first, shots2) => {
47267
+ askBatch = async (rt, o, first2, shots2) => {
46895
47268
  const per = o.framesPerShot ?? 3, side = o.maxSide ?? 384;
46896
- const content = [{ type: "text", text: ASK(first, shots2.length) }];
47269
+ const content = [{ type: "text", text: ASK(first2, shots2.length) }];
46897
47270
  for (const [k, s] of shots2.entries()) {
46898
- content.push({ type: "text", text: "Shot " + (first + k) + " (" + (s.end - s.start).toFixed(1) + " s):" });
47271
+ content.push({ type: "text", text: "Shot " + (first2 + k) + " (" + (s.end - s.start).toFixed(1) + " s):" });
46899
47272
  for (const t of lookTimes(s.start, s.end, per)) content.push({ type: "image_url", image_url: { url: await pictureUrl(rt, o.video, side, t) } });
46900
47273
  }
46901
47274
  const usage2 = { input: 0, output: 0 };
@@ -46912,21 +47285,21 @@ var init_see = __esm({
46912
47285
  return { usage: usage2, requests: 2, why };
46913
47286
  };
46914
47287
  seeShots = async (rt, o) => {
46915
- const size = Math.max(1, o.batch ?? 6);
47288
+ const size2 = Math.max(1, o.batch ?? 6);
46916
47289
  const notes2 = [];
46917
47290
  const problems2 = [];
46918
47291
  const usage2 = { input: 0, output: 0 };
46919
47292
  let requests = 0;
46920
- for (let first = 0; first < o.shots.length; first += size) {
46921
- const part = o.shots.slice(first, first + size);
46922
- const r = await askBatch(rt, o, first, part);
47293
+ for (let first2 = 0; first2 < o.shots.length; first2 += size2) {
47294
+ const part = o.shots.slice(first2, first2 + size2);
47295
+ const r = await askBatch(rt, o, first2, part);
46923
47296
  usage2.input += r.usage.input;
46924
47297
  usage2.output += r.usage.output;
46925
47298
  requests += r.requests;
46926
47299
  if (r.notes) notes2.push(...r.notes);
46927
47300
  else {
46928
47301
  notes2.push(...part.map(() => ""));
46929
- problems2.push(error("shots[" + first + "-" + (first + part.length - 1) + "]", "What these shots show could not be read: " + r.why + ".", "Run it again, or write their lines in the notes file by hand."));
47302
+ problems2.push(error("shots[" + first2 + "-" + (first2 + part.length - 1) + "]", "What these shots show could not be read: " + r.why + ".", "Run it again, or write their lines in the notes file by hand."));
46930
47303
  }
46931
47304
  }
46932
47305
  return { notes: notes2, problems: problems2, usage: usage2, requests };
@@ -47782,7 +48155,7 @@ var init_loop2 = __esm({
47782
48155
  const model = planModel(rt);
47783
48156
  const out2 = userPath(rt, args.string("out") ?? "fill.json");
47784
48157
  const stem = out2.replace(/\.json$/, "");
47785
- const productPictures = generate2?.images && assetsDir ? await Promise.all(generate2.images.map((p) => pictureUrl(rt, rt.path.join(assetsDir, p), 512))) : void 0;
48158
+ const productPictures2 = generate2?.images && assetsDir ? await Promise.all(generate2.images.map((p) => pictureUrl(rt, rt.path.join(assetsDir, p), 512))) : void 0;
47786
48159
  const r = await askFill(rt, {
47787
48160
  pkg,
47788
48161
  card: card2,
@@ -47795,7 +48168,7 @@ var init_loop2 = __esm({
47795
48168
  ...generate2 ? { generate: generate2 } : {},
47796
48169
  ...shotNotes ? { shotNotes } : {},
47797
48170
  ...budgets ? { budgets } : {},
47798
- ...productPictures ? { productPictures } : {}
48171
+ ...productPictures2 ? { productPictures: productPictures2 } : {}
47799
48172
  });
47800
48173
  const attemptsFile = stem + ".attempts.json";
47801
48174
  await rt.fs.writeFile(attemptsFile, jsonText({ model: r.model, first: r.first, passed: r.fill !== void 0, attempts: r.attempts }));
@@ -47859,15 +48232,15 @@ var init_loop2 = __esm({
47859
48232
  const kinds = kindRanges(speech2);
47860
48233
  const dialogue = kinds ? sourceBeats(measure3, text13, transcript2, kinds).beats.flatMap((b, i) => b.speech === "on-camera" ? [i] : []) : [];
47861
48234
  const reference2 = { measure: measure3, ...args.number("fps") !== void 0 ? { fps: args.number("fps") } : {}, ...text13 ? { text: text13 } : {}, ...transcript2 ? { transcript: transcript2 } : {}, ...kinds ? { kinds } : {}, ...dialogue.length ? { dialogue } : {} };
47862
- const first = retarget({ ...reference2, plan: given2 });
48235
+ const first2 = retarget({ ...reference2, plan: given2 });
47863
48236
  const askedVoice = await voiceAskedOf(rt, args.string("voice-asked"), outDir2);
47864
- const refusedSound = [
48237
+ const refusedSound2 = [
47865
48238
  ...voiceProblems(speech2 ? factsOfSpeech(speech2) : void 0, voiceWanted(given2, { speak: args.flag("speak") }), askedVoice),
47866
48239
  ...typeof given2.sound === "string" ? await soundProblems2(rt, outDir2, given2.sound, "sound") : []
47867
48240
  ];
47868
- if (!first.project || refusedSound.length) {
47869
- const problems2 = [...first.problems, ...refusedSound];
47870
- printJson(rt, { ok: false, error: "The plan has " + errorsIn4(problems2) + " error(s); nothing was written.", problems: problems2, notes: first.notes });
48241
+ if (!first2.project || refusedSound2.length) {
48242
+ const problems2 = [...first2.problems, ...refusedSound2];
48243
+ printJson(rt, { ok: false, error: "The plan has " + errorsIn4(problems2) + " error(s); nothing was written.", problems: problems2, notes: first2.notes });
47871
48244
  return 2;
47872
48245
  }
47873
48246
  if (args.flag("speak") && speaksHosted(rt, given2.voice)) await holdVoice(rt, outDir2, args.req("out"), args.flag("confirm"), { ...given2.voice ? { voice: given2.voice } : {}, lines: spokenLinesOf(given2, dialogue) });
@@ -47879,7 +48252,7 @@ var init_loop2 = __esm({
47879
48252
  const transcriber = commandTranscriber(rt, wallet);
47880
48253
  const language = args.string("language");
47881
48254
  const spoken = speaker ? await speakRetarget(rt, { input: { ...reference2, plan: given2 }, outDir: outDir2, speaker, ...transcriber ? { transcriber } : {}, ...language ? { language } : {}, ...args.flag("keep-length") ? { hold: true } : {}, ...args.flag("keep-pauses") ? { keepPauses: true } : {}, ...fitTempo2 ? { fitTempo: fitTempo2 } : {} }) : void 0;
47882
- const r = spoken ? spoken.result : first;
48255
+ const r = spoken ? spoken.result : first2;
47883
48256
  if (!r.project || spoken && !r.timing) {
47884
48257
  printJson(rt, { ok: false, error: "The re-flowed project could not be built.", problems: r.problems, notes: r.notes });
47885
48258
  return 2;
@@ -48893,8 +49266,8 @@ var init_place = __esm({
48893
49266
  skipped2.push({ ...c, why: "quiet" });
48894
49267
  continue;
48895
49268
  }
48896
- const takes = takesOf2(o.catalogue, c.cue, c.gain, o.seed, c.seconds, o.preferred), first = takes[0];
48897
- if (!first) {
49269
+ const takes = takesOf2(o.catalogue, c.cue, c.gain, o.seed, c.seconds, o.preferred), first2 = takes[0];
49270
+ if (!first2) {
48898
49271
  skipped2.push({ ...c, why: "no-sound", note: 'no sound of the catalogue serves "' + c.cue + '"' });
48899
49272
  continue;
48900
49273
  }
@@ -48903,12 +49276,12 @@ var init_place = __esm({
48903
49276
  skipped2.push({ ...c, why: "gap", note: "within " + (Math.abs(near3.frame - c.frame) / o.fps).toFixed(2) + " s of the " + near3.cue + " at " + (near3.frame / o.fps).toFixed(2) + " s" });
48904
49277
  continue;
48905
49278
  }
48906
- const at7 = startOf(c.frame, first, o.fps);
49279
+ const at7 = startOf(c.frame, first2, o.fps);
48907
49280
  if (at7 >= o.total) {
48908
49281
  skipped2.push({ ...c, why: "late" });
48909
49282
  continue;
48910
49283
  }
48911
- const longest = takes.reduce((a, b) => b.seconds > a.seconds ? b : a, first);
49284
+ const longest = takes.reduce((a, b) => b.seconds > a.seconds ? b : a, first2);
48912
49285
  if (c.cue !== "impact" && overlaps2(at7, spanOf3(at7, longest, o.fps), o.speech)) {
48913
49286
  skipped2.push({ ...c, why: "speech" });
48914
49287
  continue;
@@ -49639,9 +50012,9 @@ var init_project_windows = __esm({
49639
50012
  if (!(fps > 0) || !project.segments?.length || project.segments.some((s) => !(Number.isInteger(s.frames) && s.frames > 0))) return void 0;
49640
50013
  const tl = timelineOf(project);
49641
50014
  if (Math.abs(tl.total / fps - videoSeconds2) > RENDER_SLACK_S) return void 0;
49642
- const first = firstSegments(project, shots2);
49643
- if (!first) return void 0;
49644
- return first.map((k) => {
50015
+ const first2 = firstSegments(project, shots2);
50016
+ if (!first2) return void 0;
50017
+ return first2.map((k) => {
49645
50018
  if (k === void 0 || k === 0) return void 0;
49646
50019
  const t = resolveTransition(project.segments[k]?.in, tl.starts[k], fps);
49647
50020
  const spec10 = project.segments[k]?.in;
@@ -50271,7 +50644,7 @@ var init_source2 = __esm({
50271
50644
  });
50272
50645
 
50273
50646
  // src/video/replication/pairs.ts
50274
- var PAIRS_FILE, object4, text11, hash4, positive2, relativeFile, sameHash2, sameFps, seconds7, issue3, validTrim, validSide, validatePairs, checkPairs;
50647
+ var PAIRS_FILE, object4, text11, hash4, positive3, relativeFile, sameHash2, sameFps, seconds7, issue3, validTrim, validSide, validatePairs, checkPairs;
50275
50648
  var init_pairs = __esm({
50276
50649
  "src/video/replication/pairs.ts"() {
50277
50650
  "use strict";
@@ -50281,7 +50654,7 @@ var init_pairs = __esm({
50281
50654
  object4 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
50282
50655
  text11 = (v) => typeof v === "string" && v.trim() !== "";
50283
50656
  hash4 = (v) => typeof v === "string" && /^[a-f\d]{64}$/i.test(v);
50284
- positive2 = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
50657
+ positive3 = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
50285
50658
  relativeFile = (v) => text11(v) && !/^(?:\/|[a-z]:|[a-z][\w+.-]*:)/i.test(v.replace(/\\/g, "/")) && !v.replace(/\\/g, "/").split("/").includes("..");
50286
50659
  sameHash2 = (a, b) => a.toLowerCase() === b.toLowerCase();
50287
50660
  sameFps = (a, b) => Math.abs(a - b) < 0.01;
@@ -50313,7 +50686,7 @@ var init_pairs = __esm({
50313
50686
  if (!text11(value.source)) {
50314
50687
  issue3(ps, at7 + ".source", "The original URL, attachment or captured-file provenance is unknown.", true);
50315
50688
  }
50316
- if (!positive2(value.sourceFps)) {
50689
+ if (!positive3(value.sourceFps)) {
50317
50690
  issue3(ps, at7 + ".sourceFps", "Record this file's actual source FPS, not the project FPS.");
50318
50691
  valid = false;
50319
50692
  }
@@ -50367,7 +50740,7 @@ var init_pairs = __esm({
50367
50740
  issue3(ps, here + ".file", "The actual bytes and source clock have not yet been checked.", true);
50368
50741
  continue;
50369
50742
  }
50370
- if (!hash4(f.sha256) || !positive2(f.fps) || !Number.isInteger(f.frames) || f.frames <= 0) {
50743
+ if (!hash4(f.sha256) || !positive3(f.fps) || !Number.isInteger(f.frames) || f.frames <= 0) {
50371
50744
  issue3(ps, here + ".file", "Actual file facts need a SHA256, source FPS and positive whole frame count.");
50372
50745
  continue;
50373
50746
  }
@@ -50393,7 +50766,7 @@ var init_pairs = __esm({
50393
50766
  }
50394
50767
  const s = p[use2.side];
50395
50768
  if (use2.file !== s.file) issue3(ps, at7 + ".file", "This file is not the declared " + use2.side + ' of pair "' + p.id + '".');
50396
- if (!positive2(use2.sourceFps) || !sameFps(use2.sourceFps, s.sourceFps)) {
50769
+ if (!positive3(use2.sourceFps) || !sameFps(use2.sourceFps, s.sourceFps)) {
50397
50770
  issue3(ps, at7 + ".sourceFps", "This use changes the declared source FPS; convert project frames explicitly before selecting source frames.");
50398
50771
  continue;
50399
50772
  }
@@ -50467,9 +50840,9 @@ var init_review3 = __esm({
50467
50840
  };
50468
50841
  spreadFrames3 = (total2, n) => [...new Set(Array.from({ length: Math.min(n, total2) }, (_, k) => Math.floor((2 * k + 1) * total2 / (2 * Math.min(n, total2)))))];
50469
50842
  spanFrames2 = (span2, total2) => {
50470
- const last = Math.max(0, Math.min(span2[1], total2) - 1), first = Math.min(span2[0], last);
50471
- const picked2 = [.../* @__PURE__ */ new Set([first, Math.floor((first + last) / 2), last])];
50472
- if (picked2.length < 2 && total2 > 1) picked2.push(first > 0 ? first - 1 : first + 1);
50843
+ const last = Math.max(0, Math.min(span2[1], total2) - 1), first2 = Math.min(span2[0], last);
50844
+ const picked2 = [.../* @__PURE__ */ new Set([first2, Math.floor((first2 + last) / 2), last])];
50845
+ if (picked2.length < 2 && total2 > 1) picked2.push(first2 > 0 ? first2 - 1 : first2 + 1);
50473
50846
  return picked2.sort((a, b) => a - b);
50474
50847
  };
50475
50848
  same4 = (a, b) => !!a && !!b && a.toLowerCase() === b.toLowerCase();
@@ -51373,11 +51746,11 @@ var init_replication = __esm({
51373
51746
  if (c.events.some((e) => e.kind === "comparison")) {
51374
51747
  try {
51375
51748
  const value = JSON.parse(await rt.fs.readText(rt.path.join(dir, PAIRS_FILE)));
51376
- const first = await checkPairs(rt, dir, value), uses = pairUses(built.resolved, first.pairs);
51749
+ const first2 = await checkPairs(rt, dir, value), uses = pairUses(built.resolved, first2.pairs);
51377
51750
  const pairs = await checkPairs(rt, dir, value, { uses });
51378
51751
  problems2.push(...pairs.problems);
51379
- for (const pair4 of pairs.pairs) if (!uses.some((u) => u.pairId === pair4.id && u.side === "reference") || !uses.some((u) => u.pairId === pair4.id && u.side === "remake"))
51380
- problems2.push(error(PAIRS_FILE, "A declared comparison is missing one of its actual timeline sides: " + pair4.id, "Place the verified sides at matching stages using their own source FPS."));
51752
+ for (const pair5 of pairs.pairs) if (!uses.some((u) => u.pairId === pair5.id && u.side === "reference") || !uses.some((u) => u.pairId === pair5.id && u.side === "remake"))
51753
+ problems2.push(error(PAIRS_FILE, "A declared comparison is missing one of its actual timeline sides: " + pair5.id, "Place the verified sides at matching stages using their own source FPS."));
51381
51754
  if (pairs.status !== "verified") problems2.push(error(PAIRS_FILE, "The actual comparison pairing is not verified.", "Resolve source identity, relationship, trim and source-clock evidence."));
51382
51755
  } catch (e) {
51383
51756
  problems2.push(error(PAIRS_FILE, String(e), "Keep a verified actual source-pair manifest with comparison scenes."));
@@ -51415,7 +51788,7 @@ var init_replication = __esm({
51415
51788
  });
51416
51789
 
51417
51790
  // src/video/commands/speech-check.ts
51418
- var inProject2, entry, speechCheck;
51791
+ var inProject3, entry, speechCheck;
51419
51792
  var init_speech_check2 = __esm({
51420
51793
  "src/video/commands/speech-check.ts"() {
51421
51794
  "use strict";
@@ -51426,7 +51799,7 @@ var init_speech_check2 = __esm({
51426
51799
  init_speech_check();
51427
51800
  init_credits();
51428
51801
  init_shared();
51429
- inProject2 = (rt, dir, given2) => {
51802
+ inProject3 = (rt, dir, given2) => {
51430
51803
  const rel2 = rt.path.relative(dir, userPath(rt, given2)).split(rt.path.sep).join("/");
51431
51804
  if (!rel2 || rel2.startsWith("..") || rt.path.isAbsolute(rel2)) throw new VideoCommandError("--clip names a clip of the project; " + given2 + " is not in " + dir + ".");
51432
51805
  return rel2;
@@ -51455,7 +51828,7 @@ var init_speech_check2 = __esm({
51455
51828
  },
51456
51829
  async (args, rt) => {
51457
51830
  const dir = userPath(rt, args.req("project"));
51458
- const listed3 = args.list("clip").map((c) => inProject2(rt, dir, c));
51831
+ const listed3 = args.list("clip").map((c) => inProject3(rt, dir, c));
51459
51832
  const files = listed3.length ? listed3 : await speakingClips(rt, dir);
51460
51833
  if (!files.length) {
51461
51834
  printJson(rt, { ok: true, project: dir, clips: [], chargedCredits: 0, note: 'No clip of the project has a script to say (a speech receipt beside it, written when materials makes a clip with "speech").' });
@@ -51683,6 +52056,146 @@ var init_clean2 = __esm({
51683
52056
  }
51684
52057
  });
51685
52058
 
52059
+ // src/feedback/media.ts
52060
+ var MAX_PICTURES2, MAX_PICTURE_BYTES3, MAX_VIDEO_BYTES2, PARENTS_SEARCHED, EDITOR_UPLOAD, readJsonAt, asArray, str2, inProject4, tag3, productPictures, castPictures, assetsNamed, imageProjectPictures, inputCandidates, workDirs, lastRecordedRender, studioRenders, resultCandidate, sniffVideoMime2, PICTURE_TYPES2, nameOf2, take, isTaken, collectMedia;
52061
+ var init_media2 = __esm({
52062
+ "src/feedback/media.ts"() {
52063
+ "use strict";
52064
+ init_project();
52065
+ init_util();
52066
+ init_api();
52067
+ init_base();
52068
+ init_cast();
52069
+ init_sheet3();
52070
+ init_record3();
52071
+ MAX_PICTURES2 = 8;
52072
+ MAX_PICTURE_BYTES3 = 10 * 1024 * 1024;
52073
+ MAX_VIDEO_BYTES2 = 100 * 1024 * 1024;
52074
+ PARENTS_SEARCHED = 3;
52075
+ EDITOR_UPLOAD = /^assets\/import(\d{3}|-[0-9a-f]{32})\.(png|jpe?g|webp)$/i;
52076
+ readJsonAt = async (rt, file) => rt.fs.readText(file).then((text13) => JSON.parse(text13), () => void 0);
52077
+ asArray = (value) => Array.isArray(value) ? value : [];
52078
+ str2 = (value) => typeof value === "string" && value.trim() ? value : void 0;
52079
+ inProject4 = (rt, root, rel2) => rel2 && !rt.path.isAbsolute(rel2) && isInside(rt, root, rel2) ? rt.path.join(root, ...rel2.split("/")) : void 0;
52080
+ tag3 = (from, files) => files.filter((file) => file !== void 0).map((file) => ({ role: "input", from, file }));
52081
+ productPictures = async (rt, root) => {
52082
+ const sheet4 = await readJsonAt(rt, rt.path.join(root, ...PRODUCT_FILE.split("/")));
52083
+ if (!isRecord(sheet4)) return [];
52084
+ const pictures = asArray(sheet4.products).flatMap((product) => isRecord(product) ? asArray(product.pictures) : []);
52085
+ return pictures.map((p) => isRecord(p) ? inProject4(rt, root, str2(isRecord(p.original) ? p.original.file : void 0) ?? str2(p.file)) : void 0);
52086
+ };
52087
+ castPictures = async (rt, root) => {
52088
+ const cast = await readJsonAt(rt, rt.path.join(root, CAST_FILE));
52089
+ if (!isRecord(cast)) return [];
52090
+ return asArray(cast.roles).map((role) => isRecord(role) && role.identity === "user" ? inProject4(rt, root, str2(role.image)) : void 0);
52091
+ };
52092
+ assetsNamed = async (rt, root, pattern) => {
52093
+ const names = await rt.fs.readdir(rt.path.join(root, "assets")).catch(() => []);
52094
+ return names.filter((name) => pattern.test(name)).map((name) => rt.path.join(root, "assets", name));
52095
+ };
52096
+ imageProjectPictures = async (rt, root) => {
52097
+ const manifest = await readJsonAt(rt, rt.path.join(root, MANIFEST_NAME));
52098
+ if (!isRecord(manifest)) return [];
52099
+ const references = asArray(manifest.sources).map((s) => isRecord(s) && s.kind === "local-reference" ? inProject4(rt, root, str2(s.path)) : void 0);
52100
+ const uploads = asArray(manifest.assets).map((a) => isRecord(a) && EDITOR_UPLOAD.test(str2(a.path) ?? "") ? inProject4(rt, root, str2(a.path)) : void 0);
52101
+ return [...tag3("reference", references), ...tag3("upload", uploads)];
52102
+ };
52103
+ inputCandidates = async (rt, root) => {
52104
+ const all = [
52105
+ ...tag3("product", await productPictures(rt, root)),
52106
+ ...tag3("cast", await castPictures(rt, root)),
52107
+ ...tag3("anchor", await assetsNamed(rt, root, /^anchor-image\.(png|jpe?g|webp)$/i)),
52108
+ ...tag3("character", await assetsNamed(rt, root, /^character-[^/]+\.(png|jpe?g|webp)$/i)),
52109
+ ...await imageProjectPictures(rt, root)
52110
+ ];
52111
+ return all.filter((c, i) => all.findIndex((other) => other.file === c.file) === i);
52112
+ };
52113
+ workDirs = (rt, root) => {
52114
+ const above = [root];
52115
+ for (let i = 0; i < PARENTS_SEARCHED; i++) above.push(rt.path.dirname(above.at(-1)));
52116
+ const given2 = rt.env.POPOST_VIDEO_WORK?.trim();
52117
+ const dirs = [...given2 ? [rt.path.resolve(rt.cwd, given2)] : [], rt.path.join(rt.cwd, ".popost", "video"), ...above.map((dir) => rt.path.join(dir, ".popost", "video"))];
52118
+ return [...new Set(dirs)];
52119
+ };
52120
+ lastRecordedRender = async (rt, root) => {
52121
+ const found = [];
52122
+ for (const work of workDirs(rt, root))
52123
+ for (const entry2 of [...await recordedRenders(rt, work, root).catch(() => [])].reverse())
52124
+ if ((await rt.fs.stat(entry2.out))?.isFile) {
52125
+ found.push({ file: entry2.out, from: "render", at: Date.parse(entry2.at) || 0 });
52126
+ break;
52127
+ }
52128
+ return found.sort((a, b) => b.at - a.at)[0];
52129
+ };
52130
+ studioRenders = async (rt, root) => {
52131
+ const last = await readJsonAt(rt, rt.path.join(root, ".studio", "last-export.json"));
52132
+ const exported = isRecord(last) && last.state === "done" ? str2(last.file) : void 0;
52133
+ const finished = isRecord(last) && typeof last.finished === "number" ? last.finished : void 0;
52134
+ const dated = await Promise.all(
52135
+ [
52136
+ { file: exported, at: finished },
52137
+ { file: rt.path.join(root, "out.mp4"), at: void 0 }
52138
+ ].map(async ({ file, at: at7 }) => {
52139
+ const stat = file && isInside(rt, root, file) ? await rt.fs.stat(file) : null;
52140
+ return file && stat?.isFile ? { file, from: "studio-export", at: at7 ?? stat.mtimeMs } : void 0;
52141
+ })
52142
+ );
52143
+ return dated.filter((d) => d !== void 0);
52144
+ };
52145
+ resultCandidate = async (rt, root) => {
52146
+ const all = [await lastRecordedRender(rt, root), ...await studioRenders(rt, root)].filter((d) => d !== void 0);
52147
+ const newest = all.sort((a, b) => b.at - a.at)[0];
52148
+ return newest ? { role: "result", from: newest.from, file: newest.file } : void 0;
52149
+ };
52150
+ sniffVideoMime2 = (head) => {
52151
+ if (head.length < 12) return null;
52152
+ const ascii5 = (from, to) => String.fromCharCode(...head.subarray(from, to));
52153
+ const box2 = ascii5(4, 8);
52154
+ if (box2 === "ftyp") return ascii5(8, 12) === "qt " ? "video/quicktime" : "video/mp4";
52155
+ return ["moov", "wide", "mdat", "free", "skip", "pnot"].includes(box2) ? "video/quicktime" : null;
52156
+ };
52157
+ PICTURE_TYPES2 = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp"]);
52158
+ nameOf2 = (rt, file) => {
52159
+ const base = rt.path.basename(file).replace(new RegExp("\\p{Cc}", "gu"), "").replace(/[\\/]/g, "_").trim() || "file";
52160
+ let out2 = "";
52161
+ for (const ch of base) {
52162
+ if (out2.length + ch.length > 200) break;
52163
+ out2 += ch;
52164
+ }
52165
+ return out2;
52166
+ };
52167
+ take = async (rt, c, video) => {
52168
+ const stat = await rt.fs.stat(c.file);
52169
+ if (!stat?.isFile) return { ...c, reason: "unreadable" };
52170
+ if (stat.size > (video ? MAX_VIDEO_BYTES2 : MAX_PICTURE_BYTES3)) return { ...c, reason: "too-large", bytes: stat.size };
52171
+ const data = await rt.fs.readFile(c.file).catch(() => void 0);
52172
+ if (!data?.length) return { ...c, reason: "unreadable" };
52173
+ const type = video ? sniffVideoMime2(data.subarray(0, 16)) : sniffImageMime(data.subarray(0, 16));
52174
+ if (!type || !video && !PICTURE_TYPES2.has(type)) return { ...c, reason: "unsupported-type", bytes: data.length };
52175
+ return { ...c, name: nameOf2(rt, c.file), contentType: type, bytes: data.length, sha256: sha256(data), data };
52176
+ };
52177
+ isTaken = (item2) => "data" in item2;
52178
+ collectMedia = async (rt, root) => {
52179
+ const files = [];
52180
+ const skipped2 = [];
52181
+ for (const c of await inputCandidates(rt, root)) {
52182
+ if (files.length >= MAX_PICTURES2) {
52183
+ skipped2.push({ ...c, reason: "over-limit" });
52184
+ continue;
52185
+ }
52186
+ const item2 = await take(rt, c, false);
52187
+ if (!isTaken(item2)) skipped2.push(item2);
52188
+ else if (!files.some((f) => f.sha256 === item2.sha256)) files.push(item2);
52189
+ }
52190
+ const result = await resultCandidate(rt, root);
52191
+ const video = result ? await take(rt, result, true) : void 0;
52192
+ if (video && isTaken(video)) files.push(video);
52193
+ else if (video) skipped2.push(video);
52194
+ return { files, skipped: skipped2 };
52195
+ };
52196
+ }
52197
+ });
52198
+
51686
52199
  // src/feedback/project-files.ts
51687
52200
  var MAX_DEPTH2, MAX_LISTED, DOCUMENT_MAX_BYTES, DOCUMENTS_MAX_BYTES, TEXT_EXTENSIONS, SKIPPED_DIRS, PRIVATE_NAME, extensionOf2, listFiles, isDocument, collectProjectFiles;
51688
52201
  var init_project_files = __esm({
@@ -51740,6 +52253,103 @@ var init_project_files = __esm({
51740
52253
  }
51741
52254
  });
51742
52255
 
52256
+ // src/feedback/request.ts
52257
+ var REQUEST_MESSAGES, REQUEST_MAX_CHARS, SEPARATOR, MAX_LINES_SCANNED, CLAUDE_NOT_WORDS, CODEX_NOT_WORDS, REMINDER, textParts, slashCommand, claudeWords, codexEvent, codexMessage, scanLines, firstWords2, cutText, wordsOf2, extractRequest;
52258
+ var init_request = __esm({
52259
+ "src/feedback/request.ts"() {
52260
+ "use strict";
52261
+ init_base();
52262
+ REQUEST_MESSAGES = 3;
52263
+ REQUEST_MAX_CHARS = 4e3;
52264
+ SEPARATOR = "\n\n---\n\n";
52265
+ MAX_LINES_SCANNED = 5e3;
52266
+ CLAUDE_NOT_WORDS = /^(<local-command-|<bash-(input|stdout|stderr)>|Caveat: |\[Request interrupted)/;
52267
+ CODEX_NOT_WORDS = /^(<environment_context>|<user_instructions>|<INSTRUCTIONS>|# AGENTS\.md instructions|<user_shell_command>)/;
52268
+ REMINDER = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
52269
+ textParts = (content, kinds) => {
52270
+ if (typeof content === "string") return content;
52271
+ if (!Array.isArray(content)) return void 0;
52272
+ if (content.some((part) => isRecord(part) && part.type === "tool_result")) return void 0;
52273
+ const texts = content.filter((part) => isRecord(part) && kinds.includes(String(part.type)) && typeof part.text === "string");
52274
+ return texts.map((part) => part.text).join("\n");
52275
+ };
52276
+ slashCommand = (text13) => {
52277
+ if (!text13.startsWith("<command-")) return text13;
52278
+ const name = /<command-name>([\s\S]*?)<\/command-name>/.exec(text13)?.[1]?.trim();
52279
+ const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(text13)?.[1]?.trim();
52280
+ return name && args ? `${name} ${args}` : void 0;
52281
+ };
52282
+ claudeWords = (line) => {
52283
+ if (line.type !== "user" || line.isMeta === true || line.isSidechain === true || line.isCompactSummary === true) return void 0;
52284
+ const message2 = line.message;
52285
+ if (!isRecord(message2) || message2.role !== void 0 && message2.role !== "user") return void 0;
52286
+ const text13 = textParts(message2.content, ["text"])?.replace(REMINDER, "").trim();
52287
+ if (!text13 || CLAUDE_NOT_WORDS.test(text13)) return void 0;
52288
+ return slashCommand(text13);
52289
+ };
52290
+ codexEvent = (line) => {
52291
+ const payload2 = line.payload;
52292
+ if (line.type !== "event_msg" || !isRecord(payload2) || payload2.type !== "user_message") return void 0;
52293
+ return typeof payload2.message === "string" ? payload2.message.trim() || void 0 : void 0;
52294
+ };
52295
+ codexMessage = (line) => {
52296
+ const item2 = line.type === "response_item" && isRecord(line.payload) ? line.payload : line;
52297
+ if (item2.type !== "message" || item2.role !== "user") return void 0;
52298
+ const text13 = textParts(item2.content, ["input_text", "text"])?.trim();
52299
+ return text13 && !CODEX_NOT_WORDS.test(text13) ? text13 : void 0;
52300
+ };
52301
+ scanLines = (jsonl, visit) => {
52302
+ let start = 0;
52303
+ for (let n = 0; n < MAX_LINES_SCANNED && start < jsonl.length; n++) {
52304
+ const end = jsonl.indexOf("\n", start);
52305
+ const raw = jsonl.slice(start, end < 0 ? jsonl.length : end);
52306
+ start = end < 0 ? jsonl.length : end + 1;
52307
+ let value;
52308
+ try {
52309
+ value = raw.trim() ? JSON.parse(raw) : void 0;
52310
+ } catch {
52311
+ value = void 0;
52312
+ }
52313
+ if (isRecord(value) && visit(value)) return;
52314
+ }
52315
+ };
52316
+ firstWords2 = (jsonl, pick) => {
52317
+ const found = [];
52318
+ scanLines(jsonl, (line) => {
52319
+ const words = pick(line);
52320
+ if (words) found.push(words);
52321
+ return found.length >= REQUEST_MESSAGES;
52322
+ });
52323
+ return found;
52324
+ };
52325
+ cutText = (text13, max) => {
52326
+ if (text13.length <= max) return text13;
52327
+ let out2 = "";
52328
+ for (const ch of text13) {
52329
+ if (out2.length + ch.length > max - 1) break;
52330
+ out2 += ch;
52331
+ }
52332
+ return out2.trimEnd() + "\u2026";
52333
+ };
52334
+ wordsOf2 = (jsonl, format) => {
52335
+ const claude = () => firstWords2(jsonl, claudeWords);
52336
+ const codex = () => {
52337
+ const events = firstWords2(jsonl, codexEvent);
52338
+ return events.length ? events : firstWords2(jsonl, codexMessage);
52339
+ };
52340
+ if (format === "claude-code-jsonl") return claude();
52341
+ if (format === "codex-jsonl") return codex();
52342
+ const either = claude();
52343
+ return either.length ? either : codex();
52344
+ };
52345
+ extractRequest = (cleanedText, format) => {
52346
+ if (format === "text") return void 0;
52347
+ const words = wordsOf2(cleanedText, format);
52348
+ return words.length ? cutText(words.join(SEPARATOR), REQUEST_MAX_CHARS) : void 0;
52349
+ };
52350
+ }
52351
+ });
52352
+
51743
52353
  // src/feedback/transcript.ts
51744
52354
  var TRANSCRIPT_MAX_BYTES, TRANSCRIPT_READ_MAX_BYTES, SESSION_ID, CODEX_DAYS_SEARCHED, FeedbackError, envValue2, detectAgent, isFileAt, listDir, moved, findClaudeCode, newestFirst, codexRollout, findCodex, locate3, tail3, missing3, readTranscript;
51745
52355
  var init_transcript = __esm({
@@ -51748,6 +52358,7 @@ var init_transcript = __esm({
51748
52358
  init_agents();
51749
52359
  init_i18n();
51750
52360
  init_clean2();
52361
+ init_request();
51751
52362
  TRANSCRIPT_MAX_BYTES = 40 * 1024 * 1024;
51752
52363
  TRANSCRIPT_READ_MAX_BYTES = 256 * 1024 * 1024;
51753
52364
  SESSION_ID = /^[A-Za-z0-9_-]{1,200}$/;
@@ -51842,14 +52453,16 @@ var init_transcript = __esm({
51842
52453
  const kept3 = tail3(bytes, TRANSCRIPT_MAX_BYTES);
51843
52454
  const text13 = kept3.cut ? new TextDecoder().decode(kept3.data) : cleaned.text;
51844
52455
  const lines2 = kept3.cut ? text13.split("\n").filter((line) => line.trim() !== "").length : cleaned.lines;
51845
- return { status: "found", path: found.path, format: found.format ?? "jsonl", text: text13, lines: lines2, bytes: kept3.data.length, truncated: raw.cut || kept3.cut };
52456
+ const format = found.format ?? "jsonl";
52457
+ const request = extractRequest(cleaned.text, format);
52458
+ return { status: "found", path: found.path, format, text: text13, lines: lines2, bytes: kept3.data.length, truncated: raw.cut || kept3.cut, ...request ? { request } : {} };
51846
52459
  };
51847
52460
  }
51848
52461
  });
51849
52462
 
51850
52463
  // src/feedback/bundle.ts
51851
52464
  import { gzipSync } from "fflate";
51852
- var FORMAT5, MESSAGE_MAX_CHARS, MAX_BUNDLE_BYTES, tildify, projectDirOf, cleanMessage, documentOf, buildFeedback;
52465
+ var FORMAT5, MESSAGE_MAX_CHARS, MAX_BUNDLE_BYTES, tildify, projectDirOf, cleanMessage, mediaPath, mediaList, documentOf, buildFeedback;
51853
52466
  var init_bundle = __esm({
51854
52467
  "src/feedback/bundle.ts"() {
51855
52468
  "use strict";
@@ -51858,6 +52471,7 @@ var init_bundle = __esm({
51858
52471
  init_task();
51859
52472
  init_version();
51860
52473
  init_clean2();
52474
+ init_media2();
51861
52475
  init_project_files();
51862
52476
  init_transcript();
51863
52477
  FORMAT5 = "popost-feedback/1";
@@ -51881,10 +52495,16 @@ var init_bundle = __esm({
51881
52495
  throw new FeedbackError("MESSAGE_TOO_LONG", msg(`--message is longer than ${MESSAGE_MAX_CHARS} characters; shorten it`, `--message \u8D85\u8FC7 ${MESSAGE_MAX_CHARS} \u4E2A\u5B57\u7B26\uFF0C\u8BF7\u7F29\u77ED`));
51882
52496
  return clean2(message2);
51883
52497
  };
52498
+ mediaPath = (rt, projectDir, file) => {
52499
+ const rel2 = projectDir ? rt.path.relative(projectDir, file) : "";
52500
+ return rel2 && !rel2.startsWith("..") && !rt.path.isAbsolute(rel2) ? rel2.split(rt.path.sep).join("/") : tildify(rt, file);
52501
+ };
52502
+ mediaList = (rt, built) => (built.media?.files ?? []).map((f) => ({ role: f.role, from: f.from, path: mediaPath(rt, built.projectDir, f.file), name: f.name, contentType: f.contentType, bytes: f.bytes, sha256: f.sha256 }));
51884
52503
  documentOf = (rt, built, createdAt) => ({
51885
52504
  format: FORMAT5,
51886
52505
  createdAt,
51887
52506
  message: built.message,
52507
+ ...built.transcript.request ? { request: built.transcript.request } : {},
51888
52508
  client: { version: VERSION, platform: rt.platform ?? "unknown", ...rt.arch ? { arch: rt.arch } : {}, ...rt.nodeVersion ? { node: rt.nodeVersion } : {}, lang: currentLang() },
51889
52509
  agent: { id: built.agent.id, ...built.agent.sessionId ? { sessionId: built.agent.sessionId } : {}, ...built.transcript.path ? { transcriptPath: tildify(rt, built.transcript.path) } : {} },
51890
52510
  task: {
@@ -51903,7 +52523,8 @@ var init_bundle = __esm({
51903
52523
  truncated: built.transcript.truncated,
51904
52524
  omittedImages: built.transcript.omittedImages
51905
52525
  },
51906
- redactions: built.stats.redactions
52526
+ redactions: built.stats.redactions,
52527
+ media: mediaList(rt, built)
51907
52528
  });
51908
52529
  buildFeedback = async (rt, options) => {
51909
52530
  const cleaner = createCleaner({ homeDir: rt.homeDir, secrets: environmentSecrets(rt.env) });
@@ -51915,7 +52536,8 @@ var init_bundle = __esm({
51915
52536
  const projectDir = await projectDirOf(rt, options.dir);
51916
52537
  const task = projectDir ? await projectTask(rt, { dir: projectDir, kind: "found" }, false).catch(() => void 0) : void 0;
51917
52538
  const project = projectDir ? await collectProjectFiles(rt, projectDir, cleaner) : void 0;
51918
- const parts = { message: message2, agent, transcript: { ...transcript2, omittedImages: transcriptImages }, projectDir, task, project, stats: { ...cleaner.stats } };
52539
+ const media = projectDir && !options.noMedia ? await collectMedia(rt, projectDir) : void 0;
52540
+ const parts = { message: message2, agent, transcript: { ...transcript2, omittedImages: transcriptImages }, projectDir, task, project, media, stats: { ...cleaner.stats } };
51919
52541
  const json4 = JSON.stringify(documentOf(rt, parts, rt.now().toISOString()));
51920
52542
  const gzip = gzipSync(new TextEncoder().encode(json4), { level: 6, mtime: 0 });
51921
52543
  return { ...parts, gzip, sha256: sha256(gzip) };
@@ -51924,7 +52546,7 @@ var init_bundle = __esm({
51924
52546
  });
51925
52547
 
51926
52548
  // src/feedback/upload.ts
51927
- var RATE_RETRIES2, MAX_WAIT_SEC2, UPLOAD_ATTEMPTS, AGENT_ID, rateAware2, reservation, badAnswer, ticketOf, uploadMissing, attempt2, sendFeedback;
52549
+ var RATE_RETRIES2, MAX_WAIT_SEC2, UPLOAD_ATTEMPTS, AGENT_ID, rateAware2, mediaOf2, reservation, badAnswer, mediaUploadsOf, ticketOf, MEDIA_STATES, mediaStatesOf, sendMedia, uploadMissing, attempt2, sendFeedback;
51928
52550
  var init_upload = __esm({
51929
52551
  "src/feedback/upload.ts"() {
51930
52552
  "use strict";
@@ -51949,6 +52571,7 @@ var init_upload = __esm({
51949
52571
  }
51950
52572
  }
51951
52573
  };
52574
+ mediaOf2 = (built) => built.media?.files ?? [];
51952
52575
  reservation = (rt, built, operationKey) => {
51953
52576
  const title = cleanTitle(built.task?.title);
51954
52577
  const task = {
@@ -51972,28 +52595,48 @@ var init_upload = __esm({
51972
52595
  redactions: built.stats.redactions,
51973
52596
  omittedImages: built.stats.omittedImages,
51974
52597
  truncated: built.transcript.truncated
51975
- }
52598
+ },
52599
+ ...built.transcript.request ? { request: built.transcript.request } : {},
52600
+ ...mediaOf2(built).length ? { media: mediaOf2(built).map((f) => ({ role: f.role, name: f.name, contentType: f.contentType, sizeBytes: f.bytes, sha256: f.sha256 })) } : {}
51976
52601
  };
51977
52602
  };
51978
52603
  badAnswer = (what) => new PopostApiError(msg(`popost.ai answered ${what} in an unexpected format`, `popost.ai \u5BF9 ${what} \u7684\u8FD4\u56DE\u683C\u5F0F\u4E0D\u7B26`), { code: "BAD_RESPONSE" });
52604
+ mediaUploadsOf = (value) => new Map(
52605
+ (Array.isArray(value) ? value : []).filter((u) => isRecord(u) && Number.isInteger(u.index) && typeof u.uploadUrl === "string").map((u) => [u.index, u.uploadUrl])
52606
+ );
51979
52607
  ticketOf = (data) => {
51980
52608
  if (!isRecord(data) || typeof data.id !== "string" || !/^[A-Za-z0-9-]{1,64}$/.test(data.id) || data.uploadUrl !== null && typeof data.uploadUrl !== "string")
51981
52609
  throw badAnswer("POST /feedback");
51982
52610
  const reference2 = typeof data.reference === "string" && data.reference ? data.reference : data.id.slice(0, 8);
51983
- return { id: data.id, reference: reference2, uploadUrl: data.uploadUrl, state: String(data.state ?? "") };
52611
+ return { id: data.id, reference: reference2, uploadUrl: data.uploadUrl, state: String(data.state ?? ""), mediaUploads: mediaUploadsOf(data.mediaUploads) };
52612
+ };
52613
+ MEDIA_STATES = ["received", "missing", "invalid"];
52614
+ mediaStatesOf = (built, answer3) => {
52615
+ const states = new Map(
52616
+ (Array.isArray(answer3) ? answer3 : []).filter((m) => isRecord(m) && Number.isInteger(m.index) && MEDIA_STATES.includes(String(m.state))).map((m) => [m.index, m.state])
52617
+ );
52618
+ return mediaOf2(built).map((file, index) => ({ file, state: states.get(index) ?? "missing" }));
52619
+ };
52620
+ sendMedia = async (client2, built, ticket2) => {
52621
+ for (const [index, file] of mediaOf2(built).entries()) {
52622
+ const url = ticket2.mediaUploads.get(index);
52623
+ if (url) await client2.putSigned(url, file.data, file.contentType, file.name, "").catch(() => void 0);
52624
+ }
51984
52625
  };
51985
52626
  uploadMissing = (error2) => error2 instanceof PopostApiError && (error2.code === "UPLOAD_FAILED" || error2.code === "INVALID_REQUEST" && Array.isArray(error2.details.issues) && error2.details.issues.some((issue4) => isRecord(issue4) && issue4.path === "upload"));
51986
52627
  attempt2 = async (rt, client2, built, body) => {
51987
52628
  const ticket2 = ticketOf(await rateAware2(rt, () => client2.request("POST", "/feedback", { body })));
51988
- if (ticket2.state === "received" && !ticket2.uploadUrl) return { id: ticket2.id, reference: ticket2.reference, receivedAt: rt.now().toISOString() };
52629
+ if (ticket2.state === "received" && !ticket2.uploadUrl) return { id: ticket2.id, reference: ticket2.reference, receivedAt: rt.now().toISOString(), media: [] };
51989
52630
  if (ticket2.uploadUrl)
51990
52631
  await client2.putSigned(ticket2.uploadUrl, built.gzip, "application/gzip", "feedback.json.gz", msg("run the same popost feedback command again", "\u8BF7\u518D\u6B21\u8FD0\u884C\u540C\u4E00\u6761 popost feedback \u547D\u4EE4"));
52632
+ await sendMedia(client2, built, ticket2);
51991
52633
  const done2 = await rateAware2(rt, () => client2.request("POST", `/feedback/${encodeURIComponent(ticket2.id)}/complete`, { body: {} }));
51992
52634
  if (!isRecord(done2) || done2.id !== ticket2.id) throw badAnswer(`POST /feedback/${ticket2.id}/complete`);
51993
52635
  return {
51994
52636
  id: ticket2.id,
51995
52637
  reference: typeof done2.reference === "string" && done2.reference ? done2.reference : ticket2.reference,
51996
- receivedAt: typeof done2.receivedAt === "string" ? done2.receivedAt : rt.now().toISOString()
52638
+ receivedAt: typeof done2.receivedAt === "string" ? done2.receivedAt : rt.now().toISOString(),
52639
+ media: mediaStatesOf(built, done2.media)
51997
52640
  };
51998
52641
  };
51999
52642
  sendFeedback = async (rt, client2, built) => {
@@ -52014,13 +52657,14 @@ var feedback_exports = {};
52014
52657
  __export(feedback_exports, {
52015
52658
  main: () => main22
52016
52659
  });
52017
- var spec9, quote15, wouldSend, tooLarge, report3, run5, main22;
52660
+ var spec9, quote15, MB, skipWhy, mediaToSend, wouldSend, tooLarge, report3, run5, main22;
52018
52661
  var init_feedback = __esm({
52019
52662
  "src/commands/feedback.ts"() {
52020
52663
  "use strict";
52021
52664
  init_args();
52022
52665
  init_util();
52023
52666
  init_bundle();
52667
+ init_media2();
52024
52668
  init_transcript();
52025
52669
  init_upload();
52026
52670
  init_i18n();
@@ -52029,8 +52673,8 @@ var init_feedback = __esm({
52029
52673
  spec9 = () => ({
52030
52674
  prog: "popost feedback",
52031
52675
  description: msg(
52032
- "Report a problem to the popost team, only when the user asks for it (free). Without --confirm nothing is sent: it prints what would go, which is the message, this Agent session's transcript with secrets and pictures removed, and the project's file list with its small text files. Show that to the user and add --confirm only after they agree.",
52033
- "\u5411 popost \u56E2\u961F\u53CD\u9988\u95EE\u9898\uFF0C\u4EC5\u5728\u7528\u6237\u8981\u6C42\u65F6\u4F7F\u7528\uFF08\u514D\u8D39\uFF09\u3002\u4E0D\u52A0 --confirm \u65F6\u4E0D\u53D1\u9001\u4EFB\u4F55\u5185\u5BB9\uFF1A\u53EA\u5217\u51FA\u5C06\u8981\u53D1\u9001\u7684\u5185\u5BB9\uFF0C\u5373\u95EE\u9898\u63CF\u8FF0\u3001\u53BB\u6389\u5BC6\u94A5\u548C\u56FE\u7247\u540E\u7684\u5F53\u524D Agent \u4F1A\u8BDD\u8BB0\u5F55\u3001\u5DE5\u7A0B\u7684\u6587\u4EF6\u5217\u8868\u53CA\u5176\u4E2D\u7684\u5C0F\u6587\u672C\u6587\u4EF6\u3002\u628A\u8FD9\u4E9B\u7ED9\u7528\u6237\u770B\uFF0C\u7528\u6237\u540C\u610F\u540E\u518D\u52A0 --confirm\u3002"
52676
+ "Report a problem to the popost team, only when the user asks for it (free). Without --confirm nothing is sent: it prints what would go, which is the message, the user's first words of this session, this Agent session's transcript with secrets and pictures removed, the project's file list with its small text files, and the pictures the user gave for the task with the video it produced (--no-media leaves those out). Show that to the user and add --confirm only after they agree.",
52677
+ "\u5411 popost \u56E2\u961F\u53CD\u9988\u95EE\u9898\uFF0C\u4EC5\u5728\u7528\u6237\u8981\u6C42\u65F6\u4F7F\u7528\uFF08\u514D\u8D39\uFF09\u3002\u4E0D\u52A0 --confirm \u65F6\u4E0D\u53D1\u9001\u4EFB\u4F55\u5185\u5BB9\uFF1A\u53EA\u5217\u51FA\u5C06\u8981\u53D1\u9001\u7684\u5185\u5BB9\uFF0C\u5373\u95EE\u9898\u63CF\u8FF0\u3001\u7528\u6237\u5728\u672C\u6B21\u4F1A\u8BDD\u5F00\u5934\u8BF4\u7684\u8BDD\u3001\u53BB\u6389\u5BC6\u94A5\u548C\u56FE\u7247\u540E\u7684\u5F53\u524D Agent \u4F1A\u8BDD\u8BB0\u5F55\u3001\u5DE5\u7A0B\u7684\u6587\u4EF6\u5217\u8868\u53CA\u5176\u4E2D\u7684\u5C0F\u6587\u672C\u6587\u4EF6\uFF0C\u4EE5\u53CA\u7528\u6237\u4E3A\u8FD9\u4E2A\u4EFB\u52A1\u63D0\u4F9B\u7684\u56FE\u7247\u548C\u4EFB\u52A1\u505A\u51FA\u7684\u89C6\u9891\uFF08\u52A0 --no-media \u4E0D\u53D1\u9001\u56FE\u7247\u548C\u89C6\u9891\uFF09\u3002\u628A\u8FD9\u4E9B\u7ED9\u7528\u6237\u770B\uFF0C\u7528\u6237\u540C\u610F\u540E\u518D\u52A0 --confirm\u3002"
52034
52678
  ),
52035
52679
  options: [
52036
52680
  { flag: "--message", required: true, metavar: "TEXT", help: msg("what went wrong, in the user's own words (at most 4000 characters)", "\u51FA\u4E86\u4EC0\u4E48\u95EE\u9898\uFF0C\u7528\u7528\u6237\u81EA\u5DF1\u7684\u8BDD\uFF08\u6700\u591A 4000 \u4E2A\u5B57\u7B26\uFF09") },
@@ -52038,16 +52682,37 @@ var init_feedback = __esm({
52038
52682
  { flag: "--transcript", metavar: "FILE", help: msg("the Agent session's transcript file, when popost cannot find it by itself", "Agent \u4F1A\u8BDD\u8BB0\u5F55\u6587\u4EF6\uFF0Cpopost \u81EA\u5DF1\u627E\u4E0D\u5230\u65F6\u6307\u5B9A") },
52039
52683
  { flag: "--no-transcript", kind: "flag", help: msg("send no session transcript", "\u4E0D\u53D1\u9001\u4F1A\u8BDD\u8BB0\u5F55") },
52040
52684
  { flag: "--session", metavar: "ID", help: msg("the Agent session id, when the Agent does not set it", "Agent \u4F1A\u8BDD id\uFF0CAgent \u6CA1\u6709\u63D0\u4F9B\u65F6\u6307\u5B9A") },
52685
+ { flag: "--no-media", kind: "flag", help: msg("send none of the pictures the user gave and not the task's video", "\u4E0D\u53D1\u9001\u7528\u6237\u63D0\u4F9B\u7684\u56FE\u7247\u548C\u4EFB\u52A1\u7684\u89C6\u9891") },
52041
52686
  { flag: "--out", metavar: "FILE", help: msg("also write the report (gzip JSON) to this file", "\u540C\u65F6\u628A\u62A5\u544A\uFF08gzip \u538B\u7F29\u7684 JSON\uFF09\u5199\u5230\u8FD9\u4E2A\u6587\u4EF6") },
52042
52687
  { flag: "--confirm", kind: "flag", help: msg("send it; only after the user has seen the dry run and agreed", "\u53D1\u9001\uFF1B\u4EC5\u5728\u7528\u6237\u770B\u8FC7\u8BD5\u8FD0\u884C\u7ED3\u679C\u5E76\u540C\u610F\u4E4B\u540E") }
52043
52688
  ]
52044
52689
  });
52045
52690
  quote15 = (word2) => /^[A-Za-z0-9_./:=,@+-]+$/.test(word2) ? word2 : `'${word2.replace(/'/g, `'\\''`)}'`;
52046
- wouldSend = (rt, built) => {
52691
+ MB = 1024 * 1024;
52692
+ skipWhy = (item2) => {
52693
+ const video = item2.role === "result";
52694
+ if (item2.reason === "too-large")
52695
+ return video ? msg(`larger than ${MAX_VIDEO_BYTES2 / MB} MB`, `\u8D85\u8FC7 ${MAX_VIDEO_BYTES2 / MB} MB`) : msg(`larger than ${MAX_PICTURE_BYTES3 / MB} MB`, `\u8D85\u8FC7 ${MAX_PICTURE_BYTES3 / MB} MB`);
52696
+ if (item2.reason === "over-limit") return msg(`only the first ${MAX_PICTURES2} pictures go`, `\u6700\u591A\u53D1\u9001\u524D ${MAX_PICTURES2} \u5F20\u56FE\u7247`);
52697
+ if (item2.reason === "unsupported-type")
52698
+ return video ? msg("not an MP4 or QuickTime video", "\u4E0D\u662F MP4 \u6216 QuickTime \u89C6\u9891") : msg("not a JPEG, PNG or WebP picture", "\u4E0D\u662F JPEG\u3001PNG \u6216 WebP \u56FE\u7247");
52699
+ return msg("cannot be read", "\u65E0\u6CD5\u8BFB\u53D6");
52700
+ };
52701
+ mediaToSend = (rt, built, noMedia) => {
52702
+ if (noMedia) return { off: true, send: [], skipped: [] };
52703
+ const files = built.media?.files ?? [];
52704
+ return {
52705
+ send: files.map((f) => ({ role: f.role, from: f.from, path: mediaPath(rt, built.projectDir, f.file), contentType: f.contentType, bytes: f.bytes })),
52706
+ skipped: (built.media?.skipped ?? []).map((f) => ({ role: f.role, from: f.from, path: mediaPath(rt, built.projectDir, f.file), reason: f.reason, why: skipWhy(f), ...f.bytes !== void 0 ? { bytes: f.bytes } : {} })),
52707
+ bytes: files.reduce((sum2, f) => sum2 + f.bytes, 0)
52708
+ };
52709
+ };
52710
+ wouldSend = (rt, built, noMedia) => {
52047
52711
  const { transcript: transcript2, project } = built;
52048
52712
  const sent = project ? project.files.filter((file) => file.path in project.documents) : [];
52049
52713
  return {
52050
52714
  message: built.message,
52715
+ request: transcript2.request ?? null,
52051
52716
  agent: { id: built.agent.id, label: built.agent.label, ...built.agent.sessionId ? { sessionId: built.agent.sessionId } : {} },
52052
52717
  transcript: {
52053
52718
  status: transcript2.status,
@@ -52066,6 +52731,7 @@ var init_feedback = __esm({
52066
52731
  listedOnly: project.files.length - sent.length,
52067
52732
  ...project.listTruncated ? { listTruncated: true } : {}
52068
52733
  } : null,
52734
+ media: mediaToSend(rt, built, noMedia),
52069
52735
  redactions: built.stats.redactions,
52070
52736
  omittedImages: built.stats.omittedImages,
52071
52737
  bytes: built.gzip.length
@@ -52089,12 +52755,13 @@ var init_feedback = __esm({
52089
52755
  "Nothing was sent. Show the user what would be sent; run next only after they agree.",
52090
52756
  "\u672A\u53D1\u9001\u4EFB\u4F55\u5185\u5BB9\u3002\u5148\u628A\u5C06\u8981\u53D1\u9001\u7684\u5185\u5BB9\u7ED9\u7528\u6237\u770B\uFF1B\u7528\u6237\u540C\u610F\u540E\u518D\u8FD0\u884C next\u3002"
52091
52757
  );
52092
- printJson(rt, { ok: true, dryRun: true, wouldSend: wouldSend(rt, built), ...written2, next, note }, true);
52758
+ printJson(rt, { ok: true, dryRun: true, wouldSend: wouldSend(rt, built, options.noMedia), ...written2, next, note }, true);
52093
52759
  return 0;
52094
52760
  }
52095
52761
  const sent = await sendFeedback(rt, new PopostClient({ ...rt, project: void 0 }), built);
52096
52762
  const thanks = msg(`Sent. Give the user the reference ${sent.reference} for any follow-up.`, `\u5DF2\u53D1\u9001\u3002\u8BF7\u628A\u7F16\u53F7 ${sent.reference} \u544A\u8BC9\u7528\u6237\uFF0C\u65B9\u4FBF\u540E\u7EED\u6C9F\u901A\u3002`);
52097
- printJson(rt, { ok: true, id: sent.id, reference: sent.reference, bytes: built.gzip.length, receivedAt: sent.receivedAt, ...written2, note: thanks });
52763
+ const media = sent.media.map((m) => ({ path: mediaPath(rt, built.projectDir, m.file.file), state: m.state }));
52764
+ printJson(rt, { ok: true, id: sent.id, reference: sent.reference, bytes: built.gzip.length, receivedAt: sent.receivedAt, ...media.length ? { media } : {}, ...written2, note: thanks });
52098
52765
  return 0;
52099
52766
  };
52100
52767
  run5 = async (rt, argv, options) => {
@@ -52120,6 +52787,7 @@ var init_feedback = __esm({
52120
52787
  transcript: args.string("transcript"),
52121
52788
  noTranscript: args.flag("no-transcript"),
52122
52789
  session: args.string("session"),
52790
+ noMedia: args.flag("no-media"),
52123
52791
  out: args.string("out"),
52124
52792
  confirm: args.flag("confirm")
52125
52793
  })
@@ -52314,9 +52982,9 @@ ${usage()}`);
52314
52982
  const own3 = updates.rt;
52315
52983
  try {
52316
52984
  const main24 = await group.load();
52317
- const { dirArg: dirArg2, inProject: inProject3 } = await Promise.resolve().then(() => (init_task(), task_exports));
52985
+ const { dirArg: dirArg2, inProject: inProject5 } = await Promise.resolve().then(() => (init_task(), task_exports));
52318
52986
  const dir = dirArg2(rest);
52319
- return await main24(group.keepName ? argv : rest, dir ? inProject3(own3, dir, "found") : own3);
52987
+ return await main24(group.keepName ? argv : rest, dir ? inProject5(own3, dir, "found") : own3);
52320
52988
  } catch (error2) {
52321
52989
  printJson(own3, { ok: false, error: errorText(error2) });
52322
52990
  return 1;