popost 4.6.8 → 4.6.10

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/cli.js CHANGED
@@ -21,9 +21,9 @@ var init_i18n = __esm({
21
21
  "src/i18n.ts"() {
22
22
  "use strict";
23
23
  LANG_ENV = ["POPOST_LANG", "LC_ALL", "LC_MESSAGES", "LANG"];
24
- resolveLang = (env) => {
24
+ resolveLang = (env2) => {
25
25
  for (const name of LANG_ENV) {
26
- const value = (env[name] ?? "").trim();
26
+ const value = (env2[name] ?? "").trim();
27
27
  if (value) return value.toLowerCase().startsWith("zh") ? "zh" : "en";
28
28
  }
29
29
  return "en";
@@ -275,7 +275,7 @@ var VERSION;
275
275
  var init_version = __esm({
276
276
  "src/version.ts"() {
277
277
  "use strict";
278
- VERSION = "4.6.8";
278
+ VERSION = "4.6.10";
279
279
  }
280
280
  });
281
281
 
@@ -963,8 +963,8 @@ var init_post_bundle = __esm({
963
963
  const blocker = await resourceBlocker(rt, res, baseDir);
964
964
  if (blocker) blockers.push(blocker);
965
965
  }
966
- const missing3 = Array.isArray(bundle.missing) ? bundle.missing : [];
967
- for (const item2 of missing3) blockers.push(msg(`the bundle still declares a missing item: ${plain(item2)}`, `bundle \u4ECD\u58F0\u660E\u7F3A\u9879: ${plain(item2)}`));
966
+ const missing4 = Array.isArray(bundle.missing) ? bundle.missing : [];
967
+ for (const item2 of missing4) blockers.push(msg(`the bundle still declares a missing item: ${plain(item2)}`, `bundle \u4ECD\u58F0\u660E\u7F3A\u9879: ${plain(item2)}`));
968
968
  return { buildable: blockers.length === 0, blockers };
969
969
  };
970
970
  }
@@ -1618,11 +1618,11 @@ var init_args = __esm({
1618
1618
  );
1619
1619
  values.set(keyOf(positional.name), positional.variadic ? raws : raws[0]);
1620
1620
  });
1621
- const missing3 = [
1621
+ const missing4 = [
1622
1622
  ...declared.filter((p) => p.required !== false && !values.has(keyOf(p.name))).map((p) => p.name),
1623
1623
  ...(spec8.options ?? []).filter((o) => o.required && !values.has(keyOf(o.flag))).map((o) => o.flag)
1624
1624
  ];
1625
- if (missing3.length) throw new UsageError(`the following arguments are required: ${missing3.join(", ")}`);
1625
+ if (missing4.length) throw new UsageError(`the following arguments are required: ${missing4.join(", ")}`);
1626
1626
  for (const option of spec8.options ?? []) {
1627
1627
  const key2 = keyOf(option.flag);
1628
1628
  if (!values.has(key2) && option.default !== void 0) values.set(key2, option.default);
@@ -2800,9 +2800,9 @@ var init_project_bundle = __esm({
2800
2800
  const roles = JSON.parse(await rt.fs.readText(palette)).roles ?? [];
2801
2801
  for (const role of roles) {
2802
2802
  const dir = rt.path.join(fontRoot, role.id);
2803
- const present2 = (await walkFiles(rt, dir)).filter((f) => rt.path.dirname(f) === dir);
2804
- if (!present2.some((f) => f.endsWith(".woff2"))) continue;
2805
- for (const file of [rt.path.join(fontRoot, role.cssPath), ...present2])
2803
+ const present3 = (await walkFiles(rt, dir)).filter((f) => rt.path.dirname(f) === dir);
2804
+ if (!present3.some((f) => f.endsWith(".woff2"))) continue;
2805
+ for (const file of [rt.path.join(fontRoot, role.cssPath), ...present3])
2806
2806
  if (await isFile(rt, file)) add2(file);
2807
2807
  }
2808
2808
  return files;
@@ -3447,11 +3447,11 @@ var init_credentials = __esm({
3447
3447
  if (apiKey === null || baseUrl === null) return null;
3448
3448
  return { ...apiKey ? { apiKey } : {}, ...baseUrl ? { baseUrl } : {} };
3449
3449
  };
3450
- applyStoredCredentials = (env, stored) => {
3451
- if (!stored) return env;
3452
- const out2 = { ...env };
3453
- if (stored.apiKey && !(env[DEFAULT_KEY_ENV] ?? "").trim()) out2[DEFAULT_KEY_ENV] = stored.apiKey;
3454
- if (stored.baseUrl && !(env[BASE_URL_ENV] ?? "").trim()) out2[BASE_URL_ENV] = stored.baseUrl;
3450
+ applyStoredCredentials = (env2, stored) => {
3451
+ if (!stored) return env2;
3452
+ const out2 = { ...env2 };
3453
+ if (stored.apiKey && !(env2[DEFAULT_KEY_ENV] ?? "").trim()) out2[DEFAULT_KEY_ENV] = stored.apiKey;
3454
+ if (stored.baseUrl && !(env2[BASE_URL_ENV] ?? "").trim()) out2[BASE_URL_ENV] = stored.baseUrl;
3455
3455
  return out2;
3456
3456
  };
3457
3457
  readStoredCredentials = async (rt) => {
@@ -3822,12 +3822,12 @@ var init_api = __esm({
3822
3822
  // ---------- sending ----------
3823
3823
  /** Returns the envelope's `data`. See the file header for what throws `AmbiguousSubmitError`. */
3824
3824
  async request(method, path4, options = {}) {
3825
- const { body, query, ambiguous = false, hint = "" } = options;
3826
- const device = !this.bearer && this.keyEnv === DEFAULT_KEY_ENV && this.rt.deviceAccess;
3827
- const key2 = device ? await device(this.baseUrl) : this.key();
3825
+ const { body, query, ambiguous = false, hint = "", anonymous = false } = options;
3826
+ const device = !anonymous && !this.bearer && this.keyEnv === DEFAULT_KEY_ENV && this.rt.deviceAccess;
3827
+ const key2 = anonymous ? null : device ? await device(this.baseUrl) : this.key();
3828
3828
  const wait = Number(options.timeoutSec || this.timeoutSec);
3829
3829
  const headers = { ...this.headers(body !== void 0), ...await taskHeaders(this.rt) };
3830
- headers.Authorization = `Bearer ${key2}`;
3830
+ if (key2) headers.Authorization = `Bearer ${key2}`;
3831
3831
  const signal = timeoutSignal(this.rt, wait * 1e3);
3832
3832
  const url = this.url(path4, query);
3833
3833
  try {
@@ -3993,6 +3993,86 @@ var init_api = __esm({
3993
3993
  }
3994
3994
  });
3995
3995
 
3996
+ // src/install/agents.ts
3997
+ var env, sharedSkillsDir, configHome, shared, own, AGENTS, AGENT_IDS, agentLabel;
3998
+ var init_agents = __esm({
3999
+ "src/install/agents.ts"() {
4000
+ "use strict";
4001
+ env = (rt, name) => {
4002
+ const value = (rt.env[name] ?? "").trim();
4003
+ return value ? rt.path.resolve(rt.cwd, value) : null;
4004
+ };
4005
+ sharedSkillsDir = (rt, home) => rt.path.join(home, ".agents", "skills");
4006
+ configHome = (rt, home) => env(rt, "XDG_CONFIG_HOME") ?? rt.path.join(home, ".config");
4007
+ shared = (id2, label2, homes, vars) => ({
4008
+ id: id2,
4009
+ label: label2,
4010
+ homes,
4011
+ skillsDir: sharedSkillsDir,
4012
+ ...vars ? { env: vars } : {}
4013
+ });
4014
+ own = (id2, label2, dir, variable) => {
4015
+ const home = (rt, base) => (variable ? env(rt, variable) : null) ?? rt.path.join(base, dir);
4016
+ return { id: id2, label: label2, homes: (rt, base) => [home(rt, base)], skillsDir: (rt, base) => rt.path.join(home(rt, base), "skills") };
4017
+ };
4018
+ AGENTS = [
4019
+ { ...own("claude-code", "Claude Code", ".claude"), env: ["CLAUDECODE"] },
4020
+ shared("codex", "Codex", (rt, home) => [env(rt, "CODEX_HOME") ?? rt.path.join(home, ".codex")], ["CODEX_THREAD_ID"]),
4021
+ own("workbuddy", "WorkBuddy", ".workbuddy"),
4022
+ {
4023
+ id: "gemini",
4024
+ label: "Gemini CLI",
4025
+ homes: (rt, home) => [rt.path.join(env(rt, "GEMINI_CLI_HOME") ?? home, ".gemini")],
4026
+ skillsDir: (rt, home) => sharedSkillsDir(rt, env(rt, "GEMINI_CLI_HOME") ?? home),
4027
+ env: ["GEMINI_CLI"]
4028
+ },
4029
+ {
4030
+ id: "antigravity",
4031
+ label: "Antigravity",
4032
+ homes: (rt, home) => [rt.path.join(home, ".gemini", "antigravity"), rt.path.join(home, ".gemini", "antigravity-cli")],
4033
+ skillsDir: (rt, home) => rt.path.join(home, ".gemini", "config", "skills")
4034
+ },
4035
+ shared("opencode", "OpenCode", (rt, home) => [rt.path.join(configHome(rt, home), "opencode")], ["OPENCODE"]),
4036
+ shared("cursor", "Cursor", (rt, home) => [rt.path.join(home, ".cursor")]),
4037
+ shared("grok", "Grok", (rt, home) => [env(rt, "GROK_HOME") ?? rt.path.join(home, ".grok")]),
4038
+ shared("kimi", "Kimi Code", (rt, home) => [env(rt, "KIMI_CODE_HOME") ?? rt.path.join(home, ".kimi-code"), rt.path.join(home, ".kimi")], ["KIMI_CODE_SESSION_ID"]),
4039
+ shared("qwen", "Qwen Code", (rt, home) => [env(rt, "QWEN_HOME") ?? rt.path.join(home, ".qwen")], ["QWEN_CODE"]),
4040
+ shared("vibe-cli", "Mistral Vibe", (rt, home) => [env(rt, "VIBE_HOME") ?? rt.path.join(home, ".vibe")]),
4041
+ {
4042
+ id: "copilot",
4043
+ label: "Copilot CLI",
4044
+ homes: (rt, home) => [env(rt, "COPILOT_HOME") ?? rt.path.join(home, ".copilot")],
4045
+ skillsDir: (rt, home) => {
4046
+ const moved = env(rt, "COPILOT_HOME");
4047
+ return moved ? rt.path.join(moved, "skills") : sharedSkillsDir(rt, home);
4048
+ },
4049
+ env: ["COPILOT_CLI"]
4050
+ },
4051
+ shared("kilo", "Kilo Code", (rt, home) => [rt.path.join(home, ".kilo"), rt.path.join(home, ".kilocode"), rt.path.join(configHome(rt, home), "kilo")], ["KILO"]),
4052
+ shared("pi", "Pi", (rt, home) => [env(rt, "PI_CODING_AGENT_DIR") ?? rt.path.join(home, ".pi", "agent")], ["PI_CODING_AGENT"]),
4053
+ shared("devin", "Devin", (rt, home) => [rt.path.join(configHome(rt, home), "devin")]),
4054
+ {
4055
+ id: "deepseek-harness",
4056
+ label: "DeepSeek Harness",
4057
+ homes: (rt, home) => [env(rt, "DSH_HOME") ?? rt.path.join(home, ".dsh")],
4058
+ skillsDir: (rt, home) => {
4059
+ const moved = env(rt, "DSH_AGENTS_HOME");
4060
+ return moved ? rt.path.join(moved, "skills") : sharedSkillsDir(rt, home);
4061
+ },
4062
+ env: ["DSH_SHELL"]
4063
+ },
4064
+ shared("reasonix", "Reasonix", (rt, home) => [env(rt, "REASONIX_HOME") ?? rt.path.join(home, ".reasonix")]),
4065
+ own("hermes", "Hermes", ".hermes", "HERMES_HOME"),
4066
+ own("trae", "Trae", ".trae"),
4067
+ own("trae-cn", "Trae CN", ".trae-cn"),
4068
+ own("qoder", "Qoder", ".qoder"),
4069
+ own("kiro", "Kiro", ".kiro", "KIRO_HOME")
4070
+ ];
4071
+ AGENT_IDS = AGENTS.map((agent) => agent.id);
4072
+ agentLabel = (id2) => AGENTS.find((agent) => agent.id === id2)?.label ?? id2;
4073
+ }
4074
+ });
4075
+
3996
4076
  // src/device-login.ts
3997
4077
  import { createPrivateKey, generateKeyPairSync, randomUUID, sign } from "node:crypto";
3998
4078
  var profileName, deviceLocation, parseDeviceGrant, DeviceRequestError, deviceApi, deviceTokenProvider, codeExpired, login;
@@ -4005,11 +4085,12 @@ var init_device_login = __esm({
4005
4085
  init_api();
4006
4086
  init_util();
4007
4087
  init_i18n();
4088
+ init_agents();
4008
4089
  init_profile();
4009
- profileName = (env) => {
4010
- const configured = env.POPOST_AGENT_PROFILE?.trim();
4090
+ profileName = (env2) => {
4091
+ const configured = env2.POPOST_AGENT_PROFILE?.trim();
4011
4092
  if (configured && !PROFILE_NAME.test(configured)) throw new UsageError(profileNameHint());
4012
- return configured || (env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT ? "claude-code" : env.CODEX_THREAD_ID || env.CODEX_CI ? "codex" : "terminal");
4093
+ return configured || (env2.CLAUDECODE || env2.CLAUDE_CODE_ENTRYPOINT ? "claude-code" : env2.CODEX_THREAD_ID || env2.CODEX_CI ? "codex" : "terminal");
4013
4094
  };
4014
4095
  deviceLocation = (rt) => {
4015
4096
  const root = credentialsDir(rt);
@@ -4132,7 +4213,7 @@ var init_device_login = __esm({
4132
4213
  if (!pending3 || pending3.expiresAt <= Date.now()) {
4133
4214
  const pair4 = generateKeyPairSync("ed25519");
4134
4215
  const publicKey = pair4.publicKey.export({ format: "jwk" }).x;
4135
- const agent = { codex: "Codex", "claude-code": "Claude Code", terminal: "CLI" }[profile2] || profile2;
4216
+ const agent = profile2 === "terminal" ? "CLI" : agentLabel(profile2);
4136
4217
  const label2 = [agent, rt.deviceName].filter(Boolean).join(" \xB7 ").slice(0, 80);
4137
4218
  const start = await deviceApi(rt.fetch, baseUrl, "start", { label: label2, publicKey });
4138
4219
  pending3 = {
@@ -4452,29 +4533,6 @@ Key \u4FDD\u5B58\u5728 <home>/.popost/credentials.json\uFF08\u76EE\u5F55\uFF1APO
4452
4533
  }
4453
4534
  });
4454
4535
 
4455
- // src/install/agents.ts
4456
- var AGENTS, AGENT_IDS;
4457
- var init_agents = __esm({
4458
- "src/install/agents.ts"() {
4459
- "use strict";
4460
- AGENTS = [
4461
- {
4462
- id: "claude-code",
4463
- label: "Claude Code",
4464
- home: (rt, home) => rt.path.join(home, ".claude"),
4465
- skillsDir: (rt, home) => rt.path.join(home, ".claude", "skills")
4466
- },
4467
- {
4468
- id: "codex",
4469
- label: "Codex",
4470
- home: (rt, home) => (rt.env.CODEX_HOME ?? "").trim() ? rt.path.resolve(rt.cwd, rt.env.CODEX_HOME.trim()) : rt.path.join(home, ".codex"),
4471
- skillsDir: (rt, home) => rt.path.join(home, ".agents", "skills")
4472
- }
4473
- ];
4474
- AGENT_IDS = AGENTS.map((agent) => agent.id);
4475
- }
4476
- });
4477
-
4478
4536
  // src/install/payload.ts
4479
4537
  var NOT_COPIED, ALWAYS, SKIP_NAMES, segmentPattern, compile, relate, readManifest, listPayload;
4480
4538
  var init_payload = __esm({
@@ -4527,7 +4585,7 @@ var init_payload = __esm({
4527
4585
 
4528
4586
  // src/install/skill-install.ts
4529
4587
  import { createHash as createHash5 } from "node:crypto";
4530
- var SKILL_DIR_NAME, installedVersion, decide, stage, swap, installSkill;
4588
+ var SKILL_DIR_NAME, installedVersion, installedProfile, decide, stage, swap, installSkill;
4531
4589
  var init_skill_install = __esm({
4532
4590
  "src/install/skill-install.ts"() {
4533
4591
  "use strict";
@@ -4542,6 +4600,13 @@ var init_skill_install = __esm({
4542
4600
  return null;
4543
4601
  }
4544
4602
  };
4603
+ installedProfile = async (rt, skillDir) => {
4604
+ try {
4605
+ return /popost --profile ([A-Za-z0-9][A-Za-z0-9._-]*)/.exec(await rt.fs.readText(rt.path.join(skillDir, "SKILL.md")))?.[1] ?? null;
4606
+ } catch {
4607
+ return null;
4608
+ }
4609
+ };
4545
4610
  decide = (exists3, previous, manifest, force2, dryRun2) => {
4546
4611
  const same5 = exists3 && previous === manifest.version;
4547
4612
  if (same5 && !force2) return "up-to-date";
@@ -4583,7 +4648,7 @@ var init_skill_install = __esm({
4583
4648
  try {
4584
4649
  await stage(rt, root, files, staging);
4585
4650
  const entry2 = rt.path.join(staging, "SKILL.md");
4586
- const profile2 = options.agent && options.agent !== "custom" ? options.agent : "agent-" + createHash5("sha256").update(skillsDir).digest("hex").slice(0, 10);
4651
+ const profile2 = (stat2 ? await installedProfile(rt, skillDir) : null) ?? (options.agent && options.agent !== "custom" ? options.agent : "agent-" + createHash5("sha256").update(skillsDir).digest("hex").slice(0, 10));
4587
4652
  const instructions = await rt.fs.readText(entry2);
4588
4653
  await rt.fs.writeFile(entry2, instructions.replace(
4589
4654
  "<!-- installed-profile -->",
@@ -4603,7 +4668,7 @@ var install_exports = {};
4603
4668
  __export(install_exports, {
4604
4669
  main: () => main4
4605
4670
  });
4606
- var OUTPUT, description2, spec2, detect, plan2, nextStep, run, main4;
4671
+ var OUTPUT, description2, spec2, SHARED, present, absent, byDirectory, ownerOf, plan2, fallbackNote, nextStep, run, main4;
4607
4672
  var init_install2 = __esm({
4608
4673
  "src/commands/install.ts"() {
4609
4674
  "use strict";
@@ -4615,18 +4680,18 @@ var init_install2 = __esm({
4615
4680
  init_i18n();
4616
4681
  init_api();
4617
4682
  init_version();
4618
- OUTPUT = `output: {"ok": true, "version", "dryRun", "installed": [{"agent", "skillDir", "status": "installed|updated|reinstalled|up-to-date|would-...", "previousVersion", "files"}], "skipped": [{"agent", "reason"}], "next"}`;
4683
+ OUTPUT = `output: {"ok": true, "version", "dryRun", "installed": [{"agent", "skillDir", "status": "installed|updated|reinstalled|up-to-date|would-...", "previousVersion", "files", "alsoFor": [agents that read the same directory]}], "skipped": [{"agent", "reason"}], "note", "next"}`;
4619
4684
  description2 = () => {
4620
4685
  const ids3 = AGENTS.map((a) => a.id).join(", ");
4621
4686
  return msg(
4622
- `Install the popost Skill for coding agents. Without --agent it installs for every supported agent whose home directory exists on this machine (${ids3}) and lists the ones skipped; --agent all forces all supported agents. For any other agent pass its skills directory with --dir. An existing install is replaced (atomically) when its version differs or with --force; the same version is reported as up-to-date. --dry-run shows what would happen and writes nothing.
4687
+ `Install the popost Skill for coding agents. Without --agent it installs for every supported agent found on this machine (${ids3}) and lists the ones skipped; agents that read the shared directory ~/.agents/skills get one copy there. When none of them is found, the Skill still goes to ~/.agents/skills, which most agents read, and the output says how to point another agent at it. --agent all forces all supported agents. For any other agent pass its skills directory with --dir. An existing install is replaced (atomically) when its version differs or with --force and keeps its sign-in profile; the same version is reported as up-to-date. --dry-run shows what would happen and writes nothing.
4623
4688
 
4624
4689
  ${OUTPUT}
4625
- failure: {"ok": false, "error", ...} exit 1 when nothing could be installed, 2 for a usage error`,
4626
- `\u4E3A\u7F16\u7A0B Agent \u5B89\u88C5 popost Skill\u3002\u4E0D\u5E26 --agent \u65F6\uFF0C\u5B89\u88C5\u5230\u672C\u673A\u6240\u6709\u5DF2\u6709\u4E3B\u76EE\u5F55\u7684\u53D7\u652F\u6301 Agent\uFF08${ids3}\uFF09\uFF0C\u5E76\u5217\u51FA\u8DF3\u8FC7\u7684\uFF1B--agent all \u5F3A\u5236\u5B89\u88C5\u5230\u6240\u6709\u53D7\u652F\u6301\u7684 Agent\u3002\u5176\u4ED6 Agent \u7528 --dir \u6307\u5B9A\u5B83\u7684 skills \u76EE\u5F55\u3002\u5DF2\u6709\u5B89\u88C5\u5728\u7248\u672C\u4E0D\u540C\u6216\u5E26 --force \u65F6\uFF08\u539F\u5B50\u5730\uFF09\u66FF\u6362\uFF1B\u7248\u672C\u76F8\u540C\u65F6\u62A5\u544A\u4E3A up-to-date\u3002--dry-run \u53EA\u663E\u793A\u5C06\u8981\u505A\u4EC0\u4E48\uFF0C\u4E0D\u5199\u5165\u4EFB\u4F55\u6587\u4EF6\u3002
4690
+ failure: {"ok": false, "error", ...} exit 1 when a directory could not be written, 2 for a usage error`,
4691
+ `\u4E3A\u7F16\u7A0B Agent \u5B89\u88C5 popost Skill\u3002\u4E0D\u5E26 --agent \u65F6\uFF0C\u5B89\u88C5\u5230\u672C\u673A\u627E\u5230\u7684\u6240\u6709\u53D7\u652F\u6301 Agent\uFF08${ids3}\uFF09\uFF0C\u5E76\u5217\u51FA\u8DF3\u8FC7\u7684\uFF1B\u8BFB\u53D6\u5171\u4EAB\u76EE\u5F55 ~/.agents/skills \u7684 Agent \u5171\u7528\u90A3\u91CC\u7684\u4E00\u4EFD\u3002\u4E00\u4E2A\u90FD\u6CA1\u627E\u5230\u65F6\uFF0C\u4ECD\u4F1A\u88C5\u5230\u591A\u6570 Agent \u90FD\u8BFB\u53D6\u7684 ~/.agents/skills\uFF0C\u5E76\u5728\u8F93\u51FA\u91CC\u8BF4\u660E\u5176\u4ED6 Agent \u5982\u4F55\u6307\u5B9A\u76EE\u5F55\u3002--agent all \u5F3A\u5236\u5B89\u88C5\u5230\u6240\u6709\u53D7\u652F\u6301\u7684 Agent\u3002\u5176\u4ED6 Agent \u7528 --dir \u6307\u5B9A\u5B83\u7684 skills \u76EE\u5F55\u3002\u5DF2\u6709\u5B89\u88C5\u5728\u7248\u672C\u4E0D\u540C\u6216\u5E26 --force \u65F6\uFF08\u539F\u5B50\u5730\uFF09\u66FF\u6362\uFF0C\u5E76\u4FDD\u7559\u539F\u6765\u7684\u767B\u5F55\u6863\u6848\uFF1B\u7248\u672C\u76F8\u540C\u65F6\u62A5\u544A\u4E3A up-to-date\u3002--dry-run \u53EA\u663E\u793A\u5C06\u8981\u505A\u4EC0\u4E48\uFF0C\u4E0D\u5199\u5165\u4EFB\u4F55\u6587\u4EF6\u3002
4627
4692
 
4628
4693
  ${OUTPUT}
4629
- failure: {"ok": false, "error", ...} \u4E00\u4E2A\u90FD\u88C5\u4E0D\u4E0A\u65F6\u9000\u51FA\u7801 1\uFF0C\u7528\u6CD5\u9519\u8BEF\u4E3A 2`
4694
+ failure: {"ok": false, "error", ...} \u76EE\u5F55\u5199\u4E0D\u8FDB\u53BB\u65F6\u9000\u51FA\u7801 1\uFF0C\u7528\u6CD5\u9519\u8BEF\u4E3A 2`
4630
4695
  );
4631
4696
  };
4632
4697
  spec2 = () => ({
@@ -4650,14 +4715,30 @@ failure: {"ok": false, "error", ...} \u4E00\u4E2A\u90FD\u88C5\u4E0D\u4E0A\u65F6\
4650
4715
  { flag: "--dry-run", kind: "flag", help: msg("show what would be installed; write nothing", "\u53EA\u663E\u793A\u5C06\u8981\u5B89\u88C5\u4EC0\u4E48\uFF0C\u4E0D\u5199\u5165") }
4651
4716
  ]
4652
4717
  });
4653
- detect = async (rt, agent, homeDir2) => {
4654
- const home = agent.home(rt, homeDir2);
4655
- if ((await rt.fs.stat(home))?.isDirectory) return null;
4718
+ SHARED = "shared";
4719
+ present = async (rt, agent, homeDir2) => {
4720
+ if ((agent.env ?? []).some((name) => (rt.env[name] ?? "").trim())) return true;
4721
+ for (const home of agent.homes(rt, homeDir2)) if ((await rt.fs.stat(home))?.isDirectory) return true;
4722
+ return false;
4723
+ };
4724
+ absent = (rt, agent, homeDir2) => {
4725
+ const homes = agent.homes(rt, homeDir2).join(msg(" or ", " \u6216 "));
4656
4726
  return msg(
4657
- `${agent.label} is not installed here (${home} does not exist); use --agent ${agent.id} to install anyway`,
4658
- `\u672C\u673A\u6CA1\u6709\u5B89\u88C5 ${agent.label}\uFF08${home} \u4E0D\u5B58\u5728\uFF09\uFF1B\u4ECD\u8981\u5B89\u88C5\u8BF7\u7528 --agent ${agent.id}`
4727
+ `${agent.label} is not installed here (${homes} does not exist); use --agent ${agent.id} to install anyway`,
4728
+ `\u672C\u673A\u6CA1\u6709\u5B89\u88C5 ${agent.label}\uFF08${homes} \u4E0D\u5B58\u5728\uFF09\uFF1B\u4ECD\u8981\u5B89\u88C5\u8BF7\u7528 --agent ${agent.id}`
4659
4729
  );
4660
4730
  };
4731
+ byDirectory = (rt, agents, homeDir2) => {
4732
+ const dirs = [...new Set(agents.map((agent) => agent.skillsDir(rt, homeDir2)))];
4733
+ return dirs.map((skillsDir) => {
4734
+ const [first, ...rest] = agents.filter((agent) => agent.skillsDir(rt, homeDir2) === skillsDir).map((agent) => agent.id);
4735
+ return { agent: first, skillsDir, alsoFor: rest };
4736
+ });
4737
+ };
4738
+ ownerOf = (rt, homeDir2, skillsDir) => {
4739
+ const owners = homeDir2 === void 0 ? [] : AGENTS.filter((agent) => agent.skillsDir(rt, homeDir2) === skillsDir);
4740
+ return owners.length === 1 ? owners[0].id : "custom";
4741
+ };
4661
4742
  plan2 = async (rt, args2, homeDir2) => {
4662
4743
  const dir = args2.string("dir");
4663
4744
  const asked2 = args2.list("agent");
@@ -4665,21 +4746,28 @@ failure: {"ok": false, "error", ...} \u4E00\u4E2A\u90FD\u88C5\u4E0D\u4E0A\u65F6\
4665
4746
  if (asked2.length)
4666
4747
  throw new UsageError(msg("--dir and --agent cannot be combined: --dir names the skills directory itself", "--dir \u548C --agent \u4E0D\u80FD\u540C\u65F6\u4F7F\u7528\uFF1A--dir \u76F4\u63A5\u6307\u5B9A skills \u76EE\u5F55"));
4667
4748
  if (!dir.trim()) throw new UsageError(msg("--dir is empty", "--dir \u4E3A\u7A7A"));
4668
- return { targets: [{ agent: "custom", skillsDir: rt.path.resolve(rt.cwd, dir) }], skipped: [] };
4749
+ const skillsDir = rt.path.resolve(rt.cwd, dir);
4750
+ return { targets: [{ agent: ownerOf(rt, homeDir2, skillsDir), skillsDir, alsoFor: [] }], skipped: [], fallback: false };
4669
4751
  }
4670
4752
  if (homeDir2 === void 0)
4671
4753
  throw new UsageError(msg("no user home directory in this environment: pass --dir <skills directory>", "\u5F53\u524D\u73AF\u5883\u6CA1\u6709\u7528\u6237\u4E3B\u76EE\u5F55\uFF1A\u8BF7\u4F20 --dir <skills \u76EE\u5F55>"));
4672
- const explicit = asked2.length > 0;
4673
- const wanted = asked2.includes("all") || !explicit ? AGENTS : AGENTS.filter((a) => asked2.includes(a.id));
4674
- const targets = [];
4754
+ if (asked2.length) {
4755
+ const wanted = asked2.includes("all") ? AGENTS : AGENTS.filter((a) => asked2.includes(a.id));
4756
+ return { targets: byDirectory(rt, wanted, homeDir2), skipped: [], fallback: false };
4757
+ }
4758
+ const found = [];
4675
4759
  const skipped2 = [];
4676
- for (const agent of wanted) {
4677
- const reason2 = explicit ? null : await detect(rt, agent, homeDir2);
4678
- if (reason2) skipped2.push({ agent: agent.id, reason: reason2 });
4679
- else targets.push({ agent: agent.id, skillsDir: agent.skillsDir(rt, homeDir2) });
4760
+ for (const agent of AGENTS) {
4761
+ if (await present(rt, agent, homeDir2)) found.push(agent);
4762
+ else skipped2.push({ agent: agent.id, reason: absent(rt, agent, homeDir2) });
4680
4763
  }
4681
- return { targets, skipped: skipped2 };
4764
+ if (!found.length) return { targets: [{ agent: SHARED, skillsDir: sharedSkillsDir(rt, homeDir2), alsoFor: [] }], skipped: skipped2, fallback: true };
4765
+ return { targets: byDirectory(rt, found, homeDir2), skipped: skipped2, fallback: false };
4682
4766
  };
4767
+ fallbackNote = (skillsDir) => msg(
4768
+ `No agent known to this installer was found on this machine, so the Skill was put in ${skillsDir}, the shared skills directory that Codex, Gemini CLI, Cursor, OpenCode, Copilot CLI and most other agents read. If your agent keeps skills somewhere else, run popost install --dir <its skills directory> (the Skill goes to <dir>/popost).`,
4769
+ `\u672C\u673A\u6CA1\u6709\u627E\u5230\u5B89\u88C5\u5668\u8BA4\u8BC6\u7684 Agent\uFF0C\u6240\u4EE5 Skill \u88C5\u5230\u4E86 ${skillsDir}\uFF1A\u8FD9\u662F Codex\u3001Gemini CLI\u3001Cursor\u3001OpenCode\u3001Copilot CLI \u7B49\u591A\u6570 Agent \u90FD\u4F1A\u8BFB\u53D6\u7684\u5171\u4EAB skills \u76EE\u5F55\u3002\u5982\u679C\u4F60\u7684 Agent \u628A skills \u653E\u5728\u522B\u5904\uFF0C\u8BF7\u8FD0\u884C popost install --dir <\u5B83\u7684 skills \u76EE\u5F55>\uFF08Skill \u4F1A\u88C5\u5230 <\u76EE\u5F55>/popost\uFF09\u3002`
4770
+ );
4683
4771
  nextStep = (page2) => msg(
4684
4772
  `Restart the agent only if it has not discovered the Skill; keep the supplied companion CLI when using a pinned build. How to use it, for example:
4685
4773
  Reproduce a video: Reference video: XX link. Use popost to reproduce its style, structure and hook; my content is: XX.
@@ -4697,29 +4785,22 @@ Popost cloud is the recommended integrated route for models and compute. Support
4697
4785
  \u9700\u8981\u4E91\u7AEF\u6A21\u578B\u6216\u7B97\u529B\u65F6\uFF0C\u4F18\u5148\u63A8\u8350 Popost\uFF1B\u4E5F\u53EF\u4F7F\u7528\u53D7\u652F\u6301\u7684\u81EA\u5E26\u670D\u52A1\u6216 Agent \u5DE5\u5177\uFF0C\u5E76\u4FDD\u7559\u5DF2\u6709\u9009\u62E9\u3002\u4F7F\u7528 Popost \u670D\u52A1\u65F6\uFF0C\u590D\u7528\u8D26\u53F7\u8FDE\u63A5\u6216\u8FD0\u884C popost auth login\uFF0C\u7531 CLI \u6253\u5F00\u72EC\u7ACB\u684C\u9762\u6D4F\u89C8\u5668\uFF0C\u628A\u8BBE\u5907\u7801\u53D1\u7ED9\u7528\u6237\uFF1B\u4E0D\u8981\u5728 Agent \u4FA7\u8FB9\u680F\u4E2D\u767B\u5F55\uFF0C\u7B49\u5F85\u6D4F\u89C8\u5668\u6388\u6743\u548C CLI \u9A8C\u8BC1\u6210\u529F\u3002\u5728 ${page2} \u7BA1\u7406\u8BBF\u95EE\u3002\u8FDE\u63A5\u8D26\u6237\u4E0D\u4EE3\u8868\u6388\u6743\u6D88\u8D39\uFF1B\u5DF2\u6709\u6388\u6743\u8986\u76D6\u7684\u4EFB\u52A1\uFF0C\u5728\u8303\u56F4\u548C\u9884\u7B97\u5185\u7EE7\u7EED\u6267\u884C\uFF0C\u4E0D\u91CD\u590D\u786E\u8BA4\u3002`
4698
4786
  );
4699
4787
  run = async (rt, args2) => {
4700
- const { targets, skipped: skipped2 } = await plan2(rt, args2, rt.homeDir);
4788
+ const { targets, skipped: skipped2, fallback } = await plan2(rt, args2, rt.homeDir);
4701
4789
  const dryRun2 = args2.flag("dry-run");
4702
4790
  const installed = [];
4703
4791
  const failed4 = [];
4704
4792
  for (const target2 of targets) {
4705
4793
  try {
4706
- installed.push({ agent: target2.agent, ...await installSkill(rt, target2.skillsDir, { force: args2.flag("force"), dryRun: dryRun2, agent: target2.agent }) });
4794
+ const result = await installSkill(rt, target2.skillsDir, { force: args2.flag("force"), dryRun: dryRun2, ...target2.agent === SHARED ? {} : { agent: target2.agent } });
4795
+ installed.push({ agent: target2.agent, ...result, ...target2.alsoFor.length ? { alsoFor: target2.alsoFor } : {} });
4707
4796
  } catch (error2) {
4708
4797
  failed4.push({ agent: target2.agent, error: errorText(error2) });
4709
4798
  }
4710
4799
  }
4711
4800
  const page2 = keyPageUrl((rt.env[BASE_URL_ENV] ?? "").trim() || DEFAULT_BASE_URL);
4712
- if (!installed.length)
4713
- return fail(
4714
- rt,
4715
- failed4.length ? msg("the Skill could not be installed", "Skill \u5B89\u88C5\u5931\u8D25") : msg(
4716
- "no supported agent found on this machine: use --agent all to install for every supported agent anyway, or --dir <skills directory> for another agent",
4717
- "\u672C\u673A\u6CA1\u6709\u627E\u5230\u53D7\u652F\u6301\u7684 Agent\uFF1A\u4ECD\u8981\u5B89\u88C5\u5230\u6240\u6709\u53D7\u652F\u6301\u7684 Agent \u8BF7\u7528 --agent all\uFF0C\u5176\u4ED6 Agent \u7528 --dir <skills \u76EE\u5F55>"
4718
- ),
4719
- 1,
4720
- { skipped: skipped2, ...failed4.length ? { failed: failed4 } : {} }
4721
- );
4722
- printJson(rt, { ok: failed4.length === 0, version: VERSION, dryRun: dryRun2, installed, skipped: skipped2, ...failed4.length ? { failed: failed4 } : {}, next: dryRun2 ? msg("Dry run: nothing was written.", "Dry run\uFF1A\u6CA1\u6709\u5199\u5165\u4EFB\u4F55\u6587\u4EF6\u3002") : nextStep(page2) }, true);
4801
+ if (!installed.length) return fail(rt, msg("the Skill could not be installed", "Skill \u5B89\u88C5\u5931\u8D25"), 1, { skipped: skipped2, failed: failed4 });
4802
+ const note = fallback ? { note: fallbackNote(targets[0].skillsDir) } : {};
4803
+ printJson(rt, { ok: failed4.length === 0, version: VERSION, dryRun: dryRun2, installed, skipped: skipped2, ...failed4.length ? { failed: failed4 } : {}, ...note, next: dryRun2 ? msg("Dry run: nothing was written.", "Dry run\uFF1A\u6CA1\u6709\u5199\u5165\u4EFB\u4F55\u6587\u4EF6\u3002") : nextStep(page2) }, true);
4723
4804
  return failed4.length ? 1 : 0;
4724
4805
  };
4725
4806
  main4 = (argv, rt) => withArgs(argv, spec2(), rt, async (args2) => {
@@ -5418,7 +5499,7 @@ var init_paths = __esm({
5418
5499
  });
5419
5500
 
5420
5501
  // src/providers/popost-async.ts
5421
- var STATES, imageTaskOf, generationAnswer, routeMissing, fallbackNote, TRANSIENT_CODES, isTransient, failureText2, refundText;
5502
+ var STATES, imageTaskOf, generationAnswer, routeMissing, fallbackNote2, TRANSIENT_CODES, isTransient, failureText2, refundText;
5422
5503
  var init_popost_async = __esm({
5423
5504
  "src/providers/popost-async.ts"() {
5424
5505
  "use strict";
@@ -5447,7 +5528,7 @@ var init_popost_async = __esm({
5447
5528
  ...task.balance !== null ? { balance: task.balance } : {}
5448
5529
  });
5449
5530
  routeMissing = (error2) => error2 instanceof PopostApiError && (error2.status === 404 || error2.code === "NOT_FOUND");
5450
- fallbackNote = (rt) => rt.stderr(
5531
+ fallbackNote2 = (rt) => rt.stderr(
5451
5532
  msg(
5452
5533
  "note: popost.ai has no image task endpoint here yet; the picture is made with the synchronous call under the same idempotency key, and this call waits for it.\n",
5453
5534
  "\u63D0\u793A\uFF1Apopost.ai \u8FD9\u91CC\u8FD8\u6CA1\u6709\u751F\u56FE\u4EFB\u52A1\u63A5\u53E3\uFF1B\u6539\u7528\u540C\u6B65\u751F\u56FE\uFF08\u540C\u4E00\u5E42\u7B49\u952E\uFF09\uFF0C\u672C\u6B21\u4F1A\u7B49\u5230\u56FE\u51FA\u6765\u3002\n"
@@ -6034,7 +6115,7 @@ var init_popost = __esm({
6034
6115
  } catch (error2) {
6035
6116
  if (!(error2 instanceof AmbiguousSubmitError)) await this.rt.fs.rm(root);
6036
6117
  if (!routeMissing(error2)) throw error2;
6037
- fallbackNote(this.rt);
6118
+ fallbackNote2(this.rt);
6038
6119
  return this.generate(body, model, aspect, count5, idem);
6039
6120
  }
6040
6121
  const task = imageTaskOf(data);
@@ -8338,18 +8419,18 @@ var init_steps = __esm({
8338
8419
  };
8339
8420
  fontsStep = async (ctx) => {
8340
8421
  const project = projectOf(ctx);
8341
- const missing3 = [];
8342
- for (const role of ctx.spec.fonts) if (!await isInstalled(project, role)) missing3.push(role);
8343
- if (!missing3.length)
8422
+ const missing4 = [];
8423
+ for (const role of ctx.spec.fonts) if (!await isInstalled(project, role)) missing4.push(role);
8424
+ if (!missing4.length)
8344
8425
  return skipped(
8345
8426
  msg(`font roles already installed: ${ctx.spec.fonts.join(", ")}`, `\u5B57\u4F53\u89D2\u8272\u5DF2\u5B89\u88C5\uFF1A${ctx.spec.fonts.join(", ")}`) + linksNote(project)
8346
8427
  );
8347
- const { result, fontLinks } = await installFonts(ctx.rt, project, missing3.join(","), true);
8428
+ const { result, fontLinks } = await installFonts(ctx.rt, project, missing4.join(","), true);
8348
8429
  const { installed } = result;
8349
- const kept2 = ctx.spec.fonts.length - missing3.length;
8430
+ const kept2 = ctx.spec.fonts.length - missing4.length;
8350
8431
  const detail2 = msg(
8351
- `installed ${missing3.join(", ")}${kept2 ? `; ${kept2} already installed` : ""}`,
8352
- `\u5DF2\u5B89\u88C5 ${missing3.join(", ")}${kept2 ? `\uFF1B${kept2} \u4E2A\u6B64\u524D\u5DF2\u5B89\u88C5` : ""}`
8432
+ `installed ${missing4.join(", ")}${kept2 ? `; ${kept2} already installed` : ""}`,
8433
+ `\u5DF2\u5B89\u88C5 ${missing4.join(", ")}${kept2 ? `\uFF1B${kept2} \u4E2A\u6B64\u524D\u5DF2\u5B89\u88C5` : ""}`
8353
8434
  ) + linksNote(project);
8354
8435
  return done(detail2, [], cjkFontWarnings(project, installed.map((role) => role.id)), fontLinks);
8355
8436
  };
@@ -9852,7 +9933,7 @@ var init_service = __esm({
9852
9933
  });
9853
9934
 
9854
9935
  // src/editor/handoff.ts
9855
- var EDITOR_VERSION, editorInfo, resolveHost, editorHandoff, handoff, sleep2, probe, isLoopbackOrigin, saveHandoff, reusable, readLog, READY_TIMEOUT_MS, reportedCloud, presentLocal, presentCloud, WEB_HOST, present;
9936
+ var EDITOR_VERSION, serviceState, recordService, editorInfo, resolveHost, editorHandoff, handoff, sleep2, probe, isLoopbackOrigin, saveHandoff, reusable, readLog, READY_TIMEOUT_MS, reportedCloud, BACKGROUND_TASK_HOSTS, shellWord, startInBackground, presentLocal, presentCloud, WEB_HOST, present2;
9856
9937
  var init_handoff = __esm({
9857
9938
  "src/editor/handoff.ts"() {
9858
9939
  "use strict";
@@ -9866,6 +9947,11 @@ var init_handoff = __esm({
9866
9947
  init_i18n();
9867
9948
  init_canvas_state();
9868
9949
  EDITOR_VERSION = "4.1.3";
9950
+ serviceState = (rt, root) => rt.path.join(root, STATE_DIR, "service.json");
9951
+ recordService = async (rt, root, url, pid) => {
9952
+ await rt.fs.mkdir(rt.path.join(root, STATE_DIR));
9953
+ await writeJson(rt, serviceState(rt, root), { url, ...pid !== void 0 ? { pid } : {}, version: EDITOR_VERSION });
9954
+ };
9869
9955
  editorInfo = (project) => {
9870
9956
  const identity = sha256(project.rt.path.resolve(project.root));
9871
9957
  return {
@@ -9909,7 +9995,8 @@ var init_handoff = __esm({
9909
9995
  try {
9910
9996
  const response = await rt.fetch(`${url}/api/editor-info`, { signal: AbortSignal.timeout(700) });
9911
9997
  const info = await response.json();
9912
- return info.projectIdentity === expected2.projectIdentity && info.version === EDITOR_VERSION;
9998
+ if (info.projectIdentity !== expected2.projectIdentity || info.version !== EDITOR_VERSION) return false;
9999
+ return (await rt.fetch(`${url}/editor.html`, { method: "HEAD", signal: AbortSignal.timeout(2e3) })).ok;
9913
10000
  } catch {
9914
10001
  return false;
9915
10002
  }
@@ -9968,30 +10055,43 @@ var init_handoff = __esm({
9968
10055
  return { mode: "off", state: "idle" };
9969
10056
  }
9970
10057
  };
10058
+ BACKGROUND_TASK_HOSTS = /* @__PURE__ */ new Set(["workbuddy"]);
10059
+ shellWord = (word2) => /^[\w@%+=:,./-]+$/.test(word2) ? word2 : `'${word2.replace(/'/g, `'\\''`)}'`;
10060
+ startInBackground = (rt, host, argv) => ({
10061
+ ok: false,
10062
+ code: "START_SERVICE",
10063
+ host: resolveHost(rt, host),
10064
+ // --port as present got it: 0 (the default) lets the service pick a free port, which a stale service may still hold.
10065
+ startService: { argv, command: argv.map(shellWord).join(" "), background: true },
10066
+ next: msg(
10067
+ 'This host stops a service started inside an ordinary command once that command ends. Run startService.command as a background task of the host (one that keeps running after this call), wait for its {"listening": \u2026} line, then run this same present command again: it finds that service and prints open.url.',
10068
+ '\u8FD9\u4E2A\u5BBF\u4E3B\u4F1A\u5728\u666E\u901A\u547D\u4EE4\u7ED3\u675F\u540E\u5207\u65AD\u5B83\u542F\u52A8\u7684\u670D\u52A1\u3002\u8BF7\u628A startService.command \u4F5C\u4E3A\u5BBF\u4E3B\u7684\u540E\u53F0\u4EFB\u52A1\u8FD0\u884C\uFF08\u8C03\u7528\u7ED3\u675F\u540E\u4ECD\u6301\u7EED\u8FD0\u884C\uFF09\uFF0C\u7B49\u5B83\u8F93\u51FA {"listening": \u2026} \u8FD9\u4E00\u884C\uFF0C\u518D\u8FD0\u884C\u540C\u4E00\u6761 present \u547D\u4EE4\uFF1A\u5B83\u4F1A\u627E\u5230\u8FD9\u4E2A\u670D\u52A1\u5E76\u7ED9\u51FA open.url\u3002'
10069
+ )
10070
+ });
9971
10071
  presentLocal = async (rt, project, host, port, cloud = true, fallback) => {
9972
10072
  const processes = rt.processes;
9973
10073
  if (!processes) throw new Error(msg("the local editor service is not available in this host", "\u5F53\u524D\u5BBF\u4E3B\u4E0D\u652F\u6301\u672C\u5730\u7F16\u8F91\u5668\u670D\u52A1"));
9974
10074
  const info = editorInfo(project);
9975
10075
  const dir = rt.path.join(project.root, STATE_DIR);
9976
10076
  await rt.fs.mkdir(dir);
9977
- const state = rt.path.join(dir, "service.json");
9978
- const running = await reusable(rt, state, info, port);
10077
+ const running = await reusable(rt, serviceState(rt, project.root), info, port);
9979
10078
  const mode = resolveCloudMode(rt, cloud, Boolean(fallback));
9980
10079
  const localHandoff = (url, reused, status2) => saveHandoff(rt, project, handoff(rt, project, url, host, reused, { ...status2, ...fallback ? { error: fallback } : {} }));
9981
10080
  if (running) {
9982
10081
  const status2 = await reportedCloud(rt, running);
9983
10082
  if (mode === status2.mode) return localHandoff(running, true, status2);
9984
10083
  }
9985
- const log = rt.path.join(dir, `server-${rt.now().getTime()}.log`);
9986
10084
  const cloudArg = !cloud ? "off" : fallback ? "login" : "auto";
9987
10085
  const argv = [...processes.selfCommand, "serve", "--dir", project.root, "--port", String(port), "--cloud", cloudArg];
10086
+ if (BACKGROUND_TASK_HOSTS.has(resolveHost(rt, host))) return startInBackground(rt, host, argv);
10087
+ const log = rt.path.join(dir, `server-${rt.now().getTime()}.log`);
9988
10088
  const { pid } = await processes.spawnDetached(argv, { cwd: rt.cwd, logFile: log });
9989
10089
  const deadline2 = rt.now().getTime() + READY_TIMEOUT_MS;
9990
10090
  while (rt.now().getTime() < deadline2) {
9991
10091
  const { url, error: error2 } = await readLog(rt, log, info);
9992
10092
  if (error2) throw new Error(msg(`editor service did not start: ${error2}; inspect ${log}`, `\u7F16\u8F91\u5668\u670D\u52A1\u6CA1\u6709\u542F\u52A8\uFF1A${error2}\uFF1B\u8BF7\u67E5\u770B ${log}`));
9993
10093
  if (url) {
9994
- await writeJson(rt, state, { url, pid, version: EDITOR_VERSION });
10094
+ await recordService(rt, project.root, url, pid);
9995
10095
  return localHandoff(url, false, await reportedCloud(rt, url));
9996
10096
  }
9997
10097
  await sleep2(50);
@@ -10010,19 +10110,19 @@ var init_handoff = __esm({
10010
10110
  return editorHandoff(rt, project, url, host, "web-http", { mode: "keyed", state: "saved", deckId, webUrl });
10011
10111
  };
10012
10112
  WEB_HOST = "web";
10013
- present = async (rt, project, host, port, cloud = true) => {
10014
- const own2 = rt.editorHost;
10015
- if (host === WEB_HOST && !own2)
10113
+ present2 = async (rt, project, host, port, cloud = true) => {
10114
+ const own3 = rt.editorHost;
10115
+ if (host === WEB_HOST && !own3)
10016
10116
  throw new Error(
10017
10117
  msg(
10018
10118
  "--host web needs a host that shows projects itself (the popost.ai workbench); this one has none",
10019
10119
  "--host web \u9700\u8981\u4E00\u4E2A\u80FD\u81EA\u5DF1\u5C55\u793A\u5DE5\u7A0B\u7684\u5BBF\u4E3B\uFF08popost.ai \u5DE5\u4F5C\u53F0\uFF09\uFF1B\u5F53\u524D\u5BBF\u4E3B\u6CA1\u6709"
10020
10120
  )
10021
10121
  );
10022
- if (own2 && (host === WEB_HOST || host === "auto" || host === own2.id)) return own2.present(project.root);
10122
+ if (own3 && (host === WEB_HOST || host === "auto" || host === own3.id)) return own3.present(project.root);
10023
10123
  if (!rt.processes)
10024
10124
  throw new Error(
10025
- own2 ? msg(
10125
+ own3 ? msg(
10026
10126
  `host "${host}" is not available here: the project is shown by the host's own editor (--host ${WEB_HOST} or auto)`,
10027
10127
  `\u8FD9\u91CC\u4E0D\u80FD\u7528\u5BBF\u4E3B "${host}"\uFF1A\u5DE5\u7A0B\u7531\u5BBF\u4E3B\u81EA\u5E26\u7684\u7F16\u8F91\u5668\u5C55\u793A\uFF08--host ${WEB_HOST} \u6216 auto\uFF09`
10028
10128
  ) : msg(
@@ -10303,9 +10403,9 @@ var init_routes_get = __esm({
10303
10403
  const html2 = editorHtml(await ctx.load(), source2, ctx.req.rawQuery, ctx.state.cloud.mode());
10304
10404
  return noStoreResponse(html2, "text/html; charset=utf-8");
10305
10405
  };
10306
- staticFile = async (ctx, root, urlPath, missing3) => {
10406
+ staticFile = async (ctx, root, urlPath, missing4) => {
10307
10407
  const file = await readProjectFile(ctx.rt, root, urlPath);
10308
- return file ? fileResponse(file.data, mimeType(file.path)) : notFound(ctx, missing3);
10408
+ return file ? fileResponse(file.data, mimeType(file.path)) : notFound(ctx, missing4);
10309
10409
  };
10310
10410
  EXACT = {
10311
10411
  "/api/export-options": async (ctx) => {
@@ -10687,6 +10787,7 @@ var init_server = __esm({
10687
10787
  init_util();
10688
10788
  init_i18n();
10689
10789
  init_http_types();
10790
+ init_handoff();
10690
10791
  init_request_security();
10691
10792
  init_routes_get();
10692
10793
  init_routes_post();
@@ -10747,10 +10848,10 @@ var init_server = __esm({
10747
10848
  port
10748
10849
  };
10749
10850
  };
10750
- send = (res, response) => {
10851
+ send = (res, response, head = false) => {
10751
10852
  const body = typeof response.body === "string" ? encoder.encode(response.body) : response.body;
10752
10853
  res.writeHead(response.status, { ...response.headers, "Content-Length": String(body.byteLength) });
10753
- res.end(body);
10854
+ res.end(head ? void 0 : body);
10754
10855
  };
10755
10856
  createCtx = (rt, state, lock, req) => ({
10756
10857
  rt,
@@ -10761,7 +10862,7 @@ var init_server = __esm({
10761
10862
  });
10762
10863
  dispatch2 = async (rt, state, lock, req) => {
10763
10864
  const ctx = createCtx(rt, state, lock, req);
10764
- if (req.method === "GET") return handleGet(ctx);
10865
+ if (req.method === "GET" || req.method === "HEAD") return handleGet(ctx);
10765
10866
  if (req.method === "POST") return handlePost(ctx);
10766
10867
  return jsonResponse(req, 501, { ok: false, error: msg(`unsupported method ${req.method}`, `\u4E0D\u652F\u6301\u7684\u8BF7\u6C42\u65B9\u6CD5 ${req.method}`) });
10767
10868
  };
@@ -10775,7 +10876,7 @@ var init_server = __esm({
10775
10876
  const stub = toRequest(req, new Uint8Array(), port());
10776
10877
  return send(res, jsonResponse(stub, 413, { ok: false, error: msg("request body is too large", "\u8BF7\u6C42\u4F53\u8FC7\u5927") }));
10777
10878
  }
10778
- send(res, await dispatch2(rt, state, lock, toRequest(req, body, port())));
10879
+ send(res, await dispatch2(rt, state, lock, toRequest(req, body, port())), req.method === "HEAD");
10779
10880
  } catch (error2) {
10780
10881
  if (!res.headersSent) send(res, jsonResponse(toRequest(req, new Uint8Array(), port()), 500, { ok: false, error: errorMessage(error2) }));
10781
10882
  else res.destroy();
@@ -10806,7 +10907,9 @@ var init_server = __esm({
10806
10907
  });
10807
10908
  });
10808
10909
  listening = await listen(server, port);
10809
- printJson(rt, { ok: true, listening: `http://127.0.0.1:${listening}`, project: project.root });
10910
+ const url = `http://127.0.0.1:${listening}`;
10911
+ await recordService(rt, project.root, url);
10912
+ printJson(rt, { ok: true, listening: url, project: project.root });
10810
10913
  state.cloud.autoStart();
10811
10914
  await new Promise((resolve2) => {
10812
10915
  server.once("close", resolve2);
@@ -10956,7 +11059,7 @@ var init_render = __esm({
10956
11059
  run: async (args2, rt) => {
10957
11060
  const project = await Project.load(rt, args2.req("dir"));
10958
11061
  try {
10959
- const result = await present(rt, project, args2.req("host"), args2.number("port") ?? 0, args2.req("cloud") !== "off");
11062
+ const result = await present2(rt, project, args2.req("host"), args2.number("port") ?? 0, args2.req("cloud") !== "off");
10960
11063
  printJson(rt, result, true);
10961
11064
  return result.ok === false ? 2 : 0;
10962
11065
  } catch (error2) {
@@ -12598,8 +12701,8 @@ var init_inspiration_plan = __esm({
12598
12701
  const b = bundle;
12599
12702
  if (b.parseStatus !== "ready" && !options.allowIncomplete) {
12600
12703
  const errorsOf = b.errors ?? [];
12601
- const missing3 = (b.missing ?? []).map((m) => msg(`missing ${m}`, `\u7F3A ${m}`));
12602
- const detail2 = [...errorsOf, ...missing3].join(msg("; ", "\uFF1B")) || msg("no reason given", "\u672A\u8BF4\u660E");
12704
+ const missing4 = (b.missing ?? []).map((m) => msg(`missing ${m}`, `\u7F3A ${m}`));
12705
+ const detail2 = [...errorsOf, ...missing4].join(msg("; ", "\uFF1B")) || msg("no reason given", "\u672A\u8BF4\u660E");
12603
12706
  throw new InputError(
12604
12707
  msg(
12605
12708
  `PostBundle parseStatus=${String(b.parseStatus)}: the content is incomplete (${detail2}). Complete it from local screenshots or text and mark it ready first, or, to save only what is there, add --allow-incomplete`,
@@ -12743,7 +12846,7 @@ var init_inspiration = __esm({
12743
12846
  });
12744
12847
 
12745
12848
  // src/providers/link-bundle.ts
12746
- var text3, badResponse, tagsOf2, imageOf, validPublishedAt, planPost, remoteView, COMMON_RATIOS, gcd2, ratioOf, fileName, sizeOf, reason, downloadPictures, utcNow2, buildBundle;
12849
+ var text3, badResponse, tagsOf2, imageOf, validPublishedAt, planPost, remoteView, COMMON_RATIOS, gcd2, ratioOf, fileName, sizeOf, reason, downloadPictures, utcNow2, pictureResource, videoResource, buildBundle;
12747
12850
  var init_link_bundle = __esm({
12748
12851
  "src/providers/link-bundle.ts"() {
12749
12852
  "use strict";
@@ -12786,6 +12889,7 @@ var init_link_bundle = __esm({
12786
12889
  const serverNote = text3(post.note) || (note ?? "").trim();
12787
12890
  return {
12788
12891
  platform: post.platform,
12892
+ kind: post.kind === "images" || post.kind === "video" ? post.kind : null,
12789
12893
  sourceUrl,
12790
12894
  title: text3(post.title),
12791
12895
  text: text3(post.text),
@@ -12800,6 +12904,7 @@ var init_link_bundle = __esm({
12800
12904
  };
12801
12905
  remoteView = (plan4) => ({
12802
12906
  platform: plan4.platform,
12907
+ ...plan4.kind ? { kind: plan4.kind } : {},
12803
12908
  title: plan4.title,
12804
12909
  text: plan4.text,
12805
12910
  tags: plan4.tags,
@@ -12854,7 +12959,17 @@ var init_link_bundle = __esm({
12854
12959
  return { saved, failure: null };
12855
12960
  };
12856
12961
  utcNow2 = (rt) => `${rt.now().toISOString().slice(0, 19)}+00:00`;
12857
- buildBundle = (rt, plan4, saved) => {
12962
+ pictureResource = (s) => ({
12963
+ id: `img${s.index}`,
12964
+ kind: "image",
12965
+ path: s.file,
12966
+ mimeType: s.mimeType,
12967
+ sha256: s.sha256,
12968
+ ...s.width && s.height ? { width: s.width, height: s.height } : {},
12969
+ ...s.alt ? { alt: s.alt } : {}
12970
+ });
12971
+ videoResource = (v) => ({ id: "video", kind: "video", path: v.file, mimeType: v.mimeType, sha256: v.sha256, bytes: v.bytes });
12972
+ buildBundle = (rt, plan4, saved, video) => {
12858
12973
  const first = saved[0];
12859
12974
  const complete3 = saved.length > 0;
12860
12975
  return {
@@ -12867,15 +12982,7 @@ var init_link_bundle = __esm({
12867
12982
  music: { title: "", url: "" },
12868
12983
  pageOrder: saved.map((s) => s.index),
12869
12984
  ratio: first?.width && first.height ? ratioOf(first.width, first.height) : null,
12870
- resources: saved.map((s) => ({
12871
- id: `img${s.index}`,
12872
- kind: "image",
12873
- path: s.file,
12874
- mimeType: s.mimeType,
12875
- sha256: s.sha256,
12876
- ...s.width && s.height ? { width: s.width, height: s.height } : {},
12877
- ...s.alt ? { alt: s.alt } : {}
12878
- })),
12985
+ resources: [...saved.map(pictureResource), ...video ? [videoResource(video)] : []],
12879
12986
  parseStatus: complete3 ? "ready" : "missing_resources",
12880
12987
  auth: {
12881
12988
  required: false,
@@ -12894,6 +13001,71 @@ var init_link_bundle = __esm({
12894
13001
  }
12895
13002
  });
12896
13003
 
13004
+ // src/providers/link-video.ts
13005
+ var MAX_VIDEO_BYTES, REQUEST_TIMEOUT_SEC, DOWNLOAD_TIMEOUT_SEC, EXTENSIONS2, LEADING_BOXES, ascii4, sniffVideoMime, missing, videoLink, downloadVideo;
13006
+ var init_link_video = __esm({
13007
+ "src/providers/link-video.ts"() {
13008
+ "use strict";
13009
+ init_util();
13010
+ init_i18n();
13011
+ init_api();
13012
+ init_base();
13013
+ init_errors3();
13014
+ MAX_VIDEO_BYTES = 200 * 1024 * 1024;
13015
+ REQUEST_TIMEOUT_SEC = 300;
13016
+ DOWNLOAD_TIMEOUT_SEC = 600;
13017
+ EXTENSIONS2 = { "video/mp4": ".mp4", "video/quicktime": ".mov", "video/webm": ".webm" };
13018
+ LEADING_BOXES = ["moov", "mdat", "free", "wide", "skip"];
13019
+ ascii4 = (bytes, from, to) => String.fromCharCode(...bytes.subarray(from, to));
13020
+ sniffVideoMime = (head, claimed) => {
13021
+ if (head.length >= 4 && head[0] === 26 && head[1] === 69 && head[2] === 223 && head[3] === 163) return "video/webm";
13022
+ if (head.length < 12) return null;
13023
+ const box2 = ascii4(head, 4, 8);
13024
+ if (box2 === "ftyp") return ascii4(head, 8, 12) === "qt " ? "video/quicktime" : "video/mp4";
13025
+ if (LEADING_BOXES.includes(box2)) return claimed === "video/quicktime" ? "video/quicktime" : "video/mp4";
13026
+ return null;
13027
+ };
13028
+ missing = (code, error2) => ({ missing: { code, error: error2 } });
13029
+ videoLink = async (client2, inspirationId) => {
13030
+ let answer3;
13031
+ try {
13032
+ answer3 = await client2.request("GET", `/inspirations/${encodeURIComponent(inspirationId)}/video`, { timeoutSec: REQUEST_TIMEOUT_SEC });
13033
+ } catch (error2) {
13034
+ if (error2 instanceof PopostApiError && error2.code === "VIDEO_GENERATION_DISABLED") return { skipped: true };
13035
+ if (error2 instanceof PopostApiError) return missing(error2.code || "API_ERROR", error2.message);
13036
+ if (error2 instanceof ImageProviderError) return missing("API_ERROR", error2.message);
13037
+ throw error2;
13038
+ }
13039
+ if (!isRecord(answer3) || typeof answer3.url !== "string" || typeof answer3.mimeType !== "string" || !EXTENSIONS2[answer3.mimeType])
13040
+ return missing("BAD_RESPONSE", msg("the answer for the post video has no usable link", "\u5E16\u5B50\u89C6\u9891\u7684\u54CD\u5E94\u91CC\u6CA1\u6709\u53EF\u7528\u7684\u94FE\u63A5"));
13041
+ return { url: answer3.url, mimeType: answer3.mimeType };
13042
+ };
13043
+ downloadVideo = async (rt, client2, inspirationId, outDir2, retry) => {
13044
+ const link = await videoLink(client2, inspirationId);
13045
+ if (!("url" in link)) return link;
13046
+ const what = msg("the post video", "\u5E16\u5B50\u89C6\u9891");
13047
+ const tmp = rt.path.join(outDir2, "video.download");
13048
+ let raw;
13049
+ try {
13050
+ raw = await downloadResult(rt, link.url, tmp, MAX_VIDEO_BYTES, DOWNLOAD_TIMEOUT_SEC, { what, retry });
13051
+ } catch (error2) {
13052
+ await rt.fs.rm(tmp).catch(() => void 0);
13053
+ if (error2 instanceof PopostApiError) return missing(error2.code || "DOWNLOAD_FAILED", error2.message);
13054
+ throw error2;
13055
+ }
13056
+ const mimeType2 = sniffVideoMime(raw.subarray(0, 16), link.mimeType);
13057
+ if (!mimeType2) {
13058
+ await rt.fs.rm(tmp);
13059
+ return missing("BAD_RESPONSE", msg(`the download of ${what} is not an MP4/MOV/WebM video; ${retry}`, `${what}\u4E0B\u8F7D\u7684\u5185\u5BB9\u4E0D\u662F MP4/MOV/WebM \u89C6\u9891\uFF1B${retry}`));
13060
+ }
13061
+ const file = `video${EXTENSIONS2[mimeType2]}`;
13062
+ const path4 = rt.path.join(outDir2, file);
13063
+ await rt.fs.rename(tmp, path4);
13064
+ return { saved: { file, path: path4, mimeType: mimeType2, sha256: sha256(raw), bytes: raw.length } };
13065
+ };
13066
+ }
13067
+ });
13068
+
12897
13069
  // src/providers/link-task.ts
12898
13070
  var POLL_INTERVAL_MS, MAX_POLL_FAILURES, RATE_LIMIT_WAIT_MS, RATE_LIMIT_WAIT_MAX_MS, TASK_ID2, STATUSES, taskOf2, isTerminal, TRANSIENT_CODES2, isTransient2, rateLimitWaitMs, fetchTask, waitForTask2;
12899
13071
  var init_link_task = __esm({
@@ -12969,7 +13141,7 @@ var init_link_task = __esm({
12969
13141
  });
12970
13142
 
12971
13143
  // src/providers/link.ts
12972
- var NOTE_MAX, TIMEOUT_MAX_SEC, LOCAL_CODES, shellArg, resumeCommand, briefOf, badArgs, checkOptions, parseBody, outDirOf, makeClient, dryRunOf, createTask, codeText, failedOutcome, unfinishedOutcome, succeededOutcome, finish2, failureOf5, report, parseLink, linkStatus;
13144
+ var NOTE_MAX, TIMEOUT_MAX_SEC, LOCAL_CODES, shellArg, resumeCommand, briefOf, badArgs, checkOptions, parseBody, outDirOf, makeClient, dryRunOf, createTask, codeText, failedOutcome, unfinishedOutcome, videoPart, succeededOutcome, finish2, failureOf5, report, parseLink, linkStatus;
12973
13145
  var init_link = __esm({
12974
13146
  "src/providers/link.ts"() {
12975
13147
  "use strict";
@@ -12981,6 +13153,7 @@ var init_link = __esm({
12981
13153
  init_cli_config();
12982
13154
  init_errors3();
12983
13155
  init_link_bundle();
13156
+ init_link_video();
12984
13157
  init_link_task();
12985
13158
  init_paths();
12986
13159
  init_secrets();
@@ -13061,7 +13234,30 @@ var init_link = __esm({
13061
13234
  );
13062
13235
  return { exit: 1, body: { ok: false, code, error: error2, task: { id: id2, status: task?.status ?? null, chargedCredits: task?.chargedCredits ?? null }, resume } };
13063
13236
  };
13064
- succeededOutcome = async (rt, task, call2, fallback) => {
13237
+ videoPart = async (rt, client2, plan4, call2, outDir2, retry) => {
13238
+ if (plan4.kind !== "video" || call2.noVideo || !plan4.inspirationId) return { fields: {}, note: "" };
13239
+ const outcome = await downloadVideo(rt, client2, plan4.inspirationId, outDir2, retry);
13240
+ if ("skipped" in outcome) return { fields: {}, note: "" };
13241
+ if ("saved" in outcome) {
13242
+ const path4 = shellArg(outcome.saved.path);
13243
+ return {
13244
+ saved: outcome.saved,
13245
+ fields: { video: outcome.saved.path },
13246
+ note: msg(
13247
+ `; the post's original video is ${path4}: use it as the reference video (for example popost video replication init <project> --reference ${path4})`,
13248
+ `\uFF1B\u5E16\u5B50\u539F\u89C6\u9891\u5728 ${path4}\uFF1A\u7528\u5B83\u4F5C\u53C2\u8003\u89C6\u9891\uFF08\u4F8B\u5982 popost video replication init <\u9879\u76EE> --reference ${path4}\uFF09`
13249
+ )
13250
+ };
13251
+ }
13252
+ return {
13253
+ fields: { videoMissing: outcome.missing },
13254
+ note: msg(
13255
+ `; the original video could not be fetched (${outcome.missing.code}): the bundle has the cover and text only; for shot, subtitle or sound analysis ask the user for the video file or a screen recording`,
13256
+ `\uFF1B\u6CA1\u80FD\u53D6\u5230\u5E16\u5B50\u539F\u89C6\u9891\uFF08${outcome.missing.code}\uFF09\uFF1Abundle \u53EA\u6709\u5C01\u9762\u548C\u6587\u5B57\uFF1B\u8981\u505A\u5206\u955C\u3001\u5B57\u5E55\u6216\u58F0\u97F3\u5206\u6790\uFF0C\u8BF7\u7528\u6237\u63D0\u4F9B\u89C6\u9891\u6587\u4EF6\u6216\u5F55\u5C4F`
13257
+ )
13258
+ };
13259
+ };
13260
+ succeededOutcome = async (rt, client2, task, call2, fallback) => {
13065
13261
  if (!task.post) throw badResponse(msg("the task succeeded but the answer has no post", "\u4EFB\u52A1\u5DF2\u6210\u529F\uFF0C\u4F46\u54CD\u5E94\u91CC\u6CA1\u6709 post"));
13066
13262
  const plan4 = planPost(task.post, fallback.url, fallback.note);
13067
13263
  const info = { id: task.id, status: task.status, created: task.created, chargedCredits: task.chargedCredits };
@@ -13088,7 +13284,8 @@ var init_link = __esm({
13088
13284
  const { saved, failure: failure4 } = await downloadPictures(rt, plan4.images, outDir2, retry);
13089
13285
  const images = saved.map((s) => s.path);
13090
13286
  if (failure4) return { exit: 1, body: { ok: false, code: "DOWNLOAD_FAILED", error: failure4, task: { id: task.id, status: task.status, chargedCredits: task.chargedCredits }, images, resume: resumeCommand(task.id, call2) } };
13091
- const bundle = buildBundle(rt, plan4, saved);
13287
+ const video = await videoPart(rt, client2, plan4, call2, outDir2, retry);
13288
+ const bundle = buildBundle(rt, plan4, saved, video.saved);
13092
13289
  const [valid, errors] = validateBundle(bundle);
13093
13290
  if (!valid) throw badResponse(msg(`the parsed result does not make a valid PostBundle: ${errors.join("; ")}`, `\u89E3\u6790\u7ED3\u679C\u65E0\u6CD5\u7EC4\u6210\u5408\u6CD5\u7684 PostBundle\uFF1A${errors.join("\uFF1B")}`));
13094
13291
  const bundlePath = rt.path.join(outDir2, "postbundle.json");
@@ -13098,8 +13295,8 @@ var init_link = __esm({
13098
13295
  "the post has no pictures: the bundle is marked missing_resources and cannot be built directly; the platform saved this post to My Inspirations",
13099
13296
  "\u5E16\u5B50\u91CC\u6CA1\u6709\u56FE\u7247\uFF1Abundle \u6807\u4E3A missing_resources\uFF0C\u4E0D\u80FD\u76F4\u63A5 build\uFF1B\u5E73\u53F0\u5DF2\u628A\u8FD9\u6761\u5E16\u5B50\u5B58\u5165\u300C\u6211\u7684\u7075\u611F\u300D"
13100
13297
  );
13101
- const post = { platform: plan4.platform, title: plan4.title, sourceUrl: plan4.sourceUrl, imageCount: saved.length, ...plan4.inspirationId ? { inspirationId: plan4.inspirationId } : {} };
13102
- return { exit: 0, body: { ok: true, task: info, bundle: bundlePath, images, post, next: `popost validate --file ${file} && popost import --file ${file}`, note } };
13298
+ const post = { platform: plan4.platform, ...plan4.kind ? { kind: plan4.kind } : {}, title: plan4.title, sourceUrl: plan4.sourceUrl, imageCount: saved.length, ...plan4.inspirationId ? { inspirationId: plan4.inspirationId } : {} };
13299
+ 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 } };
13103
13300
  };
13104
13301
  finish2 = async (rt, client2, state, first, call2, fallback) => {
13105
13302
  const id2 = state.id;
@@ -13114,7 +13311,7 @@ var init_link = __esm({
13114
13311
  );
13115
13312
  return unfinishedOutcome("POLL_FAILED", what, id2, waited.task, call2);
13116
13313
  }
13117
- return waited.task.status === "failed" ? failedOutcome(waited.task) : succeededOutcome(rt, waited.task, call2, fallback);
13314
+ return waited.task.status === "failed" ? failedOutcome(waited.task) : succeededOutcome(rt, client2, waited.task, call2, fallback);
13118
13315
  };
13119
13316
  failureOf5 = (error2) => {
13120
13317
  if (error2 instanceof CliReject) return { code: "CONFIG", exit: error2.code, message: error2.message };
@@ -13196,7 +13393,7 @@ var init_link = __esm({
13196
13393
  });
13197
13394
 
13198
13395
  // src/providers/pricing.ts
13199
- var pricingClient, queryLinkPrice;
13396
+ var pricingClient, queryLinkPrice, queryLinkPlatforms;
13200
13397
  var init_pricing = __esm({
13201
13398
  "src/providers/pricing.ts"() {
13202
13399
  "use strict";
@@ -13220,6 +13417,14 @@ var init_pricing = __esm({
13220
13417
  );
13221
13418
  return { creditsPerRequest: link.creditsPerRequest, balance: body.balance, sufficient: body.balance >= Number(link.creditsPerRequest), unit: "credits", source: `${client2.baseUrl}/pricing` };
13222
13419
  };
13420
+ queryLinkPlatforms = async (client2) => {
13421
+ const body = await client2.request("GET", "/links/platforms", { anonymous: true });
13422
+ const list7 = isRecord(body) && Array.isArray(body.platforms) ? body.platforms : null;
13423
+ const valid = (p) => isRecord(p) && typeof p.id === "string" && typeof p.name === "string" && typeof p.video === "boolean";
13424
+ if (!list7 || !list7.length || !list7.every(valid))
13425
+ throw new PopostApiError(msg("popost.ai answered the platform list in an unexpected form", "popost.ai \u8FD4\u56DE\u7684\u5E73\u53F0\u5217\u8868\u683C\u5F0F\u4E0D\u5BF9"), { code: "BAD_RESPONSE" });
13426
+ return list7.map(({ id: id2, name, video }) => ({ id: id2, name, video }));
13427
+ };
13223
13428
  }
13224
13429
  });
13225
13430
 
@@ -13628,12 +13833,60 @@ var init_usage = __esm({
13628
13833
  }
13629
13834
  });
13630
13835
 
13836
+ // src/commands/link-platforms.ts
13837
+ var nameOf, listText, linkPlatforms;
13838
+ var init_link_platforms = __esm({
13839
+ "src/commands/link-platforms.ts"() {
13840
+ "use strict";
13841
+ init_util();
13842
+ init_i18n();
13843
+ init_errors3();
13844
+ init_pricing();
13845
+ init_post_bundle();
13846
+ nameOf = (p) => {
13847
+ const known2 = PLATFORMS.includes(p.id) ? PLATFORM_NAMES[p.id] : null;
13848
+ return known2 ? known2[currentLang()] : p.name;
13849
+ };
13850
+ listText = (names) => names.length < 2 ? names.join("") : msg(`${names.slice(0, -1).join(", ")} and ${names.at(-1)}`, `${names.slice(0, -1).join("\u3001")}\u548C${names.at(-1)}`);
13851
+ linkPlatforms = async (rt, config3) => {
13852
+ try {
13853
+ const platforms = await queryLinkPlatforms(await pricingClient(rt, config3));
13854
+ const coverOnly = platforms.filter((p) => !p.video).map(nameOf);
13855
+ printJson(rt, {
13856
+ ok: true,
13857
+ platforms,
13858
+ text: listText(platforms.map(nameOf)),
13859
+ ...coverOnly.length ? { coverOnly: listText(coverOnly) } : {},
13860
+ next: msg(
13861
+ "These are the platforms popost.ai parses now: name exactly these when you tell the user which links work, never a list from memory or a README. For the coverOnly ones a video post gives its cover and text, not the video file.",
13862
+ "\u8FD9\u662F popost.ai \u5F53\u524D\u80FD\u89E3\u6790\u7684\u5E73\u53F0\uFF1A\u544A\u8BC9\u7528\u6237\u652F\u6301\u54EA\u4E9B\u94FE\u63A5\u65F6\u5C31\u7528\u8FD9\u4EFD\u5217\u8868\uFF0C\u4E0D\u8981\u51ED\u8BB0\u5FC6\u6216 README \u91CC\u7684\u5217\u8868\u3002coverOnly \u91CC\u7684\u5E73\u53F0\uFF0C\u89C6\u9891\u5E16\u53EA\u80FD\u62FF\u5230\u5C01\u9762\u548C\u6587\u5B57\uFF0C\u62FF\u4E0D\u5230\u89C6\u9891\u6587\u4EF6\u3002"
13863
+ )
13864
+ }, true);
13865
+ return 0;
13866
+ } catch (error2) {
13867
+ if (!(error2 instanceof PopostApiError || error2 instanceof CliReject)) throw error2;
13868
+ printJson(rt, {
13869
+ ok: false,
13870
+ code: error2 instanceof PopostApiError ? error2.code : "CONFIG",
13871
+ error: error2.message,
13872
+ next: msg(
13873
+ "The live list could not be read. Do not name platforms from memory; if the user needs an answer now, give this CLI version's list (known) and say it may be out of date.",
13874
+ "\u6CA1\u80FD\u8BFB\u5230\u5B9E\u65F6\u5217\u8868\u3002\u4E0D\u8981\u51ED\u8BB0\u5FC6\u5217\u5E73\u53F0\uFF1B\u7528\u6237\u73B0\u5728\u5C31\u8981\u7B54\u6848\u65F6\uFF0C\u7ED9\u51FA\u8FD9\u4E2A CLI \u7248\u672C\u5DF2\u77E5\u7684\u5217\u8868\uFF08known\uFF09\uFF0C\u5E76\u8BF4\u660E\u5B83\u53EF\u80FD\u4E0D\u662F\u6700\u65B0\u7684\u3002"
13875
+ ),
13876
+ known: listText(PLATFORMS.map((p) => PLATFORM_NAMES[p][currentLang()]))
13877
+ }, true);
13878
+ return 1;
13879
+ }
13880
+ };
13881
+ }
13882
+ });
13883
+
13631
13884
  // src/commands/link.ts
13632
13885
  var link_exports = {};
13633
13886
  __export(link_exports, {
13634
13887
  main: () => main16
13635
13888
  });
13636
- var out, timeout, noDownload, config2, main16;
13889
+ var out, timeout, noDownload, noVideo, config2, main16;
13637
13890
  var init_link2 = __esm({
13638
13891
  "src/commands/link.ts"() {
13639
13892
  "use strict";
@@ -13641,6 +13894,7 @@ var init_link2 = __esm({
13641
13894
  init_i18n();
13642
13895
  init_post_bundle();
13643
13896
  init_link();
13897
+ init_link_platforms();
13644
13898
  init_cli_args();
13645
13899
  init_task();
13646
13900
  out = () => ({
@@ -13667,10 +13921,28 @@ var init_link2 = __esm({
13667
13921
  "\u4E0D\u4E0B\u8F7D\u56FE\u7247\uFF0C\u53EA\u6253\u5370\u5E16\u5B50\u5185\u5BB9\u548C\u56FE\u7247\u5730\u5740\uFF08\u5730\u5740\u662F\u77ED\u671F\u7B7E\u540D\u94FE\u63A5\uFF0C\u5F88\u5FEB\u5931\u6548\uFF09"
13668
13922
  )
13669
13923
  });
13924
+ noVideo = () => ({
13925
+ flag: "--no-video",
13926
+ kind: "flag",
13927
+ help: msg(
13928
+ "for a video post, keep the cover and text only: do not fetch the original video file",
13929
+ "\u89C6\u9891\u5E16\u53EA\u4FDD\u7559\u5C01\u9762\u548C\u6587\u5B57\uFF0C\u4E0D\u53D6\u539F\u89C6\u9891\u6587\u4EF6"
13930
+ )
13931
+ });
13670
13932
  config2 = () => ({ flag: "--config", help: msg("private config JSON (popost.baseUrl / popost.auth.envVar)", "\u79C1\u6709\u914D\u7F6E JSON\uFF08popost.baseUrl / popost.auth.envVar\uFF09") });
13671
13933
  main16 = (argv, rt) => runSubcommand2(
13672
13934
  "popost link",
13673
13935
  {
13936
+ platforms: {
13937
+ spec: {
13938
+ description: msg(
13939
+ "List the platforms whose links popost.ai parses now, read from popost.ai: name these when telling the user which links work. Free, no account needed.",
13940
+ "\u5217\u51FA popost.ai \u5F53\u524D\u80FD\u89E3\u6790\u94FE\u63A5\u7684\u5E73\u53F0\uFF08\u4ECE popost.ai \u5B9E\u65F6\u8BFB\u53D6\uFF09\uFF1A\u544A\u8BC9\u7528\u6237\u652F\u6301\u54EA\u4E9B\u94FE\u63A5\u65F6\u7528\u8FD9\u4EFD\u5217\u8868\u3002\u514D\u8D39\uFF0C\u4E0D\u9700\u8981\u8FDE\u63A5\u8D26\u6237\u3002"
13941
+ ),
13942
+ options: [config2()]
13943
+ },
13944
+ run: (a) => linkPlatforms(rt, a.string("config"))
13945
+ },
13674
13946
  quote: {
13675
13947
  spec: {
13676
13948
  description: msg("Read the live parsing tariff and balance without creating a task or charging.", "\u67E5\u8BE2\u5B9E\u65F6\u7684\u94FE\u63A5\u89E3\u6790\u4EF7\u683C\u548C\u4F59\u989D\uFF0C\u4E0D\u5EFA\u4EFB\u52A1\u3001\u4E0D\u6263\u79EF\u5206\u3002"),
@@ -13681,8 +13953,8 @@ var init_link2 = __esm({
13681
13953
  parse: {
13682
13954
  spec: {
13683
13955
  description: msg(
13684
- `Have popost.ai parse a social post link (${platformNameList("or")}; YouTube, Bilibili and WeChat Channels video links provide the cover and post details when available), wait for the result, download the pictures and write a PostBundle (postbundle.v1). Get the live price with link quote first, then submit with --confirm --max-credits N, the ceiling the user authorized; the actual net charge is task.chargedCredits; a link already saved is reused without a new charge. The parsed post is also saved to My Inspirations.`,
13685
- `\u8BA9 popost.ai \u89E3\u6790\u4E00\u6761\u793E\u5A92\u5E16\u5B50\u94FE\u63A5\uFF08${platformNameList("or")}\uFF1BYouTube\u3001\u54D4\u54E9\u54D4\u54E9\u548C\u5FAE\u4FE1\u89C6\u9891\u53F7\u94FE\u63A5\u53EF\u4FDD\u5B58\u53EF\u7528\u7684\u5C01\u9762\u548C\u5E16\u5B50\u4FE1\u606F\uFF09\uFF0C\u7B49\u5F85\u7ED3\u679C\uFF0C\u628A\u56FE\u7247\u4E0B\u8F7D\u5230\u672C\u5730\u5E76\u5199\u51FA PostBundle\uFF08postbundle.v1\uFF09\u3002\u5148 link quote \u67E5\u8BE2\u52A8\u6001\u4EF7\u683C\uFF0C\u518D\u5E26 --confirm --max-credits N \u6309\u5DF2\u6388\u6743\u4E0A\u9650\u63D0\u4EA4\uFF1B\u5B9E\u9645\u51C0\u6263\u89C1 task.chargedCredits\uFF1B\u5DF2\u4FDD\u5B58\u8FC7\u7684\u94FE\u63A5\u76F4\u63A5\u590D\u7528\u3001\u4E0D\u518D\u6263\u3002\u89E3\u6790\u7ED3\u679C\u540C\u65F6\u5B58\u5165\u300C\u6211\u7684\u7075\u611F\u300D\u3002`
13956
+ `Have popost.ai parse a social post link (${platformNameList("or")}), wait for the result, download the pictures and write a PostBundle (postbundle.v1). A video post also gets its original video file (video.mp4, free) for shot, subtitle and sound analysis; YouTube, Bilibili and WeChat Channels give the cover and post details only. Get the live price with link quote first, then submit with --confirm --max-credits N, the ceiling the user authorized; the actual net charge is task.chargedCredits; a link already saved is reused without a new charge. The parsed post is also saved to My Inspirations.`,
13957
+ `\u8BA9 popost.ai \u89E3\u6790\u4E00\u6761\u793E\u5A92\u5E16\u5B50\u94FE\u63A5\uFF08${platformNameList("or")}\uFF09\uFF0C\u7B49\u5F85\u7ED3\u679C\uFF0C\u628A\u56FE\u7247\u4E0B\u8F7D\u5230\u672C\u5730\u5E76\u5199\u51FA PostBundle\uFF08postbundle.v1\uFF09\u3002\u89C6\u9891\u5E16\u8FD8\u4F1A\u53D6\u56DE\u539F\u89C6\u9891\u6587\u4EF6\uFF08video.mp4\uFF0C\u4E0D\u53E6\u6263\u79EF\u5206\uFF09\uFF0C\u7528\u4E8E\u5206\u955C\u3001\u5B57\u5E55\u548C\u58F0\u97F3\u5206\u6790\uFF1BYouTube\u3001\u54D4\u54E9\u54D4\u54E9\u548C\u5FAE\u4FE1\u89C6\u9891\u53F7\u53EA\u6709\u5C01\u9762\u548C\u5E16\u5B50\u4FE1\u606F\u3002\u5148 link quote \u67E5\u8BE2\u52A8\u6001\u4EF7\u683C\uFF0C\u518D\u5E26 --confirm --max-credits N \u6309\u5DF2\u6388\u6743\u4E0A\u9650\u63D0\u4EA4\uFF1B\u5B9E\u9645\u51C0\u6263\u89C1 task.chargedCredits\uFF1B\u5DF2\u4FDD\u5B58\u8FC7\u7684\u94FE\u63A5\u76F4\u63A5\u590D\u7528\u3001\u4E0D\u518D\u6263\u3002\u89E3\u6790\u7ED3\u679C\u540C\u65F6\u5B58\u5165\u300C\u6211\u7684\u7075\u611F\u300D\u3002`
13686
13958
  ),
13687
13959
  positionals: [{ name: "url", help: msg("the post link (http/https)", "\u5E16\u5B50\u94FE\u63A5\uFF08http/https\uFF09") }],
13688
13960
  options: [
@@ -13692,12 +13964,13 @@ var init_link2 = __esm({
13692
13964
  out(),
13693
13965
  timeout(),
13694
13966
  noDownload(),
13967
+ noVideo(),
13695
13968
  { flag: "--dry-run", kind: "flag", help: msg("offline, no key, no charge: only show the requests that would be sent", "\u4E0D\u8054\u7F51\u3001\u4E0D\u9700\u8981\u5BC6\u94A5\u3001\u4E0D\u6263\u79EF\u5206\uFF0C\u53EA\u5C55\u793A\u5C06\u53D1\u51FA\u7684\u8BF7\u6C42") },
13696
13969
  config2()
13697
13970
  ]
13698
13971
  },
13699
13972
  // Into a project (--out inside one): the parse is charged under the project's task (providers/task.ts).
13700
- run: async (a) => parseLink(await aroundPath(rt, a.string("out")), { url: a.req("url"), note: a.string("note"), out: a.string("out"), timeoutSec: a.number("timeout"), noDownload: a.flag("no-download"), dryRun: a.flag("dry-run"), confirm: a.flag("confirm"), maxCredits: a.number("max-credits"), config: a.string("config") })
13973
+ run: async (a) => parseLink(await aroundPath(rt, a.string("out")), { url: a.req("url"), note: a.string("note"), out: a.string("out"), timeoutSec: a.number("timeout"), noDownload: a.flag("no-download"), noVideo: a.flag("no-video"), dryRun: a.flag("dry-run"), confirm: a.flag("confirm"), maxCredits: a.number("max-credits"), config: a.string("config") })
13701
13974
  },
13702
13975
  status: {
13703
13976
  spec: {
@@ -13706,9 +13979,9 @@ var init_link2 = __esm({
13706
13979
  "\u7EE7\u7EED\u7B49\u5F85\u4E00\u4E2A\u5DF2\u5B58\u5728\u7684\u89E3\u6790\u4EFB\u52A1\u5E76\u4E0B\u8F7D\u7ED3\u679C\uFF08\u7528\u4E8E link parse \u8D85\u65F6\u6216\u88AB\u6253\u65AD\u4E4B\u540E\uFF09\u3002\u4E0D\u65B0\u5EFA\u4EFB\u52A1\u3001\u4E0D\u6263\u79EF\u5206\u3002"
13707
13980
  ),
13708
13981
  positionals: [{ name: "task-id", help: msg("the task.id printed by link parse", "link parse \u8F93\u51FA\u7684 task.id") }],
13709
- options: [out(), timeout(), noDownload(), config2()]
13982
+ options: [out(), timeout(), noDownload(), noVideo(), config2()]
13710
13983
  },
13711
- run: (a) => linkStatus(rt, { taskId: a.req("task-id"), out: a.string("out"), timeoutSec: a.number("timeout"), noDownload: a.flag("no-download"), config: a.string("config") })
13984
+ run: (a) => linkStatus(rt, { taskId: a.req("task-id"), out: a.string("out"), timeoutSec: a.number("timeout"), noDownload: a.flag("no-download"), noVideo: a.flag("no-video"), config: a.string("config") })
13712
13985
  }
13713
13986
  },
13714
13987
  argv,
@@ -13871,8 +14144,8 @@ var init_browser = __esm({
13871
14144
  "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
13872
14145
  "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe"
13873
14146
  ];
13874
- findChromium = (env) => {
13875
- const explicit = env.POPOST_CHROME || env.PLAYWRIGHT_CHROMIUM;
14147
+ findChromium = (env2) => {
14148
+ const explicit = env2.POPOST_CHROME || env2.PLAYWRIGHT_CHROMIUM;
13876
14149
  if (explicit) return existsSync(explicit) ? explicit : null;
13877
14150
  return [...SYSTEM_BROWSERS, ...playwrightCaches()].find((p) => existsSync(p)) ?? null;
13878
14151
  };
@@ -13915,8 +14188,8 @@ var init_browser = __esm({
13915
14188
  clearTimeout(timer);
13916
14189
  }
13917
14190
  };
13918
- launchChromium = async (env, profile2 = "pages", o = {}) => {
13919
- const executablePath = findChromium(env);
14191
+ launchChromium = async (env2, profile2 = "pages", o = {}) => {
14192
+ const executablePath = findChromium(env2);
13920
14193
  if (!executablePath)
13921
14194
  throw new BrowserUnavailableError(
13922
14195
  msg(
@@ -15665,9 +15938,9 @@ var init_check2 = __esm({
15665
15938
  const named = namedFiles(project);
15666
15939
  const all = [.../* @__PURE__ */ new Set([...named.files, ...named.scenes])];
15667
15940
  const found = await Promise.all(all.map(async (f) => await rt.fs.stat(rt.path.resolve(root, f)) !== null ? [f] : []));
15668
- const present2 = new Set(found.flat());
15669
- const scenes = await Promise.all([...new Set(named.scenes)].filter((f) => present2.has(f)).map(async (f) => [f, await rt.fs.readText(rt.path.resolve(root, f))]));
15670
- return { dir, present: present2, scenes: Object.fromEntries(scenes) };
15941
+ const present3 = new Set(found.flat());
15942
+ const scenes = await Promise.all([...new Set(named.scenes)].filter((f) => present3.has(f)).map(async (f) => [f, await rt.fs.readText(rt.path.resolve(root, f))]));
15943
+ return { dir, present: present3, scenes: Object.fromEntries(scenes) };
15671
15944
  };
15672
15945
  checkMaterialFiles = (project, files) => project.materials.flatMap((m, i) => ["file", "words"].flatMap((key2) => {
15673
15946
  const at7 = "materials[" + i + "]." + key2;
@@ -16317,10 +16590,10 @@ var init_footage2 = __esm({
16317
16590
  const { fs, path: path4 } = rt;
16318
16591
  await fs.mkdir(job.dir);
16319
16592
  const have = new Set(await fs.readdir(job.dir));
16320
- const missing3 = job.frames.filter((f) => !have.has(frameName(f)));
16321
- if (missing3.length === 0) return { extracted: 0, reused: job.frames.length };
16322
- const lo = missing3[0] ?? 0;
16323
- const hi = missing3[missing3.length - 1] ?? 0;
16593
+ const missing4 = job.frames.filter((f) => !have.has(frameName(f)));
16594
+ if (missing4.length === 0) return { extracted: 0, reused: job.frames.length };
16595
+ const lo = missing4[0] ?? 0;
16596
+ const hi = missing4[missing4.length - 1] ?? 0;
16324
16597
  const tmp = path4.join(job.dir, ".extract-" + rt.randomUUID());
16325
16598
  await fs.mkdir(tmp);
16326
16599
  try {
@@ -16347,11 +16620,11 @@ var init_footage2 = __esm({
16347
16620
  path4.join(tmp, "%0" + FRAME_DIGITS + "d.png")
16348
16621
  ]);
16349
16622
  const written2 = new Set(await fs.readdir(tmp));
16350
- const absent = missing3.filter((f) => !written2.has(frameName(f - lo)));
16351
- if (absent.length > 0)
16352
- throw new Error("Extracting frames " + lo + ".." + hi + " of " + job.file + " gave " + written2.size + " pictures; frame " + absent[0] + " is missing. The file may be damaged or shorter than its header says; re-encode it with ffmpeg.");
16353
- for (const f of missing3) await fs.rename(path4.join(tmp, frameName(f - lo)), path4.join(job.dir, frameName(f)));
16354
- return { extracted: missing3.length, reused: job.frames.length - missing3.length };
16623
+ const absent2 = missing4.filter((f) => !written2.has(frameName(f - lo)));
16624
+ if (absent2.length > 0)
16625
+ throw new Error("Extracting frames " + lo + ".." + hi + " of " + job.file + " gave " + written2.size + " pictures; frame " + absent2[0] + " is missing. The file may be damaged or shorter than its header says; re-encode it with ffmpeg.");
16626
+ for (const f of missing4) await fs.rename(path4.join(tmp, frameName(f - lo)), path4.join(job.dir, frameName(f)));
16627
+ return { extracted: missing4.length, reused: job.frames.length - missing4.length };
16355
16628
  } finally {
16356
16629
  await fs.rm(tmp);
16357
16630
  }
@@ -17532,10 +17805,10 @@ var init_fits = __esm({
17532
17805
  const isNew = mids.map((M) => sig.map((k) => blockDiff(M, B, k) < blockDiff(M, A, k)));
17533
17806
  const pure = mids.map((M) => sig.filter((k) => Math.min(blockDiff(M, A, k), blockDiff(M, B, k)) < 0.35 * dab[k]).length / sig.length);
17534
17807
  const share2 = isNew.map((v) => v.filter(Boolean).length / sig.length);
17535
- const shared2 = (i) => share2[i] > 0.15 && share2[i] < 0.85;
17536
- const central = pure.filter((_, i) => shared2(i));
17808
+ const shared3 = (i) => share2[i] > 0.15 && share2[i] < 0.85;
17809
+ const central = pure.filter((_, i) => shared3(i));
17537
17810
  if (!central.length) return void 0;
17538
- const left = mids.flatMap((M, i) => shared2(i) ? [sig.reduce((n, k) => n + Math.min(blockDiff(M, A, k), blockDiff(M, B, k)) / dab[k], 0) / sig.length] : []);
17811
+ const left = mids.flatMap((M, i) => shared3(i) ? [sig.reduce((n, k) => n + Math.min(blockDiff(M, A, k), blockDiff(M, B, k)) / dab[k], 0) / sig.length] : []);
17539
17812
  const purity = median2(central);
17540
17813
  if (purity < 0.5 || share2[share2.length - 1] - share2[0] < 0.3) return void 0;
17541
17814
  let flipsBack = 0;
@@ -20126,13 +20399,13 @@ var init_kind = __esm({
20126
20399
  textFacts = (s, cues, step2) => {
20127
20400
  if (!cues) return { page: void 0, design: void 0, filmed: void 0 };
20128
20401
  const mine = cues.filter((c) => shownIn(c, s, step2));
20129
- const own2 = mine.filter((c) => c.role === "in-picture");
20402
+ const own3 = mine.filter((c) => c.role === "in-picture");
20130
20403
  const laid = mine.filter((c) => c.role === "title" || c.role === "label");
20131
20404
  const largest2 = Math.max(0, ...laid.map((c) => c.size));
20132
20405
  return {
20133
- page: own2.length >= MANY_LINES ? plural2(own2.length, "small line", "small lines") + " of text, median height " + pct(median3(own2.map((c) => c.size))) : void 0,
20134
- design: laid.length >= 1 && laid.length <= FEW_LINES && largest2 >= LARGE && own2.length < MANY_LINES ? plural2(laid.length, "large line", "large lines") + " of text, up to " + pct(largest2) + " of the height" : void 0,
20135
- filmed: own2.length + laid.length <= 2 && largest2 < LARGE ? "little text (" + plural2(own2.length + laid.length, "line", "lines") + ")" : void 0
20406
+ page: own3.length >= MANY_LINES ? plural2(own3.length, "small line", "small lines") + " of text, median height " + pct(median3(own3.map((c) => c.size))) : void 0,
20407
+ design: laid.length >= 1 && laid.length <= FEW_LINES && largest2 >= LARGE && own3.length < MANY_LINES ? plural2(laid.length, "large line", "large lines") + " of text, up to " + pct(largest2) + " of the height" : void 0,
20408
+ filmed: own3.length + laid.length <= 2 && largest2 < LARGE ? "little text (" + plural2(own3.length + laid.length, "line", "lines") + ")" : void 0
20136
20409
  };
20137
20410
  };
20138
20411
  groundFacts = (s) => {
@@ -20430,14 +20703,14 @@ var init_check3 = __esm({
20430
20703
  measuredLabel = (b) => [b.kind, b.mode, b.direction, b.via ? "via " + b.via : ""].filter(Boolean).join(" ");
20431
20704
  coverageProblems = ({ r, m, at: at7 }) => {
20432
20705
  const fps = m.source.fps, s22 = (f) => (f / fps).toFixed(2);
20433
- const missing3 = m.shots.filter((s) => !r.present.includes(s.index + 1)).map((s) => error("shots", "Shot " + (s.index + 1) + " (" + s22(s.start) + "-" + s22(s.end) + " s) has no entry.", "Open " + shotSheetFile(s.index + 1) + ' and add {"shot": ' + (s.index + 1) + ', "time": [' + s22(s.start) + ", " + s22(s.end) + '], "layout": "...", "layers": [...]} for it.'));
20706
+ const missing4 = m.shots.filter((s) => !r.present.includes(s.index + 1)).map((s) => error("shots", "Shot " + (s.index + 1) + " (" + s22(s.start) + "-" + s22(s.end) + " s) has no entry.", "Open " + shotSheetFile(s.index + 1) + ' and add {"shot": ' + (s.index + 1) + ', "time": [' + s22(s.start) + ", " + s22(s.end) + '], "layout": "...", "layers": [...]} for it.'));
20434
20707
  const extra2 = r.present.filter((n) => n > m.shots.length).map((n) => error(at7(n) + ".shot", "There is no shot " + n + ": the measurement has " + m.shots.length + ".", "Remove the entry, or give it the number of the shot it describes."));
20435
20708
  const times = r.elements.shots.flatMap((s) => {
20436
20709
  const ms = m.shots[s.shot - 1];
20437
20710
  if (!ms || Math.abs(s.time[0] - ms.start / fps) <= TIME_SLACK && Math.abs(s.time[1] - ms.end / fps) <= TIME_SLACK) return [];
20438
20711
  return [warning(at7(s.shot) + ".time", "Shot " + s.shot + " is " + s22(ms.start) + "-" + s22(ms.end) + " s in the measurement; its entry says " + s.time[0] + "-" + s.time[1] + " s.", "Copy the measured time, [" + s22(ms.start) + ", " + s22(ms.end) + ']: entries go by the measured shots. Where the frames show a change the measurement missed, say so in "rebuild".')];
20439
20712
  });
20440
- return [...missing3, ...extra2, ...times];
20713
+ return [...missing4, ...extra2, ...times];
20441
20714
  };
20442
20715
  transitionProblems2 = ({ r, m, at: at7 }) => r.elements.shots.flatMap((s) => {
20443
20716
  const here = at7(s.shot) + ".transitionIn", t = s.transitionIn;
@@ -20514,9 +20787,9 @@ var init_check3 = __esm({
20514
20787
  if (byNumber(end)?.sameEffectAsNext)
20515
20788
  out2.push(warning(at7(end) + ".sameEffectAsNext", "Shot " + end + " is the last one re-made, and its entry says an animation runs on into the next.", 'Leave "sameEffectAsNext" out of the last shot.'));
20516
20789
  const last = byNumber(m.shots.length);
20517
- const own2 = last && !last.drop ? last.layers.filter((l) => l.kind !== "ground") : [];
20518
- const theirs = own2.filter((l) => isDropped(l.role));
20519
- if (last && own2.length && theirs.length * 2 > own2.length)
20790
+ const own3 = last && !last.drop ? last.layers.filter((l) => l.kind !== "ground") : [];
20791
+ const theirs = own3.filter((l) => isDropped(l.role));
20792
+ if (last && own3.length && theirs.length * 2 > own3.length)
20520
20793
  out2.push(warning(
20521
20794
  at7(last.shot),
20522
20795
  "The last shot (" + last.shot + ") is made mostly of the platform's or the author's layers (" + theirs.map((l) => l.id).join(", ") + "): an end card, which a re-make never copies.",
@@ -20791,9 +21064,9 @@ var init_tool = __esm({
20791
21064
  lastLines = (stderr, n) => stderr.trim().split("\n").slice(-n).join(" | ");
20792
21065
  TOOL_THREADS = 4;
20793
21066
  toolEnv = (rt, threads) => {
20794
- const own2 = rt.env.POPOST_TOOL_THREADS?.trim();
21067
+ const own3 = rt.env.POPOST_TOOL_THREADS?.trim();
20795
21068
  const n = threads ?? Math.min(TOOL_THREADS, cpuBudgetOf(rt).cpus);
20796
- const budget2 = own2 || String(Math.max(1, Math.floor(n)));
21069
+ const budget2 = own3 || String(Math.max(1, Math.floor(n)));
20797
21070
  return {
20798
21071
  POPOST_TOOL_THREADS: budget2,
20799
21072
  ...Object.fromEntries(["OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS"].map((name) => [name, rt.env[name]?.trim() || budget2]))
@@ -21569,7 +21842,7 @@ var init_measure2 = __esm({
21569
21842
  envelopeRate = (rate) => rate / HOP;
21570
21843
  onsetEnvelope = (pcm) => {
21571
21844
  const frames = Math.max(0, Math.floor((pcm.length - FRAME) / HOP) + 1);
21572
- const env = new Float32Array(frames);
21845
+ const env2 = new Float32Array(frames);
21573
21846
  let prev = new Float64Array(FRAME / 2), cur = new Float64Array(FRAME / 2);
21574
21847
  for (let i = 0; i < frames; i++) {
21575
21848
  spectrum(pcm, i * HOP, cur);
@@ -21580,10 +21853,10 @@ var init_measure2 = __esm({
21580
21853
  const d = v - prev[k];
21581
21854
  if (d > 0) flux += d;
21582
21855
  }
21583
- env[i] = i === 0 ? 0 : flux;
21856
+ env2[i] = i === 0 ? 0 : flux;
21584
21857
  [prev, cur] = [cur, prev];
21585
21858
  }
21586
- return env;
21859
+ return env2;
21587
21860
  };
21588
21861
  ONSET_AT = 0.86;
21589
21862
  PEAK_HOPS = 3;
@@ -21597,19 +21870,19 @@ var init_measure2 = __esm({
21597
21870
  const sorted = Float32Array.from(values).sort();
21598
21871
  return sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))] ?? 0;
21599
21872
  };
21600
- onsetsOf = (env, rate) => {
21601
- const fps = envelopeRate(rate), top2 = percentile(env, 0.995);
21873
+ onsetsOf = (env2, rate) => {
21874
+ const fps = envelopeRate(rate), top2 = percentile(env2, 0.995);
21602
21875
  if (!(top2 >= ONSET_FLOOR)) return [];
21603
21876
  const around3 = Math.max(1, Math.round(AROUND_SECONDS * fps));
21604
- const sums = new Float64Array(env.length + 1);
21605
- for (let i = 0; i < env.length; i++) sums[i + 1] = sums[i] + env[i];
21877
+ const sums = new Float64Array(env2.length + 1);
21878
+ for (let i = 0; i < env2.length; i++) sums[i + 1] = sums[i] + env2[i];
21606
21879
  const out2 = [];
21607
- for (let i = 1; i < env.length - 1; i++) {
21608
- const v = env[i];
21880
+ for (let i = 1; i < env2.length - 1; i++) {
21881
+ const v = env2[i];
21609
21882
  let peak = true;
21610
- for (let j = Math.max(0, i - PEAK_HOPS); j <= Math.min(env.length - 1, i + PEAK_HOPS) && peak; j++) if (env[j] > v || env[j] === v && j < i) peak = false;
21883
+ for (let j = Math.max(0, i - PEAK_HOPS); j <= Math.min(env2.length - 1, i + PEAK_HOPS) && peak; j++) if (env2[j] > v || env2[j] === v && j < i) peak = false;
21611
21884
  if (!peak) continue;
21612
- const a = Math.max(0, i - around3), b = Math.min(env.length, i + around3 + 1);
21885
+ const a = Math.max(0, i - around3), b = Math.min(env2.length, i + around3 + 1);
21613
21886
  const mean5 = (sums[b] - sums[a]) / (b - a);
21614
21887
  if (v < ONSET_FLOOR || v < LOCAL_FACTOR * mean5 + GLOBAL_SHARE * top2) continue;
21615
21888
  const t = (i * HOP + ONSET_AT * FRAME) / rate;
@@ -21622,13 +21895,13 @@ var init_measure2 = __esm({
21622
21895
  }
21623
21896
  return out2;
21624
21897
  };
21625
- tempoOf = (env, rate) => {
21898
+ tempoOf = (env2, rate) => {
21626
21899
  const fps = envelopeRate(rate);
21627
- if (env.length < 4 * fps) return void 0;
21900
+ if (env2.length < 4 * fps) return void 0;
21628
21901
  let mean5 = 0;
21629
- for (const v of env) mean5 += v;
21630
- mean5 /= env.length;
21631
- const sharp = Float64Array.from(env, (v) => v >= ONSET_FLOOR ? Math.max(0, v - mean5) : 0);
21902
+ for (const v of env2) mean5 += v;
21903
+ mean5 /= env2.length;
21904
+ const sharp = Float64Array.from(env2, (v) => v >= ONSET_FLOOR ? Math.max(0, v - mean5) : 0);
21632
21905
  const x = Float64Array.from(sharp, (_v, i) => ((sharp[i - 2] ?? 0) + 2 * (sharp[i - 1] ?? 0) + 3 * (sharp[i] ?? 0) + 2 * (sharp[i + 1] ?? 0) + (sharp[i + 2] ?? 0)) / 9);
21633
21906
  let zero = 0;
21634
21907
  for (const v of x) zero += v * v;
@@ -21698,9 +21971,9 @@ var init_measure2 = __esm({
21698
21971
  const seconds7 = pcm.length / rate;
21699
21972
  const db = levelCurve(pcm, rate);
21700
21973
  const silences = silencesOf(pcm, rate);
21701
- const env = onsetEnvelope(pcm);
21702
- const onsets = onsetsOf(env, rate);
21703
- const tempo2 = onsets.length >= 4 ? tempoOf(env, rate) : void 0;
21974
+ const env2 = onsetEnvelope(pcm);
21975
+ const onsets = onsetsOf(env2, rate);
21976
+ const tempo2 = onsets.length >= 4 ? tempoOf(env2, rate) : void 0;
21704
21977
  return {
21705
21978
  seconds: r23(seconds7),
21706
21979
  level: { step: 0.5, db, peakDb: db.length ? Math.max(...db) : FLOOR_DB, meanDb: r1(rmsDb(pcm)) },
@@ -25301,8 +25574,8 @@ var init_speech2 = __esm({
25301
25574
  const within = (c, m) => words.filter((_w, k) => (mids[k] ?? 0) >= c.start - m && (mids[k] ?? 0) < c.end + m);
25302
25575
  const marks = track.cues.filter((c) => c.role === "watermark").map((c) => letters(c.text));
25303
25576
  const likeMark = (c) => {
25304
- const own2 = letters(c.text);
25305
- return marks.some((m) => sameText(m, own2) && Math.min(m.length, own2.length) >= MARK_LENGTH * Math.max(m.length, own2.length));
25577
+ const own3 = letters(c.text);
25578
+ return marks.some((m) => sameText(m, own3) && Math.min(m.length, own3.length) >= MARK_LENGTH * Math.max(m.length, own3.length));
25306
25579
  };
25307
25580
  const seen = track.cues.map((c) => {
25308
25581
  const silent = !within(c, Math.round(QUIET_SECONDS * fps)).length;
@@ -26266,10 +26539,10 @@ var init_describe = __esm({
26266
26539
  const x0 = Math.min(...bar.map((c) => c.box[0])), x1 = Math.max(...bar.map((c) => c.box[0] + c.box[2])), y0 = Math.min(...bar.map((c) => c.box[1])), y1 = Math.max(...bar.map((c) => c.box[1] + c.box[3]));
26267
26540
  if (bar.length) L.push("- bar (through the video, REFERENCE.md) " + bar.map((c) => quote5(c.text)).join(" ") + ", " + where([x0, y0, x1 - x0, y1 - y0]) + ", height " + pct5(bar[0]?.size ?? 0) + (lit ? "; " + quote5(lit.text) + " is marked here" : ""));
26268
26541
  }
26269
- const own2 = mine.filter((c) => c.role === "in-picture").sort((a, b) => b.size - a.size);
26270
- if (own2.length) {
26271
- L.push("", "## Text that belongs to the footage (" + own2.length + " lines; the largest)", "");
26272
- for (const c of own2.slice(0, 8)) L.push("- " + quote5(c.text) + " " + where(c.box) + ", height " + pct5(c.size));
26542
+ const own3 = mine.filter((c) => c.role === "in-picture").sort((a, b) => b.size - a.size);
26543
+ if (own3.length) {
26544
+ L.push("", "## Text that belongs to the footage (" + own3.length + " lines; the largest)", "");
26545
+ for (const c of own3.slice(0, 8)) L.push("- " + quote5(c.text) + " " + where(c.box) + ", height " + pct5(c.size));
26273
26546
  }
26274
26547
  const curves = p.measure.curves?.find((c) => c.shot === k + 1);
26275
26548
  if (s.events.length || curves) {
@@ -26335,9 +26608,9 @@ var init_describe = __esm({
26335
26608
  const where3 = (k) => p.written ? transitionFile(k + 2) : "the change into shot " + two7(k + 2);
26336
26609
  const poor = m.boundaries.flatMap((b, k) => fitsPoorly(b) ? [where3(k) + " (" + [b.kind, b.mode, b.direction].filter(Boolean).join(" ") + ")"] : []);
26337
26610
  const joined = [...p.joined].map((k) => "shot " + two7(k + 1) + " with " + where3(k));
26338
- const own2 = p.tracks.filter(ownEffect).map((t) => (p.written ? transitionFile(t.shot) : "the change into shot " + two7(t.shot)) + " (" + trackBrief(t, m.source.fps).replace("path: ", "") + ")");
26611
+ const own3 = p.tracks.filter(ownEffect).map((t) => (p.written ? transitionFile(t.shot) : "the change into shot " + two7(t.shot)) + " (" + trackBrief(t, m.source.fps).replace("path: ", "") + ")");
26339
26612
  return [
26340
- ...own2.length ? ["- " + own2.length + " change" + (own2.length === 1 ? " is" : "s are") + " not a standard transition by " + (own2.length === 1 ? "its" : "their") + " measured path: " + own2.join(", ") + ". Re-make each as a scene set from the path in its shot's file."] : [],
26613
+ ...own3.length ? ["- " + own3.length + " change" + (own3.length === 1 ? " is" : "s are") + " not a standard transition by " + (own3.length === 1 ? "its" : "their") + " measured path: " + own3.join(", ") + ". Re-make each as a scene set from the path in its shot's file."] : [],
26341
26614
  ...poor.length ? ["- " + poor.length + " measured transition kind" + (poor.length === 1 ? " does" : "s do") + " not fit the frames well: " + poor.join(", ") + ". Each may be an effect of its own: look at it first."] : [],
26342
26615
  ...joined.length ? ["- Very short shots that are most likely part of the effect after them: " + joined.join(", ") + "."] : []
26343
26616
  ];
@@ -26371,8 +26644,8 @@ var init_describe = __esm({
26371
26644
  const marked2 = markedText(bar);
26372
26645
  L.push("- A bar laid on in the edit through the video (design text a re-make draws, not a watermark): " + bar.words.map((c) => quote5(c.text)).join(" ") + " at " + pct5((bar.words[0]?.box[1] ?? 0) + (bar.words[0]?.box[3] ?? 0) / 2) + " of the height" + (marked2 ? "; the marked word follows the shots: " + marked2 : ""));
26373
26646
  }
26374
- const own2 = text13.cues.filter((c) => c.role === "in-picture").length;
26375
- if (own2) L.push("- " + own2 + " lines of text belong to the footage itself (pages, interfaces, documents)");
26647
+ const own3 = text13.cues.filter((c) => c.role === "in-picture").length;
26648
+ if (own3) L.push("- " + own3 + " lines of text belong to the footage itself (pages, interfaces, documents)");
26376
26649
  } else L.push("- On-screen text was not read (no text reader was available)");
26377
26650
  if (transcript2 && transcript2.words.length) {
26378
26651
  const spoken = transcript2.words.reduce((n, w) => n + w.end - w.start, 0) / fps;
@@ -26581,8 +26854,8 @@ var init_marks = __esm({
26581
26854
  };
26582
26855
  highlightColour = (look2, letters2) => {
26583
26856
  if (look2?.highlight?.color) return look2.highlight.color;
26584
- const own2 = toLab(hexToRgb(letters2 ?? "#ffffff"));
26585
- return STAND_OUT.find((c) => deltaE(toLab(hexToRgb(c)), own2) >= 30) ?? STAND_OUT[0];
26857
+ const own3 = toLab(hexToRgb(letters2 ?? "#ffffff"));
26858
+ return STAND_OUT.find((c) => deltaE(toLab(hexToRgb(c)), own3) >= 30) ?? STAND_OUT[0];
26586
26859
  };
26587
26860
  markSpans = (marks, color2) => marks.map(([from, to]) => ({ from, to, color: color2 }));
26588
26861
  }
@@ -27569,8 +27842,8 @@ var init_main = __esm({
27569
27842
  const said = layers.flatMap((l) => {
27570
27843
  const isMain = main22 !== void 0 && l.box === main22.box && l.kind === main22.kind;
27571
27844
  const words = [l.moves, l.enters].filter((t) => typeof t === "string" && t.trim() !== "");
27572
- const own2 = l.kind === "pointer" ? l.moves ? [l.moves] : [] : isMain ? words.filter((t) => MOTION_WORDS.test(t)) : [];
27573
- return own2.map((t) => l.id + ": " + t.trim());
27845
+ const own3 = l.kind === "pointer" ? l.moves ? [l.moves] : [] : isMain ? words.filter((t) => MOTION_WORDS.test(t)) : [];
27846
+ return own3.map((t) => l.id + ": " + t.trim());
27574
27847
  });
27575
27848
  return said.length ? said.join("; ") : void 0;
27576
27849
  };
@@ -29402,19 +29675,19 @@ var init_read = __esm({
29402
29675
  const lost = unrecoveredOf2(raw.unrecovered);
29403
29676
  const problems2 = [...extraKeys(raw, ["shots", "unrecovered"], "(root)"), ...lost.problems];
29404
29677
  const shots2 = [];
29405
- const present2 = [];
29678
+ const present3 = [];
29406
29679
  const where3 = {};
29407
29680
  raw.shots.forEach((s, k) => {
29408
29681
  const r = shotOf2(s, k);
29409
29682
  problems2.push(...r.problems);
29410
- if (r.number !== void 0 && present2.includes(r.number)) problems2.push(error("shots[" + k + "].shot", "Shot " + r.number + " has two entries.", "Keep one entry per shot; merge what the two say."));
29683
+ if (r.number !== void 0 && present3.includes(r.number)) problems2.push(error("shots[" + k + "].shot", "Shot " + r.number + " has two entries.", "Keep one entry per shot; merge what the two say."));
29411
29684
  else if (r.number !== void 0) {
29412
- present2.push(r.number);
29685
+ present3.push(r.number);
29413
29686
  where3[r.number] = k;
29414
29687
  }
29415
29688
  if (r.shot && !shots2.some((x) => x.shot === r.number)) shots2.push(r.shot);
29416
29689
  });
29417
- return { elements: { shots: [...shots2].sort((a, b) => a.shot - b.shot), ...lost.unrecovered.length ? { unrecovered: lost.unrecovered } : {} }, present: [...present2].sort((a, b) => a - b), where: where3, problems: problems2 };
29690
+ return { elements: { shots: [...shots2].sort((a, b) => a.shot - b.shot), ...lost.unrecovered.length ? { unrecovered: lost.unrecovered } : {} }, present: [...present3].sort((a, b) => a - b), where: where3, problems: problems2 };
29418
29691
  };
29419
29692
  }
29420
29693
  });
@@ -29456,8 +29729,8 @@ var init_elements = __esm({
29456
29729
  };
29457
29730
  unrecoveredIn = async (rt, dir, elements) => {
29458
29731
  const reading = await optionalJson(rt, rt.path.join(dir, UNRECOVERED_FILE));
29459
- const own2 = elements ?? await optionalJson(rt, rt.path.join(dir, ELEMENTS_FILE)).then((raw) => raw === void 0 ? void 0 : readElements(raw).elements);
29460
- return [...Array.isArray(reading?.unrecovered) ? reading.unrecovered : [], ...own2?.unrecovered ?? []];
29732
+ const own3 = elements ?? await optionalJson(rt, rt.path.join(dir, ELEMENTS_FILE)).then((raw) => raw === void 0 ? void 0 : readElements(raw).elements);
29733
+ return [...Array.isArray(reading?.unrecovered) ? reading.unrecovered : [], ...own3?.unrecovered ?? []];
29461
29734
  };
29462
29735
  questions = command(
29463
29736
  'what the model that reads the frames is to do: the instructions (references/video-elements.md from "For the reader" on), the pictures to open in order, and every shot to describe with its time and its measured change; prompt holds it all as one text, to send with pictures to any model',
@@ -29470,9 +29743,9 @@ var init_elements = __esm({
29470
29743
  const guide = await readerGuide(rt);
29471
29744
  if (!guide) throw new VideoCommandError("The instructions for the reader are not in " + rt.path.join(rt.skillRoot, GUIDE_FILE) + ": the Skill is incomplete. Install the popost package again.");
29472
29745
  const candidates3 = [OPENING_FILE, ...questionShots(m).flatMap((s) => [s.frames, ...s.transition ? [s.transition] : []])];
29473
- const present2 = /* @__PURE__ */ new Set();
29474
- for (const f of candidates3) if ((await rt.fs.stat(rt.path.join(dir, f)))?.isFile) present2.add(f);
29475
- const q = videoQuestions(m, text13, (f) => present2.has(f));
29746
+ const present3 = /* @__PURE__ */ new Set();
29747
+ for (const f of candidates3) if ((await rt.fs.stat(rt.path.join(dir, f)))?.isFile) present3.add(f);
29748
+ const q = videoQuestions(m, text13, (f) => present3.has(f));
29476
29749
  if (!q.pictures.length) throw new VideoCommandError("There are no pictures in " + dir + " (opening.jpg, shots/NN-frames.jpg, transitions/NN.jpg). Describe the video again with this version: popost video describe <video> --out " + typed);
29477
29750
  printJson(rt, {
29478
29751
  ok: true,
@@ -29625,8 +29898,8 @@ var init_generate = __esm({
29625
29898
  name = "StillMaking";
29626
29899
  };
29627
29900
  PENDING_EXIT2 = 4;
29628
- run2 = async (rt, words, args2, env = {}) => {
29629
- const r = await programsOf(rt).run([...words, ...args2], { env: { ...toolEnv(rt), ...env }, lowPriority: true }).catch((e) => {
29901
+ run2 = async (rt, words, args2, env2 = {}) => {
29902
+ const r = await programsOf(rt).run([...words, ...args2], { env: { ...toolEnv(rt), ...env2 }, lowPriority: true }).catch((e) => {
29630
29903
  throw new Error("The generator could not be started (" + (e instanceof Error ? e.message : String(e)) + "). Check POPOST_GEN_CMD.");
29631
29904
  });
29632
29905
  return { code: r.code, stdout: new TextDecoder().decode(r.stdout).slice(-8e3), stderr: r.stderr.slice(-4e3) };
@@ -29645,10 +29918,10 @@ var init_generate = __esm({
29645
29918
  const words = toolCommand(rt, "POPOST_GEN_CMD");
29646
29919
  if (!words) return void 0;
29647
29920
  return {
29648
- make: (kind, request, out2, env) => withTempDir(rt, "popost-video-gen-", async (dir) => {
29921
+ make: (kind, request, out2, env2) => withTempDir(rt, "popost-video-gen-", async (dir) => {
29649
29922
  const file = rt.path.join(dir, "request.json");
29650
29923
  await rt.fs.writeFile(file, JSON.stringify(request));
29651
- const r = await run2(rt, words, [kind, file, out2], env);
29924
+ const r = await run2(rt, words, [kind, file, out2], env2);
29652
29925
  const said = lastObject(r.stdout);
29653
29926
  const why = r.stderr.trim().split("\n").slice(-2).join(" | ");
29654
29927
  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.");
@@ -29922,7 +30195,7 @@ var init_generate = __esm({
29922
30195
  const anchorFile = first >= 0 ? o.requests[first].file : void 0;
29923
30196
  const source2 = o.picture ? o.picture.person ? "character" : "image" : fromClip ? "clip" : void 0;
29924
30197
  let picture3 = o.picture?.file;
29925
- const absent = /* @__PURE__ */ new Map();
30198
+ const absent2 = /* @__PURE__ */ new Map();
29926
30199
  for (const [i, original] of order.entries()) {
29927
30200
  const cast = locked.get(original.file);
29928
30201
  const voice = voices.get(original.file);
@@ -29968,19 +30241,19 @@ var init_generate = __esm({
29968
30241
  }
29969
30242
  }
29970
30243
  if (!await exists3(target2)) {
29971
- const failed5 = needs.find((f) => absent.get(f) === "failed");
30244
+ const failed5 = needs.find((f) => absent2.get(f) === "failed");
29972
30245
  if (failed5) {
29973
- absent.set(asked3.file, "failed");
30246
+ absent2.set(asked3.file, "failed");
29974
30247
  materials2.push({ ...entry2, waiting: true, waitsFor: failed5 });
29975
30248
  continue;
29976
30249
  }
29977
- const making2 = needs.find((f) => absent.get(f) === "pending");
30250
+ const making2 = needs.find((f) => absent2.get(f) === "pending");
29978
30251
  if (making2) {
29979
- absent.set(asked3.file, "pending");
30252
+ absent2.set(asked3.file, "pending");
29980
30253
  materials2.push({ ...entry2, queued: true, waitsFor: making2 });
29981
30254
  continue;
29982
30255
  }
29983
- const priced = needs.find((f) => absent.get(f) === "priced");
30256
+ const priced = needs.find((f) => absent2.get(f) === "priced");
29984
30257
  const priceOnly = priced !== void 0;
29985
30258
  await rt.fs.mkdir(rt.path.dirname(target2));
29986
30259
  const partial = target2 + ".partial" + rt.path.extname(target2);
@@ -30009,12 +30282,12 @@ var init_generate = __esm({
30009
30282
  await rt.fs.rm(partial);
30010
30283
  for (const ext of [".speech.wav", ".speech.json"]) await rt.fs.rm(partial + ext);
30011
30284
  if (e instanceof StillMaking) {
30012
- absent.set(asked3.file, "pending");
30285
+ absent2.set(asked3.file, "pending");
30013
30286
  const charged = e.pending.chargedCredits;
30014
30287
  materials2.push({ ...entry2, pending: true, ...e.pending.task ? { task: e.pending.task } : {}, ...charged !== void 0 ? { chargedCredits: charged } : {} });
30015
30288
  continue;
30016
30289
  }
30017
- absent.set(asked3.file, e instanceof ConfirmNeeded ? "priced" : "failed");
30290
+ absent2.set(asked3.file, e instanceof ConfirmNeeded ? "priced" : "failed");
30018
30291
  materials2.push({ ...entry2, error: e instanceof Error ? e.message : String(e), ...e instanceof ConfirmNeeded ? { confirm: e.confirm } : {}, ...priceOnly ? { waiting: true, waitsFor: priced } : {} });
30019
30292
  continue;
30020
30293
  }
@@ -30030,7 +30303,7 @@ var init_generate = __esm({
30030
30303
  const rel = rt.path.join(rt.path.dirname(asked3.file), ANCHOR_FILE);
30031
30304
  const got = await exists3(rt.path.resolve(o.dir, rel)) || await grabAnchor(rt, target2, rt.path.resolve(o.dir, rel)).then(() => true, () => false);
30032
30305
  if (got) picture3 = rel;
30033
- else absent.set(asked3.file, "failed");
30306
+ else absent2.set(asked3.file, "failed");
30034
30307
  entry2 = { ...entry2, anchor: true };
30035
30308
  }
30036
30309
  notes2[asked3.file] = asked3.note ?? asked3.prompt;
@@ -30039,7 +30312,7 @@ var init_generate = __esm({
30039
30312
  }
30040
30313
  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";
30041
30314
  const failed4 = materials2.filter((m) => m.error).map(
30042
- (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 (confirm has the total). 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." : ""))
30315
+ (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." : ""))
30043
30316
  );
30044
30317
  const held = materials2.filter((m) => m.waiting && !m.confirm && !m.queued).map((m) => error(
30045
30318
  m.file,
@@ -30056,7 +30329,7 @@ var init_generate = __esm({
30056
30329
  });
30057
30330
 
30058
30331
  // src/video/generate/cloud.ts
30059
- var GenerateError, MINUTE_MS, POLL_MS2, DEFAULT_WAIT_MIN, DEFAULT_SECONDS, CREATE_TRIES, CREATE_TIMEOUT_SEC, UPLOAD_TIMEOUT_MS, DOWNLOAD_TIMEOUT_SEC, MAX_CLIP_BYTES, RETRY_HINT, setting, numberSetting, keysOf, cloudSettings, agreeToPrice, requestKey, LISTS2, has, mediaType, readReference3, readReferences, recordFile, 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, listModels;
30332
+ 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, recordFile, 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, listModels;
30060
30333
  var init_cloud2 = __esm({
30061
30334
  "src/video/generate/cloud.ts"() {
30062
30335
  "use strict";
@@ -30087,7 +30360,7 @@ var init_cloud2 = __esm({
30087
30360
  CREATE_TRIES = 3;
30088
30361
  CREATE_TIMEOUT_SEC = 120;
30089
30362
  UPLOAD_TIMEOUT_MS = 10 * MINUTE_MS;
30090
- DOWNLOAD_TIMEOUT_SEC = 900;
30363
+ DOWNLOAD_TIMEOUT_SEC2 = 900;
30091
30364
  MAX_CLIP_BYTES = 1024 * 1024 * 1024;
30092
30365
  RETRY_HINT = "Run the same command again: it sends the same idempotency key, so it is never paid twice.";
30093
30366
  setting = (rt, name) => rt.env[name]?.trim() || void 0;
@@ -30121,7 +30394,7 @@ var init_cloud2 = __esm({
30121
30394
  if (s.maxCredits !== void 0 ? price.credits <= s.maxCredits : s.yes) return;
30122
30395
  throw new ConfirmNeeded(
30123
30396
  price,
30124
- s.maxCredits !== void 0 ? "This costs " + price.credits + " credits, more than the budget of this call (" + s.maxCredits + " credits), so nothing was charged. Show the user the price; only if they agree, run again with --confirm --max-credits N (N: what is left of the agreed budget)." : "This costs " + price.credits + " credits and nothing was charged: show the user the price, and run again with --confirm --max-credits N only after they agree."
30397
+ s.maxCredits !== void 0 ? "This costs " + price.credits + " credits, more than the budget of this call (" + s.maxCredits + " credits), so nothing was charged. Show the user the price with what it buys (confirm: model, resolution, seconds, aspect ratio); only if they agree, run again with --confirm --max-credits N (N: what is left of the agreed budget)." : "This costs " + price.credits + " credits and nothing was charged: show the user the price with what it buys (confirm: model, resolution, seconds, aspect ratio), and run again with --confirm --max-credits N only after they agree."
30125
30398
  );
30126
30399
  };
30127
30400
  requestKey = (kind, fields2) => kind + "-" + sha256(JSON.stringify(fields2));
@@ -30318,7 +30591,7 @@ var init_cloud2 = __esm({
30318
30591
  const url = task.video?.url;
30319
30592
  if (typeof url !== "string") throw new GenerateError("popost.ai says the clip of task " + task.id + " is made but gives no link to it. Run the command again later.");
30320
30593
  try {
30321
- const data = await downloadResult(rt, url, out2, MAX_CLIP_BYTES, DOWNLOAD_TIMEOUT_SEC, labels);
30594
+ const data = await downloadResult(rt, url, out2, MAX_CLIP_BYTES, DOWNLOAD_TIMEOUT_SEC2, labels);
30322
30595
  const bytes = task.video?.bytes;
30323
30596
  if (typeof bytes === "number" && data.length !== bytes) {
30324
30597
  await rt.fs.rm(out2);
@@ -31459,9 +31732,9 @@ var init_letters = __esm({
31459
31732
  const lab = g.at[k], box2 = boxes2[k];
31460
31733
  if (!lab || !box2) return void 0;
31461
31734
  const mine = strokesOf(f, box2, lab, strokeMax(box2));
31462
- const own2 = { edges: noEdges(), thick: [], pairs: { v: [], h: [] }, beyond: { v: [], h: [] }, ground: groundOn(f, box2, lab) };
31463
- edgesFrom(f, mine, lab, Math.max(4, Math.round(0.3 * (box2.y1 - box2.y0))), own2.edges, own2.thick, own2.pairs, own2.beyond);
31464
- return { own: own2, mine };
31735
+ const own3 = { edges: noEdges(), thick: [], pairs: { v: [], h: [] }, beyond: { v: [], h: [] }, ground: groundOn(f, box2, lab) };
31736
+ edgesFrom(f, mine, lab, Math.max(4, Math.round(0.3 * (box2.y1 - box2.y0))), own3.edges, own3.thick, own3.pairs, own3.beyond);
31737
+ return { own: own3, mine };
31465
31738
  });
31466
31739
  const perLine = lines.map((l) => l?.own);
31467
31740
  return { ...aggregate(g, lines.map((l) => l?.mine ?? []), perLine), ground: perLine.filter((l) => l?.ground).length >= frames.length / 2 };
@@ -31506,13 +31779,13 @@ var init_letters = __esm({
31506
31779
  return lines.length >= Math.max(2, 0.2 * n) ? [{ ...aggregate(s.group, s.px, s.perLine, lines), ground: false, told: lines }] : [];
31507
31780
  });
31508
31781
  HUG_TIE = 0.1;
31509
- fillAmong = (frames, boxes2, first, own2, weight) => {
31782
+ fillAmong = (frames, boxes2, first, own3, weight) => {
31510
31783
  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;
31511
31784
  const within = (s) => s.enclosed >= ENCLOSED && (dEdge(s.around, first.around) <= 15 || (() => {
31512
31785
  const a = along(s.group.lab, first.around, s.around);
31513
31786
  return a.t >= 0.5 && a.off <= 15;
31514
31787
  })());
31515
- const rivals = own2.filter((s) => s === first || within(s) || mutual(s));
31788
+ const rivals = own3.filter((s) => s === first || within(s) || mutual(s));
31516
31789
  if (rivals.length < 2) return first;
31517
31790
  const told = rivals.flatMap((s) => s.told ? [s.told] : []);
31518
31791
  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) }));
@@ -31534,21 +31807,21 @@ var init_letters = __esm({
31534
31807
  const a = along(core.group.lab, core.around, s.group.lab);
31535
31808
  return a.t > 0 && a.t < 0.85 && a.off <= 15;
31536
31809
  };
31537
- const own2 = candidates3.filter((s) => !plainCores.some((core) => core !== s && core.group.lines >= s.group.lines && strokesPerLine(core) > strokesPerLine(s) && dEdge(core.group.lab, s.around) <= 15 && fringeOf(s, core)));
31810
+ const own3 = candidates3.filter((s) => !plainCores.some((core) => core !== s && core.group.lines >= s.group.lines && strokesPerLine(core) > strokesPerLine(s) && dEdge(core.group.lab, s.around) <= 15 && fringeOf(s, core)));
31538
31811
  const lineHeight = median10(boxes2.map((b) => b.y1 - b.y0));
31539
- const enclosed = own2.filter((s) => s.enclosed >= ENCLOSED && !isPicture(aroundOf(s, around3), s.around) || off2.has(s)).sort((a, b) => b.enclosed * b.group.lines - a.enclosed * a.group.lines || strokesPerLine(b) - strokesPerLine(a));
31812
+ const enclosed = own3.filter((s) => s.enclosed >= ENCLOSED && !isPicture(aroundOf(s, around3), s.around) || off2.has(s)).sort((a, b) => b.enclosed * b.group.lines - a.enclosed * a.group.lines || strokesPerLine(b) - strokesPerLine(a));
31540
31813
  const fillSure = (s) => {
31541
31814
  const c = sureOf(s, n);
31542
31815
  return c >= SURE2 ? { color: hexOf(s), confidence: c } : { confidence: c };
31543
31816
  };
31544
31817
  const base = { samples: n };
31545
31818
  const top2 = enclosed[0];
31546
- const best = top2 && fillAmong(frames, boxes2, top2, own2, (s) => strokesPerLine(s) * s.group.lines);
31819
+ const best = top2 && fillAmong(frames, boxes2, top2, own3, (s) => strokesPerLine(s) * s.group.lines);
31547
31820
  const look2 = best ? outlineLook(frames, boxes2, best, all, n, fillSure(best), lineHeight, off2.get(best)) : void 0;
31548
31821
  const part = best ? off2.get(best) : void 0;
31549
31822
  if (best && look2) return { fill: best, look: look2, ...part ? { part } : {} };
31550
- const arounds = own2.filter((s) => s.enclosed >= ENCLOSED / 2).map((s) => s.around);
31551
- const fill4 = own2.filter((s) => !arounds.some((a) => dEdge(a, s.group.lab) < 15)).sort((a, b) => strokesPerLine(b) * b.group.lines - strokesPerLine(a) * a.group.lines)[0];
31823
+ const arounds = own3.filter((s) => s.enclosed >= ENCLOSED / 2).map((s) => s.around);
31824
+ const fill4 = own3.filter((s) => !arounds.some((a) => dEdge(a, s.group.lab) < 15)).sort((a, b) => strokesPerLine(b) * b.group.lines - strokesPerLine(a) * a.group.lines)[0];
31552
31825
  if (!fill4) return { look: { kind: "plain", ...base, confidence: 0, unsure: ["fill: no colour stayed the same inside the lines while the picture changed, so the letters' colour is not given"] } };
31553
31826
  const sure = fillSure(fill4);
31554
31827
  const unsure = sure.color ? {} : { unsure: ["fill: the letters' colour changed from line to line, so it is not given"] };
@@ -31918,7 +32191,7 @@ var init_shadow = __esm({
31918
32191
  });
31919
32192
 
31920
32193
  // src/video/text/look.ts
31921
- var MAX_SAMPLES3, MIN_SAMPLES, PLATE_SHARE2, FONT_OF_BOX2, edgeBeyond, cornerCut, rgbAt, edgePairs, plateOf, plateColour, plateLook, refined, shared, lookOf2, samplesOf, captionFrames, measureCaptionLook;
32194
+ var MAX_SAMPLES3, MIN_SAMPLES, PLATE_SHARE2, FONT_OF_BOX2, edgeBeyond, cornerCut, rgbAt, edgePairs, plateOf, plateColour, plateLook, refined, shared2, lookOf2, samplesOf, captionFrames, measureCaptionLook;
31922
32195
  var init_look = __esm({
31923
32196
  "src/video/text/look.ts"() {
31924
32197
  "use strict";
@@ -32077,7 +32350,7 @@ var init_look = __esm({
32077
32350
  ...weight ?? {}
32078
32351
  };
32079
32352
  };
32080
- shared = (h, n) => h ? { ...h, share: r210(h.lines / Math.max(1, n)) } : void 0;
32353
+ shared2 = (h, n) => h ? { ...h, share: r210(h.lines / Math.max(1, n)) } : void 0;
32081
32354
  lookOf2 = (frames, boxes2, texts = []) => {
32082
32355
  if (frames.length < MIN_SAMPLES) return void 0;
32083
32356
  const readings = frames.map((f, k) => plateOf(f, boxes2[k]));
@@ -32087,14 +32360,14 @@ var init_look = __esm({
32087
32360
  if (plates.length >= PLATE_SHARE2 * readings.length) {
32088
32361
  const look3 = plateLook(frames.length, plates);
32089
32362
  const fill5 = readings.map((r) => r.plate && r.letters ? toLab(r.letters) : void 0);
32090
- const highlight2 = shared(highlightOf(frames, boxes2, texts, { fill: fill5, around: labMedian(plates.map((p) => toLab(p.colour))) }, candidates3, around3), frames.length);
32363
+ const highlight2 = shared2(highlightOf(frames, boxes2, texts, { fill: fill5, around: labMedian(plates.map((p) => toLab(p.colour))) }, candidates3, around3), frames.length);
32091
32364
  return highlight2 ? { ...look3, highlight: highlight2 } : look3;
32092
32365
  }
32093
32366
  const letters2 = lettersOf(frames, boxes2, candidates3, around3);
32094
32367
  const { fill: fill4 } = letters2;
32095
32368
  const look2 = refined(frames, boxes2, letters2, around3);
32096
32369
  const ctx = fill4 ? { fill: fill4.group.at, px: fill4.px, ...look2.kind === "outline" || look2.kind === "plate" ? { around: fill4.around } : {} } : void 0;
32097
- const highlight = shared(ctx ? highlightOf(frames, boxes2, texts, ctx, candidates3, around3) : void 0, frames.length);
32370
+ const highlight = shared2(ctx ? highlightOf(frames, boxes2, texts, ctx, candidates3, around3) : void 0, frames.length);
32098
32371
  return highlight ? { ...look2, highlight } : look2;
32099
32372
  };
32100
32373
  samplesOf = (track) => {
@@ -32152,8 +32425,8 @@ var init_reader_command = __esm({
32152
32425
  jobs = (rt) => Math.max(1, Math.min(16, Math.round(Number(rt.env.POPOST_OCR_JOBS) || 1)));
32153
32426
  readerSplit = (rt, frames) => {
32154
32427
  const budget2 = cpuBudgetOf(rt).cpus;
32155
- const own2 = Math.floor(Number(rt.env.POPOST_TOOL_THREADS?.trim()));
32156
- const each = own2 >= 1 ? own2 : void 0;
32428
+ const own3 = Math.floor(Number(rt.env.POPOST_TOOL_THREADS?.trim()));
32429
+ const each = own3 >= 1 ? own3 : void 0;
32157
32430
  const processes = Math.max(1, Math.min(jobs(rt), Math.ceil(frames / 8), Math.floor(budget2 / (each ?? 1))));
32158
32431
  return { processes, threads: each ?? Math.max(1, Math.min(TOOL_THREADS, Math.floor(budget2 / processes))) };
32159
32432
  };
@@ -32355,9 +32628,9 @@ var init_readback_kept = __esm({
32355
32628
  const who = readerOf(rt);
32356
32629
  const [hashes2, kept2] = await Promise.all([Promise.all(frames.map(async (f) => sha256(await rt.fs.readFile(f.file)))), keptLines(rt, file, who)]);
32357
32630
  const old = hashes2.map((h) => Array.isArray(kept2[h]) ? kept2[h] : void 0);
32358
- const missing3 = frames.filter((_f, i) => old[i] === void 0);
32359
- onKept?.(frames.length - missing3.length, frames.length);
32360
- const read2 = new Map((missing3.length ? await reader.read(missing3) : []).map((s) => [s.frame, s.lines]));
32631
+ const missing4 = frames.filter((_f, i) => old[i] === void 0);
32632
+ onKept?.(frames.length - missing4.length, frames.length);
32633
+ const read2 = new Map((missing4.length ? await reader.read(missing4) : []).map((s) => [s.frame, s.lines]));
32361
32634
  const found = frames.flatMap((f, i) => {
32362
32635
  const lines = old[i] ?? read2.get(f.frame);
32363
32636
  return lines ? [{ hash: hashes2[i], sample: { frame: f.frame, lines } }] : [];
@@ -33152,23 +33425,23 @@ var init_findings = __esm({
33152
33425
  });
33153
33426
  effectProjectProblems = (rf, project) => rf.shots.flatMap((s, k) => {
33154
33427
  const e = s.effect, o = e?.by === "before" ? k - 1 : k;
33155
- const seg = project.segments[k], own2 = project.segments[o];
33156
- if (!e || !seg || !own2) return [];
33428
+ const seg = project.segments[k], own3 = project.segments[o];
33429
+ if (!e || !seg || !own3) return [];
33157
33430
  const out2 = [];
33158
33431
  if (seg.in && seg.in.transition !== "cut")
33159
33432
  out2.push(warning(
33160
33433
  "segments[" + k + "].in",
33161
33434
  'The change into segment "' + seg.id + '" is the preset "' + seg.in.transition + '"; the reading saw an effect of its own there: ' + effectText(e) + ". A preset does not make it.",
33162
- 'Remove "in" (a cut). ' + effectFix(e, 'segment "' + own2.id + '"', 'segment "' + seg.id + '"') + " Running template fill again does both."
33435
+ 'Remove "in" (a cut). ' + effectFix(e, 'segment "' + own3.id + '"', 'segment "' + seg.id + '"') + " Running template fill again does both."
33163
33436
  ));
33164
- if (!("scene" in own2.base))
33437
+ if (!("scene" in own3.base))
33165
33438
  out2.push(warning(
33166
33439
  "segments[" + o + "].base",
33167
- effectOwner(e, o + 1, k + 1, "Segment") + effectText(e) + '; segment "' + own2.id + '" is not a scene, so nothing draws it.',
33168
- 'Make segment "' + own2.id + '" a scene. ' + effectFix(e, 'segment "' + own2.id + '"', 'segment "' + seg.id + '"')
33440
+ effectOwner(e, o + 1, k + 1, "Segment") + effectText(e) + '; segment "' + own3.id + '" is not a scene, so nothing draws it.',
33441
+ 'Make segment "' + own3.id + '" a scene. ' + effectFix(e, 'segment "' + own3.id + '"', 'segment "' + seg.id + '"')
33169
33442
  ));
33170
- else if ((own2.frames ?? 0) < e.frames)
33171
- out2.push(warning("segments[" + o + "].frames", 'Segment "' + own2.id + '" draws an effect of ' + e.frames + " frames (" + effectText(e) + ") and is " + (own2.frames ?? 0) + " frames long.", "Run template fill again: it moves the cut so that the scene covers the effect."));
33443
+ else if ((own3.frames ?? 0) < e.frames)
33444
+ out2.push(warning("segments[" + o + "].frames", 'Segment "' + own3.id + '" draws an effect of ' + e.frames + " frames (" + effectText(e) + ") and is " + (own3.frames ?? 0) + " frames long.", "Run template fill again: it moves the cut so that the scene covers the effect."));
33172
33445
  return out2;
33173
33446
  });
33174
33447
  CJK3 = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/gu;
@@ -33204,7 +33477,7 @@ var init_findings = __esm({
33204
33477
  droppedFillProblems = (rf, fill4, scenes) => {
33205
33478
  const keys2 = rf.dropped.map(keysOf2);
33206
33479
  if (!keys2.length) return [];
33207
- const own2 = fillTexts(fill4).flatMap((t) => {
33480
+ const own3 = fillTexts(fill4).flatMap((t) => {
33208
33481
  const shown3 = shownOf(t.text, keys2);
33209
33482
  return shown3.length ? [droppedProblem(t.at, t.at + " " + quote12(t.text), shown3)] : [];
33210
33483
  });
@@ -33214,7 +33487,7 @@ var init_findings = __esm({
33214
33487
  const shown3 = file ? shownOf(pageText(scenes.get(file) ?? ""), keys2) : [];
33215
33488
  return file && shown3.length ? [droppedProblem("shots[" + k + "].scene", 'The scene "' + file + '"', shown3)] : [];
33216
33489
  });
33217
- return [...own2, ...drawn];
33490
+ return [...own3, ...drawn];
33218
33491
  };
33219
33492
  droppedProjectProblems = (rf, project, scenes) => {
33220
33493
  const keys2 = rf.dropped.map(keysOf2);
@@ -33581,7 +33854,7 @@ var init_check5 = __esm({
33581
33854
  fileProblems = async (rt, pkg, fill4, dir, lengths) => {
33582
33855
  const exists3 = async (p) => await rt.fs.stat(p) !== null;
33583
33856
  const out2 = [];
33584
- const missing3 = (at7, file) => error(at7, quote13(file) + " does not exist in " + dir + ".", "Put the file there, or correct the path (it is relative to the project directory).");
33857
+ const missing4 = (at7, file) => error(at7, quote13(file) + " does not exist in " + dir + ".", "Put the file there, or correct the path (it is relative to the project directory).");
33585
33858
  for (const [k, raw] of fill4.shots.entries()) {
33586
33859
  const s = raw;
33587
33860
  if (k >= pkg.template.shots.length || kindsOf2(s).length !== 1) continue;
@@ -33590,7 +33863,7 @@ var init_check5 = __esm({
33590
33863
  if (typeof file !== "string" || !file.trim() || isOutside(file)) continue;
33591
33864
  const full = rt.path.resolve(dir, file);
33592
33865
  if (!await exists3(full)) {
33593
- out2.push(missing3("shots[" + k + "]." + key2, file));
33866
+ out2.push(missing4("shots[" + k + "]." + key2, file));
33594
33867
  continue;
33595
33868
  }
33596
33869
  if (key2 === "picture" && !PICTURES3.includes(rt.path.extname(file).toLowerCase())) out2.push(error("shots[" + k + "].picture", quote13(file) + " is not a picture file (" + PICTURES3.join(", ") + ").", "Convert it to WebP or PNG."));
@@ -33600,8 +33873,8 @@ var init_check5 = __esm({
33600
33873
  }
33601
33874
  out2.push(...await itemFileProblems(rt, pkg, s, k, dir, lengths));
33602
33875
  }
33603
- if (typeof fill4.sound === "string" && !await exists3(rt.path.resolve(dir, fill4.sound))) out2.push(missing3("sound", fill4.sound));
33604
- for (const [i, bed] of (Array.isArray(fill4.beds) ? fill4.beds : []).entries()) if (typeof bed?.footage === "string" && !isOutside(bed.footage) && !await exists3(rt.path.resolve(dir, bed.footage))) out2.push(missing3("beds[" + i + "].footage", bed.footage));
33876
+ if (typeof fill4.sound === "string" && !await exists3(rt.path.resolve(dir, fill4.sound))) out2.push(missing4("sound", fill4.sound));
33877
+ for (const [i, bed] of (Array.isArray(fill4.beds) ? fill4.beds : []).entries()) if (typeof bed?.footage === "string" && !isOutside(bed.footage) && !await exists3(rt.path.resolve(dir, bed.footage))) out2.push(missing4("beds[" + i + "].footage", bed.footage));
33605
33878
  out2.push(...await stillProblems(rt, pkg, fill4, dir, lengths));
33606
33879
  for (const p of await slotPictures(rt, fill4, dir)) out2.push(...await slotPictureProblems(rt, p, dir));
33607
33880
  return out2;
@@ -34339,12 +34612,12 @@ var init_speak = __esm({
34339
34612
  const takes = takesOf(spoken);
34340
34613
  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 } : {} });
34341
34614
  const said = [];
34342
- let own2 = true;
34615
+ let own3 = true;
34343
34616
  for (const [k, take] of takes.entries()) {
34344
34617
  const clip11 = clips[k], lines2 = take.lines.map((i) => spoken[i] ?? "");
34345
34618
  const got = await takeWords(rt, o, clip11, lines2, fps, notes2);
34346
34619
  const words2 = got.words;
34347
- own2 = own2 && got.own;
34620
+ own3 = own3 && got.own;
34348
34621
  const { spans, matched } = lineSpans(lines2, words2);
34349
34622
  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.");
34350
34623
  said.push({ take, clip: clip11, words: words2, spans, pieces: piecesOf(take, spans, ref, fps, o.hold === true, o.keepPauses === true) });
@@ -34364,7 +34637,7 @@ var init_speak = __esm({
34364
34637
  await writeVoiceReceipt(rt, rt.path.join(o.outDir, VOICE_FILE), lines.filter((l) => l.file).length);
34365
34638
  const words = voiceWords({ lines: captions, starts: result.timing.starts, frames: flow.frames, fps, ...plan4.say ? { say: plan4.say } : {}, transcript: { language: "", fps, words: laid.words } });
34366
34639
  await rt.fs.writeFile(rt.path.join(o.outDir, WORDS_FILE), JSON.stringify({ fps: words.fps, tokens: words.tokens }, null, 1) + "\n");
34367
- notes2.push(words.tokens.length + " word times written to " + WORDS_FILE + (own2 ? " (the speaker's own word times)." : " (heard or spread over the takes, see above)."));
34640
+ notes2.push(words.tokens.length + " word times written to " + WORDS_FILE + (own3 ? " (the speaker's own word times)." : " (heard or spread over the takes, see above)."));
34368
34641
  return { result, lines, words, notes: notes2 };
34369
34642
  };
34370
34643
  speakRetarget = async (rt, o) => {
@@ -34392,11 +34665,11 @@ var init_speak = __esm({
34392
34665
  notes2.push(...overrunNotes({ lines: captions, slots: t.slots, spoken: lines.map((l) => l.frames), reference: t.reference, total: t.total, fps, ...plan4.speed ? { speed: plan4.speed } : {} }));
34393
34666
  await mixLines(rt, { lines, starts: result.timing.starts, fps, totalFrames: result.timing.total, out: rt.path.join(o.outDir, VOICE_FILE) });
34394
34667
  await writeVoiceReceipt(rt, rt.path.join(o.outDir, VOICE_FILE), lines.filter((l) => l.file).length);
34395
- const own2 = spokenTranscript(lines, result.timing.starts, fps);
34396
- const transcript2 = own2 ?? (o.transcriber ? await hear2(rt, rt.path.join(o.outDir, VOICE_FILE), fps, o.transcriber, o.language, notes2) : void 0);
34668
+ const own3 = spokenTranscript(lines, result.timing.starts, fps);
34669
+ const transcript2 = own3 ?? (o.transcriber ? await hear2(rt, rt.path.join(o.outDir, VOICE_FILE), fps, o.transcriber, o.language, notes2) : void 0);
34397
34670
  const words = voiceWords({ lines: captions, starts: result.timing.starts, frames: lines.map((l) => l.frames), fps, ...plan4.say ? { say: plan4.say } : {}, ...transcript2 ? { transcript: transcript2 } : {} });
34398
34671
  await rt.fs.writeFile(rt.path.join(o.outDir, WORDS_FILE), JSON.stringify({ fps: words.fps, tokens: words.tokens }, null, 1) + "\n");
34399
- notes2.push(words.tokens.length + " word times written to " + WORDS_FILE + (words.estimated ? " (estimated: no transcriber, so each line's time is shared evenly among its words)." : own2 ? " (the speaker's own word times)." : " (from a transcript of the voice)."));
34672
+ notes2.push(words.tokens.length + " word times written to " + WORDS_FILE + (words.estimated ? " (estimated: no transcriber, so each line's time is shared evenly among its words)." : own3 ? " (the speaker's own word times)." : " (from a transcript of the voice)."));
34400
34673
  return { result, lines, words, notes: notes2 };
34401
34674
  };
34402
34675
  }
@@ -35665,12 +35938,12 @@ var init_time2 = __esm({
35665
35938
  const offset = boundaryOffset(ref, other, tol);
35666
35939
  const byTime = pairBoundaries(ref, other, tol, offset);
35667
35940
  const byShare = 2 * byTime.length < ref.boundaries.length ? fillGaps(ref, other, pairCutsByShare(ref, other)) : [];
35668
- const shared2 = byShare.length > byTime.length;
35669
- const pairs = shared2 ? byShare : byTime;
35941
+ const shared3 = byShare.length > byTime.length;
35942
+ const pairs = shared3 ? byShare : byTime;
35670
35943
  const fr = fpsOf(ref), fo = fpsOf(other);
35671
35944
  const per = pairs.map((p) => {
35672
35945
  const a = ref.boundaries[p.r], b = other.boundaries[p.o];
35673
- const shift = shared2 ? a.frame / fr - b.frame / fo : -offset;
35946
+ const shift = shared3 ? a.frame / fr - b.frame / fo : -offset;
35674
35947
  const [b0, b1] = spanSeconds(b, fo);
35675
35948
  const overlap6 = a.kind === "cut" && b.kind === "cut" ? 1 : intervalIoU(spanSeconds(a, fr), [b0 + shift, b1 + shift]);
35676
35949
  const kind = kindCredit(a.kind, b.kind), pr = params(a, b);
@@ -35685,7 +35958,7 @@ var init_time2 = __esm({
35685
35958
  spanOverlap: r310(mean4(per.map((x) => x.overlap))),
35686
35959
  params: prs.length ? r310(mean4(prs)) : "-",
35687
35960
  exactKind: per.filter((x) => x.kind === 1).length,
35688
- ...shared2 ? { pairedBy: "share of the length" } : {}
35961
+ ...shared3 ? { pairedBy: "share of the length" } : {}
35689
35962
  }
35690
35963
  };
35691
35964
  };
@@ -36555,8 +36828,8 @@ var init_stage = __esm({
36555
36828
  return /^(header|footer|nav|main|aside|article|form|table)$/.test(p) && unique3(p) ? p : null;
36556
36829
  };
36557
36830
  const selectorOf = (el) => {
36558
- const own2 = anchor(el);
36559
- if (own2 && own2 !== "body") return own2;
36831
+ const own3 = anchor(el);
36832
+ if (own3 && own3 !== "body") return own3;
36560
36833
  const tag3 = el.tagName.toLowerCase();
36561
36834
  for (const attr2 of ["data-testid", "data-test", "aria-label", "name", "placeholder", "href"]) {
36562
36835
  const v = el.getAttribute(attr2);
@@ -37746,10 +38019,10 @@ var SHELL_BUNDLE;
37746
38019
  var init_shell_bundle = __esm({
37747
38020
  "src/video/preview/shell-bundle.ts"() {
37748
38021
  "use strict";
37749
- SHELL_BUNDLE = `"use strict";(()=>{var De="reload",je="render";var ao=new Set(["wipe","slide","whip"]),se=e=>e.resolved?.canvas.fps??e.measure?.measure.source.fps??e.referenceMeasure?.measure.source.fps??30,ye=(e,t,n)=>e*n/t,io=(e,t,n)=>Math.floor((e+.5)*n/t),W=e=>{if(e.resolved)return e.resolved.frames;let t=se(e),n=[e.measure,e.referenceMeasure].map(o=>o?Math.round(ye(o.measure.source.frames,o.measure.source.fps,t)):0);return Math.max(0,...n)},pe=(e,t)=>Math.min(Math.max(0,t-1),Math.max(0,Math.round(e))),Z=(e,t)=>e.segments.find(n=>t>=n.start&&t<n.end),fe=(e,t)=>e.items.filter(n=>t>=n.start&&t<n.end),Nt=e=>[e.kind,e.frames+"f",ao.has(e.kind)?e.direction:"",e.kind==="slide"?e.mode:"",e.kind==="fade"?"via "+e.via:"",e.side&&e.side!=="both"?e.side:"",e.strength!==void 0&&e.strength!==1?"x"+e.strength:""].filter(Boolean).join(" "),Te=e=>e.preset+" "+e.frames+"f"+(e.preset==="slide"||e.preset==="wipe"?" "+e.direction:""),It=e=>[e.kind,e.kind==="cut"?"":e.end-e.start-1+"f",e.direction??"",e.mode??"",e.via?"via "+e.via:"",e.confidence.toFixed(2)].filter(Boolean).join(" "),ze=e=>[e.kind,e.how??"",e.direction??""].filter(Boolean).join(" "),Ft=e=>e.shots.flatMap((t,n)=>t.events.map((o,r)=>({shot:n,index:r,event:o}))).sort((t,n)=>t.event.start-n.event.start||t.shot-n.shot),Dt=(e,t,n)=>{let o=io(t,n,e.source.fps);return e.shots.flatMap(r=>r.events.filter(s=>o>=s.start&&o<s.end))},mt=(e,t)=>{let n=[];return e.map(o=>{let r=n.findIndex(a=>a<=o.start),s=r>=0?r:Math.min(n.length,t-1);return n[s]=Math.max(n[s]??0,o.end),{row:s,...o}})},jt=(e,t)=>{let n=e/t,o=[.5,1,2,5,10,15,30,60,120,300].find(s=>n/s<=12)??600,r=Math.floor(n/o);return Array.from({length:r+1},(s,a)=>({frame:Math.round(a*o*t),label:String(Number((a*o).toFixed(1)))+"s"}))},zt=e=>e.height>e.width?[.06,.08,.82,.72]:[.05,.05,.9,.9],pt=(e,t)=>(e/t).toFixed(2)+" s",ge=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Ht=(e,t)=>(t==="render"?e.measure:e.referenceMeasure)?.measure,Bt=(e,t)=>{switch(t.kind){case"slot":return;case"segment":return e.resolved?.segments.find(n=>n.id===t.id);case"item":return e.resolved?.items.find(n=>n.id===t.id);case"audio":return e.resolved?.audio.find(n=>n.id===t.id);case"boundary":return Ht(e,t.source)?.boundaries[t.index];case"event":return Ht(e,t.source)?.shots[t.shot]?.events[t.index]}},Vt=e=>{switch(e.kind){case"slot":return e.name;case"segment":case"item":case"audio":return e.kind+" "+e.id;case"boundary":return e.source+" boundary "+(e.index+1);case"event":return e.source+" event "+(e.shot+1)+"."+(e.index+1)}};var Ve={schema:null,status:null,problems:[],render:null,playRender:!1},_e=e=>{let t=e,n=[];return{get:()=>t,set:o=>{let r=t;t={...t,...o},n.forEach(s=>s(t,r))},subscribe:o=>(n.push(o),()=>{let r=n.indexOf(o);r>=0&&n.splice(r,1)})}},_t=[.25,.5,1],Be=e=>e.state?W(e.state):0,lo=e=>e.state?se(e.state):30,co=e=>{let t={frame:0,time:0},n=0,o=s=>{let a=e.get();if(!a.playing)return;let d=Math.max(0,Be(a)-1),i=Math.min(d,t.frame+Math.floor((s-t.time)/1e3*lo(a)*a.speed));if(i>=d)return e.set({frame:d,playing:!1});i!==a.frame&&e.set({frame:i}),n=requestAnimationFrame(o)},r=()=>{t={frame:e.get().frame,time:performance.now()}};return{reanchor:r,pause:()=>{cancelAnimationFrame(n),e.get().playing&&e.set({playing:!1})},play:()=>{let s=e.get();Be(s)<2||(s.frame>=Be(s)-1&&e.set({frame:0}),r(),e.set({playing:!0}),n=requestAnimationFrame(o))}}},Ke=e=>{let t=co(e),n=o=>{e.set({frame:pe(o,Be(e.get()))}),t.reanchor()};return{seek:n,step:o=>n(e.get().frame+o),togglePlay:()=>e.get().playing?t.pause():t.play(),pause:t.pause,setSpeed:o=>{e.set({speed:o}),t.reanchor()},pin:o=>e.set({pinned:o}),toggleOverlay:o=>{let r=e.get().overlays;e.set({overlays:{...r,[o]:!r[o]}})},setLang:o=>{document.documentElement.lang=o==="zh"?"zh-CN":"en",e.set({lang:o})}}};var m=(e,t={},n=[])=>{let o=document.createElement(e);t.class&&(o.className=t.class),t.id&&(o.id=t.id),t.text!==void 0&&(o.textContent=t.text),t.title&&(o.title=t.title),t.style&&(o.style.cssText=t.style);for(let[r,s]of Object.entries(t.attrs??{}))o.setAttribute(r,s);for(let[r,s]of Object.entries(t.data??{}))o.dataset[r]=s;for(let[r,s]of Object.entries(t.on??{}))s&&o.addEventListener(r,s);return o.append(...n),o},Kt="http://www.w3.org/2000/svg",uo={film:"M2 2h12v12H2zM5 2v12M11 2v12M2 6h3M2 10h3M11 6h3M11 10h3",media:"M2 2h12v12H2zM2 12l4-5 4 4 2-2 2 3M5 4h.1",text:"M2 3h12M8 3v11M5 14h6",layers:"M1 5l7-4 7 4-7 4-7-4M1 8l7 4 7-4M1 11l7 4 7-4",code:"M5 3 1 8l4 5M11 3l4 5-4 5M9 2 7 14",checks:"M8 1l6 2v5c0 4-6 7-6 7S2 12 2 8V3l6-2M5 8l2 2 4-4",first:"M4 3v10M12 3.5 6 8l6 4.5z",last:"M12 3v10M4 3.5 10 8l-6 4.5z",play:"M5 3l8 5-8 5z",pause:"M5.5 3v10M10.5 3v10",undo:"M6 3.5 3 6.5l3 3M3 6.5h6.5a3.5 3.5 0 0 1 0 7H7",redo:"M10 3.5l3 3-3 3M13 6.5H6.5a3.5 3.5 0 0 0 0 7H9",remove:"M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.7 8.5h5.6l.7-8.5M7 7v4M9 7v4",addText:"M2 3.5h7M5.5 3.5V12M11.5 8v5M9 10.5h5",duplicate:"M5.5 5.5h7v7h-7zM3.5 10.5v-7h7",render:"M2.5 3.5h11v9h-11zM7 6l3 2-3 2z",compare:"M2 2h12v12H2zM8 2v12M4 6h2M10 10h2",layout:"M2 2h12v12H2zM5.5 2v12M10.5 2v12",history:"M2 2v4h4M2 6a6 6 0 1 1 0 4M8 4v4l3 2",theme:"M8 1a7 7 0 1 0 7 7A5 5 0 0 1 8 1z",language:"M1 3h8M5 1v2M3 3c0 4 3 6 6 7M8 3c0 4-3 6-7 7M9 14l3-8 3 8M10 11h4",download:"M8 1v9M4 6l4 4 4-4M2 11v3h12v-3",external:"M9 2h5v5M14 2 7 9M6 2H2v12h12v-4",cloud:"M4 12a3 3 0 0 1-1-5.8A5 5 0 0 1 12 5a3.5 3.5 0 0 1 0 7M8 14V7M5.5 9.5 8 7l2.5 2.5",refresh:"M13 2v4H9M13 6a5.5 5.5 0 1 0 .2 5"},Y=e=>{let t=document.createElementNS(Kt,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","16"),t.setAttribute("height","16"),t.setAttribute("aria-hidden","true");let n=document.createElementNS(Kt,"path");return n.setAttribute("d",uo[e]),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.5"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("stroke-linecap","round"),t.appendChild(n),t},Le=(e,t,n,o)=>{let r=Math.max(1,o);return e.style.left=Math.max(0,t)/r*100+"%",e.style.width=Math.max(0,Math.min(n,r)-Math.max(0,t))/r*100+"%",e},Q=(e,t,n)=>(e.style.left=Math.max(0,Math.min(t,n))/Math.max(1,n)*100+"%",e),le=(e,t)=>{let[n=0,o=0,r=0,s=0]=t;return e.style.left=n*100+"%",e.style.top=o*100+"%",e.style.width=r*100+"%",e.style.height=s*100+"%",e};var ft={title:"Video preview",readOnly:"read-only",live:"live",offline:"offline, retrying",language:"\\u4E2D\\u6587",languageTitle:"Switch the interface to Chinese",currentVideo:"Current video",render:"Render",reference:"Reference",seekNote:"A browser video seek is near, not frame-exact.",noReference:"No reference video. Start with --reference <video> to show one here.",errorsOnStage:"The project has errors; the stage lists them.",imageFailed:"A picture failed to load",first:"First frame (Home)",last:"Last frame (End)",back10:"Back 10 frames (Shift+Left)",back1:"Back 1 frame (Left)",fwd1:"Forward 1 frame (Right)",fwd10:"Forward 10 frames (Shift+Right)",play:"Play (Space)",pause:"Pause (Space)",frame:"Frame",time:"Time",speed:"Speed",jump:"Go to frame",jumpHint:"Frame number, then Enter",ruler:"Seconds",segments:"Segments",audio:"Audio",words:"Words",renderBoundaries:"Render: boundaries",renderEvents:"Render: events",referenceBoundaries:"Reference: boundaries",referenceEvents:"Reference: events",boxes:"Item boxes",events:"Measured events",safe:"Safe area",selection:"Selection",underPlayhead:"under the playhead",pinned:"clicked",follow:"Follow the playhead",onScreen:"On screen",nothing:"Nothing here.",problems:"Problems",noProblems:"No problems.",allowed:"Allowed",fix:"Fix",error:"error",warning:"warning",score:"Score",noScore:"No score: it needs a measurement of the render and one of the reference.",dimension:"Dimension",value:"Score",compared:"Compared",detail:"Detail",composite:"composite",measurements:"Measurements",renderMeasure:"Render",referenceMeasure:"Reference",none:"none",notes:"Draft notes",structure:"structure",transitions:"transitions",camera:"camera",motion:"motion",rhythm:"rhythm",colour:"colour",picture:"picture",editing:"editing",undo:"Undo (Ctrl+Z)",redo:"Redo (Shift+Ctrl+Z)",addText:"Add a text at the playhead",duplicate:"Duplicate the selection",remove:"Delete the selection (Delete)",renderTool:"Render the project to out.mp4",newText:"New text",saved:"Saved",added:"Added",removed:"Deleted",moved:"Moved",outside:"an edit made outside the page",undone:"Undone",redone:"Redone",notSaved:"Not saved",phraseSpan:"This item is placed on spoken words, so it is not dragged: change its lead and hold in the panel.",offlineEdit:"The preview server cannot be reached; nothing was saved.",rendering:"Rendering",rendered:"Rendered",framesIn:"frames in",renderFailed:"The render failed",playRender:"Play it beside the stage",showReference:"Show the reference again",renderFile:"Render",editHint:"Click an item on the stage, a bar in the lanes or a segment to edit it. Escape clears the selection.",resolvedTitle:"What the timeline plays (the default, or the value after resolving)",snapped:"snapped to",snapPlayhead:"the playhead",snapSegment:"a segment border",snapReference:"a boundary of the reference",framesWord:"frames",videoLength:"video",onFrames:"On frames",fDefault:"(default)",fCustom:"own values",fStyle:"Style",fNamed:"Style",fSize:"Size",fColour:"Colour",fWeight:"Weight",fAlign:"Align",fPreset:"Preset",fNone:"(none)",fFrames:"Frames",fDirection:"Direction",fEase:"Ease",fEnter:"Entrance",fExit:"Exit",fBox:"Box (fractions of the canvas)",fX:"x",fY:"y",fW:"width",fH:"height",fRotate:"Rotate",fOpacity:"Opacity",fZ:"Layer (z)",fLook:"Look",fRadius:"Corners",fShape:"Shape",fGradient:"A gradient: edit it in video.json.",fMaterial:"Material",fFit:"Fit",fMask:"Mask",fIn:"First frame",fSpeed:"Speed",fFootage:"Footage",fPicture:"Picture",fText:"Text",fStart:"Starts in",fWhole:"(the whole video)",fFrom:"From",fAudio:"Sound",fGain:"Gain (dB)",fSourceAudio:"Source audio dB (empty = automatic: on when the video has no audio track)",fSegment:"Segment",fWhen:"When",fPhrase:"Phrase",fOccurrence:"Occurrence",fLead:"Lead",fHold:"Hold",fTo:"To",fCue:"Cue",fCues:"Cues",fKind:"Kind",fHardCut:"(hard cut)",fMode:"Mode",fVia:"Via",fSide:"Side",fStrength:"Strength",fTransition:"Transition into it",fBase:"Base",fBaseColor:"colour",fBaseMaterial:"material",fBaseScene:"Scene content",fLength:"Length in frames",fCamera:"The camera: edit it in video.json."},mo={title:"\\u89C6\\u9891\\u9884\\u89C8",readOnly:"\\u53EA\\u8BFB",live:"\\u5DF2\\u8FDE\\u63A5",offline:"\\u8FDE\\u63A5\\u4E2D\\u65AD\\uFF0C\\u6B63\\u5728\\u91CD\\u8BD5",language:"English",languageTitle:"\\u628A\\u754C\\u9762\\u5207\\u6362\\u4E3A\\u82F1\\u6587",currentVideo:"\\u5F53\\u524D\\u4F5C\\u54C1",render:"\\u6E32\\u67D3",reference:"\\u53C2\\u8003\\u89C6\\u9891",seekNote:"\\u6D4F\\u89C8\\u5668\\u7684\\u89C6\\u9891\\u8DF3\\u8F6C\\u53EA\\u662F\\u63A5\\u8FD1\\uFF0C\\u4E0D\\u662F\\u9010\\u5E27\\u7CBE\\u786E\\u3002",noReference:"\\u6CA1\\u6709\\u53C2\\u8003\\u89C6\\u9891\\u3002\\u7528 --reference <\\u89C6\\u9891> \\u542F\\u52A8\\u5373\\u53EF\\u5728\\u6B64\\u663E\\u793A\\u3002",errorsOnStage:"\\u9879\\u76EE\\u6709\\u9519\\u8BEF\\uFF0C\\u753B\\u9762\\u533A\\u5217\\u51FA\\u4E86\\u5B83\\u4EEC\\u3002",imageFailed:"\\u6709\\u56FE\\u7247\\u52A0\\u8F7D\\u5931\\u8D25",first:"\\u7B2C\\u4E00\\u5E27 (Home)",last:"\\u6700\\u540E\\u4E00\\u5E27 (End)",back10:"\\u540E\\u9000 10 \\u5E27 (Shift+\\u2190)",back1:"\\u540E\\u9000 1 \\u5E27 (\\u2190)",fwd1:"\\u524D\\u8FDB 1 \\u5E27 (\\u2192)",fwd10:"\\u524D\\u8FDB 10 \\u5E27 (Shift+\\u2192)",play:"\\u64AD\\u653E (\\u7A7A\\u683C)",pause:"\\u6682\\u505C (\\u7A7A\\u683C)",frame:"\\u5E27",time:"\\u65F6\\u95F4",speed:"\\u901F\\u5EA6",jump:"\\u8DF3\\u5230\\u5E27",jumpHint:"\\u8F93\\u5165\\u5E27\\u53F7\\u540E\\u6309\\u56DE\\u8F66",ruler:"\\u79D2",segments:"\\u5206\\u6BB5",audio:"\\u97F3\\u9891",words:"\\u5B57\\u8BCD",renderBoundaries:"\\u6E32\\u67D3\\uFF1A\\u8FB9\\u754C",renderEvents:"\\u6E32\\u67D3\\uFF1A\\u5143\\u7D20\\u4E8B\\u4EF6",referenceBoundaries:"\\u53C2\\u8003\\uFF1A\\u8FB9\\u754C",referenceEvents:"\\u53C2\\u8003\\uFF1A\\u5143\\u7D20\\u4E8B\\u4EF6",boxes:"\\u5143\\u7D20\\u6846",events:"\\u6D4B\\u5F97\\u7684\\u4E8B\\u4EF6",safe:"\\u5B89\\u5168\\u533A",selection:"\\u9009\\u4E2D",underPlayhead:"\\u64AD\\u653E\\u5934\\u6240\\u5728\\u5904",pinned:"\\u5DF2\\u70B9\\u9009",follow:"\\u8DDF\\u968F\\u64AD\\u653E\\u5934",onScreen:"\\u753B\\u9762\\u4E2D",nothing:"\\u8FD9\\u91CC\\u6CA1\\u6709\\u5185\\u5BB9\\u3002",problems:"\\u95EE\\u9898",noProblems:"\\u6CA1\\u6709\\u95EE\\u9898\\u3002",allowed:"\\u5141\\u8BB8\\u7684\\u503C",fix:"\\u4FEE\\u6B63",error:"\\u9519\\u8BEF",warning:"\\u8B66\\u544A",score:"\\u8BC4\\u5206",noScore:"\\u6CA1\\u6709\\u8BC4\\u5206\\uFF1A\\u9700\\u8981\\u6E32\\u67D3\\u548C\\u53C2\\u8003\\u89C6\\u9891\\u5404\\u81EA\\u7684\\u6D4B\\u91CF\\u7ED3\\u679C\\u3002",dimension:"\\u7EF4\\u5EA6",value:"\\u5206\\u6570",compared:"\\u6BD4\\u8F83\\u6570",detail:"\\u7EC6\\u8282",composite:"\\u7EFC\\u5408",measurements:"\\u6D4B\\u91CF\\u7ED3\\u679C",renderMeasure:"\\u6E32\\u67D3",referenceMeasure:"\\u53C2\\u8003",none:"\\u65E0",notes:"\\u8349\\u7A3F\\u5907\\u6CE8",structure:"\\u7ED3\\u6784",transitions:"\\u8F6C\\u573A",camera:"\\u955C\\u5934\\u8FD0\\u52A8",motion:"\\u5143\\u7D20\\u52A8\\u6548",rhythm:"\\u8282\\u594F",colour:"\\u8272\\u5F69",picture:"\\u753B\\u9762",editing:"\\u7F16\\u8F91\\u4E2D",undo:"\\u64A4\\u9500 (Ctrl+Z)",redo:"\\u91CD\\u505A (Shift+Ctrl+Z)",addText:"\\u5728\\u64AD\\u653E\\u5934\\u5904\\u6DFB\\u52A0\\u6587\\u5B57",duplicate:"\\u590D\\u5236\\u6240\\u9009\\u5185\\u5BB9",remove:"\\u5220\\u9664\\u6240\\u9009\\u5185\\u5BB9 (Delete)",renderTool:"\\u628A\\u9879\\u76EE\\u6E32\\u67D3\\u4E3A out.mp4",newText:"\\u65B0\\u6587\\u5B57",saved:"\\u5DF2\\u4FDD\\u5B58",added:"\\u5DF2\\u6DFB\\u52A0",removed:"\\u5DF2\\u5220\\u9664",moved:"\\u5DF2\\u79FB\\u52A8",outside:"\\u9875\\u9762\\u5916\\u7684\\u4FEE\\u6539",undone:"\\u5DF2\\u64A4\\u9500",redone:"\\u5DF2\\u91CD\\u505A",notSaved:"\\u672A\\u4FDD\\u5B58",phraseSpan:"\\u8FD9\\u4E2A\\u5143\\u7D20\\u6309\\u8BF4\\u51FA\\u7684\\u5B57\\u8BCD\\u5B9A\\u4F4D\\uFF0C\\u4E0D\\u80FD\\u62D6\\u52A8\\uFF1A\\u8BF7\\u5728\\u9762\\u677F\\u91CC\\u4FEE\\u6539\\u5B83\\u7684\\u63D0\\u524D\\u91CF\\u548C\\u5EF6\\u540E\\u91CF\\u3002",offlineEdit:"\\u8FDE\\u4E0D\\u4E0A\\u9884\\u89C8\\u670D\\u52A1\\u5668\\uFF0C\\u6CA1\\u6709\\u4FDD\\u5B58\\u4EFB\\u4F55\\u4FEE\\u6539\\u3002",rendering:"\\u6E32\\u67D3\\u4E2D",rendered:"\\u5DF2\\u6E32\\u67D3",framesIn:"\\u5E27\\uFF0C\\u7528\\u65F6",renderFailed:"\\u6E32\\u67D3\\u5931\\u8D25",playRender:"\\u5728\\u753B\\u9762\\u65C1\\u64AD\\u653E",showReference:"\\u6539\\u56DE\\u663E\\u793A\\u53C2\\u8003\\u89C6\\u9891",renderFile:"\\u6E32\\u67D3\\u7ED3\\u679C",editHint:"\\u70B9\\u51FB\\u753B\\u9762\\u4E2D\\u7684\\u5143\\u7D20\\u3001\\u8F68\\u9053\\u4E0A\\u7684\\u6761\\u5757\\u6216\\u5206\\u6BB5\\u5373\\u53EF\\u7F16\\u8F91\\u3002\\u6309 Esc \\u53D6\\u6D88\\u9009\\u4E2D\\u3002",resolvedTitle:"\\u65F6\\u95F4\\u7EBF\\u5B9E\\u9645\\u64AD\\u653E\\u7684\\u503C\\uFF08\\u9ED8\\u8BA4\\u503C\\uFF0C\\u6216\\u89E3\\u6790\\u540E\\u7684\\u503C\\uFF09",snapped:"\\u5DF2\\u5438\\u9644\\u5230",snapPlayhead:"\\u64AD\\u653E\\u5934",snapSegment:"\\u5206\\u6BB5\\u8FB9\\u754C",snapReference:"\\u53C2\\u8003\\u89C6\\u9891\\u7684\\u8FB9\\u754C",framesWord:"\\u5E27",videoLength:"\\u89C6\\u9891",onFrames:"\\u6240\\u5728\\u5E27",fDefault:"\\uFF08\\u9ED8\\u8BA4\\uFF09",fCustom:"\\u81EA\\u5B9A\\u4E49",fStyle:"\\u6837\\u5F0F",fNamed:"\\u6837\\u5F0F",fSize:"\\u5B57\\u53F7",fColour:"\\u989C\\u8272",fWeight:"\\u5B57\\u91CD",fAlign:"\\u5BF9\\u9F50",fPreset:"\\u9884\\u8BBE",fNone:"\\uFF08\\u65E0\\uFF09",fFrames:"\\u5E27\\u6570",fDirection:"\\u65B9\\u5411",fEase:"\\u7F13\\u52A8",fEnter:"\\u5165\\u573A",fExit:"\\u51FA\\u573A",fBox:"\\u6846\\uFF08\\u753B\\u5E03\\u7684\\u6BD4\\u4F8B\\uFF09",fX:"x",fY:"y",fW:"\\u5BBD",fH:"\\u9AD8",fRotate:"\\u65CB\\u8F6C",fOpacity:"\\u4E0D\\u900F\\u660E\\u5EA6",fZ:"\\u5C42\\u7EA7 (z)",fLook:"\\u5916\\u89C2",fRadius:"\\u5706\\u89D2",fShape:"\\u5F62\\u72B6",fGradient:"\\u6E10\\u53D8\\uFF1A\\u8BF7\\u5728 video.json \\u91CC\\u4FEE\\u6539\\u3002",fMaterial:"\\u7D20\\u6750",fFit:"\\u9002\\u914D",fMask:"\\u906E\\u7F69",fIn:"\\u8D77\\u59CB\\u5E27",fSpeed:"\\u901F\\u5EA6",fFootage:"\\u89C6\\u9891\\u7D20\\u6750",fPicture:"\\u56FE\\u7247",fText:"\\u6587\\u5B57",fStart:"\\u5F00\\u59CB\\u4E8E",fWhole:"\\uFF08\\u6574\\u4E2A\\u89C6\\u9891\\uFF09",fFrom:"\\u4ECE",fAudio:"\\u58F0\\u97F3",fGain:"\\u589E\\u76CA (dB)",fSourceAudio:"\\u7D20\\u6750\\u539F\\u58F0 dB\\uFF08\\u7559\\u7A7A\\u4E3A\\u81EA\\u52A8\\uFF1A\\u89C6\\u9891\\u6CA1\\u6709\\u97F3\\u8F68\\u65F6\\u4FDD\\u7559\\uFF09",fSegment:"\\u5206\\u6BB5",fWhen:"\\u51FA\\u73B0\\u65F6\\u95F4",fPhrase:"\\u5B57\\u8BCD",fOccurrence:"\\u7B2C\\u51E0\\u6B21",fLead:"\\u63D0\\u524D",fHold:"\\u5EF6\\u540E",fTo:"\\u5230",fCue:"\\u5B57\\u5E55",fCues:"\\u5B57\\u5E55\\u6761",fKind:"\\u7C7B\\u578B",fHardCut:"\\uFF08\\u786C\\u5207\\uFF09",fMode:"\\u6A21\\u5F0F",fVia:"\\u7ECF\\u8FC7",fSide:"\\u5355\\u4FA7",fStrength:"\\u5F3A\\u5EA6",fTransition:"\\u8FDB\\u5165\\u5B83\\u7684\\u8F6C\\u573A",fBase:"\\u5E95\\u56FE",fBaseColor:"\\u989C\\u8272",fBaseMaterial:"\\u7D20\\u6750",fBaseScene:"\\u573A\\u666F\\u5185\\u5BB9",fLength:"\\u957F\\u5EA6\\uFF08\\u5E27\\uFF09",fCamera:"\\u955C\\u5934\\u8FD0\\u52A8\\uFF1A\\u8BF7\\u5728 video.json \\u91CC\\u4FEE\\u6539\\u3002"},po={en:ft,zh:mo},Ue=e=>e?.toLowerCase().startsWith("zh")?"zh":"en",S=(e,t)=>po[e][t],Ut=e=>Object.hasOwn(ft,e),Jt=(e,t)=>t in ft?S(e,t):t;var T=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),he=(e,t)=>T(e)&&Array.isArray(e[t])?e[t]:[],ee=e=>he(e.source,"tracks").filter(T),te=e=>he(e.source,"segments").filter(T),ve=(e,t)=>he(e.source,"materials").filter(T).filter(n=>t.includes(String(n.kind))).map(n=>String(n.id)),gt=(e,t)=>e.findIndex(n=>T(n)&&n.id===t),fo=(e,t)=>{let n=e.resolved?.items.find(r=>r.id===t);if(n)return n.cue;let o=t.match(/^(.+)#(\\d+)$/);return o?{track:o[1]??"",index:Number(o[2])}:void 0},q=(e,t)=>{if(!t||!T(e.source))return;let n=he(e.source,"tracks");if(t.kind==="segment"){let i=gt(he(e.source,"segments"),t.id),l=he(e.source,"segments")[i];return T(l)?{kind:"segment",index:i,segment:l}:void 0}if(t.kind!=="item"&&t.kind!=="audio")return;let o=gt(n,t.id),r=n[o];if(T(r)&&r.type!=="caption")return{kind:"track",index:o,track:r};let s=t.kind==="item"?fo(e,t.id):void 0,a=s?gt(n,s.track):-1,d=n[a];return s&&T(d)&&s.index<he(d,"cues").length?{kind:"cue",index:a,cue:s.index,track:d}:void 0},go=e=>e.kind==="segment"?["segments",e.index]:["tracks",e.index],ht=e=>{if(e.kind==="cue")return["tracks",e.index,"cues",e.cue,"during"];if(e.kind==="track"&&T(e.track.during))return["tracks",e.index,"during"]},bt=e=>e.kind!=="segment"&&Array.isArray(e.track.box)?["tracks",e.index,"box"]:void 0,oe=(e,t)=>t.reduce((n,o)=>Array.isArray(n)?n[o]:T(n)?n[String(o)]:void 0,e),Re=(e,t)=>{let n=bt(t),o=n?oe(e.source,n):void 0;return Array.isArray(o)&&o.length===4&&o.every(r=>typeof r=="number")?o:void 0},Wt=(e,t,n)=>{if(n===void 0)return oe(e,t)===void 0?void 0:{op:"remove",path:t};let o=t.length-1;for(;o>0&&!T(oe(e,t.slice(0,o)))&&!Array.isArray(oe(e,t.slice(0,o)));)o--;let r=t.slice(o+1).reduceRight((s,a)=>({[String(a)]:s}),n);return{op:"set",path:t.slice(0,o+1),value:r}},Se=(e,t)=>{if(!T(t)||t.phrase!==void 0||typeof t.segment!="string")return;let n=e.segments.find(s=>s.id===t.segment);if(!n)return;let o=typeof t.from=="number"?t.from:0,r=typeof t.to=="number"?t.to:n.end-n.start;return{start:n.start+o,end:n.start+r,segment:n}},yt=(e,t,n,o)=>{let r=e.segments.find(d=>d.id===t.segment),s=r&&n>=r.start&&n<r.end?r:Z(e,n)??r??e.segments[0],a=s?.start??0;return{...t,segment:s?.id??t.segment,from:n-a,to:o-a}},qt=(e,t,n=!0)=>{let o=e.resolved,r=o?.canvas.fps??30,s=e.referenceMeasure?.measure;return[{frame:t,kind:"playhead"},...n&&o?o.segments.flatMap(a=>[a.start,a.end]).map(a=>({frame:a,kind:"segment"})):[],...s?s.boundaries.map(a=>({frame:Math.round(ye(a.frame,s.source.fps,r)),kind:"reference"})):[]]},ho=4,Pe=(e,t,n)=>{let o=t.map(r=>({t:r,d:Math.abs(r.frame-e)*n})).filter(r=>r.d<=ho).sort((r,s)=>r.d-s.d)[0];return o?o.t:{frame:Math.round(e),kind:"frame"}},re=(e,t)=>{let n=new Set(e.map(r=>String(r.id))),o=t.replace(/-\\d+$/,"");if(!n.has(t))return t;for(let r=2;;r++)if(!n.has(o+"-"+r))return o+"-"+r},Gt=(e,t,n)=>{let o=e.resolved,r=o?Z(o,t)??o.segments[o.segments.length-1]:void 0;if(!o||!r)return;let s=ee(e),a=re(s,"text"),d=Math.max(0,t-r.start),i=Math.max(d+1,Math.min(r.end-r.start,d+2*o.canvas.fps)),l={id:a,type:"text",text:n,box:[.1,.42,.8,.12],during:{segment:r.id,from:d,to:i},style:"subtitle"};return{op:{op:"insert",path:["tracks",s.length],value:l},select:{kind:"item",id:a}}},bo=e=>Array.isArray(e)&&e.length===4?e.map((t,n)=>n<2&&typeof t=="number"?Math.round((t+.03)*1e5)/1e5:t):e,Yt=(e,t)=>{if(t.kind==="segment"){let r=re(te(e),String(t.segment.id));return{op:{op:"insert",path:["segments",t.index+1],value:{...t.segment,id:r}},select:{kind:"segment",id:r}}}if(t.kind==="cue"){let r=he(t.track,"cues")[t.cue],s=e.resolved,a=s&&T(r)?Se(s,r.during):void 0;if(!T(r)||!s||!a||!T(r.during))return;let d=yt(s,r.during,a.end,a.end+(a.end-a.start));return{op:{op:"insert",path:["tracks",t.index,"cues",t.cue+1],value:{...r,during:d}},select:{kind:"item",id:String(t.track.id)+"#"+(t.cue+1)}}}let n=re(ee(e),String(t.track.id)),o={...t.track,id:n,...Array.isArray(t.track.box)?{box:bo(t.track.box)}:{}};return{op:{op:"insert",path:["tracks",t.index+1],value:o},select:{kind:t.track.type==="audio"?"audio":"item",id:n}}},Xt=e=>e.kind==="cue"&&Array.isArray(e.track.cues)&&e.track.cues.length>1?{op:"remove",path:["tracks",e.index,"cues",e.cue]}:{op:"remove",path:go(e)},Zt=e=>e.map(t=>Math.round(t*1e5)/1e5);var Qt=(e,t)=>{if(!T(e.source))return;let n=te(e),o=n[t];if(!o)return;let r=re(n,String(o.id)),s=ee(e).map(i=>structuredClone(i)),a=i=>T(i)&&i.segment===o.id?{...i,segment:r}:i;for(let i of ee(e)){let l=Array.isArray(i.cues)?i.cues.filter(u=>T(u)&&T(u.during)&&u.during.segment===o.id):[];if(!l.length&&(!T(i.during)||i.during.segment!==o.id))continue;let c={...structuredClone(i),id:re(s,String(i.id)),...i.during?{during:a(i.during)}:{},...l.length?{cues:l.map(u=>({...u,during:a(u.during)}))}:{}};s.push(c)}let d=n.map(i=>structuredClone(i));return d.splice(t+1,0,{...structuredClone(o),id:r}),{source:{...e.source,segments:d,tracks:s},id:r}};var yo='"Noto Sans CJK SC", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif',we={font:yo,size:.045,weight:700,color:"#ffffff",align:"center",italic:!1};var vo={blur:.12,x:.04,y:.06},$t=["headline","subtitle","label","caption"],vt={headline:{...we,size:.065,weight:800,stroke:{color:"#000000",width:.12}},subtitle:{...we,size:.04,weight:700,stroke:{color:"#000000",width:.1}},label:{...we,size:.032,weight:700,color:"#111111",background:{color:"#ffffff",padding:.35,radius:.3}},caption:{...we,size:.036,weight:600,background:{color:"rgba(0, 0, 0, 0.6)",padding:.3,radius:.2}}},St=e=>$t.includes(e),So=(e,t)=>({color:e.color,blur:e.blur??t.blur,x:e.x??t.x,y:e.y??t.y}),en=e=>{if(e===void 0)return we;if(typeof e=="string"){if(!St(e))throw new Error('Unknown text style "'+e+'". Use one of: '+$t.join(", ")+".");return vt[e]}let{shadow:t,...n}=e;return{...we,...n,...t?{shadow:So(t,vo)}:{}}};var tn=(e,t)=>{if(!e?.resolved||t.op!=="set"||t.path[0]!=="tracks"||t.path[2]!=="text"||typeof t.value!="string")return t;let n=T(e.source)?e.source:{},o=Array.isArray(n.tracks)?n.tracks[Number(t.path[1])]:void 0;if(!T(o)||o.type!=="text")return t;let r=e.resolved.items.find(f=>f.id===o.id),a=document.querySelector("#page")?.contentDocument,d=a?.querySelector('[data-item="'+CSS.escape(String(o.id))+'"] > div');if(!a||!d||!r?.style)return t;let i=r.box[2]*e.resolved.canvas.width,l=r.box[3]*e.resolved.canvas.height,c=d.cloneNode(!1);c.textContent=t.value,Object.assign(c.style,{position:"fixed",left:"0",top:"0",width:i+"px",height:"auto",visibility:"hidden",transform:"none"}),a.body.append(c);let u=r.style.size*e.resolved.canvas.height,h=f=>(c.style.fontSize=f+"px",c.style.letterSpacing=(r.style.letterSpacing??0)*f+"px",c.scrollHeight<=l+.5&&c.scrollWidth<=i+.5);try{if(h(u))return t;let f=1,p=u;for(let v=0;v<16;v++){let E=(f+p)/2;h(E)?f=E:p=E}let{font:g,...b}=en(typeof o.style=="string"?o.style:void 0),y=T(o.style)?o.style:b;return{op:"set",path:["tracks",Number(t.path[1])],value:{...o,text:t.value,style:{...y,size:Math.floor(f*100)/100/e.resolved.canvas.height}}}}finally{c.remove()}};var Ae=(e,t,n)=>{let o=e?.resolved,r=t.kind==="item"?o?.items.find(d=>d.id===t.id):t.kind==="audio"?o?.audio.find(d=>d.id===t.id):t.kind==="segment"||t.kind==="slot"?o?.segments.find(d=>d.id===t.id):void 0;if(!r)return n;let s=r.end??o.frames,a="enter"in r?r.enter?.frames??0:0;return n>=r.start+a&&n<s&&t.kind!=="slot"?n:Math.min(s-1,Math.max(r.start+a,r.start+Math.floor((s-r.start)*.3)))};var nn=(e,t)=>{let n=e.resolved,o=te(e),r=n?.segments[t];if(!n||!r||o.length<2||!T(e.source))return;let s=structuredClone(e.source),a=o.filter((f,p)=>p!==t),d=r.end-r.start,i=String(a[0].id),l=f=>f<=r.start?f:f>=r.end?f-d:r.start,c=(f,p)=>({segment:i,from:l(f),to:l(p)}),u=ee(e),h=[];for(let f of u){let p=structuredClone(f);if(p.type==="caption"&&Array.isArray(p.cues)){let k=p.cues.flatMap((H,L)=>{if(!T(H))return[];let R=n.items.find(F=>F.cue?.track===p.id&&F.cue?.index===L);return!R||l(R.end)<=l(R.start)?[]:[{...H,during:c(R.start,R.end)}]});k.length&&h.push({...p,cues:k});continue}let g=p.type==="audio"?n.audio.find(k=>k.id===p.id):n.items.find(k=>k.id===p.id),b=Se(n,p.during),y=g?.start??b?.start??0,v=g?.end??b?.end??n.frames;if(l(v)<=l(y))continue;let E=p.type==="audio"||p.type==="video",M=E&&y<r.start&&v>r.end?[[y,r.start],[r.end,v]]:[[y<r.end&&y>=r.start?r.end:y,v>r.start&&v<=r.end?r.start:v]];for(let[k,H]of M){if(k===void 0||H===void 0||H<=k)continue;let L={...p,during:c(k,H)};if(h.some(R=>R.id===L.id)&&(L.id=re([...u,...h],String(L.id))),E&&k>y){let R=p.type==="video"?n.items.find(O=>O.id===p.id)?.play:void 0,F=R?(n.footage?.[R.material]?.fps??n.canvas.fps)/n.canvas.fps*R.speed:p.bed?(n.footage?.[String(p.material)]?.fps??n.canvas.fps)/n.canvas.fps:1;L.in=Number(p.in??0)+Math.round((k-y)*F)}k>y&&delete L.enter,H<v&&delete L.exit,h.push(L)}}return s.segments=a,s.tracks=h,s};var xt=(e,t,n)=>{let o=q(e,t),r=e.resolved;if(!o||!r||!T(e.source))return;let s=structuredClone(e.source);if(o.kind==="segment"){let g=r.segments[o.index];if(!g||n<=g.start||n>=g.end)return;let b=te(e).map(R=>structuredClone(R)),y=b[o.index],v=n-g.start,E=re(b,String(y.id)),M=T(y.base)?y.base:{},k={...M};M.scene&&(k.offset=Number(M.offset??0)+v/r.canvas.fps),M.material&&g.base.kind==="video"&&(k.in=g.base.play.in+Math.round(v*(r.footage?.[g.base.play.material]?.fps??r.canvas.fps)*g.base.play.speed/r.canvas.fps));let H={...y,id:E,frames:g.end-n,base:k};delete H.in;let L=R=>T(R)&&R.segment===y.id&&R.phrase===void 0&&R.to===void 0?{...R,to:g.end-g.start}:R;return s.tracks=ee(e).map(R=>({...R,...R.during?{during:L(R.during)}:{},...Array.isArray(R.cues)?{cues:R.cues.map(F=>T(F)?{...F,during:L(F.during)}:F)}:{}})),b.splice(o.index,1,{...y,frames:v},H),s.segments=b,{source:s,select:{kind:"segment",id:E}}}let a=structuredClone(o.track),d=o.kind==="cue"&&Array.isArray(a.cues)?a.cues[o.cue]:void 0,i=o.kind==="cue"?d:a;if(!T(i))return;if(!T(i.during)&&a.type==="audio"){let g=r.audio.find(b=>b.id===a.id);g&&(i.during={segment:r.segments[0]?.id,from:g.start,to:g.end??r.frames})}if(!T(i.during))return;let l=Se(r,i.during);if(!l||n<=l.start||n>=l.end)return;let c=i.during,u={...i,during:{...c,to:n-l.segment.start}},h={...i,during:{...c,from:n-l.segment.start}},f=ee(e).map(g=>structuredClone(g));if(o.kind==="cue")return a.cues.splice(o.cue,1,u,h),f[o.index]=a,s.tracks=f,{source:s,select:{kind:"item",id:String(a.id)+"#"+(o.cue+1)}};let p=re(f,String(a.id));if(h.id=p,a.type==="video"){let g=r.items.find(b=>b.id===a.id);g&&(h.in=Number(a.in??0)+Math.round((n-l.start)*Number(r.footage?.[g.play?.material??""]?.fps??r.canvas.fps)*Number(a.speed??1)/r.canvas.fps))}return a.type==="audio"&&(h.in=Number(a.in??0)+Math.round((n-l.start)*(a.bed?(r.footage?.[String(a.material)]?.fps??r.canvas.fps)/r.canvas.fps:1))),delete u.exit,delete h.enter,f.splice(o.index,1,u,h),s.tracks=f,{source:s,select:{kind:a.type==="audio"?"audio":"item",id:p}}};var Et=e=>"popost-preview-selection:"+e.project.dir,Je=e=>{try{let t=sessionStorage.getItem(Et(e));return t?JSON.parse(t):null}catch{return null}},We=e=>{e.subscribe((t,n)=>{if(!(t.pinned===n.pinned||!t.state))try{t.pinned?sessionStorage.setItem(Et(t.state),JSON.stringify(t.pinned)):sessionStorage.removeItem(Et(t.state))}catch{}})},xo=async(e,t)=>{try{return await(await fetch(e,{method:"POST",headers:{"content-type":"application/json"},...t===void 0?{}:{body:JSON.stringify(t)}})).json()}catch(n){return{ok:!1,problems:[{level:"error",at:"(request)",message:n instanceof Error?n.message:String(n),fix:""}]}}},qe=(e,t)=>{let n=f=>e.set({edit:{...e.get().edit,...f}}),o=new Set,r=Promise.resolve(!0),s=!0,a=f=>{f&&["item","slot","audio"].includes(f.kind)&&e.get().timeline&&!e.get().timeline?.layers&&e.set({timeline:{layers:!0,snapping:e.get().timeline?.snapping??!0}}),t.pin(f)},d=(f,p)=>{if(!f.ok){let y=f.problems.find(v=>v.level==="error")??f.problems[0];return n({status:y?{kind:"refused",problem:y}:null,problems:f.problems}),!1}let g=f.state;if(g.generation<(e.get().state?.generation??-1))return!0;if(e.set({state:g,frame:pe(e.get().frame,W(g)),edit:{...e.get().edit,status:{kind:"done",op:f.op,step:f.step,label:f.label},problems:[]}}),p!==void 0)a(p);else{let y=e.get().pinned;y&&y.kind!=="slot"&&!q(g,y)&&a(null)}let b=e.get().pinned;return b&&b.kind!=="slot"&&t.seek(Ae(g,b,e.get().frame)),!0},i=()=>{let f=e.get();return f.state?q(f.state,f.pinned):void 0},l=(f,p,g)=>{n({saving:!0});let b=r.then(()=>xo(f,typeof p=="function"?p():p)).then(y=>(s=d(y,g),s));return r=b.catch(()=>!1),o.add(b),b.finally(()=>{o.delete(b),o.size||n({saving:!1})}),b},c=(f,p)=>l("/api/edit",()=>tn(e.get().state,f),p),u=async()=>{for(;o.size;)await Promise.all([...o])},h=async f=>{if(document.activeElement instanceof HTMLElement&&document.activeElement.blur(),await u(),!s)return;let p=e.get().state,g=i();p&&g&&await f(p,g)};return{send:c,reveal:(f,p)=>{t.pause(),t.seek(p??Ae(e.get().state,f,e.get().frame)),a(f)},flush:async()=>{for(document.activeElement instanceof HTMLElement&&document.activeElement.blur();o.size;)await Promise.all([...o]);return s},canSplit:()=>{let f=e.get();return!!(f.state&&xt(f.state,f.pinned,f.frame))},split:async()=>{let f=e.get(),p=f.state?xt(f.state,f.pinned,f.frame):void 0;p&&await l("/api/source",{source:p.source,base:f.state?.source})&&a(p.select)},replace:(f,p)=>l("/api/source",{source:f,base:p}),undo:async()=>{await u(),await l("/api/undo")},redo:async()=>{await u(),await l("/api/redo")},remove:()=>h(async(f,p)=>{if(p.kind==="segment"){let g=nn(f,p.index);g&&await l("/api/source",{source:g,base:f.source},null);return}await c(Xt(p),null)}),duplicate:()=>h(async(f,p)=>{if(p.kind==="segment"){let b=Qt(f,p.index);b&&await l("/api/source",{source:b.source,base:f.source},{kind:"segment",id:b.id});return}let g=Yt(f,p);g&&await c(g.op,g.select)}),addText:async()=>{let f=e.get(),p=f.state?Gt(f.state,f.frame,S(f.lang,"newText")):void 0;p&&await c(p.op,p.select)},render:async()=>{let p=await(await fetch("/api/render",{method:"POST"}).catch(()=>{}))?.json().catch(()=>{});p?.render?n({render:p.render}):p?.problems?.[0]&&n({status:{kind:"refused",problem:p.problems[0]}})},select:a,note:f=>n({status:{kind:"note",key:f}}),target:i,setRender:f=>n({render:f}),togglePlayRender:()=>n({playRender:!e.get().edit.playRender})}};var Eo={frame:null,playhead:"snapPlayhead",segment:"snapSegment",reference:"snapReference"},wo=(e,t,n,o)=>{let r=Pe(e.start+t,n,o),s=Pe(e.end+t,n,o),a=r.kind==="frame"?1/0:Math.abs(r.frame-(e.start+t)),d=s.kind==="frame"?1/0:Math.abs(s.frame-(e.end+t)),i=a<=d&&a!==1/0?r.frame-e.start:d!==1/0?s.frame-e.end:Math.round(t),l=a<=d&&a!==1/0?r:d!==1/0?s:{frame:e.start+i,kind:"frame"};return{start:e.start+i,end:e.end+i,snap:l}},ko=(e,t,n,o)=>{if(e.mode==="move")return wo(e,t,n,o);if(e.mode==="start"){let s=Pe(e.start+t,n,o);return{start:Math.min(s.frame,e.end-1),end:e.end,snap:s}}let r=Pe(e.end+t,n,o);return{start:e.start,end:Math.max(r.frame,e.start+1),snap:r}},Mo=(e,t,n,o)=>{let r=Eo[o.snap.kind],s=r?" \\xB7 "+S(e,"snapped")+" "+S(e,r):"";if(n.mode==="border"){let a=W(t),d=o.end-n.end;return(t.resolved?.segments.find(l=>l.end===n.end)?.id??"")+": "+(n.end-n.start)+" \\u2192 "+(o.end-n.start)+" "+S(e,"framesWord")+" \\xB7 "+S(e,"videoLength")+" "+a+" \\u2192 "+(a+d)+" ("+(d>=0?"+":"")+d+")"+s}return S(e,"onFrames")+" "+o.start+".."+(o.end-1)+s},To=(e,t,n)=>{let o=t.closest(".lane-track"),r=e.resolved;if(!o||!r)return;let s=t.closest(".seg-grip")?.dataset.border;if(s!==void 0){let p=r.segments[Number(s)];return p?{mode:"border",x0:n,track:o,start:p.start,end:p.end,border:Number(s),moved:!1}:void 0}let a=t.closest("[data-sel]")?.dataset.sel,d=a?JSON.parse(a):void 0;if(d?.kind!=="item"&&d?.kind!=="audio")return;let i=q(e,d),l=i?ht(i):void 0,c=d.kind==="audio"?r.audio.find(p=>p.id===d.id):void 0,u=(i&&l?on(i):void 0)??(c?{segment:r.segments[0]?.id,from:c.start,to:c.end??r.frames}:void 0);if(!i||!u)return;let h=Se(r,u);if(!h)return{mode:"move",x0:n,track:o,start:0,end:0,target:i,phrase:!0,moved:!1};let f=t.closest(".grip")?.dataset.grip;return{mode:f==="start"||f==="end"?f:"move",x0:n,track:o,start:h.start,end:h.end,target:i,span:u,moved:!1}},on=e=>{let t=e.kind==="cue"?e.track.cues[e.cue]:e.kind==="track"?e.track:void 0,n=t&&typeof t=="object"?t.during:void 0;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0},Lo=(e,t,n,o,r)=>{let s=o.state;if(!s||n.phrase)return;let a=W(s);if(!n.track.isConnected){let h=n.track.closest(".lane")?.id,f=h?e.querySelector("#"+CSS.escape(h)+" .lane-track"):null;if(!f)return;n.track=f}let d=n.track.getBoundingClientRect().width/Math.max(1,a);if(!Number.isFinite(d)||d<=0)return;let i=o.timeline?.snapping===!1?[]:qt(s,o.frame,n.mode!=="border"),l=ko(n.mode==="border"?{mode:"end",start:n.start,end:n.end}:n,(r-n.x0)/d,i,d);if(n.mode!=="border")if(n.mode==="move"){let h=Math.min(a,n.end-n.start);l.start=Math.max(0,Math.min(a-h,l.start)),l.end=l.start+h}else l.start=Math.max(0,l.start),l.end=Math.min(a,l.end);n.result=l,n.mode!=="border"&&n.track.append(Le(t.ghost,l.start,l.end,a));let c=e.querySelector(".playhead-layer");if(!c)return;let u=l.snap.kind!=="frame"?l.snap.frame:n.mode==="end"||n.mode==="border"?l.end:l.start;c.append(Q(t.guide,u,a)),t.guide.classList.toggle("snapped",l.snap.kind!=="frame"),t.label.textContent=Mo(o.lang,s,n,l),c.append(Q(t.label,Math.min(u,a*.6),a))},Ro=(e,t)=>{let n=t.resolved;if(!n||!e.result)return;if(e.mode==="border")return e.border!==void 0&&e.result.end!==e.end?{op:"set",path:["segments",e.border,"frames"],value:e.result.end-e.start}:void 0;let o=e.target?ht(e.target)??(e.target.kind==="track"&&e.target.track.type==="audio"?["tracks",e.target.index,"during"]:void 0):void 0,r=e.span??(e.target?on(e.target):void 0);if(!(!o||!r||e.result.start===e.start&&e.result.end===e.end))return{op:"set",path:o,value:yt(n,r,e.result.start,e.result.end)}},Ge=(e,t,n)=>{let o={ghost:m("div",{class:"drag-ghost",id:"drag-ghost"}),guide:m("div",{class:"snap-guide",id:"snap-guide"}),label:m("div",{class:"lane-readout",id:"lane-readout"})},r,s=!1,a;e.addEventListener("pointerdown",i=>{let l=t.get().state;if(i.button!==0||!l?.edit||t.get().edit.saving)return;document.activeElement instanceof HTMLElement&&document.activeElement!==document.body&&document.activeElement.blur();let c=i.target.closest("[data-sel]")?.dataset.sel;c&&n.select(JSON.parse(c));let u=c?JSON.parse(c):void 0;if(u?.kind==="segment"&&!i.target.closest(".seg-grip")){let h=l.resolved?.segments.findIndex(p=>p.id===u.id)??-1,f=i.target.closest(".lane-track");if(h>=0&&f){a={index:h,to:h,x:i.clientX,moved:!1,track:f},e.setPointerCapture(i.pointerId),i.preventDefault();return}}r=To(l,i.target,i.clientX),r&&(e.setPointerCapture(i.pointerId),i.preventDefault())}),e.addEventListener("pointermove",i=>{if(a){if(!a.moved&&Math.abs(i.clientX-a.x)<4)return;a.moved=!0;let l=t.get().state?.resolved;if(!l)return;let c=a.track.getBoundingClientRect(),u=(i.clientX-c.left)/c.width*l.frames;a.to=Math.max(0,l.segments.findIndex(p=>u<p.end)),u>=l.frames&&(a.to=l.segments.length-1);let h=l.segments[a.to]?.start??0,f=e.querySelector(".playhead-layer");o.label.textContent=(t.get().lang==="zh"?"\\u79FB\\u52A8\\u955C\\u5934 ":"Move shot ")+(a.index+1)+" \\u2192 "+(a.to+1),f?.append(Q(o.guide,h,l.frames),Q(o.label,Math.min(h,l.frames*.6),l.frames));return}!r||!r.moved&&Math.abs(i.clientX-r.x0)<3||(r.moved=!0,Lo(e,o,r,t.get(),i.clientX))});let d=i=>{if(a){let h=a;a=void 0,[o.ghost,o.guide,o.label].forEach(f=>f.remove()),h.moved&&(s=!0,setTimeout(()=>{s=!1},0),i.type!=="pointercancel"&&h.index!==h.to&&n.send({op:"move",path:["segments",h.index],to:h.to}));return}let l=r;if(r=void 0,[o.ghost,o.guide,o.label].forEach(h=>h.remove()),!l?.moved)return;s=!0,setTimeout(()=>{s=!1},0);let c=t.get().state;if(l.phrase)return n.note("phraseSpan");let u=c?Ro(l,c):void 0;u&&i.type!=="pointercancel"&&n.send(u)};e.addEventListener("pointerup",d),e.addEventListener("pointercancel",d),e.addEventListener("click",i=>{s&&(s=!1,i.stopImmediatePropagation())},!0)};var Po=e=>e?.anyOf?.find(t=>t.type==="object")??e,j=(e,...t)=>t.reduce((n,o)=>Po(n)?.properties?.[o],e),X=e=>(e?.enum??e?.anyOf?.find(t=>t.enum)?.enum??[]).map(t=>String(t));var Ye=e=>e===void 0||Math.abs(e)>=9e15?void 0:e,xe=e=>({...Ye(e?.minimum??e?.exclusiveMinimum)===void 0?{}:{min:Ye(e?.minimum??e?.exclusiveMinimum)},...Ye(e?.maximum??e?.exclusiveMaximum)===void 0?{}:{max:Ye(e?.maximum??e?.exclusiveMaximum)},integer:e?.type==="integer"}),Xe=async()=>{let e=await fetch("/api/schema",{cache:"no-store"}).catch(()=>{});return e?.ok?await e.json():null};var Ao={noReference:"No reference video is available for this project.",shots:"Shots",media:"Media",script:"Script",elements:"Elements",code:"Code",checks:"Review",versions:"Versions",export:"Export",compare:"Compare",layout:"Layout",theme:"Theme",saved:"Saved locally",readOnly:"Read only",live:"Connected",offline:"Disconnected",preview:"Preview",current:"Current",add:"Add",upload:"Import",search:"Search",scene:"Animated scene",video:"Video",image:"Image",color:"Background",duration:"Duration",keepRhythm:"Keep reference rhythm",content:"Content",properties:"Properties",viewAll:"Fit timeline",assist:"Analysis",zoom:"Zoom",audio:"Project audio",onlyPreview:"Preview controls do not change exported audio",sourceTitle:"Draft JSON",autosave:"Valid JSON saves automatically",format:"Format JSON",download:"Download JSON",invalid:"Invalid JSON \\u2014 draft kept",saving:"Saving\\u2026",conflict:"The draft changed elsewhere. Reload before saving.",reload:"Reload JSON",choose:"Select an item to edit",text:"Text",audioTrack:"Audio",subtitles:"Subtitles",voice:"Voiceover",music:"Music / effects",addText:"Add text",duplicate:"Duplicate",remove:"Delete",undo:"Undo",redo:"Redo",time:"Time",wordBound:"Follows speech",original:"Original",resolution:"Resolution",dynamicRange:"Dynamic range",hdrUnavailable:"HDR is unavailable: this HTML renderer outputs SDR.",fps:"Frame rate",match:"Match timeline",bitrate:"Video bitrate",recommended:"Recommended",filename:"File name",includeAudio:"Include project audio",range:"Range",full:"Full video",start:"Start frame",end:"End frame (exclusive)",paid:"Paid benefit",paidInfo:"This feature is available with a paid plan.",unlock:"Unlock",refreshPlan:"Refresh plan",preparing:"Preparing",rendering:"Rendering",renderDone:"Export ready",stale:"The draft changed after this export",play:"Play",downloadVideo:"Download video",exportSnapshot:"Export uses the JSON snapshot at start. You can continue editing.",general:"General",effects:"Timing and motion",sourceFile:"Source file",missing:"Missing",replace:"Replace",apply:"Apply",applyShot:"Use in selected shot",addOverlay:"Add overlay",slot:"Scene field",noSlots:"This scene exposes no editable slots. Use JSON to change its source or replace the scene.",currentShot:"Current shot",selected:"Selected",noMedia:"No project media",importHint:"Images, video or audio up to 12 MB",scriptHint:"Editing captions does not regenerate voiceover.",pendingVoice:"Caption changed; review voiceover",all:"All",notes:"Notes",comment:"Add timed note",noteHint:"Describe the change at this frame\\u2026",resolved:"Resolved",resolve:"Resolve",reopen:"Reopen",copyNote:"Copy change request",noNotes:"No review notes yet",noProblems:"No structural problems found",unmeasured:"No comparison measurements for this version",saveVersion:"Save version",restore:"Restore",versionName:"Version name",noVersions:"No saved versions",defaultLayout:"Default layout",focusedPreview:"Focus preview",codeHint:"Changes update the same draft after validation. Invalid JSON never overwrites it.",sourceChanged:"Draft saved",quality:"Quality",loading:"Loading\\u2026",sameAsReference:"Reference / replica",toggleAnalysis:"Show analysis lanes",sceneFields:"Scene content",position:"Position",trackGain:"Gain (dB)",chooseMaterial:"Choose a material, then select where to use it.",unsupported:"Unavailable for this selection",refresh:"Refresh",inspect:"Inspect",seconds:"s",waveform:"Waveform",recheck:"Reload checks",sourceExport:"The source JSON is included separately; it is not an MP4.",goShot:"Go to shot",moveUp:"Move earlier",moveDown:"Move later",narrationUnavailable:"Voice generation is managed by the Agent. Copy the revised script to request updated narration.",copyScript:"Copy revised script",applyCaption:"Save caption",error:"Could not complete the operation",fileRange:"Whole timeline",frame:"Frame",newVersion:"Studio version",noSelection:"Select a shot, caption or overlay to edit.",segment:"Shot",previewQuality:"Fit preview",allChanges:"All changes saved",currentExport:"Export current draft",jsonDownload:"Download the saved video.json",imageSlot:"Replace image slot",selectedSlot:"Selected scene field",sceneOffset:"Scene element offset",fontSize:"Font size",textColor:"Text colour",versionSnapshot:"Saved versions preserve the draft JSON; assets are reused.",bitrateUnit:"Mbps",reviewOnly:"Review notes are local; sending to an Agent requires copying the request."},Co={noReference:"\\u6B64\\u9879\\u76EE\\u6CA1\\u6709\\u53C2\\u8003\\u89C6\\u9891\\u3002",shots:"\\u955C\\u5934",media:"\\u7D20\\u6750",script:"\\u6587\\u7A3F",elements:"\\u5143\\u7D20",code:"\\u4EE3\\u7801",checks:"\\u68C0\\u67E5",versions:"\\u7248\\u672C",export:"\\u5BFC\\u51FA",compare:"\\u5BF9\\u7167",layout:"\\u5E03\\u5C40",theme:"\\u4E3B\\u9898",saved:"\\u5DF2\\u4FDD\\u5B58\\u5230\\u672C\\u673A",readOnly:"\\u53EA\\u8BFB",live:"\\u5DF2\\u8FDE\\u63A5",offline:"\\u8FDE\\u63A5\\u5DF2\\u65AD\\u5F00",preview:"\\u6210\\u7247\\u9884\\u89C8",current:"\\u5F53\\u524D",add:"\\u6DFB\\u52A0",upload:"\\u5BFC\\u5165\\u7D20\\u6750",search:"\\u641C\\u7D22",scene:"\\u52A8\\u6001\\u573A\\u666F",video:"\\u89C6\\u9891",image:"\\u56FE\\u7247",color:"\\u80CC\\u666F",duration:"\\u65F6\\u957F",keepRhythm:"\\u4FDD\\u6301\\u53C2\\u8003\\u8282\\u594F",content:"\\u5185\\u5BB9",properties:"\\u5C5E\\u6027",viewAll:"\\u9002\\u914D\\u65F6\\u95F4\\u7EBF",assist:"\\u8F85\\u52A9\\u4FE1\\u606F",zoom:"\\u7F29\\u653E",audio:"\\u9879\\u76EE\\u58F0\\u97F3",onlyPreview:"\\u8BD5\\u542C\\u63A7\\u5236\\u4E0D\\u4F1A\\u6539\\u53D8\\u5BFC\\u51FA\\u58F0\\u97F3",sourceTitle:"\\u8349\\u7A3F JSON",autosave:"\\u6709\\u6548 JSON \\u5C06\\u81EA\\u52A8\\u4FDD\\u5B58",format:"\\u683C\\u5F0F\\u5316",download:"\\u4E0B\\u8F7D JSON",invalid:"JSON \\u65E0\\u6548\\uFF0C\\u5DF2\\u4FDD\\u7559\\u8F93\\u5165",saving:"\\u4FDD\\u5B58\\u4E2D\\u2026",conflict:"\\u8349\\u7A3F\\u5DF2\\u5728\\u5176\\u4ED6\\u4F4D\\u7F6E\\u4FEE\\u6539\\uFF0C\\u8BF7\\u5148\\u91CD\\u65B0\\u8F7D\\u5165\\u3002",reload:"\\u91CD\\u65B0\\u8F7D\\u5165 JSON",choose:"\\u9009\\u62E9\\u5BF9\\u8C61\\u540E\\u7F16\\u8F91",text:"\\u6587\\u5B57",audioTrack:"\\u97F3\\u9891",subtitles:"\\u5B57\\u5E55",voice:"\\u914D\\u97F3",music:"\\u97F3\\u4E50 / \\u97F3\\u6548",addText:"\\u6DFB\\u52A0\\u6587\\u5B57",duplicate:"\\u590D\\u5236",remove:"\\u5220\\u9664",undo:"\\u64A4\\u9500",redo:"\\u91CD\\u505A",time:"\\u65F6\\u95F4",wordBound:"\\u8DDF\\u968F\\u914D\\u97F3",original:"\\u539F\\u59CB",resolution:"\\u5206\\u8FA8\\u7387",dynamicRange:"\\u52A8\\u6001\\u8303\\u56F4",hdrUnavailable:"\\u5F53\\u524D HTML \\u6E32\\u67D3\\u5668\\u8F93\\u51FA SDR\\uFF0C\\u6682\\u4E0D\\u652F\\u6301 HDR\\u3002",fps:"\\u5E27\\u7387",match:"\\u5339\\u914D\\u65F6\\u95F4\\u7EBF",bitrate:"\\u89C6\\u9891\\u7801\\u7387",recommended:"\\u63A8\\u8350",filename:"\\u6587\\u4EF6\\u540D",includeAudio:"\\u5305\\u542B\\u9879\\u76EE\\u58F0\\u97F3",range:"\\u5BFC\\u51FA\\u8303\\u56F4",full:"\\u5B8C\\u6574\\u89C6\\u9891",start:"\\u5F00\\u59CB\\u5E27",end:"\\u7ED3\\u675F\\u5E27\\uFF08\\u4E0D\\u542B\\uFF09",paid:"\\u4ED8\\u8D39\\u6743\\u76CA",paidInfo:"\\u8BE5\\u529F\\u80FD\\u4E3A\\u4ED8\\u8D39\\u6743\\u76CA\\uFF0C\\u4ED8\\u8D39\\u540E\\u53EF\\u4F7F\\u7528\\u3002",unlock:"\\u524D\\u5F80\\u89E3\\u9501",refreshPlan:"\\u5237\\u65B0\\u6743\\u76CA",preparing:"\\u51C6\\u5907\\u4E2D",rendering:"\\u6B63\\u5728\\u5BFC\\u51FA",renderDone:"\\u5BFC\\u51FA\\u5B8C\\u6210",stale:"\\u6B64\\u540E\\u8349\\u7A3F\\u5DF2\\u4FEE\\u6539\\uFF0C\\u9700\\u8981\\u91CD\\u65B0\\u5BFC\\u51FA",play:"\\u64AD\\u653E",downloadVideo:"\\u4E0B\\u8F7D\\u89C6\\u9891",exportSnapshot:"\\u5BFC\\u51FA\\u4F7F\\u7528\\u5F00\\u59CB\\u65F6\\u7684 JSON \\u5FEB\\u7167\\uFF0C\\u4F60\\u53EF\\u4EE5\\u7EE7\\u7EED\\u7F16\\u8F91\\u3002",general:"\\u5E38\\u89C4",effects:"\\u65F6\\u95F4\\u4E0E\\u52A8\\u6548",sourceFile:"\\u6E90\\u6587\\u4EF6",missing:"\\u7F3A\\u5931",replace:"\\u66FF\\u6362",apply:"\\u5E94\\u7528",applyShot:"\\u66FF\\u6362\\u5F53\\u524D\\u955C\\u5934\\u7D20\\u6750",addOverlay:"\\u6DFB\\u52A0\\u4E3A\\u53E0\\u52A0\\u5143\\u7D20",slot:"\\u573A\\u666F\\u5B57\\u6BB5",noSlots:"\\u8BE5\\u573A\\u666F\\u672A\\u516C\\u5F00\\u53EF\\u7F16\\u8F91\\u5B57\\u6BB5\\uFF0C\\u53EF\\u901A\\u8FC7\\u4EE3\\u7801\\u66F4\\u6362\\u573A\\u666F\\u6216\\u4EA4\\u7ED9 Agent \\u4FEE\\u6539\\u3002",currentShot:"\\u5F53\\u524D\\u955C\\u5934",selected:"\\u5DF2\\u9009\\u4E2D",noMedia:"\\u9879\\u76EE\\u6682\\u65E0\\u7D20\\u6750",importHint:"\\u652F\\u6301\\u56FE\\u7247\\u3001\\u89C6\\u9891\\u548C\\u97F3\\u9891\\uFF0C\\u5355\\u6587\\u4EF6\\u4E0D\\u8D85\\u8FC7 12 MB",scriptHint:"\\u4FEE\\u6539\\u5B57\\u5E55\\u4E0D\\u4F1A\\u81EA\\u52A8\\u91CD\\u505A\\u914D\\u97F3\\u3002",pendingVoice:"\\u5B57\\u5E55\\u5DF2\\u4FEE\\u6539\\uFF0C\\u8BF7\\u6838\\u5BF9\\u914D\\u97F3",all:"\\u5168\\u90E8",notes:"\\u4FEE\\u6539\\u610F\\u89C1",comment:"\\u6DFB\\u52A0\\u65F6\\u95F4\\u70B9\\u610F\\u89C1",noteHint:"\\u63CF\\u8FF0\\u5F53\\u524D\\u753B\\u9762\\u9700\\u8981\\u600E\\u6837\\u4FEE\\u6539\\u2026",resolved:"\\u5DF2\\u5904\\u7406",resolve:"\\u6807\\u8BB0\\u5DF2\\u5904\\u7406",reopen:"\\u91CD\\u65B0\\u6253\\u5F00",copyNote:"\\u590D\\u5236\\u7ED9 Agent \\u7684\\u4FEE\\u6539\\u8BF4\\u660E",noNotes:"\\u8FD8\\u6CA1\\u6709\\u4FEE\\u6539\\u610F\\u89C1",noProblems:"\\u672A\\u53D1\\u73B0\\u7ED3\\u6784\\u95EE\\u9898",unmeasured:"\\u5F53\\u524D\\u7248\\u672C\\u6682\\u65E0\\u5BF9\\u6BD4\\u6D4B\\u91CF\\u7ED3\\u679C",saveVersion:"\\u4FDD\\u5B58\\u4E00\\u4E2A\\u7248\\u672C",restore:"\\u6062\\u590D",versionName:"\\u7248\\u672C\\u540D\\u79F0",noVersions:"\\u8FD8\\u6CA1\\u6709\\u4FDD\\u5B58\\u7684\\u7248\\u672C",defaultLayout:"\\u9ED8\\u8BA4\\u5E03\\u5C40",focusedPreview:"\\u4E13\\u6CE8\\u9884\\u89C8",codeHint:"\\u7F16\\u8F91\\u540E\\u81EA\\u52A8\\u6821\\u9A8C\\u5E76\\u66F4\\u65B0\\u540C\\u4E00\\u4EFD\\u8349\\u7A3F\\uFF1B\\u65E0\\u6548 JSON \\u4E0D\\u4F1A\\u8986\\u76D6\\u539F\\u6587\\u4EF6\\u3002",sourceChanged:"\\u8349\\u7A3F\\u5DF2\\u4FDD\\u5B58",quality:"\\u753B\\u8D28",loading:"\\u52A0\\u8F7D\\u4E2D\\u2026",sameAsReference:"\\u53C2\\u8003 / \\u6210\\u7247",toggleAnalysis:"\\u663E\\u793A\\u5206\\u6790\\u8F68\\u9053",sceneFields:"\\u573A\\u666F\\u5185\\u5BB9",position:"\\u4F4D\\u7F6E",trackGain:"\\u589E\\u76CA\\uFF08dB\\uFF09",chooseMaterial:"\\u9009\\u62E9\\u7D20\\u6750\\u540E\\uFF0C\\u6307\\u5B9A\\u66FF\\u6362\\u955C\\u5934\\u6216\\u6DFB\\u52A0\\u53E0\\u52A0\\u5143\\u7D20\\u3002",unsupported:"\\u5F53\\u524D\\u9009\\u62E9\\u4E0D\\u652F\\u6301\\u6B64\\u64CD\\u4F5C",refresh:"\\u5237\\u65B0",inspect:"\\u67E5\\u770B",seconds:"\\u79D2",waveform:"\\u6CE2\\u5F62",recheck:"\\u5237\\u65B0\\u68C0\\u67E5",sourceExport:"JSON \\u5355\\u72EC\\u4E0B\\u8F7D\\uFF0C\\u89C6\\u9891\\u901A\\u8FC7\\u5BFC\\u51FA\\u9762\\u677F\\u751F\\u6210\\u3002",goShot:"\\u5B9A\\u4F4D\\u955C\\u5934",moveUp:"\\u5411\\u524D\\u79FB\\u52A8",moveDown:"\\u5411\\u540E\\u79FB\\u52A8",narrationUnavailable:"\\u914D\\u97F3\\u751F\\u6210\\u7531 Agent \\u5904\\u7406\\uFF0C\\u590D\\u5236\\u4FEE\\u6539\\u6587\\u7A3F\\u540E\\u53EF\\u8BF7\\u6C42\\u66F4\\u65B0\\u58F0\\u97F3\\u3002",copyScript:"\\u590D\\u5236\\u4FEE\\u6539\\u540E\\u7684\\u6587\\u7A3F",applyCaption:"\\u4FDD\\u5B58\\u5B57\\u5E55",error:"\\u64CD\\u4F5C\\u672A\\u5B8C\\u6210",fileRange:"\\u6574\\u6761\\u65F6\\u95F4\\u7EBF",frame:"\\u5E27",newVersion:"Studio \\u7248\\u672C",noSelection:"\\u9009\\u62E9\\u955C\\u5934\\u3001\\u5B57\\u5E55\\u6216\\u53E0\\u52A0\\u5143\\u7D20\\u5373\\u53EF\\u7F16\\u8F91\\u3002",segment:"\\u955C\\u5934",previewQuality:"\\u9002\\u914D\\u9884\\u89C8",allChanges:"\\u6240\\u6709\\u66F4\\u6539\\u5DF2\\u4FDD\\u5B58",currentExport:"\\u5BFC\\u51FA\\u5F53\\u524D\\u8349\\u7A3F",jsonDownload:"\\u4E0B\\u8F7D\\u5DF2\\u4FDD\\u5B58\\u7684 video.json",imageSlot:"\\u66FF\\u6362\\u56FE\\u7247\\u69FD",selectedSlot:"\\u5F53\\u524D\\u573A\\u666F\\u5B57\\u6BB5",sceneOffset:"\\u573A\\u666F\\u5143\\u7D20\\u504F\\u79FB",fontSize:"\\u5B57\\u53F7",textColor:"\\u6587\\u5B57\\u989C\\u8272",versionSnapshot:"\\u7248\\u672C\\u4FDD\\u5B58\\u8349\\u7A3F JSON\\uFF0C\\u5E76\\u7EE7\\u7EED\\u5F15\\u7528\\u539F\\u7D20\\u6750\\u3002",bitrateUnit:"Mbps",reviewOnly:"\\u610F\\u89C1\\u4FDD\\u5B58\\u5728\\u672C\\u673A\\uFF1B\\u590D\\u5236\\u540E\\u53EF\\u4EA4\\u7ED9 Agent \\u7EE7\\u7EED\\u4FEE\\u6539\\u3002"},x=(e,t)=>(e.get().lang==="zh"?Co:Ao)[t];var C=(e,t,n="")=>m("button",{class:"studio-btn "+n,text:e,attrs:{type:"button"},on:{click:t}}),ne=(e,t,n)=>m("button",{class:"studio-btn studio-icon-btn",attrs:{type:"button",title:e,"aria-label":e},on:{click:n}},[Y(t)]),U=(e,t)=>m("div",{class:"studio-heading"},[m("h2",{text:e}),...t?[m("small",{text:t})]:[]]),A=(e,t="")=>m("p",{class:"studio-note "+t,text:e}),Ce=e=>"/project/"+e.replace(/^\\.\\//,"").split("/").map(encodeURIComponent).join("/"),rn=(e,t)=>{let n=URL.createObjectURL(new Blob([e],{type:"application/json"}));m("a",{attrs:{href:n,download:t}}).click(),setTimeout(()=>URL.revokeObjectURL(n),1e3)},ce=(e,t)=>{let n=document.getElementById("studio-message");n?(n.textContent=t,n.classList.add("visible"),setTimeout(()=>n.classList.remove("visible"),6e3)):e.set({pageError:t})},J=async(e,t)=>{let n=await fetch(e,{...t===void 0?{}:{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)},cache:"no-store"}),o=await n.json();if(!n.ok||o.ok===!1)throw new Error(o.problems?.[0]?.message??"Request failed: "+n.status);return o},ke=async(e,t,n)=>{try{let o=await J(t,n);e.set({state:o.state})}catch(o){ce(e,o instanceof Error?o.message:x(e,"error"))}},G=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},$=e=>Array.isArray(e)?e.map(G):[],Oe=(e,t,n)=>{let o=m("input",{attrs:{type:"text","aria-label":t},class:"studio-input"});return o.value=e,n&&o.addEventListener("change",()=>n(o.value)),o},wt=(e,t,n,o)=>{let r=m("select",{class:"studio-input",attrs:{"aria-label":n}},e.map(([s,a])=>m("option",{text:a,attrs:{value:s}})));return r.value=t,r.addEventListener("change",()=>o(r.value)),r},Me=(e,t)=>m("label",{class:"studio-field"},[m("span",{text:e}),t]),sn=(e,t)=>m("img",{class:"studio-thumb",attrs:{src:"/api/thumbnail?frame="+Math.floor(e)+"&g="+t,loading:"lazy",alt:""}}),Ze=(e,t)=>{let n=Math.floor(e/t);return[Math.floor(n/60),n%60,e%Math.round(t)].map(o=>Math.floor(o).toString().padStart(2,"0")).join(":")};var be=(e,t,n=t.get().frame)=>{let o=t.get(),r=o.state?.resolved;if(!r)return[];let s=Z(r,n);if(!s)return[];let a=e.contentDocument;if(!a)return[];let d=[];for(let i of Array.from(a.querySelectorAll("iframe"))){let l=i.contentDocument,c=i.contentWindow;if(!l||!c||i.parentElement?.dataset.segment!==s.id)continue;let u=i.getBoundingClientRect();if(!(!u.width||!u.height)&&c.getComputedStyle(i).visibility!=="hidden")for(let h of Array.from(l.querySelectorAll("[data-slot]"))){let f=!0,p=1;for(let y=h;y;y=y.parentElement){let v=c.getComputedStyle(y);p*=Number(v.opacity),(v.display==="none"||v.visibility==="hidden")&&(f=!1)}let g=h.getBoundingClientRect();if(!f||p<.1||!g.width||!g.height||g.right<=0||g.bottom<=0||g.left>=i.clientWidth||g.top>=i.clientHeight)continue;let b=h.dataset.slot;b&&d.push({selection:{kind:"slot",id:s.id,name:b},box:[(u.left+g.left*u.width/(i.clientWidth||r.canvas.width))/r.canvas.width,(u.top+g.top*u.height/(i.clientHeight||r.canvas.height))/r.canvas.height,g.width/r.canvas.width,g.height/r.canvas.height],value:h.tagName==="IMG"?h.getAttribute("src")??"":h.textContent??"",image:h.tagName==="IMG"})}}return d},an=new WeakMap,He=(e,t,n)=>{let o=t.get(),r=o.state?.resolved?.segments.find(u=>u.id===n),s=e?.contentWindow?.__popostVideo;if(!e||!r||!s||document.body.dataset.ready!=="1"||new URL(e.src).searchParams.get("g")!==String(o.state?.generation)||r.base.kind!=="scene")return;let a=e.contentDocument,d=a?.querySelector('[data-segment="'+CSS.escape(n)+'"] > iframe')?.contentDocument;if(!a||!d||d.URL==="about:blank"||d.readyState!=="complete")return;let i=an.get(e);(!i||i.generation!==o.state.generation||i.page!==a)&&(i={generation:o.state.generation,page:a,segments:new Map},an.set(e,i));let l=i.segments.get(n);if(l?.scene===d)return l.frames;let c=new Map;try{for(let u=0;u<=32;u++){let h=Math.min(r.end-1,r.start+Math.floor((r.end-r.start)*u/33));s.applyFrame(h);for(let f of be(e,t,h))c.has(f.selection.name)||c.set(f.selection.name,h)}}finally{s.applyFrame(o.frame)}return i.segments.set(n,{scene:d,frames:c}),c},Qe=(e,t,n)=>e&&be(e,t).some(o=>o.selection.id===n.id&&o.selection.name===n.name)?t.get().frame:He(e,t,n.id)?.get(n.name),dn=(e,t)=>{let n=e.get(),o=n.pinned,r=m("div",{class:"form",id:"slot-inspector"});if(o?.kind!=="slot")return r;let s=n.lang==="zh",a=G(n.state?.source),d=$(a.segments).findIndex(i=>i.id===o.id);return r.append(m("div",{class:"sel-title",text:s?"\\u573A\\u666F\\u5143\\u7D20":"Scene element"})),J("/api/studio").then(i=>{if(!r.isConnected)return;let l=i.slots.find(h=>h.segment===o.id&&h.name===o.name);if(!l)return;let c=l.kind==="image"?Oe(l.value,s?"\\u56FE\\u7247\\u5730\\u5740":"Image path"):m("textarea",{class:"studio-input",attrs:{rows:"5","aria-label":s?"\\u6587\\u5B57\\u5185\\u5BB9":"Text content"}});c.value=l.value;let u=h=>{let f=G($(G(e.get().state?.source).segments)[d]?.base);t.send({op:"set",path:["segments",d,"base","slots"],value:{...G(f.slots),[l.name]:h}})};if(c.addEventListener("change",()=>u(c.value)),c.addEventListener("keydown",h=>{let f=h;(f.ctrlKey||f.metaKey)&&f.key==="Enter"&&c.blur()}),l.kind==="image"){let h=G($(a.segments)[d]?.base),f=String(h.scene??""),p=new URL(l.value,location.origin+"/project/"+f);p.origin===location.origin&&p.pathname.startsWith("/project/")&&r.append(m("img",{class:"studio-slot-preview",attrs:{src:p.href,alt:s?"\\u5F53\\u524D\\u56FE\\u7247":"Current image"}}));let g=$(a.materials).filter(b=>b.kind==="image");if(g.length){let b=m("select",{class:"studio-input",attrs:{"aria-label":s?"\\u66FF\\u6362\\u56FE\\u7247":"Replace image"}},[m("option",{text:s?"\\u9009\\u62E9\\u7D20\\u6750\\u4E2D\\u7684\\u56FE\\u7247":"Choose an image",attrs:{value:""}}),...g.map((y,v)=>m("option",{text:String(y.note??y.file??(s?"\\u56FE\\u7247 ":"Image ")+(v+1)),attrs:{value:String(y.id)}}))]);b.addEventListener("change",()=>{let y=g.find(v=>v.id===b.value);y&&u("../".repeat(f.split("/").length-1)+String(y.file))}),r.append(Me(s?"\\u66FF\\u6362\\u56FE\\u7247":"Replace image",b))}else r.append(A(s?"\\u5148\\u5728\\u7D20\\u6750\\u4E2D\\u5BFC\\u5165\\u56FE\\u7247\\uFF0C\\u518D\\u56DE\\u5230\\u8FD9\\u91CC\\u66FF\\u6362\\u3002":"Import an image in Media, then select it here."));r.append(m("details",{},[m("summary",{text:s?"\\u56FE\\u7247\\u5730\\u5740":"Image path"}),c]))}else r.append(Me(s?"\\u6587\\u5B57\\u5185\\u5BB9":"Text content",c));r.append(A(s?"\\u4FEE\\u6539\\u4F1A\\u4FDD\\u5B58\\u5230\\u5F53\\u524D\\u5DE5\\u7A0B\\uFF0C\\u5E76\\u7528\\u4E8E\\u89C6\\u9891\\u5BFC\\u51FA\\u3002":"Changes are saved to this project and used in the exported video."))}).catch(i=>r.append(A(String(i),"bad"))),r};var ln=(e,t,n,o)=>{let r,s=a=>{let d=r;d&&(r=void 0,a&&d.dispatchEvent(new Event("commit")),d.remove())};e.addEventListener("studio:inline-edit",a=>{if(r)return;let d=n.get(),i=d.pinned;if(!i||!d.state||a.target.closest(".handle"))return;let l=q(d.state,i),c=i.kind==="item"?d.state.resolved?.items.find(g=>g.id===i.id):void 0,u=i.kind==="slot"?be(t,n).find(g=>g.selection.id===i.id&&g.selection.name===i.name):void 0;if(u?.image||l?.kind==="track"&&l.track.type==="image"){document.querySelector('#slot-inspector select, #edit-form select[data-path$=".material"]')?.focus();return}let h=u?.value??c?.text,f=u?.box??(l?Re(d.state,l):void 0);if(h===void 0||!f)return;s(!0),a.preventDefault(),a.stopPropagation();let p=m("textarea",{id:"stage-text-editor",class:"stage-text-editor",attrs:{"aria-label":d.lang==="zh"?"\\u76F4\\u63A5\\u7F16\\u8F91\\u6587\\u5B57":"Edit text on canvas"}});p.value=h,le(p,f),p.style.fontSize=Math.max(14,(c?.style?.size??.04)*(d.state.resolved?.canvas.height??1)*e.clientWidth/(d.state.resolved?.canvas.width??1))+"px",p.addEventListener("commit",()=>{if(!(p.value===h||!p.value.trim()))if(i.kind==="slot"){let g=n.get().state,b=$(G(g?.source).segments).findIndex(v=>v.id===i.id),y=G($(G(g?.source).segments)[b]?.base);o.send({op:"set",path:["segments",b,"base","slots"],value:{...G(y.slots),[i.name]:p.value}})}else l?.kind==="cue"?o.send({op:"set",path:["tracks",l.index,"cues",l.cue,"text"],value:p.value}):l?.kind==="track"&&o.send({op:"set",path:["tracks",l.index,"text"],value:p.value})}),p.addEventListener("blur",()=>s(!0)),p.addEventListener("pointerdown",g=>g.stopPropagation()),p.addEventListener("keydown",g=>{g.key==="Escape"?(g.preventDefault(),g.stopPropagation(),s(!1)):g.key==="Enter"&&(g.metaKey||g.ctrlKey)&&(g.preventDefault(),s(!0))}),e.append(p),r=p,p.focus(),p.select()}),n.subscribe((a,d)=>{(a.pinned!==d.pinned||a.state!==d.state||a.frame!==d.frame)&&s(!1)})};var Oo=["nw","n","ne","e","se","s","sw","w"],Ho=(e,t)=>{if(t.kind==="segment")return[];let n=String(t.track.id);return(e.state?.resolved?.items??[]).filter(o=>o.id===n||o.cue?.track===n).map(o=>o.id)},No=(e,t)=>{let n=e.state?.resolved;if(!n||t.kind==="segment")return!1;let o=t.kind==="cue"?String(t.track.id)+"#"+t.cue:String(t.track.id);return fe(n,e.frame).some(r=>r.id===o)},Io=(e,t,n,o,r,s)=>{let[a,d,i,l]=e.box0,c=(E,M)=>Math.round(E*M)/M;if(e.mode==="move")return[c(a+t,o),c(d+n,r),i,l];let[u,h,f,p]=[a,d,a+i,d+l];if(e.mode.includes("w")&&(u+=t),e.mode.includes("e")&&(f+=t),e.mode.includes("n")&&(h+=n),e.mode.includes("s")&&(p+=n),s){let E=i*o/(l*r),M=f-u,k=p-h;if(e.mode.length===1?e.mode==="e"||e.mode==="w":Math.abs(M/i-1)>=Math.abs(k/l-1)){let L=M*o/E/r;e.mode.includes("n")?h=p-L:(e.mode.includes("s")||(h=d+l/2-L/2),p=h+L)}else{let L=k*r*E/o;e.mode.includes("w")?u=f-L:(e.mode.includes("e")||(u=a+i/2-L/2),f=u+L)}}let[g,b,y,v]=[c(u,o),c(h,r),c(f,o),c(p,r)];return[Math.min(g,y-1/o),Math.min(b,v-1/r),Math.max(1/o,y-g),Math.max(1/r,v-b)]},Fo=(e,t,n)=>{let o=(s,a)=>String(Math.round(s*a)),r=s=>s.toFixed(3);return"x "+o(e[0],t)+" y "+o(e[1],n)+" "+o(e[2],t)+"\\xD7"+o(e[3],n)+" px ("+[e[0],e[1],e[2],e[3]].map(r).join(", ")+")"},Do=(e,t)=>{let n=new Map;return{move:(o,r)=>{let s=e.contentDocument,{W:a,H:d}=$e(t.get());for(let i of Ho(t.get(),o)){let l=s?.querySelector('[data-item="'+CSS.escape(i)+'"]');l&&(n.has(l)||n.set(l,l.style.cssText),Object.assign(l.style,{left:r[0]*a+"px",top:r[1]*d+"px",width:r[2]*a+"px",height:r[3]*d+"px"}))}},restore:()=>{n.forEach((o,r)=>{r.style.cssText=o}),n=new Map},forget:()=>{n=new Map}}},$e=e=>({W:e.state?.resolved?.canvas.width??1,H:e.state?.resolved?.canvas.height??1}),jo=(e,t,n,o)=>{let r=t.state?.resolved;if(!r)return;let s=e.getBoundingClientRect(),a=(n-s.left)/s.width,d=(o-s.top)/s.height;return[...fe(r,t.frame)].reverse().find(i=>a>=i.box[0]&&a<=i.box[0]+i.box[2]&&d>=i.box[1]&&d<=i.box[1]+i.box[3])?.id},zo=(e,t,n)=>{let o=t.state?q(t.state,t.pinned):void 0,r=n??(o&&t.state?Re(t.state,o):void 0),s=!!(r&&o&&(n||No(t,o)));if(e.layer.classList.toggle("off",!t.state?.resolved),e.sel.hidden=!s,e.readout.hidden=!n,s&&r&&(le(e.sel,r),e.sel.classList.toggle("thin",e.sel.getBoundingClientRect().height<18)),n){let{W:a,H:d}=$e(t);e.readout.textContent=Fo(n,a,d)}},cn=e=>{let t=e.state?q(e.state,e.pinned):void 0,n=t&&e.state?Re(e.state,t):void 0;return t&&n?{t,box:n}:void 0},et=(e,t,n,o)=>{let r=m("div",{class:"sel-box",id:"sel-box"},Oo.map(v=>m("div",{class:"handle h-"+v,data:{h:v}}))),s=m("div",{class:"drag-readout",id:"drag-readout"}),a=m("div",{class:"studio-slot-outline",attrs:{hidden:""}},[m("span",{class:"studio-slot-name"})]),d={layer:m("div",{class:"edit-layer",id:"edit-layer"},[r,s]),sel:r,readout:s};d.layer.append(a),e.append(d.layer),ln(e,t,n,o);let i=Do(t,n),l,c,u,h,f=!0,p=()=>{let v=n.get();zo(d,v,l&&!l.moved?void 0:u?.box);let E=v.pinned,M=E?.kind==="slot"?be(t,n).find(k=>k.selection.id===E.id&&k.selection.name===E.name):void 0;if(E?.kind==="slot"&&f&&document.body.dataset.ready==="1"){f=!1;let k=Qe(t,n,E);if(k===void 0){o.select(null);return}if(k!==v.frame){o.reveal(E,k);return}}a.hidden=!M,M&&(le(a,M.box),a.firstElementChild.textContent=M.image?v.lang==="zh"?"\\u56FE\\u7247":"Image":M.value.slice(0,40))},g=(v,E)=>{let M=bt(v);M&&o.send({op:"set",path:M,value:Zt(E)}).then(k=>{k||i.restore(),u=void 0,p()})},b=(v,E)=>{u={box:E,target:v},i.move(v,E),p()};d.layer.addEventListener("pointerdown",v=>{if(v.button!==0||!n.get().state?.resolved||n.get().edit.saving||v.target.closest("#stage-text-editor"))return;let E=n.get().pinned;if((E?.kind==="slot"?be(t,n).some(L=>L.selection.id===E.id&&L.selection.name===E.name&&!L.image):E?.kind==="item"&&n.get().state?.resolved?.items.some(L=>L.id===E.id&&L.type==="text"))&&c&&performance.now()-c.time<450&&Math.hypot(v.clientX-c.x,v.clientY-c.y)<6&&!v.target.closest(".handle")){c=void 0,e.dispatchEvent(new Event("studio:inline-edit")),v.preventDefault();return}document.activeElement instanceof HTMLElement&&document.activeElement!==document.body&&document.activeElement.blur();let k=v.target.closest(".handle")?.dataset.h;if(!k&&!v.target.closest(".sel-box")){let L=jo(e,n.get(),v.clientX,v.clientY);if(!L){let R=e.getBoundingClientRect(),F=(v.clientX-R.left)/R.width,O=(v.clientY-R.top)/R.height,D=be(t,n).reverse().find(w=>F>=w.box[0]&&F<=w.box[0]+w.box[2]&&O>=w.box[1]&&O<=w.box[1]+w.box[3]);if(D){o.select(D.selection),c={time:performance.now(),x:v.clientX,y:v.clientY},v.preventDefault();return}}if(o.select(L?{kind:"item",id:L}:null),!L)return}let H=cn(n.get());H&&(l={mode:k??"move",x0:v.clientX,y0:v.clientY,box0:u?.box??H.box,moved:!1,target:H.t},d.layer.setPointerCapture(v.pointerId),v.preventDefault())}),d.layer.addEventListener("pointermove",v=>{if(!l||!l.moved&&Math.hypot(v.clientX-l.x0,v.clientY-l.y0)<2)return;l.moved=!0;let E=e.getBoundingClientRect(),{W:M,H:k}=$e(n.get());b(l.target,Io(l,(v.clientX-l.x0)/E.width,(v.clientY-l.y0)/E.height,M,k,v.shiftKey))});let y=v=>{if(v.type==="pointercancel"){l=void 0,u=void 0,c=void 0,i.restore(),p();return}let E=l;l=void 0,E&&!E.moved&&(c={time:performance.now(),x:E.x0,y:E.y0}),E?.moved&&u&&(c=void 0,g(E.target,u.box)),p()};return d.layer.addEventListener("pointerup",y),d.layer.addEventListener("pointercancel",y),n.subscribe((v,E)=>{v.state!==E.state&&i.forget(),(v.pinned!==E.pinned||v.state!==E.state)&&(f=!0),!l&&(v.state!==E.state||v.pinned!==E.pinned||v.frame!==E.frame)&&p()}),t.addEventListener("frameapplied",p),new ResizeObserver(p).observe(e),p(),{nudge:(v,E)=>{let M=cn(n.get()),k=u?.box??M?.box;if(!M||!k||l)return!1;let{W:H,H:L}=$e(n.get()),R=[Math.round(k[0]*H+v)/H,Math.round(k[1]*L+E)/L,k[2],k[3]];return b(M.t,R),h&&clearTimeout(h),h=setTimeout(()=>g(M.t,R),400),!0}}};var tt=(e,t,n)=>{let r=[{id:"edit-undo",icon:"undo",title:"undo",run:()=>{n.undo()},enabled:d=>(d.state?.edit?.undo??0)>0},{id:"edit-redo",icon:"redo",title:"redo",run:()=>{n.redo()},enabled:d=>(d.state?.edit?.redo??0)>0},{id:"edit-add-text",icon:"addText",title:"addText",run:()=>{n.addText()},enabled:d=>!!d.state?.resolved},{id:"edit-duplicate",icon:"duplicate",title:"duplicate",run:()=>{n.duplicate()},enabled:()=>n.target()!==void 0},{id:"edit-delete",icon:"remove",title:"remove",run:()=>{n.remove()},enabled:d=>{let i=n.target();return!!(i&&(i.kind!=="segment"||(d.state?.resolved?.segments.length??0)>1))}},{id:"edit-render",icon:"render",title:"renderTool",run:()=>{n.render()},enabled:d=>!!d.state?.resolved&&d.edit.render?.state!=="running"}].map(d=>{let i=m("button",{id:d.id,class:"tbtn",attrs:{type:"button"}},[Y(d.icon)]);return["edit-add-text","edit-duplicate","edit-delete"].includes(d.id)&&i.append(m("span",{class:"tool-label"})),i.addEventListener("click",()=>{d.run(),i.blur()}),{tool:d,el:i}}),s=(d,i)=>m("span",{class:"tool-group"},r.slice(d,i).map(l=>l.el));e.append(m("span",{class:"edit-tools",id:"edit-tools"},[s(0,2),s(2,5),s(5,6)]));let a=d=>{for(let i of r){i.el.title=S(d.lang,i.tool.title);let l=i.el.querySelector(".tool-label");l&&(l.textContent=i.tool.id==="edit-add-text"?d.lang==="zh"?"\\u6587\\u5B57":"Text":i.tool.id==="edit-duplicate"?d.lang==="zh"?"\\u590D\\u5236":"Duplicate":d.lang==="zh"?"\\u5220\\u9664":"Delete"),i.el.setAttribute("aria-label",S(d.lang,i.tool.title)),i.el.disabled=!!d.edit.saving||!i.tool.enabled(d)}};a(t.get()),t.subscribe((d,i)=>{(d.state!==i.state||d.lang!==i.lang||d.pinned!==i.pinned||d.edit.render!==i.edit.render||d.edit.saving!==i.edit.saving)&&a(d)})},Bo={set:"saved",insert:"added",remove:"removed",move:"moved",outside:"outside"},Vo=e=>{let t=e.edit.status,n=e.lang;if(!t)return"";if(t.kind==="note")return S(n,t.key==="phraseSpan"?"phraseSpan":"offlineEdit");if(t.kind==="refused")return S(n,"notSaved")+": "+(t.problem.at.startsWith("(")?"":t.problem.at+": ")+t.problem.message+(t.problem.fix?" "+S(n,"fix")+": "+t.problem.fix:"");let o=t.step==="outside"?S(n,"outside"):t.label;return t.op==="undo"||t.op==="redo"?S(n,t.op==="undo"?"undone":"redone")+": "+o:S(n,Bo[t.op]??"saved")+": "+o},_o=(e,t,n)=>{let o=e.edit.render;if(!o||o.state==="idle")return[];if(o.state==="running")return[m("span",{text:S(n,"rendering")+": "+o.frame+" / "+(o.total||"?")})];if(o.state==="failed")return[m("span",{class:"bad",text:S(n,"renderFailed")+": "+o.message})];let r=m("button",{id:"play-render",class:"link",text:S(n,e.edit.playRender?"showReference":"playRender"),attrs:{type:"button"}});return r.addEventListener("click",()=>t.togglePlayRender()),[m("span",{text:S(n,"rendered")+": "+o.frames+" "+S(n,"framesIn")+" "+o.seconds+" s, ",title:o.file}),m("code",{text:o.file.split(/[\\\\/]/).pop()??o.file,title:o.file})," ",r]},nt=(e,t,n)=>{let o=m("div",{id:"edit-status",class:"status-line",attrs:{role:"status","aria-live":"polite"}}),r=m("div",{id:"render-status",class:"status-line render"});e.prepend(m("div",{class:"edit-status"},[o,r]));let s=a=>{o.textContent=Vo(a),o.classList.toggle("bad",a.edit.status?.kind==="refused"),r.replaceChildren(..._o(a,n,a.lang))};s(t.get()),t.subscribe((a,d)=>{(a.edit!==d.edit||a.lang!==d.lang)&&s(a)})},Ko=e=>e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLInputElement&&!["checkbox","range","button","color"].includes(e.type)||e instanceof HTMLElement&&e.isContentEditable,ot=(e,t,n)=>{document.addEventListener("keydown",o=>{if(document.querySelector('[role="dialog"]'))return;if(Ko(o.target)){if(o.target.id==="stage-text-editor")return;o.key==="Escape"&&o.target.blur();return}let r=o.ctrlKey||o.metaKey,s=o.key.toLowerCase(),a=c=>{o.preventDefault(),o.stopPropagation(),c()};if(r&&s==="z")return a(()=>{o.shiftKey?t.redo():t.undo()});if(r&&s==="y")return a(()=>{t.redo()});if(r&&s==="d")return a(()=>{t.duplicate()});if(r||o.altKey)return;if(s==="s")return a(()=>{t.split()});if(o.key==="Delete"||o.key==="Backspace")return a(()=>{t.remove()});if(o.key==="Escape")return a(()=>t.select(null));let i={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]}[o.key];if(!i||!e.get().pinned)return;let l=o.shiftKey?10:1;n(i[0]*l,i[1]*l)&&a(()=>{})},!0)};var un=(e,t,n)=>e.reduce((o,[r,s])=>Math.max(o,Math.min(1,Math.max(0,(n-(r-t))/t),Math.max(0,(s+t-n)/t))),0),mn=e=>Math.min(1,Math.max(0,e)),Uo=(e,t)=>{if(!e)return 0;let{out:n,in:o}=e;return e.spans.reduce((r,[s,a])=>Math.max(r,Math.min(mn((t-(s-n))/n),mn((a+o-t)/o))),0)},Jo=(e,t)=>{let n=Uo(e,t);return n<=0?0:n>=1?120:Math.min(120,-20*Math.log10(1-n))},pn=(e,t)=>e?e.db*un(e.spans,e.ramp,t)+(e.away?e.away.db*un(e.away.spans,e.away.ramp,t):0)+(e.gaps?Jo(e.gaps,t):0):0;var gn=e=>{let t=[],n,o=()=>{for(let s of t)s.audio.pause(),s.audio.removeAttribute("src"),s.gain.disconnect();t=[]},r=()=>{let s=e.get(),a=s.state?.resolved;if(!a)return;let d=a.audio;(d.length!==t.length||t.some((l,c)=>l.source!==d[c]?.src))&&(o(),n??=new AudioContext,t=d.map(l=>{let c=new Audio;c.crossOrigin="anonymous",c.preload="auto",c.src=Ce(l.src);let u=n.createGain();return n.createMediaElementSource(c).connect(u).connect(n.destination),{audio:c,gain:u,source:l.src}})),s.playing&&n?.state==="suspended"&&n.resume().catch(()=>{});let i=s.frame/a.canvas.fps;t.forEach((l,c)=>{let u=d[c];if(!u)return;l.gain.gain.value=s.muted?0:10**((u.gain-pn(u.duck,s.frame))/20);let h=s.frame>=u.start&&(u.end===void 0||s.frame<u.end),f=Math.max(0,(i-u.start/a.canvas.fps)*(u.speed??1)+(u.from?u.from.frame/u.from.fps:0));l.audio.playbackRate=s.speed*(u.speed??1),h&&!l.audio.seeking&&Math.abs(l.audio.currentTime-f)>.2&&(l.audio.currentTime=f),s.playing&&h&&!s.muted?l.audio.paused&&l.audio.play().catch(()=>{}):l.audio.pause()})};e.subscribe((s,a)=>{(s.state!==a.state||s.frame!==a.frame||s.playing!==a.playing||s.muted!==a.muted||s.speed!==a.speed)&&r()}),window.addEventListener("pagehide",()=>{o(),n?.close()})},fn=new Map,hn=e=>{let t=fn.get(e);if(t)return t;let n=(async()=>{let o=new AudioContext;try{let r=await fetch(Ce(e)),a=(await o.decodeAudioData(await r.arrayBuffer())).getChannelData(0),d=[];for(let i=0;i<500;i++){let l=Math.floor(i*a.length/500),c=Math.floor((i+1)*a.length/500),u=0;for(let h=l;h<c;h+=8)u=Math.max(u,Math.abs(a[h]??0));d.push(u)}return d}finally{await o.close()}})();return fn.set(e,n),n};var En=" \\xB7 ",Ne=e=>({sel:JSON.stringify(e)}),ue=(e,t,n,o={})=>m("div",{class:"lane "+(o.cls??""),id:"lane-"+e,...o.height?{style:"height:"+o.height+"px"}:{}},[m("div",{class:"lane-label",text:t,title:t,...o.labelSel?{data:Ne(o.labelSel)}:{}}),m("div",{class:"lane-track"},n)]),ae=(e,t,n,o,r,s,a)=>Le(m("div",{class:e,text:r,title:s,...a?{data:Ne(a)}:{}}),t,n,o),Wo=(e,t,n)=>ue("ruler",S(n,"ruler"),jt(e,t).map(o=>Q(m("div",{class:"rtick",text:o.label,title:"frame "+o.frame}),o.frame,e)),{cls:"ruler"}),qo=e=>e.segments.map(t=>Q(m("div",{class:"seg-grip",title:t.id+": "+(t.end-t.start)+" frames",data:{border:String(t.index)}}),t.end,e.frames)),bn=(e,t,n,o)=>{let r=e.frames,s=e.segments.flatMap(a=>{let d=a.base.kind==="color"?a.base.color:void 0,i=ae("blk seg",a.start,a.end,r,a.id,a.id+": frames "+a.start+".."+(a.end-1),{kind:"segment",id:a.id});i.textContent="",i.setAttribute("role","button"),i.tabIndex=0,i.setAttribute("aria-label",(t==="zh"?"\\u955C\\u5934 ":"Shot ")+(a.index+1)+" \\xB7 "+((a.end-a.start)/e.canvas.fps).toFixed(2)+"s"),i.dataset.index=String(a.index),i.append(m("img",{attrs:{loading:"lazy",alt:"",src:"/api/thumbnail?frame="+Math.floor((a.start+a.end)/2)+"&g="+o}}),m("span",{class:"segment-name",text:String(a.index+1).padStart(2,"0")+" \\xB7 "+((a.end-a.start)/e.canvas.fps).toFixed(2)+"s"})),d&&i.prepend(m("span",{class:"swatch",style:"background:"+d}));let l=a.transition;if(!l)return a.index===0?[i]:[i,Q(m("div",{class:"tick"}),a.start,r)];let c=Nt(l),u=ae("band",l.a,l.a+l.frames,r,"",c+": mixed frames "+l.a+".."+(l.a+l.frames-1)+", takes over at "+l.boundary,{kind:"segment",id:a.id});return u.append(m("span",{class:"band-label",text:c})),[i,u,Q(m("div",{class:"tick"}),a.start,r)]});return ue("segments",S(t,"segments"),n?[...s,...qo(e)]:s,{cls:"segments"})},yn=(e,t,n)=>{let o={kind:"item",id:e.id},r=[ae("blk item",e.start,e.end,t,"",e.id+" ("+e.type+"): frames "+e.start+".."+(e.end-1),o)];if(e.enter.frames>0&&r.push(ae("shade enter",e.start,e.start+e.enter.frames,t,Te(e.enter),"enter: "+Te(e.enter)+", "+e.enter.ease,o)),e.exit.frames>0&&r.push(ae("shade exit",e.end-e.exit.frames,e.end,t,Te(e.exit),"exit: "+Te(e.exit)+", "+e.exit.ease,o)),n)for(let[s,a]of[["start",e.start],["end",e.end]])r.push(Q(m("div",{class:"grip "+s,data:{grip:s,...Ne(o)}}),a,t));return ue("item-"+e.id,e.id+En+e.type,r,{labelSel:o})},vn=(e,t,n,o=!1)=>{let r={kind:"audio",id:e.id},s=n==="zh"?"\\u97F3\\u9891":"Audio",a=ae("blk audio",e.start,e.end??t,t,s,s,r);a.setAttribute("role","button"),a.tabIndex=0,a.setAttribute("aria-label",s),hn(e.src).then(i=>{let l=document.createElementNS("http://www.w3.org/2000/svg","svg");l.setAttribute("viewBox","0 0 500 28"),l.setAttribute("preserveAspectRatio","none");let c=document.createElementNS(l.namespaceURI,"path");c.setAttribute("d",i.map((u,h)=>"M"+h+" "+(14-Math.max(1,u*13))+"v"+Math.max(2,u*26)).join("")),c.setAttribute("stroke","#69967c"),c.setAttribute("stroke-width","0.8"),l.append(c),a.append(l),a.classList.add("wave-ready")}).catch(()=>{});let d=["start","end"].map(i=>Q(m("div",{class:"grip "+i,data:{grip:i,...Ne(r)}}),i==="start"?e.start:e.end??t,t));return ue("audio-"+e.id,S(n,"audio"),[a,...o?d:[]],{labelSel:r})},Go=(e,t,n)=>ue("words-"+e.track,S(n,"words")+": "+e.track,e.tokens.map(o=>ae("blk audio word"+(o.confidence<.4?" unsure":""),o.start,o.end,t,o.text,o.text+": frames "+o.start+".."+(o.end-1)+En+"confidence "+o.confidence)),{cls:"words-lane"}),Yo=(e,t,n,o,r)=>{let s=e.measure,a=i=>ye(i,s.source.fps,o),d=s.boundaries.flatMap((i,l)=>{let c={kind:"boundary",source:t,index:l},u=It(i),h=u+": frames "+i.start+".."+i.end+" of the measured file, takes over at "+i.frame,f=Q(m("div",{class:"mark",title:h,data:Ne(c)},[m("span",{class:"mark-label",text:u})]),a(i.frame),n);return i.kind==="cut"?[f]:[ae("mband",a(i.start+1),a(i.end),n,"",h,c),f]});return ue(t+"-boundaries",S(r,t==="render"?"renderBoundaries":"referenceBoundaries"),d,{cls:"measure "+t})},Sn=14,Xo=4,Zo=(e,t,n,o,r)=>{let s=e.measure,a=Ft(s).map(c=>({start:ye(c.event.start,s.source.fps,o),end:ye(c.event.end,s.source.fps,o),value:c})),d=mt(a,Xo),i=d.map(c=>{let u=ze(c.value.event),h=ae("ev",c.start,c.end,n,u,u+": frames "+c.value.event.start+".."+(c.value.event.end-1)+" of the measured file",{kind:"event",source:t,shot:c.value.shot,index:c.value.index});return h.style.top=3+c.row*Sn+"px",h}),l=Math.max(1,...d.map(c=>c.row+1));return ue(t+"-events",S(r,t==="render"?"renderEvents":"referenceEvents"),i,{cls:"measure "+t,height:6+l*Sn})},Qo=(e,t,n)=>{let o=W(e),r=se(e),s=e.resolved,a=e.edit!==void 0,d=[Wo(o,r,t)];if(s)if(a){let i=bn(s,t,a,e.generation);i.querySelector(".lane-label").textContent=t==="zh"?"\\u955C\\u5934":"Shots",d.push(i);let l=[{id:"subtitles",label:t==="zh"?"\\u5B57\\u5E55":"Subtitles",items:s.items.filter(c=>c.cue),cls:"caption-lane"},{id:"text",label:t==="zh"?"\\u6587\\u5B57":"Text",items:s.items.filter(c=>!c.cue&&c.type==="text"),cls:"caption-lane"},{id:"media",label:t==="zh"?"\\u7D20\\u6750":"Media",items:s.items.filter(c=>!c.cue&&c.type!=="text"),cls:"media-lane"}];for(let c of n.timeline?.layers===!1?[]:l){let u=mt(c.items.map(f=>({start:f.start,end:f.end,value:f})).sort((f,p)=>f.start-p.start||p.value.z-f.value.z||f.value.id.localeCompare(p.value.id)),Math.max(1,c.items.length)),h=Math.max(0,...u.map(f=>f.row+1));for(let f=0;f<h;f++){let p=u.filter(g=>g.row===f).flatMap(({value:g})=>{let b=Array.from(yn(g,o,a).querySelector(".lane-track").children),y=b[0];if(y){let v=g.text??(t==="zh"?g.type==="video"?"\\u89C6\\u9891":g.type==="image"?"\\u56FE\\u7247":"\\u5F62\\u72B6":g.type);y.textContent=v,y.title=v,y.setAttribute("role","button"),y.setAttribute("tabindex","0"),y.setAttribute("aria-label",v)}return b});d.push(ue(c.id+"-"+f,c.label+(f?" "+(f+1):""),p,{cls:c.cls}))}}if(n.timeline?.layers!==!1)for(let c of n.slots??[]){let u=s.segments.find(g=>g.id===c.segment);if(!u)continue;let h={kind:"slot",id:c.segment,name:c.name},f=c.kind==="image"?t==="zh"?"\\u56FE\\u7247":"Image":c.value,p=ae("blk item scene-field",u.start,u.end,o,f,t==="zh"?"\\u573A\\u666F\\u5185\\u5BB9\\uFF1A\\u65F6\\u95F4\\u7531\\u573A\\u666F\\u63A7\\u5236\\uFF0C\\u70B9\\u9009\\u540E\\u7F16\\u8F91\\u5185\\u5BB9":"Scene content: timing follows scene; select to edit",h);p.setAttribute("role","button"),p.tabIndex=0,p.setAttribute("aria-label",(t==="zh"?"\\u573A\\u666F\\u5185\\u5BB9\\uFF1A":"Scene field: ")+f),d.push(ue("slot-"+c.segment+"-"+c.name,t==="zh"?"\\u573A\\u666F\\u5185\\u5BB9":"Scene content",[p],{cls:"caption-lane"}))}d.push(...s.audio.map(c=>vn(c,o,t,!0)))}else d.push(bn(s,t,a,e.generation),...s.items.map(i=>yn(i,o,a)),...s.audio.map(i=>vn(i,o,t)),...(s.words??[]).map(i=>Go(i,o,t)));for(let[i,l]of[[e.measure,"render"],[e.referenceMeasure,"reference"]])i&&!a&&d.push(Yo(i,l,o,r,t),Zo(i,l,o,r,t));return d},xn=(e,t,n)=>{let o=e.getBoundingClientRect();return Math.floor((t-o.left)/Math.max(1,o.width)*n)},rt=(e,t,n)=>{let o=m("div",{class:"lanes",id:"lanes"}),r=m("div",{class:"playhead",id:"playhead"}),s=m("div",{class:"playhead-layer"},[r]);e.append(o);let a=c=>c.state?W(c.state):0,d=c=>{Le(r,c.frame,c.frame+1,a(c))},i=c=>{o.querySelectorAll("[data-sel]").forEach(u=>{u.setAttribute("aria-pressed",String(c.pinned!==null&&ge(JSON.parse(u.dataset.sel??"null"),c.pinned))),u.classList.toggle("selected",c.pinned!==null&&ge(JSON.parse(u.dataset.sel??"null"),c.pinned))})},l=c=>{o.replaceChildren(...c.state?Qo(c.state,c.lang,c):[],s),d(c),i(c)};o.addEventListener("click",c=>{let u=c.target,h=u.closest("[data-sel]")?.dataset.sel;if(h){let f=JSON.parse(h);n.pause();let p=t.get();p.timeline&&["item","slot","audio"].includes(f.kind)&&!p.timeline.layers&&t.set({timeline:{...p.timeline,layers:!0}}),n.pin(f);let g=u.closest(".lane-track");if(p.state?.edit)n.seek(Ae(t.get().state,f,t.get().frame));else if(g&&c.detail!==0)n.seek(xn(g,c.clientX,a(p)));else{let b=f.kind==="segment"?p.state?.resolved?.segments.find(y=>y.id===f.id):f.kind==="item"?p.state?.resolved?.items.find(y=>y.id===f.id):void 0;b&&(p.frame<b.start||p.frame>=b.end)&&n.seek(b.start)}}else{let f=u.closest(".lane-track");f&&(n.pin(null),c.detail!==0&&n.seek(xn(f,c.clientX,a(t.get()))))}}),o.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let u=c.target.closest("[data-sel]");u&&(c.preventDefault(),u.click())}),e.addEventListener("wheel",c=>{c.shiftKey&&!c.deltaX&&(e.scrollLeft+=c.deltaY,c.preventDefault())},{passive:!1}),l(t.get()),t.subscribe((c,u)=>{if(c.state!==u.state||c.lang!==u.lang||c.timeline?.layers!==u.timeline?.layers||c.slots!==u.slots?l(c):c.frame!==u.frame&&d(c),c.pinned!==u.pinned){i(c);let h=o.querySelector(".blk.selected");if(h){let f=h.getBoundingClientRect(),p=e.getBoundingClientRect(),g=o.querySelector(".lane-label")?.getBoundingClientRect().width??0;(f.left<p.left+g||f.right>p.right)&&(e.scrollLeft+=f.left-p.left-g-20);let b=(o.querySelector(".ruler")?.getBoundingClientRect().height??0)+(h.closest(".segments")?0:o.querySelector(".segments")?.getBoundingClientRect().height??0);(f.top<p.top+b||f.bottom>p.bottom)&&(e.scrollTop+=f.top-p.top-b-6)}}})};var wn=e=>e.reduce((t,n)=>typeof n=="number"?t+"["+n+"]":t?t+"."+n:n,""),$o=(e,t)=>Ut(t)?S(e,t):t,Mt=e=>typeof e=="number"?String(Number(e.toFixed(4))):typeof e=="string"?e:JSON.stringify(e)??"",kt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),er=(e,t)=>{let n=wn(t);return e.filter(o=>o.at===n||o.at.startsWith(n+".")||o.at.startsWith(n+"["))},tr=(e,t)=>{let n=m("input",{attrs:{type:"number",step:String(e.step??(e.range?.integer?1:"any")),...e.range?.min===void 0?{}:{min:String(e.range.min)},...e.range?.max===void 0?{}:{max:String(e.range.max)}}});return n.value=typeof e.value=="number"?Mt(e.value):"",typeof e.resolved=="number"&&e.value===void 0&&(n.placeholder=Mt(e.resolved)),n.addEventListener("change",()=>{let o=n.value.trim(),r=Number(o);if(o!==""&&!Number.isFinite(r))return void n.setAttribute("aria-invalid","true");t(o===""?void 0:r)}),n},kn=(e,t)=>{let n=typeof e.value=="string"?e.value:"";if(e.kind==="textarea"){let r=m("textarea",{attrs:{rows:String(Math.min(6,Math.max(2,n.split(\`
37750
- \`).length)))}});return r.value=n,r.addEventListener("change",()=>t(r.value===""?void 0:r.value)),r.addEventListener("keydown",s=>{s.key==="Enter"&&(s.ctrlKey||s.metaKey)&&r.blur()}),r}let o=m("input",{attrs:{type:"text",autocomplete:"off",spellcheck:"false"}});return o.value=n,typeof e.resolved=="string"&&e.value===void 0&&(o.placeholder=e.resolved),o.addEventListener("change",()=>t(o.value.trim()===""?void 0:o.value.trim())),o},nr=(e,t,n)=>{let o=[...e.empty===null?[]:[m("option",{text:e.empty??S(n,"fDefault"),attrs:{value:""}})],...e.options.map(a=>m("option",{text:e.labels?.[a]??a,attrs:{value:a}}))],r=m("select",{},o),s=e.value===void 0?"":String(e.value);return s!==""&&!e.options.includes(s)&&r.append(m("option",{text:s,attrs:{value:s}})),r.value=s,r.addEventListener("change",()=>t(r.value===""?void 0:r.value)),r},or=(e,t)=>{let n=kn(e,t),o=e.value??e.resolved,r=typeof o=="string"&&/^#[0-9a-f]{6}$/i.test(o)?o:"#000000",s=m("input",{class:"swatch-pick",attrs:{type:"color",tabindex:"-1"}});return s.value=r.toLowerCase(),s.addEventListener("change",()=>t(s.value)),m("span",{class:"colour"},[s,n])},rr=(e,t)=>{let n=e.commit??(l=>{kt(l,e.value)||t.commit(e.path,l)}),o=l=>{kt(l,e.value)||n(l)},r=e.kind==="number"?tr(e,o):e.kind==="select"?nr(e,o,t.lang):e.kind==="color"?or(e,o):kn(e,o),s=r.tagName==="SPAN"?r.querySelector("input[type=text]"):r;s.dataset.path=wn(e.path),e.disabled&&s.setAttribute("disabled","");let a=er(t.problems,e.path);a.length&&s.setAttribute("aria-invalid","true");let d=e.resolved!==void 0&&e.value!==void 0&&!kt(e.value,e.resolved),i=$o(t.lang,e.label);return m("label",{class:"fld"+(e.wide||e.kind==="textarea"?" wide":"")+(e.kind==="textarea"?" area":"")},[m("span",{class:"fl",text:i,title:i}),r,...d?[m("span",{class:"rv",text:"\\u2192 "+Mt(e.resolved),title:S(t.lang,"resolvedTitle")})]:[],...a.map(l=>m("span",{class:"fprob",text:l.message+(l.fix?" "+S(t.lang,"fix")+": "+l.fix:"")}))])},_=(e,t,n,o=[])=>m("fieldset",{class:"fs"},[m("legend",{text:e}),...t.map(r=>m("div",{class:"row"},r.filter(s=>s!==null).map(s=>s instanceof HTMLElement?s:rr(s,n)))),...o]);var Ln=["slide","whip"],Rn=["blur","zoom","shake","flash","whip","glitch","fade","spin"];var Pn=(e,t,n)=>m("div",{class:"hint",text:S(e.lang,"onFrames")+" "+t+".."+(n-1)}),Tt=(e,t,n,o,r=S(e.lang,"fWhen"))=>{let s=T(n)?n:{},a=e.state.resolved?.canvas.fps??30,d=e.state.resolved?.segments.find(h=>h.id===s.segment),i=h=>h==="from"?0:h==="to"&&d?d.end-d.start:void 0,l=(h,f)=>({kind:"number",label:S(e.lang,f)+(e.lang==="zh"?"\\uFF08\\u79D2\\uFF09":" (s)"),path:[...t,h],value:typeof(s[h]??i(h))=="number"?Number(s[h]??i(h))/a:void 0,step:.01,commit:p=>e.commit([...t,h],p===void 0?void 0:Math.round(Number(p)*a))}),c=o?[Pn(e,o.start,o.end)]:[];if(s.phrase!==void 0)return _(r,[[{kind:"text",label:"fPhrase",path:[...t,"phrase"],value:s.phrase,wide:!0}],[l("occurrence","fOccurrence"),l("lead","fLead"),l("hold","fHold")]],e,c);let u={kind:"select",label:"fSegment",path:[...t,"segment"],value:s.segment,options:te(e.state).map(h=>String(h.id)),labels:Object.fromEntries(te(e.state).map((h,f)=>[String(h.id),(e.lang==="zh"?"\\u753B\\u9762 ":"Scene ")+(f+1)])),empty:null};return _(r,[[u,l("from","fFrom"),l("to","fTo")]],e,c)},An=(e,t)=>{let n=Array.isArray(t.track.cues)?t.track.cues:[],o=String(t.track.id),r=n.flatMap((s,a)=>{if(t.kind==="cue"&&t.cue!==a)return[];let d=["tracks",t.index,"cues",a],i=e.state.resolved?.items.find(u=>u.id===o+"#"+a),l={kind:"textarea",label:S(e.lang,"fCue")+" "+a,path:[...d,"text"],value:T(s)?s.text:void 0},c=_("#"+a,[[l]],e,[Tt(e,[...d,"during"],T(s)?s.during:void 0,i,S(e.lang,"fWhen"))]);return c.classList.add("cue"),t.kind==="cue"&&t.cue===a&&c.classList.add("current"),c});return m("div",{class:"cues"},[m("h3",{text:S(e.lang,"fCues")+" ("+n.length+")"}),...r])},ar=(e,t)=>e==="wipe"?X(j(t.schema.transition,"direction")):Ln.includes(e)?X(j(t.schema.motion,"direction")):[],ir=(e,t,n,o)=>{let r=[...t,"in"],s=T(n)?n:void 0,a=String(s?.transition??""),d=e.schema.transition,i=o?.transition,l=(p,g,b,y)=>({kind:b,label:g,path:[...r,p],value:s?.[p],resolved:i?.[p==="transition"?"kind":p],range:xe(j(d,p)),options:y??X(j(d,p)),step:p==="strength"?.1:void 0}),c={kind:"select",label:"fKind",path:[...r,"transition"],value:s?.transition,options:X(j(d,"transition")),empty:S(e.lang,"fHardCut"),commit:p=>p===void 0?e.commit(r,void 0):e.commit([...r,"transition"],p)},u=ar(a,e),h=Rn.includes(a),f=[[c,s&&a!=="cut"?l("frames","fFrames","number"):null],[u.length?l("direction","fDirection","select",u):null,a==="slide"?l("mode","fMode","select"):null,a==="fade"?l("via","fVia","select"):null],[h?l("side","fSide","select"):null,s&&a!=="cut"?l("ease","fEase","select"):null,s&&a!=="cut"?l("strength","fStrength","number"):null]];return _(S(e.lang,"fTransition"),f.filter(p=>p.some(g=>g!==null)),e)},dr=(e,t,n)=>{let o=e.schema.base,r=ve(e.state,["image","video"]),s="material"in n?"material":"color"in n?"color":"scene",a={kind:"select",label:"fBase",path:t,value:s,options:s==="scene"?["scene","color","material"]:["color","material"],labels:{scene:S(e.lang,"fBaseScene"),color:S(e.lang,"fBaseColor"),material:S(e.lang,"fBaseMaterial")},empty:null,commit:l=>e.set(t,l==="scene"?n:l==="color"?{color:"#000000"}:{material:r[0]??""})};if(s==="scene"){let l=T(n.slots)?n.slots:{},c=Object.entries(l).filter(u=>typeof u[1]=="string").map(([u,h])=>[{kind:"textarea",label:u,path:[...t,"slots",u],value:h,wide:!0}]);return _(S(e.lang,"fBaseScene"),[[a],...c],e)}if(s!=="material"){let l=typeof n.color=="string"?{kind:"color",label:"fColour",path:[...t,"color"],value:n.color,empty:null}:m("div",{class:"hint",text:S(e.lang,"fGradient")});return _(S(e.lang,"fBase"),[[a,l]],e)}let d=ve(e.state,["video"]).includes(String(n.material)),i=(l,c,u)=>({kind:"number",label:c,path:[...t,l],value:n[l],range:xe(j(o,l)),...u?{step:u}:{}});return _(S(e.lang,"fBase"),[[a,{kind:"select",label:"fMaterial",path:[...t,"material"],value:n.material,options:r,empty:null,wide:!0}],[{kind:"select",label:"fFit",path:[...t,"fit"],value:n.fit,options:X(j(o,"fit"))},...d?[i("in","fIn"),i("speed","fSpeed",.05),i("audio","fSourceAudio")]:[]]],e,n.camera!==void 0?[m("div",{class:"hint",text:S(e.lang,"fCamera")})]:[])},Cn=(e,t)=>{let n=["segments",t.index],o=e.state.resolved?.segments[t.index],r=e.state.resolved?.canvas.fps??30,s={kind:"number",label:e.lang==="zh"?"\\u65F6\\u957F\\uFF08\\u79D2\\uFF09":"Duration (s)",path:[...n,"frames"],value:Number(oe(e.state.source,[...n,"frames"]))/r,step:.01,range:{min:1/r,integer:!1},commit:i=>e.commit([...n,"frames"],Math.max(1,Math.round(Number(i)*r)))},a=_(e.lang==="zh"?"\\u955C\\u5934\\u65F6\\u957F":"Shot duration",[[s]],e,o?[Pn(e,o.start,o.end)]:[]),d=t.segment;return[a,...t.index>0?[ir(e,n,d.in,o)]:[],...T(d.base)?[dr(e,[...n,"base"],d.base)]:[]]};var On=e=>{if(T(e))return e;if(typeof e!="string"||!St(e))return{};let{font:t,...n}=vt[e];return n},st="custom",Hn=(e,t,n,o)=>{let r=[...t,"style"],s=j(e.schema.text,"style"),a=X(s),d=T(n)?n:void 0,i=e.state.resolved?.canvas.height??1,l={kind:"number",label:e.lang==="zh"?"\\u5B57\\u53F7\\uFF08px\\uFF09":"Font size (px)",path:[...r,"size"],value:Math.round(Number(d?.size??o?.size??.05)*i),step:1,range:{min:1,max:i,integer:!0},commit:p=>c("size")(p===void 0?void 0:Number(p)/i)},c=p=>g=>{let b=Object.fromEntries(Object.entries({...On(n),[p]:g}).filter(([,y])=>y!==void 0));e.set(r,b)},u=(p,g,b={})=>({kind:g,label:"f"+p[0]?.toUpperCase()+p.slice(1),path:[...r,p],value:d?.[p],resolved:o?.[p],commit:c(p),range:xe(j(s,p)),options:X(j(s,p)),...b}),h={kind:"select",label:"fNamed",path:r,value:typeof n=="string"?n:d?st:void 0,options:[...a,st],labels:{[st]:S(e.lang,"fCustom"),...e.lang==="zh"?{headline:"\\u6807\\u9898",subtitle:"\\u526F\\u6807\\u9898",label:"\\u6807\\u7B7E",caption:"\\u5B57\\u5E55"}:{}},commit:p=>e.set(r,p===st?On(n):p)},f=u("font","select",{value:d?.font??o?.font,options:[...new Set([String(d?.font??o?.font??"sans-serif"),...ve(e.state,["font"]),"sans-serif","serif","monospace"])],label:e.lang==="zh"?"\\u5B57\\u4F53":"Font",wide:!0});return _(S(e.lang,"fStyle"),[[f],[h,l],[u("color","color",{label:"fColour"}),u("weight","number",{step:100}),u("align","select",{labels:e.lang==="zh"?{left:"\\u5DE6\\u5BF9\\u9F50",center:"\\u5C45\\u4E2D",right:"\\u53F3\\u5BF9\\u9F50"}:{}})]],e)},lr=new Set(["slide","wipe"]),at=(e,t,n,o,r)=>{let s=[...t,n],a=e.schema.motion,d=T(o)?o:void 0,i=(u,h,f)=>({kind:h,label:f,path:[...s,u],value:d?.[u],resolved:r?.[u],disabled:!d,range:xe(j(a,u)),options:X(j(a,u))}),l={kind:"select",label:"fPreset",path:[...s,"preset"],value:d?.preset,options:X(j(a,"preset")),empty:S(e.lang,"fNone"),commit:u=>u===void 0?e.commit(s,void 0):e.commit([...s,"preset"],u)},c=lr.has(String(d?.preset??""));return _(S(e.lang,n==="enter"?"fEnter":"fExit"),[[l,i("frames","number","fFrames")],[c?i("direction","select","fDirection"):null,i("ease","select","fEase")]],e)},ie=(e,t,n,o,r={})=>({kind:"number",label:n,path:t,value:oe(e.state.source,t),range:xe(o),...r}),Ie=(e,t,n,o,r={})=>({kind:"select",label:n,path:t,value:oe(e.state.source,t),options:o,...r}),Nn=(e,t,n)=>{let o=e.state.resolved?.canvas,r=n&&o?[n.box[0]*o.width,n.box[1]*o.height,n.box[2]*o.width,n.box[3]*o.height].map(a=>Math.round(a)).join(", ")+" px":"",s=["fX","fY","fW","fH"].map((a,d)=>{let i=[...t,"box",d],l=d%2===0?o?.width??1:o?.height??1;return ie(e,i,a,void 0,{step:1,value:Math.round(Number(oe(e.state.source,i)??0)*l),commit:c=>e.commit(i,Number(c)/l)})});return _(e.lang==="zh"?"\\u4F4D\\u7F6E\\u4E0E\\u5C3A\\u5BF8\\uFF08px\\uFF09":"Position and size (px)",[s],e,r?[m("div",{class:"hint",text:r})]:[])},cr=(e,t,n)=>_(S(e.lang,"fLook"),[[ie(e,[...t,"rotate"],"fRotate",j(n,"rotate")),ie(e,[...t,"opacity"],"fOpacity",j(n,"opacity"),{step:.05}),ie(e,[...t,"z"],"fZ",j(n,"z"))]],e),ur=(e,t,n,o)=>{let r=String(n.type),s=e.schema[r==="image"?"image":r==="video"?"video":"shape"],a=ie(e,[...t,"radius"],"fRadius",j(s,"radius"),{step:.01});if(r==="shape"){let u=typeof n.color=="string"?{kind:"color",label:"fColour",path:[...t,"color"],value:n.color,resolved:o?.color}:m("div",{class:"hint",text:S(e.lang,"fGradient")});return _(S(e.lang,"fShape"),[[Ie(e,[...t,"shape"],"fShape",X(j(s,"shape")),{empty:null}),u,a]],e)}if(r!=="image"&&r!=="video")return null;let d=Ie(e,[...t,"material"],"fMaterial",ve(e.state,[r]),{empty:null,wide:!0}),i=Ie(e,[...t,"fit"],"fFit",X(j(s,"fit")),{resolved:o?.fit}),l=Ie(e,[...t,"mask"],"fMask",X(j(s,"mask")),{empty:S(e.lang,"fNone")}),c=r==="video"?[ie(e,[...t,"in"],"fIn",j(s,"in")),ie(e,[...t,"speed"],"fSpeed",j(s,"speed"),{step:.05}),ie(e,[...t,"audio"],"fSourceAudio",j(s,"audio"))]:[];return _(S(e.lang,r==="video"?"fFootage":"fPicture"),[[d,i],[a,l,...c]],e)},mr=(e,t)=>{let n=_(S(e.lang,"fText"),[[{kind:"textarea",label:e.lang==="zh"?"\\u5185\\u5BB9":"Content",path:[...t,"text"],value:oe(e.state.source,[...t,"text"])}]],e);return n.querySelector("legend")?.remove(),n},pr=(e,t,n)=>{let o=T(n.during)?n.during:void 0,r={kind:"select",label:"fStart",path:[...t,"during","segment"],value:o?.segment,options:te(e.state).map(s=>String(s.id)),empty:S(e.lang,"fWhole"),commit:s=>s===void 0?e.commit([...t,"during"],void 0):e.set([...t,"during"],{...o??{},segment:s})};return _(S(e.lang,"fAudio"),[[Ie(e,[...t,"material"],"fMaterial",ve(e.state,["audio","voice","speech"]),{empty:null,wide:!0}),ie(e,[...t,"gain"],"fGain",j(e.schema.audio,"gain"))],[r,ie(e,[...t,"during","from"],"fFrom",void 0,{disabled:!o})]],e)},In=(e,t)=>e.resolved?.items.find(n=>n.id===t),fr=(e,t)=>{let n=["tracks",t.index],o=t.track,r=String(o.type);if(r==="audio")return[pr(e,n,o)];let s=String(o.id);if(r==="caption"){let i=In(e.state,s+"#"+(t.kind==="cue"?t.cue:0));return[An(e,t),Hn(e,n,o.style,i?.style),Nn(e,n,i),at(e,n,"enter",o.enter,i?.enter),at(e,n,"exit",o.exit,i?.exit)]}let a=In(e.state,s),d=e.schema[r==="text"?"text":r==="image"?"image":r==="video"?"video":"shape"];return[...r==="text"?[mr(e,n)]:[],...r==="text"?[Hn(e,n,o.style,a?.style)]:[ur(e,n,o,a)].filter(i=>i!==null),Tt(e,[...n,"during"],o.during,a),Nn(e,n,a),at(e,n,"enter",o.enter,a?.enter),at(e,n,"exit",o.exit,a?.exit),cr(e,n,d)]},Fn=(e,t)=>{let n=t.kind==="segment"?S(e.lang,"fSegment")+" "+String(t.segment.id):String(t.track.type)+" "+String(t.track.id)+(t.kind==="cue"?" #"+t.cue:""),o=t.kind==="segment"?Cn(e,t):fr(e,t),r=t.kind==="segment"?e.lang==="zh"?"\\u753B\\u9762 "+(t.index+1):"Scene "+(t.index+1):t.kind==="cue"?e.lang==="zh"?"\\u5B57\\u5E55 "+(t.cue+1):"Subtitle "+(t.cue+1):e.lang==="zh"?{text:"\\u6587\\u5B57",image:"\\u56FE\\u7247",video:"\\u89C6\\u9891",audio:"\\u97F3\\u9891",shape:"\\u5F62\\u72B6"}[String(t.track.type)]??"\\u5143\\u7D20":String(t.track.type),s=t.kind==="cue"?2:t.kind==="segment"?1:t.track.type==="text"?2:1;return m("div",{class:"form",id:"edit-form"},[m("div",{class:"sel-title",text:r,title:n}),...o.slice(0,s),...o.length>s?[m("details",{},[m("summary",{text:e.lang==="zh"?"\\u4F4D\\u7F6E\\u3001\\u65F6\\u95F4\\u4E0E\\u52A8\\u6548":"Position, timing and motion"}),...o.slice(s)])]:[]])};var Fe=(e,t=[])=>m("h2",{},[m("span",{text:e}),...t]),Dn=e=>m("pre",{class:"json",text:JSON.stringify(e,null,2)??"undefined"}),gr=(e,t,n)=>{if(e.pinned){let a=Bt(t,e.pinned);return[m("div",{class:"sel-title",text:Vt(e.pinned)}),a===void 0?m("p",{class:"muted",text:S(e.lang,"nothing")}):Dn(a)]}let o=t.resolved?Z(t.resolved,e.frame):void 0,s=(t.resolved?fe(t.resolved,e.frame):[]).map(a=>m("button",{class:"chip",text:a.id,attrs:{type:"button"},on:{click:()=>n.pin({kind:"item",id:a.id})}}));return[...o?[m("div",{class:"sel-title",text:"segment "+o.id}),Dn(o)]:[m("p",{class:"muted",text:S(e.lang,"nothing")})],m("div",{class:"chips"},[m("span",{class:"muted",text:S(e.lang,"onScreen")+": "}),...s.length?s:[S(e.lang,"none")]])]},hr=(e,t,n,o)=>{let r=e.edit.schema;if(!t.edit)return;if(!r)return[m("p",{class:"muted",text:e.lang==="zh"?"\\u6B63\\u5728\\u8F7D\\u5165\\u7F16\\u8F91\\u5DE5\\u5177\\u2026":"Loading editing tools\\u2026"})];if(e.pinned?.kind==="slot")return[dn(o,n)];let s=q(t,e.pinned);if(s){let a={lang:e.lang,problems:e.edit.problems,state:t,schema:r,commit:(d,i)=>{let l=Wt(t.source,d,i);l&&n.send(l)},set:(d,i)=>{n.send({op:"set",path:d,value:i})}};return[Fn(a,s)]}if(!e.pinned)return[]},br=(e,t)=>m("li",{class:"problem "+e.level},[m("div",{},[m("b",{class:e.level,text:S(t,e.level)})," ",m("code",{text:e.at})]),m("div",{text:e.message}),...e.allowed?.length?[m("div",{class:"muted",text:S(t,"allowed")+": "+e.allowed.join(", ")})]:[],...e.fix?[m("div",{text:S(t,"fix")+": "+e.fix})]:[]]),yr=e=>Object.entries(e).map(([t,n])=>t+"="+(typeof n=="number"?Number(n.toFixed(3)):n)).join(", "),vr=(e,t)=>{let n=(r,s="")=>m("tr",{class:s},r.map(a=>m("td",{},[a]))),o=Object.entries(e.dimensions).map(([r,s])=>{let a=yr(s.detail);return n([Jt(t,r),s.n?s.score.toFixed(2):"-",String(s.n),m("span",{class:"detail",text:a,title:a})],s.n?"":"muted")});return m("table",{class:"score"},[m("thead",{},[m("tr",{},[S(t,"dimension"),S(t,"value"),S(t,"compared"),S(t,"detail")].map(r=>m("th",{text:r})))]),m("tbody",{},[...o,n([S(t,"composite"),e.composite.toFixed(2),"",""],"total")])])},Sr=(e,t)=>[m("div",{class:"kv"},[m("span",{class:"muted",text:S(t,"renderMeasure")+": "}),m("code",{text:e.measure?.file??S(t,"none"),title:e.measure?.file??""})]),m("div",{class:"kv"},[m("span",{class:"muted",text:S(t,"referenceMeasure")+": "}),m("code",{text:e.referenceMeasure?.file??S(t,"none"),title:e.referenceMeasure?.file??""})]),...e.messages.map(n=>m("p",{class:"message",text:n}))],it=(e,t,n,o)=>{let r=m("section",{id:"selection"}),s=m("section",{id:"problems"}),a=m("section",{id:"score"}),d=m("section",{id:"measures"}),i=m("section",{id:"notes"});e.append(r,s,a,d,i);let l="",c="",u=f=>{let p=f.state,g=p?.resolved&&!f.pinned?[Z(p.resolved,f.frame)?.id,fe(p.resolved,f.frame).map(H=>H.id)]:null,b=p?.edit?[f.edit.problems,f.edit.schema!==null]:null,y=JSON.stringify([f.lang,p?.generation,f.pinned,g,b]);if(y===l)return;let v=JSON.stringify(f.pinned)!==c;c=JSON.stringify(f.pinned),l=y;let E=r.contains(document.activeElement)?document.activeElement.dataset.path:void 0,M=f.pinned?[m("button",{class:"link",text:S(f.lang,"follow"),attrs:{type:"button"},on:{click:()=>n.pin(null)}})]:[],k=p?(o&&hr(f,p,o,t))??gr(f,p,n):[];r.replaceChildren(Fe(S(f.lang,"selection"),[m("span",{class:"muted",text:" ("+S(f.lang,f.pinned?"pinned":"underPlayhead")+")"}),...M]),...k),E&&r.querySelector('[data-path="'+CSS.escape(E)+'"]')?.focus(),v&&r.querySelector(".cue.current")?.scrollIntoView({block:"nearest"})},h=f=>{let p=f.state;if(!p)return;let g=f.lang;s.replaceChildren(Fe(S(g,"problems")+" ("+p.problems.length+")"),p.problems.length?m("ul",{},p.problems.map(b=>br(b,g))):m("p",{class:"muted",text:S(g,"noProblems")})),a.replaceChildren(Fe(S(g,"score")),p.score?vr(p.score,g):m("p",{class:"muted",text:S(g,"noScore")})),d.replaceChildren(Fe(S(g,"measurements")),...Sr(p,g)),i.hidden=!p.notes,i.replaceChildren(Fe(S(g,"notes")+" ("+(p.notes?.length??0)+")"),m("ul",{},(p.notes??[]).map(b=>m("li",{class:"note-item"},[m("code",{text:b.at})," ",m("b",{text:b.kind}),m("div",{text:b.message})]))))};h(t.get()),u(t.get()),t.subscribe((f,p)=>{(f.state!==p.state||f.lang!==p.lang)&&h(f),(f.state!==p.state||f.lang!==p.lang||f.pinned!==p.pinned||f.frame!==p.frame||f.edit.problems!==p.edit.problems||f.edit.schema!==p.edit.schema)&&u(f)})};var Lt=(e,t,n,o)=>{let r=Math.max(0,t.frames-1),s=o-e.start;return s<=0?Math.min(e.in,r):Math.min(r,e.in+Math.round(s*t.fps*e.speed/n))};var jn=(e,t)=>{let n=[],o=(d,i)=>{let l=e.querySelector(d+" > img");l&&n.push({img:l,play:i,active:!1})};t.segments.forEach(d=>{d.base.kind==="video"&&o('[data-segment="'+CSS.escape(d.id)+'"]',d.base.play)}),t.items.forEach(d=>{d.play&&o('[data-item="'+CSS.escape(d.id)+'"]',d.play)});let r=(d,i)=>{if(d.video)return;let l=t.footage?.[d.play.material],c=d.img.parentElement;if(!l||!c)return;let u=e.createElement("video");u.muted=!0,u.playsInline=!0,u.preload="auto",u.hidden=!0,u.style.display="none",u.dataset.previewVideo=d.play.material;let h=Lt(d.play,l,t.canvas.fps,Math.max(i,d.play.start))/l.fps;d.time=h,u.addEventListener("loadedmetadata",()=>{u.paused&&u.isConnected&&(u.currentTime=d.time??h)},{once:!0}),u.src=l.src.startsWith("project/")?"/"+l.src:"/project/"+l.src.split("/").map(encodeURIComponent).join("/");let f=()=>{!d.active||!u.isConnected||c.style.display==="none"||(u.style.cssText=d.img.style.cssText+";position:absolute;inset:0;pointer-events:none;",u.hidden=!1,u.style.visibility="",d.img.style.visibility="hidden")};u.addEventListener("loadeddata",f),u.addEventListener("seeked",()=>{if(!d.playing&&d.active&&d.time!==void 0&&Math.abs(u.currentTime-d.time)>.5/l.fps){u.currentTime=d.time;return}f()}),c.append(u),d.video=u},s=d=>{d.video?.pause(),d.video?.removeAttribute("src"),d.video?.load(),d.video?.remove(),d.video=void 0,d.active=!1,d.img.style.visibility=""};return{sync:(d,i,l)=>{let c=n.filter(u=>u.play.start>d).sort((u,h)=>u.play.start-h.play.start).slice(0,2);for(let u of n)c.includes(u)||u.img.parentElement?.style.display!=="none"?r(u,d):u.video&&s(u);for(let u of n){let h=t.footage?.[u.play.material],f=u.img.parentElement;if(!((i||h?.dir===void 0)&&!!h&&!!f&&f.style.display!=="none")){u.video?.pause(),u.video&&(u.video.hidden=!0,u.video.style.display="none"),u.img.style.visibility="",u.active=!1;continue}if(!h||!f)continue;let g=u.video;g.hidden=!1,g.style.cssText=u.img.style.cssText+";position:absolute;inset:0;pointer-events:none;",u.img.style.visibility=g.readyState>=2?"hidden":"",g.style.visibility=g.readyState>=2?"":"hidden";let b=Lt(u.play,h,t.canvas.fps,d)/h.fps;u.time=b,u.playing=i;let y=l*u.play.speed;g.playbackRate=Math.max(.0625,Math.min(16,y));let v=i&&u.active?.25:.5/h.fps;!g.seeking&&Math.abs(g.currentTime-b)>v&&(g.currentTime=b),d<u.play.start||b>=(h.frames-1)/h.fps||!i?g.pause():g.paused&&g.play().catch(()=>{}),u.active=!0}},needsPictures:()=>n.some(d=>!!(d.video?.error&&t.footage?.[d.play.material]?.dir&&d.img.parentElement?.style.display!=="none")),dispose:()=>{n.forEach(s)}}};var zn=(e,t)=>{let n=m("div",{class:"caption"}),o=m("div",{class:"note"}),r=m("div",{class:"overlay"}),s=m("div",{class:"frame-box"},[t,r]);return{root:m("div",{class:"viewer",id:e},[n,s,o]),caption:n,note:o,box:s,overlay:r}},Bn=(e,t,n,o)=>Math.max(.01,Math.min(n/e,o/t)),Rt=(e,t)=>{let n=e.reference.root.isConnected,o=getComputedStyle(e.root),r=e.root.classList.contains("comparing"),s=(e.root.clientWidth-parseFloat(o.paddingLeft)-parseFloat(o.paddingRight)-(n?parseFloat(o.gap)||16:0))/(n?2:1)-(r?18:0),a=e.root.clientHeight-parseFloat(o.paddingTop)-parseFloat(o.paddingBottom)-e.render.caption.offsetHeight-e.render.note.offsetHeight-(r?32:8),d=t.state?.resolved?.canvas;if(e.render.box.classList.toggle("problems",!d),d){let h=Bn(d.width,d.height,s,a);e.render.box.style.cssText="width:"+d.width*h+"px;height:"+d.height*h+"px;",e.scaler.style.cssText="width:"+d.width+"px;height:"+d.height+"px;transform:scale("+h+");"}else e.render.box.style.cssText="width:"+Math.max(0,s)+"px;height:"+Math.max(0,a)+"px;",e.scaler.style.cssText="width:100%;height:100%;";if(!n)return;let i=t.state?.referenceMeasure?.measure.source,l=e.video.videoWidth||i?.width||d?.width||16,c=e.video.videoHeight||i?.height||d?.height||9,u=Bn(l,c,s,a);e.reference.box.style.cssText="width:"+l*u+"px;height:"+c*u+"px;"},Vn=(e,t,n,o)=>{if(t)for(let r of Dt(t,n,o))e.append(le(m("div",{class:"ebox"},[m("span",{text:ze(r)})]),r.box))},xr=(e,t,n)=>{let o=t.state;if(e.render.overlay.replaceChildren(),e.reference.overlay.replaceChildren(),!o?.resolved)return;let r=se(o);if(t.overlays.safe)for(let s of[e.render.overlay,e.reference.overlay])s.append(le(m("div",{class:"safe"}),zt(o.resolved.canvas)));if(t.overlays.boxes)for(let s of fe(o.resolved,t.frame))e.render.overlay.append(le(m("div",{class:"ibox",title:s.id,on:{click:()=>n.pin({kind:"item",id:s.id})}},[m("span",{text:s.id})]),s.box));t.overlays.events&&(Vn(e.render.overlay,o.measure?.measure,t.frame,r),Vn(e.reference.overlay,o.referenceMeasure?.measure,t.frame,r))},Er=(e,t)=>{let n=t.state?.resolved?.canvas,o=!!(t.state&&!t.state.resolved);e.render.caption.textContent=S(t.lang,t.state?.edit?"currentVideo":"render")+(n?" "+n.width+"x"+n.height+", "+n.fps+" fps":""),e.render.note.textContent=o?S(t.lang,"errorsOnStage"):t.pageError?S(t.lang,"imageFailed")+": "+t.pageError:"",e.render.note.classList.toggle("error",o||!!t.pageError);let r=t.edit.playRender&&t.edit.render?.state==="done"?t.edit.render:void 0;e.reference.caption.textContent=r?S(t.lang,"renderFile")+" "+(r.file.split(/[\\\\/]/).pop()??""):S(t.lang,"reference")+(t.state?.reference?" "+t.state.reference.name:""),e.reference.note.textContent=S(t.lang,"seekNote")},_n=(e,t,n,o)=>{if(!t.state||!e.getAttribute("src"))return;let r=(t.frame+.25)/se(t.state);if(!t.playing){e.paused||e.pause(),(o||n.playing||Math.abs(e.currentTime-r)>.001)&&(e.currentTime=r);return}e.playbackRate=t.speed,o||!n.playing||n.speed!==t.speed?(e.currentTime=r,e.play().catch(()=>{})):!e.seeking&&Math.abs(e.currentTime-r)>.2&&(e.currentTime=r)},wr=(e,t)=>{let n,o=-1,r=0,s=0,a,d,i=()=>{let c=n;if(!c)return;let u=t.get(),h=u.frame,f=++s;(c.preparePreview?.(h)??Promise.resolve()).then(async()=>{f===s&&(u.playing&&c.previewFrame&&a&&!a.needsPictures()?c.previewFrame(h):c.applyFrame(h),a?.sync(h,u.playing,u.speed),await c.settle())}).then(()=>null,g=>g instanceof Error?g.message:String(g)).then(g=>{if(f!==s)return;g!==null&&g!==t.get().pageError&&t.set({pageError:g}),document.body.dataset.applied=String(h),e.dispatchEvent(new Event("frameapplied"));let b=t.get().state?.resolved,y=b?Z(b,h)?.id:void 0;g===null&&y!==d&&(d=y,document.dispatchEvent(new Event("studio:scene-ready")))})};return e.addEventListener("load",()=>{let c=++r,u=e.contentWindow?.__popostVideo;if(n=void 0,d=void 0,!u){document.body.dataset.ready="error";return}(u.preparePreview?.(t.get().frame)??u.prepare()).then(()=>null,f=>f instanceof Error?f.message:String(f)).then(f=>{if(c!==r)return;n=u;let p=t.get().state?.resolved;p&&e.contentDocument&&(a=jn(e.contentDocument,p)),f!==t.get().pageError&&t.set({pageError:f}),i(),document.body.dataset.ready="1",document.dispatchEvent(new Event("studio:page-ready"))})}),{load:c=>{o=c,s++,a?.dispose(),a=void 0,n=void 0,document.body.dataset.ready="",e.src="/page?g="+c},apply:i,loaded:()=>o}},kr=e=>{let t=e.edit.render;return e.edit.playRender&&t?.state==="done"?t.url:e.compare!==!1&&e.state?.reference?e.state.reference.url??"/reference":""},dt=(e,t,n)=>{let o=m("iframe",{id:"page",attrs:{title:"page",tabindex:"-1"}}),r=m("div",{class:"scaler"},[o]),s=m("video",{id:"reference-video",attrs:{preload:"auto",playsinline:"",tabindex:"-1"}});s.muted=!0;let a={root:e,render:zn("render-view",r),reference:zn("reference-view",s),iframe:o,scaler:r,video:s};e.append(a.render.root);let d=wr(o,t);new ResizeObserver(()=>Rt(a,t.get())).observe(e),s.addEventListener("loadedmetadata",()=>{Rt(a,t.get()),_n(s,t.get(),t.get(),!0)});let i="";return t.subscribe((l,c)=>{let u=kr(l);if(u!==i){i=u,u&&!a.reference.root.isConnected&&e.append(a.reference.root),u||a.reference.root.remove(),u?s.src=u:s.removeAttribute("src");let h=!!(u&&!l.edit.playRender);e.classList.toggle("comparing",h),a.reference.root.style.order=h?"-1":""}l.state&&l.state.generation!==d.loaded()&&d.load(l.state.generation),(l.frame!==c.frame||l.playing!==c.playing||l.speed!==c.speed)&&d.apply(),(l.frame!==c.frame||l.overlays!==c.overlays||l.state!==c.state)&&xr(a,l,n),(l.frame!==c.frame||l.playing!==c.playing||l.speed!==c.speed)&&_n(s,l,c,!1),(l.compare!==c.compare||l.lang!==c.lang||l.state!==c.state||l.pageError!==c.pageError||l.edit!==c.edit)&&(Er(a,l),Rt(a,l))}),{frameBox:a.render.box,iframe:o}};var Ee=(e,t,n,o,r)=>{let s=m("button",{id:t,class:"tbtn",attrs:{type:"button"}},[o]);return s.addEventListener("click",()=>{r(),s.blur()}),e.buttons.push({el:s,title:n}),s},Mr=e=>{let t=m("input",{id:"jump",attrs:{type:"text",inputmode:"numeric",autocomplete:"off"}});return t.addEventListener("keydown",n=>{if(n.key!=="Enter")return;let o=Number(t.value.trim()),r=t.value.trim()!==""&&Number.isInteger(o);t.setAttribute("aria-invalid",String(!r)),r&&(e.pause(),e.seek(o),t.value="",t.blur())}),t},Tr=e=>{let t=m("select",{id:"speed"},_t.map(n=>m("option",{text:n+"x",attrs:{value:String(n)}})));return t.value="1",t.addEventListener("change",()=>{e.setSpeed(Number(t.value)),t.blur()}),t},Lr=(e,t)=>{let n=[],o=d=>()=>{t.pause(),d()},r=m("span",{class:"icon"},[Y("play")]),s=m("input",{id:"slider",attrs:{type:"range",min:"0",max:"0",step:"1",value:"0","aria-label":"frame"}});s.addEventListener("input",()=>t.seek(Number(s.value)));let a={buttons:n,playIcon:r,slider:s,play:Ee({buttons:n},"play","play",r,()=>t.togglePlay()),frameLabel:m("span",{class:"muted"}),frameNo:m("span",{id:"frame-no",class:"num"}),frameOf:m("span",{class:"num muted"}),time:m("span",{id:"time",class:"num muted"}),speedLabel:m("label",{class:"muted",attrs:{for:"speed"}}),speed:Tr(t),jump:Mr(t)};return e.append(Ee(a,"first","first",Y("first"),o(()=>t.seek(0))),Ee(a,"back10","back10","\\u221210",o(()=>t.step(-10))),Ee(a,"back1","back1","\\u22121",o(()=>t.step(-1))),a.play,Ee(a,"fwd1","fwd1","+1",o(()=>t.step(1))),Ee(a,"fwd10","fwd10","+10",o(()=>t.step(10))),Ee(a,"last","last",Y("last"),o(()=>t.seek(Number.MAX_SAFE_INTEGER))),m("div",{class:"slider-wrap"},[s]),m("span",{class:"readout"},[m("span",{},[a.frameLabel,a.frameNo,a.frameOf]),a.time]),m("span",{class:"speed"},[a.speedLabel,a.speed]),a.jump),a},Kn=(e,t,n)=>{let o=t.state?W(t.state):0,r=t.state?se(t.state):30;e.slider.max=String(Math.max(0,o-1)),e.slider.value=String(t.frame),e.frameNo.textContent=String(t.frame),e.frameOf.textContent=" / "+Math.max(0,o-1),e.time.textContent=pt(t.frame,r)+" / "+pt(o,r),!(n&&t.playing===n.playing&&t.lang===n.lang)&&(e.playIcon.replaceChildren(Y(t.playing?"pause":"play")),e.buttons.forEach(s=>{s.el.title=S(t.lang,s.el===e.play?t.playing?"pause":"play":s.title)}),e.frameLabel.textContent=S(t.lang,"frame")+" ",e.speedLabel.textContent=S(t.lang,"speed")+" ",e.jump.placeholder=S(t.lang,"jump"),e.jump.title=S(t.lang,"jumpHint"))},Rr=(e,t)=>{let n=e.target;if(e.defaultPrevented||n?.tagName==="SELECT"||n?.tagName==="TEXTAREA"||n instanceof HTMLInputElement&&(n.type==="text"||n.type==="number")||e.altKey||e.ctrlKey||e.metaKey)return;let r={" ":()=>t.togglePlay(),ArrowLeft:()=>{t.pause(),t.step(e.shiftKey?-10:-1)},ArrowRight:()=>{t.pause(),t.step(e.shiftKey?10:1)},Home:()=>{t.pause(),t.seek(0)},End:()=>{t.pause(),t.seek(Number.MAX_SAFE_INTEGER)}}[e.key];r&&(e.preventDefault(),r())},lt=(e,t,n)=>{let o=Lr(e,n);Kn(o,t.get(),void 0),t.subscribe((r,s)=>{(r.frame!==s.frame||r.state!==s.state||r.playing!==s.playing||r.lang!==s.lang)&&Kn(o,r,s)}),document.addEventListener("keydown",r=>Rr(r,n))};var Pt=e=>{let t=e.store.get(),n=t.state?.resolved,o=t.pinned,r=o?.kind==="item"?n?.items.find(s=>s.id===o.id):void 0;return n?n.segments.find(s=>(o?.kind==="segment"||o?.kind==="slot")&&s.id===o.id)??(r?Z(n,r.start):void 0)??Z(n,t.frame):void 0},Jn=(e,t)=>{let n=e.store.get().state?.resolved?.segments.find(o=>o.id===t);n&&(e.actions.pause(),e.actions.seek(Math.min(n.end-1,n.start+Math.floor((n.end-n.start)*.3))),e.edit.select({kind:"segment",id:t}))},At=e=>{let{store:t,edit:n}=e,o=t.get().state,r=o?.resolved,s=m("div",{class:"studio-shot-list"});if(r)for(let d of r.segments){let i=d.base,l=i.kind==="scene"?x(t,"scene"):i.kind==="video"?x(t,"video"):i.kind==="image"?x(t,"image"):x(t,"color"),c=C("",()=>Jn(e,d.id),"studio-shot "+(ge(t.get().pinned,{kind:"segment",id:d.id})?"selected":""));c.append(sn(d.start+Math.floor((d.end-d.start)/2),o?.generation??0),m("span",{class:"studio-shot-copy"},[m("strong",{text:String(d.index+1).padStart(2,"0")+" "+d.id}),m("small",{text:l+" \\xB7 "+((d.end-d.start)/r.canvas.fps).toFixed(2)+"s"})])),c.dataset.selection=JSON.stringify({kind:"segment",id:d.id}),c.draggable=!!o?.edit,c.addEventListener("dragstart",u=>u.dataTransfer?.setData("application/x-popost-segment",String(d.index))),c.addEventListener("dragover",u=>u.preventDefault()),c.addEventListener("drop",u=>{u.preventDefault();let h=Number(u.dataTransfer?.getData("application/x-popost-segment"));Number.isInteger(h)&&h!==d.index&&n.send({op:"move",path:["segments",h],to:d.index})}),s.append(c)}let a=Oe("",x(t,"search"));return a.placeholder=x(t,"search"),a.addEventListener("input",()=>s.querySelectorAll(".studio-shot").forEach(d=>{d.hidden=!d.textContent?.toLowerCase().includes(a.value.toLowerCase())})),m("div",{class:"studio-side-body"},[U(x(t,"shots"),String(r?.segments.length??0)),a,s,A(x(t,"keepRhythm"))])},Un=async(e,t,n)=>{let{store:o,edit:r}=e,s=o.get().state,a=Pt(e);if(!s||!a)return;let d=t.kind,i=String(t.id);if(!n&&["image","video"].includes(String(d))){await r.send({op:"set",path:["segments",a.index,"base"],value:{material:i,fit:"cover"}});return}let l=$(G(s.source).tracks),c=["audio","voice","speech"].includes(String(d))?"audio":d;if(!["image","video","audio"].includes(String(c)))return;let u={id:"overlay-"+Date.now(),type:c,material:i,...c==="audio"?{gain:0}:{box:[.1,.1,.8,.6],fit:"contain"},during:{segment:a.id,from:0,to:a.end-a.start}};await r.send({op:"insert",path:["tracks",l.length],value:u},{kind:c==="audio"?"audio":"item",id:u.id})},Wn=e=>{let{store:t}=e,n=m("div",{class:"studio-resource-tabs"}),o=m("div"),r=()=>{n.replaceChildren(...["shots","files"].map(s=>C(x(t,s==="shots"?"shots":"sourceFile"),()=>{e.mediaView=s,r()},(e.mediaView??"shots")===s?"selected":""))),o.replaceChildren(n,(e.mediaView??"shots")==="shots"?At(e):Pr(e))};return r(),o},Pr=e=>{let{store:t}=e,n=t.get().state,o=m("input",{attrs:{type:"file",accept:"image/png,image/jpeg,image/webp,video/mp4,video/webm,video/quicktime,audio/*",hidden:""}});o.addEventListener("change",()=>{let s=o.files?.[0];if(!s)return;if(s.size>12*1024*1024){ce(t,x(t,"importHint"));return}let a=new FileReader;a.onload=()=>{ke(t,"/api/studio/import",{name:s.name,data:String(a.result).split(",")[1]})},a.readAsDataURL(s)});let r=m("div",{class:"studio-media-list"});for(let s of $(G(n?.source).materials)){let a=String(s.note??s.file??s.id),d=Ce(String(s.file??"")),i=s.kind==="image"?m("img",{attrs:{src:d,alt:a,loading:"lazy"}}):s.kind==="video"?m("video",{attrs:{src:d,controls:"",preload:"metadata"}}):m("audio",{attrs:{src:d,controls:"",preload:"none"}}),l=m("div",{class:"studio-actions"},[C(x(t,"addOverlay"),()=>{Un(e,s,!0)})]);["image","video"].includes(String(s.kind))&&l.prepend(C(x(t,"applyShot"),()=>{Un(e,s,!1)})),r.append(m("article",{class:"studio-media-card"},[i,m("strong",{text:a,title:a}),A(String(s.kind)),l]))}return r.children.length||r.append(A(x(t,"noMedia"))),m("div",{class:"studio-side-body"},[U(x(t,"media")),C(x(t,"upload"),()=>o.click(),"primary"),o,A(x(t,"importHint")),A(x(t,"chooseMaterial")),r])},qn=e=>{let{store:t,edit:n}=e,o=t.get().state,r=m("div",{class:"studio-script-list"}),s=[];return $(G(o?.source).tracks).forEach((a,d)=>{a.type==="caption"&&$(a.cues).forEach((i,l)=>{s.push(String(i.text));let c=o?.resolved?.items.find(b=>b.cue?.track===a.id&&b.cue?.index===l),u=m("textarea",{class:"studio-input",attrs:{"aria-label":x(t,"subtitles")+" "+(l+1),rows:"2"}});u.value=String(i.text),u.addEventListener("change",()=>{n.send({op:"set",path:["tracks",d,"cues",l,"text"],value:u.value}),ce(t,x(t,"pendingVoice"))});let h=c?{kind:"item",id:c.id}:void 0,f=()=>{h&&n.reveal(h)};u.addEventListener("focus",f);let p=C(Ze(c?.start??0,o?.resolved?.canvas.fps??30),f),g=m("article",{class:"studio-sentence"+(h&&ge(h,t.get().pinned)?" selected":""),data:h?{selection:JSON.stringify(h)}:{}},[p,u]);g.addEventListener("click",f),r.append(g)})}),m("div",{class:"studio-side-body"},[U(x(t,"script")),A(x(t,"scriptHint"),"notice"),r,A(x(t,"narrationUnavailable")),C(x(t,"copyScript"),()=>{navigator.clipboard.writeText(s.join(\`
37751
- \`)).then(()=>ce(t,x(t,"sourceChanged")))})])},Gn=e=>{let{store:t,edit:n}=e,o=t.get().state,r=Pt(e),s=m("div",{class:"studio-side-body"},[U(x(t,"elements"),r?.id)]);if(!o||!r)return s;s.append(C(x(t,"addText"),()=>{n.addText()}));for(let i of o.resolved?.items.filter(l=>l.end>r.start&&l.start<r.end)??[]){let l={kind:"item",id:i.id},c=C(i.text??x(t,i.type==="video"?"video":i.type==="image"?"image":i.type==="shape"?"color":"text"),()=>n.reveal(l),"studio-item"+(ge(l,t.get().pinned)?" selected":""));c.dataset.selection=JSON.stringify(l),s.append(c)}for(let i of o.resolved?.audio??[]){let l={kind:"audio",id:i.id},c=C(x(t,"audioTrack")+" \\xB7 "+i.id,()=>n.reveal(l),"studio-item"+(ge(l,t.get().pinned)?" selected":""));c.dataset.selection=JSON.stringify(l),s.append(c)}let a=He(document.querySelector("#page"),t,r.id),d=e.meta.slots.filter(i=>i.segment===r.id&&a?.has(i.name));s.append(U(x(t,"sceneFields")));for(let i of d){let l=t.get().pinned,c={kind:"slot",id:r.id,name:i.name},u=C("",()=>n.reveal(c,Qe(document.querySelector("#page"),t,c)),"studio-item "+(l?.kind==="slot"&&l.name===i.name?"selected":""));u.dataset.selection=JSON.stringify(c),u.append(m("span",{class:"studio-element-label",text:i.kind==="image"?x(t,"image"):i.value||i.name,title:i.value})),s.append(u)}return!d.length&&r.base.kind==="scene"&&s.append(A(x(t,"noSlots"))),s},Yn=e=>{let{store:t,actions:n}=e,o=t.get(),r=m("div",{class:"studio-side-body"},[U(x(t,"checks"))]);for(let a of o.state?.problems??[]){let d=m("article",{class:"studio-review-card"},[m("strong",{text:a.at}),A(a.message),A(a.fix??"")]),i=/^segments\\[(\\d+)\\]/.exec(a.at),l=i?o.state?.resolved?.segments[Number(i[1])]:void 0;l&&d.append(C(x(t,"goShot"),()=>Jn(e,l.id))),r.append(d)}o.state?.problems.length||r.append(A(x(t,"noProblems"))),r.append(A(o.state?.score?JSON.stringify(Object.fromEntries(Object.entries(o.state.score.dimensions).map(([a,d])=>[a,d.score.toFixed(2)]))):x(t,"unmeasured"))),r.append(U(x(t,"notes")));for(let a of e.meta.comments)r.append(m("article",{class:"studio-review-card"},[C(Ze(a.frame,o.state?.resolved?.canvas.fps??30),()=>{n.pause(),n.seek(a.frame)}),A(a.text),C(x(t,a.resolved?"reopen":"resolve"),()=>{ke(t,"/api/studio/comment",{id:a.id,resolved:!a.resolved}).then(e.refresh)})]));let s=m("textarea",{class:"studio-input",attrs:{rows:"3",placeholder:x(t,"noteHint")}});return r.append(s,C(x(t,"comment"),()=>{s.value.trim()&&ke(t,"/api/studio/comment",{text:s.value,frame:t.get().frame}).then(e.refresh)}),C(x(t,"copyNote"),()=>{navigator.clipboard.writeText(Ze(t.get().frame,o.state?.resolved?.canvas.fps??30)+" \\xB7 "+(Pt(e)?.id??"")+\`
37752
- \`+s.value)}),A(x(t,"reviewOnly"))),r},Xn=e=>{let{store:t}=e,n=m("div",{class:"studio-side-body"},[U(x(t,"versions"))]),o=Oe("",x(t,"versionName"));o.placeholder=x(t,"versionName"),n.append(o,C(x(t,"saveVersion"),()=>{ke(t,"/api/studio/version",{name:o.value||x(t,"newVersion")}).then(e.refresh)},"primary"),A(x(t,"versionSnapshot")));for(let r of e.meta.versions)n.append(m("article",{class:"studio-review-card"},[m("strong",{text:r.name}),A(new Date(r.created).toLocaleString()),...r.hash===e.meta.hash?[A(x(t,"current"))]:[C(x(t,"restore"),()=>{ke(t,"/api/studio/restore",{id:r.id,base:t.get().state?.source}).then(e.refresh)})]]));return e.meta.versions.length||n.append(A(x(t,"noVersions"))),n},Zn=()=>J("/api/studio");var Qn=(e,t)=>{let n=m("textarea",{id:"studio-json",class:"studio-json",attrs:{spellcheck:"false","aria-label":"video.json"}}),o=m("div",{class:"studio-code-status",attrs:{role:"status"}}),r,s,a=!1,d=!1,i,l=()=>{s=e.get().state?.source,n.value=JSON.stringify(s,null,2)??"",a=!1,o.textContent=x(e,"autosave")},c=async()=>{if(!a||d)return;let p;try{p=JSON.parse(n.value)}catch(y){o.textContent=x(e,"invalid")+": "+(y instanceof Error?y.message:"");return}d=!0,o.textContent=x(e,"saving");let g=n.value,b=await t.replace(p,s);d=!1,b?(s=e.get().state?.source,a=g!==n.value,o.textContent=x(e,"sourceChanged"),a&&setTimeout(()=>{u()},0)):o.textContent=e.get().edit.problems[0]?.message??x(e,"conflict")},u=()=>r??=c().finally(()=>{r=void 0});n.addEventListener("input",()=>{a=!0,i&&clearTimeout(i),i=setTimeout(()=>{u()},650)}),n.addEventListener("keydown",p=>{(p.ctrlKey||p.metaKey)&&p.key.toLowerCase()==="s"&&(p.preventDefault(),u()),p.key==="Tab"&&(p.preventDefault(),n.setRangeText(" ",n.selectionStart,n.selectionEnd,"end"),n.dispatchEvent(new Event("input")))}),window.addEventListener("beforeunload",p=>{a&&(p.preventDefault(),p.returnValue="")});let h=()=>{try{n.value=JSON.stringify(JSON.parse(n.value),null,2),n.dispatchEvent(new Event("input"))}catch{o.textContent=x(e,"invalid")}},f=m("div",{class:"studio-code-wrap"},[U(x(e,"sourceTitle"),"video.json"),A(x(e,"codeHint")),m("div",{class:"studio-actions"},[C(x(e,"format"),h),C(x(e,"download"),()=>rn(n.value,"video.json"))]),n,o,C(x(e,"reload"),l)]);return e.subscribe((p,g)=>{p.state?.source!==g.state?.source&&(!a&&!d?l():!d&&JSON.stringify(p.state?.source)!==JSON.stringify(s)&&(o.textContent=x(e,"conflict")))}),l(),{root:f,flush:async()=>(clearTimeout(i),r&&await r,a&&await u(),!a)}};var $n=(e,t,n)=>{let o=t.get().lang==="zh",r=(O,D)=>o?O:D,s=m("div",{class:"studio-cloud",id:"studio-cloud",attrs:{"aria-live":"polite"}});e.append(s);let a,d,i,l="push",c="",u="",h=!1,f=!1,p=!0,g,b=O=>({UNAUTHORIZED:r("\\u767B\\u5F55\\u5DF2\\u8FC7\\u671F\\u6216\\u5DF2\\u4F7F\\u7528\\uFF0C\\u8BF7\\u91CD\\u65B0\\u70B9\\u51FB\\u201C\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF\\u201D\\u3002","The login expired or was already used. Save to Cloud again."),LOGIN_REQUIRED:r("\\u8BF7\\u5148\\u767B\\u5F55\\uFF0C\\u518D\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF\\u3002","Sign in to save to cloud."),STORAGE_FULL:r("\\u4E91\\u7AEF\\u5B58\\u50A8\\u7A7A\\u95F4\\u5DF2\\u6EE1\\u3002","Your cloud storage is full."),STORAGE_QUOTA_EXCEEDED:r("\\u4E91\\u7AEF\\u5B58\\u50A8\\u7A7A\\u95F4\\u5DF2\\u6EE1\\u3002","Your cloud storage is full."),RATE_LIMITED:r("\\u4E0A\\u4F20\\u8FC7\\u4E8E\\u9891\\u7E41\\uFF0C\\u8BF7\\u7A0D\\u540E\\u518D\\u8BD5\\u3002","Too many uploads. Try again in a moment."),DECK_INVALID:r("\\u4E91\\u7AEF\\u65E0\\u6CD5\\u63A5\\u6536\\u8FD9\\u4E2A\\u4F5C\\u54C1\\u3002","The cloud could not accept this project."),NETWORK:r("\\u65E0\\u6CD5\\u8FDE\\u63A5 popost.ai\\u3002","Could not reach popost.ai."),LOCAL_SAVE_FAILED:r("\\u672C\\u5730\\u6539\\u52A8\\u4FDD\\u5B58\\u5931\\u8D25\\u3002\\u8BF7\\u5148\\u4FDD\\u5B58\\u4F5C\\u54C1\\uFF0C\\u518D\\u4E0A\\u4F20\\u5230\\u4E91\\u7AEF\\u3002","Could not save local edits. Save the project before uploading.")})[O??""]??r("\\u4E0A\\u4F20\\u5931\\u8D25\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u3002","Upload failed. Try again."),y=(O,D=!1)=>m("span",{class:"studio-cloud-state"+(D?" bad":""),text:O,attrs:{role:"status"},title:d?.message??a?.error?.message??O}),v=()=>a?.webUrl?[m("a",{class:"studio-btn studio-icon-btn",attrs:{href:a.webUrl,target:"_blank",rel:"noopener noreferrer",title:r("\\u5728 popost \\u6253\\u5F00","Open in popost"),"aria-label":r("\\u5728 popost \\u6253\\u5F00","Open in popost")}},[Y("external")])]:[],E=O=>{d={code:"NETWORK",message:O instanceof Error?O.message:String(O)}},M=async()=>{try{a=await J("/api/cloud/status")}catch{}p&&(F(),clearTimeout(g),g=setTimeout(()=>{M()},i||a?.state==="waiting"||a?.state==="uploading"?2e3:5e3))},k=async()=>{if(i)return;let O=window.open("about:blank","_blank");l="start",d=void 0,f=!1,i="start",F();try{if(!await n()){O?.close(),d={code:"LOCAL_SAVE_FAILED",message:""};return}u=(await J("/api/studio/cloud/start",{lang:t.get().lang})).result.authorizeUrl,h=!O,O&&(O.opener=null,O.location.href=u),l="push",await M()}catch(D){O?.close(),E(D)}finally{i=void 0,await M()}},H=async(O=!1)=>{if(!i){l="push",d=void 0,i="push",F();try{if(!await n()){d={code:"LOCAL_SAVE_FAILED",message:""};return}a=(await J("/api/studio/cloud/push",{lang:t.get().lang,force:O})).result,!a.ok&&a.error?.code==="LOGIN_REQUIRED"&&(i=void 0,await k())}catch(D){E(D)}finally{i=void 0,await M()}}},L=async()=>{try{await navigator.clipboard.writeText(u),f=!0}catch{h=!0}F()},R=()=>{let O=d?.code??a?.error?.code;l==="start"||a?.mode==="anonymous"&&(O==="LOGIN_REQUIRED"||O==="UNAUTHORIZED")?k():H()},F=()=>{let O=JSON.stringify([a,d,i,u,h,f]);if(O===c||(c=O,s.hidden=a?.mode==="off",s.replaceChildren(),s.hidden))return;let D=i==="push"?"uploading":i==="start"?"starting":d?"failed":a?.state??"idle";if(D==="uploading"||D==="starting")s.append(y(D==="starting"?r("\\u7B49\\u5F85\\u767B\\u5F55\\u2026","Waiting for login\\u2026"):a?.mode==="keyed"?r("\\u540C\\u6B65\\u4E2D\\u2026","Syncing\\u2026"):r("\\u4E0A\\u4F20\\u4E2D\\u2026","Uploading\\u2026")));else if(D==="waiting"){if(s.append(y(r("\\u7B49\\u5F85\\u767B\\u5F55\\u2026","Waiting for login\\u2026")),ne(f?r("\\u94FE\\u63A5\\u5DF2\\u590D\\u5236","Link copied"):r("\\u590D\\u5236\\u94FE\\u63A5","Copy link"),"duplicate",()=>{L()})),h&&u){let w=m("input",{class:"studio-cloud-link",attrs:{readonly:"","aria-label":r("\\u767B\\u5F55\\u94FE\\u63A5","Login link")}});w.value=u,w.addEventListener("focus",()=>w.select()),s.append(w)}}else if(D==="saved")s.append(y(a?.mode==="keyed"?r("\\u5DF2\\u540C\\u6B65","Synced"):r("\\u5DF2\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF","Saved to cloud")),...v());else if(D==="failed")s.append(y(b(d?.code??a?.error?.code),!0),ne(r("\\u91CD\\u8BD5","Retry"),"refresh",R));else if(D==="conflict"){if(s.append(y(r("\\u7F51\\u9875\\u7AEF\\u5DF2\\u6709\\u4FEE\\u6539","Edited on the web"),!0),...v()),a?.mode==="keyed"){let w=ne(r("\\u8986\\u76D6","Overwrite"),"cloud",()=>{H(!0)});w.title=r("\\u7528\\u672C\\u5730\\u7248\\u672C\\u66FF\\u6362\\u7F51\\u9875\\u7AEF\\u7684\\u7248\\u672C","Replace the web copy with this local version"),s.append(w)}}else if(!a)s.append(y(r("\\u6B63\\u5728\\u68C0\\u67E5\\u8D26\\u53F7\\u2026","Checking account\\u2026")));else{let w=ne(a?.mode==="keyed"?r("\\u7ACB\\u5373\\u540C\\u6B65","Sync now"):a?.webUrl&&a.dirty?r("\\u672C\\u5730\\u6539\\u52A8\\u672A\\u4E0A\\u4F20","Local changes not uploaded"):r("\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF","Save to Cloud"),"cloud",()=>{a?.mode==="keyed"?H():k()});w.id="studio-cloud-save",w.disabled=!a,w.title=r("\\u5728 popost \\u7F51\\u9875\\u7AEF\\u7BA1\\u7406\\u4F60\\u7684\\u6240\\u6709\\u8D44\\u4EA7","Manage all your assets on the Popost website"),s.append(w)}};t.subscribe((O,D)=>{O.state?.source!==D.state?.source&&M()}),window.addEventListener("pagehide",()=>{p=!1,clearTimeout(g)}),F(),M()};var ct=(e,t,n)=>{if(t.kind==="segment"||t.track.type==="audio"||!T(e.source))return;let o=ee(e),r=o.map((p,g)=>({track:p,index:g})).filter(p=>p.track.type!=="audio").sort((p,g)=>Number(p.track.z??p.index)-Number(g.track.z??g.index)||p.index-g.index),s=e.resolved?.items.filter(p=>p.id===t.track.id||p.cue?.track===t.track.id)??[],a=new Set((e.resolved?.items??[]).filter(p=>s.some(g=>g.start<p.end&&g.end>p.start)).map(p=>p.cue?.track??p.id)),d=r.filter(p=>a.has(String(p.track.id))),i=d.findIndex(p=>p.index===t.index),l=d[i+n];if(!l)return;let c=r.findIndex(p=>p.index===t.index),u=r.indexOf(l);if(c<0||u<0||u>=r.length)return;let h=r.splice(c,1)[0];r.splice(u,0,h);let f=new Map(r.map((p,g)=>[p.index,g]));return{...e.source,tracks:o.map((p,g)=>f.has(g)?{...p,z:f.get(g)}:p)}};var eo=(e,t,n)=>{let o=m("input",{attrs:{type:"range",min:"100",max:"500",value:"100","aria-label":x(t,"zoom")}}),r=()=>e.parentElement?.style.setProperty("--timeline-zoom",String(Number(o.value)/100));o.addEventListener("input",r),r();let s=t.get().lang==="zh",a=(g,b)=>{let y=C(b,()=>{let v=t.get().timeline??{layers:!0,snapping:!0};t.set({timeline:{...v,[g]:!v[g]}})});return y.id="timeline-"+g,y},d=a("layers",s?"\\u56FE\\u5C42":"Layers");d.prepend(Y("layers"));let i=a("snapping",s?"\\u5438\\u9644":"Snap"),l=C(s?"\\u5206\\u5272":"Split",()=>{n.split()});l.id="edit-split";let c=g=>C(g<0?s?"\\u524D\\u79FB":"Earlier":s?"\\u540E\\u79FB":"Later",()=>{let b=n.target(),y=t.get().state;if(!(!y||!b))if(b.kind==="segment")n.send({op:"move",path:["segments",b.index],to:b.index+g});else{let v=ct(y,b,g);v&&n.replace(v,y.source)}}),u=c(-1),h=c(1);u.id="scene-earlier",h.id="scene-later";let f=m("span",{id:"timeline-selection",class:"timeline-selection"});e.append(m("span",{id:"edit-slot"}),l,u,h,m("span",{class:"timeline-divider"}),d,i,f,m("span",{class:"spacer"}),C(x(t,"viewAll"),()=>{o.value="100",r()}),o);let p=()=>{let g=t.get(),b=n.target();d.classList.toggle("selected",g.timeline?.layers!==!1),i.classList.toggle("selected",g.timeline?.snapping!==!1),d.setAttribute("aria-pressed",String(g.timeline?.layers!==!1)),i.setAttribute("aria-pressed",String(g.timeline?.snapping!==!1)),l.disabled=!!g.edit.saving||!n.canSplit(),u.hidden=h.hidden=!b||b.kind!=="segment"&&b.track.type==="audio",u.textContent=b?.kind==="segment"?s?"\\u524D\\u79FB":"Earlier":s?"\\u4E0B\\u79FB\\u56FE\\u5C42":"Send backward",h.textContent=b?.kind==="segment"?s?"\\u540E\\u79FB":"Later":s?"\\u4E0A\\u79FB\\u56FE\\u5C42":"Bring forward",u.disabled=b?.kind==="segment"?b.index===0:!(g.state&&b&&ct(g.state,b,-1)),h.disabled=b?.kind==="segment"?b.index>=(g.state?.resolved?.segments.length??0)-1:!(g.state&&b&&ct(g.state,b,1)),g.edit.saving&&(u.disabled=h.disabled=!0);let y=g.pinned,v=y?.kind==="slot"?g.slots?.find(M=>M.segment===y.id&&M.name===y.name):void 0,E=y?.kind==="item"?g.state?.resolved?.items.find(M=>M.id===y.id):void 0;f.textContent=y?y.kind==="slot"?v?.kind==="image"?s?"\\u56FE\\u7247":"Image":v?.value??x(t,"selected"):E?.text??(b?.kind==="segment"?(s?"\\u955C\\u5934 ":"Shot ")+(b.index+1):y.kind==="audio"?x(t,"audioTrack"):x(t,"selected")):s?"\\u70B9\\u9009\\u955C\\u5934\\u6216\\u753B\\u9762\\u5185\\u5BB9\\u8FDB\\u884C\\u7F16\\u8F91":"Select a shot or canvas element to edit",f.title=f.textContent};t.subscribe((g,b)=>{g.state!==b.state||g.pinned!==b.pinned||g.timeline!==b.timeline||g.slots!==b.slots||g.edit.saving!==b.edit.saving?p():g.frame!==b.frame&&(l.disabled=!!g.edit.saving||!n.canSplit())}),p()};var to=(e,t)=>{let n=e.get().lang==="zh",o=(g,b)=>n?g:b,r=t.target==="jianying"?o("\\u526A\\u6620\\u4E13\\u4E1A\\u7248","Jianying Pro"):"CapCut",s=!1,a=()=>{s||(i.remove(),d.remove(),document.getElementById("studio-export-open")?.focus())},d=m("div",{class:"studio-scrim",on:{click:a}}),i=m("aside",{class:"studio-export studio-draft-success",attrs:{role:"dialog","aria-modal":"true","aria-label":o("\\u5DF2\\u5BFC\\u5165","Imported into ")+r}}),l=A(t.productRunning?o("\\u91CD\\u542F"+r+"\\u5373\\u53EF\\u5728\\u672C\\u5730\\u8349\\u7A3F\\u770B\\u5230\\u300C"+t.name+"\\u300D\\u3002","Restart "+r+" to find \\u201C"+t.name+"\\u201D in local drafts."):o("\\u5DF2\\u4FDD\\u5B58\\u5230\\u672C\\u673A\\u8349\\u7A3F\\uFF0C\\u6253\\u5F00"+r+"\\u5373\\u53EF\\u67E5\\u770B\\u300C"+t.name+"\\u300D\\u3002","Open "+r+" to find \\u201C"+t.name+"\\u201D in local drafts.")),c=m("div",{attrs:{role:"status"}}),u=C(o("\\u7A0D\\u540E","Later"),a),h=C("\\xD7",a);h.setAttribute("aria-label",o("\\u5173\\u95ED","Close"));let f=t.productRunning?o("\\u91CD\\u542F","Restart ")+r:o("\\u6253\\u5F00","Open ")+r,p=C(f,()=>{(async()=>{s=!0,p.disabled=u.disabled=h.disabled=!0,p.textContent=o("\\u6B63\\u5728\\u6253\\u5F00\\u2026","Opening\\u2026"),c.replaceChildren();try{let g=await J("/api/studio/draft-open",{receiptId:t.receiptId});if(!g.result.ok){c.replaceChildren(A(g.result.quitPending?o(r+"\\u8FD8\\u672A\\u9000\\u51FA\\uFF0C\\u8BF7\\u5148\\u5728\\u5E94\\u7528\\u4E2D\\u4FDD\\u5B58\\u6216\\u5173\\u95ED\\u5F39\\u7A97\\uFF0C\\u7136\\u540E\\u91CD\\u8BD5\\u3002\\u8349\\u7A3F\\u5DF2\\u7ECF\\u4FDD\\u5B58\\u3002",r+" has not exited. Save your work or close its dialog, then retry. Your draft is already saved."):g.result.message??o("\\u5E94\\u7528\\u672A\\u80FD\\u6253\\u5F00\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u3002\\u8349\\u7A3F\\u5DF2\\u7ECF\\u4FDD\\u5B58\\u3002","The editor did not open. Retry; your draft is already saved."),"bad"));return}s=!1,a(),ce(e,g.result.restarted?o("\\u5DF2\\u91CD\\u542F","Restarted ")+r:o("\\u5DF2\\u6253\\u5F00","Opened ")+r)}catch(g){c.replaceChildren(A(String(g),"bad"))}finally{s=!1,p.disabled=u.disabled=h.disabled=!1,p.textContent=f}})()},"primary");t.canOpen||c.append(A(o("\\u672A\\u627E\\u5230\\u5E94\\u7528\\u5B89\\u88C5\\u4F4D\\u7F6E\\uFF0C\\u53EF\\u4EE5\\u7A0D\\u540E\\u624B\\u52A8\\u6253\\u5F00\\u3002\\u8349\\u7A3F\\u548C\\u7D20\\u6750\\u5DF2\\u4FDD\\u5B58\\u5230\\u672C\\u673A\\u3002","The app location could not be found. Open it manually later; the draft and media are saved locally."))),i.append(m("div",{class:"studio-export-header"},[U(o("\\u5DF2\\u5BFC\\u5165","Imported into ")+r),h]),l,c,m("div",{class:"studio-draft-actions"},[u,...t.canOpen?[p]:[]])),document.body.append(d,i),i.addEventListener("keydown",g=>{if(g.key==="Escape"&&a(),g.key!=="Tab")return;let b=Array.from(i.querySelectorAll("button:not(:disabled)")),y=b[0],v=b[b.length-1];g.shiftKey&&document.activeElement===y?(g.preventDefault(),v?.focus()):!g.shiftKey&&document.activeElement===v&&(g.preventDefault(),y?.focus())}),(t.canOpen?p:u).focus()};var Ct=(e,t)=>{if(document.getElementById("studio-export"))return;let n=e.get().state;if(!n?.resolved||!n.edit)return;let o=n.resolved,r=e.get().lang==="zh",s=(P,V)=>r?P:V,a="video",d="jianying",i="1080",l="",c="",u=!1,h=!1,f,p=!1,g,b,y=m("div",{class:"studio-export-result",attrs:{role:"status"}}),v=m("div",{class:"studio-paid-info"}),E,M=m("progress",{attrs:{max:"1",value:"0",hidden:""}}),k=m("fieldset",{class:"studio-export-fields"}),H=m("div",{class:"studio-segments export-tabs",attrs:{role:"tablist"}}),L=m("aside",{id:"studio-export",class:"studio-export",attrs:{role:"dialog","aria-modal":"true","aria-label":s("\\u5BFC\\u51FA\\u8BBE\\u7F6E","Export settings")}}),R=()=>{h||(document.removeEventListener("keydown",F,!0),so(),O.remove(),L.remove(),document.getElementById("studio-export-open")?.focus())},F=P=>{P.key==="Escape"&&(P.preventDefault(),P.stopPropagation(),R())},O=m("div",{class:"studio-scrim",on:{click:R}}),D=(P,V,I)=>m("div",{class:"studio-segments"},P.map(([me,de])=>{let Ot=C(de,()=>I(me),me===V?"selected":"");return Ot.setAttribute("aria-pressed",String(me===V)),Ot})),w=(P,V)=>(V.setAttribute("role","group"),V.setAttribute("aria-label",P),m("div",{class:"studio-field"},[m("span",{text:P}),V])),N=()=>{if(v.hidden=a!=="video",H.replaceChildren(...[["video",x(e,"video")],["draft",s("\\u526A\\u6620","Draft")]].map(([I,me])=>{let de=C(me,()=>{a=I,y.replaceChildren(),N(),B()},a===I?"selected":"");return de.setAttribute("role","tab"),de.setAttribute("aria-selected",String(a===I)),de})),a==="draft"){let I=m("details",{},[m("summary",{text:s("\\u90E8\\u5206\\u5185\\u5BB9\\u4E0D\\u652F\\u6301","Some content is flattened")}),A(s("\\u652F\\u6301\\uFF1A\\u5B57\\u5E55\\u6587\\u5B57\\u4E0E\\u65F6\\u95F4\\u3001\\u89C6\\u9891\\u7247\\u6BB5\\u3001\\u97F3\\u9891\\u7247\\u6BB5\\u3002\\u5B57\\u5E55\\u6837\\u5F0F\\u9700\\u5728\\u76EE\\u6807\\u7F16\\u8F91\\u5668\\u4E2D\\u91CD\\u65B0\\u8BBE\\u7F6E\\uFF1B\\u590D\\u6742\\u89C6\\u89C9\\u6548\\u679C\\u70D8\\u7119\\u5230\\u5404\\u4E2A\\u89C6\\u9891\\u7247\\u6BB5\\u3002","Supported: caption text/timing, video clips and audio clips. Reapply caption styles in the target editor. Complex visuals are baked per clip."))]),me=g?.find(de=>de.target===d);k.replaceChildren(A(s("\\u628A\\u5F53\\u524D\\u65F6\\u95F4\\u7EBF\\u76F4\\u63A5\\u4FDD\\u5B58\\u4E3A\\u672C\\u673A\\u5E94\\u7528\\u4E2D\\u53EF\\u7EE7\\u7EED\\u7F16\\u8F91\\u7684\\u8349\\u7A3F\\u3002","Save the current timeline directly into your desktop editor\\u2019s local drafts.")),A(s("\\u5BFC\\u51FA\\u6210\\u529F\\u540E\\u53EF\\u4E00\\u952E\\u91CD\\u542F\\u5E94\\u7528\\uFF0C\\u5728\\u672C\\u5730\\u8349\\u7A3F\\u4E2D\\u7EE7\\u7EED\\u7F16\\u8F91\\u3002","After export, restart the app with one click and continue editing from local drafts.")),w(s("\\u5E94\\u7528","Application"),D([["jianying",s("\\u526A\\u6620\\u4E13\\u4E1A\\u7248","Jianying Pro")],["capcut","CapCut"]],d,de=>{d=de,b=void 0,N(),B()})),I),g?me?.usable||k.append(A(me?.error??s("\\u8BF7\\u5728\\u8FD0\\u884C\\u6B64\\u7F16\\u8F91\\u5668\\u7684\\u7535\\u8111\\u4E0A\\u5B89\\u88C5\\u5E76\\u6253\\u5F00\\u6240\\u9009\\u5E94\\u7528\\uFF0C\\u518D\\u91CD\\u65B0\\u6253\\u5F00\\u5BFC\\u51FA\\u8BBE\\u7F6E\\u3002","Install and open the selected app on the computer running this editor, then reopen export settings."),"bad")):k.append(A(s("\\u6B63\\u5728\\u68C0\\u67E5\\u672C\\u673A\\u5E94\\u7528\\u2026","Checking desktop editors\\u2026")));return}let P=D([["480","480p"],["720","720p"],["1080","1080p"],["2160","4K"]],i,I=>{i=I,N(),B()}),V=m("button",{text:"HDR",attrs:{type:"button",disabled:"",title:x(e,"hdrUnavailable")}});if(k.replaceChildren(w(x(e,"dynamicRange"),m("div",{class:"studio-segments"},[C("SDR",()=>{},"selected"),V])),w(x(e,"resolution"),P),Me(x(e,"fps"),wt([["",x(e,"match")+" ("+o.canvas.fps+" fps)"],...[24,25,30,50,60].map(I=>[String(I),I+" fps"])],l,x(e,"fps"),I=>{l=I})),Me(s("\\u89C6\\u9891\\u7801\\u7387","Video bitrate"),wt([["",x(e,"recommended")],...[2,5,8,12,20,40].map(I=>[String(I),I+" Mbps"])],c,x(e,"bitrate"),I=>{c=I}))),v.replaceChildren(),!u){let I=P.lastElementChild;I&&I.append(m("span",{class:"export-pro",text:"PRO"}))}i==="2160"&&!u&&v.append(A(s("4K \\u4E3A\\u4ED8\\u8D39\\u5206\\u8FA8\\u7387\\u3002\\u5347\\u7EA7\\u5957\\u9910\\u540E\\u5373\\u53EF\\u5BFC\\u51FA\\uFF1B1080p \\u53CA\\u4EE5\\u4E0B\\u53EF\\u7EE7\\u7EED\\u4F7F\\u7528\\u3002","4K requires a paid plan. Upgrade to export in 4K, or choose 1080p or below.")),...E?[m("a",{class:"studio-btn",text:x(e,"unlock"),attrs:{href:E,target:"_blank",rel:"noopener"}})]:[A(x(e,"loading"))],C(x(e,"refreshPlan"),()=>{J("/api/export-options").then(I=>{u=I.premium,N(),B()})}))},z=C(s("\\u5BFC\\u51FA","Export"),()=>{(async()=>{try{if(a==="draft"){h=!0,B(),b??=crypto.randomUUID();let P=await J("/api/studio/draft",{target:d,requestId:b});h=!1,R(),to(e,P.result)}else{f=void 0,p=!1;let P=await J("/api/render",{name:"Popost-video",resolution:i,dynamicRange:"sdr",fps:l?Number(l):null,bitrate:c?Number(c):null,audio:!0});f=P.render.state==="running"?P.render.started:P.render.state==="done"||P.render.state==="failed"?P.render.finished:void 0,t.setRender(P.render)}}catch(P){y.replaceChildren(A(String(P),"bad"))}finally{h=!1,B()}})()},"primary"),B=()=>{let P=e.get().edit.render,V=h||a==="video"&&P?.state==="running";if(k.disabled=V,z.disabled=V||a==="video"&&i==="2160"&&!u||a==="draft"&&!g?.find(I=>I.target===d)?.usable,K.disabled=h,H.querySelectorAll("button").forEach(I=>{I.disabled=V}),M.hidden=!V,z.textContent=V?s("\\u6B63\\u5728\\u5BFC\\u51FA\\u2026","Exporting\\u2026"):s("\\u5BFC\\u51FA","Export"),a==="draft"){h&&M.removeAttribute("value");return}P?.state==="running"&&(M.value=P.total?P.frame/P.total:0,y.replaceChildren()),P?.state==="failed"&&y.replaceChildren(A(P.message,"bad")),P?.state==="done"&&f!==void 0&&P.finished>=f&&(f!==void 0&&P.finished>=f&&!p&&(p=!0,m("a",{attrs:{href:P.url,download:"Popost-video.mp4"}}).click()),y.replaceChildren(A(s("\\u5BFC\\u51FA\\u5B8C\\u6210\\uFF0C\\u89C6\\u9891\\u5DF2\\u4FDD\\u5B58\\u5E76\\u5F00\\u59CB\\u4E0B\\u8F7D\\u3002","Export complete. The video is saved and downloading."))))},K=C("\\xD7",R);L.append(m("div",{class:"studio-export-header"},[U(s("\\u5BFC\\u51FA\\u8BBE\\u7F6E","Export settings")),K]),H,k,v,M,z,y),document.body.append(O,L),N(),B(),J("/api/export-options").then(P=>{u=P.premium,E=P.pricingUrl??E,N(),B()}).catch(()=>{}),J("/api/studio/draft-targets",{}).then(P=>{g=P.result.applications,N(),B()}).catch(P=>{g=[],y.replaceChildren(A(String(P),"bad")),N(),B()});let so=e.subscribe((P,V)=>{L.isConnected&&P.edit.render!==V.edit.render&&B()});document.addEventListener("keydown",F,!0),z.focus()};var Ar=[["media","media","media"],["elements","elements","layers"],["script","subtitles","text"],["code","code","code"]],no=(e,t,n,o)=>{let r="media",s=m("nav",{class:"studio-rail",attrs:{"aria-label":"Studio"}}),a=m("aside",{id:"studio-content",class:"studio-content"}),d=Qn(t,o),i=d.root,l={store:t,actions:n,edit:o,meta:{hash:"",slots:[],versions:[],comments:[]},refresh:()=>{}},c=()=>{let w=document.querySelector("#page"),N=new Map([...new Set(l.meta.slots.map(K=>K.segment))].map(K=>[K,He(w,t,K)])),z=l.meta.slots.filter(K=>N.get(K.segment)?.has(K.name));if(JSON.stringify(z)!==JSON.stringify(t.get().slots)&&t.set({slots:z}),s.querySelectorAll("button").forEach(K=>{K.classList.toggle("active",K.dataset.panel===r),K.setAttribute("aria-pressed",String(K.dataset.panel===r))}),document.body.classList.toggle("panel-code",r==="code"),r==="code"){a.contains(i)||a.replaceChildren(i);return}let B={shots:At,media:Wn,script:qn,elements:Gn,checks:Yn,versions:Xn};a.replaceChildren(B[r](l))},u=w=>{r=w,c()};for(let[w,N,z]of Ar){let B=m("button",{data:{panel:w},attrs:{type:"button",title:x(t,N)},on:{click:()=>u(w)}},[Y(z),m("span",{text:x(t,N)})]);s.append(B)}let h=async()=>{let w=t.get().state?.generation;try{let N=await Zn();if(w!==t.get().state?.generation)return;l.meta=N,N.lastExport&&t.get().edit.render?.state!=="running"&&(!t.get().edit.render||t.get().edit.render?.state==="idle")&&o.setRender(N.lastExport),c()}catch{}};l.refresh=()=>{h()},e.prepend(s,a);let f=document.querySelector(".studio-topbar"),p=m("strong",{class:"studio-brand",text:"popost"}),g=m("span",{class:"studio-project"}),b=m("span",{class:"studio-save"}),y=m("span",{class:"studio-global-actions"}),v=ne(x(t,"compare"),"compare",()=>{if(!t.get().state?.reference){ce(t,x(t,"noReference"));return}t.get().edit.playRender&&o.togglePlayRender(),t.set({compare:!t.get().compare})});v.id="studio-compare";let E=ne(x(t,"layout"),"layout",()=>{let w=document.body.classList.toggle("focus-preview");E.setAttribute("aria-pressed",String(w))});E.setAttribute("aria-pressed","false");let M=ne(x(t,"theme"),"theme",()=>{let w=document.documentElement.classList.toggle("dark");M.setAttribute("aria-pressed",String(w)),localStorage.setItem("popost-studio-theme",w?"dark":"light")});M.setAttribute("aria-pressed",String(localStorage.getItem("popost-studio-theme")==="dark"));let k=ne(t.get().lang==="zh"?"English":"\\u4E2D\\u6587","language",()=>{let w=t.get().lang==="zh"?"en":"zh";localStorage.setItem("popost-studio-language",w),n.setLang(w),location.reload()});k.id="lang-toggle";let H=ne(x(t,"versions"),"history",()=>u("versions")),L=ne(x(t,"export"),"download",()=>Ct(t,o));L.id="studio-export-open",y.append(v,E,H,M,k),$n(y,t,async()=>await o.flush()?await d.flush()&&await o.flush():!1),y.append(L),f.append(p,g,b,y),document.documentElement.classList.toggle("dark",localStorage.getItem("popost-studio-theme")==="dark"),document.addEventListener("studio:export",()=>Ct(t,o));let R=document.getElementById("studio-stage-heading"),F=m("input",{attrs:{type:"checkbox","aria-label":x(t,"audio")}});F.checked=!0,F.addEventListener("change",()=>t.set({muted:!F.checked})),R.append(m("span",{text:x(t,"preview")}),m("label",{class:"studio-check",title:x(t,"onlyPreview")},[F,x(t,"audio")]));let O=document.querySelector(".panel");O.prepend(U(x(t,"properties")));let D=()=>{let w=t.get();document.body.setAttribute("aria-busy",String(!!w.edit.saving)),g.textContent=w.state?.project.name??"Popost Video Studio",b.textContent=w.connected?w.state?.edit?x(t,"saved"):x(t,"readOnly"):x(t,"offline"),w.edit.saving&&(b.textContent=x(t,"saving")),w.edit.status?.kind==="refused"&&(b.textContent=x(t,"error")),v.classList.toggle("selected",!!w.compare),v.setAttribute("aria-pressed",String(!!w.compare)),L.disabled=!w.state?.edit||!w.state.resolved,O.hidden=!w.pinned,document.body.classList.toggle("inspecting",!!w.pinned)};return t.subscribe((w,N)=>{if((w.state!==N.state||w.pinned!==N.pinned||w.compare!==N.compare||w.connected!==N.connected||w.edit.status!==N.edit.status||w.edit.saving!==N.edit.saving)&&D(),w.state!==N.state?(c(),h()):w.frame!==N.frame&&r==="elements"&&w.state?.resolved?.segments.find(z=>w.frame>=z.start&&w.frame<z.end)?.id!==N.state?.resolved?.segments.find(z=>N.frame>=z.start&&N.frame<z.end)?.id&&c(),w.pinned!==N.pinned&&w.pinned){let z=w.state?q(w.state,w.pinned):void 0,B=w.pinned.kind==="segment"?"media":z?.kind==="cue"?"script":"elements";B==="media"&&(l.mediaView="shots");let K=a.contains(document.activeElement);(r!==B||!K)&&(r=B,c())}w.pinned!==N.pinned&&a.querySelectorAll("[data-selection]").forEach(z=>{let B=z.dataset.selection===JSON.stringify(w.pinned);z.classList.toggle("selected",B),z.tagName==="BUTTON"&&z.setAttribute("aria-pressed",String(B)),B&&z.scrollIntoView({block:"nearest"})})}),document.addEventListener("studio:page-ready",c),document.addEventListener("studio:scene-ready",()=>{r==="elements"&&c()}),D(),c(),{refresh:h,choose:u,content:a,panel:()=>r}},oo=eo,ut=(e,t)=>{let n=t==="timeline",o=m("div",{class:"studio-handle "+(n?"horizontal":"vertical")+(t==="right"?" inspector-resize":""),attrs:{role:"separator",tabindex:"0","aria-orientation":n?"horizontal":"vertical"}});return n||(o.style.left=t==="left"?"calc(64px + var(--left-width) - 2px)":"calc(100% - var(--right-width) - 2px)"),o.addEventListener("pointerdown",r=>{o.setPointerCapture(r.pointerId);let s=n?r.clientY:r.clientX,a=n?"--timeline-height":t==="left"?"--left-width":"--right-width",d=parseFloat(getComputedStyle(document.documentElement).getPropertyValue(a)),i=c=>{let u=(n?c.clientY:c.clientX)-s,h=Math.min(n?innerHeight*.65:innerWidth*.4,Math.max(n?150:210,d+(t==="left"?u:-u)));document.documentElement.style.setProperty(a,h+"px")},l=()=>{o.removeEventListener("pointermove",i),o.removeEventListener("pointerup",l),localStorage.setItem("popost-studio-layout",document.documentElement.style.cssText)};o.addEventListener("pointermove",i),o.addEventListener("pointerup",l)}),e.append(o),o};var Cr=async()=>{let e=await fetch("/api/state",{cache:"no-store"});if(!e.ok)throw new Error("GET /api/state answered "+e.status);return await e.json()},Or=["boxes","events","safe"],Hr=(e,t)=>{let n=m("h1"),o=m("span",{class:"project",id:"project"}),r=m("span",{class:"status",id:"status"}),s=Or.map(i=>{let l=m("input",{id:"toggle-"+i,attrs:{type:"checkbox"}});l.addEventListener("change",()=>{t.toggleOverlay(i),l.blur()});let c=m("span");return{name:i,input:l,text:c,el:m("label",{class:"toggle"},[l,c])}}),a=m("button",{id:"lang-toggle",class:"tbtn",attrs:{type:"button"}});a.addEventListener("click",()=>{t.setLang(e.get().lang==="en"?"zh":"en"),a.blur()});let d=i=>{let l=i.state;n.textContent=S(i.lang,"title"),o.textContent=l?l.project.name+(l.resolved?" "+l.resolved.frames+"f, "+(l.resolved.frames/l.resolved.canvas.fps).toFixed(2)+" s":""):"",o.title=l?.project.dir??"",r.textContent=S(i.lang,l?.edit?"editing":"readOnly")+", "+S(i.lang,i.connected?"live":"offline"),r.classList.toggle("offline",!i.connected),s.forEach(c=>{c.text.textContent=S(i.lang,c.name),c.input.checked=i.overlays[c.name]}),a.textContent=S(i.lang,"language"),a.title=S(i.lang,"languageTitle")};return d(e.get()),e.subscribe((i,l)=>{(i.state!==l.state||i.lang!==l.lang||i.connected!==l.connected||i.overlays!==l.overlays)&&d(i)}),m("header",{},[n,o,...s.map(i=>i.el),m("span",{id:"edit-slot",class:"edit-slot"}),r,a])},Nr=(e,t)=>{document.body.classList.add("editing");let n=document.getElementById("edit-slot");n&&tt(n,e.store,e.edit),nt(e.panel,e.store,e.edit);let o=et(e.stage.frameBox,e.stage.iframe,e.store,e.edit);Ge(e.lanes,e.store,e.edit),ot(e.store,e.edit,o.nudge),We(e.store);let r=Je(t);r&&e.edit.select(r),t.edit&&t.edit.render.state!=="idle"&&e.edit.setRender(t.edit.render),e.events.addEventListener(je,s=>e.edit.setRender(JSON.parse(s.data))),Xe().then(s=>e.store.set({edit:{...e.store.get().edit,schema:s}}))},ro=()=>{let e=Ue(navigator.language);document.documentElement.lang=e==="zh"?"zh-CN":"en";let t=_e({state:null,frame:0,playing:!1,speed:1,lang:e,pinned:null,overlays:{boxes:!1,events:!0,safe:!1},connected:!0,pageError:null,edit:Ve}),n=Ke(t),o=qe(t,n),r=document.getElementById("app")??document.body,s=m("div",{class:"stage-area",id:"stage"}),a=m("div",{class:"transport",id:"transport"}),d=m("div",{class:"timeline",id:"timeline"}),i=m("aside",{class:"panel",id:"panel"});r.append(Hr(t,n),m("div",{class:"main"},[m("div",{class:"left"},[s,a,d]),i]));let l=dt(s,t,n);lt(a,t,n),rt(d,t,n),it(i,t,n,o);let c=new EventSource("/api/events"),u=!1,h=async()=>{try{let f=await Cr(),p=t.get();if(p.connected&&p.state&&f.generation<p.state.generation)return;t.set({state:f,frame:pe(t.get().frame,W(f)),connected:!0}),f.edit&&!u&&(u=!0,Nr({store:t,edit:o,stage:l,lanes:d.querySelector("#lanes")??d,panel:i,events:c},f))}catch{t.set({connected:!1})}};c.addEventListener(De,()=>{h()}),c.addEventListener("open",()=>{t.get().connected||h()}),c.addEventListener("error",()=>{t.get().connected&&t.set({connected:!1})}),h()};var Ir=()=>{let e=localStorage.getItem("popost-studio-language"),t=e==="zh"||e==="en"?e:Ue(navigator.language);document.documentElement.lang=t==="zh"?"zh-CN":"en",document.body.classList.add("studio");let n=localStorage.getItem("popost-studio-layout");n&&/^[-a-z0-9:;. %px]+$/i.test(n)&&(document.documentElement.style.cssText=n);let o=_e({state:null,frame:0,playing:!1,speed:1,lang:t,pinned:null,compare:!1,muted:!1,timeline:{layers:!1,snapping:!0},overlays:{boxes:!1,events:!1,safe:!1},connected:!0,pageError:null,edit:Ve}),r=Ke(o),s=qe(o,r),a=document.getElementById("app")??document.body,d=m("header",{class:"studio-topbar"}),i=m("div",{class:"stage-area",id:"stage"}),l=m("div",{class:"transport",id:"transport"}),c=m("div",{class:"timeline",id:"timeline"}),u=m("aside",{class:"panel",id:"panel"}),h=m("div",{class:"main"},[m("div",{class:"left"},[m("div",{id:"studio-stage-heading",class:"studio-stage-heading"}),i,l]),u]),f=m("div",{class:"studio-timeline-toolbar"}),p=m("div",{class:"studio-timeline-wrap"},[f,c]),g=m("footer",{class:"studio-footer"},["Popost Video Studio","video.json"]);a.append(d,h,p,g,m("div",{id:"studio-message",attrs:{role:"status"}})),no(h,o,r,s),oo(f,o,s),ut(h,"left"),ut(h,"right"),ut(p,"timeline");let b=dt(i,o,r);lt(l,o,r),rt(c,o,r),it(u,o,r,s),gn(o);let y=new EventSource("/api/events"),v=!1,E=async()=>{try{let M=await fetch("/api/state",{cache:"no-store"});if(!M.ok)throw new Error;let k=await M.json(),H=o.get();if(H.connected&&H.state&&k.generation<H.state.generation)return;if(o.set({state:k,frame:pe(H.frame,W(k)),connected:!0}),k.edit&&!v){v=!0,document.body.classList.add("editing"),tt(document.getElementById("edit-slot"),o,s),nt(u,o,s);let L=et(b.frameBox,b.iframe,o,s);Ge(c.querySelector("#lanes")??c,o,s),ot(o,s,L.nudge),We(o);let R=Je(k);R&&s.select(R),k.edit.render.state!=="idle"&&s.setRender(k.edit.render),Xe().then(F=>o.set({edit:{...o.get().edit,schema:F}}))}}catch{o.set({connected:!1})}};y.addEventListener(De,()=>{E()}),y.addEventListener(je,M=>s.setRender(JSON.parse(M.data))),y.addEventListener("open",()=>{o.get().connected||E()}),y.addEventListener("error",()=>{o.get().connected&&o.set({connected:!1})}),E()};document.documentElement.dataset.mode==="readonly"?ro():Ir();})();
38022
+ SHELL_BUNDLE = `"use strict";(()=>{var De="reload",je="render";var ao=new Set(["wipe","slide","whip"]),se=e=>e.resolved?.canvas.fps??e.measure?.measure.source.fps??e.referenceMeasure?.measure.source.fps??30,ye=(e,t,n)=>e*n/t,io=(e,t,n)=>Math.floor((e+.5)*n/t),W=e=>{if(e.resolved)return e.resolved.frames;let t=se(e),n=[e.measure,e.referenceMeasure].map(o=>o?Math.round(ye(o.measure.source.frames,o.measure.source.fps,t)):0);return Math.max(0,...n)},pe=(e,t)=>Math.min(Math.max(0,t-1),Math.max(0,Math.round(e))),Z=(e,t)=>e.segments.find(n=>t>=n.start&&t<n.end),fe=(e,t)=>e.items.filter(n=>t>=n.start&&t<n.end),Nt=e=>[e.kind,e.frames+"f",ao.has(e.kind)?e.direction:"",e.kind==="slide"?e.mode:"",e.kind==="fade"?"via "+e.via:"",e.side&&e.side!=="both"?e.side:"",e.strength!==void 0&&e.strength!==1?"x"+e.strength:""].filter(Boolean).join(" "),Te=e=>e.preset+" "+e.frames+"f"+(e.preset==="slide"||e.preset==="wipe"?" "+e.direction:""),It=e=>[e.kind,e.kind==="cut"?"":e.end-e.start-1+"f",e.direction??"",e.mode??"",e.via?"via "+e.via:"",e.confidence.toFixed(2)].filter(Boolean).join(" "),ze=e=>[e.kind,e.how??"",e.direction??""].filter(Boolean).join(" "),Ft=e=>e.shots.flatMap((t,n)=>t.events.map((o,r)=>({shot:n,index:r,event:o}))).sort((t,n)=>t.event.start-n.event.start||t.shot-n.shot),Dt=(e,t,n)=>{let o=io(t,n,e.source.fps);return e.shots.flatMap(r=>r.events.filter(s=>o>=s.start&&o<s.end))},mt=(e,t)=>{let n=[];return e.map(o=>{let r=n.findIndex(a=>a<=o.start),s=r>=0?r:Math.min(n.length,t-1);return n[s]=Math.max(n[s]??0,o.end),{row:s,...o}})},jt=(e,t)=>{let n=e/t,o=[.5,1,2,5,10,15,30,60,120,300].find(s=>n/s<=12)??600,r=Math.floor(n/o);return Array.from({length:r+1},(s,a)=>({frame:Math.round(a*o*t),label:String(Number((a*o).toFixed(1)))+"s"}))},zt=e=>e.height>e.width?[.06,.08,.82,.72]:[.05,.05,.9,.9],pt=(e,t)=>(e/t).toFixed(2)+" s",ge=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Ht=(e,t)=>(t==="render"?e.measure:e.referenceMeasure)?.measure,Bt=(e,t)=>{switch(t.kind){case"slot":return;case"segment":return e.resolved?.segments.find(n=>n.id===t.id);case"item":return e.resolved?.items.find(n=>n.id===t.id);case"audio":return e.resolved?.audio.find(n=>n.id===t.id);case"boundary":return Ht(e,t.source)?.boundaries[t.index];case"event":return Ht(e,t.source)?.shots[t.shot]?.events[t.index]}},Vt=e=>{switch(e.kind){case"slot":return e.name;case"segment":case"item":case"audio":return e.kind+" "+e.id;case"boundary":return e.source+" boundary "+(e.index+1);case"event":return e.source+" event "+(e.shot+1)+"."+(e.index+1)}};var Ve={schema:null,status:null,problems:[],render:null,playRender:!1},_e=e=>{let t=e,n=[];return{get:()=>t,set:o=>{let r=t;t={...t,...o},n.forEach(s=>s(t,r))},subscribe:o=>(n.push(o),()=>{let r=n.indexOf(o);r>=0&&n.splice(r,1)})}},_t=[.25,.5,1],Be=e=>e.state?W(e.state):0,lo=e=>e.state?se(e.state):30,co=e=>{let t={frame:0,time:0},n=0,o=s=>{let a=e.get();if(!a.playing)return;let c=Math.max(0,Be(a)-1),i=Math.min(c,t.frame+Math.floor((s-t.time)/1e3*lo(a)*a.speed));if(i>=c)return e.set({frame:c,playing:!1});i!==a.frame&&e.set({frame:i}),n=requestAnimationFrame(o)},r=()=>{t={frame:e.get().frame,time:performance.now()}};return{reanchor:r,pause:()=>{cancelAnimationFrame(n),e.get().playing&&e.set({playing:!1})},play:()=>{let s=e.get();Be(s)<2||(s.frame>=Be(s)-1&&e.set({frame:0}),r(),e.set({playing:!0}),n=requestAnimationFrame(o))}}},Ke=e=>{let t=co(e),n=o=>{e.set({frame:pe(o,Be(e.get()))}),t.reanchor()};return{seek:n,step:o=>n(e.get().frame+o),togglePlay:()=>e.get().playing?t.pause():t.play(),pause:t.pause,setSpeed:o=>{e.set({speed:o}),t.reanchor()},pin:o=>e.set({pinned:o}),toggleOverlay:o=>{let r=e.get().overlays;e.set({overlays:{...r,[o]:!r[o]}})},setLang:o=>{document.documentElement.lang=o==="zh"?"zh-CN":"en",e.set({lang:o})}}};var u=(e,t={},n=[])=>{let o=document.createElement(e);t.class&&(o.className=t.class),t.id&&(o.id=t.id),t.text!==void 0&&(o.textContent=t.text),t.title&&(o.title=t.title),t.style&&(o.style.cssText=t.style);for(let[r,s]of Object.entries(t.attrs??{}))o.setAttribute(r,s);for(let[r,s]of Object.entries(t.data??{}))o.dataset[r]=s;for(let[r,s]of Object.entries(t.on??{}))s&&o.addEventListener(r,s);return o.append(...n),o},Kt="http://www.w3.org/2000/svg",uo={film:"M2 2h12v12H2zM5 2v12M11 2v12M2 6h3M2 10h3M11 6h3M11 10h3",media:"M2 2h12v12H2zM2 12l4-5 4 4 2-2 2 3M5 4h.1",text:"M2 3h12M8 3v11M5 14h6",layers:"M1 5l7-4 7 4-7 4-7-4M1 8l7 4 7-4M1 11l7 4 7-4",code:"M5 3 1 8l4 5M11 3l4 5-4 5M9 2 7 14",checks:"M8 1l6 2v5c0 4-6 7-6 7S2 12 2 8V3l6-2M5 8l2 2 4-4",first:"M4 3v10M12 3.5 6 8l6 4.5z",last:"M12 3v10M4 3.5 10 8l-6 4.5z",play:"M5 3l8 5-8 5z",pause:"M5.5 3v10M10.5 3v10",undo:"M6 3.5 3 6.5l3 3M3 6.5h6.5a3.5 3.5 0 0 1 0 7H7",redo:"M10 3.5l3 3-3 3M13 6.5H6.5a3.5 3.5 0 0 0 0 7H9",remove:"M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.7 8.5h5.6l.7-8.5M7 7v4M9 7v4",addText:"M2 3.5h7M5.5 3.5V12M11.5 8v5M9 10.5h5",duplicate:"M5.5 5.5h7v7h-7zM3.5 10.5v-7h7",render:"M2.5 3.5h11v9h-11zM7 6l3 2-3 2z",compare:"M2 2h12v12H2zM8 2v12M4 6h2M10 10h2",layout:"M2 2h12v12H2zM5.5 2v12M10.5 2v12",history:"M2 2v4h4M2 6a6 6 0 1 1 0 4M8 4v4l3 2",theme:"M8 1a7 7 0 1 0 7 7A5 5 0 0 1 8 1z",language:"M1 3h8M5 1v2M3 3c0 4 3 6 6 7M8 3c0 4-3 6-7 7M9 14l3-8 3 8M10 11h4",download:"M8 1v9M4 6l4 4 4-4M2 11v3h12v-3",external:"M9 2h5v5M14 2 7 9M6 2H2v12h12v-4",cloud:"M4 12a3 3 0 0 1-1-5.8A5 5 0 0 1 12 5a3.5 3.5 0 0 1 0 7M8 14V7M5.5 9.5 8 7l2.5 2.5",refresh:"M13 2v4H9M13 6a5.5 5.5 0 1 0 .2 5"},Y=e=>{let t=document.createElementNS(Kt,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","16"),t.setAttribute("height","16"),t.setAttribute("aria-hidden","true");let n=document.createElementNS(Kt,"path");return n.setAttribute("d",uo[e]),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.5"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("stroke-linecap","round"),t.appendChild(n),t},Le=(e,t,n,o)=>{let r=Math.max(1,o);return e.style.left=Math.max(0,t)/r*100+"%",e.style.width=Math.max(0,Math.min(n,r)-Math.max(0,t))/r*100+"%",e},Q=(e,t,n)=>(e.style.left=Math.max(0,Math.min(t,n))/Math.max(1,n)*100+"%",e),le=(e,t)=>{let[n=0,o=0,r=0,s=0]=t;return e.style.left=n*100+"%",e.style.top=o*100+"%",e.style.width=r*100+"%",e.style.height=s*100+"%",e};var ft={title:"Video preview",readOnly:"read-only",live:"live",offline:"offline, retrying",language:"\\u4E2D\\u6587",languageTitle:"Switch the interface to Chinese",currentVideo:"Current video",render:"Render",reference:"Reference",seekNote:"A browser video seek is near, not frame-exact.",noReference:"No reference video. Start with --reference <video> to show one here.",errorsOnStage:"The project has errors; the stage lists them.",imageFailed:"A picture or video failed to load",first:"First frame (Home)",last:"Last frame (End)",back10:"Back 10 frames (Shift+Left)",back1:"Back 1 frame (Left)",fwd1:"Forward 1 frame (Right)",fwd10:"Forward 10 frames (Shift+Right)",play:"Play (Space)",pause:"Pause (Space)",frame:"Frame",time:"Time",speed:"Speed",jump:"Go to frame",jumpHint:"Frame number, then Enter",ruler:"Seconds",segments:"Segments",audio:"Audio",words:"Words",renderBoundaries:"Render: boundaries",renderEvents:"Render: events",referenceBoundaries:"Reference: boundaries",referenceEvents:"Reference: events",boxes:"Item boxes",events:"Measured events",safe:"Safe area",selection:"Selection",underPlayhead:"under the playhead",pinned:"clicked",follow:"Follow the playhead",onScreen:"On screen",nothing:"Nothing here.",problems:"Problems",noProblems:"No problems.",allowed:"Allowed",fix:"Fix",error:"error",warning:"warning",score:"Score",noScore:"No score: it needs a measurement of the render and one of the reference.",dimension:"Dimension",value:"Score",compared:"Compared",detail:"Detail",composite:"composite",measurements:"Measurements",renderMeasure:"Render",referenceMeasure:"Reference",none:"none",notes:"Draft notes",structure:"structure",transitions:"transitions",camera:"camera",motion:"motion",rhythm:"rhythm",colour:"colour",picture:"picture",editing:"editing",undo:"Undo (Ctrl+Z)",redo:"Redo (Shift+Ctrl+Z)",addText:"Add a text at the playhead",duplicate:"Duplicate the selection",remove:"Delete the selection (Delete)",renderTool:"Render the project to out.mp4",newText:"New text",saved:"Saved",added:"Added",removed:"Deleted",moved:"Moved",outside:"an edit made outside the page",undone:"Undone",redone:"Redone",notSaved:"Not saved",phraseSpan:"This item is placed on spoken words, so it is not dragged: change its lead and hold in the panel.",offlineEdit:"The preview server cannot be reached; nothing was saved.",rendering:"Rendering",rendered:"Rendered",framesIn:"frames in",renderFailed:"The render failed",playRender:"Play it beside the stage",showReference:"Show the reference again",renderFile:"Render",editHint:"Click an item on the stage, a bar in the lanes or a segment to edit it. Escape clears the selection.",resolvedTitle:"What the timeline plays (the default, or the value after resolving)",snapped:"snapped to",snapPlayhead:"the playhead",snapSegment:"a segment border",snapReference:"a boundary of the reference",framesWord:"frames",videoLength:"video",onFrames:"On frames",fDefault:"(default)",fCustom:"own values",fStyle:"Style",fNamed:"Style",fSize:"Size",fColour:"Colour",fWeight:"Weight",fAlign:"Align",fPreset:"Preset",fNone:"(none)",fFrames:"Frames",fDirection:"Direction",fEase:"Ease",fEnter:"Entrance",fExit:"Exit",fBox:"Box (fractions of the canvas)",fX:"x",fY:"y",fW:"width",fH:"height",fRotate:"Rotate",fOpacity:"Opacity",fZ:"Layer (z)",fLook:"Look",fRadius:"Corners",fShape:"Shape",fGradient:"A gradient: edit it in video.json.",fMaterial:"Material",fFit:"Fit",fMask:"Mask",fIn:"First frame",fSpeed:"Speed",fFootage:"Footage",fPicture:"Picture",fText:"Text",fStart:"Starts in",fWhole:"(the whole video)",fFrom:"From",fAudio:"Sound",fGain:"Gain (dB)",fSourceAudio:"Source audio dB (empty = automatic: on when the video has no audio track)",fSegment:"Segment",fWhen:"When",fPhrase:"Phrase",fOccurrence:"Occurrence",fLead:"Lead",fHold:"Hold",fTo:"To",fCue:"Cue",fCues:"Cues",fKind:"Kind",fHardCut:"(hard cut)",fMode:"Mode",fVia:"Via",fSide:"Side",fStrength:"Strength",fTransition:"Transition into it",fBase:"Base",fBaseColor:"colour",fBaseMaterial:"material",fBaseScene:"Scene content",fLength:"Length in frames",fCamera:"The camera: edit it in video.json."},mo={title:"\\u89C6\\u9891\\u9884\\u89C8",readOnly:"\\u53EA\\u8BFB",live:"\\u5DF2\\u8FDE\\u63A5",offline:"\\u8FDE\\u63A5\\u4E2D\\u65AD\\uFF0C\\u6B63\\u5728\\u91CD\\u8BD5",language:"English",languageTitle:"\\u628A\\u754C\\u9762\\u5207\\u6362\\u4E3A\\u82F1\\u6587",currentVideo:"\\u5F53\\u524D\\u4F5C\\u54C1",render:"\\u6E32\\u67D3",reference:"\\u53C2\\u8003\\u89C6\\u9891",seekNote:"\\u6D4F\\u89C8\\u5668\\u7684\\u89C6\\u9891\\u8DF3\\u8F6C\\u53EA\\u662F\\u63A5\\u8FD1\\uFF0C\\u4E0D\\u662F\\u9010\\u5E27\\u7CBE\\u786E\\u3002",noReference:"\\u6CA1\\u6709\\u53C2\\u8003\\u89C6\\u9891\\u3002\\u7528 --reference <\\u89C6\\u9891> \\u542F\\u52A8\\u5373\\u53EF\\u5728\\u6B64\\u663E\\u793A\\u3002",errorsOnStage:"\\u9879\\u76EE\\u6709\\u9519\\u8BEF\\uFF0C\\u753B\\u9762\\u533A\\u5217\\u51FA\\u4E86\\u5B83\\u4EEC\\u3002",imageFailed:"\\u6709\\u56FE\\u7247\\u6216\\u89C6\\u9891\\u52A0\\u8F7D\\u5931\\u8D25",first:"\\u7B2C\\u4E00\\u5E27 (Home)",last:"\\u6700\\u540E\\u4E00\\u5E27 (End)",back10:"\\u540E\\u9000 10 \\u5E27 (Shift+\\u2190)",back1:"\\u540E\\u9000 1 \\u5E27 (\\u2190)",fwd1:"\\u524D\\u8FDB 1 \\u5E27 (\\u2192)",fwd10:"\\u524D\\u8FDB 10 \\u5E27 (Shift+\\u2192)",play:"\\u64AD\\u653E (\\u7A7A\\u683C)",pause:"\\u6682\\u505C (\\u7A7A\\u683C)",frame:"\\u5E27",time:"\\u65F6\\u95F4",speed:"\\u901F\\u5EA6",jump:"\\u8DF3\\u5230\\u5E27",jumpHint:"\\u8F93\\u5165\\u5E27\\u53F7\\u540E\\u6309\\u56DE\\u8F66",ruler:"\\u79D2",segments:"\\u5206\\u6BB5",audio:"\\u97F3\\u9891",words:"\\u5B57\\u8BCD",renderBoundaries:"\\u6E32\\u67D3\\uFF1A\\u8FB9\\u754C",renderEvents:"\\u6E32\\u67D3\\uFF1A\\u5143\\u7D20\\u4E8B\\u4EF6",referenceBoundaries:"\\u53C2\\u8003\\uFF1A\\u8FB9\\u754C",referenceEvents:"\\u53C2\\u8003\\uFF1A\\u5143\\u7D20\\u4E8B\\u4EF6",boxes:"\\u5143\\u7D20\\u6846",events:"\\u6D4B\\u5F97\\u7684\\u4E8B\\u4EF6",safe:"\\u5B89\\u5168\\u533A",selection:"\\u9009\\u4E2D",underPlayhead:"\\u64AD\\u653E\\u5934\\u6240\\u5728\\u5904",pinned:"\\u5DF2\\u70B9\\u9009",follow:"\\u8DDF\\u968F\\u64AD\\u653E\\u5934",onScreen:"\\u753B\\u9762\\u4E2D",nothing:"\\u8FD9\\u91CC\\u6CA1\\u6709\\u5185\\u5BB9\\u3002",problems:"\\u95EE\\u9898",noProblems:"\\u6CA1\\u6709\\u95EE\\u9898\\u3002",allowed:"\\u5141\\u8BB8\\u7684\\u503C",fix:"\\u4FEE\\u6B63",error:"\\u9519\\u8BEF",warning:"\\u8B66\\u544A",score:"\\u8BC4\\u5206",noScore:"\\u6CA1\\u6709\\u8BC4\\u5206\\uFF1A\\u9700\\u8981\\u6E32\\u67D3\\u548C\\u53C2\\u8003\\u89C6\\u9891\\u5404\\u81EA\\u7684\\u6D4B\\u91CF\\u7ED3\\u679C\\u3002",dimension:"\\u7EF4\\u5EA6",value:"\\u5206\\u6570",compared:"\\u6BD4\\u8F83\\u6570",detail:"\\u7EC6\\u8282",composite:"\\u7EFC\\u5408",measurements:"\\u6D4B\\u91CF\\u7ED3\\u679C",renderMeasure:"\\u6E32\\u67D3",referenceMeasure:"\\u53C2\\u8003",none:"\\u65E0",notes:"\\u8349\\u7A3F\\u5907\\u6CE8",structure:"\\u7ED3\\u6784",transitions:"\\u8F6C\\u573A",camera:"\\u955C\\u5934\\u8FD0\\u52A8",motion:"\\u5143\\u7D20\\u52A8\\u6548",rhythm:"\\u8282\\u594F",colour:"\\u8272\\u5F69",picture:"\\u753B\\u9762",editing:"\\u7F16\\u8F91\\u4E2D",undo:"\\u64A4\\u9500 (Ctrl+Z)",redo:"\\u91CD\\u505A (Shift+Ctrl+Z)",addText:"\\u5728\\u64AD\\u653E\\u5934\\u5904\\u6DFB\\u52A0\\u6587\\u5B57",duplicate:"\\u590D\\u5236\\u6240\\u9009\\u5185\\u5BB9",remove:"\\u5220\\u9664\\u6240\\u9009\\u5185\\u5BB9 (Delete)",renderTool:"\\u628A\\u9879\\u76EE\\u6E32\\u67D3\\u4E3A out.mp4",newText:"\\u65B0\\u6587\\u5B57",saved:"\\u5DF2\\u4FDD\\u5B58",added:"\\u5DF2\\u6DFB\\u52A0",removed:"\\u5DF2\\u5220\\u9664",moved:"\\u5DF2\\u79FB\\u52A8",outside:"\\u9875\\u9762\\u5916\\u7684\\u4FEE\\u6539",undone:"\\u5DF2\\u64A4\\u9500",redone:"\\u5DF2\\u91CD\\u505A",notSaved:"\\u672A\\u4FDD\\u5B58",phraseSpan:"\\u8FD9\\u4E2A\\u5143\\u7D20\\u6309\\u8BF4\\u51FA\\u7684\\u5B57\\u8BCD\\u5B9A\\u4F4D\\uFF0C\\u4E0D\\u80FD\\u62D6\\u52A8\\uFF1A\\u8BF7\\u5728\\u9762\\u677F\\u91CC\\u4FEE\\u6539\\u5B83\\u7684\\u63D0\\u524D\\u91CF\\u548C\\u5EF6\\u540E\\u91CF\\u3002",offlineEdit:"\\u8FDE\\u4E0D\\u4E0A\\u9884\\u89C8\\u670D\\u52A1\\u5668\\uFF0C\\u6CA1\\u6709\\u4FDD\\u5B58\\u4EFB\\u4F55\\u4FEE\\u6539\\u3002",rendering:"\\u6E32\\u67D3\\u4E2D",rendered:"\\u5DF2\\u6E32\\u67D3",framesIn:"\\u5E27\\uFF0C\\u7528\\u65F6",renderFailed:"\\u6E32\\u67D3\\u5931\\u8D25",playRender:"\\u5728\\u753B\\u9762\\u65C1\\u64AD\\u653E",showReference:"\\u6539\\u56DE\\u663E\\u793A\\u53C2\\u8003\\u89C6\\u9891",renderFile:"\\u6E32\\u67D3\\u7ED3\\u679C",editHint:"\\u70B9\\u51FB\\u753B\\u9762\\u4E2D\\u7684\\u5143\\u7D20\\u3001\\u8F68\\u9053\\u4E0A\\u7684\\u6761\\u5757\\u6216\\u5206\\u6BB5\\u5373\\u53EF\\u7F16\\u8F91\\u3002\\u6309 Esc \\u53D6\\u6D88\\u9009\\u4E2D\\u3002",resolvedTitle:"\\u65F6\\u95F4\\u7EBF\\u5B9E\\u9645\\u64AD\\u653E\\u7684\\u503C\\uFF08\\u9ED8\\u8BA4\\u503C\\uFF0C\\u6216\\u89E3\\u6790\\u540E\\u7684\\u503C\\uFF09",snapped:"\\u5DF2\\u5438\\u9644\\u5230",snapPlayhead:"\\u64AD\\u653E\\u5934",snapSegment:"\\u5206\\u6BB5\\u8FB9\\u754C",snapReference:"\\u53C2\\u8003\\u89C6\\u9891\\u7684\\u8FB9\\u754C",framesWord:"\\u5E27",videoLength:"\\u89C6\\u9891",onFrames:"\\u6240\\u5728\\u5E27",fDefault:"\\uFF08\\u9ED8\\u8BA4\\uFF09",fCustom:"\\u81EA\\u5B9A\\u4E49",fStyle:"\\u6837\\u5F0F",fNamed:"\\u6837\\u5F0F",fSize:"\\u5B57\\u53F7",fColour:"\\u989C\\u8272",fWeight:"\\u5B57\\u91CD",fAlign:"\\u5BF9\\u9F50",fPreset:"\\u9884\\u8BBE",fNone:"\\uFF08\\u65E0\\uFF09",fFrames:"\\u5E27\\u6570",fDirection:"\\u65B9\\u5411",fEase:"\\u7F13\\u52A8",fEnter:"\\u5165\\u573A",fExit:"\\u51FA\\u573A",fBox:"\\u6846\\uFF08\\u753B\\u5E03\\u7684\\u6BD4\\u4F8B\\uFF09",fX:"x",fY:"y",fW:"\\u5BBD",fH:"\\u9AD8",fRotate:"\\u65CB\\u8F6C",fOpacity:"\\u4E0D\\u900F\\u660E\\u5EA6",fZ:"\\u5C42\\u7EA7 (z)",fLook:"\\u5916\\u89C2",fRadius:"\\u5706\\u89D2",fShape:"\\u5F62\\u72B6",fGradient:"\\u6E10\\u53D8\\uFF1A\\u8BF7\\u5728 video.json \\u91CC\\u4FEE\\u6539\\u3002",fMaterial:"\\u7D20\\u6750",fFit:"\\u9002\\u914D",fMask:"\\u906E\\u7F69",fIn:"\\u8D77\\u59CB\\u5E27",fSpeed:"\\u901F\\u5EA6",fFootage:"\\u89C6\\u9891\\u7D20\\u6750",fPicture:"\\u56FE\\u7247",fText:"\\u6587\\u5B57",fStart:"\\u5F00\\u59CB\\u4E8E",fWhole:"\\uFF08\\u6574\\u4E2A\\u89C6\\u9891\\uFF09",fFrom:"\\u4ECE",fAudio:"\\u58F0\\u97F3",fGain:"\\u589E\\u76CA (dB)",fSourceAudio:"\\u7D20\\u6750\\u539F\\u58F0 dB\\uFF08\\u7559\\u7A7A\\u4E3A\\u81EA\\u52A8\\uFF1A\\u89C6\\u9891\\u6CA1\\u6709\\u97F3\\u8F68\\u65F6\\u4FDD\\u7559\\uFF09",fSegment:"\\u5206\\u6BB5",fWhen:"\\u51FA\\u73B0\\u65F6\\u95F4",fPhrase:"\\u5B57\\u8BCD",fOccurrence:"\\u7B2C\\u51E0\\u6B21",fLead:"\\u63D0\\u524D",fHold:"\\u5EF6\\u540E",fTo:"\\u5230",fCue:"\\u5B57\\u5E55",fCues:"\\u5B57\\u5E55\\u6761",fKind:"\\u7C7B\\u578B",fHardCut:"\\uFF08\\u786C\\u5207\\uFF09",fMode:"\\u6A21\\u5F0F",fVia:"\\u7ECF\\u8FC7",fSide:"\\u5355\\u4FA7",fStrength:"\\u5F3A\\u5EA6",fTransition:"\\u8FDB\\u5165\\u5B83\\u7684\\u8F6C\\u573A",fBase:"\\u5E95\\u56FE",fBaseColor:"\\u989C\\u8272",fBaseMaterial:"\\u7D20\\u6750",fBaseScene:"\\u573A\\u666F\\u5185\\u5BB9",fLength:"\\u957F\\u5EA6\\uFF08\\u5E27\\uFF09",fCamera:"\\u955C\\u5934\\u8FD0\\u52A8\\uFF1A\\u8BF7\\u5728 video.json \\u91CC\\u4FEE\\u6539\\u3002"},po={en:ft,zh:mo},Ue=e=>e?.toLowerCase().startsWith("zh")?"zh":"en",S=(e,t)=>po[e][t],Ut=e=>Object.hasOwn(ft,e),Jt=(e,t)=>t in ft?S(e,t):t;var T=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),he=(e,t)=>T(e)&&Array.isArray(e[t])?e[t]:[],ee=e=>he(e.source,"tracks").filter(T),te=e=>he(e.source,"segments").filter(T),ve=(e,t)=>he(e.source,"materials").filter(T).filter(n=>t.includes(String(n.kind))).map(n=>String(n.id)),gt=(e,t)=>e.findIndex(n=>T(n)&&n.id===t),fo=(e,t)=>{let n=e.resolved?.items.find(r=>r.id===t);if(n)return n.cue;let o=t.match(/^(.+)#(\\d+)$/);return o?{track:o[1]??"",index:Number(o[2])}:void 0},q=(e,t)=>{if(!t||!T(e.source))return;let n=he(e.source,"tracks");if(t.kind==="segment"){let i=gt(he(e.source,"segments"),t.id),d=he(e.source,"segments")[i];return T(d)?{kind:"segment",index:i,segment:d}:void 0}if(t.kind!=="item"&&t.kind!=="audio")return;let o=gt(n,t.id),r=n[o];if(T(r)&&r.type!=="caption")return{kind:"track",index:o,track:r};let s=t.kind==="item"?fo(e,t.id):void 0,a=s?gt(n,s.track):-1,c=n[a];return s&&T(c)&&s.index<he(c,"cues").length?{kind:"cue",index:a,cue:s.index,track:c}:void 0},go=e=>e.kind==="segment"?["segments",e.index]:["tracks",e.index],ht=e=>{if(e.kind==="cue")return["tracks",e.index,"cues",e.cue,"during"];if(e.kind==="track"&&T(e.track.during))return["tracks",e.index,"during"]},bt=e=>e.kind!=="segment"&&Array.isArray(e.track.box)?["tracks",e.index,"box"]:void 0,oe=(e,t)=>t.reduce((n,o)=>Array.isArray(n)?n[o]:T(n)?n[String(o)]:void 0,e),Re=(e,t)=>{let n=bt(t),o=n?oe(e.source,n):void 0;return Array.isArray(o)&&o.length===4&&o.every(r=>typeof r=="number")?o:void 0},Wt=(e,t,n)=>{if(n===void 0)return oe(e,t)===void 0?void 0:{op:"remove",path:t};let o=t.length-1;for(;o>0&&!T(oe(e,t.slice(0,o)))&&!Array.isArray(oe(e,t.slice(0,o)));)o--;let r=t.slice(o+1).reduceRight((s,a)=>({[String(a)]:s}),n);return{op:"set",path:t.slice(0,o+1),value:r}},Se=(e,t)=>{if(!T(t)||t.phrase!==void 0||typeof t.segment!="string")return;let n=e.segments.find(s=>s.id===t.segment);if(!n)return;let o=typeof t.from=="number"?t.from:0,r=typeof t.to=="number"?t.to:n.end-n.start;return{start:n.start+o,end:n.start+r,segment:n}},yt=(e,t,n,o)=>{let r=e.segments.find(c=>c.id===t.segment),s=r&&n>=r.start&&n<r.end?r:Z(e,n)??r??e.segments[0],a=s?.start??0;return{...t,segment:s?.id??t.segment,from:n-a,to:o-a}},qt=(e,t,n=!0)=>{let o=e.resolved,r=o?.canvas.fps??30,s=e.referenceMeasure?.measure;return[{frame:t,kind:"playhead"},...n&&o?o.segments.flatMap(a=>[a.start,a.end]).map(a=>({frame:a,kind:"segment"})):[],...s?s.boundaries.map(a=>({frame:Math.round(ye(a.frame,s.source.fps,r)),kind:"reference"})):[]]},ho=4,Pe=(e,t,n)=>{let o=t.map(r=>({t:r,d:Math.abs(r.frame-e)*n})).filter(r=>r.d<=ho).sort((r,s)=>r.d-s.d)[0];return o?o.t:{frame:Math.round(e),kind:"frame"}},re=(e,t)=>{let n=new Set(e.map(r=>String(r.id))),o=t.replace(/-\\d+$/,"");if(!n.has(t))return t;for(let r=2;;r++)if(!n.has(o+"-"+r))return o+"-"+r},Gt=(e,t,n)=>{let o=e.resolved,r=o?Z(o,t)??o.segments[o.segments.length-1]:void 0;if(!o||!r)return;let s=ee(e),a=re(s,"text"),c=Math.max(0,t-r.start),i=Math.max(c+1,Math.min(r.end-r.start,c+2*o.canvas.fps)),d={id:a,type:"text",text:n,box:[.1,.42,.8,.12],during:{segment:r.id,from:c,to:i},style:"subtitle"};return{op:{op:"insert",path:["tracks",s.length],value:d},select:{kind:"item",id:a}}},bo=e=>Array.isArray(e)&&e.length===4?e.map((t,n)=>n<2&&typeof t=="number"?Math.round((t+.03)*1e5)/1e5:t):e,Yt=(e,t)=>{if(t.kind==="segment"){let r=re(te(e),String(t.segment.id));return{op:{op:"insert",path:["segments",t.index+1],value:{...t.segment,id:r}},select:{kind:"segment",id:r}}}if(t.kind==="cue"){let r=he(t.track,"cues")[t.cue],s=e.resolved,a=s&&T(r)?Se(s,r.during):void 0;if(!T(r)||!s||!a||!T(r.during))return;let c=yt(s,r.during,a.end,a.end+(a.end-a.start));return{op:{op:"insert",path:["tracks",t.index,"cues",t.cue+1],value:{...r,during:c}},select:{kind:"item",id:String(t.track.id)+"#"+(t.cue+1)}}}let n=re(ee(e),String(t.track.id)),o={...t.track,id:n,...Array.isArray(t.track.box)?{box:bo(t.track.box)}:{}};return{op:{op:"insert",path:["tracks",t.index+1],value:o},select:{kind:t.track.type==="audio"?"audio":"item",id:n}}},Xt=e=>e.kind==="cue"&&Array.isArray(e.track.cues)&&e.track.cues.length>1?{op:"remove",path:["tracks",e.index,"cues",e.cue]}:{op:"remove",path:go(e)},Zt=e=>e.map(t=>Math.round(t*1e5)/1e5);var Qt=(e,t)=>{if(!T(e.source))return;let n=te(e),o=n[t];if(!o)return;let r=re(n,String(o.id)),s=ee(e).map(i=>structuredClone(i)),a=i=>T(i)&&i.segment===o.id?{...i,segment:r}:i;for(let i of ee(e)){let d=Array.isArray(i.cues)?i.cues.filter(f=>T(f)&&T(f.during)&&f.during.segment===o.id):[];if(!d.length&&(!T(i.during)||i.during.segment!==o.id))continue;let l={...structuredClone(i),id:re(s,String(i.id)),...i.during?{during:a(i.during)}:{},...d.length?{cues:d.map(f=>({...f,during:a(f.during)}))}:{}};s.push(l)}let c=n.map(i=>structuredClone(i));return c.splice(t+1,0,{...structuredClone(o),id:r}),{source:{...e.source,segments:c,tracks:s},id:r}};var yo='"Noto Sans CJK SC", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif',we={font:yo,size:.045,weight:700,color:"#ffffff",align:"center",italic:!1};var vo={blur:.12,x:.04,y:.06},$t=["headline","subtitle","label","caption"],vt={headline:{...we,size:.065,weight:800,stroke:{color:"#000000",width:.12}},subtitle:{...we,size:.04,weight:700,stroke:{color:"#000000",width:.1}},label:{...we,size:.032,weight:700,color:"#111111",background:{color:"#ffffff",padding:.35,radius:.3}},caption:{...we,size:.036,weight:600,background:{color:"rgba(0, 0, 0, 0.6)",padding:.3,radius:.2}}},St=e=>$t.includes(e),So=(e,t)=>({color:e.color,blur:e.blur??t.blur,x:e.x??t.x,y:e.y??t.y}),en=e=>{if(e===void 0)return we;if(typeof e=="string"){if(!St(e))throw new Error('Unknown text style "'+e+'". Use one of: '+$t.join(", ")+".");return vt[e]}let{shadow:t,...n}=e;return{...we,...n,...t?{shadow:So(t,vo)}:{}}};var tn=(e,t)=>{if(!e?.resolved||t.op!=="set"||t.path[0]!=="tracks"||t.path[2]!=="text"||typeof t.value!="string")return t;let n=T(e.source)?e.source:{},o=Array.isArray(n.tracks)?n.tracks[Number(t.path[1])]:void 0;if(!T(o)||o.type!=="text")return t;let r=e.resolved.items.find(p=>p.id===o.id),a=document.querySelector("#page")?.contentDocument,c=a?.querySelector('[data-item="'+CSS.escape(String(o.id))+'"] > div');if(!a||!c||!r?.style)return t;let i=r.box[2]*e.resolved.canvas.width,d=r.box[3]*e.resolved.canvas.height,l=c.cloneNode(!1);l.textContent=t.value,Object.assign(l.style,{position:"fixed",left:"0",top:"0",width:i+"px",height:"auto",visibility:"hidden",transform:"none"}),a.body.append(l);let f=r.style.size*e.resolved.canvas.height,g=p=>(l.style.fontSize=p+"px",l.style.letterSpacing=(r.style.letterSpacing??0)*p+"px",l.scrollHeight<=d+.5&&l.scrollWidth<=i+.5);try{if(g(f))return t;let p=1,m=f;for(let v=0;v<16;v++){let E=(p+m)/2;g(E)?p=E:m=E}let{font:h,...b}=en(typeof o.style=="string"?o.style:void 0),y=T(o.style)?o.style:b;return{op:"set",path:["tracks",Number(t.path[1])],value:{...o,text:t.value,style:{...y,size:Math.floor(p*100)/100/e.resolved.canvas.height}}}}finally{l.remove()}};var Ae=(e,t,n)=>{let o=e?.resolved,r=t.kind==="item"?o?.items.find(c=>c.id===t.id):t.kind==="audio"?o?.audio.find(c=>c.id===t.id):t.kind==="segment"||t.kind==="slot"?o?.segments.find(c=>c.id===t.id):void 0;if(!r)return n;let s=r.end??o.frames,a="enter"in r?r.enter?.frames??0:0;return n>=r.start+a&&n<s&&t.kind!=="slot"?n:Math.min(s-1,Math.max(r.start+a,r.start+Math.floor((s-r.start)*.3)))};var nn=(e,t)=>{let n=e.resolved,o=te(e),r=n?.segments[t];if(!n||!r||o.length<2||!T(e.source))return;let s=structuredClone(e.source),a=o.filter((p,m)=>m!==t),c=r.end-r.start,i=String(a[0].id),d=p=>p<=r.start?p:p>=r.end?p-c:r.start,l=(p,m)=>({segment:i,from:d(p),to:d(m)}),f=ee(e),g=[];for(let p of f){let m=structuredClone(p);if(m.type==="caption"&&Array.isArray(m.cues)){let k=m.cues.flatMap((H,L)=>{if(!T(H))return[];let R=n.items.find(F=>F.cue?.track===m.id&&F.cue?.index===L);return!R||d(R.end)<=d(R.start)?[]:[{...H,during:l(R.start,R.end)}]});k.length&&g.push({...m,cues:k});continue}let h=m.type==="audio"?n.audio.find(k=>k.id===m.id):n.items.find(k=>k.id===m.id),b=Se(n,m.during),y=h?.start??b?.start??0,v=h?.end??b?.end??n.frames;if(d(v)<=d(y))continue;let E=m.type==="audio"||m.type==="video",M=E&&y<r.start&&v>r.end?[[y,r.start],[r.end,v]]:[[y<r.end&&y>=r.start?r.end:y,v>r.start&&v<=r.end?r.start:v]];for(let[k,H]of M){if(k===void 0||H===void 0||H<=k)continue;let L={...m,during:l(k,H)};if(g.some(R=>R.id===L.id)&&(L.id=re([...f,...g],String(L.id))),E&&k>y){let R=m.type==="video"?n.items.find(O=>O.id===m.id)?.play:void 0,F=R?(n.footage?.[R.material]?.fps??n.canvas.fps)/n.canvas.fps*R.speed:m.bed?(n.footage?.[String(m.material)]?.fps??n.canvas.fps)/n.canvas.fps:1;L.in=Number(m.in??0)+Math.round((k-y)*F)}k>y&&delete L.enter,H<v&&delete L.exit,g.push(L)}}return s.segments=a,s.tracks=g,s};var xt=(e,t,n)=>{let o=q(e,t),r=e.resolved;if(!o||!r||!T(e.source))return;let s=structuredClone(e.source);if(o.kind==="segment"){let h=r.segments[o.index];if(!h||n<=h.start||n>=h.end)return;let b=te(e).map(R=>structuredClone(R)),y=b[o.index],v=n-h.start,E=re(b,String(y.id)),M=T(y.base)?y.base:{},k={...M};M.scene&&(k.offset=Number(M.offset??0)+v/r.canvas.fps),M.material&&h.base.kind==="video"&&(k.in=h.base.play.in+Math.round(v*(r.footage?.[h.base.play.material]?.fps??r.canvas.fps)*h.base.play.speed/r.canvas.fps));let H={...y,id:E,frames:h.end-n,base:k};delete H.in;let L=R=>T(R)&&R.segment===y.id&&R.phrase===void 0&&R.to===void 0?{...R,to:h.end-h.start}:R;return s.tracks=ee(e).map(R=>({...R,...R.during?{during:L(R.during)}:{},...Array.isArray(R.cues)?{cues:R.cues.map(F=>T(F)?{...F,during:L(F.during)}:F)}:{}})),b.splice(o.index,1,{...y,frames:v},H),s.segments=b,{source:s,select:{kind:"segment",id:E}}}let a=structuredClone(o.track),c=o.kind==="cue"&&Array.isArray(a.cues)?a.cues[o.cue]:void 0,i=o.kind==="cue"?c:a;if(!T(i))return;if(!T(i.during)&&a.type==="audio"){let h=r.audio.find(b=>b.id===a.id);h&&(i.during={segment:r.segments[0]?.id,from:h.start,to:h.end??r.frames})}if(!T(i.during))return;let d=Se(r,i.during);if(!d||n<=d.start||n>=d.end)return;let l=i.during,f={...i,during:{...l,to:n-d.segment.start}},g={...i,during:{...l,from:n-d.segment.start}},p=ee(e).map(h=>structuredClone(h));if(o.kind==="cue")return a.cues.splice(o.cue,1,f,g),p[o.index]=a,s.tracks=p,{source:s,select:{kind:"item",id:String(a.id)+"#"+(o.cue+1)}};let m=re(p,String(a.id));if(g.id=m,a.type==="video"){let h=r.items.find(b=>b.id===a.id);h&&(g.in=Number(a.in??0)+Math.round((n-d.start)*Number(r.footage?.[h.play?.material??""]?.fps??r.canvas.fps)*Number(a.speed??1)/r.canvas.fps))}return a.type==="audio"&&(g.in=Number(a.in??0)+Math.round((n-d.start)*(a.bed?(r.footage?.[String(a.material)]?.fps??r.canvas.fps)/r.canvas.fps:1))),delete f.exit,delete g.enter,p.splice(o.index,1,f,g),s.tracks=p,{source:s,select:{kind:a.type==="audio"?"audio":"item",id:m}}};var Et=e=>"popost-preview-selection:"+e.project.dir,Je=e=>{try{let t=sessionStorage.getItem(Et(e));return t?JSON.parse(t):null}catch{return null}},We=e=>{e.subscribe((t,n)=>{if(!(t.pinned===n.pinned||!t.state))try{t.pinned?sessionStorage.setItem(Et(t.state),JSON.stringify(t.pinned)):sessionStorage.removeItem(Et(t.state))}catch{}})},xo=async(e,t)=>{try{return await(await fetch(e,{method:"POST",headers:{"content-type":"application/json"},...t===void 0?{}:{body:JSON.stringify(t)}})).json()}catch(n){return{ok:!1,problems:[{level:"error",at:"(request)",message:n instanceof Error?n.message:String(n),fix:""}]}}},qe=(e,t)=>{let n=p=>e.set({edit:{...e.get().edit,...p}}),o=new Set,r=Promise.resolve(!0),s=!0,a=p=>{p&&["item","slot","audio"].includes(p.kind)&&e.get().timeline&&!e.get().timeline?.layers&&e.set({timeline:{layers:!0,snapping:e.get().timeline?.snapping??!0}}),t.pin(p)},c=(p,m)=>{if(!p.ok){let y=p.problems.find(v=>v.level==="error")??p.problems[0];return n({status:y?{kind:"refused",problem:y}:null,problems:p.problems}),!1}let h=p.state;if(h.generation<(e.get().state?.generation??-1))return!0;if(e.set({state:h,frame:pe(e.get().frame,W(h)),edit:{...e.get().edit,status:{kind:"done",op:p.op,step:p.step,label:p.label},problems:[]}}),m!==void 0)a(m);else{let y=e.get().pinned;y&&y.kind!=="slot"&&!q(h,y)&&a(null)}let b=e.get().pinned;return b&&b.kind!=="slot"&&t.seek(Ae(h,b,e.get().frame)),!0},i=()=>{let p=e.get();return p.state?q(p.state,p.pinned):void 0},d=(p,m,h)=>{n({saving:!0});let b=r.then(()=>xo(p,typeof m=="function"?m():m)).then(y=>(s=c(y,h),s));return r=b.catch(()=>!1),o.add(b),b.finally(()=>{o.delete(b),o.size||n({saving:!1})}),b},l=(p,m)=>d("/api/edit",()=>tn(e.get().state,p),m),f=async()=>{for(;o.size;)await Promise.all([...o])},g=async p=>{if(document.activeElement instanceof HTMLElement&&document.activeElement.blur(),await f(),!s)return;let m=e.get().state,h=i();m&&h&&await p(m,h)};return{send:l,reveal:(p,m)=>{t.pause(),t.seek(m??Ae(e.get().state,p,e.get().frame)),a(p)},flush:async()=>{for(document.activeElement instanceof HTMLElement&&document.activeElement.blur();o.size;)await Promise.all([...o]);return s},canSplit:()=>{let p=e.get();return!!(p.state&&xt(p.state,p.pinned,p.frame))},split:async()=>{let p=e.get(),m=p.state?xt(p.state,p.pinned,p.frame):void 0;m&&await d("/api/source",{source:m.source,base:p.state?.source})&&a(m.select)},replace:(p,m)=>d("/api/source",{source:p,base:m}),undo:async()=>{await f(),await d("/api/undo")},redo:async()=>{await f(),await d("/api/redo")},remove:()=>g(async(p,m)=>{if(m.kind==="segment"){let h=nn(p,m.index);h&&await d("/api/source",{source:h,base:p.source},null);return}await l(Xt(m),null)}),duplicate:()=>g(async(p,m)=>{if(m.kind==="segment"){let b=Qt(p,m.index);b&&await d("/api/source",{source:b.source,base:p.source},{kind:"segment",id:b.id});return}let h=Yt(p,m);h&&await l(h.op,h.select)}),addText:async()=>{let p=e.get(),m=p.state?Gt(p.state,p.frame,S(p.lang,"newText")):void 0;m&&await l(m.op,m.select)},render:async()=>{let m=await(await fetch("/api/render",{method:"POST"}).catch(()=>{}))?.json().catch(()=>{});m?.render?n({render:m.render}):m?.problems?.[0]&&n({status:{kind:"refused",problem:m.problems[0]}})},select:a,note:p=>n({status:{kind:"note",key:p}}),target:i,setRender:p=>n({render:p}),togglePlayRender:()=>n({playRender:!e.get().edit.playRender})}};var Eo={frame:null,playhead:"snapPlayhead",segment:"snapSegment",reference:"snapReference"},wo=(e,t,n,o)=>{let r=Pe(e.start+t,n,o),s=Pe(e.end+t,n,o),a=r.kind==="frame"?1/0:Math.abs(r.frame-(e.start+t)),c=s.kind==="frame"?1/0:Math.abs(s.frame-(e.end+t)),i=a<=c&&a!==1/0?r.frame-e.start:c!==1/0?s.frame-e.end:Math.round(t),d=a<=c&&a!==1/0?r:c!==1/0?s:{frame:e.start+i,kind:"frame"};return{start:e.start+i,end:e.end+i,snap:d}},ko=(e,t,n,o)=>{if(e.mode==="move")return wo(e,t,n,o);if(e.mode==="start"){let s=Pe(e.start+t,n,o);return{start:Math.min(s.frame,e.end-1),end:e.end,snap:s}}let r=Pe(e.end+t,n,o);return{start:e.start,end:Math.max(r.frame,e.start+1),snap:r}},Mo=(e,t,n,o)=>{let r=Eo[o.snap.kind],s=r?" \\xB7 "+S(e,"snapped")+" "+S(e,r):"";if(n.mode==="border"){let a=W(t),c=o.end-n.end;return(t.resolved?.segments.find(d=>d.end===n.end)?.id??"")+": "+(n.end-n.start)+" \\u2192 "+(o.end-n.start)+" "+S(e,"framesWord")+" \\xB7 "+S(e,"videoLength")+" "+a+" \\u2192 "+(a+c)+" ("+(c>=0?"+":"")+c+")"+s}return S(e,"onFrames")+" "+o.start+".."+(o.end-1)+s},To=(e,t,n)=>{let o=t.closest(".lane-track"),r=e.resolved;if(!o||!r)return;let s=t.closest(".seg-grip")?.dataset.border;if(s!==void 0){let m=r.segments[Number(s)];return m?{mode:"border",x0:n,track:o,start:m.start,end:m.end,border:Number(s),moved:!1}:void 0}let a=t.closest("[data-sel]")?.dataset.sel,c=a?JSON.parse(a):void 0;if(c?.kind!=="item"&&c?.kind!=="audio")return;let i=q(e,c),d=i?ht(i):void 0,l=c.kind==="audio"?r.audio.find(m=>m.id===c.id):void 0,f=(i&&d?on(i):void 0)??(l?{segment:r.segments[0]?.id,from:l.start,to:l.end??r.frames}:void 0);if(!i||!f)return;let g=Se(r,f);if(!g)return{mode:"move",x0:n,track:o,start:0,end:0,target:i,phrase:!0,moved:!1};let p=t.closest(".grip")?.dataset.grip;return{mode:p==="start"||p==="end"?p:"move",x0:n,track:o,start:g.start,end:g.end,target:i,span:f,moved:!1}},on=e=>{let t=e.kind==="cue"?e.track.cues[e.cue]:e.kind==="track"?e.track:void 0,n=t&&typeof t=="object"?t.during:void 0;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0},Lo=(e,t,n,o,r)=>{let s=o.state;if(!s||n.phrase)return;let a=W(s);if(!n.track.isConnected){let g=n.track.closest(".lane")?.id,p=g?e.querySelector("#"+CSS.escape(g)+" .lane-track"):null;if(!p)return;n.track=p}let c=n.track.getBoundingClientRect().width/Math.max(1,a);if(!Number.isFinite(c)||c<=0)return;let i=o.timeline?.snapping===!1?[]:qt(s,o.frame,n.mode!=="border"),d=ko(n.mode==="border"?{mode:"end",start:n.start,end:n.end}:n,(r-n.x0)/c,i,c);if(n.mode!=="border")if(n.mode==="move"){let g=Math.min(a,n.end-n.start);d.start=Math.max(0,Math.min(a-g,d.start)),d.end=d.start+g}else d.start=Math.max(0,d.start),d.end=Math.min(a,d.end);n.result=d,n.mode!=="border"&&n.track.append(Le(t.ghost,d.start,d.end,a));let l=e.querySelector(".playhead-layer");if(!l)return;let f=d.snap.kind!=="frame"?d.snap.frame:n.mode==="end"||n.mode==="border"?d.end:d.start;l.append(Q(t.guide,f,a)),t.guide.classList.toggle("snapped",d.snap.kind!=="frame"),t.label.textContent=Mo(o.lang,s,n,d),l.append(Q(t.label,Math.min(f,a*.6),a))},Ro=(e,t)=>{let n=t.resolved;if(!n||!e.result)return;if(e.mode==="border")return e.border!==void 0&&e.result.end!==e.end?{op:"set",path:["segments",e.border,"frames"],value:e.result.end-e.start}:void 0;let o=e.target?ht(e.target)??(e.target.kind==="track"&&e.target.track.type==="audio"?["tracks",e.target.index,"during"]:void 0):void 0,r=e.span??(e.target?on(e.target):void 0);if(!(!o||!r||e.result.start===e.start&&e.result.end===e.end))return{op:"set",path:o,value:yt(n,r,e.result.start,e.result.end)}},Ge=(e,t,n)=>{let o={ghost:u("div",{class:"drag-ghost",id:"drag-ghost"}),guide:u("div",{class:"snap-guide",id:"snap-guide"}),label:u("div",{class:"lane-readout",id:"lane-readout"})},r,s=!1,a;e.addEventListener("pointerdown",i=>{let d=t.get().state;if(i.button!==0||!d?.edit||t.get().edit.saving)return;document.activeElement instanceof HTMLElement&&document.activeElement!==document.body&&document.activeElement.blur();let l=i.target.closest("[data-sel]")?.dataset.sel;l&&n.select(JSON.parse(l));let f=l?JSON.parse(l):void 0;if(f?.kind==="segment"&&!i.target.closest(".seg-grip")){let g=d.resolved?.segments.findIndex(m=>m.id===f.id)??-1,p=i.target.closest(".lane-track");if(g>=0&&p){a={index:g,to:g,x:i.clientX,moved:!1,track:p},e.setPointerCapture(i.pointerId),i.preventDefault();return}}r=To(d,i.target,i.clientX),r&&(e.setPointerCapture(i.pointerId),i.preventDefault())}),e.addEventListener("pointermove",i=>{if(a){if(!a.moved&&Math.abs(i.clientX-a.x)<4)return;a.moved=!0;let d=t.get().state?.resolved;if(!d)return;let l=a.track.getBoundingClientRect(),f=(i.clientX-l.left)/l.width*d.frames;a.to=Math.max(0,d.segments.findIndex(m=>f<m.end)),f>=d.frames&&(a.to=d.segments.length-1);let g=d.segments[a.to]?.start??0,p=e.querySelector(".playhead-layer");o.label.textContent=(t.get().lang==="zh"?"\\u79FB\\u52A8\\u955C\\u5934 ":"Move shot ")+(a.index+1)+" \\u2192 "+(a.to+1),p?.append(Q(o.guide,g,d.frames),Q(o.label,Math.min(g,d.frames*.6),d.frames));return}!r||!r.moved&&Math.abs(i.clientX-r.x0)<3||(r.moved=!0,Lo(e,o,r,t.get(),i.clientX))});let c=i=>{if(a){let g=a;a=void 0,[o.ghost,o.guide,o.label].forEach(p=>p.remove()),g.moved&&(s=!0,setTimeout(()=>{s=!1},0),i.type!=="pointercancel"&&g.index!==g.to&&n.send({op:"move",path:["segments",g.index],to:g.to}));return}let d=r;if(r=void 0,[o.ghost,o.guide,o.label].forEach(g=>g.remove()),!d?.moved)return;s=!0,setTimeout(()=>{s=!1},0);let l=t.get().state;if(d.phrase)return n.note("phraseSpan");let f=l?Ro(d,l):void 0;f&&i.type!=="pointercancel"&&n.send(f)};e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c),e.addEventListener("click",i=>{s&&(s=!1,i.stopImmediatePropagation())},!0)};var Po=e=>e?.anyOf?.find(t=>t.type==="object")??e,j=(e,...t)=>t.reduce((n,o)=>Po(n)?.properties?.[o],e),X=e=>(e?.enum??e?.anyOf?.find(t=>t.enum)?.enum??[]).map(t=>String(t));var Ye=e=>e===void 0||Math.abs(e)>=9e15?void 0:e,xe=e=>({...Ye(e?.minimum??e?.exclusiveMinimum)===void 0?{}:{min:Ye(e?.minimum??e?.exclusiveMinimum)},...Ye(e?.maximum??e?.exclusiveMaximum)===void 0?{}:{max:Ye(e?.maximum??e?.exclusiveMaximum)},integer:e?.type==="integer"}),Xe=async()=>{let e=await fetch("/api/schema",{cache:"no-store"}).catch(()=>{});return e?.ok?await e.json():null};var Ao={noReference:"No reference video is available for this project.",shots:"Shots",media:"Media",script:"Script",elements:"Elements",code:"Code",checks:"Review",versions:"Versions",export:"Export",compare:"Compare",layout:"Layout",theme:"Theme",saved:"Saved locally",readOnly:"Read only",live:"Connected",offline:"Disconnected",preview:"Preview",current:"Current",add:"Add",upload:"Import",search:"Search",scene:"Animated scene",video:"Video",image:"Image",color:"Background",duration:"Duration",keepRhythm:"Keep reference rhythm",content:"Content",properties:"Properties",viewAll:"Fit timeline",assist:"Analysis",zoom:"Zoom",audio:"Project audio",onlyPreview:"Preview controls do not change exported audio",sourceTitle:"Draft JSON",autosave:"Valid JSON saves automatically",format:"Format JSON",download:"Download JSON",invalid:"Invalid JSON \\u2014 draft kept",saving:"Saving\\u2026",conflict:"The draft changed elsewhere. Reload before saving.",reload:"Reload JSON",choose:"Select an item to edit",text:"Text",audioTrack:"Audio",subtitles:"Subtitles",voice:"Voiceover",music:"Music / effects",addText:"Add text",duplicate:"Duplicate",remove:"Delete",undo:"Undo",redo:"Redo",time:"Time",wordBound:"Follows speech",original:"Original",resolution:"Resolution",dynamicRange:"Dynamic range",hdrUnavailable:"HDR is unavailable: this HTML renderer outputs SDR.",fps:"Frame rate",match:"Match timeline",bitrate:"Video bitrate",recommended:"Recommended",filename:"File name",includeAudio:"Include project audio",range:"Range",full:"Full video",start:"Start frame",end:"End frame (exclusive)",paid:"Paid benefit",paidInfo:"This feature is available with a paid plan.",unlock:"Unlock",refreshPlan:"Refresh plan",preparing:"Preparing",rendering:"Rendering",renderDone:"Export ready",stale:"The draft changed after this export",play:"Play",downloadVideo:"Download video",exportSnapshot:"Export uses the JSON snapshot at start. You can continue editing.",general:"General",effects:"Timing and motion",sourceFile:"Source file",missing:"Missing",replace:"Replace",apply:"Apply",applyShot:"Use in selected shot",addOverlay:"Add overlay",slot:"Scene field",noSlots:"This scene exposes no editable slots. Use JSON to change its source or replace the scene.",currentShot:"Current shot",selected:"Selected",noMedia:"No project media",importHint:"Images, video or audio up to 12 MB",scriptHint:"Editing captions does not regenerate voiceover.",pendingVoice:"Caption changed; review voiceover",all:"All",notes:"Notes",comment:"Add timed note",noteHint:"Describe the change at this frame\\u2026",resolved:"Resolved",resolve:"Resolve",reopen:"Reopen",copyNote:"Copy change request",noNotes:"No review notes yet",noProblems:"No structural problems found",unmeasured:"No comparison measurements for this version",saveVersion:"Save version",restore:"Restore",versionName:"Version name",noVersions:"No saved versions",defaultLayout:"Default layout",focusedPreview:"Focus preview",codeHint:"Changes update the same draft after validation. Invalid JSON never overwrites it.",sourceChanged:"Draft saved",quality:"Quality",loading:"Loading\\u2026",sameAsReference:"Reference / replica",toggleAnalysis:"Show analysis lanes",sceneFields:"Scene content",position:"Position",trackGain:"Gain (dB)",chooseMaterial:"Choose a material, then select where to use it.",unsupported:"Unavailable for this selection",refresh:"Refresh",inspect:"Inspect",seconds:"s",waveform:"Waveform",recheck:"Reload checks",sourceExport:"The source JSON is included separately; it is not an MP4.",goShot:"Go to shot",moveUp:"Move earlier",moveDown:"Move later",narrationUnavailable:"Voice generation is managed by the Agent. Copy the revised script to request updated narration.",copyScript:"Copy revised script",applyCaption:"Save caption",error:"Could not complete the operation",fileRange:"Whole timeline",frame:"Frame",newVersion:"Studio version",noSelection:"Select a shot, caption or overlay to edit.",segment:"Shot",previewQuality:"Fit preview",allChanges:"All changes saved",currentExport:"Export current draft",jsonDownload:"Download the saved video.json",imageSlot:"Replace image slot",selectedSlot:"Selected scene field",sceneOffset:"Scene element offset",fontSize:"Font size",textColor:"Text colour",versionSnapshot:"Saved versions preserve the draft JSON; assets are reused.",bitrateUnit:"Mbps",reviewOnly:"Review notes are local; sending to an Agent requires copying the request."},Co={noReference:"\\u6B64\\u9879\\u76EE\\u6CA1\\u6709\\u53C2\\u8003\\u89C6\\u9891\\u3002",shots:"\\u955C\\u5934",media:"\\u7D20\\u6750",script:"\\u6587\\u7A3F",elements:"\\u5143\\u7D20",code:"\\u4EE3\\u7801",checks:"\\u68C0\\u67E5",versions:"\\u7248\\u672C",export:"\\u5BFC\\u51FA",compare:"\\u5BF9\\u7167",layout:"\\u5E03\\u5C40",theme:"\\u4E3B\\u9898",saved:"\\u5DF2\\u4FDD\\u5B58\\u5230\\u672C\\u673A",readOnly:"\\u53EA\\u8BFB",live:"\\u5DF2\\u8FDE\\u63A5",offline:"\\u8FDE\\u63A5\\u5DF2\\u65AD\\u5F00",preview:"\\u6210\\u7247\\u9884\\u89C8",current:"\\u5F53\\u524D",add:"\\u6DFB\\u52A0",upload:"\\u5BFC\\u5165\\u7D20\\u6750",search:"\\u641C\\u7D22",scene:"\\u52A8\\u6001\\u573A\\u666F",video:"\\u89C6\\u9891",image:"\\u56FE\\u7247",color:"\\u80CC\\u666F",duration:"\\u65F6\\u957F",keepRhythm:"\\u4FDD\\u6301\\u53C2\\u8003\\u8282\\u594F",content:"\\u5185\\u5BB9",properties:"\\u5C5E\\u6027",viewAll:"\\u9002\\u914D\\u65F6\\u95F4\\u7EBF",assist:"\\u8F85\\u52A9\\u4FE1\\u606F",zoom:"\\u7F29\\u653E",audio:"\\u9879\\u76EE\\u58F0\\u97F3",onlyPreview:"\\u8BD5\\u542C\\u63A7\\u5236\\u4E0D\\u4F1A\\u6539\\u53D8\\u5BFC\\u51FA\\u58F0\\u97F3",sourceTitle:"\\u8349\\u7A3F JSON",autosave:"\\u6709\\u6548 JSON \\u5C06\\u81EA\\u52A8\\u4FDD\\u5B58",format:"\\u683C\\u5F0F\\u5316",download:"\\u4E0B\\u8F7D JSON",invalid:"JSON \\u65E0\\u6548\\uFF0C\\u5DF2\\u4FDD\\u7559\\u8F93\\u5165",saving:"\\u4FDD\\u5B58\\u4E2D\\u2026",conflict:"\\u8349\\u7A3F\\u5DF2\\u5728\\u5176\\u4ED6\\u4F4D\\u7F6E\\u4FEE\\u6539\\uFF0C\\u8BF7\\u5148\\u91CD\\u65B0\\u8F7D\\u5165\\u3002",reload:"\\u91CD\\u65B0\\u8F7D\\u5165 JSON",choose:"\\u9009\\u62E9\\u5BF9\\u8C61\\u540E\\u7F16\\u8F91",text:"\\u6587\\u5B57",audioTrack:"\\u97F3\\u9891",subtitles:"\\u5B57\\u5E55",voice:"\\u914D\\u97F3",music:"\\u97F3\\u4E50 / \\u97F3\\u6548",addText:"\\u6DFB\\u52A0\\u6587\\u5B57",duplicate:"\\u590D\\u5236",remove:"\\u5220\\u9664",undo:"\\u64A4\\u9500",redo:"\\u91CD\\u505A",time:"\\u65F6\\u95F4",wordBound:"\\u8DDF\\u968F\\u914D\\u97F3",original:"\\u539F\\u59CB",resolution:"\\u5206\\u8FA8\\u7387",dynamicRange:"\\u52A8\\u6001\\u8303\\u56F4",hdrUnavailable:"\\u5F53\\u524D HTML \\u6E32\\u67D3\\u5668\\u8F93\\u51FA SDR\\uFF0C\\u6682\\u4E0D\\u652F\\u6301 HDR\\u3002",fps:"\\u5E27\\u7387",match:"\\u5339\\u914D\\u65F6\\u95F4\\u7EBF",bitrate:"\\u89C6\\u9891\\u7801\\u7387",recommended:"\\u63A8\\u8350",filename:"\\u6587\\u4EF6\\u540D",includeAudio:"\\u5305\\u542B\\u9879\\u76EE\\u58F0\\u97F3",range:"\\u5BFC\\u51FA\\u8303\\u56F4",full:"\\u5B8C\\u6574\\u89C6\\u9891",start:"\\u5F00\\u59CB\\u5E27",end:"\\u7ED3\\u675F\\u5E27\\uFF08\\u4E0D\\u542B\\uFF09",paid:"\\u4ED8\\u8D39\\u6743\\u76CA",paidInfo:"\\u8BE5\\u529F\\u80FD\\u4E3A\\u4ED8\\u8D39\\u6743\\u76CA\\uFF0C\\u4ED8\\u8D39\\u540E\\u53EF\\u4F7F\\u7528\\u3002",unlock:"\\u524D\\u5F80\\u89E3\\u9501",refreshPlan:"\\u5237\\u65B0\\u6743\\u76CA",preparing:"\\u51C6\\u5907\\u4E2D",rendering:"\\u6B63\\u5728\\u5BFC\\u51FA",renderDone:"\\u5BFC\\u51FA\\u5B8C\\u6210",stale:"\\u6B64\\u540E\\u8349\\u7A3F\\u5DF2\\u4FEE\\u6539\\uFF0C\\u9700\\u8981\\u91CD\\u65B0\\u5BFC\\u51FA",play:"\\u64AD\\u653E",downloadVideo:"\\u4E0B\\u8F7D\\u89C6\\u9891",exportSnapshot:"\\u5BFC\\u51FA\\u4F7F\\u7528\\u5F00\\u59CB\\u65F6\\u7684 JSON \\u5FEB\\u7167\\uFF0C\\u4F60\\u53EF\\u4EE5\\u7EE7\\u7EED\\u7F16\\u8F91\\u3002",general:"\\u5E38\\u89C4",effects:"\\u65F6\\u95F4\\u4E0E\\u52A8\\u6548",sourceFile:"\\u6E90\\u6587\\u4EF6",missing:"\\u7F3A\\u5931",replace:"\\u66FF\\u6362",apply:"\\u5E94\\u7528",applyShot:"\\u66FF\\u6362\\u5F53\\u524D\\u955C\\u5934\\u7D20\\u6750",addOverlay:"\\u6DFB\\u52A0\\u4E3A\\u53E0\\u52A0\\u5143\\u7D20",slot:"\\u573A\\u666F\\u5B57\\u6BB5",noSlots:"\\u8BE5\\u573A\\u666F\\u672A\\u516C\\u5F00\\u53EF\\u7F16\\u8F91\\u5B57\\u6BB5\\uFF0C\\u53EF\\u901A\\u8FC7\\u4EE3\\u7801\\u66F4\\u6362\\u573A\\u666F\\u6216\\u4EA4\\u7ED9 Agent \\u4FEE\\u6539\\u3002",currentShot:"\\u5F53\\u524D\\u955C\\u5934",selected:"\\u5DF2\\u9009\\u4E2D",noMedia:"\\u9879\\u76EE\\u6682\\u65E0\\u7D20\\u6750",importHint:"\\u652F\\u6301\\u56FE\\u7247\\u3001\\u89C6\\u9891\\u548C\\u97F3\\u9891\\uFF0C\\u5355\\u6587\\u4EF6\\u4E0D\\u8D85\\u8FC7 12 MB",scriptHint:"\\u4FEE\\u6539\\u5B57\\u5E55\\u4E0D\\u4F1A\\u81EA\\u52A8\\u91CD\\u505A\\u914D\\u97F3\\u3002",pendingVoice:"\\u5B57\\u5E55\\u5DF2\\u4FEE\\u6539\\uFF0C\\u8BF7\\u6838\\u5BF9\\u914D\\u97F3",all:"\\u5168\\u90E8",notes:"\\u4FEE\\u6539\\u610F\\u89C1",comment:"\\u6DFB\\u52A0\\u65F6\\u95F4\\u70B9\\u610F\\u89C1",noteHint:"\\u63CF\\u8FF0\\u5F53\\u524D\\u753B\\u9762\\u9700\\u8981\\u600E\\u6837\\u4FEE\\u6539\\u2026",resolved:"\\u5DF2\\u5904\\u7406",resolve:"\\u6807\\u8BB0\\u5DF2\\u5904\\u7406",reopen:"\\u91CD\\u65B0\\u6253\\u5F00",copyNote:"\\u590D\\u5236\\u7ED9 Agent \\u7684\\u4FEE\\u6539\\u8BF4\\u660E",noNotes:"\\u8FD8\\u6CA1\\u6709\\u4FEE\\u6539\\u610F\\u89C1",noProblems:"\\u672A\\u53D1\\u73B0\\u7ED3\\u6784\\u95EE\\u9898",unmeasured:"\\u5F53\\u524D\\u7248\\u672C\\u6682\\u65E0\\u5BF9\\u6BD4\\u6D4B\\u91CF\\u7ED3\\u679C",saveVersion:"\\u4FDD\\u5B58\\u4E00\\u4E2A\\u7248\\u672C",restore:"\\u6062\\u590D",versionName:"\\u7248\\u672C\\u540D\\u79F0",noVersions:"\\u8FD8\\u6CA1\\u6709\\u4FDD\\u5B58\\u7684\\u7248\\u672C",defaultLayout:"\\u9ED8\\u8BA4\\u5E03\\u5C40",focusedPreview:"\\u4E13\\u6CE8\\u9884\\u89C8",codeHint:"\\u7F16\\u8F91\\u540E\\u81EA\\u52A8\\u6821\\u9A8C\\u5E76\\u66F4\\u65B0\\u540C\\u4E00\\u4EFD\\u8349\\u7A3F\\uFF1B\\u65E0\\u6548 JSON \\u4E0D\\u4F1A\\u8986\\u76D6\\u539F\\u6587\\u4EF6\\u3002",sourceChanged:"\\u8349\\u7A3F\\u5DF2\\u4FDD\\u5B58",quality:"\\u753B\\u8D28",loading:"\\u52A0\\u8F7D\\u4E2D\\u2026",sameAsReference:"\\u53C2\\u8003 / \\u6210\\u7247",toggleAnalysis:"\\u663E\\u793A\\u5206\\u6790\\u8F68\\u9053",sceneFields:"\\u573A\\u666F\\u5185\\u5BB9",position:"\\u4F4D\\u7F6E",trackGain:"\\u589E\\u76CA\\uFF08dB\\uFF09",chooseMaterial:"\\u9009\\u62E9\\u7D20\\u6750\\u540E\\uFF0C\\u6307\\u5B9A\\u66FF\\u6362\\u955C\\u5934\\u6216\\u6DFB\\u52A0\\u53E0\\u52A0\\u5143\\u7D20\\u3002",unsupported:"\\u5F53\\u524D\\u9009\\u62E9\\u4E0D\\u652F\\u6301\\u6B64\\u64CD\\u4F5C",refresh:"\\u5237\\u65B0",inspect:"\\u67E5\\u770B",seconds:"\\u79D2",waveform:"\\u6CE2\\u5F62",recheck:"\\u5237\\u65B0\\u68C0\\u67E5",sourceExport:"JSON \\u5355\\u72EC\\u4E0B\\u8F7D\\uFF0C\\u89C6\\u9891\\u901A\\u8FC7\\u5BFC\\u51FA\\u9762\\u677F\\u751F\\u6210\\u3002",goShot:"\\u5B9A\\u4F4D\\u955C\\u5934",moveUp:"\\u5411\\u524D\\u79FB\\u52A8",moveDown:"\\u5411\\u540E\\u79FB\\u52A8",narrationUnavailable:"\\u914D\\u97F3\\u751F\\u6210\\u7531 Agent \\u5904\\u7406\\uFF0C\\u590D\\u5236\\u4FEE\\u6539\\u6587\\u7A3F\\u540E\\u53EF\\u8BF7\\u6C42\\u66F4\\u65B0\\u58F0\\u97F3\\u3002",copyScript:"\\u590D\\u5236\\u4FEE\\u6539\\u540E\\u7684\\u6587\\u7A3F",applyCaption:"\\u4FDD\\u5B58\\u5B57\\u5E55",error:"\\u64CD\\u4F5C\\u672A\\u5B8C\\u6210",fileRange:"\\u6574\\u6761\\u65F6\\u95F4\\u7EBF",frame:"\\u5E27",newVersion:"Studio \\u7248\\u672C",noSelection:"\\u9009\\u62E9\\u955C\\u5934\\u3001\\u5B57\\u5E55\\u6216\\u53E0\\u52A0\\u5143\\u7D20\\u5373\\u53EF\\u7F16\\u8F91\\u3002",segment:"\\u955C\\u5934",previewQuality:"\\u9002\\u914D\\u9884\\u89C8",allChanges:"\\u6240\\u6709\\u66F4\\u6539\\u5DF2\\u4FDD\\u5B58",currentExport:"\\u5BFC\\u51FA\\u5F53\\u524D\\u8349\\u7A3F",jsonDownload:"\\u4E0B\\u8F7D\\u5DF2\\u4FDD\\u5B58\\u7684 video.json",imageSlot:"\\u66FF\\u6362\\u56FE\\u7247\\u69FD",selectedSlot:"\\u5F53\\u524D\\u573A\\u666F\\u5B57\\u6BB5",sceneOffset:"\\u573A\\u666F\\u5143\\u7D20\\u504F\\u79FB",fontSize:"\\u5B57\\u53F7",textColor:"\\u6587\\u5B57\\u989C\\u8272",versionSnapshot:"\\u7248\\u672C\\u4FDD\\u5B58\\u8349\\u7A3F JSON\\uFF0C\\u5E76\\u7EE7\\u7EED\\u5F15\\u7528\\u539F\\u7D20\\u6750\\u3002",bitrateUnit:"Mbps",reviewOnly:"\\u610F\\u89C1\\u4FDD\\u5B58\\u5728\\u672C\\u673A\\uFF1B\\u590D\\u5236\\u540E\\u53EF\\u4EA4\\u7ED9 Agent \\u7EE7\\u7EED\\u4FEE\\u6539\\u3002"},x=(e,t)=>(e.get().lang==="zh"?Co:Ao)[t];var C=(e,t,n="")=>u("button",{class:"studio-btn "+n,text:e,attrs:{type:"button"},on:{click:t}}),ne=(e,t,n)=>u("button",{class:"studio-btn studio-icon-btn",attrs:{type:"button",title:e,"aria-label":e},on:{click:n}},[Y(t)]),U=(e,t)=>u("div",{class:"studio-heading"},[u("h2",{text:e}),...t?[u("small",{text:t})]:[]]),A=(e,t="")=>u("p",{class:"studio-note "+t,text:e}),Ce=e=>"/project/"+e.replace(/^\\.\\//,"").split("/").map(encodeURIComponent).join("/"),rn=(e,t)=>{let n=URL.createObjectURL(new Blob([e],{type:"application/json"}));u("a",{attrs:{href:n,download:t}}).click(),setTimeout(()=>URL.revokeObjectURL(n),1e3)},ce=(e,t)=>{let n=document.getElementById("studio-message");n?(n.textContent=t,n.classList.add("visible"),setTimeout(()=>n.classList.remove("visible"),6e3)):e.set({pageError:t})},J=async(e,t)=>{let n=await fetch(e,{...t===void 0?{}:{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)},cache:"no-store"}),o=await n.json();if(!n.ok||o.ok===!1)throw new Error(o.problems?.[0]?.message??"Request failed: "+n.status);return o},ke=async(e,t,n)=>{try{let o=await J(t,n);e.set({state:o.state})}catch(o){ce(e,o instanceof Error?o.message:x(e,"error"))}},G=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},$=e=>Array.isArray(e)?e.map(G):[],Oe=(e,t,n)=>{let o=u("input",{attrs:{type:"text","aria-label":t},class:"studio-input"});return o.value=e,n&&o.addEventListener("change",()=>n(o.value)),o},wt=(e,t,n,o)=>{let r=u("select",{class:"studio-input",attrs:{"aria-label":n}},e.map(([s,a])=>u("option",{text:a,attrs:{value:s}})));return r.value=t,r.addEventListener("change",()=>o(r.value)),r},Me=(e,t)=>u("label",{class:"studio-field"},[u("span",{text:e}),t]),sn=(e,t)=>u("img",{class:"studio-thumb",attrs:{src:"/api/thumbnail?frame="+Math.floor(e)+"&g="+t,loading:"lazy",alt:""}}),Ze=(e,t)=>{let n=Math.floor(e/t);return[Math.floor(n/60),n%60,e%Math.round(t)].map(o=>Math.floor(o).toString().padStart(2,"0")).join(":")};var be=(e,t,n=t.get().frame)=>{let o=t.get(),r=o.state?.resolved;if(!r)return[];let s=Z(r,n);if(!s)return[];let a=e.contentDocument;if(!a)return[];let c=[];for(let i of Array.from(a.querySelectorAll("iframe"))){let d=i.contentDocument,l=i.contentWindow;if(!d||!l||i.parentElement?.dataset.segment!==s.id)continue;let f=i.getBoundingClientRect();if(!(!f.width||!f.height)&&l.getComputedStyle(i).visibility!=="hidden")for(let g of Array.from(d.querySelectorAll("[data-slot]"))){let p=!0,m=1;for(let y=g;y;y=y.parentElement){let v=l.getComputedStyle(y);m*=Number(v.opacity),(v.display==="none"||v.visibility==="hidden")&&(p=!1)}let h=g.getBoundingClientRect();if(!p||m<.1||!h.width||!h.height||h.right<=0||h.bottom<=0||h.left>=i.clientWidth||h.top>=i.clientHeight)continue;let b=g.dataset.slot;b&&c.push({selection:{kind:"slot",id:s.id,name:b},box:[(f.left+h.left*f.width/(i.clientWidth||r.canvas.width))/r.canvas.width,(f.top+h.top*f.height/(i.clientHeight||r.canvas.height))/r.canvas.height,h.width/r.canvas.width,h.height/r.canvas.height],value:g.tagName==="IMG"?g.getAttribute("src")??"":g.textContent??"",image:g.tagName==="IMG"})}}return c},an=new WeakMap,He=(e,t,n)=>{let o=t.get(),r=o.state?.resolved?.segments.find(f=>f.id===n),s=e?.contentWindow?.__popostVideo;if(!e||!r||!s||document.body.dataset.ready!=="1"||new URL(e.src).searchParams.get("g")!==String(o.state?.generation)||r.base.kind!=="scene")return;let a=e.contentDocument,c=a?.querySelector('[data-segment="'+CSS.escape(n)+'"] > iframe')?.contentDocument;if(!a||!c||c.URL==="about:blank"||c.readyState!=="complete")return;let i=an.get(e);(!i||i.generation!==o.state.generation||i.page!==a)&&(i={generation:o.state.generation,page:a,segments:new Map},an.set(e,i));let d=i.segments.get(n);if(d?.scene===c)return d.frames;let l=new Map;try{for(let f=0;f<=32;f++){let g=Math.min(r.end-1,r.start+Math.floor((r.end-r.start)*f/33));s.applyFrame(g);for(let p of be(e,t,g))l.has(p.selection.name)||l.set(p.selection.name,g)}}finally{s.applyFrame(o.frame)}return i.segments.set(n,{scene:c,frames:l}),l},Qe=(e,t,n)=>e&&be(e,t).some(o=>o.selection.id===n.id&&o.selection.name===n.name)?t.get().frame:He(e,t,n.id)?.get(n.name),dn=(e,t)=>{let n=e.get(),o=n.pinned,r=u("div",{class:"form",id:"slot-inspector"});if(o?.kind!=="slot")return r;let s=n.lang==="zh",a=G(n.state?.source),c=$(a.segments).findIndex(i=>i.id===o.id);return r.append(u("div",{class:"sel-title",text:s?"\\u573A\\u666F\\u5143\\u7D20":"Scene element"})),J("/api/studio").then(i=>{if(!r.isConnected)return;let d=i.slots.find(g=>g.segment===o.id&&g.name===o.name);if(!d)return;let l=d.kind==="image"?Oe(d.value,s?"\\u56FE\\u7247\\u5730\\u5740":"Image path"):u("textarea",{class:"studio-input",attrs:{rows:"5","aria-label":s?"\\u6587\\u5B57\\u5185\\u5BB9":"Text content"}});l.value=d.value;let f=g=>{let p=G($(G(e.get().state?.source).segments)[c]?.base);t.send({op:"set",path:["segments",c,"base","slots"],value:{...G(p.slots),[d.name]:g}})};if(l.addEventListener("change",()=>f(l.value)),l.addEventListener("keydown",g=>{let p=g;(p.ctrlKey||p.metaKey)&&p.key==="Enter"&&l.blur()}),d.kind==="image"){let g=G($(a.segments)[c]?.base),p=String(g.scene??""),m=new URL(d.value,location.origin+"/project/"+p);m.origin===location.origin&&m.pathname.startsWith("/project/")&&r.append(u("img",{class:"studio-slot-preview",attrs:{src:m.href,alt:s?"\\u5F53\\u524D\\u56FE\\u7247":"Current image"}}));let h=$(a.materials).filter(b=>b.kind==="image");if(h.length){let b=u("select",{class:"studio-input",attrs:{"aria-label":s?"\\u66FF\\u6362\\u56FE\\u7247":"Replace image"}},[u("option",{text:s?"\\u9009\\u62E9\\u7D20\\u6750\\u4E2D\\u7684\\u56FE\\u7247":"Choose an image",attrs:{value:""}}),...h.map((y,v)=>u("option",{text:String(y.note??y.file??(s?"\\u56FE\\u7247 ":"Image ")+(v+1)),attrs:{value:String(y.id)}}))]);b.addEventListener("change",()=>{let y=h.find(v=>v.id===b.value);y&&f("../".repeat(p.split("/").length-1)+String(y.file))}),r.append(Me(s?"\\u66FF\\u6362\\u56FE\\u7247":"Replace image",b))}else r.append(A(s?"\\u5148\\u5728\\u7D20\\u6750\\u4E2D\\u5BFC\\u5165\\u56FE\\u7247\\uFF0C\\u518D\\u56DE\\u5230\\u8FD9\\u91CC\\u66FF\\u6362\\u3002":"Import an image in Media, then select it here."));r.append(u("details",{},[u("summary",{text:s?"\\u56FE\\u7247\\u5730\\u5740":"Image path"}),l]))}else r.append(Me(s?"\\u6587\\u5B57\\u5185\\u5BB9":"Text content",l));r.append(A(s?"\\u4FEE\\u6539\\u4F1A\\u4FDD\\u5B58\\u5230\\u5F53\\u524D\\u5DE5\\u7A0B\\uFF0C\\u5E76\\u7528\\u4E8E\\u89C6\\u9891\\u5BFC\\u51FA\\u3002":"Changes are saved to this project and used in the exported video."))}).catch(i=>r.append(A(String(i),"bad"))),r};var ln=(e,t,n,o)=>{let r,s=a=>{let c=r;c&&(r=void 0,a&&c.dispatchEvent(new Event("commit")),c.remove())};e.addEventListener("studio:inline-edit",a=>{if(r)return;let c=n.get(),i=c.pinned;if(!i||!c.state||a.target.closest(".handle"))return;let d=q(c.state,i),l=i.kind==="item"?c.state.resolved?.items.find(h=>h.id===i.id):void 0,f=i.kind==="slot"?be(t,n).find(h=>h.selection.id===i.id&&h.selection.name===i.name):void 0;if(f?.image||d?.kind==="track"&&d.track.type==="image"){document.querySelector('#slot-inspector select, #edit-form select[data-path$=".material"]')?.focus();return}let g=f?.value??l?.text,p=f?.box??(d?Re(c.state,d):void 0);if(g===void 0||!p)return;s(!0),a.preventDefault(),a.stopPropagation();let m=u("textarea",{id:"stage-text-editor",class:"stage-text-editor",attrs:{"aria-label":c.lang==="zh"?"\\u76F4\\u63A5\\u7F16\\u8F91\\u6587\\u5B57":"Edit text on canvas"}});m.value=g,le(m,p),m.style.fontSize=Math.max(14,(l?.style?.size??.04)*(c.state.resolved?.canvas.height??1)*e.clientWidth/(c.state.resolved?.canvas.width??1))+"px",m.addEventListener("commit",()=>{if(!(m.value===g||!m.value.trim()))if(i.kind==="slot"){let h=n.get().state,b=$(G(h?.source).segments).findIndex(v=>v.id===i.id),y=G($(G(h?.source).segments)[b]?.base);o.send({op:"set",path:["segments",b,"base","slots"],value:{...G(y.slots),[i.name]:m.value}})}else d?.kind==="cue"?o.send({op:"set",path:["tracks",d.index,"cues",d.cue,"text"],value:m.value}):d?.kind==="track"&&o.send({op:"set",path:["tracks",d.index,"text"],value:m.value})}),m.addEventListener("blur",()=>s(!0)),m.addEventListener("pointerdown",h=>h.stopPropagation()),m.addEventListener("keydown",h=>{h.key==="Escape"?(h.preventDefault(),h.stopPropagation(),s(!1)):h.key==="Enter"&&(h.metaKey||h.ctrlKey)&&(h.preventDefault(),s(!0))}),e.append(m),r=m,m.focus(),m.select()}),n.subscribe((a,c)=>{(a.pinned!==c.pinned||a.state!==c.state||a.frame!==c.frame)&&s(!1)})};var Oo=["nw","n","ne","e","se","s","sw","w"],Ho=(e,t)=>{if(t.kind==="segment")return[];let n=String(t.track.id);return(e.state?.resolved?.items??[]).filter(o=>o.id===n||o.cue?.track===n).map(o=>o.id)},No=(e,t)=>{let n=e.state?.resolved;if(!n||t.kind==="segment")return!1;let o=t.kind==="cue"?String(t.track.id)+"#"+t.cue:String(t.track.id);return fe(n,e.frame).some(r=>r.id===o)},Io=(e,t,n,o,r,s)=>{let[a,c,i,d]=e.box0,l=(E,M)=>Math.round(E*M)/M;if(e.mode==="move")return[l(a+t,o),l(c+n,r),i,d];let[f,g,p,m]=[a,c,a+i,c+d];if(e.mode.includes("w")&&(f+=t),e.mode.includes("e")&&(p+=t),e.mode.includes("n")&&(g+=n),e.mode.includes("s")&&(m+=n),s){let E=i*o/(d*r),M=p-f,k=m-g;if(e.mode.length===1?e.mode==="e"||e.mode==="w":Math.abs(M/i-1)>=Math.abs(k/d-1)){let L=M*o/E/r;e.mode.includes("n")?g=m-L:(e.mode.includes("s")||(g=c+d/2-L/2),m=g+L)}else{let L=k*r*E/o;e.mode.includes("w")?f=p-L:(e.mode.includes("e")||(f=a+i/2-L/2),p=f+L)}}let[h,b,y,v]=[l(f,o),l(g,r),l(p,o),l(m,r)];return[Math.min(h,y-1/o),Math.min(b,v-1/r),Math.max(1/o,y-h),Math.max(1/r,v-b)]},Fo=(e,t,n)=>{let o=(s,a)=>String(Math.round(s*a)),r=s=>s.toFixed(3);return"x "+o(e[0],t)+" y "+o(e[1],n)+" "+o(e[2],t)+"\\xD7"+o(e[3],n)+" px ("+[e[0],e[1],e[2],e[3]].map(r).join(", ")+")"},Do=(e,t)=>{let n=new Map;return{move:(o,r)=>{let s=e.contentDocument,{W:a,H:c}=$e(t.get());for(let i of Ho(t.get(),o)){let d=s?.querySelector('[data-item="'+CSS.escape(i)+'"]');d&&(n.has(d)||n.set(d,d.style.cssText),Object.assign(d.style,{left:r[0]*a+"px",top:r[1]*c+"px",width:r[2]*a+"px",height:r[3]*c+"px"}))}},restore:()=>{n.forEach((o,r)=>{r.style.cssText=o}),n=new Map},forget:()=>{n=new Map}}},$e=e=>({W:e.state?.resolved?.canvas.width??1,H:e.state?.resolved?.canvas.height??1}),jo=(e,t,n,o)=>{let r=t.state?.resolved;if(!r)return;let s=e.getBoundingClientRect(),a=(n-s.left)/s.width,c=(o-s.top)/s.height;return[...fe(r,t.frame)].reverse().find(i=>a>=i.box[0]&&a<=i.box[0]+i.box[2]&&c>=i.box[1]&&c<=i.box[1]+i.box[3])?.id},zo=(e,t,n)=>{let o=t.state?q(t.state,t.pinned):void 0,r=n??(o&&t.state?Re(t.state,o):void 0),s=!!(r&&o&&(n||No(t,o)));if(e.layer.classList.toggle("off",!t.state?.resolved),e.sel.hidden=!s,e.readout.hidden=!n,s&&r&&(le(e.sel,r),e.sel.classList.toggle("thin",e.sel.getBoundingClientRect().height<18)),n){let{W:a,H:c}=$e(t);e.readout.textContent=Fo(n,a,c)}},cn=e=>{let t=e.state?q(e.state,e.pinned):void 0,n=t&&e.state?Re(e.state,t):void 0;return t&&n?{t,box:n}:void 0},et=(e,t,n,o)=>{let r=u("div",{class:"sel-box",id:"sel-box"},Oo.map(v=>u("div",{class:"handle h-"+v,data:{h:v}}))),s=u("div",{class:"drag-readout",id:"drag-readout"}),a=u("div",{class:"studio-slot-outline",attrs:{hidden:""}},[u("span",{class:"studio-slot-name"})]),c={layer:u("div",{class:"edit-layer",id:"edit-layer"},[r,s]),sel:r,readout:s};c.layer.append(a),e.append(c.layer),ln(e,t,n,o);let i=Do(t,n),d,l,f,g,p=!0,m=()=>{let v=n.get();zo(c,v,d&&!d.moved?void 0:f?.box);let E=v.pinned,M=E?.kind==="slot"?be(t,n).find(k=>k.selection.id===E.id&&k.selection.name===E.name):void 0;if(E?.kind==="slot"&&p&&document.body.dataset.ready==="1"){p=!1;let k=Qe(t,n,E);if(k===void 0){o.select(null);return}if(k!==v.frame){o.reveal(E,k);return}}a.hidden=!M,M&&(le(a,M.box),a.firstElementChild.textContent=M.image?v.lang==="zh"?"\\u56FE\\u7247":"Image":M.value.slice(0,40))},h=(v,E)=>{let M=bt(v);M&&o.send({op:"set",path:M,value:Zt(E)}).then(k=>{k||i.restore(),f=void 0,m()})},b=(v,E)=>{f={box:E,target:v},i.move(v,E),m()};c.layer.addEventListener("pointerdown",v=>{if(v.button!==0||!n.get().state?.resolved||n.get().edit.saving||v.target.closest("#stage-text-editor"))return;let E=n.get().pinned;if((E?.kind==="slot"?be(t,n).some(L=>L.selection.id===E.id&&L.selection.name===E.name&&!L.image):E?.kind==="item"&&n.get().state?.resolved?.items.some(L=>L.id===E.id&&L.type==="text"))&&l&&performance.now()-l.time<450&&Math.hypot(v.clientX-l.x,v.clientY-l.y)<6&&!v.target.closest(".handle")){l=void 0,e.dispatchEvent(new Event("studio:inline-edit")),v.preventDefault();return}document.activeElement instanceof HTMLElement&&document.activeElement!==document.body&&document.activeElement.blur();let k=v.target.closest(".handle")?.dataset.h;if(!k&&!v.target.closest(".sel-box")){let L=jo(e,n.get(),v.clientX,v.clientY);if(!L){let R=e.getBoundingClientRect(),F=(v.clientX-R.left)/R.width,O=(v.clientY-R.top)/R.height,D=be(t,n).reverse().find(w=>F>=w.box[0]&&F<=w.box[0]+w.box[2]&&O>=w.box[1]&&O<=w.box[1]+w.box[3]);if(D){o.select(D.selection),l={time:performance.now(),x:v.clientX,y:v.clientY},v.preventDefault();return}}if(o.select(L?{kind:"item",id:L}:null),!L)return}let H=cn(n.get());H&&(d={mode:k??"move",x0:v.clientX,y0:v.clientY,box0:f?.box??H.box,moved:!1,target:H.t},c.layer.setPointerCapture(v.pointerId),v.preventDefault())}),c.layer.addEventListener("pointermove",v=>{if(!d||!d.moved&&Math.hypot(v.clientX-d.x0,v.clientY-d.y0)<2)return;d.moved=!0;let E=e.getBoundingClientRect(),{W:M,H:k}=$e(n.get());b(d.target,Io(d,(v.clientX-d.x0)/E.width,(v.clientY-d.y0)/E.height,M,k,v.shiftKey))});let y=v=>{if(v.type==="pointercancel"){d=void 0,f=void 0,l=void 0,i.restore(),m();return}let E=d;d=void 0,E&&!E.moved&&(l={time:performance.now(),x:E.x0,y:E.y0}),E?.moved&&f&&(l=void 0,h(E.target,f.box)),m()};return c.layer.addEventListener("pointerup",y),c.layer.addEventListener("pointercancel",y),n.subscribe((v,E)=>{v.state!==E.state&&i.forget(),(v.pinned!==E.pinned||v.state!==E.state)&&(p=!0),!d&&(v.state!==E.state||v.pinned!==E.pinned||v.frame!==E.frame)&&m()}),t.addEventListener("frameapplied",m),new ResizeObserver(m).observe(e),m(),{nudge:(v,E)=>{let M=cn(n.get()),k=f?.box??M?.box;if(!M||!k||d)return!1;let{W:H,H:L}=$e(n.get()),R=[Math.round(k[0]*H+v)/H,Math.round(k[1]*L+E)/L,k[2],k[3]];return b(M.t,R),g&&clearTimeout(g),g=setTimeout(()=>h(M.t,R),400),!0}}};var tt=(e,t,n)=>{let r=[{id:"edit-undo",icon:"undo",title:"undo",run:()=>{n.undo()},enabled:c=>(c.state?.edit?.undo??0)>0},{id:"edit-redo",icon:"redo",title:"redo",run:()=>{n.redo()},enabled:c=>(c.state?.edit?.redo??0)>0},{id:"edit-add-text",icon:"addText",title:"addText",run:()=>{n.addText()},enabled:c=>!!c.state?.resolved},{id:"edit-duplicate",icon:"duplicate",title:"duplicate",run:()=>{n.duplicate()},enabled:()=>n.target()!==void 0},{id:"edit-delete",icon:"remove",title:"remove",run:()=>{n.remove()},enabled:c=>{let i=n.target();return!!(i&&(i.kind!=="segment"||(c.state?.resolved?.segments.length??0)>1))}},{id:"edit-render",icon:"render",title:"renderTool",run:()=>{n.render()},enabled:c=>!!c.state?.resolved&&c.edit.render?.state!=="running"}].map(c=>{let i=u("button",{id:c.id,class:"tbtn",attrs:{type:"button"}},[Y(c.icon)]);return["edit-add-text","edit-duplicate","edit-delete"].includes(c.id)&&i.append(u("span",{class:"tool-label"})),i.addEventListener("click",()=>{c.run(),i.blur()}),{tool:c,el:i}}),s=(c,i)=>u("span",{class:"tool-group"},r.slice(c,i).map(d=>d.el));e.append(u("span",{class:"edit-tools",id:"edit-tools"},[s(0,2),s(2,5),s(5,6)]));let a=c=>{for(let i of r){i.el.title=S(c.lang,i.tool.title);let d=i.el.querySelector(".tool-label");d&&(d.textContent=i.tool.id==="edit-add-text"?c.lang==="zh"?"\\u6587\\u5B57":"Text":i.tool.id==="edit-duplicate"?c.lang==="zh"?"\\u590D\\u5236":"Duplicate":c.lang==="zh"?"\\u5220\\u9664":"Delete"),i.el.setAttribute("aria-label",S(c.lang,i.tool.title)),i.el.disabled=!!c.edit.saving||!i.tool.enabled(c)}};a(t.get()),t.subscribe((c,i)=>{(c.state!==i.state||c.lang!==i.lang||c.pinned!==i.pinned||c.edit.render!==i.edit.render||c.edit.saving!==i.edit.saving)&&a(c)})},Bo={set:"saved",insert:"added",remove:"removed",move:"moved",outside:"outside"},Vo=e=>{let t=e.edit.status,n=e.lang;if(!t)return"";if(t.kind==="note")return S(n,t.key==="phraseSpan"?"phraseSpan":"offlineEdit");if(t.kind==="refused")return S(n,"notSaved")+": "+(t.problem.at.startsWith("(")?"":t.problem.at+": ")+t.problem.message+(t.problem.fix?" "+S(n,"fix")+": "+t.problem.fix:"");let o=t.step==="outside"?S(n,"outside"):t.label;return t.op==="undo"||t.op==="redo"?S(n,t.op==="undo"?"undone":"redone")+": "+o:S(n,Bo[t.op]??"saved")+": "+o},_o=(e,t,n)=>{let o=e.edit.render;if(!o||o.state==="idle")return[];if(o.state==="running")return[u("span",{text:S(n,"rendering")+": "+o.frame+" / "+(o.total||"?")})];if(o.state==="failed")return[u("span",{class:"bad",text:S(n,"renderFailed")+": "+o.message})];let r=u("button",{id:"play-render",class:"link",text:S(n,e.edit.playRender?"showReference":"playRender"),attrs:{type:"button"}});return r.addEventListener("click",()=>t.togglePlayRender()),[u("span",{text:S(n,"rendered")+": "+o.frames+" "+S(n,"framesIn")+" "+o.seconds+" s, ",title:o.file}),u("code",{text:o.file.split(/[\\\\/]/).pop()??o.file,title:o.file})," ",r]},nt=(e,t,n)=>{let o=u("div",{id:"edit-status",class:"status-line",attrs:{role:"status","aria-live":"polite"}}),r=u("div",{id:"render-status",class:"status-line render"});e.prepend(u("div",{class:"edit-status"},[o,r]));let s=a=>{o.textContent=Vo(a),o.classList.toggle("bad",a.edit.status?.kind==="refused"),r.replaceChildren(..._o(a,n,a.lang))};s(t.get()),t.subscribe((a,c)=>{(a.edit!==c.edit||a.lang!==c.lang)&&s(a)})},Ko=e=>e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLInputElement&&!["checkbox","range","button","color"].includes(e.type)||e instanceof HTMLElement&&e.isContentEditable,ot=(e,t,n)=>{document.addEventListener("keydown",o=>{if(document.querySelector('[role="dialog"]'))return;if(Ko(o.target)){if(o.target.id==="stage-text-editor")return;o.key==="Escape"&&o.target.blur();return}let r=o.ctrlKey||o.metaKey,s=o.key.toLowerCase(),a=l=>{o.preventDefault(),o.stopPropagation(),l()};if(r&&s==="z")return a(()=>{o.shiftKey?t.redo():t.undo()});if(r&&s==="y")return a(()=>{t.redo()});if(r&&s==="d")return a(()=>{t.duplicate()});if(r||o.altKey)return;if(s==="s")return a(()=>{t.split()});if(o.key==="Delete"||o.key==="Backspace")return a(()=>{t.remove()});if(o.key==="Escape")return a(()=>t.select(null));let i={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]}[o.key];if(!i||!e.get().pinned)return;let d=o.shiftKey?10:1;n(i[0]*d,i[1]*d)&&a(()=>{})},!0)};var un=(e,t,n)=>e.reduce((o,[r,s])=>Math.max(o,Math.min(1,Math.max(0,(n-(r-t))/t),Math.max(0,(s+t-n)/t))),0),mn=e=>Math.min(1,Math.max(0,e)),Uo=(e,t)=>{if(!e)return 0;let{out:n,in:o}=e;return e.spans.reduce((r,[s,a])=>Math.max(r,Math.min(mn((t-(s-n))/n),mn((a+o-t)/o))),0)},Jo=(e,t)=>{let n=Uo(e,t);return n<=0?0:n>=1?120:Math.min(120,-20*Math.log10(1-n))},pn=(e,t)=>e?e.db*un(e.spans,e.ramp,t)+(e.away?e.away.db*un(e.away.spans,e.away.ramp,t):0)+(e.gaps?Jo(e.gaps,t):0):0;var gn=e=>{let t=[],n,o=()=>{for(let s of t)s.audio.pause(),s.audio.removeAttribute("src"),s.gain.disconnect();t=[]},r=()=>{let s=e.get(),a=s.state?.resolved;if(!a)return;let c=a.audio;(c.length!==t.length||t.some((d,l)=>d.source!==c[l]?.src))&&(o(),n??=new AudioContext,t=c.map(d=>{let l=new Audio;l.crossOrigin="anonymous",l.preload="auto",l.src=Ce(d.src);let f=n.createGain();return n.createMediaElementSource(l).connect(f).connect(n.destination),{audio:l,gain:f,source:d.src}})),s.playing&&n?.state==="suspended"&&n.resume().catch(()=>{});let i=s.frame/a.canvas.fps;t.forEach((d,l)=>{let f=c[l];if(!f)return;d.gain.gain.value=s.muted?0:10**((f.gain-pn(f.duck,s.frame))/20);let g=s.frame>=f.start&&(f.end===void 0||s.frame<f.end),p=Math.max(0,(i-f.start/a.canvas.fps)*(f.speed??1)+(f.from?f.from.frame/f.from.fps:0));d.audio.playbackRate=s.speed*(f.speed??1),g&&!d.audio.seeking&&Math.abs(d.audio.currentTime-p)>.2&&(d.audio.currentTime=p),s.playing&&g&&!s.muted?d.audio.paused&&d.audio.play().catch(()=>{}):d.audio.pause()})};e.subscribe((s,a)=>{(s.state!==a.state||s.frame!==a.frame||s.playing!==a.playing||s.muted!==a.muted||s.speed!==a.speed)&&r()}),window.addEventListener("pagehide",()=>{o(),n?.close()})},fn=new Map,hn=e=>{let t=fn.get(e);if(t)return t;let n=(async()=>{let o=new AudioContext;try{let r=await fetch(Ce(e)),a=(await o.decodeAudioData(await r.arrayBuffer())).getChannelData(0),c=[];for(let i=0;i<500;i++){let d=Math.floor(i*a.length/500),l=Math.floor((i+1)*a.length/500),f=0;for(let g=d;g<l;g+=8)f=Math.max(f,Math.abs(a[g]??0));c.push(f)}return c}finally{await o.close()}})();return fn.set(e,n),n};var En=" \\xB7 ",Ne=e=>({sel:JSON.stringify(e)}),ue=(e,t,n,o={})=>u("div",{class:"lane "+(o.cls??""),id:"lane-"+e,...o.height?{style:"height:"+o.height+"px"}:{}},[u("div",{class:"lane-label",text:t,title:t,...o.labelSel?{data:Ne(o.labelSel)}:{}}),u("div",{class:"lane-track"},n)]),ae=(e,t,n,o,r,s,a)=>Le(u("div",{class:e,text:r,title:s,...a?{data:Ne(a)}:{}}),t,n,o),Wo=(e,t,n)=>ue("ruler",S(n,"ruler"),jt(e,t).map(o=>Q(u("div",{class:"rtick",text:o.label,title:"frame "+o.frame}),o.frame,e)),{cls:"ruler"}),qo=e=>e.segments.map(t=>Q(u("div",{class:"seg-grip",title:t.id+": "+(t.end-t.start)+" frames",data:{border:String(t.index)}}),t.end,e.frames)),bn=(e,t,n,o)=>{let r=e.frames,s=e.segments.flatMap(a=>{let c=a.base.kind==="color"?a.base.color:void 0,i=ae("blk seg",a.start,a.end,r,a.id,a.id+": frames "+a.start+".."+(a.end-1),{kind:"segment",id:a.id});i.textContent="",i.setAttribute("role","button"),i.tabIndex=0,i.setAttribute("aria-label",(t==="zh"?"\\u955C\\u5934 ":"Shot ")+(a.index+1)+" \\xB7 "+((a.end-a.start)/e.canvas.fps).toFixed(2)+"s"),i.dataset.index=String(a.index),i.append(u("img",{attrs:{loading:"lazy",alt:"",src:"/api/thumbnail?frame="+Math.floor((a.start+a.end)/2)+"&g="+o}}),u("span",{class:"segment-name",text:String(a.index+1).padStart(2,"0")+" \\xB7 "+((a.end-a.start)/e.canvas.fps).toFixed(2)+"s"})),c&&i.prepend(u("span",{class:"swatch",style:"background:"+c}));let d=a.transition;if(!d)return a.index===0?[i]:[i,Q(u("div",{class:"tick"}),a.start,r)];let l=Nt(d),f=ae("band",d.a,d.a+d.frames,r,"",l+": mixed frames "+d.a+".."+(d.a+d.frames-1)+", takes over at "+d.boundary,{kind:"segment",id:a.id});return f.append(u("span",{class:"band-label",text:l})),[i,f,Q(u("div",{class:"tick"}),a.start,r)]});return ue("segments",S(t,"segments"),n?[...s,...qo(e)]:s,{cls:"segments"})},yn=(e,t,n)=>{let o={kind:"item",id:e.id},r=[ae("blk item",e.start,e.end,t,"",e.id+" ("+e.type+"): frames "+e.start+".."+(e.end-1),o)];if(e.enter.frames>0&&r.push(ae("shade enter",e.start,e.start+e.enter.frames,t,Te(e.enter),"enter: "+Te(e.enter)+", "+e.enter.ease,o)),e.exit.frames>0&&r.push(ae("shade exit",e.end-e.exit.frames,e.end,t,Te(e.exit),"exit: "+Te(e.exit)+", "+e.exit.ease,o)),n)for(let[s,a]of[["start",e.start],["end",e.end]])r.push(Q(u("div",{class:"grip "+s,data:{grip:s,...Ne(o)}}),a,t));return ue("item-"+e.id,e.id+En+e.type,r,{labelSel:o})},vn=(e,t,n,o=!1)=>{let r={kind:"audio",id:e.id},s=n==="zh"?"\\u97F3\\u9891":"Audio",a=ae("blk audio",e.start,e.end??t,t,s,s,r);a.setAttribute("role","button"),a.tabIndex=0,a.setAttribute("aria-label",s),hn(e.src).then(i=>{let d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("viewBox","0 0 500 28"),d.setAttribute("preserveAspectRatio","none");let l=document.createElementNS(d.namespaceURI,"path");l.setAttribute("d",i.map((f,g)=>"M"+g+" "+(14-Math.max(1,f*13))+"v"+Math.max(2,f*26)).join("")),l.setAttribute("stroke","#69967c"),l.setAttribute("stroke-width","0.8"),d.append(l),a.append(d),a.classList.add("wave-ready")}).catch(()=>{});let c=["start","end"].map(i=>Q(u("div",{class:"grip "+i,data:{grip:i,...Ne(r)}}),i==="start"?e.start:e.end??t,t));return ue("audio-"+e.id,S(n,"audio"),[a,...o?c:[]],{labelSel:r})},Go=(e,t,n)=>ue("words-"+e.track,S(n,"words")+": "+e.track,e.tokens.map(o=>ae("blk audio word"+(o.confidence<.4?" unsure":""),o.start,o.end,t,o.text,o.text+": frames "+o.start+".."+(o.end-1)+En+"confidence "+o.confidence)),{cls:"words-lane"}),Yo=(e,t,n,o,r)=>{let s=e.measure,a=i=>ye(i,s.source.fps,o),c=s.boundaries.flatMap((i,d)=>{let l={kind:"boundary",source:t,index:d},f=It(i),g=f+": frames "+i.start+".."+i.end+" of the measured file, takes over at "+i.frame,p=Q(u("div",{class:"mark",title:g,data:Ne(l)},[u("span",{class:"mark-label",text:f})]),a(i.frame),n);return i.kind==="cut"?[p]:[ae("mband",a(i.start+1),a(i.end),n,"",g,l),p]});return ue(t+"-boundaries",S(r,t==="render"?"renderBoundaries":"referenceBoundaries"),c,{cls:"measure "+t})},Sn=14,Xo=4,Zo=(e,t,n,o,r)=>{let s=e.measure,a=Ft(s).map(l=>({start:ye(l.event.start,s.source.fps,o),end:ye(l.event.end,s.source.fps,o),value:l})),c=mt(a,Xo),i=c.map(l=>{let f=ze(l.value.event),g=ae("ev",l.start,l.end,n,f,f+": frames "+l.value.event.start+".."+(l.value.event.end-1)+" of the measured file",{kind:"event",source:t,shot:l.value.shot,index:l.value.index});return g.style.top=3+l.row*Sn+"px",g}),d=Math.max(1,...c.map(l=>l.row+1));return ue(t+"-events",S(r,t==="render"?"renderEvents":"referenceEvents"),i,{cls:"measure "+t,height:6+d*Sn})},Qo=(e,t,n)=>{let o=W(e),r=se(e),s=e.resolved,a=e.edit!==void 0,c=[Wo(o,r,t)];if(s)if(a){let i=bn(s,t,a,e.generation);i.querySelector(".lane-label").textContent=t==="zh"?"\\u955C\\u5934":"Shots",c.push(i);let d=[{id:"subtitles",label:t==="zh"?"\\u5B57\\u5E55":"Subtitles",items:s.items.filter(l=>l.cue),cls:"caption-lane"},{id:"text",label:t==="zh"?"\\u6587\\u5B57":"Text",items:s.items.filter(l=>!l.cue&&l.type==="text"),cls:"caption-lane"},{id:"media",label:t==="zh"?"\\u7D20\\u6750":"Media",items:s.items.filter(l=>!l.cue&&l.type!=="text"),cls:"media-lane"}];for(let l of n.timeline?.layers===!1?[]:d){let f=mt(l.items.map(p=>({start:p.start,end:p.end,value:p})).sort((p,m)=>p.start-m.start||m.value.z-p.value.z||p.value.id.localeCompare(m.value.id)),Math.max(1,l.items.length)),g=Math.max(0,...f.map(p=>p.row+1));for(let p=0;p<g;p++){let m=f.filter(h=>h.row===p).flatMap(({value:h})=>{let b=Array.from(yn(h,o,a).querySelector(".lane-track").children),y=b[0];if(y){let v=h.text??(t==="zh"?h.type==="video"?"\\u89C6\\u9891":h.type==="image"?"\\u56FE\\u7247":"\\u5F62\\u72B6":h.type);y.textContent=v,y.title=v,y.setAttribute("role","button"),y.setAttribute("tabindex","0"),y.setAttribute("aria-label",v)}return b});c.push(ue(l.id+"-"+p,l.label+(p?" "+(p+1):""),m,{cls:l.cls}))}}if(n.timeline?.layers!==!1)for(let l of n.slots??[]){let f=s.segments.find(h=>h.id===l.segment);if(!f)continue;let g={kind:"slot",id:l.segment,name:l.name},p=l.kind==="image"?t==="zh"?"\\u56FE\\u7247":"Image":l.value,m=ae("blk item scene-field",f.start,f.end,o,p,t==="zh"?"\\u573A\\u666F\\u5185\\u5BB9\\uFF1A\\u65F6\\u95F4\\u7531\\u573A\\u666F\\u63A7\\u5236\\uFF0C\\u70B9\\u9009\\u540E\\u7F16\\u8F91\\u5185\\u5BB9":"Scene content: timing follows scene; select to edit",g);m.setAttribute("role","button"),m.tabIndex=0,m.setAttribute("aria-label",(t==="zh"?"\\u573A\\u666F\\u5185\\u5BB9\\uFF1A":"Scene field: ")+p),c.push(ue("slot-"+l.segment+"-"+l.name,t==="zh"?"\\u573A\\u666F\\u5185\\u5BB9":"Scene content",[m],{cls:"caption-lane"}))}c.push(...s.audio.map(l=>vn(l,o,t,!0)))}else c.push(bn(s,t,a,e.generation),...s.items.map(i=>yn(i,o,a)),...s.audio.map(i=>vn(i,o,t)),...(s.words??[]).map(i=>Go(i,o,t)));for(let[i,d]of[[e.measure,"render"],[e.referenceMeasure,"reference"]])i&&!a&&c.push(Yo(i,d,o,r,t),Zo(i,d,o,r,t));return c},xn=(e,t,n)=>{let o=e.getBoundingClientRect();return Math.floor((t-o.left)/Math.max(1,o.width)*n)},rt=(e,t,n)=>{let o=u("div",{class:"lanes",id:"lanes"}),r=u("div",{class:"playhead",id:"playhead"}),s=u("div",{class:"playhead-layer"},[r]);e.append(o);let a=l=>l.state?W(l.state):0,c=l=>{Le(r,l.frame,l.frame+1,a(l))},i=l=>{o.querySelectorAll("[data-sel]").forEach(f=>{f.setAttribute("aria-pressed",String(l.pinned!==null&&ge(JSON.parse(f.dataset.sel??"null"),l.pinned))),f.classList.toggle("selected",l.pinned!==null&&ge(JSON.parse(f.dataset.sel??"null"),l.pinned))})},d=l=>{o.replaceChildren(...l.state?Qo(l.state,l.lang,l):[],s),c(l),i(l)};o.addEventListener("click",l=>{let f=l.target,g=f.closest("[data-sel]")?.dataset.sel;if(g){let p=JSON.parse(g);n.pause();let m=t.get();m.timeline&&["item","slot","audio"].includes(p.kind)&&!m.timeline.layers&&t.set({timeline:{...m.timeline,layers:!0}}),n.pin(p);let h=f.closest(".lane-track");if(m.state?.edit)n.seek(Ae(t.get().state,p,t.get().frame));else if(h&&l.detail!==0)n.seek(xn(h,l.clientX,a(m)));else{let b=p.kind==="segment"?m.state?.resolved?.segments.find(y=>y.id===p.id):p.kind==="item"?m.state?.resolved?.items.find(y=>y.id===p.id):void 0;b&&(m.frame<b.start||m.frame>=b.end)&&n.seek(b.start)}}else{let p=f.closest(".lane-track");p&&(n.pin(null),l.detail!==0&&n.seek(xn(p,l.clientX,a(t.get()))))}}),o.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let f=l.target.closest("[data-sel]");f&&(l.preventDefault(),f.click())}),e.addEventListener("wheel",l=>{l.shiftKey&&!l.deltaX&&(e.scrollLeft+=l.deltaY,l.preventDefault())},{passive:!1}),d(t.get()),t.subscribe((l,f)=>{if(l.state!==f.state||l.lang!==f.lang||l.timeline?.layers!==f.timeline?.layers||l.slots!==f.slots?d(l):l.frame!==f.frame&&c(l),l.pinned!==f.pinned){i(l);let g=o.querySelector(".blk.selected");if(g){let p=g.getBoundingClientRect(),m=e.getBoundingClientRect(),h=o.querySelector(".lane-label")?.getBoundingClientRect().width??0;(p.left<m.left+h||p.right>m.right)&&(e.scrollLeft+=p.left-m.left-h-20);let b=(o.querySelector(".ruler")?.getBoundingClientRect().height??0)+(g.closest(".segments")?0:o.querySelector(".segments")?.getBoundingClientRect().height??0);(p.top<m.top+b||p.bottom>m.bottom)&&(e.scrollTop+=p.top-m.top-b-6)}}})};var wn=e=>e.reduce((t,n)=>typeof n=="number"?t+"["+n+"]":t?t+"."+n:n,""),$o=(e,t)=>Ut(t)?S(e,t):t,Mt=e=>typeof e=="number"?String(Number(e.toFixed(4))):typeof e=="string"?e:JSON.stringify(e)??"",kt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),er=(e,t)=>{let n=wn(t);return e.filter(o=>o.at===n||o.at.startsWith(n+".")||o.at.startsWith(n+"["))},tr=(e,t)=>{let n=u("input",{attrs:{type:"number",step:String(e.step??(e.range?.integer?1:"any")),...e.range?.min===void 0?{}:{min:String(e.range.min)},...e.range?.max===void 0?{}:{max:String(e.range.max)}}});return n.value=typeof e.value=="number"?Mt(e.value):"",typeof e.resolved=="number"&&e.value===void 0&&(n.placeholder=Mt(e.resolved)),n.addEventListener("change",()=>{let o=n.value.trim(),r=Number(o);if(o!==""&&!Number.isFinite(r))return void n.setAttribute("aria-invalid","true");t(o===""?void 0:r)}),n},kn=(e,t)=>{let n=typeof e.value=="string"?e.value:"";if(e.kind==="textarea"){let r=u("textarea",{attrs:{rows:String(Math.min(6,Math.max(2,n.split(\`
38023
+ \`).length)))}});return r.value=n,r.addEventListener("change",()=>t(r.value===""?void 0:r.value)),r.addEventListener("keydown",s=>{s.key==="Enter"&&(s.ctrlKey||s.metaKey)&&r.blur()}),r}let o=u("input",{attrs:{type:"text",autocomplete:"off",spellcheck:"false"}});return o.value=n,typeof e.resolved=="string"&&e.value===void 0&&(o.placeholder=e.resolved),o.addEventListener("change",()=>t(o.value.trim()===""?void 0:o.value.trim())),o},nr=(e,t,n)=>{let o=[...e.empty===null?[]:[u("option",{text:e.empty??S(n,"fDefault"),attrs:{value:""}})],...e.options.map(a=>u("option",{text:e.labels?.[a]??a,attrs:{value:a}}))],r=u("select",{},o),s=e.value===void 0?"":String(e.value);return s!==""&&!e.options.includes(s)&&r.append(u("option",{text:s,attrs:{value:s}})),r.value=s,r.addEventListener("change",()=>t(r.value===""?void 0:r.value)),r},or=(e,t)=>{let n=kn(e,t),o=e.value??e.resolved,r=typeof o=="string"&&/^#[0-9a-f]{6}$/i.test(o)?o:"#000000",s=u("input",{class:"swatch-pick",attrs:{type:"color",tabindex:"-1"}});return s.value=r.toLowerCase(),s.addEventListener("change",()=>t(s.value)),u("span",{class:"colour"},[s,n])},rr=(e,t)=>{let n=e.commit??(d=>{kt(d,e.value)||t.commit(e.path,d)}),o=d=>{kt(d,e.value)||n(d)},r=e.kind==="number"?tr(e,o):e.kind==="select"?nr(e,o,t.lang):e.kind==="color"?or(e,o):kn(e,o),s=r.tagName==="SPAN"?r.querySelector("input[type=text]"):r;s.dataset.path=wn(e.path),e.disabled&&s.setAttribute("disabled","");let a=er(t.problems,e.path);a.length&&s.setAttribute("aria-invalid","true");let c=e.resolved!==void 0&&e.value!==void 0&&!kt(e.value,e.resolved),i=$o(t.lang,e.label);return u("label",{class:"fld"+(e.wide||e.kind==="textarea"?" wide":"")+(e.kind==="textarea"?" area":"")},[u("span",{class:"fl",text:i,title:i}),r,...c?[u("span",{class:"rv",text:"\\u2192 "+Mt(e.resolved),title:S(t.lang,"resolvedTitle")})]:[],...a.map(d=>u("span",{class:"fprob",text:d.message+(d.fix?" "+S(t.lang,"fix")+": "+d.fix:"")}))])},_=(e,t,n,o=[])=>u("fieldset",{class:"fs"},[u("legend",{text:e}),...t.map(r=>u("div",{class:"row"},r.filter(s=>s!==null).map(s=>s instanceof HTMLElement?s:rr(s,n)))),...o]);var Ln=["slide","whip"],Rn=["blur","zoom","shake","flash","whip","glitch","fade","spin"];var Pn=(e,t,n)=>u("div",{class:"hint",text:S(e.lang,"onFrames")+" "+t+".."+(n-1)}),Tt=(e,t,n,o,r=S(e.lang,"fWhen"))=>{let s=T(n)?n:{},a=e.state.resolved?.canvas.fps??30,c=e.state.resolved?.segments.find(g=>g.id===s.segment),i=g=>g==="from"?0:g==="to"&&c?c.end-c.start:void 0,d=(g,p)=>({kind:"number",label:S(e.lang,p)+(e.lang==="zh"?"\\uFF08\\u79D2\\uFF09":" (s)"),path:[...t,g],value:typeof(s[g]??i(g))=="number"?Number(s[g]??i(g))/a:void 0,step:.01,commit:m=>e.commit([...t,g],m===void 0?void 0:Math.round(Number(m)*a))}),l=o?[Pn(e,o.start,o.end)]:[];if(s.phrase!==void 0)return _(r,[[{kind:"text",label:"fPhrase",path:[...t,"phrase"],value:s.phrase,wide:!0}],[d("occurrence","fOccurrence"),d("lead","fLead"),d("hold","fHold")]],e,l);let f={kind:"select",label:"fSegment",path:[...t,"segment"],value:s.segment,options:te(e.state).map(g=>String(g.id)),labels:Object.fromEntries(te(e.state).map((g,p)=>[String(g.id),(e.lang==="zh"?"\\u753B\\u9762 ":"Scene ")+(p+1)])),empty:null};return _(r,[[f,d("from","fFrom"),d("to","fTo")]],e,l)},An=(e,t)=>{let n=Array.isArray(t.track.cues)?t.track.cues:[],o=String(t.track.id),r=n.flatMap((s,a)=>{if(t.kind==="cue"&&t.cue!==a)return[];let c=["tracks",t.index,"cues",a],i=e.state.resolved?.items.find(f=>f.id===o+"#"+a),d={kind:"textarea",label:S(e.lang,"fCue")+" "+a,path:[...c,"text"],value:T(s)?s.text:void 0},l=_("#"+a,[[d]],e,[Tt(e,[...c,"during"],T(s)?s.during:void 0,i,S(e.lang,"fWhen"))]);return l.classList.add("cue"),t.kind==="cue"&&t.cue===a&&l.classList.add("current"),l});return u("div",{class:"cues"},[u("h3",{text:S(e.lang,"fCues")+" ("+n.length+")"}),...r])},ar=(e,t)=>e==="wipe"?X(j(t.schema.transition,"direction")):Ln.includes(e)?X(j(t.schema.motion,"direction")):[],ir=(e,t,n,o)=>{let r=[...t,"in"],s=T(n)?n:void 0,a=String(s?.transition??""),c=e.schema.transition,i=o?.transition,d=(m,h,b,y)=>({kind:b,label:h,path:[...r,m],value:s?.[m],resolved:i?.[m==="transition"?"kind":m],range:xe(j(c,m)),options:y??X(j(c,m)),step:m==="strength"?.1:void 0}),l={kind:"select",label:"fKind",path:[...r,"transition"],value:s?.transition,options:X(j(c,"transition")),empty:S(e.lang,"fHardCut"),commit:m=>m===void 0?e.commit(r,void 0):e.commit([...r,"transition"],m)},f=ar(a,e),g=Rn.includes(a),p=[[l,s&&a!=="cut"?d("frames","fFrames","number"):null],[f.length?d("direction","fDirection","select",f):null,a==="slide"?d("mode","fMode","select"):null,a==="fade"?d("via","fVia","select"):null],[g?d("side","fSide","select"):null,s&&a!=="cut"?d("ease","fEase","select"):null,s&&a!=="cut"?d("strength","fStrength","number"):null]];return _(S(e.lang,"fTransition"),p.filter(m=>m.some(h=>h!==null)),e)},dr=(e,t,n)=>{let o=e.schema.base,r=ve(e.state,["image","video"]),s="material"in n?"material":"color"in n?"color":"scene",a={kind:"select",label:"fBase",path:t,value:s,options:s==="scene"?["scene","color","material"]:["color","material"],labels:{scene:S(e.lang,"fBaseScene"),color:S(e.lang,"fBaseColor"),material:S(e.lang,"fBaseMaterial")},empty:null,commit:d=>e.set(t,d==="scene"?n:d==="color"?{color:"#000000"}:{material:r[0]??""})};if(s==="scene"){let d=T(n.slots)?n.slots:{},l=Object.entries(d).filter(f=>typeof f[1]=="string").map(([f,g])=>[{kind:"textarea",label:f,path:[...t,"slots",f],value:g,wide:!0}]);return _(S(e.lang,"fBaseScene"),[[a],...l],e)}if(s!=="material"){let d=typeof n.color=="string"?{kind:"color",label:"fColour",path:[...t,"color"],value:n.color,empty:null}:u("div",{class:"hint",text:S(e.lang,"fGradient")});return _(S(e.lang,"fBase"),[[a,d]],e)}let c=ve(e.state,["video"]).includes(String(n.material)),i=(d,l,f)=>({kind:"number",label:l,path:[...t,d],value:n[d],range:xe(j(o,d)),...f?{step:f}:{}});return _(S(e.lang,"fBase"),[[a,{kind:"select",label:"fMaterial",path:[...t,"material"],value:n.material,options:r,empty:null,wide:!0}],[{kind:"select",label:"fFit",path:[...t,"fit"],value:n.fit,options:X(j(o,"fit"))},...c?[i("in","fIn"),i("speed","fSpeed",.05),i("audio","fSourceAudio")]:[]]],e,n.camera!==void 0?[u("div",{class:"hint",text:S(e.lang,"fCamera")})]:[])},Cn=(e,t)=>{let n=["segments",t.index],o=e.state.resolved?.segments[t.index],r=e.state.resolved?.canvas.fps??30,s={kind:"number",label:e.lang==="zh"?"\\u65F6\\u957F\\uFF08\\u79D2\\uFF09":"Duration (s)",path:[...n,"frames"],value:Number(oe(e.state.source,[...n,"frames"]))/r,step:.01,range:{min:1/r,integer:!1},commit:i=>e.commit([...n,"frames"],Math.max(1,Math.round(Number(i)*r)))},a=_(e.lang==="zh"?"\\u955C\\u5934\\u65F6\\u957F":"Shot duration",[[s]],e,o?[Pn(e,o.start,o.end)]:[]),c=t.segment;return[a,...t.index>0?[ir(e,n,c.in,o)]:[],...T(c.base)?[dr(e,[...n,"base"],c.base)]:[]]};var On=e=>{if(T(e))return e;if(typeof e!="string"||!St(e))return{};let{font:t,...n}=vt[e];return n},st="custom",Hn=(e,t,n,o)=>{let r=[...t,"style"],s=j(e.schema.text,"style"),a=X(s),c=T(n)?n:void 0,i=e.state.resolved?.canvas.height??1,d={kind:"number",label:e.lang==="zh"?"\\u5B57\\u53F7\\uFF08px\\uFF09":"Font size (px)",path:[...r,"size"],value:Math.round(Number(c?.size??o?.size??.05)*i),step:1,range:{min:1,max:i,integer:!0},commit:m=>l("size")(m===void 0?void 0:Number(m)/i)},l=m=>h=>{let b=Object.fromEntries(Object.entries({...On(n),[m]:h}).filter(([,y])=>y!==void 0));e.set(r,b)},f=(m,h,b={})=>({kind:h,label:"f"+m[0]?.toUpperCase()+m.slice(1),path:[...r,m],value:c?.[m],resolved:o?.[m],commit:l(m),range:xe(j(s,m)),options:X(j(s,m)),...b}),g={kind:"select",label:"fNamed",path:r,value:typeof n=="string"?n:c?st:void 0,options:[...a,st],labels:{[st]:S(e.lang,"fCustom"),...e.lang==="zh"?{headline:"\\u6807\\u9898",subtitle:"\\u526F\\u6807\\u9898",label:"\\u6807\\u7B7E",caption:"\\u5B57\\u5E55"}:{}},commit:m=>e.set(r,m===st?On(n):m)},p=f("font","select",{value:c?.font??o?.font,options:[...new Set([String(c?.font??o?.font??"sans-serif"),...ve(e.state,["font"]),"sans-serif","serif","monospace"])],label:e.lang==="zh"?"\\u5B57\\u4F53":"Font",wide:!0});return _(S(e.lang,"fStyle"),[[p],[g,d],[f("color","color",{label:"fColour"}),f("weight","number",{step:100}),f("align","select",{labels:e.lang==="zh"?{left:"\\u5DE6\\u5BF9\\u9F50",center:"\\u5C45\\u4E2D",right:"\\u53F3\\u5BF9\\u9F50"}:{}})]],e)},lr=new Set(["slide","wipe"]),at=(e,t,n,o,r)=>{let s=[...t,n],a=e.schema.motion,c=T(o)?o:void 0,i=(f,g,p)=>({kind:g,label:p,path:[...s,f],value:c?.[f],resolved:r?.[f],disabled:!c,range:xe(j(a,f)),options:X(j(a,f))}),d={kind:"select",label:"fPreset",path:[...s,"preset"],value:c?.preset,options:X(j(a,"preset")),empty:S(e.lang,"fNone"),commit:f=>f===void 0?e.commit(s,void 0):e.commit([...s,"preset"],f)},l=lr.has(String(c?.preset??""));return _(S(e.lang,n==="enter"?"fEnter":"fExit"),[[d,i("frames","number","fFrames")],[l?i("direction","select","fDirection"):null,i("ease","select","fEase")]],e)},ie=(e,t,n,o,r={})=>({kind:"number",label:n,path:t,value:oe(e.state.source,t),range:xe(o),...r}),Ie=(e,t,n,o,r={})=>({kind:"select",label:n,path:t,value:oe(e.state.source,t),options:o,...r}),Nn=(e,t,n)=>{let o=e.state.resolved?.canvas,r=n&&o?[n.box[0]*o.width,n.box[1]*o.height,n.box[2]*o.width,n.box[3]*o.height].map(a=>Math.round(a)).join(", ")+" px":"",s=["fX","fY","fW","fH"].map((a,c)=>{let i=[...t,"box",c],d=c%2===0?o?.width??1:o?.height??1;return ie(e,i,a,void 0,{step:1,value:Math.round(Number(oe(e.state.source,i)??0)*d),commit:l=>e.commit(i,Number(l)/d)})});return _(e.lang==="zh"?"\\u4F4D\\u7F6E\\u4E0E\\u5C3A\\u5BF8\\uFF08px\\uFF09":"Position and size (px)",[s],e,r?[u("div",{class:"hint",text:r})]:[])},cr=(e,t,n)=>_(S(e.lang,"fLook"),[[ie(e,[...t,"rotate"],"fRotate",j(n,"rotate")),ie(e,[...t,"opacity"],"fOpacity",j(n,"opacity"),{step:.05}),ie(e,[...t,"z"],"fZ",j(n,"z"))]],e),ur=(e,t,n,o)=>{let r=String(n.type),s=e.schema[r==="image"?"image":r==="video"?"video":"shape"],a=ie(e,[...t,"radius"],"fRadius",j(s,"radius"),{step:.01});if(r==="shape"){let f=typeof n.color=="string"?{kind:"color",label:"fColour",path:[...t,"color"],value:n.color,resolved:o?.color}:u("div",{class:"hint",text:S(e.lang,"fGradient")});return _(S(e.lang,"fShape"),[[Ie(e,[...t,"shape"],"fShape",X(j(s,"shape")),{empty:null}),f,a]],e)}if(r!=="image"&&r!=="video")return null;let c=Ie(e,[...t,"material"],"fMaterial",ve(e.state,[r]),{empty:null,wide:!0}),i=Ie(e,[...t,"fit"],"fFit",X(j(s,"fit")),{resolved:o?.fit}),d=Ie(e,[...t,"mask"],"fMask",X(j(s,"mask")),{empty:S(e.lang,"fNone")}),l=r==="video"?[ie(e,[...t,"in"],"fIn",j(s,"in")),ie(e,[...t,"speed"],"fSpeed",j(s,"speed"),{step:.05}),ie(e,[...t,"audio"],"fSourceAudio",j(s,"audio"))]:[];return _(S(e.lang,r==="video"?"fFootage":"fPicture"),[[c,i],[a,d,...l]],e)},mr=(e,t)=>{let n=_(S(e.lang,"fText"),[[{kind:"textarea",label:e.lang==="zh"?"\\u5185\\u5BB9":"Content",path:[...t,"text"],value:oe(e.state.source,[...t,"text"])}]],e);return n.querySelector("legend")?.remove(),n},pr=(e,t,n)=>{let o=T(n.during)?n.during:void 0,r={kind:"select",label:"fStart",path:[...t,"during","segment"],value:o?.segment,options:te(e.state).map(s=>String(s.id)),empty:S(e.lang,"fWhole"),commit:s=>s===void 0?e.commit([...t,"during"],void 0):e.set([...t,"during"],{...o??{},segment:s})};return _(S(e.lang,"fAudio"),[[Ie(e,[...t,"material"],"fMaterial",ve(e.state,["audio","voice","speech"]),{empty:null,wide:!0}),ie(e,[...t,"gain"],"fGain",j(e.schema.audio,"gain"))],[r,ie(e,[...t,"during","from"],"fFrom",void 0,{disabled:!o})]],e)},In=(e,t)=>e.resolved?.items.find(n=>n.id===t),fr=(e,t)=>{let n=["tracks",t.index],o=t.track,r=String(o.type);if(r==="audio")return[pr(e,n,o)];let s=String(o.id);if(r==="caption"){let i=In(e.state,s+"#"+(t.kind==="cue"?t.cue:0));return[An(e,t),Hn(e,n,o.style,i?.style),Nn(e,n,i),at(e,n,"enter",o.enter,i?.enter),at(e,n,"exit",o.exit,i?.exit)]}let a=In(e.state,s),c=e.schema[r==="text"?"text":r==="image"?"image":r==="video"?"video":"shape"];return[...r==="text"?[mr(e,n)]:[],...r==="text"?[Hn(e,n,o.style,a?.style)]:[ur(e,n,o,a)].filter(i=>i!==null),Tt(e,[...n,"during"],o.during,a),Nn(e,n,a),at(e,n,"enter",o.enter,a?.enter),at(e,n,"exit",o.exit,a?.exit),cr(e,n,c)]},Fn=(e,t)=>{let n=t.kind==="segment"?S(e.lang,"fSegment")+" "+String(t.segment.id):String(t.track.type)+" "+String(t.track.id)+(t.kind==="cue"?" #"+t.cue:""),o=t.kind==="segment"?Cn(e,t):fr(e,t),r=t.kind==="segment"?e.lang==="zh"?"\\u753B\\u9762 "+(t.index+1):"Scene "+(t.index+1):t.kind==="cue"?e.lang==="zh"?"\\u5B57\\u5E55 "+(t.cue+1):"Subtitle "+(t.cue+1):e.lang==="zh"?{text:"\\u6587\\u5B57",image:"\\u56FE\\u7247",video:"\\u89C6\\u9891",audio:"\\u97F3\\u9891",shape:"\\u5F62\\u72B6"}[String(t.track.type)]??"\\u5143\\u7D20":String(t.track.type),s=t.kind==="cue"?2:t.kind==="segment"?1:t.track.type==="text"?2:1;return u("div",{class:"form",id:"edit-form"},[u("div",{class:"sel-title",text:r,title:n}),...o.slice(0,s),...o.length>s?[u("details",{},[u("summary",{text:e.lang==="zh"?"\\u4F4D\\u7F6E\\u3001\\u65F6\\u95F4\\u4E0E\\u52A8\\u6548":"Position, timing and motion"}),...o.slice(s)])]:[]])};var Fe=(e,t=[])=>u("h2",{},[u("span",{text:e}),...t]),Dn=e=>u("pre",{class:"json",text:JSON.stringify(e,null,2)??"undefined"}),gr=(e,t,n)=>{if(e.pinned){let a=Bt(t,e.pinned);return[u("div",{class:"sel-title",text:Vt(e.pinned)}),a===void 0?u("p",{class:"muted",text:S(e.lang,"nothing")}):Dn(a)]}let o=t.resolved?Z(t.resolved,e.frame):void 0,s=(t.resolved?fe(t.resolved,e.frame):[]).map(a=>u("button",{class:"chip",text:a.id,attrs:{type:"button"},on:{click:()=>n.pin({kind:"item",id:a.id})}}));return[...o?[u("div",{class:"sel-title",text:"segment "+o.id}),Dn(o)]:[u("p",{class:"muted",text:S(e.lang,"nothing")})],u("div",{class:"chips"},[u("span",{class:"muted",text:S(e.lang,"onScreen")+": "}),...s.length?s:[S(e.lang,"none")]])]},hr=(e,t,n,o)=>{let r=e.edit.schema;if(!t.edit)return;if(!r)return[u("p",{class:"muted",text:e.lang==="zh"?"\\u6B63\\u5728\\u8F7D\\u5165\\u7F16\\u8F91\\u5DE5\\u5177\\u2026":"Loading editing tools\\u2026"})];if(e.pinned?.kind==="slot")return[dn(o,n)];let s=q(t,e.pinned);if(s){let a={lang:e.lang,problems:e.edit.problems,state:t,schema:r,commit:(c,i)=>{let d=Wt(t.source,c,i);d&&n.send(d)},set:(c,i)=>{n.send({op:"set",path:c,value:i})}};return[Fn(a,s)]}if(!e.pinned)return[]},br=(e,t)=>u("li",{class:"problem "+e.level},[u("div",{},[u("b",{class:e.level,text:S(t,e.level)})," ",u("code",{text:e.at})]),u("div",{text:e.message}),...e.allowed?.length?[u("div",{class:"muted",text:S(t,"allowed")+": "+e.allowed.join(", ")})]:[],...e.fix?[u("div",{text:S(t,"fix")+": "+e.fix})]:[]]),yr=e=>Object.entries(e).map(([t,n])=>t+"="+(typeof n=="number"?Number(n.toFixed(3)):n)).join(", "),vr=(e,t)=>{let n=(r,s="")=>u("tr",{class:s},r.map(a=>u("td",{},[a]))),o=Object.entries(e.dimensions).map(([r,s])=>{let a=yr(s.detail);return n([Jt(t,r),s.n?s.score.toFixed(2):"-",String(s.n),u("span",{class:"detail",text:a,title:a})],s.n?"":"muted")});return u("table",{class:"score"},[u("thead",{},[u("tr",{},[S(t,"dimension"),S(t,"value"),S(t,"compared"),S(t,"detail")].map(r=>u("th",{text:r})))]),u("tbody",{},[...o,n([S(t,"composite"),e.composite.toFixed(2),"",""],"total")])])},Sr=(e,t)=>[u("div",{class:"kv"},[u("span",{class:"muted",text:S(t,"renderMeasure")+": "}),u("code",{text:e.measure?.file??S(t,"none"),title:e.measure?.file??""})]),u("div",{class:"kv"},[u("span",{class:"muted",text:S(t,"referenceMeasure")+": "}),u("code",{text:e.referenceMeasure?.file??S(t,"none"),title:e.referenceMeasure?.file??""})]),...e.messages.map(n=>u("p",{class:"message",text:n}))],it=(e,t,n,o)=>{let r=u("section",{id:"selection"}),s=u("section",{id:"problems"}),a=u("section",{id:"score"}),c=u("section",{id:"measures"}),i=u("section",{id:"notes"});e.append(r,s,a,c,i);let d="",l="",f=p=>{let m=p.state,h=m?.resolved&&!p.pinned?[Z(m.resolved,p.frame)?.id,fe(m.resolved,p.frame).map(H=>H.id)]:null,b=m?.edit?[p.edit.problems,p.edit.schema!==null]:null,y=JSON.stringify([p.lang,m?.generation,p.pinned,h,b]);if(y===d)return;let v=JSON.stringify(p.pinned)!==l;l=JSON.stringify(p.pinned),d=y;let E=r.contains(document.activeElement)?document.activeElement.dataset.path:void 0,M=p.pinned?[u("button",{class:"link",text:S(p.lang,"follow"),attrs:{type:"button"},on:{click:()=>n.pin(null)}})]:[],k=m?(o&&hr(p,m,o,t))??gr(p,m,n):[];r.replaceChildren(Fe(S(p.lang,"selection"),[u("span",{class:"muted",text:" ("+S(p.lang,p.pinned?"pinned":"underPlayhead")+")"}),...M]),...k),E&&r.querySelector('[data-path="'+CSS.escape(E)+'"]')?.focus(),v&&r.querySelector(".cue.current")?.scrollIntoView({block:"nearest"})},g=p=>{let m=p.state;if(!m)return;let h=p.lang;s.replaceChildren(Fe(S(h,"problems")+" ("+m.problems.length+")"),m.problems.length?u("ul",{},m.problems.map(b=>br(b,h))):u("p",{class:"muted",text:S(h,"noProblems")})),a.replaceChildren(Fe(S(h,"score")),m.score?vr(m.score,h):u("p",{class:"muted",text:S(h,"noScore")})),c.replaceChildren(Fe(S(h,"measurements")),...Sr(m,h)),i.hidden=!m.notes,i.replaceChildren(Fe(S(h,"notes")+" ("+(m.notes?.length??0)+")"),u("ul",{},(m.notes??[]).map(b=>u("li",{class:"note-item"},[u("code",{text:b.at})," ",u("b",{text:b.kind}),u("div",{text:b.message})]))))};g(t.get()),f(t.get()),t.subscribe((p,m)=>{(p.state!==m.state||p.lang!==m.lang)&&g(p),(p.state!==m.state||p.lang!==m.lang||p.pinned!==m.pinned||p.frame!==m.frame||p.edit.problems!==m.edit.problems||p.edit.schema!==m.edit.schema)&&f(p)})};var Lt=(e,t,n,o)=>{let r=Math.max(0,t.frames-1),s=o-e.start;return s<=0?Math.min(e.in,r):Math.min(r,e.in+Math.round(s*t.fps*e.speed/n))};var jn=(e,t,n=()=>{})=>{let o=[],r=(i,d)=>{let l=e.querySelector(i+" > img");l&&o.push({img:l,play:d,active:!1})};t.segments.forEach(i=>{i.base.kind==="video"&&r('[data-segment="'+CSS.escape(i.id)+'"]',i.base.play)}),t.items.forEach(i=>{i.play&&r('[data-item="'+CSS.escape(i.id)+'"]',i.play)});let s=(i,d)=>{if(i.video)return;let l=t.footage?.[i.play.material],f=i.img.parentElement;if(!l||!f)return;let g=e.createElement("video");g.muted=!0,g.playsInline=!0,g.preload="auto",g.hidden=!0,g.style.display="none",g.dataset.previewVideo=i.play.material;let p=Lt(i.play,l,t.canvas.fps,Math.max(d,i.play.start))/l.fps;i.time=p,g.addEventListener("loadedmetadata",()=>{g.paused&&g.isConnected&&(g.currentTime=i.time??p)},{once:!0}),g.src=l.src.startsWith("project/")?"/"+l.src:"/project/"+l.src.split("/").map(encodeURIComponent).join("/");let m=()=>{!i.active||!g.isConnected||f.style.display==="none"||(g.style.cssText=i.img.style.cssText+";position:absolute;inset:0;pointer-events:none;",g.hidden=!1,g.style.visibility="",i.img.style.visibility="hidden")};g.addEventListener("loadeddata",m),g.addEventListener("error",()=>{l.dir===void 0&&g.isConnected&&n(l.src.replace(/^project\\//,"").split("/").map(decodeURIComponent).join("/"))}),g.addEventListener("seeked",()=>{if(!i.playing&&i.active&&i.time!==void 0&&Math.abs(g.currentTime-i.time)>.5/l.fps){g.currentTime=i.time;return}m()}),f.append(g),i.video=g},a=i=>{i.video?.pause(),i.video?.removeAttribute("src"),i.video?.load(),i.video?.remove(),i.video=void 0,i.active=!1,i.img.style.visibility=""};return{sync:(i,d,l)=>{let f=o.filter(g=>g.play.start>i).sort((g,p)=>g.play.start-p.play.start).slice(0,2);for(let g of o)f.includes(g)||g.img.parentElement?.style.display!=="none"?s(g,i):g.video&&a(g);for(let g of o){let p=t.footage?.[g.play.material],m=g.img.parentElement;if(!((d||p?.dir===void 0)&&!!p&&!!m&&m.style.display!=="none")){g.video?.pause(),g.video&&(g.video.hidden=!0,g.video.style.display="none"),g.img.style.visibility="",g.active=!1;continue}if(!p||!m)continue;let b=g.video;b.hidden=!1,b.style.cssText=g.img.style.cssText+";position:absolute;inset:0;pointer-events:none;",g.img.style.visibility=b.readyState>=2?"hidden":"",b.style.visibility=b.readyState>=2?"":"hidden";let y=Lt(g.play,p,t.canvas.fps,i)/p.fps;g.time=y,g.playing=d;let v=l*g.play.speed;b.playbackRate=Math.max(.0625,Math.min(16,v));let E=d&&g.active?.25:.5/p.fps;!b.seeking&&Math.abs(b.currentTime-y)>E&&(b.currentTime=y),i<g.play.start||y>=(p.frames-1)/p.fps||!d?b.pause():b.paused&&b.play().catch(()=>{}),g.active=!0}},needsPictures:()=>o.some(i=>!!(i.video?.error&&t.footage?.[i.play.material]?.dir&&i.img.parentElement?.style.display!=="none")),dispose:()=>{o.forEach(a)}}};var zn=(e,t)=>{let n=u("div",{class:"caption"}),o=u("div",{class:"note"}),r=u("div",{class:"overlay"}),s=u("div",{class:"frame-box"},[t,r]);return{root:u("div",{class:"viewer",id:e},[n,s,o]),caption:n,note:o,box:s,overlay:r}},Bn=(e,t,n,o)=>Math.max(.01,Math.min(n/e,o/t)),Rt=(e,t)=>{let n=e.reference.root.isConnected,o=getComputedStyle(e.root),r=e.root.classList.contains("comparing"),s=(e.root.clientWidth-parseFloat(o.paddingLeft)-parseFloat(o.paddingRight)-(n?parseFloat(o.gap)||16:0))/(n?2:1)-(r?18:0),a=e.root.clientHeight-parseFloat(o.paddingTop)-parseFloat(o.paddingBottom)-e.render.caption.offsetHeight-e.render.note.offsetHeight-(r?32:8),c=t.state?.resolved?.canvas;if(e.render.box.classList.toggle("problems",!c),c){let g=Bn(c.width,c.height,s,a);e.render.box.style.cssText="width:"+c.width*g+"px;height:"+c.height*g+"px;",e.scaler.style.cssText="width:"+c.width+"px;height:"+c.height+"px;transform:scale("+g+");"}else e.render.box.style.cssText="width:"+Math.max(0,s)+"px;height:"+Math.max(0,a)+"px;",e.scaler.style.cssText="width:100%;height:100%;";if(!n)return;let i=t.state?.referenceMeasure?.measure.source,d=e.video.videoWidth||i?.width||c?.width||16,l=e.video.videoHeight||i?.height||c?.height||9,f=Bn(d,l,s,a);e.reference.box.style.cssText="width:"+d*f+"px;height:"+l*f+"px;"},Vn=(e,t,n,o)=>{if(t)for(let r of Dt(t,n,o))e.append(le(u("div",{class:"ebox"},[u("span",{text:ze(r)})]),r.box))},xr=(e,t,n)=>{let o=t.state;if(e.render.overlay.replaceChildren(),e.reference.overlay.replaceChildren(),!o?.resolved)return;let r=se(o);if(t.overlays.safe)for(let s of[e.render.overlay,e.reference.overlay])s.append(le(u("div",{class:"safe"}),zt(o.resolved.canvas)));if(t.overlays.boxes)for(let s of fe(o.resolved,t.frame))e.render.overlay.append(le(u("div",{class:"ibox",title:s.id,on:{click:()=>n.pin({kind:"item",id:s.id})}},[u("span",{text:s.id})]),s.box));t.overlays.events&&(Vn(e.render.overlay,o.measure?.measure,t.frame,r),Vn(e.reference.overlay,o.referenceMeasure?.measure,t.frame,r))},Er=(e,t)=>{let n=t.state?.resolved?.canvas,o=!!(t.state&&!t.state.resolved);e.render.caption.textContent=S(t.lang,t.state?.edit?"currentVideo":"render")+(n?" "+n.width+"x"+n.height+", "+n.fps+" fps":""),e.render.note.textContent=o?S(t.lang,"errorsOnStage"):t.pageError?S(t.lang,"imageFailed")+": "+t.pageError:"",e.render.note.classList.toggle("error",o||!!t.pageError);let r=t.edit.playRender&&t.edit.render?.state==="done"?t.edit.render:void 0;e.reference.caption.textContent=r?S(t.lang,"renderFile")+" "+(r.file.split(/[\\\\/]/).pop()??""):S(t.lang,"reference")+(t.state?.reference?" "+t.state.reference.name:""),e.reference.note.textContent=S(t.lang,"seekNote")},_n=(e,t,n,o)=>{if(!t.state||!e.getAttribute("src"))return;let r=(t.frame+.25)/se(t.state);if(!t.playing){e.paused||e.pause(),(o||n.playing||Math.abs(e.currentTime-r)>.001)&&(e.currentTime=r);return}e.playbackRate=t.speed,o||!n.playing||n.speed!==t.speed?(e.currentTime=r,e.play().catch(()=>{})):!e.seeking&&Math.abs(e.currentTime-r)>.2&&(e.currentTime=r)},wr=(e,t)=>{let n,o=-1,r=0,s=0,a,c,i=()=>{let l=n;if(!l)return;let f=t.get(),g=f.frame,p=++s;(l.preparePreview?.(g)??Promise.resolve()).then(async()=>{p===s&&(f.playing&&l.previewFrame&&a&&!a.needsPictures()?l.previewFrame(g):l.applyFrame(g),a?.sync(g,f.playing,f.speed),await l.settle())}).then(()=>null,h=>h instanceof Error?h.message:String(h)).then(h=>{if(p!==s)return;h!==null&&h!==t.get().pageError&&t.set({pageError:h}),document.body.dataset.applied=String(g),e.dispatchEvent(new Event("frameapplied"));let b=t.get().state?.resolved,y=b?Z(b,g)?.id:void 0;h===null&&y!==c&&(c=y,document.dispatchEvent(new Event("studio:scene-ready")))})};return e.addEventListener("load",()=>{let l=++r,f=e.contentWindow?.__popostVideo;if(n=void 0,c=void 0,!f){document.body.dataset.ready="error";return}(f.preparePreview?.(t.get().frame)??f.prepare()).then(()=>null,p=>p instanceof Error?p.message:String(p)).then(p=>{if(l!==r)return;n=f;let m=t.get().state?.resolved;p!==t.get().pageError&&t.set({pageError:p}),m&&e.contentDocument&&(a=jn(e.contentDocument,m,h=>{l===r&&t.set({pageError:h})})),i(),document.body.dataset.ready="1",document.dispatchEvent(new Event("studio:page-ready"))})}),{load:l=>{o=l,s++,a?.dispose(),a=void 0,n=void 0,document.body.dataset.ready="",e.src="/page?g="+l},apply:i,loaded:()=>o}},kr=e=>{let t=e.edit.render;return e.edit.playRender&&t?.state==="done"?t.url:e.compare!==!1&&e.state?.reference?e.state.reference.url??"/reference":""},dt=(e,t,n)=>{let o=u("iframe",{id:"page",attrs:{title:"page",tabindex:"-1"}}),r=u("div",{class:"scaler"},[o]),s=u("video",{id:"reference-video",attrs:{preload:"auto",playsinline:"",tabindex:"-1"}});s.muted=!0;let a={root:e,render:zn("render-view",r),reference:zn("reference-view",s),iframe:o,scaler:r,video:s};e.append(a.render.root);let c=wr(o,t);new ResizeObserver(()=>Rt(a,t.get())).observe(e),s.addEventListener("loadedmetadata",()=>{Rt(a,t.get()),_n(s,t.get(),t.get(),!0)});let i="";return t.subscribe((d,l)=>{let f=kr(d);if(f!==i){i=f,f&&!a.reference.root.isConnected&&e.append(a.reference.root),f||a.reference.root.remove(),f?s.src=f:s.removeAttribute("src");let g=!!(f&&!d.edit.playRender);e.classList.toggle("comparing",g),a.reference.root.style.order=g?"-1":""}d.state&&d.state.generation!==c.loaded()&&c.load(d.state.generation),(d.frame!==l.frame||d.playing!==l.playing||d.speed!==l.speed)&&c.apply(),(d.frame!==l.frame||d.overlays!==l.overlays||d.state!==l.state)&&xr(a,d,n),(d.frame!==l.frame||d.playing!==l.playing||d.speed!==l.speed)&&_n(s,d,l,!1),(d.compare!==l.compare||d.lang!==l.lang||d.state!==l.state||d.pageError!==l.pageError||d.edit!==l.edit)&&(Er(a,d),Rt(a,d))}),{frameBox:a.render.box,iframe:o}};var Ee=(e,t,n,o,r)=>{let s=u("button",{id:t,class:"tbtn",attrs:{type:"button"}},[o]);return s.addEventListener("click",()=>{r(),s.blur()}),e.buttons.push({el:s,title:n}),s},Mr=e=>{let t=u("input",{id:"jump",attrs:{type:"text",inputmode:"numeric",autocomplete:"off"}});return t.addEventListener("keydown",n=>{if(n.key!=="Enter")return;let o=Number(t.value.trim()),r=t.value.trim()!==""&&Number.isInteger(o);t.setAttribute("aria-invalid",String(!r)),r&&(e.pause(),e.seek(o),t.value="",t.blur())}),t},Tr=e=>{let t=u("select",{id:"speed"},_t.map(n=>u("option",{text:n+"x",attrs:{value:String(n)}})));return t.value="1",t.addEventListener("change",()=>{e.setSpeed(Number(t.value)),t.blur()}),t},Lr=(e,t)=>{let n=[],o=c=>()=>{t.pause(),c()},r=u("span",{class:"icon"},[Y("play")]),s=u("input",{id:"slider",attrs:{type:"range",min:"0",max:"0",step:"1",value:"0","aria-label":"frame"}});s.addEventListener("input",()=>t.seek(Number(s.value)));let a={buttons:n,playIcon:r,slider:s,play:Ee({buttons:n},"play","play",r,()=>t.togglePlay()),frameLabel:u("span",{class:"muted"}),frameNo:u("span",{id:"frame-no",class:"num"}),frameOf:u("span",{class:"num muted"}),time:u("span",{id:"time",class:"num muted"}),speedLabel:u("label",{class:"muted",attrs:{for:"speed"}}),speed:Tr(t),jump:Mr(t)};return e.append(Ee(a,"first","first",Y("first"),o(()=>t.seek(0))),Ee(a,"back10","back10","\\u221210",o(()=>t.step(-10))),Ee(a,"back1","back1","\\u22121",o(()=>t.step(-1))),a.play,Ee(a,"fwd1","fwd1","+1",o(()=>t.step(1))),Ee(a,"fwd10","fwd10","+10",o(()=>t.step(10))),Ee(a,"last","last",Y("last"),o(()=>t.seek(Number.MAX_SAFE_INTEGER))),u("div",{class:"slider-wrap"},[s]),u("span",{class:"readout"},[u("span",{},[a.frameLabel,a.frameNo,a.frameOf]),a.time]),u("span",{class:"speed"},[a.speedLabel,a.speed]),a.jump),a},Kn=(e,t,n)=>{let o=t.state?W(t.state):0,r=t.state?se(t.state):30;e.slider.max=String(Math.max(0,o-1)),e.slider.value=String(t.frame),e.frameNo.textContent=String(t.frame),e.frameOf.textContent=" / "+Math.max(0,o-1),e.time.textContent=pt(t.frame,r)+" / "+pt(o,r),!(n&&t.playing===n.playing&&t.lang===n.lang)&&(e.playIcon.replaceChildren(Y(t.playing?"pause":"play")),e.buttons.forEach(s=>{s.el.title=S(t.lang,s.el===e.play?t.playing?"pause":"play":s.title)}),e.frameLabel.textContent=S(t.lang,"frame")+" ",e.speedLabel.textContent=S(t.lang,"speed")+" ",e.jump.placeholder=S(t.lang,"jump"),e.jump.title=S(t.lang,"jumpHint"))},Rr=(e,t)=>{let n=e.target;if(e.defaultPrevented||n?.tagName==="SELECT"||n?.tagName==="TEXTAREA"||n instanceof HTMLInputElement&&(n.type==="text"||n.type==="number")||e.altKey||e.ctrlKey||e.metaKey)return;let r={" ":()=>t.togglePlay(),ArrowLeft:()=>{t.pause(),t.step(e.shiftKey?-10:-1)},ArrowRight:()=>{t.pause(),t.step(e.shiftKey?10:1)},Home:()=>{t.pause(),t.seek(0)},End:()=>{t.pause(),t.seek(Number.MAX_SAFE_INTEGER)}}[e.key];r&&(e.preventDefault(),r())},lt=(e,t,n)=>{let o=Lr(e,n);Kn(o,t.get(),void 0),t.subscribe((r,s)=>{(r.frame!==s.frame||r.state!==s.state||r.playing!==s.playing||r.lang!==s.lang)&&Kn(o,r,s)}),document.addEventListener("keydown",r=>Rr(r,n))};var Pt=e=>{let t=e.store.get(),n=t.state?.resolved,o=t.pinned,r=o?.kind==="item"?n?.items.find(s=>s.id===o.id):void 0;return n?n.segments.find(s=>(o?.kind==="segment"||o?.kind==="slot")&&s.id===o.id)??(r?Z(n,r.start):void 0)??Z(n,t.frame):void 0},Jn=(e,t)=>{let n=e.store.get().state?.resolved?.segments.find(o=>o.id===t);n&&(e.actions.pause(),e.actions.seek(Math.min(n.end-1,n.start+Math.floor((n.end-n.start)*.3))),e.edit.select({kind:"segment",id:t}))},At=e=>{let{store:t,edit:n}=e,o=t.get().state,r=o?.resolved,s=u("div",{class:"studio-shot-list"});if(r)for(let c of r.segments){let i=c.base,d=i.kind==="scene"?x(t,"scene"):i.kind==="video"?x(t,"video"):i.kind==="image"?x(t,"image"):x(t,"color"),l=C("",()=>Jn(e,c.id),"studio-shot "+(ge(t.get().pinned,{kind:"segment",id:c.id})?"selected":""));l.append(sn(c.start+Math.floor((c.end-c.start)/2),o?.generation??0),u("span",{class:"studio-shot-copy"},[u("strong",{text:String(c.index+1).padStart(2,"0")+" "+c.id}),u("small",{text:d+" \\xB7 "+((c.end-c.start)/r.canvas.fps).toFixed(2)+"s"})])),l.dataset.selection=JSON.stringify({kind:"segment",id:c.id}),l.draggable=!!o?.edit,l.addEventListener("dragstart",f=>f.dataTransfer?.setData("application/x-popost-segment",String(c.index))),l.addEventListener("dragover",f=>f.preventDefault()),l.addEventListener("drop",f=>{f.preventDefault();let g=Number(f.dataTransfer?.getData("application/x-popost-segment"));Number.isInteger(g)&&g!==c.index&&n.send({op:"move",path:["segments",g],to:c.index})}),s.append(l)}let a=Oe("",x(t,"search"));return a.placeholder=x(t,"search"),a.addEventListener("input",()=>s.querySelectorAll(".studio-shot").forEach(c=>{c.hidden=!c.textContent?.toLowerCase().includes(a.value.toLowerCase())})),u("div",{class:"studio-side-body"},[U(x(t,"shots"),String(r?.segments.length??0)),a,s,A(x(t,"keepRhythm"))])},Un=async(e,t,n)=>{let{store:o,edit:r}=e,s=o.get().state,a=Pt(e);if(!s||!a)return;let c=t.kind,i=String(t.id);if(!n&&["image","video"].includes(String(c))){await r.send({op:"set",path:["segments",a.index,"base"],value:{material:i,fit:"cover"}});return}let d=$(G(s.source).tracks),l=["audio","voice","speech"].includes(String(c))?"audio":c;if(!["image","video","audio"].includes(String(l)))return;let f={id:"overlay-"+Date.now(),type:l,material:i,...l==="audio"?{gain:0}:{box:[.1,.1,.8,.6],fit:"contain"},during:{segment:a.id,from:0,to:a.end-a.start}};await r.send({op:"insert",path:["tracks",d.length],value:f},{kind:l==="audio"?"audio":"item",id:f.id})},Wn=e=>{let{store:t}=e,n=u("div",{class:"studio-resource-tabs"}),o=u("div"),r=()=>{n.replaceChildren(...["shots","files"].map(s=>C(x(t,s==="shots"?"shots":"sourceFile"),()=>{e.mediaView=s,r()},(e.mediaView??"shots")===s?"selected":""))),o.replaceChildren(n,(e.mediaView??"shots")==="shots"?At(e):Pr(e))};return r(),o},Pr=e=>{let{store:t}=e,n=t.get().state,o=u("input",{attrs:{type:"file",accept:"image/png,image/jpeg,image/webp,video/mp4,video/webm,video/quicktime,audio/*",hidden:""}});o.addEventListener("change",()=>{let s=o.files?.[0];if(!s)return;if(s.size>12*1024*1024){ce(t,x(t,"importHint"));return}let a=new FileReader;a.onload=()=>{ke(t,"/api/studio/import",{name:s.name,data:String(a.result).split(",")[1]})},a.readAsDataURL(s)});let r=u("div",{class:"studio-media-list"});for(let s of $(G(n?.source).materials)){let a=String(s.note??s.file??s.id),c=Ce(String(s.file??"")),i=s.kind==="image"?u("img",{attrs:{src:c,alt:a,loading:"lazy"}}):s.kind==="video"?u("video",{attrs:{src:c,controls:"",preload:"metadata"}}):u("audio",{attrs:{src:c,controls:"",preload:"none"}}),d=u("div",{class:"studio-actions"},[C(x(t,"addOverlay"),()=>{Un(e,s,!0)})]);["image","video"].includes(String(s.kind))&&d.prepend(C(x(t,"applyShot"),()=>{Un(e,s,!1)})),r.append(u("article",{class:"studio-media-card"},[i,u("strong",{text:a,title:a}),A(String(s.kind)),d]))}return r.children.length||r.append(A(x(t,"noMedia"))),u("div",{class:"studio-side-body"},[U(x(t,"media")),C(x(t,"upload"),()=>o.click(),"primary"),o,A(x(t,"importHint")),A(x(t,"chooseMaterial")),r])},qn=e=>{let{store:t,edit:n}=e,o=t.get().state,r=u("div",{class:"studio-script-list"}),s=[];return $(G(o?.source).tracks).forEach((a,c)=>{a.type==="caption"&&$(a.cues).forEach((i,d)=>{s.push(String(i.text));let l=o?.resolved?.items.find(b=>b.cue?.track===a.id&&b.cue?.index===d),f=u("textarea",{class:"studio-input",attrs:{"aria-label":x(t,"subtitles")+" "+(d+1),rows:"2"}});f.value=String(i.text),f.addEventListener("change",()=>{n.send({op:"set",path:["tracks",c,"cues",d,"text"],value:f.value}),ce(t,x(t,"pendingVoice"))});let g=l?{kind:"item",id:l.id}:void 0,p=()=>{g&&n.reveal(g)};f.addEventListener("focus",p);let m=C(Ze(l?.start??0,o?.resolved?.canvas.fps??30),p),h=u("article",{class:"studio-sentence"+(g&&ge(g,t.get().pinned)?" selected":""),data:g?{selection:JSON.stringify(g)}:{}},[m,f]);h.addEventListener("click",p),r.append(h)})}),u("div",{class:"studio-side-body"},[U(x(t,"script")),A(x(t,"scriptHint"),"notice"),r,A(x(t,"narrationUnavailable")),C(x(t,"copyScript"),()=>{navigator.clipboard.writeText(s.join(\`
38024
+ \`)).then(()=>ce(t,x(t,"sourceChanged")))})])},Gn=e=>{let{store:t,edit:n}=e,o=t.get().state,r=Pt(e),s=u("div",{class:"studio-side-body"},[U(x(t,"elements"),r?.id)]);if(!o||!r)return s;s.append(C(x(t,"addText"),()=>{n.addText()}));for(let i of o.resolved?.items.filter(d=>d.end>r.start&&d.start<r.end)??[]){let d={kind:"item",id:i.id},l=C(i.text??x(t,i.type==="video"?"video":i.type==="image"?"image":i.type==="shape"?"color":"text"),()=>n.reveal(d),"studio-item"+(ge(d,t.get().pinned)?" selected":""));l.dataset.selection=JSON.stringify(d),s.append(l)}for(let i of o.resolved?.audio??[]){let d={kind:"audio",id:i.id},l=C(x(t,"audioTrack")+" \\xB7 "+i.id,()=>n.reveal(d),"studio-item"+(ge(d,t.get().pinned)?" selected":""));l.dataset.selection=JSON.stringify(d),s.append(l)}let a=He(document.querySelector("#page"),t,r.id),c=e.meta.slots.filter(i=>i.segment===r.id&&a?.has(i.name));s.append(U(x(t,"sceneFields")));for(let i of c){let d=t.get().pinned,l={kind:"slot",id:r.id,name:i.name},f=C("",()=>n.reveal(l,Qe(document.querySelector("#page"),t,l)),"studio-item "+(d?.kind==="slot"&&d.name===i.name?"selected":""));f.dataset.selection=JSON.stringify(l),f.append(u("span",{class:"studio-element-label",text:i.kind==="image"?x(t,"image"):i.value||i.name,title:i.value})),s.append(f)}return!c.length&&r.base.kind==="scene"&&s.append(A(x(t,"noSlots"))),s},Yn=e=>{let{store:t,actions:n}=e,o=t.get(),r=u("div",{class:"studio-side-body"},[U(x(t,"checks"))]);for(let a of o.state?.problems??[]){let c=u("article",{class:"studio-review-card"},[u("strong",{text:a.at}),A(a.message),A(a.fix??"")]),i=/^segments\\[(\\d+)\\]/.exec(a.at),d=i?o.state?.resolved?.segments[Number(i[1])]:void 0;d&&c.append(C(x(t,"goShot"),()=>Jn(e,d.id))),r.append(c)}o.state?.problems.length||r.append(A(x(t,"noProblems"))),r.append(A(o.state?.score?JSON.stringify(Object.fromEntries(Object.entries(o.state.score.dimensions).map(([a,c])=>[a,c.score.toFixed(2)]))):x(t,"unmeasured"))),r.append(U(x(t,"notes")));for(let a of e.meta.comments)r.append(u("article",{class:"studio-review-card"},[C(Ze(a.frame,o.state?.resolved?.canvas.fps??30),()=>{n.pause(),n.seek(a.frame)}),A(a.text),C(x(t,a.resolved?"reopen":"resolve"),()=>{ke(t,"/api/studio/comment",{id:a.id,resolved:!a.resolved}).then(e.refresh)})]));let s=u("textarea",{class:"studio-input",attrs:{rows:"3",placeholder:x(t,"noteHint")}});return r.append(s,C(x(t,"comment"),()=>{s.value.trim()&&ke(t,"/api/studio/comment",{text:s.value,frame:t.get().frame}).then(e.refresh)}),C(x(t,"copyNote"),()=>{navigator.clipboard.writeText(Ze(t.get().frame,o.state?.resolved?.canvas.fps??30)+" \\xB7 "+(Pt(e)?.id??"")+\`
38025
+ \`+s.value)}),A(x(t,"reviewOnly"))),r},Xn=e=>{let{store:t}=e,n=u("div",{class:"studio-side-body"},[U(x(t,"versions"))]),o=Oe("",x(t,"versionName"));o.placeholder=x(t,"versionName"),n.append(o,C(x(t,"saveVersion"),()=>{ke(t,"/api/studio/version",{name:o.value||x(t,"newVersion")}).then(e.refresh)},"primary"),A(x(t,"versionSnapshot")));for(let r of e.meta.versions)n.append(u("article",{class:"studio-review-card"},[u("strong",{text:r.name}),A(new Date(r.created).toLocaleString()),...r.hash===e.meta.hash?[A(x(t,"current"))]:[C(x(t,"restore"),()=>{ke(t,"/api/studio/restore",{id:r.id,base:t.get().state?.source}).then(e.refresh)})]]));return e.meta.versions.length||n.append(A(x(t,"noVersions"))),n},Zn=()=>J("/api/studio");var Qn=(e,t)=>{let n=u("textarea",{id:"studio-json",class:"studio-json",attrs:{spellcheck:"false","aria-label":"video.json"}}),o=u("div",{class:"studio-code-status",attrs:{role:"status"}}),r,s,a=!1,c=!1,i,d=()=>{s=e.get().state?.source,n.value=JSON.stringify(s,null,2)??"",a=!1,o.textContent=x(e,"autosave")},l=async()=>{if(!a||c)return;let m;try{m=JSON.parse(n.value)}catch(y){o.textContent=x(e,"invalid")+": "+(y instanceof Error?y.message:"");return}c=!0,o.textContent=x(e,"saving");let h=n.value,b=await t.replace(m,s);c=!1,b?(s=e.get().state?.source,a=h!==n.value,o.textContent=x(e,"sourceChanged"),a&&setTimeout(()=>{f()},0)):o.textContent=e.get().edit.problems[0]?.message??x(e,"conflict")},f=()=>r??=l().finally(()=>{r=void 0});n.addEventListener("input",()=>{a=!0,i&&clearTimeout(i),i=setTimeout(()=>{f()},650)}),n.addEventListener("keydown",m=>{(m.ctrlKey||m.metaKey)&&m.key.toLowerCase()==="s"&&(m.preventDefault(),f()),m.key==="Tab"&&(m.preventDefault(),n.setRangeText(" ",n.selectionStart,n.selectionEnd,"end"),n.dispatchEvent(new Event("input")))}),window.addEventListener("beforeunload",m=>{a&&(m.preventDefault(),m.returnValue="")});let g=()=>{try{n.value=JSON.stringify(JSON.parse(n.value),null,2),n.dispatchEvent(new Event("input"))}catch{o.textContent=x(e,"invalid")}},p=u("div",{class:"studio-code-wrap"},[U(x(e,"sourceTitle"),"video.json"),A(x(e,"codeHint")),u("div",{class:"studio-actions"},[C(x(e,"format"),g),C(x(e,"download"),()=>rn(n.value,"video.json"))]),n,o,C(x(e,"reload"),d)]);return e.subscribe((m,h)=>{m.state?.source!==h.state?.source&&(!a&&!c?d():!c&&JSON.stringify(m.state?.source)!==JSON.stringify(s)&&(o.textContent=x(e,"conflict")))}),d(),{root:p,flush:async()=>(clearTimeout(i),r&&await r,a&&await f(),!a)}};var $n=(e,t,n)=>{let o=t.get().lang==="zh",r=(O,D)=>o?O:D,s=u("div",{class:"studio-cloud",id:"studio-cloud",attrs:{"aria-live":"polite"}});e.append(s);let a,c,i,d="push",l="",f="",g=!1,p=!1,m=!0,h,b=O=>({UNAUTHORIZED:r("\\u767B\\u5F55\\u5DF2\\u8FC7\\u671F\\u6216\\u5DF2\\u4F7F\\u7528\\uFF0C\\u8BF7\\u91CD\\u65B0\\u70B9\\u51FB\\u201C\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF\\u201D\\u3002","The login expired or was already used. Save to Cloud again."),LOGIN_REQUIRED:r("\\u8BF7\\u5148\\u767B\\u5F55\\uFF0C\\u518D\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF\\u3002","Sign in to save to cloud."),STORAGE_FULL:r("\\u4E91\\u7AEF\\u5B58\\u50A8\\u7A7A\\u95F4\\u5DF2\\u6EE1\\u3002","Your cloud storage is full."),STORAGE_QUOTA_EXCEEDED:r("\\u4E91\\u7AEF\\u5B58\\u50A8\\u7A7A\\u95F4\\u5DF2\\u6EE1\\u3002","Your cloud storage is full."),RATE_LIMITED:r("\\u4E0A\\u4F20\\u8FC7\\u4E8E\\u9891\\u7E41\\uFF0C\\u8BF7\\u7A0D\\u540E\\u518D\\u8BD5\\u3002","Too many uploads. Try again in a moment."),DECK_INVALID:r("\\u4E91\\u7AEF\\u65E0\\u6CD5\\u63A5\\u6536\\u8FD9\\u4E2A\\u4F5C\\u54C1\\u3002","The cloud could not accept this project."),NETWORK:r("\\u65E0\\u6CD5\\u8FDE\\u63A5 popost.ai\\u3002","Could not reach popost.ai."),LOCAL_SAVE_FAILED:r("\\u672C\\u5730\\u6539\\u52A8\\u4FDD\\u5B58\\u5931\\u8D25\\u3002\\u8BF7\\u5148\\u4FDD\\u5B58\\u4F5C\\u54C1\\uFF0C\\u518D\\u4E0A\\u4F20\\u5230\\u4E91\\u7AEF\\u3002","Could not save local edits. Save the project before uploading.")})[O??""]??r("\\u4E0A\\u4F20\\u5931\\u8D25\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u3002","Upload failed. Try again."),y=(O,D=!1)=>u("span",{class:"studio-cloud-state"+(D?" bad":""),text:O,attrs:{role:"status"},title:c?.message??a?.error?.message??O}),v=()=>a?.webUrl?[u("a",{class:"studio-btn studio-icon-btn",attrs:{href:a.webUrl,target:"_blank",rel:"noopener noreferrer",title:r("\\u5728 popost \\u6253\\u5F00","Open in popost"),"aria-label":r("\\u5728 popost \\u6253\\u5F00","Open in popost")}},[Y("external")])]:[],E=O=>{c={code:"NETWORK",message:O instanceof Error?O.message:String(O)}},M=async()=>{try{a=await J("/api/cloud/status")}catch{}m&&(F(),clearTimeout(h),h=setTimeout(()=>{M()},i||a?.state==="waiting"||a?.state==="uploading"?2e3:5e3))},k=async()=>{if(i)return;let O=window.open("about:blank","_blank");d="start",c=void 0,p=!1,i="start",F();try{if(!await n()){O?.close(),c={code:"LOCAL_SAVE_FAILED",message:""};return}f=(await J("/api/studio/cloud/start",{lang:t.get().lang})).result.authorizeUrl,g=!O,O&&(O.opener=null,O.location.href=f),d="push",await M()}catch(D){O?.close(),E(D)}finally{i=void 0,await M()}},H=async(O=!1)=>{if(!i){d="push",c=void 0,i="push",F();try{if(!await n()){c={code:"LOCAL_SAVE_FAILED",message:""};return}a=(await J("/api/studio/cloud/push",{lang:t.get().lang,force:O})).result,!a.ok&&a.error?.code==="LOGIN_REQUIRED"&&(i=void 0,await k())}catch(D){E(D)}finally{i=void 0,await M()}}},L=async()=>{try{await navigator.clipboard.writeText(f),p=!0}catch{g=!0}F()},R=()=>{let O=c?.code??a?.error?.code;d==="start"||a?.mode==="anonymous"&&(O==="LOGIN_REQUIRED"||O==="UNAUTHORIZED")?k():H()},F=()=>{let O=JSON.stringify([a,c,i,f,g,p]);if(O===l||(l=O,s.hidden=a?.mode==="off",s.replaceChildren(),s.hidden))return;let D=i==="push"?"uploading":i==="start"?"starting":c?"failed":a?.state??"idle";if(D==="uploading"||D==="starting")s.append(y(D==="starting"?r("\\u7B49\\u5F85\\u767B\\u5F55\\u2026","Waiting for login\\u2026"):a?.mode==="keyed"?r("\\u540C\\u6B65\\u4E2D\\u2026","Syncing\\u2026"):r("\\u4E0A\\u4F20\\u4E2D\\u2026","Uploading\\u2026")));else if(D==="waiting"){if(s.append(y(r("\\u7B49\\u5F85\\u767B\\u5F55\\u2026","Waiting for login\\u2026")),ne(p?r("\\u94FE\\u63A5\\u5DF2\\u590D\\u5236","Link copied"):r("\\u590D\\u5236\\u94FE\\u63A5","Copy link"),"duplicate",()=>{L()})),g&&f){let w=u("input",{class:"studio-cloud-link",attrs:{readonly:"","aria-label":r("\\u767B\\u5F55\\u94FE\\u63A5","Login link")}});w.value=f,w.addEventListener("focus",()=>w.select()),s.append(w)}}else if(D==="saved")s.append(y(a?.mode==="keyed"?r("\\u5DF2\\u540C\\u6B65","Synced"):r("\\u5DF2\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF","Saved to cloud")),...v());else if(D==="failed")s.append(y(b(c?.code??a?.error?.code),!0),ne(r("\\u91CD\\u8BD5","Retry"),"refresh",R));else if(D==="conflict"){if(s.append(y(r("\\u7F51\\u9875\\u7AEF\\u5DF2\\u6709\\u4FEE\\u6539","Edited on the web"),!0),...v()),a?.mode==="keyed"){let w=ne(r("\\u8986\\u76D6","Overwrite"),"cloud",()=>{H(!0)});w.title=r("\\u7528\\u672C\\u5730\\u7248\\u672C\\u66FF\\u6362\\u7F51\\u9875\\u7AEF\\u7684\\u7248\\u672C","Replace the web copy with this local version"),s.append(w)}}else if(!a)s.append(y(r("\\u6B63\\u5728\\u68C0\\u67E5\\u8D26\\u53F7\\u2026","Checking account\\u2026")));else{let w=ne(a?.mode==="keyed"?r("\\u7ACB\\u5373\\u540C\\u6B65","Sync now"):a?.webUrl&&a.dirty?r("\\u672C\\u5730\\u6539\\u52A8\\u672A\\u4E0A\\u4F20","Local changes not uploaded"):r("\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF","Save to Cloud"),"cloud",()=>{a?.mode==="keyed"?H():k()});w.id="studio-cloud-save",w.disabled=!a,w.title=r("\\u5728 popost \\u7F51\\u9875\\u7AEF\\u7BA1\\u7406\\u4F60\\u7684\\u6240\\u6709\\u8D44\\u4EA7","Manage all your assets on the Popost website"),s.append(w)}};t.subscribe((O,D)=>{O.state?.source!==D.state?.source&&M()}),window.addEventListener("pagehide",()=>{m=!1,clearTimeout(h)}),F(),M()};var ct=(e,t,n)=>{if(t.kind==="segment"||t.track.type==="audio"||!T(e.source))return;let o=ee(e),r=o.map((m,h)=>({track:m,index:h})).filter(m=>m.track.type!=="audio").sort((m,h)=>Number(m.track.z??m.index)-Number(h.track.z??h.index)||m.index-h.index),s=e.resolved?.items.filter(m=>m.id===t.track.id||m.cue?.track===t.track.id)??[],a=new Set((e.resolved?.items??[]).filter(m=>s.some(h=>h.start<m.end&&h.end>m.start)).map(m=>m.cue?.track??m.id)),c=r.filter(m=>a.has(String(m.track.id))),i=c.findIndex(m=>m.index===t.index),d=c[i+n];if(!d)return;let l=r.findIndex(m=>m.index===t.index),f=r.indexOf(d);if(l<0||f<0||f>=r.length)return;let g=r.splice(l,1)[0];r.splice(f,0,g);let p=new Map(r.map((m,h)=>[m.index,h]));return{...e.source,tracks:o.map((m,h)=>p.has(h)?{...m,z:p.get(h)}:m)}};var eo=(e,t,n)=>{let o=u("input",{attrs:{type:"range",min:"100",max:"500",value:"100","aria-label":x(t,"zoom")}}),r=()=>e.parentElement?.style.setProperty("--timeline-zoom",String(Number(o.value)/100));o.addEventListener("input",r),r();let s=t.get().lang==="zh",a=(h,b)=>{let y=C(b,()=>{let v=t.get().timeline??{layers:!0,snapping:!0};t.set({timeline:{...v,[h]:!v[h]}})});return y.id="timeline-"+h,y},c=a("layers",s?"\\u56FE\\u5C42":"Layers");c.prepend(Y("layers"));let i=a("snapping",s?"\\u5438\\u9644":"Snap"),d=C(s?"\\u5206\\u5272":"Split",()=>{n.split()});d.id="edit-split";let l=h=>C(h<0?s?"\\u524D\\u79FB":"Earlier":s?"\\u540E\\u79FB":"Later",()=>{let b=n.target(),y=t.get().state;if(!(!y||!b))if(b.kind==="segment")n.send({op:"move",path:["segments",b.index],to:b.index+h});else{let v=ct(y,b,h);v&&n.replace(v,y.source)}}),f=l(-1),g=l(1);f.id="scene-earlier",g.id="scene-later";let p=u("span",{id:"timeline-selection",class:"timeline-selection"});e.append(u("span",{id:"edit-slot"}),d,f,g,u("span",{class:"timeline-divider"}),c,i,p,u("span",{class:"spacer"}),C(x(t,"viewAll"),()=>{o.value="100",r()}),o);let m=()=>{let h=t.get(),b=n.target();c.classList.toggle("selected",h.timeline?.layers!==!1),i.classList.toggle("selected",h.timeline?.snapping!==!1),c.setAttribute("aria-pressed",String(h.timeline?.layers!==!1)),i.setAttribute("aria-pressed",String(h.timeline?.snapping!==!1)),d.disabled=!!h.edit.saving||!n.canSplit(),f.hidden=g.hidden=!b||b.kind!=="segment"&&b.track.type==="audio",f.textContent=b?.kind==="segment"?s?"\\u524D\\u79FB":"Earlier":s?"\\u4E0B\\u79FB\\u56FE\\u5C42":"Send backward",g.textContent=b?.kind==="segment"?s?"\\u540E\\u79FB":"Later":s?"\\u4E0A\\u79FB\\u56FE\\u5C42":"Bring forward",f.disabled=b?.kind==="segment"?b.index===0:!(h.state&&b&&ct(h.state,b,-1)),g.disabled=b?.kind==="segment"?b.index>=(h.state?.resolved?.segments.length??0)-1:!(h.state&&b&&ct(h.state,b,1)),h.edit.saving&&(f.disabled=g.disabled=!0);let y=h.pinned,v=y?.kind==="slot"?h.slots?.find(M=>M.segment===y.id&&M.name===y.name):void 0,E=y?.kind==="item"?h.state?.resolved?.items.find(M=>M.id===y.id):void 0;p.textContent=y?y.kind==="slot"?v?.kind==="image"?s?"\\u56FE\\u7247":"Image":v?.value??x(t,"selected"):E?.text??(b?.kind==="segment"?(s?"\\u955C\\u5934 ":"Shot ")+(b.index+1):y.kind==="audio"?x(t,"audioTrack"):x(t,"selected")):s?"\\u70B9\\u9009\\u955C\\u5934\\u6216\\u753B\\u9762\\u5185\\u5BB9\\u8FDB\\u884C\\u7F16\\u8F91":"Select a shot or canvas element to edit",p.title=p.textContent};t.subscribe((h,b)=>{h.state!==b.state||h.pinned!==b.pinned||h.timeline!==b.timeline||h.slots!==b.slots||h.edit.saving!==b.edit.saving?m():h.frame!==b.frame&&(d.disabled=!!h.edit.saving||!n.canSplit())}),m()};var to=(e,t)=>{let n=e.get().lang==="zh",o=(h,b)=>n?h:b,r=t.target==="jianying"?o("\\u526A\\u6620\\u4E13\\u4E1A\\u7248","Jianying Pro"):"CapCut",s=!1,a=()=>{s||(i.remove(),c.remove(),document.getElementById("studio-export-open")?.focus())},c=u("div",{class:"studio-scrim",on:{click:a}}),i=u("aside",{class:"studio-export studio-draft-success",attrs:{role:"dialog","aria-modal":"true","aria-label":o("\\u5DF2\\u5BFC\\u5165","Imported into ")+r}}),d=A(t.productRunning?o("\\u91CD\\u542F"+r+"\\u5373\\u53EF\\u5728\\u672C\\u5730\\u8349\\u7A3F\\u770B\\u5230\\u300C"+t.name+"\\u300D\\u3002","Restart "+r+" to find \\u201C"+t.name+"\\u201D in local drafts."):o("\\u5DF2\\u4FDD\\u5B58\\u5230\\u672C\\u673A\\u8349\\u7A3F\\uFF0C\\u6253\\u5F00"+r+"\\u5373\\u53EF\\u67E5\\u770B\\u300C"+t.name+"\\u300D\\u3002","Open "+r+" to find \\u201C"+t.name+"\\u201D in local drafts.")),l=u("div",{attrs:{role:"status"}}),f=C(o("\\u7A0D\\u540E","Later"),a),g=C("\\xD7",a);g.setAttribute("aria-label",o("\\u5173\\u95ED","Close"));let p=t.productRunning?o("\\u91CD\\u542F","Restart ")+r:o("\\u6253\\u5F00","Open ")+r,m=C(p,()=>{(async()=>{s=!0,m.disabled=f.disabled=g.disabled=!0,m.textContent=o("\\u6B63\\u5728\\u6253\\u5F00\\u2026","Opening\\u2026"),l.replaceChildren();try{let h=await J("/api/studio/draft-open",{receiptId:t.receiptId});if(!h.result.ok){l.replaceChildren(A(h.result.quitPending?o(r+"\\u8FD8\\u672A\\u9000\\u51FA\\uFF0C\\u8BF7\\u5148\\u5728\\u5E94\\u7528\\u4E2D\\u4FDD\\u5B58\\u6216\\u5173\\u95ED\\u5F39\\u7A97\\uFF0C\\u7136\\u540E\\u91CD\\u8BD5\\u3002\\u8349\\u7A3F\\u5DF2\\u7ECF\\u4FDD\\u5B58\\u3002",r+" has not exited. Save your work or close its dialog, then retry. Your draft is already saved."):h.result.message??o("\\u5E94\\u7528\\u672A\\u80FD\\u6253\\u5F00\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u3002\\u8349\\u7A3F\\u5DF2\\u7ECF\\u4FDD\\u5B58\\u3002","The editor did not open. Retry; your draft is already saved."),"bad"));return}s=!1,a(),ce(e,h.result.restarted?o("\\u5DF2\\u91CD\\u542F","Restarted ")+r:o("\\u5DF2\\u6253\\u5F00","Opened ")+r)}catch(h){l.replaceChildren(A(String(h),"bad"))}finally{s=!1,m.disabled=f.disabled=g.disabled=!1,m.textContent=p}})()},"primary");t.canOpen||l.append(A(o("\\u672A\\u627E\\u5230\\u5E94\\u7528\\u5B89\\u88C5\\u4F4D\\u7F6E\\uFF0C\\u53EF\\u4EE5\\u7A0D\\u540E\\u624B\\u52A8\\u6253\\u5F00\\u3002\\u8349\\u7A3F\\u548C\\u7D20\\u6750\\u5DF2\\u4FDD\\u5B58\\u5230\\u672C\\u673A\\u3002","The app location could not be found. Open it manually later; the draft and media are saved locally."))),i.append(u("div",{class:"studio-export-header"},[U(o("\\u5DF2\\u5BFC\\u5165","Imported into ")+r),g]),d,l,u("div",{class:"studio-draft-actions"},[f,...t.canOpen?[m]:[]])),document.body.append(c,i),i.addEventListener("keydown",h=>{if(h.key==="Escape"&&a(),h.key!=="Tab")return;let b=Array.from(i.querySelectorAll("button:not(:disabled)")),y=b[0],v=b[b.length-1];h.shiftKey&&document.activeElement===y?(h.preventDefault(),v?.focus()):!h.shiftKey&&document.activeElement===v&&(h.preventDefault(),y?.focus())}),(t.canOpen?m:f).focus()};var Ct=(e,t)=>{if(document.getElementById("studio-export"))return;let n=e.get().state;if(!n?.resolved||!n.edit)return;let o=n.resolved,r=e.get().lang==="zh",s=(P,V)=>r?P:V,a="video",c="jianying",i="1080",d="",l="",f=!1,g=!1,p,m=!1,h,b,y=u("div",{class:"studio-export-result",attrs:{role:"status"}}),v=u("div",{class:"studio-paid-info"}),E,M=u("progress",{attrs:{max:"1",value:"0",hidden:""}}),k=u("fieldset",{class:"studio-export-fields"}),H=u("div",{class:"studio-segments export-tabs",attrs:{role:"tablist"}}),L=u("aside",{id:"studio-export",class:"studio-export",attrs:{role:"dialog","aria-modal":"true","aria-label":s("\\u5BFC\\u51FA\\u8BBE\\u7F6E","Export settings")}}),R=()=>{g||(document.removeEventListener("keydown",F,!0),so(),O.remove(),L.remove(),document.getElementById("studio-export-open")?.focus())},F=P=>{P.key==="Escape"&&(P.preventDefault(),P.stopPropagation(),R())},O=u("div",{class:"studio-scrim",on:{click:R}}),D=(P,V,I)=>u("div",{class:"studio-segments"},P.map(([me,de])=>{let Ot=C(de,()=>I(me),me===V?"selected":"");return Ot.setAttribute("aria-pressed",String(me===V)),Ot})),w=(P,V)=>(V.setAttribute("role","group"),V.setAttribute("aria-label",P),u("div",{class:"studio-field"},[u("span",{text:P}),V])),N=()=>{if(v.hidden=a!=="video",H.replaceChildren(...[["video",x(e,"video")],["draft",s("\\u526A\\u6620","Draft")]].map(([I,me])=>{let de=C(me,()=>{a=I,y.replaceChildren(),N(),B()},a===I?"selected":"");return de.setAttribute("role","tab"),de.setAttribute("aria-selected",String(a===I)),de})),a==="draft"){let I=u("details",{},[u("summary",{text:s("\\u90E8\\u5206\\u5185\\u5BB9\\u4E0D\\u652F\\u6301","Some content is flattened")}),A(s("\\u652F\\u6301\\uFF1A\\u5B57\\u5E55\\u6587\\u5B57\\u4E0E\\u65F6\\u95F4\\u3001\\u89C6\\u9891\\u7247\\u6BB5\\u3001\\u97F3\\u9891\\u7247\\u6BB5\\u3002\\u5B57\\u5E55\\u6837\\u5F0F\\u9700\\u5728\\u76EE\\u6807\\u7F16\\u8F91\\u5668\\u4E2D\\u91CD\\u65B0\\u8BBE\\u7F6E\\uFF1B\\u590D\\u6742\\u89C6\\u89C9\\u6548\\u679C\\u70D8\\u7119\\u5230\\u5404\\u4E2A\\u89C6\\u9891\\u7247\\u6BB5\\u3002","Supported: caption text/timing, video clips and audio clips. Reapply caption styles in the target editor. Complex visuals are baked per clip."))]),me=h?.find(de=>de.target===c);k.replaceChildren(A(s("\\u628A\\u5F53\\u524D\\u65F6\\u95F4\\u7EBF\\u76F4\\u63A5\\u4FDD\\u5B58\\u4E3A\\u672C\\u673A\\u5E94\\u7528\\u4E2D\\u53EF\\u7EE7\\u7EED\\u7F16\\u8F91\\u7684\\u8349\\u7A3F\\u3002","Save the current timeline directly into your desktop editor\\u2019s local drafts.")),A(s("\\u5BFC\\u51FA\\u6210\\u529F\\u540E\\u53EF\\u4E00\\u952E\\u91CD\\u542F\\u5E94\\u7528\\uFF0C\\u5728\\u672C\\u5730\\u8349\\u7A3F\\u4E2D\\u7EE7\\u7EED\\u7F16\\u8F91\\u3002","After export, restart the app with one click and continue editing from local drafts.")),w(s("\\u5E94\\u7528","Application"),D([["jianying",s("\\u526A\\u6620\\u4E13\\u4E1A\\u7248","Jianying Pro")],["capcut","CapCut"]],c,de=>{c=de,b=void 0,N(),B()})),I),h?me?.usable||k.append(A(me?.error??s("\\u8BF7\\u5728\\u8FD0\\u884C\\u6B64\\u7F16\\u8F91\\u5668\\u7684\\u7535\\u8111\\u4E0A\\u5B89\\u88C5\\u5E76\\u6253\\u5F00\\u6240\\u9009\\u5E94\\u7528\\uFF0C\\u518D\\u91CD\\u65B0\\u6253\\u5F00\\u5BFC\\u51FA\\u8BBE\\u7F6E\\u3002","Install and open the selected app on the computer running this editor, then reopen export settings."),"bad")):k.append(A(s("\\u6B63\\u5728\\u68C0\\u67E5\\u672C\\u673A\\u5E94\\u7528\\u2026","Checking desktop editors\\u2026")));return}let P=D([["480","480p"],["720","720p"],["1080","1080p"],["2160","4K"]],i,I=>{i=I,N(),B()}),V=u("button",{text:"HDR",attrs:{type:"button",disabled:"",title:x(e,"hdrUnavailable")}});if(k.replaceChildren(w(x(e,"dynamicRange"),u("div",{class:"studio-segments"},[C("SDR",()=>{},"selected"),V])),w(x(e,"resolution"),P),Me(x(e,"fps"),wt([["",x(e,"match")+" ("+o.canvas.fps+" fps)"],...[24,25,30,50,60].map(I=>[String(I),I+" fps"])],d,x(e,"fps"),I=>{d=I})),Me(s("\\u89C6\\u9891\\u7801\\u7387","Video bitrate"),wt([["",x(e,"recommended")],...[2,5,8,12,20,40].map(I=>[String(I),I+" Mbps"])],l,x(e,"bitrate"),I=>{l=I}))),v.replaceChildren(),!f){let I=P.lastElementChild;I&&I.append(u("span",{class:"export-pro",text:"PRO"}))}i==="2160"&&!f&&v.append(A(s("4K \\u4E3A\\u4ED8\\u8D39\\u5206\\u8FA8\\u7387\\u3002\\u5347\\u7EA7\\u5957\\u9910\\u540E\\u5373\\u53EF\\u5BFC\\u51FA\\uFF1B1080p \\u53CA\\u4EE5\\u4E0B\\u53EF\\u7EE7\\u7EED\\u4F7F\\u7528\\u3002","4K requires a paid plan. Upgrade to export in 4K, or choose 1080p or below.")),...E?[u("a",{class:"studio-btn",text:x(e,"unlock"),attrs:{href:E,target:"_blank",rel:"noopener"}})]:[A(x(e,"loading"))],C(x(e,"refreshPlan"),()=>{J("/api/export-options").then(I=>{f=I.premium,N(),B()})}))},z=C(s("\\u5BFC\\u51FA","Export"),()=>{(async()=>{try{if(a==="draft"){g=!0,B(),b??=crypto.randomUUID();let P=await J("/api/studio/draft",{target:c,requestId:b});g=!1,R(),to(e,P.result)}else{p=void 0,m=!1;let P=await J("/api/render",{name:"Popost-video",resolution:i,dynamicRange:"sdr",fps:d?Number(d):null,bitrate:l?Number(l):null,audio:!0});p=P.render.state==="running"?P.render.started:P.render.state==="done"||P.render.state==="failed"?P.render.finished:void 0,t.setRender(P.render)}}catch(P){y.replaceChildren(A(String(P),"bad"))}finally{g=!1,B()}})()},"primary"),B=()=>{let P=e.get().edit.render,V=g||a==="video"&&P?.state==="running";if(k.disabled=V,z.disabled=V||a==="video"&&i==="2160"&&!f||a==="draft"&&!h?.find(I=>I.target===c)?.usable,K.disabled=g,H.querySelectorAll("button").forEach(I=>{I.disabled=V}),M.hidden=!V,z.textContent=V?s("\\u6B63\\u5728\\u5BFC\\u51FA\\u2026","Exporting\\u2026"):s("\\u5BFC\\u51FA","Export"),a==="draft"){g&&M.removeAttribute("value");return}P?.state==="running"&&(M.value=P.total?P.frame/P.total:0,y.replaceChildren()),P?.state==="failed"&&y.replaceChildren(A(P.message,"bad")),P?.state==="done"&&p!==void 0&&P.finished>=p&&(p!==void 0&&P.finished>=p&&!m&&(m=!0,u("a",{attrs:{href:P.url,download:"Popost-video.mp4"}}).click()),y.replaceChildren(A(s("\\u5BFC\\u51FA\\u5B8C\\u6210\\uFF0C\\u89C6\\u9891\\u5DF2\\u4FDD\\u5B58\\u5E76\\u5F00\\u59CB\\u4E0B\\u8F7D\\u3002","Export complete. The video is saved and downloading."))))},K=C("\\xD7",R);L.append(u("div",{class:"studio-export-header"},[U(s("\\u5BFC\\u51FA\\u8BBE\\u7F6E","Export settings")),K]),H,k,v,M,z,y),document.body.append(O,L),N(),B(),J("/api/export-options").then(P=>{f=P.premium,E=P.pricingUrl??E,N(),B()}).catch(()=>{}),J("/api/studio/draft-targets",{}).then(P=>{h=P.result.applications,N(),B()}).catch(P=>{h=[],y.replaceChildren(A(String(P),"bad")),N(),B()});let so=e.subscribe((P,V)=>{L.isConnected&&P.edit.render!==V.edit.render&&B()});document.addEventListener("keydown",F,!0),z.focus()};var Ar=[["media","media","media"],["elements","elements","layers"],["script","subtitles","text"],["code","code","code"]],no=(e,t,n,o)=>{let r="media",s=u("nav",{class:"studio-rail",attrs:{"aria-label":"Studio"}}),a=u("aside",{id:"studio-content",class:"studio-content"}),c=Qn(t,o),i=c.root,d={store:t,actions:n,edit:o,meta:{hash:"",slots:[],versions:[],comments:[]},refresh:()=>{}},l=()=>{let w=document.querySelector("#page"),N=new Map([...new Set(d.meta.slots.map(K=>K.segment))].map(K=>[K,He(w,t,K)])),z=d.meta.slots.filter(K=>N.get(K.segment)?.has(K.name));if(JSON.stringify(z)!==JSON.stringify(t.get().slots)&&t.set({slots:z}),s.querySelectorAll("button").forEach(K=>{K.classList.toggle("active",K.dataset.panel===r),K.setAttribute("aria-pressed",String(K.dataset.panel===r))}),document.body.classList.toggle("panel-code",r==="code"),r==="code"){a.contains(i)||a.replaceChildren(i);return}let B={shots:At,media:Wn,script:qn,elements:Gn,checks:Yn,versions:Xn};a.replaceChildren(B[r](d))},f=w=>{r=w,l()};for(let[w,N,z]of Ar){let B=u("button",{data:{panel:w},attrs:{type:"button",title:x(t,N)},on:{click:()=>f(w)}},[Y(z),u("span",{text:x(t,N)})]);s.append(B)}let g=async()=>{let w=t.get().state?.generation;try{let N=await Zn();if(w!==t.get().state?.generation)return;d.meta=N,N.lastExport&&t.get().edit.render?.state!=="running"&&(!t.get().edit.render||t.get().edit.render?.state==="idle")&&o.setRender(N.lastExport),l()}catch{}};d.refresh=()=>{g()},e.prepend(s,a);let p=document.querySelector(".studio-topbar"),m=u("strong",{class:"studio-brand",text:"popost"}),h=u("span",{class:"studio-project"}),b=u("span",{class:"studio-save"}),y=u("span",{class:"studio-global-actions"}),v=ne(x(t,"compare"),"compare",()=>{if(!t.get().state?.reference){ce(t,x(t,"noReference"));return}t.get().edit.playRender&&o.togglePlayRender(),t.set({compare:!t.get().compare})});v.id="studio-compare";let E=ne(x(t,"layout"),"layout",()=>{let w=document.body.classList.toggle("focus-preview");E.setAttribute("aria-pressed",String(w))});E.setAttribute("aria-pressed","false");let M=ne(x(t,"theme"),"theme",()=>{let w=document.documentElement.classList.toggle("dark");M.setAttribute("aria-pressed",String(w)),localStorage.setItem("popost-studio-theme",w?"dark":"light")});M.setAttribute("aria-pressed",String(localStorage.getItem("popost-studio-theme")==="dark"));let k=ne(t.get().lang==="zh"?"English":"\\u4E2D\\u6587","language",()=>{let w=t.get().lang==="zh"?"en":"zh";localStorage.setItem("popost-studio-language",w),n.setLang(w),location.reload()});k.id="lang-toggle";let H=ne(x(t,"versions"),"history",()=>f("versions")),L=ne(x(t,"export"),"download",()=>Ct(t,o));L.id="studio-export-open",y.append(v,E,H,M,k),$n(y,t,async()=>await o.flush()?await c.flush()&&await o.flush():!1),y.append(L),p.append(m,h,b,y),document.documentElement.classList.toggle("dark",localStorage.getItem("popost-studio-theme")==="dark"),document.addEventListener("studio:export",()=>Ct(t,o));let R=document.getElementById("studio-stage-heading"),F=u("input",{attrs:{type:"checkbox","aria-label":x(t,"audio")}});F.checked=!0,F.addEventListener("change",()=>t.set({muted:!F.checked})),R.append(u("span",{text:x(t,"preview")}),u("label",{class:"studio-check",title:x(t,"onlyPreview")},[F,x(t,"audio")]));let O=document.querySelector(".panel");O.prepend(U(x(t,"properties")));let D=()=>{let w=t.get();document.body.setAttribute("aria-busy",String(!!w.edit.saving)),h.textContent=w.state?.project.name??"Popost Video Studio",b.textContent=w.connected?w.state?.edit?x(t,"saved"):x(t,"readOnly"):x(t,"offline"),w.edit.saving&&(b.textContent=x(t,"saving")),w.edit.status?.kind==="refused"&&(b.textContent=x(t,"error")),v.classList.toggle("selected",!!w.compare),v.setAttribute("aria-pressed",String(!!w.compare)),L.disabled=!w.state?.edit||!w.state.resolved,O.hidden=!w.pinned,document.body.classList.toggle("inspecting",!!w.pinned)};return t.subscribe((w,N)=>{if((w.state!==N.state||w.pinned!==N.pinned||w.compare!==N.compare||w.connected!==N.connected||w.edit.status!==N.edit.status||w.edit.saving!==N.edit.saving)&&D(),w.state!==N.state?(l(),g()):w.frame!==N.frame&&r==="elements"&&w.state?.resolved?.segments.find(z=>w.frame>=z.start&&w.frame<z.end)?.id!==N.state?.resolved?.segments.find(z=>N.frame>=z.start&&N.frame<z.end)?.id&&l(),w.pinned!==N.pinned&&w.pinned){let z=w.state?q(w.state,w.pinned):void 0,B=w.pinned.kind==="segment"?"media":z?.kind==="cue"?"script":"elements";B==="media"&&(d.mediaView="shots");let K=a.contains(document.activeElement);(r!==B||!K)&&(r=B,l())}w.pinned!==N.pinned&&a.querySelectorAll("[data-selection]").forEach(z=>{let B=z.dataset.selection===JSON.stringify(w.pinned);z.classList.toggle("selected",B),z.tagName==="BUTTON"&&z.setAttribute("aria-pressed",String(B)),B&&z.scrollIntoView({block:"nearest"})})}),document.addEventListener("studio:page-ready",l),document.addEventListener("studio:scene-ready",()=>{r==="elements"&&l()}),D(),l(),{refresh:g,choose:f,content:a,panel:()=>r}},oo=eo,ut=(e,t)=>{let n=t==="timeline",o=u("div",{class:"studio-handle "+(n?"horizontal":"vertical")+(t==="right"?" inspector-resize":""),attrs:{role:"separator",tabindex:"0","aria-orientation":n?"horizontal":"vertical"}});return n||(o.style.left=t==="left"?"calc(64px + var(--left-width) - 2px)":"calc(100% - var(--right-width) - 2px)"),o.addEventListener("pointerdown",r=>{o.setPointerCapture(r.pointerId);let s=n?r.clientY:r.clientX,a=n?"--timeline-height":t==="left"?"--left-width":"--right-width",c=parseFloat(getComputedStyle(document.documentElement).getPropertyValue(a)),i=l=>{let f=(n?l.clientY:l.clientX)-s,g=Math.min(n?innerHeight*.65:innerWidth*.4,Math.max(n?150:210,c+(t==="left"?f:-f)));document.documentElement.style.setProperty(a,g+"px")},d=()=>{o.removeEventListener("pointermove",i),o.removeEventListener("pointerup",d),localStorage.setItem("popost-studio-layout",document.documentElement.style.cssText)};o.addEventListener("pointermove",i),o.addEventListener("pointerup",d)}),e.append(o),o};var Cr=async()=>{let e=await fetch("/api/state",{cache:"no-store"});if(!e.ok)throw new Error("GET /api/state answered "+e.status);return await e.json()},Or=["boxes","events","safe"],Hr=(e,t)=>{let n=u("h1"),o=u("span",{class:"project",id:"project"}),r=u("span",{class:"status",id:"status"}),s=Or.map(i=>{let d=u("input",{id:"toggle-"+i,attrs:{type:"checkbox"}});d.addEventListener("change",()=>{t.toggleOverlay(i),d.blur()});let l=u("span");return{name:i,input:d,text:l,el:u("label",{class:"toggle"},[d,l])}}),a=u("button",{id:"lang-toggle",class:"tbtn",attrs:{type:"button"}});a.addEventListener("click",()=>{t.setLang(e.get().lang==="en"?"zh":"en"),a.blur()});let c=i=>{let d=i.state;n.textContent=S(i.lang,"title"),o.textContent=d?d.project.name+(d.resolved?" "+d.resolved.frames+"f, "+(d.resolved.frames/d.resolved.canvas.fps).toFixed(2)+" s":""):"",o.title=d?.project.dir??"",r.textContent=S(i.lang,d?.edit?"editing":"readOnly")+", "+S(i.lang,i.connected?"live":"offline"),r.classList.toggle("offline",!i.connected),s.forEach(l=>{l.text.textContent=S(i.lang,l.name),l.input.checked=i.overlays[l.name]}),a.textContent=S(i.lang,"language"),a.title=S(i.lang,"languageTitle")};return c(e.get()),e.subscribe((i,d)=>{(i.state!==d.state||i.lang!==d.lang||i.connected!==d.connected||i.overlays!==d.overlays)&&c(i)}),u("header",{},[n,o,...s.map(i=>i.el),u("span",{id:"edit-slot",class:"edit-slot"}),r,a])},Nr=(e,t)=>{document.body.classList.add("editing");let n=document.getElementById("edit-slot");n&&tt(n,e.store,e.edit),nt(e.panel,e.store,e.edit);let o=et(e.stage.frameBox,e.stage.iframe,e.store,e.edit);Ge(e.lanes,e.store,e.edit),ot(e.store,e.edit,o.nudge),We(e.store);let r=Je(t);r&&e.edit.select(r),t.edit&&t.edit.render.state!=="idle"&&e.edit.setRender(t.edit.render),e.events.addEventListener(je,s=>e.edit.setRender(JSON.parse(s.data))),Xe().then(s=>e.store.set({edit:{...e.store.get().edit,schema:s}}))},ro=()=>{let e=Ue(navigator.language);document.documentElement.lang=e==="zh"?"zh-CN":"en";let t=_e({state:null,frame:0,playing:!1,speed:1,lang:e,pinned:null,overlays:{boxes:!1,events:!0,safe:!1},connected:!0,pageError:null,edit:Ve}),n=Ke(t),o=qe(t,n),r=document.getElementById("app")??document.body,s=u("div",{class:"stage-area",id:"stage"}),a=u("div",{class:"transport",id:"transport"}),c=u("div",{class:"timeline",id:"timeline"}),i=u("aside",{class:"panel",id:"panel"});r.append(Hr(t,n),u("div",{class:"main"},[u("div",{class:"left"},[s,a,c]),i]));let d=dt(s,t,n);lt(a,t,n),rt(c,t,n),it(i,t,n,o);let l=new EventSource("/api/events"),f=!1,g=async()=>{try{let p=await Cr(),m=t.get();if(m.connected&&m.state&&p.generation<m.state.generation)return;t.set({state:p,frame:pe(t.get().frame,W(p)),connected:!0}),p.edit&&!f&&(f=!0,Nr({store:t,edit:o,stage:d,lanes:c.querySelector("#lanes")??c,panel:i,events:l},p))}catch{t.set({connected:!1})}};l.addEventListener(De,()=>{g()}),l.addEventListener("open",()=>{t.get().connected||g()}),l.addEventListener("error",()=>{t.get().connected&&t.set({connected:!1})}),g()};var Ir=()=>{let e=localStorage.getItem("popost-studio-language"),t=e==="zh"||e==="en"?e:Ue(navigator.language);document.documentElement.lang=t==="zh"?"zh-CN":"en",document.body.classList.add("studio");let n=localStorage.getItem("popost-studio-layout");n&&/^[-a-z0-9:;. %px]+$/i.test(n)&&(document.documentElement.style.cssText=n);let o=_e({state:null,frame:0,playing:!1,speed:1,lang:t,pinned:null,compare:!1,muted:!1,timeline:{layers:!1,snapping:!0},overlays:{boxes:!1,events:!1,safe:!1},connected:!0,pageError:null,edit:Ve}),r=Ke(o),s=qe(o,r),a=document.getElementById("app")??document.body,c=u("header",{class:"studio-topbar"}),i=u("div",{class:"stage-area",id:"stage"}),d=u("div",{class:"transport",id:"transport"}),l=u("div",{class:"timeline",id:"timeline"}),f=u("aside",{class:"panel",id:"panel"}),g=u("div",{class:"main"},[u("div",{class:"left"},[u("div",{id:"studio-stage-heading",class:"studio-stage-heading"}),i,d]),f]),p=u("div",{class:"studio-timeline-toolbar"}),m=u("div",{class:"studio-timeline-wrap"},[p,l]),h=u("footer",{class:"studio-footer"},["Popost Video Studio","video.json"]);a.append(c,g,m,h,u("div",{id:"studio-message",attrs:{role:"status"}})),no(g,o,r,s),oo(p,o,s),ut(g,"left"),ut(g,"right"),ut(m,"timeline");let b=dt(i,o,r);lt(d,o,r),rt(l,o,r),it(f,o,r,s),gn(o);let y=new EventSource("/api/events"),v=!1,E=async()=>{try{let M=await fetch("/api/state",{cache:"no-store"});if(!M.ok)throw new Error;let k=await M.json(),H=o.get();if(H.connected&&H.state&&k.generation<H.state.generation)return;if(o.set({state:k,frame:pe(H.frame,W(k)),connected:!0}),k.edit&&!v){v=!0,document.body.classList.add("editing"),tt(document.getElementById("edit-slot"),o,s),nt(f,o,s);let L=et(b.frameBox,b.iframe,o,s);Ge(l.querySelector("#lanes")??l,o,s),ot(o,s,L.nudge),We(o);let R=Je(k);R&&s.select(R),k.edit.render.state!=="idle"&&s.setRender(k.edit.render),Xe().then(F=>o.set({edit:{...o.get().edit,schema:F}}))}}catch{o.set({connected:!1})}};y.addEventListener(De,()=>{E()}),y.addEventListener(je,M=>s.setRender(JSON.parse(M.data))),y.addEventListener("open",()=>{o.get().connected||E()}),y.addEventListener("error",()=>{o.get().connected&&o.set({connected:!1})}),E()};document.documentElement.dataset.mode==="readonly"?ro():Ir();})();
37753
38026
  `;
37754
38027
  }
37755
38028
  });
@@ -40776,11 +41049,11 @@ var init_findings2 = __esm({
40776
41049
  };
40777
41050
  unseenProblem = (shot, mine, longer, theirs, picture3) => {
40778
41051
  const shown3 = theirs.filter((t) => t.visible).map((t) => t.index);
40779
- const missing3 = outermost(mine.filter((t) => !t.visible && shown3.includes(t.index))).slice(0, 3);
40780
- if (!missing3.length) return void 0;
41052
+ const missing4 = outermost(mine.filter((t) => !t.visible && shown3.includes(t.index))).slice(0, 3);
41053
+ if (!missing4.length) return void 0;
40781
41054
  return warning(
40782
41055
  at4(shot.k),
40783
- "In " + where2(shot) + ", a shot of " + s2(shot.seconds) + ", " + quoted3(missing3.map((t) => t.text)) + (missing3.length > 1 ? " are" : " is") + " never visible (" + picture3 + '), though segment "' + longer.id + '" (' + s2(longer.seconds) + ") shows " + (missing3.length > 1 ? "them" : "it") + " with the same scene file: the entrance starts after this shorter shot has ended.",
41056
+ "In " + where2(shot) + ", a shot of " + s2(shot.seconds) + ", " + quoted3(missing4.map((t) => t.text)) + (missing4.length > 1 ? " are" : " is") + " never visible (" + picture3 + '), though segment "' + longer.id + '" (' + s2(longer.seconds) + ") shows " + (missing4.length > 1 ? "them" : "it") + " with the same scene file: the entrance starts after this shorter shot has ended.",
40784
41057
  'Time the entrances for the shortest shot that shows "' + shot.src + '": every text visible by ' + s2(readBy(shot.seconds)) + ", then held. Or give this segment a scene file of its own."
40785
41058
  );
40786
41059
  };
@@ -41084,8 +41357,8 @@ var init_check7 = __esm({
41084
41357
  if (!wanted.length) return { problems: built.problems, shots: [], scenes: [] };
41085
41358
  const shots2 = [];
41086
41359
  const scenes = [];
41087
- const absent = [...await missingScripts(rt, projectDir, wanted), ...await missingStylesheets(rt, projectDir, wanted)];
41088
- if (absent.length) return { problems: [...built.problems, ...absent], shots: shots2, scenes };
41360
+ const absent2 = [...await missingScripts(rt, projectDir, wanted), ...await missingStylesheets(rt, projectDir, wanted)];
41361
+ if (absent2.length) return { problems: [...built.problems, ...absent2], shots: shots2, scenes };
41089
41362
  const problems2 = [...built.problems];
41090
41363
  const session = await openSession(rt, projectDir, { reuse: false }).catch((e) => e);
41091
41364
  if (session instanceof SceneLoadError) return { problems: [...problems2, ...session.problems], shots: shots2, scenes };
@@ -41488,9 +41761,9 @@ var init_collect = __esm({
41488
41761
  }
41489
41762
  });
41490
41763
  const pictureHosts = pictures.flatMap((p) => isHttp(p.from) && p.kind === "img" ? [new URL(p.from).hostname] : []);
41491
- const own2 = ownHosts(links2.map((k) => k.host), { ...l.base ? { page: l.base.hostname } : {}, pictureHosts, names: namesOf(l) });
41764
+ const own3 = ownHosts(links2.map((k) => k.host), { ...l.base ? { page: l.base.hostname } : {}, pictureHosts, names: namesOf(l) });
41492
41765
  const once4 = /* @__PURE__ */ new Set();
41493
- const ownLinks = links2.filter((k) => own2.some((h) => siteOf(h) === siteOf(k.host)) && !once4.has(k.url) && once4.add(k.url)).slice(0, 30).map((k) => ({ url: k.url, text: k.text }));
41766
+ const ownLinks = links2.filter((k) => own3.some((h) => siteOf(h) === siteOf(k.host)) && !once4.has(k.url) && once4.add(k.url)).slice(0, 30).map((k) => ({ url: k.url, text: k.text }));
41494
41767
  const entry2 = {
41495
41768
  source: o.source,
41496
41769
  title: read2.title,
@@ -41498,8 +41771,8 @@ var init_collect = __esm({
41498
41771
  pictures,
41499
41772
  skipped: { ...skipped2, failed: skipped2.failed.slice(0, 20) },
41500
41773
  colours: colours.filter((c, i) => colours.findIndex((x) => x.hex === c.hex) === i),
41501
- site: { hosts: [...new Set(own2.map(siteOf))], links: ownLinks },
41502
- otherHosts: [...new Set(links2.map((k) => k.host))].filter((h) => !own2.some((x) => siteOf(x) === siteOf(h))).slice(0, 30)
41774
+ site: { hosts: [...new Set(own3.map(siteOf))], links: ownLinks },
41775
+ otherHosts: [...new Set(links2.map((k) => k.host))].filter((h) => !own3.some((x) => siteOf(x) === siteOf(h))).slice(0, 30)
41503
41776
  };
41504
41777
  await rt.fs.writeFile(rt.path.join(o.outDir, INVENTORY_FILE), JSON.stringify({ sources: [...others, entry2] }, null, 1) + "\n");
41505
41778
  return entry2;
@@ -42484,9 +42757,9 @@ var init_speech_check = __esm({
42484
42757
  const a = comparedWords(script), b = comparedWords(heard);
42485
42758
  const pairs = commonPairs(a, b);
42486
42759
  const saidA = new Set(pairs.map(([i]) => i)), saidB = new Set(pairs.map(([, j]) => j));
42487
- const missing3 = a.filter((_w, i) => !saidA.has(i)), extra2 = b.filter((_w, j) => !saidB.has(j));
42760
+ const missing4 = a.filter((_w, i) => !saidA.has(i)), extra2 = b.filter((_w, j) => !saidB.has(j));
42488
42761
  const n = a.length, matched = pairs.length;
42489
- return { script: n, heard: b.length, matched, share: n ? Math.round(matched / n * 100) / 100 : 1, missing: missing3.slice(0, 12), extra: extra2.slice(0, 12) };
42762
+ return { script: n, heard: b.length, matched, share: n ? Math.round(matched / n * 100) / 100 : 1, missing: missing4.slice(0, 12), extra: extra2.slice(0, 12) };
42490
42763
  };
42491
42764
  lineTimes = (lines, words) => {
42492
42765
  const perLine = lines.map((l) => comparedWords(l));
@@ -42680,7 +42953,7 @@ var init_speech_rules = __esm({
42680
42953
  });
42681
42954
 
42682
42955
  // src/video/commands/materials.ts
42683
- var errorsIn2, PICTURE_EXT, givenAnchor, characterOf, budgeted, payingPending, LOOK_AGAIN_MS, waitLimitMs, PENDING_NEXT, beingMade2, allRuns, PRICE_NEXT, toAgree, materials;
42956
+ var errorsIn2, PICTURE_EXT, givenAnchor, characterOf, budgeted, payingPending, LOOK_AGAIN_MS, waitLimitMs, PENDING_NEXT, beingMade2, allRuns, PRICE_NEXT, specOf2, toAgree, materials;
42684
42957
  var init_materials2 = __esm({
42685
42958
  "src/video/commands/materials.ts"() {
42686
42959
  "use strict";
@@ -42724,9 +42997,9 @@ var init_materials2 = __esm({
42724
42997
  }
42725
42998
  };
42726
42999
  budgeted = (generator, wallet, approve) => ({
42727
- make: async (kind, request, out2, env) => {
43000
+ make: async (kind, request, out2, env2) => {
42728
43001
  const made = await generator.make(kind, request, out2, {
42729
- ...env,
43002
+ ...env2,
42730
43003
  ...wallet ? { POPOST_GEN_MAX_CREDITS: String(wallet.left) } : {},
42731
43004
  ...approve.length ? { POPOST_GEN_APPROVE: approve.join(",") } : {}
42732
43005
  });
@@ -42735,7 +43008,7 @@ var init_materials2 = __esm({
42735
43008
  }
42736
43009
  });
42737
43010
  payingPending = (generator, wallet) => ({
42738
- make: (kind, request, out2, env) => generator.make(kind, request, out2, env).catch((e) => {
43011
+ make: (kind, request, out2, env2) => generator.make(kind, request, out2, env2).catch((e) => {
42739
43012
  if (e instanceof StillMaking) wallet?.pay(e.pending.chargedCredits ?? 0);
42740
43013
  throw e;
42741
43014
  })
@@ -42765,13 +43038,19 @@ var init_materials2 = __esm({
42765
43038
  }
42766
43039
  return { ...r, chargedCredits: charged, materials: r.materials.map((m) => made.has(m.file) && !m.made && !m.error ? { ...m, made: true } : m) };
42767
43040
  };
42768
- 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 credits (and the balance) and run it so once they agree.";
43041
+ 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.";
43042
+ specOf2 = (c) => ({
43043
+ ...c?.model ? { model: c.model } : {},
43044
+ ...c?.resolution ? { resolution: c.resolution } : {},
43045
+ ...c?.seconds !== void 0 ? { seconds: c.seconds } : {},
43046
+ ...c?.aspectRatio ? { aspectRatio: c.aspectRatio } : {}
43047
+ });
42769
43048
  toAgree = (materials2, clipMusic = []) => {
42770
43049
  const asked2 = materials2.filter((m) => m.confirm);
42771
43050
  if (!asked2.length) return void 0;
42772
43051
  const sum = (list7) => list7.reduce((n, m) => n + (m.confirm?.credits ?? 0), 0);
42773
43052
  const balance = asked2.map((m) => m.confirm?.balance).find((b) => typeof b === "number");
42774
- const items = asked2.map((m) => ({ kind: m.kind, what: m.file, credits: m.confirm?.credits ?? 0, ...m.confirm?.seconds !== void 0 ? { seconds: m.confirm.seconds } : {} }));
43053
+ const items = asked2.map((m) => ({ kind: m.kind, what: m.file, credits: m.confirm?.credits ?? 0, ...specOf2(m.confirm) }));
42775
43054
  const unplanned = asked2.filter((m) => m.confirm?.reason === "unplanned");
42776
43055
  const clips = unplanned.map((m) => ({ ...m.confirm?.clip, credits: m.confirm?.credits ?? 0 }));
42777
43056
  const music = clipMusic.length ? { clipMusic } : {};
@@ -43734,8 +44013,8 @@ var init_loop2 = __esm({
43734
44013
  const prompt = { card: card2, slots: pkg.slots, brief: brief3, materials: materials2, ...language ? { language } : {}, ...generate2 ? { generate: { product: product !== void 0 } } : {}, ...shotNotes ? { shotNotes } : {}, ...budgets ? { budgets: budgets.max } : {} };
43735
44014
  const fillCommand = "popost video template fill " + dir + " --fill <fill.json> --out <project-dir>" + (assetsDir ? " --assets " + assetsDir : "");
43736
44015
  if (args2.flag("dry")) {
43737
- const own2 = { ...prompt, ...voice ? { voice: { name: voice, ...speed ? { speed } : {} } } : {} };
43738
- const messages = planMessages(own2);
44016
+ const own3 = { ...prompt, ...voice ? { voice: { name: voice, ...speed ? { speed } : {} } } : {} };
44017
+ const messages = planMessages(own3);
43739
44018
  const lines = pkg.slots.captions?.lines ?? [];
43740
44019
  printJson(rt, {
43741
44020
  ok: true,
@@ -43746,7 +44025,7 @@ var init_loop2 = __esm({
43746
44025
  answer: { shots: pkg.slots.shots.length, captions: lines.length, ...voice ? { voice } : {}, ...voice && speed ? { speed } : {} },
43747
44026
  slots: pkg.slots,
43748
44027
  ...budgets ? { budgets: { pace: budgets.pace, ...budgets.tempo ? { tempo: budgets.tempo } : {}, slack: BUDGET_SLACK, lines: budgets.max.map((max, i) => ({ at: "captions[" + i + "]", seconds: lines[i]?.seconds, max })) } } : {},
43749
- rules: planRules(own2),
44028
+ rules: planRules(own3),
43750
44029
  forms: shotForms(generate2 !== void 0),
43751
44030
  materials: materials2,
43752
44031
  ...shotNotes ? { shotNotes: shotNotes.map((note, k) => ({ at: "shots[" + k + "]", note })) } : {},
@@ -44195,8 +44474,8 @@ var init_hosted3 = __esm({
44195
44474
  lengthOf = async (rt, o, known2) => {
44196
44475
  const had = known2 ?? await audioSeconds(rt, o.out).catch(() => void 0);
44197
44476
  if (had === void 0) return { seconds: null };
44198
- const seconds7 = round22(had), missing3 = round22((o.fit ?? o.seconds) - had);
44199
- return { seconds: seconds7, ...missing3 > SHORT_TOLERANCE ? { short: { seconds: seconds7, missing: missing3 } } : {} };
44477
+ const seconds7 = round22(had), missing4 = round22((o.fit ?? o.seconds) - had);
44478
+ return { seconds: seconds7, ...missing4 > SHORT_TOLERANCE ? { short: { seconds: seconds7, missing: missing4 } } : {} };
44200
44479
  };
44201
44480
  written = async (rt, o, receipt, job) => {
44202
44481
  if (job.state !== "ready" || !job.audioUrl) throw new ToolError("The popost.ai music is " + (job.state || "not ready") + "; run the same command again.");
@@ -44281,7 +44560,7 @@ var init_media = __esm({
44281
44560
  const account = connected(rt);
44282
44561
  const tools2 = { ...named, transcribe: named.transcribe ?? (account ? HOSTED : null), speak: named.speak ?? (account ? HOSTED : null), music: musicEnabled(rt) ? HOSTED : null };
44283
44562
  const offers = account ? { hosted: HOSTED_NOTE } : { connect: CONNECT };
44284
- const missing3 = [
44563
+ const missing4 = [
44285
44564
  ...rt.programs ? [] : ["this host cannot run local programs, so no video command works here"],
44286
44565
  ...rt.programs && version === null ? ['ffmpeg was not found: install it or set POPOST_FFMPEG (asked for "' + ffmpegPath(rt) + '")'] : [],
44287
44566
  ...browser === true ? [] : [browser]
@@ -44289,8 +44568,8 @@ var init_media = __esm({
44289
44568
  const budget2 = rt.programs ? cpuBudgetOf(rt) : void 0;
44290
44569
  const cpus = budget2 ? { budget: budget2.cpus, from: budget2.source } : null;
44291
44570
  const reading = named.readText !== null || named.transcribe !== null;
44292
- printJson(rt, { ok: missing3.length === 0, ffmpeg: version, browser: browser === true, cpus, tools: tools2, ...offers, ...reading ? { note: FIRST_RUN } : {}, ...missing3.length ? { missing: missing3 } : {} });
44293
- return missing3.length ? 2 : 0;
44571
+ printJson(rt, { ok: missing4.length === 0, ffmpeg: version, browser: browser === true, cpus, tools: tools2, ...offers, ...reading ? { note: FIRST_RUN } : {}, ...missing4.length ? { missing: missing4 } : {} });
44572
+ return missing4.length ? 2 : 0;
44294
44573
  }
44295
44574
  );
44296
44575
  soundOnly = async (rt, file, e) => {
@@ -44550,9 +44829,9 @@ var init_music_plan = __esm({
44550
44829
  if (args2.string("music") !== void 0) return record(rt, args2, project, kept2, reading);
44551
44830
  if (args2.string("silent-end") !== void 0 || args2.string("breaks") !== void 0) return amend(rt, args2, project, kept2, reading);
44552
44831
  if (kept2) return answer2(rt, project, kept2, {}, void 0, reading);
44553
- const own2 = await ownFile(rt, project);
44554
- const offer = !own2 && reading?.facts.music === "yes" && !keepable(reading) ? await musicOffer(rt, musicSeconds(await lengthOf2(rt, project, reading))) : void 0;
44555
- const proposed = proposal({ ...reading ? { reading } : {}, ownFile: own2, ...offer ? { offer } : {} });
44832
+ const own3 = await ownFile(rt, project);
44833
+ const offer = !own3 && reading?.facts.music === "yes" && !keepable(reading) ? await musicOffer(rt, musicSeconds(await lengthOf2(rt, project, reading))) : void 0;
44834
+ const proposed = proposal({ ...reading ? { reading } : {}, ownFile: own3, ...offer ? { offer } : {} });
44556
44835
  const said = (proposed.music === "generated" || proposed.music === "own") && reading ? breaksSays(reading.facts.musicBreaks ?? [], reading.facts.dipsUnderSpeech) : void 0;
44557
44836
  const breaks = said ? [said] : [];
44558
44837
  printJson(rt, {
@@ -44570,7 +44849,7 @@ var init_music_plan = __esm({
44570
44849
  });
44571
44850
 
44572
44851
  // src/video/commands/music.ts
44573
- var REJECTED_FIX, videoSeconds, secondsOf2, lengthArgs, lengthNote, tooLong, LENGTH_OPTIONS, quote14, refused4, lengthLine, overLimit, make, own, musicCommands;
44852
+ var REJECTED_FIX, videoSeconds, secondsOf2, lengthArgs, lengthNote, tooLong, LENGTH_OPTIONS, quote14, refused4, lengthLine, overLimit, make, own2, musicCommands;
44574
44853
  var init_music = __esm({
44575
44854
  "src/video/commands/music.ts"() {
44576
44855
  "use strict";
@@ -44639,8 +44918,8 @@ var init_music = __esm({
44639
44918
  lengthLine = (made, file, of) => {
44640
44919
  if (made.seconds === null) return "The length of " + file + " could not be read here (ffmpeg): check it against the video's " + of.toFixed(2) + " s before the music is placed.\n";
44641
44920
  if (!made.short) return void 0;
44642
- const { seconds: seconds7, missing: missing3 } = made.short;
44643
- return "The music is " + seconds7.toFixed(2) + " s long, " + missing3.toFixed(2) + " s shorter than the " + of.toFixed(2) + " s it is for: the last " + missing3.toFixed(2) + " s of the video would have no music. Order a longer track (this command with --seconds " + musicSeconds(of + missing3 + MARGIN_SECONDS) + " is a new order, priced and agreed anew; the music is faded out at the end of the video), or end the video with the music (shorten its last scene by " + missing3.toFixed(2) + " s).\n";
44921
+ const { seconds: seconds7, missing: missing4 } = made.short;
44922
+ return "The music is " + seconds7.toFixed(2) + " s long, " + missing4.toFixed(2) + " s shorter than the " + of.toFixed(2) + " s it is for: the last " + missing4.toFixed(2) + " s of the video would have no music. Order a longer track (this command with --seconds " + musicSeconds(of + missing4 + MARGIN_SECONDS) + " is a new order, priced and agreed anew; the music is faded out at the end of the video), or end the video with the music (shorten its last scene by " + missing4.toFixed(2) + " s).\n";
44644
44923
  };
44645
44924
  overLimit = (e, items, max) => {
44646
44925
  if (!(e instanceof PopostApiError && e.code === "CREDIT_LIMIT_EXCEEDED")) throw e;
@@ -44711,7 +44990,7 @@ var init_music = __esm({
44711
44990
  },
44712
44991
  (args2) => args2.string("project")
44713
44992
  );
44714
- own = command(
44993
+ own2 = command(
44715
44994
  `take a sound file the user gave into the project as the video's "sound", with the record that says so (<out>.sound.json): the only sound a fill takes besides generated music. Never a file put together with other tools, a narration, or the sound of the reference or of another video`,
44716
44995
  {
44717
44996
  options: [
@@ -44729,7 +45008,7 @@ var init_music = __esm({
44729
45008
  printJson(rt, { ok: true, file: args2.req("out"), receipt: args2.req("out") + ".sound.json", given: receipt.given, next: 'Write the file into the fill as "sound" (its path from the project directory) and run template fill again with the options it had.' });
44730
45009
  }
44731
45010
  );
44732
- musicCommands = { quote: quote14, make, plan: musicPlan, own };
45011
+ musicCommands = { quote: quote14, make, plan: musicPlan, own: own2 };
44733
45012
  }
44734
45013
  });
44735
45014
 
@@ -45274,7 +45553,7 @@ var init_sfx = __esm({
45274
45553
  });
45275
45554
 
45276
45555
  // src/video/sound/analysis.ts
45277
- var MAX_ANALYSIS_SECONDS, MAX_ANALYSIS_BYTES, POLL_MS5, WAIT_LIMIT_MS3, heardSound, measureFile, missing, firstLine, planAnalysis, untilDone3, runAnalysis;
45556
+ var MAX_ANALYSIS_SECONDS, MAX_ANALYSIS_BYTES, POLL_MS5, WAIT_LIMIT_MS3, heardSound, measureFile, missing2, firstLine, planAnalysis, untilDone3, runAnalysis;
45278
45557
  var init_analysis = __esm({
45279
45558
  "src/video/sound/analysis.ts"() {
45280
45559
  "use strict";
@@ -45305,7 +45584,7 @@ var init_analysis = __esm({
45305
45584
  const m = measureSound(pcm, 22050, picture3);
45306
45585
  return loudness === void 0 ? m : { ...m, loudness };
45307
45586
  };
45308
- missing = (e) => e instanceof PopostApiError && (e.status === 404 || e.code === "NOT_FOUND");
45587
+ missing2 = (e) => e instanceof PopostApiError && (e.status === 404 || e.code === "NOT_FOUND");
45309
45588
  firstLine = (e) => (e instanceof Error ? e.message : String(e)).split("\n")[0] ?? "failed";
45310
45589
  planAnalysis = async (rt, sound2, o = {}) => {
45311
45590
  if (!sound2) return { kind: "none", record: { status: "silent" } };
@@ -45318,7 +45597,7 @@ var init_analysis = __esm({
45318
45597
  const credits = await quoteSoundAnalysis(rt, sound2.seconds);
45319
45598
  return { kind: "run", credits, item: { kind: "sound-analysis", what: o.what ?? "the sound of the reference (music, ambience, effects)", credits, seconds: sound2.seconds } };
45320
45599
  } catch (e) {
45321
- if (missing(e)) return { kind: "none", record: { status: "unavailable" } };
45600
+ if (missing2(e)) return { kind: "none", record: { status: "unavailable" } };
45322
45601
  if (e instanceof PopostApiError) return { kind: "none", record: { status: "failed", why: "its price could not be read: " + firstLine(e) } };
45323
45602
  throw e;
45324
45603
  }
@@ -45351,7 +45630,7 @@ var init_analysis = __esm({
45351
45630
  if (done2.state !== "ready" || !done2.result) return { status: "failed", id: done2.id, chargedCredits: 0, why: done2.failure ?? "the analysis ended " + (done2.state || "without a result") };
45352
45631
  return { status: "done", id: done2.id, chargedCredits: charged, result: done2.result };
45353
45632
  } catch (e) {
45354
- if (missing(e)) return { status: "unavailable" };
45633
+ if (missing2(e)) return { status: "unavailable" };
45355
45634
  if (e instanceof AmbiguousSubmitError || e instanceof ToolError || e instanceof PopostApiError) return { status: "failed", why: firstLine(e) };
45356
45635
  throw e;
45357
45636
  }
@@ -46801,11 +47080,11 @@ var init_review2 = __esm({
46801
47080
  const seconds7 = Math.round(v.frames / v.fps * 1e3) / 1e3;
46802
47081
  const audio = rebind(old?.audio, [{ kind: "observed", detail: "The sound of the final video, all " + seconds7 + " s: its voices, music and effects against the reference.", file: v.file, sha256: v.fingerprint, media: "video", at: [0, seconds7] }], v, old?.artifactFingerprint, changed2);
46803
47082
  const visual = rebind(old?.visual, o.visual.map((f) => frameEvidence(v, f, "its medium, finish and layout against the reference.")), v, old?.artifactFingerprint, changed2);
46804
- const missing3 = [];
47083
+ const missing4 = [];
46805
47084
  const events = c.events.map((e) => {
46806
47085
  const planned = o.plan?.events.find((p) => p.id === e.id);
46807
47086
  const frames = o.events[e.id] ?? (planned ? spanFrames2(planned.span, v.frames) : void 0);
46808
- if (!frames) missing3.push(e.id);
47087
+ if (!frames) missing4.push(e.id);
46809
47088
  const names = ["lead-in", "middle", "resolved state"];
46810
47089
  const bound = (frames ?? []).map((f, k, all) => frameEvidence(v, f, (all.length === 3 ? names[k] : "a state") + ' of "' + short(e.description) + '" (' + e.id + ")."));
46811
47090
  return { id: e.id, ...rebind(old?.events?.find((x) => x.id === e.id), bound, v, old?.artifactFingerprint, changed2), frames: frames ?? [] };
@@ -46821,7 +47100,7 @@ var init_review2 = __esm({
46821
47100
  events: events.map(({ frames: _frames, ...finding }) => finding),
46822
47101
  ...old?.audioUses ? { audioUses: old.audioUses } : o.audioUses ? { audioUses: o.audioUses } : {}
46823
47102
  };
46824
- return { review: review3, changed: changed2, missing: missing3, frames: [{ name: "audio", frames: [] }, { name: "visual", frames: o.visual }, ...events.map((e) => ({ name: e.id, frames: e.frames }))] };
47103
+ return { review: review3, changed: changed2, missing: missing4, frames: [{ name: "audio", frames: [] }, { name: "visual", frames: o.visual }, ...events.map((e) => ({ name: e.id, frames: e.frames }))] };
46825
47104
  };
46826
47105
  withVerdicts = (r, passed, failed4) => {
46827
47106
  const names = /* @__PURE__ */ new Set(["audio", "visual", ...(r.events ?? []).map((e) => e.id)]);
@@ -47659,7 +47938,7 @@ var macDefaultBrowser = (handlers) => {
47659
47938
  const entry2 = handlers.match(/\{[^{}]*\}/g)?.find((item2) => /LSHandlerURLScheme\s*=\s*"?https"?\s*;/.test(item2));
47660
47939
  return entry2?.match(/LSHandlerRoleAll\s*=\s*"?([\w.-]+)"?\s*;/)?.[1]?.toLowerCase() ?? "";
47661
47940
  };
47662
- var browserCommands = (os, env, preferred, url) => {
47941
+ var browserCommands = (os, env2, preferred, url) => {
47663
47942
  if (os === "darwin") {
47664
47943
  const ids3 = ["com.apple.safari", "com.google.chrome", "org.mozilla.firefox", "com.microsoft.edgemac", "com.brave.browser", "com.operasoftware.opera", "company.thebrowser.browser"];
47665
47944
  return [.../* @__PURE__ */ new Set([...ids3.includes(preferred) ? [preferred] : [], ...ids3])].map((id2) => ({ command: "/usr/bin/open", args: ["-b", id2, url], wait: true }));
@@ -47672,9 +47951,9 @@ var browserCommands = (os, env, preferred, url) => {
47672
47951
  ["BraveHTML", "BraveSoftware/Brave-Browser/Application/brave.exe"]
47673
47952
  ];
47674
47953
  const ordered3 = apps2.filter(([id2]) => preferred.includes(id2)).concat(apps2);
47675
- return [...new Set(ordered3.flatMap(([, app]) => [env.ProgramFiles, env["ProgramFiles(x86)"], env.LOCALAPPDATA].filter((root) => Boolean(root)).map((root) => path2.win32.join(root, app))))].map((command2) => ({ command: command2, args: [url] }));
47954
+ return [...new Set(ordered3.flatMap(([, app]) => [env2.ProgramFiles, env2["ProgramFiles(x86)"], env2.LOCALAPPDATA].filter((root) => Boolean(root)).map((root) => path2.win32.join(root, app))))].map((command2) => ({ command: command2, args: [url] }));
47676
47955
  }
47677
- if (os !== "linux" || !env.DISPLAY && !env.WAYLAND_DISPLAY) return [];
47956
+ if (os !== "linux" || !env2.DISPLAY && !env2.WAYLAND_DISPLAY) return [];
47678
47957
  const apps = ["google-chrome", "chromium", "chromium-browser", "firefox", "microsoft-edge", "brave-browser", "opera"];
47679
47958
  const first = apps.find((app) => preferred.startsWith(app + ".") || preferred.startsWith(app + "-"));
47680
47959
  const roots2 = ["/usr/bin", "/usr/local/bin", "/opt/bin", "/snap/bin"];
@@ -47695,7 +47974,7 @@ var openSystemBrowser = async (url, host) => {
47695
47974
  };
47696
47975
 
47697
47976
  // src/node-runtime.ts
47698
- var missing2 = (error2) => error2?.code === "ENOENT";
47977
+ var missing3 = (error2) => error2?.code === "ENOENT";
47699
47978
  var nodeFileSystem = {
47700
47979
  realpath: (p) => fsp.realpath(p),
47701
47980
  readFile: async (p) => new Uint8Array(await fsp.readFile(p)),
@@ -47723,7 +48002,7 @@ var nodeFileSystem = {
47723
48002
  const s = await fsp.stat(p);
47724
48003
  return { isFile: s.isFile(), isDirectory: s.isDirectory(), size: s.size, mtimeMs: s.mtimeMs };
47725
48004
  } catch (error2) {
47726
- if (missing2(error2)) return null;
48005
+ if (missing3(error2)) return null;
47727
48006
  throw error2;
47728
48007
  }
47729
48008
  },
@@ -47765,8 +48044,8 @@ var runProgram = (argv, options = {}) => new Promise((resolve2, reject) => {
47765
48044
  return;
47766
48045
  }
47767
48046
  const [program, args2, lowerAfter] = commandLine(exe, rest, options);
47768
- const env = options.env ? { ...process.env, ...options.env } : process.env;
47769
- const child = spawn(program, args2, { cwd: options.cwd, stdio: ["pipe", "pipe", "pipe"], env });
48047
+ const env2 = options.env ? { ...process.env, ...options.env } : process.env;
48048
+ const child = spawn(program, args2, { cwd: options.cwd, stdio: ["pipe", "pipe", "pipe"], env: env2 });
47770
48049
  if (lowerAfter) lower(child.pid);
47771
48050
  const out2 = [];
47772
48051
  let err3 = "";
@@ -47867,7 +48146,7 @@ var readOptional = (file) => {
47867
48146
  try {
47868
48147
  return readFileSync(file, "utf8");
47869
48148
  } catch (error2) {
47870
- if (missing2(error2)) return null;
48149
+ if (missing3(error2)) return null;
47871
48150
  throw error2;
47872
48151
  }
47873
48152
  };
@@ -47944,8 +48223,8 @@ var createNodeRuntime = (profile2) => {
47944
48223
  }
47945
48224
  }
47946
48225
  const matchingManual = !site || site === manualSite;
47947
- const env = { ...applyStoredCredentials(raw, grant || !matchingManual ? null : manual) };
47948
- env.POPOST_BASE_URL ||= grant?.baseUrl || site && site + "/api/open/v1";
48226
+ const env2 = { ...applyStoredCredentials(raw, grant || !matchingManual ? null : manual) };
48227
+ env2.POPOST_BASE_URL ||= grant?.baseUrl || site && site + "/api/open/v1";
47949
48228
  const access = grant ? deviceTokenProvider(grant, globalThis.fetch) : void 0;
47950
48229
  const accountFile = (file) => {
47951
48230
  try {
@@ -47956,8 +48235,8 @@ var createNodeRuntime = (profile2) => {
47956
48235
  };
47957
48236
  const signature2 = () => [accountFile(deviceLocation(location)), accountFile(credentialsFile(location))].join("\n");
47958
48237
  let lastSignature = signature2();
47959
- const credentialScope = createHash19("sha256").update(grant ? grant.baseUrl + "\n" + grant.publicKey : env.POPOST_API_KEY ?? "anonymous").digest("hex");
47960
- let account = { env, deviceAccess: access, credentialScope };
48238
+ const credentialScope = createHash19("sha256").update(grant ? grant.baseUrl + "\n" + grant.publicKey : env2.POPOST_API_KEY ?? "anonymous").digest("hex");
48239
+ let account = { env: env2, deviceAccess: access, credentialScope };
47961
48240
  return {
47962
48241
  refreshAccount: () => {
47963
48242
  const next = signature2();
@@ -47971,7 +48250,7 @@ var createNodeRuntime = (profile2) => {
47971
48250
  fs: nodeFileSystem,
47972
48251
  path: path3,
47973
48252
  cwd,
47974
- env,
48253
+ env: env2,
47975
48254
  deviceName: hostname().replace(/[^\p{L}\p{N}._-]/gu, "-").slice(0, 38),
47976
48255
  explicitApiKey: Boolean(raw.POPOST_API_KEY?.trim()),
47977
48256
  deviceAccess: access,