popost 4.6.7 → 4.6.8
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/SKILL.md +5 -5
- package/assets/canvas/assets/{dist-BmD8AP0A.js → dist-CX2mxpwq.js} +1 -1
- package/assets/canvas/assets/{es-CC29Cabv.js → es-BFnFFu6P.js} +1 -1
- package/assets/canvas/assets/{index-DS6BKqT0.css → index-C5rz5H21.css} +1 -1
- package/assets/canvas/assets/{index-DhwyFpu2.js → index-CwqBT_rk.js} +1 -1
- package/assets/canvas/assets/{jszip.min-Bwf_yCrF.js → jszip.min-DqfCBLrH.js} +1 -1
- package/assets/canvas/build-info.json +7 -7
- package/assets/canvas/index.html +2 -2
- package/dist/cli.js +765 -537
- package/dist/index.js +234 -101
- package/dist/types/cloud/service.d.ts +2 -0
- package/dist/types/device-login.d.ts +6 -1
- package/dist/types/device-pending.d.ts +11 -0
- package/dist/types/editor/handoff.d.ts +1 -1
- package/dist/types/runtime.d.ts +5 -1
- package/dist/types/system-browser.d.ts +17 -0
- package/dist/types/version.d.ts +1 -1
- package/dist/types/video/compile/footage.d.ts +2 -0
- package/dist/types/video/compile/index.d.ts +2 -0
- package/dist/types/video/compile/page-bundle.d.ts +1 -1
- package/dist/types/video/compile/page.d.ts +1 -0
- package/dist/types/video/media/footage.d.ts +1 -0
- package/dist/types/video/page/contract.d.ts +2 -0
- package/dist/types/video/preview/protocol.d.ts +1 -0
- package/dist/types/video/preview/reference.d.ts +9 -0
- package/dist/types/video/preview/shell/footage.d.ts +1 -0
- package/dist/types/video/preview/shell/i18n.d.ts +1 -0
- package/dist/types/video/preview/shell/studio/copy.d.ts +1 -0
- package/dist/types/video/preview/shell/studio/style.d.ts +1 -1
- package/dist/types/video/preview/shell-bundle.d.ts +1 -1
- package/dist/types/workflow/post-bundle.d.ts +9 -2
- package/package.json +1 -1
- package/references/host-editor.md +2 -2
- package/references/onboarding.md +5 -3
- package/references/post-bundle.md +1 -1
- package/references/providers.md +1 -1
- package/references/video-editing.md +4 -0
package/dist/cli.js
CHANGED
|
@@ -128,34 +128,34 @@ var init_error_text = __esm({
|
|
|
128
128
|
};
|
|
129
129
|
isSystemError = (error2) => error2 instanceof Error && /^E[A-Z]+$/.test(codeOf(error2) ?? "");
|
|
130
130
|
pathOf = (error2) => {
|
|
131
|
-
const { path:
|
|
132
|
-
if (typeof
|
|
131
|
+
const { path: path4, message: message2 } = fields(error2);
|
|
132
|
+
if (typeof path4 === "string" && path4) return path4;
|
|
133
133
|
return typeof message2 === "string" ? /'([^']*)'\s*$/.exec(message2)?.[1] : void 0;
|
|
134
134
|
};
|
|
135
|
-
fileErrorText = (code,
|
|
135
|
+
fileErrorText = (code, path4) => {
|
|
136
136
|
switch (code) {
|
|
137
137
|
case "ENOENT":
|
|
138
|
-
return msg(`file not found: ${
|
|
138
|
+
return msg(`file not found: ${path4}`, `\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${path4}`);
|
|
139
139
|
case "EISDIR":
|
|
140
|
-
return msg(`${
|
|
140
|
+
return msg(`${path4} is a folder, not a file`, `${path4} \u662F\u6587\u4EF6\u5939\uFF0C\u4E0D\u662F\u6587\u4EF6`);
|
|
141
141
|
case "ENOTDIR":
|
|
142
|
-
return msg(`a part of ${
|
|
142
|
+
return msg(`a part of ${path4} is a file, not a folder`, `${path4} \u8DEF\u5F84\u4E2D\u6709\u4E00\u6BB5\u662F\u6587\u4EF6\u800C\u4E0D\u662F\u6587\u4EF6\u5939`);
|
|
143
143
|
case "EACCES":
|
|
144
144
|
case "EPERM":
|
|
145
|
-
return msg(`permission denied: ${
|
|
145
|
+
return msg(`permission denied: ${path4}`, `\u6CA1\u6709\u6743\u9650\u8BBF\u95EE\uFF1A${path4}`);
|
|
146
146
|
case "EEXIST":
|
|
147
|
-
return msg(`already exists: ${
|
|
147
|
+
return msg(`already exists: ${path4}`, `\u5DF2\u5B58\u5728\uFF1A${path4}`);
|
|
148
148
|
case "ENOTEMPTY":
|
|
149
|
-
return msg(`the folder is not empty: ${
|
|
149
|
+
return msg(`the folder is not empty: ${path4}`, `\u6587\u4EF6\u5939\u4E0D\u4E3A\u7A7A\uFF1A${path4}`);
|
|
150
150
|
case "ENOSPC":
|
|
151
|
-
return msg(`no space left on the disk for ${
|
|
151
|
+
return msg(`no space left on the disk for ${path4}`, `\u78C1\u76D8\u7A7A\u95F4\u4E0D\u8DB3\uFF0C\u65E0\u6CD5\u5199\u5165 ${path4}`);
|
|
152
152
|
default:
|
|
153
153
|
return void 0;
|
|
154
154
|
}
|
|
155
155
|
};
|
|
156
156
|
systemErrorText = (error2) => {
|
|
157
|
-
const
|
|
158
|
-
return
|
|
157
|
+
const path4 = pathOf(error2);
|
|
158
|
+
return path4 === void 0 ? void 0 : fileErrorText(error2.code, path4);
|
|
159
159
|
};
|
|
160
160
|
quoted = (value) => {
|
|
161
161
|
if (value === void 0 || value === null) return msg("nothing", "\u7A7A\u503C");
|
|
@@ -232,7 +232,7 @@ var init_util = __esm({
|
|
|
232
232
|
return code;
|
|
233
233
|
};
|
|
234
234
|
sha256 = (data) => createHash("sha256").update(data).digest("hex");
|
|
235
|
-
sha256File = async (rt,
|
|
235
|
+
sha256File = async (rt, path4) => sha256(await rt.fs.readFile(path4));
|
|
236
236
|
pad = (n) => String(n).padStart(2, "0");
|
|
237
237
|
isoNow = (rt) => {
|
|
238
238
|
const now = rt.now();
|
|
@@ -241,15 +241,15 @@ var init_util = __esm({
|
|
|
241
241
|
const abs = Math.abs(offset);
|
|
242
242
|
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}${sign2}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`;
|
|
243
243
|
};
|
|
244
|
-
writeAtomic = async (rt,
|
|
245
|
-
const tmp = `${
|
|
244
|
+
writeAtomic = async (rt, path4, data) => {
|
|
245
|
+
const tmp = `${path4}.tmp`;
|
|
246
246
|
await rt.fs.writeFile(tmp, data);
|
|
247
|
-
await rt.fs.rename(tmp,
|
|
247
|
+
await rt.fs.rename(tmp, path4);
|
|
248
248
|
};
|
|
249
|
-
readJson = async (rt,
|
|
250
|
-
writeJson = (rt,
|
|
251
|
-
isFile = async (rt,
|
|
252
|
-
isDir = async (rt,
|
|
249
|
+
readJson = async (rt, path4) => JSON.parse(await rt.fs.readText(path4));
|
|
250
|
+
writeJson = (rt, path4, value) => writeAtomic(rt, path4, JSON.stringify(value, null, 2));
|
|
251
|
+
isFile = async (rt, path4) => (await rt.fs.stat(path4))?.isFile ?? false;
|
|
252
|
+
isDir = async (rt, path4) => (await rt.fs.stat(path4))?.isDirectory ?? false;
|
|
253
253
|
walkFiles = async (rt, dir) => {
|
|
254
254
|
if (!await isDir(rt, dir)) return [];
|
|
255
255
|
const out2 = [];
|
|
@@ -261,9 +261,9 @@ var init_util = __esm({
|
|
|
261
261
|
}
|
|
262
262
|
return out2;
|
|
263
263
|
};
|
|
264
|
-
relPosix = (rt, root,
|
|
265
|
-
isInside = (rt, root,
|
|
266
|
-
const rel = rt.path.relative(rt.path.resolve(root), rt.path.resolve(root,
|
|
264
|
+
relPosix = (rt, root, path4) => rt.path.relative(root, path4).split(rt.path.sep).join("/");
|
|
265
|
+
isInside = (rt, root, path4) => {
|
|
266
|
+
const rel = rt.path.relative(rt.path.resolve(root), rt.path.resolve(root, path4));
|
|
267
267
|
return rel === "" || !rel.startsWith("..") && !rt.path.isAbsolute(rel);
|
|
268
268
|
};
|
|
269
269
|
escapeHtml = (text13) => text13.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
@@ -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.
|
|
278
|
+
VERSION = "4.6.8";
|
|
279
279
|
}
|
|
280
280
|
});
|
|
281
281
|
|
|
@@ -300,10 +300,10 @@ var init_errors = __esm({
|
|
|
300
300
|
name = "KeyError";
|
|
301
301
|
};
|
|
302
302
|
OsError = class extends Error {
|
|
303
|
-
constructor(code,
|
|
304
|
-
super(fileErrorText(code,
|
|
303
|
+
constructor(code, path4) {
|
|
304
|
+
super(fileErrorText(code, path4));
|
|
305
305
|
this.code = code;
|
|
306
|
-
this.path =
|
|
306
|
+
this.path = path4;
|
|
307
307
|
}
|
|
308
308
|
code;
|
|
309
309
|
path;
|
|
@@ -534,10 +534,10 @@ body { font-family: system-ui, sans-serif; }
|
|
|
534
534
|
}
|
|
535
535
|
/** `font install` writes `fonts-manifest.json`; loading merges it into `manifest.fonts`. */
|
|
536
536
|
async syncInstalledFonts() {
|
|
537
|
-
const
|
|
538
|
-
if (!await isFile(this.rt,
|
|
537
|
+
const path4 = this.rt.path.join(this.root, "fonts-manifest.json");
|
|
538
|
+
if (!await isFile(this.rt, path4)) return;
|
|
539
539
|
try {
|
|
540
|
-
const data = await readJson(this.rt,
|
|
540
|
+
const data = await readJson(this.rt, path4);
|
|
541
541
|
const installed = data.installed_roles ?? data.installed ?? [];
|
|
542
542
|
const current = new Map(this.manifest.fonts.map((f) => [String(f.id), f]));
|
|
543
543
|
for (const entry2 of installed)
|
|
@@ -583,22 +583,22 @@ body { font-family: system-ui, sans-serif; }
|
|
|
583
583
|
}
|
|
584
584
|
/** Writing different HTML drops the page's visual review and the series review: they no longer match. */
|
|
585
585
|
async writePageHtml(pid, html2) {
|
|
586
|
-
const
|
|
587
|
-
if (!await isFile(this.rt,
|
|
586
|
+
const path4 = this.pageHtmlPath(pid);
|
|
587
|
+
if (!await isFile(this.rt, path4) || await this.readPageHtml(pid) !== html2) {
|
|
588
588
|
delete this.manifest.reviews[pid];
|
|
589
589
|
delete this.manifest.seriesReview;
|
|
590
590
|
}
|
|
591
|
-
await writeAtomic(this.rt,
|
|
592
|
-
return
|
|
591
|
+
await writeAtomic(this.rt, path4, html2);
|
|
592
|
+
return path4;
|
|
593
593
|
}
|
|
594
594
|
// ---------- assets / fonts / sources ----------
|
|
595
595
|
async addAssetBytes(data, relName, kind = "image") {
|
|
596
596
|
const stem = relName.replace(/\.[^.]*$/, "");
|
|
597
597
|
if (!SAFE_ID.test(stem)) throw new ProjectError(msg(`invalid asset name: ${quoted(relName)}`, `\u8D44\u4EA7\u540D\u975E\u6CD5: ${quoted(relName)}`));
|
|
598
|
-
const
|
|
599
|
-
await this.rt.fs.writeFile(this.abs(
|
|
600
|
-
const entry2 = { id: stem, path:
|
|
601
|
-
this.manifest.assets = [...this.manifest.assets.filter((a) => a.path !==
|
|
598
|
+
const path4 = `assets/${relName}`;
|
|
599
|
+
await this.rt.fs.writeFile(this.abs(path4), data);
|
|
600
|
+
const entry2 = { id: stem, path: path4, sha256: sha256(data), kind };
|
|
601
|
+
this.manifest.assets = [...this.manifest.assets.filter((a) => a.path !== path4), entry2];
|
|
602
602
|
await this.saveManifest();
|
|
603
603
|
return entry2;
|
|
604
604
|
}
|
|
@@ -646,19 +646,19 @@ body { font-family: system-ui, sans-serif; }
|
|
|
646
646
|
await this.saveManifest();
|
|
647
647
|
}
|
|
648
648
|
/** A file the user named, relative to the working directory; a missing one is an `OsError` naming it. */
|
|
649
|
-
async readReferenceFile(
|
|
650
|
-
const full = this.rt.path.resolve(this.rt.cwd,
|
|
649
|
+
async readReferenceFile(path4) {
|
|
650
|
+
const full = this.rt.path.resolve(this.rt.cwd, path4);
|
|
651
651
|
const stat2 = await this.rt.fs.stat(full);
|
|
652
|
-
if (!stat2) throw new OsError("ENOENT",
|
|
653
|
-
if (stat2.isDirectory) throw new OsError("EISDIR",
|
|
652
|
+
if (!stat2) throw new OsError("ENOENT", path4);
|
|
653
|
+
if (stat2.isDirectory) throw new OsError("EISDIR", path4);
|
|
654
654
|
return this.rt.fs.readFile(full);
|
|
655
655
|
}
|
|
656
656
|
/** Copy a local reference image into `reference/`; the one composition contact sheet of a series is `concept`. */
|
|
657
|
-
async importReference(
|
|
658
|
-
const data = await this.readReferenceFile(
|
|
659
|
-
sniffImage(data,
|
|
657
|
+
async importReference(path4, role = "layout", pageId = null, concept2 = false) {
|
|
658
|
+
const data = await this.readReferenceFile(path4);
|
|
659
|
+
sniffImage(data, path4);
|
|
660
660
|
const digest2 = sha256(data);
|
|
661
|
-
const extension = this.rt.path.extname(
|
|
661
|
+
const extension = this.rt.path.extname(path4).toLowerCase();
|
|
662
662
|
const folder = this.rt.path.join(this.root, "reference");
|
|
663
663
|
await this.rt.fs.mkdir(folder);
|
|
664
664
|
const name = (concept2 ? "composition-reference" : digest2.slice(0, 16)) + extension;
|
|
@@ -734,13 +734,13 @@ var init_io = __esm({
|
|
|
734
734
|
"use strict";
|
|
735
735
|
init_i18n();
|
|
736
736
|
init_errors2();
|
|
737
|
-
fromCwd = (rt,
|
|
737
|
+
fromCwd = (rt, path4) => rt.path.resolve(rt.cwd, path4);
|
|
738
738
|
checked = async (rt, userPath2) => {
|
|
739
|
-
const
|
|
740
|
-
const stat2 = await rt.fs.stat(
|
|
739
|
+
const path4 = fromCwd(rt, userPath2);
|
|
740
|
+
const stat2 = await rt.fs.stat(path4);
|
|
741
741
|
if (!stat2) throw new OsError("ENOENT", userPath2);
|
|
742
742
|
if (stat2.isDirectory) throw new OsError("EISDIR", userPath2);
|
|
743
|
-
return
|
|
743
|
+
return path4;
|
|
744
744
|
};
|
|
745
745
|
readUserBytes = async (rt, userPath2) => rt.fs.readFile(await checked(rt, userPath2));
|
|
746
746
|
readUserText = async (rt, userPath2) => rt.fs.readText(await checked(rt, userPath2));
|
|
@@ -762,7 +762,7 @@ var init_io = __esm({
|
|
|
762
762
|
});
|
|
763
763
|
|
|
764
764
|
// src/workflow/post-bundle.ts
|
|
765
|
-
var SCHEMA2, PLATFORMS, PARSE_STATUSES, RESOURCE_KINDS, serviceConfig, isPlatform, utcNow, PLATFORM_HOSTS, hostOf2, platformOfUrl, checkTicketUrl, makePendingTicket, platformError, getOr, isStringList, validateResources, validateHeader, validateMeta, validateBundle, resourceBlocker, evaluateBuildable;
|
|
765
|
+
var SCHEMA2, PLATFORMS, PARSE_STATUSES, RESOURCE_KINDS, serviceConfig, isPlatform, utcNow, PLATFORM_HOSTS, PLATFORM_NAMES, platformNameList, hostOf2, platformOfUrl, checkTicketUrl, makePendingTicket, platformError, getOr, isStringList, validateResources, validateHeader, validateMeta, validateBundle, resourceBlocker, evaluateBuildable;
|
|
766
766
|
var init_post_bundle = __esm({
|
|
767
767
|
"src/workflow/post-bundle.ts"() {
|
|
768
768
|
"use strict";
|
|
@@ -772,7 +772,7 @@ var init_post_bundle = __esm({
|
|
|
772
772
|
init_io();
|
|
773
773
|
init_errors2();
|
|
774
774
|
SCHEMA2 = "postbundle.v1";
|
|
775
|
-
PLATFORMS = ["tiktok", "xiaohongshu", "instagram", "douyin", "x", "youtube"];
|
|
775
|
+
PLATFORMS = ["tiktok", "xiaohongshu", "instagram", "douyin", "x", "youtube", "threads", "linkedin", "reddit", "bilibili", "lemon8", "kuaishou", "wechat", "weibo"];
|
|
776
776
|
PARSE_STATUSES = ["pending", "ready", "auth_failed", "missing_resources", "error"];
|
|
777
777
|
RESOURCE_KINDS = ["image", "video", "music"];
|
|
778
778
|
serviceConfig = () => ({
|
|
@@ -794,7 +794,36 @@ var init_post_bundle = __esm({
|
|
|
794
794
|
xiaohongshu: ["xiaohongshu.com", "xhslink.com"],
|
|
795
795
|
instagram: ["instagram.com"],
|
|
796
796
|
x: ["x.com", "twitter.com"],
|
|
797
|
-
youtube: ["youtube.com", "youtu.be", "youtube-nocookie.com"]
|
|
797
|
+
youtube: ["youtube.com", "youtu.be", "youtube-nocookie.com"],
|
|
798
|
+
threads: ["threads.com", "threads.net"],
|
|
799
|
+
linkedin: ["linkedin.com", "lnkd.in"],
|
|
800
|
+
reddit: ["reddit.com", "redd.it"],
|
|
801
|
+
bilibili: ["bilibili.com", "b23.tv"],
|
|
802
|
+
lemon8: ["lemon8-app.com"],
|
|
803
|
+
kuaishou: ["kuaishou.com", "kuaishou.cn", "chenzhongtech.com", "gifshow.com"],
|
|
804
|
+
wechat: ["weixin.qq.com"],
|
|
805
|
+
weibo: ["weibo.com", "weibo.cn", "t.cn"]
|
|
806
|
+
};
|
|
807
|
+
PLATFORM_NAMES = {
|
|
808
|
+
tiktok: { en: "TikTok", zh: "TikTok" },
|
|
809
|
+
douyin: { en: "Douyin", zh: "\u6296\u97F3" },
|
|
810
|
+
xiaohongshu: { en: "Xiaohongshu", zh: "\u5C0F\u7EA2\u4E66" },
|
|
811
|
+
instagram: { en: "Instagram", zh: "Instagram" },
|
|
812
|
+
x: { en: "X", zh: "X" },
|
|
813
|
+
youtube: { en: "YouTube", zh: "YouTube" },
|
|
814
|
+
threads: { en: "Threads", zh: "Threads" },
|
|
815
|
+
linkedin: { en: "LinkedIn", zh: "LinkedIn" },
|
|
816
|
+
reddit: { en: "Reddit", zh: "Reddit" },
|
|
817
|
+
bilibili: { en: "Bilibili", zh: "\u54D4\u54E9\u54D4\u54E9" },
|
|
818
|
+
lemon8: { en: "Lemon8", zh: "Lemon8" },
|
|
819
|
+
kuaishou: { en: "Kuaishou", zh: "\u5FEB\u624B" },
|
|
820
|
+
wechat: { en: "WeChat", zh: "\u5FAE\u4FE1" },
|
|
821
|
+
weibo: { en: "Weibo", zh: "\u5FAE\u535A" }
|
|
822
|
+
};
|
|
823
|
+
platformNameList = (conjunction) => {
|
|
824
|
+
const en = PLATFORMS.map((p) => PLATFORM_NAMES[p].en);
|
|
825
|
+
const zh = PLATFORMS.map((p) => PLATFORM_NAMES[p].zh);
|
|
826
|
+
return msg(`${en.slice(0, -1).join(", ")} ${conjunction} ${en.at(-1)}`, `${zh.slice(0, -1).join("\u3001")}${conjunction === "or" ? "\u6216" : "\u548C"}${zh.at(-1)}`);
|
|
798
827
|
};
|
|
799
828
|
hostOf2 = (url) => {
|
|
800
829
|
try {
|
|
@@ -906,12 +935,12 @@ var init_post_bundle = __esm({
|
|
|
906
935
|
};
|
|
907
936
|
resourceBlocker = async (rt, res, baseDir) => {
|
|
908
937
|
const id2 = plain(getOr(res, "id", "?"));
|
|
909
|
-
const
|
|
910
|
-
if (truthy(
|
|
911
|
-
const text13 = String(
|
|
938
|
+
const path4 = res.path;
|
|
939
|
+
if (truthy(path4)) {
|
|
940
|
+
const text13 = String(path4);
|
|
912
941
|
const full = rt.path.isAbsolute(text13) || !baseDir ? text13 : rt.path.join(baseDir, text13);
|
|
913
942
|
if ((await rt.fs.stat(fromCwd(rt, full)))?.isFile) return null;
|
|
914
|
-
return msg(`resource ${id2} has no picture: the local file ${quoted(
|
|
943
|
+
return msg(`resource ${id2} has no picture: the local file ${quoted(path4)} does not exist`, `resource ${id2} \u7F3A\u56FE\uFF1A\u672C\u5730\u6587\u4EF6\u4E0D\u5B58\u5728 ${quoted(path4)}`);
|
|
915
944
|
}
|
|
916
945
|
if (truthy(res.url))
|
|
917
946
|
return truthy(res.license) ? null : msg(`resource ${id2} has only a url and no license or attribution: authorization is missing`, `resource ${id2} \u4EC5\u7ED9 url \u4F46\u65E0 license/\u7F72\u540D\uFF0C\u7F3A\u6388\u6743`);
|
|
@@ -1072,19 +1101,19 @@ var init_series_plan = __esm({
|
|
|
1072
1101
|
];
|
|
1073
1102
|
};
|
|
1074
1103
|
load = async (project) => {
|
|
1075
|
-
const
|
|
1076
|
-
return await isFile(project.rt,
|
|
1104
|
+
const path4 = project.abs(PLAN_FILE);
|
|
1105
|
+
return await isFile(project.rt, path4) ? await readJson(project.rt, path4) : null;
|
|
1077
1106
|
};
|
|
1078
1107
|
digest = (plan4) => createHash3("sha256").update(pyJson(plan4, true), "utf8").digest("hex");
|
|
1079
1108
|
save = async (project, plan4) => {
|
|
1080
1109
|
const errors = validate(plan4, project.manifest.pages.map((page2) => page2.id));
|
|
1081
1110
|
if (errors.length) throw new ValueError(errors.join("; "));
|
|
1082
|
-
const
|
|
1083
|
-
await writeJson(project.rt,
|
|
1111
|
+
const path4 = project.abs(PLAN_FILE);
|
|
1112
|
+
await writeJson(project.rt, path4, plan4);
|
|
1084
1113
|
project.manifest.seriesPlan = { path: PLAN_FILE, sha256: digest(plan4) };
|
|
1085
1114
|
delete project.manifest.seriesReview;
|
|
1086
1115
|
await project.saveManifest();
|
|
1087
|
-
return
|
|
1116
|
+
return path4;
|
|
1088
1117
|
};
|
|
1089
1118
|
panelText = (page2, index) => {
|
|
1090
1119
|
const next = "swipeReason" in page2 ? pyStr(page2.swipeReason) : "deliver the payoff and finish";
|
|
@@ -1131,19 +1160,19 @@ var init_template_plugins = __esm({
|
|
|
1131
1160
|
}
|
|
1132
1161
|
return fields2;
|
|
1133
1162
|
};
|
|
1134
|
-
readSkillText = async (rt,
|
|
1163
|
+
readSkillText = async (rt, path4) => {
|
|
1135
1164
|
try {
|
|
1136
1165
|
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
1137
|
-
return decoder.decode(await rt.fs.readFile(
|
|
1166
|
+
return decoder.decode(await rt.fs.readFile(path4)).replace(/\r\n?/g, "\n");
|
|
1138
1167
|
} catch (error2) {
|
|
1139
1168
|
if (error2 instanceof TypeError) return null;
|
|
1140
1169
|
throw error2;
|
|
1141
1170
|
}
|
|
1142
1171
|
};
|
|
1143
|
-
isFile2 = async (rt,
|
|
1144
|
-
listReferences = async (rt,
|
|
1172
|
+
isFile2 = async (rt, path4) => (await rt.fs.stat(path4))?.isFile ?? false;
|
|
1173
|
+
listReferences = async (rt, path4, text13) => {
|
|
1145
1174
|
const references = [];
|
|
1146
|
-
const dir = rt.path.join(
|
|
1175
|
+
const dir = rt.path.join(path4, "references");
|
|
1147
1176
|
if ((await rt.fs.stat(dir))?.isDirectory) {
|
|
1148
1177
|
const names = (await rt.fs.readdir(dir)).sort(compareCodePoints);
|
|
1149
1178
|
for (const name of names.filter((n) => n.endsWith(".md") || n.endsWith(".json"))) {
|
|
@@ -1155,7 +1184,7 @@ var init_template_plugins = __esm({
|
|
|
1155
1184
|
for (const [, link] of text13.matchAll(/\]\(([^)]+)\)/g)) {
|
|
1156
1185
|
const rel = link.split("#", 1)[0].replace(/^[<>]+|[<>]+$/g, "");
|
|
1157
1186
|
if (!rel || rel.includes("://") || rel.startsWith("#")) continue;
|
|
1158
|
-
const full = rt.path.resolve(
|
|
1187
|
+
const full = rt.path.resolve(path4, rel);
|
|
1159
1188
|
if (known2.has(full)) continue;
|
|
1160
1189
|
references.push({ path: full, exists: await isFile2(rt, full) });
|
|
1161
1190
|
known2.add(full);
|
|
@@ -1163,15 +1192,15 @@ var init_template_plugins = __esm({
|
|
|
1163
1192
|
return references;
|
|
1164
1193
|
};
|
|
1165
1194
|
locateSkill = async (rt, userPath2) => {
|
|
1166
|
-
const
|
|
1167
|
-
let skillMd = rt.path.join(
|
|
1168
|
-
const alternative = rt.path.join(
|
|
1195
|
+
const path4 = fromCwd(rt, userPath2);
|
|
1196
|
+
let skillMd = rt.path.join(path4, "SKILL.md");
|
|
1197
|
+
const alternative = rt.path.join(path4, "SOURCE-SKILL.md");
|
|
1169
1198
|
if (!await isFile2(rt, skillMd) && await isFile2(rt, alternative)) skillMd = alternative;
|
|
1170
1199
|
if (!await isFile2(rt, skillMd))
|
|
1171
1200
|
return {
|
|
1172
1201
|
ok: false,
|
|
1173
1202
|
route: "error",
|
|
1174
|
-
path:
|
|
1203
|
+
path: path4,
|
|
1175
1204
|
error: msg(`SKILL.md is missing: ${skillMd} (a resource error; nothing is silently substituted)`, `SKILL.md \u7F3A\u5931\uFF1A${skillMd}\uFF08\u8D44\u6E90\u9519\u8BEF\uFF0C\u4E0D\u9759\u9ED8\u66FF\u6362\uFF09`)
|
|
1176
1205
|
};
|
|
1177
1206
|
const text13 = await readSkillText(rt, skillMd);
|
|
@@ -1179,17 +1208,17 @@ var init_template_plugins = __esm({
|
|
|
1179
1208
|
return {
|
|
1180
1209
|
ok: false,
|
|
1181
1210
|
route: "error",
|
|
1182
|
-
path:
|
|
1211
|
+
path: path4,
|
|
1183
1212
|
error: msg("SKILL.md is not valid UTF-8 (a resource error; no fallback to free creation)", "SKILL.md \u975E\u5408\u6CD5 UTF-8\uFF08\u8D44\u6E90\u9519\u8BEF\uFF0C\u4E0D\u964D\u7EA7\u81EA\u7531\u521B\u4F5C\uFF09")
|
|
1184
1213
|
};
|
|
1185
1214
|
const frontmatter = parseFrontmatter(text13);
|
|
1186
|
-
const references = await listReferences(rt,
|
|
1215
|
+
const references = await listReferences(rt, path4, text13);
|
|
1187
1216
|
const missingRefs = references.filter((r) => !r.exists).map((r) => r.path);
|
|
1188
1217
|
return {
|
|
1189
1218
|
ok: true,
|
|
1190
1219
|
route: "found",
|
|
1191
|
-
path:
|
|
1192
|
-
skillId: rt.path.basename(
|
|
1220
|
+
path: path4,
|
|
1221
|
+
skillId: rt.path.basename(path4),
|
|
1193
1222
|
name: frontmatter.name ?? "",
|
|
1194
1223
|
version: frontmatter.version ?? null,
|
|
1195
1224
|
sha256: sha256(text13),
|
|
@@ -1348,8 +1377,8 @@ var init_build = __esm({
|
|
|
1348
1377
|
};
|
|
1349
1378
|
referenceBlockers = async (project, source2) => {
|
|
1350
1379
|
const { rt } = project;
|
|
1351
|
-
const
|
|
1352
|
-
const intact =
|
|
1380
|
+
const path4 = typeof source2.path === "string" ? rt.path.resolve(project.root, source2.path) : null;
|
|
1381
|
+
const intact = path4 !== null && await isFile(rt, path4) && await sha256File(rt, path4) === source2.sha256;
|
|
1353
1382
|
return intact ? [] : [msg("a reference file is missing or changed: look at it again and register it again", "reference \u6587\u4EF6\u7F3A\u5931\u6216\u5DF2\u53D8\u66F4\uFF0C\u8BF7\u91CD\u65B0\u89C2\u5BDF\u5E76\u767B\u8BB0")];
|
|
1354
1383
|
};
|
|
1355
1384
|
templateBlockers = async (project, source2, notes2) => {
|
|
@@ -2076,18 +2105,18 @@ var init_offline = __esm({
|
|
|
2076
2105
|
return null;
|
|
2077
2106
|
}
|
|
2078
2107
|
if (!relative || relative.includes("\0")) return null;
|
|
2079
|
-
const
|
|
2080
|
-
if (!isInside(rt, root,
|
|
2108
|
+
const path4 = rt.path.resolve(root, relative);
|
|
2109
|
+
if (!isInside(rt, root, path4) || !await isFile(rt, path4)) return null;
|
|
2081
2110
|
if (rt.fs.realpath) {
|
|
2082
2111
|
try {
|
|
2083
|
-
const [realRoot, realFile] = await Promise.all([rt.fs.realpath(root), rt.fs.realpath(
|
|
2112
|
+
const [realRoot, realFile] = await Promise.all([rt.fs.realpath(root), rt.fs.realpath(path4)]);
|
|
2084
2113
|
if (!isInside(rt, realRoot, realFile)) return null;
|
|
2085
|
-
return { data: await rt.fs.readFile(realFile), path:
|
|
2114
|
+
return { data: await rt.fs.readFile(realFile), path: path4 };
|
|
2086
2115
|
} catch {
|
|
2087
2116
|
return null;
|
|
2088
2117
|
}
|
|
2089
2118
|
}
|
|
2090
|
-
return { data: await rt.fs.readFile(
|
|
2119
|
+
return { data: await rt.fs.readFile(path4), path: path4 };
|
|
2091
2120
|
};
|
|
2092
2121
|
respond = async (rt, root, blocked2, route2) => {
|
|
2093
2122
|
const request = route2.request();
|
|
@@ -2533,13 +2562,13 @@ var init_core = __esm({
|
|
|
2533
2562
|
options: [{ flag: "--path", required: true }, { flag: "--authorized", kind: "flag" }]
|
|
2534
2563
|
},
|
|
2535
2564
|
async (project, args2, rt) => {
|
|
2536
|
-
const
|
|
2537
|
-
const loc = await locateSkill(rt,
|
|
2565
|
+
const path4 = args2.req("path");
|
|
2566
|
+
const loc = await locateSkill(rt, path4);
|
|
2538
2567
|
if (!loc.ok) return fail(rt, loc.error);
|
|
2539
2568
|
const version = loc.version === null || loc.version === void 0 ? "?" : String(loc.version);
|
|
2540
2569
|
await project.addSource("template", `${loc.skillId} v${version} sha=${loc.sha256.slice(0, 12)} refs=${loc.missingRefs.length}`);
|
|
2541
2570
|
const source2 = project.manifest.sources.at(-1);
|
|
2542
|
-
Object.assign(source2, { path:
|
|
2571
|
+
Object.assign(source2, { path: path4, sha256: loc.sha256, version: loc.version, authorized: args2.flag("authorized") });
|
|
2543
2572
|
await project.appendDesignNote(`template: ${loc.skillId} v${version} (${loc.references.length} refs)`);
|
|
2544
2573
|
await project.saveManifest();
|
|
2545
2574
|
printJson(rt, { ok: true, attached: loc.skillId });
|
|
@@ -2711,11 +2740,11 @@ var init_project_bundle = __esm({
|
|
|
2711
2740
|
const { rt, root } = project;
|
|
2712
2741
|
const entries3 = /* @__PURE__ */ new Map([[MANIFEST_NAME, project.manifestPath]]);
|
|
2713
2742
|
for (const page2 of project.manifest.pages) {
|
|
2714
|
-
const
|
|
2715
|
-
if (!isInside(rt, root,
|
|
2716
|
-
entries3.set(page2.htmlPath,
|
|
2743
|
+
const path4 = rt.path.resolve(project.pageHtmlPath(page2.id));
|
|
2744
|
+
if (!isInside(rt, root, path4)) throw new ValueError(msg("page outside project", "\u9875\u9762\u5728\u5DE5\u7A0B\u76EE\u5F55\u4E4B\u5916"));
|
|
2745
|
+
entries3.set(page2.htmlPath, path4);
|
|
2717
2746
|
}
|
|
2718
|
-
const pending3 = [...entries3].filter(([rel]) => rel.endsWith(".html")).map(([,
|
|
2747
|
+
const pending3 = [...entries3].filter(([rel]) => rel.endsWith(".html")).map(([, path4]) => path4);
|
|
2719
2748
|
const visited = /* @__PURE__ */ new Set();
|
|
2720
2749
|
for (let source2 = pending3.pop(); source2 !== void 0; source2 = pending3.pop()) {
|
|
2721
2750
|
if (visited.has(source2)) continue;
|
|
@@ -2778,9 +2807,9 @@ var init_project_bundle = __esm({
|
|
|
2778
2807
|
}
|
|
2779
2808
|
return files;
|
|
2780
2809
|
};
|
|
2781
|
-
payload = (rt,
|
|
2810
|
+
payload = (rt, path4, data) => [
|
|
2782
2811
|
data,
|
|
2783
|
-
{ level:
|
|
2812
|
+
{ level: path4.endsWith(".woff2") ? 0 : 6, mtime: rt.now() }
|
|
2784
2813
|
];
|
|
2785
2814
|
exportProject = async (project, out2) => {
|
|
2786
2815
|
const { rt } = project;
|
|
@@ -2790,12 +2819,12 @@ var init_project_bundle = __esm({
|
|
|
2790
2819
|
const zippable = {};
|
|
2791
2820
|
const manifest = portableManifest(project, new Set(entries3.keys()));
|
|
2792
2821
|
zippable[MANIFEST_NAME] = payload(rt, MANIFEST_NAME, new TextEncoder().encode(JSON.stringify(manifest, null, 2)));
|
|
2793
|
-
for (const [rel,
|
|
2822
|
+
for (const [rel, path4] of entries3) {
|
|
2794
2823
|
if (rel === MANIFEST_NAME) continue;
|
|
2795
|
-
if (!await isFile(rt,
|
|
2796
|
-
zippable[rel] = payload(rt, rel, await rt.fs.readFile(
|
|
2824
|
+
if (!await isFile(rt, path4)) throw new ValueError(msg(`missing resource: ${rel}`, `\u8D44\u6E90\u7F3A\u5931\uFF1A${rel}`));
|
|
2825
|
+
zippable[rel] = payload(rt, rel, await rt.fs.readFile(path4));
|
|
2797
2826
|
}
|
|
2798
|
-
for (const [rel,
|
|
2827
|
+
for (const [rel, path4] of await runtimeFiles(rt)) zippable[rel] = payload(rt, rel, await rt.fs.readFile(path4));
|
|
2799
2828
|
zippable["OPEN.txt"] = payload(rt, "OPEN.txt", new TextEncoder().encode(openTxt()));
|
|
2800
2829
|
await writeAtomic(rt, target2, zipSync(zippable));
|
|
2801
2830
|
return target2;
|
|
@@ -2819,9 +2848,9 @@ var init_project_bundle = __esm({
|
|
|
2819
2848
|
if (Object.values(files).reduce((sum, bytes) => sum + bytes.length, 0) > MAX_EXPANDED) throw new ValueError(msg("project archive too large", "\u5DE5\u7A0B\u538B\u7F29\u5305\u8FC7\u5927"));
|
|
2820
2849
|
try {
|
|
2821
2850
|
for (const [name, bytes] of Object.entries(files)) {
|
|
2822
|
-
const
|
|
2823
|
-
if (!isInside(rt, dest,
|
|
2824
|
-
await rt.fs.writeFile(
|
|
2851
|
+
const path4 = rt.path.resolve(dest, name);
|
|
2852
|
+
if (!isInside(rt, dest, path4)) throw new ValueError(msg("unsafe archive path", "\u538B\u7F29\u5305\u91CC\u6709\u4E0D\u5B89\u5168\u7684\u8DEF\u5F84"));
|
|
2853
|
+
await rt.fs.writeFile(path4, bytes);
|
|
2825
2854
|
}
|
|
2826
2855
|
const project = await Project.load(rt, dest);
|
|
2827
2856
|
await verifyUnpacked(project);
|
|
@@ -3059,6 +3088,29 @@ var init_workflow = __esm({
|
|
|
3059
3088
|
}
|
|
3060
3089
|
});
|
|
3061
3090
|
|
|
3091
|
+
// src/device-pending.ts
|
|
3092
|
+
var savePrivate, readPending;
|
|
3093
|
+
var init_device_pending = __esm({
|
|
3094
|
+
"src/device-pending.ts"() {
|
|
3095
|
+
"use strict";
|
|
3096
|
+
savePrivate = async (rt, file, value) => {
|
|
3097
|
+
const tmp = file + "." + rt.randomUUID() + ".tmp";
|
|
3098
|
+
try {
|
|
3099
|
+
await rt.fs.writeFile(tmp, JSON.stringify(value), { private: true });
|
|
3100
|
+
await rt.fs.rename(tmp, file);
|
|
3101
|
+
} finally {
|
|
3102
|
+
await rt.fs.rm(tmp);
|
|
3103
|
+
}
|
|
3104
|
+
};
|
|
3105
|
+
readPending = async (rt, file) => {
|
|
3106
|
+
if (!await rt.fs.stat(file)) return null;
|
|
3107
|
+
const p = JSON.parse(await rt.fs.readText(file));
|
|
3108
|
+
if (!p || ![p.baseUrl, p.deviceCode, p.publicKey, p.privateKey, p.userCode].every((v) => typeof v === "string" && v.length > 0) || !Number.isFinite(p.expiresAt) || !Number.isFinite(p.interval)) throw new Error("Invalid pending connection");
|
|
3109
|
+
return p;
|
|
3110
|
+
};
|
|
3111
|
+
}
|
|
3112
|
+
});
|
|
3113
|
+
|
|
3062
3114
|
// src/providers/errors.ts
|
|
3063
3115
|
var ImageProviderError, AmbiguousSubmitError, CapabilityError, PopostApiError, LedgerError, CliReject, LOCAL_ERROR_CODES, exitCodeOf;
|
|
3064
3116
|
var init_errors3 = __esm({
|
|
@@ -3239,6 +3291,7 @@ var init_api_errors = __esm({
|
|
|
3239
3291
|
"use strict";
|
|
3240
3292
|
init_i18n();
|
|
3241
3293
|
init_version();
|
|
3294
|
+
init_post_bundle();
|
|
3242
3295
|
init_base();
|
|
3243
3296
|
DEFAULT_KEY_ENV = "POPOST_API_KEY";
|
|
3244
3297
|
DEFAULT_KEY_PAGE = "https://popost.ai/account/api-keys";
|
|
@@ -3252,8 +3305,8 @@ var init_api_errors = __esm({
|
|
|
3252
3305
|
const parts = [];
|
|
3253
3306
|
for (const issue4 of issues.slice(0, 8)) {
|
|
3254
3307
|
if (!isRecord(issue4)) continue;
|
|
3255
|
-
const
|
|
3256
|
-
parts.push(`${String(
|
|
3308
|
+
const path4 = Array.isArray(issue4.path) ? issue4.path.map(String).join(".") : issue4.path;
|
|
3309
|
+
parts.push(`${String(path4 || "-").slice(0, 80)}: ${String(issue4.message || "").slice(0, 120)}`);
|
|
3257
3310
|
}
|
|
3258
3311
|
if (!parts.length) return "";
|
|
3259
3312
|
return msg(`: ${parts.join("; ")}`, `\uFF1A${parts.join("\uFF1B")}`);
|
|
@@ -3267,8 +3320,8 @@ var init_api_errors = __esm({
|
|
|
3267
3320
|
switch (code) {
|
|
3268
3321
|
case "UNAUTHORIZED":
|
|
3269
3322
|
return msg(
|
|
3270
|
-
`The account connection is no longer valid. Run popost auth login to reconnect; connections are managed at ${DEFAULT_KEY_PAGE}.
|
|
3271
|
-
`\u8D26\u6237\u8FDE\u63A5\u5DF2\u5931\u6548\u3002\u8BF7\u8FD0\u884C popost auth login \u91CD\u65B0\u8FDE\u63A5\uFF0C\u53EF\u5728 ${DEFAULT_KEY_PAGE} \u7BA1\u7406\u8FDE\u63A5\u3002\
|
|
3323
|
+
`The account connection is no longer valid. Run popost auth login --no-wait to reconnect; connections are managed at ${DEFAULT_KEY_PAGE}. If you choose API Key connection, create a Key and copy the one-time command from API Key step 2 into the Agent chat (5-minute expiry, one use; no long-lived Key in chat). Script environments may also configure ${keyEnv}.`,
|
|
3324
|
+
`\u8D26\u6237\u8FDE\u63A5\u5DF2\u5931\u6548\u3002\u8BF7\u8FD0\u884C popost auth login --no-wait \u91CD\u65B0\u8FDE\u63A5\uFF0C\u53EF\u5728 ${DEFAULT_KEY_PAGE} \u7BA1\u7406\u8FDE\u63A5\u3002\u5982\u9009\u62E9 API Key \u8FDE\u63A5\uFF0C\u8BF7\u521B\u5EFA Key \u540E\u590D\u5236 API Key \u7B2C 2 \u6B65\u7684\u4E00\u6B21\u6027\u6307\u4EE4\u5230 Agent \u804A\u5929\u6846\uFF085 \u5206\u949F\u6709\u6548\u3001\u4EC5\u4E00\u6B21\uFF0C\u957F\u671F Key \u4E0D\u51FA\u73B0\u5728\u804A\u5929\u4E2D\uFF09\u3002\u811A\u672C\u73AF\u5883\u4E5F\u53EF\u914D\u7F6E ${keyEnv}\u3002`
|
|
3272
3325
|
);
|
|
3273
3326
|
case "FORBIDDEN":
|
|
3274
3327
|
return msg("popost.ai refused access: this account is not allowed to do that", "popost.ai \u62D2\u7EDD\u8BBF\u95EE\uFF1A\u5F53\u524D\u8D26\u6237\u65E0\u6743\u6267\u884C\u8BE5\u64CD\u4F5C");
|
|
@@ -3276,8 +3329,8 @@ var init_api_errors = __esm({
|
|
|
3276
3329
|
return msg("popost.ai cannot find the requested resource (check the baseUrl, the model or the object id)", "popost.ai \u627E\u4E0D\u5230\u8BF7\u6C42\u7684\u8D44\u6E90\uFF08\u68C0\u67E5 baseUrl\u3001\u6A21\u578B\u6216\u5BF9\u8C61 id\uFF09");
|
|
3277
3330
|
case "LINK_UNSUPPORTED":
|
|
3278
3331
|
return msg(
|
|
3279
|
-
|
|
3280
|
-
|
|
3332
|
+
`popost.ai does not support this link: only post links from ${platformNameList("and")} are supported (no task was created, no credits were charged)`,
|
|
3333
|
+
`popost.ai \u4E0D\u652F\u6301\u8FD9\u4E2A\u94FE\u63A5\uFF1A\u53EA\u652F\u6301${platformNameList("and")}\u7684\u5E16\u5B50\u94FE\u63A5\uFF08\u672A\u5EFA\u4EFB\u52A1\uFF0C\u672A\u6263\u79EF\u5206\uFF09`
|
|
3281
3334
|
);
|
|
3282
3335
|
case "LINK_IMPORT_NOT_FOUND":
|
|
3283
3336
|
return msg("popost.ai cannot find this parsing task (the id is wrong, or the task belongs to another account)", "popost.ai \u627E\u4E0D\u5230\u8FD9\u4E2A\u89E3\u6790\u4EFB\u52A1\uFF08id \u6709\u8BEF\uFF0C\u6216\u4E0D\u662F\u5F53\u524D\u8D26\u6237\u7684\u4EFB\u52A1\uFF09");
|
|
@@ -3434,8 +3487,8 @@ var init_credentials = __esm({
|
|
|
3434
3487
|
return `${origin}/account/api-keys`;
|
|
3435
3488
|
};
|
|
3436
3489
|
keyGuidance = (page2, keyEnv) => msg(
|
|
3437
|
-
`
|
|
3438
|
-
`\u8FD0\u884C popost auth login\uFF0C\
|
|
3490
|
+
`Browser authorization is the default: run popost auth login --no-wait and let the CLI open the desktop browser and show the device code. Never use an Agent sidebar or browser tool for sign-in. After approval, rerun the same command to resume, then verify with popost account. Manage connections: ${page2}. Only if the user chooses API Key connection, create a Key and copy the one-time command from API Key step 2 into the Agent chat. It connects the newest active Key automatically; the code expires in 5 minutes and works once, and the long-lived Key stays out of chat. Scripts may also configure ${keyEnv}`,
|
|
3491
|
+
`\u9ED8\u8BA4\u4F7F\u7528\u6D4F\u89C8\u5668\u6388\u6743\uFF1A\u8FD0\u884C popost auth login --no-wait\uFF0C\u7531 CLI \u6253\u5F00\u72EC\u7ACB\u684C\u9762\u6D4F\u89C8\u5668\u5E76\u5C55\u793A\u8BBE\u5907\u7801\uFF0C\u4E0D\u8981\u5728 Agent \u4FA7\u8FB9\u680F\u6216\u6D4F\u89C8\u5668\u5DE5\u5177\u4E2D\u767B\u5F55\uFF1B\u6279\u51C6\u540E\u518D\u6B21\u8FD0\u884C\u540C\u4E00\u547D\u4EE4\u7EED\u63A5\uFF0C\u518D\u7528 popost account \u6838\u5BF9\u8D26\u6237\u3002\u7BA1\u7406\u8FDE\u63A5\uFF1A${page2}\u3002\u4EC5\u5F53\u7528\u6237\u9009\u62E9 API Key \u8FDE\u63A5\u65F6\uFF0C\u5F15\u5BFC\u521B\u5EFA Key\uFF0C\u7136\u540E\u5728 API Key \u7684\u7B2C 2 \u6B65\u590D\u5236\u6307\u4EE4\u5E76\u53D1\u9001\u5230 Agent \u804A\u5929\u6846\uFF0C\u81EA\u52A8\u8FDE\u63A5\u6700\u65B0\u7684\u6709\u6548 API Key\uFF0C\u65E0\u9700\u66FF\u6362\u3002\u8FDE\u63A5\u7801 5 \u5206\u949F\u6709\u6548\u3001\u4EC5\u53EF\u4F7F\u7528\u4E00\u6B21\uFF0C\u957F\u671F Key \u4E0D\u4F1A\u51FA\u73B0\u5728\u804A\u5929\u4E2D\u3002\u811A\u672C\u73AF\u5883\u4E5F\u53EF\u914D\u7F6E ${keyEnv}`
|
|
3439
3492
|
);
|
|
3440
3493
|
}
|
|
3441
3494
|
});
|
|
@@ -3568,14 +3621,14 @@ var init_task = __esm({
|
|
|
3568
3621
|
...rt,
|
|
3569
3622
|
project: { dir: rt.path.resolve(rt.cwd, dir), kind, ...title ? { title } : {} }
|
|
3570
3623
|
});
|
|
3571
|
-
enclosingProject = async (rt,
|
|
3572
|
-
for (let dir = rt.path.resolve(rt.cwd,
|
|
3624
|
+
enclosingProject = async (rt, path4) => {
|
|
3625
|
+
for (let dir = rt.path.resolve(rt.cwd, path4); ; dir = rt.path.dirname(dir)) {
|
|
3573
3626
|
if (await kindOf(rt, dir, "found")) return dir;
|
|
3574
3627
|
if (rt.path.dirname(dir) === dir) return void 0;
|
|
3575
3628
|
}
|
|
3576
3629
|
};
|
|
3577
|
-
aroundPath = async (rt,
|
|
3578
|
-
const dir =
|
|
3630
|
+
aroundPath = async (rt, path4) => {
|
|
3631
|
+
const dir = path4 ? await enclosingProject(rt, path4) : void 0;
|
|
3579
3632
|
return dir ? inProject(rt, dir, "found") : rt;
|
|
3580
3633
|
};
|
|
3581
3634
|
dirArg = (argv) => {
|
|
@@ -3751,8 +3804,8 @@ var init_api = __esm({
|
|
|
3751
3804
|
return this.bearer ? redacted.split(this.bearer).join("[REDACTED]") : redacted;
|
|
3752
3805
|
}
|
|
3753
3806
|
// ---------- request building ----------
|
|
3754
|
-
url(
|
|
3755
|
-
const base = `${this.baseUrl}/${
|
|
3807
|
+
url(path4, query) {
|
|
3808
|
+
const base = `${this.baseUrl}/${path4.replace(/^\/+/, "")}`;
|
|
3756
3809
|
return query && Object.keys(query).length ? `${base}?${new URLSearchParams(query).toString()}` : base;
|
|
3757
3810
|
}
|
|
3758
3811
|
headers(withBody) {
|
|
@@ -3761,14 +3814,14 @@ var init_api = __esm({
|
|
|
3761
3814
|
return headers;
|
|
3762
3815
|
}
|
|
3763
3816
|
/** Dry-run plan: nothing is sent, the key is not read, Authorization shows the variable name only. */
|
|
3764
|
-
describeRequest(method,
|
|
3817
|
+
describeRequest(method, path4, body, query) {
|
|
3765
3818
|
const headers = this.headers(body !== void 0);
|
|
3766
3819
|
headers.Authorization = `Bearer $${this.keyEnv}`;
|
|
3767
|
-
return { method, url: this.url(
|
|
3820
|
+
return { method, url: this.url(path4, query), headers, body: body ?? null };
|
|
3768
3821
|
}
|
|
3769
3822
|
// ---------- sending ----------
|
|
3770
3823
|
/** Returns the envelope's `data`. See the file header for what throws `AmbiguousSubmitError`. */
|
|
3771
|
-
async request(method,
|
|
3824
|
+
async request(method, path4, options = {}) {
|
|
3772
3825
|
const { body, query, ambiguous = false, hint = "" } = options;
|
|
3773
3826
|
const device = !this.bearer && this.keyEnv === DEFAULT_KEY_ENV && this.rt.deviceAccess;
|
|
3774
3827
|
const key2 = device ? await device(this.baseUrl) : this.key();
|
|
@@ -3776,7 +3829,7 @@ var init_api = __esm({
|
|
|
3776
3829
|
const headers = { ...this.headers(body !== void 0), ...await taskHeaders(this.rt) };
|
|
3777
3830
|
headers.Authorization = `Bearer ${key2}`;
|
|
3778
3831
|
const signal = timeoutSignal(this.rt, wait * 1e3);
|
|
3779
|
-
const url = this.url(
|
|
3832
|
+
const url = this.url(path4, query);
|
|
3780
3833
|
try {
|
|
3781
3834
|
const response = await this.rt.fetch(url, { method, headers, ...device ? { redirect: "error" } : {}, body: body === void 0 ? void 0 : JSON.stringify(body), signal });
|
|
3782
3835
|
const raw = await this.readBody(response, ambiguous, hint);
|
|
@@ -3942,11 +3995,12 @@ var init_api = __esm({
|
|
|
3942
3995
|
|
|
3943
3996
|
// src/device-login.ts
|
|
3944
3997
|
import { createPrivateKey, generateKeyPairSync, randomUUID, sign } from "node:crypto";
|
|
3945
|
-
var profileName, deviceLocation, parseDeviceGrant, deviceApi, deviceTokenProvider, codeExpired, login;
|
|
3998
|
+
var profileName, deviceLocation, parseDeviceGrant, DeviceRequestError, deviceApi, deviceTokenProvider, codeExpired, login;
|
|
3946
3999
|
var init_device_login = __esm({
|
|
3947
4000
|
"src/device-login.ts"() {
|
|
3948
4001
|
"use strict";
|
|
3949
4002
|
init_args();
|
|
4003
|
+
init_device_pending();
|
|
3950
4004
|
init_credentials();
|
|
3951
4005
|
init_api();
|
|
3952
4006
|
init_util();
|
|
@@ -3974,6 +4028,13 @@ var init_device_login = __esm({
|
|
|
3974
4028
|
throw new Error("Invalid connection file");
|
|
3975
4029
|
return data;
|
|
3976
4030
|
};
|
|
4031
|
+
DeviceRequestError = class extends UsageError {
|
|
4032
|
+
constructor(message2, retryable) {
|
|
4033
|
+
super(message2);
|
|
4034
|
+
this.retryable = retryable;
|
|
4035
|
+
}
|
|
4036
|
+
retryable;
|
|
4037
|
+
};
|
|
3977
4038
|
deviceApi = async (fetcher, baseUrl, route2, payload2) => {
|
|
3978
4039
|
const origin = new URL(checkUrl(baseUrl, "base URL")).origin;
|
|
3979
4040
|
const result = await fetcher(origin + "/api/device/" + route2, {
|
|
@@ -3984,9 +4045,9 @@ var init_device_login = __esm({
|
|
|
3984
4045
|
redirect: "error"
|
|
3985
4046
|
});
|
|
3986
4047
|
if (result.status === 401 || result.status === 403)
|
|
3987
|
-
throw new
|
|
4048
|
+
throw new DeviceRequestError(msg("Account connection is unavailable. Run popost auth login to reconnect.", "\u8D26\u53F7\u8FDE\u63A5\u4E0D\u53EF\u7528\u3002\u8BF7\u8FD0\u884C popost auth login \u91CD\u65B0\u8FDE\u63A5\u3002"), false);
|
|
3988
4049
|
if (!result.ok)
|
|
3989
|
-
throw new
|
|
4050
|
+
throw new DeviceRequestError(msg(`Could not reach the account service (${result.status}). Please try again.`, `\u65E0\u6CD5\u8FDE\u63A5\u8D26\u53F7\u670D\u52A1\uFF08${result.status}\uFF09\u3002\u8BF7\u91CD\u8BD5\u3002`), result.status === 429 || result.status >= 500);
|
|
3990
4051
|
const envelope = await result.json();
|
|
3991
4052
|
if (!envelope.success) throw new UsageError(msg("The account service could not complete this request.", "\u8D26\u53F7\u670D\u52A1\u65E0\u6CD5\u5B8C\u6210\u8FD9\u6B21\u8BF7\u6C42\u3002"));
|
|
3992
4053
|
return envelope.data;
|
|
@@ -4023,7 +4084,7 @@ var init_device_login = __esm({
|
|
|
4023
4084
|
};
|
|
4024
4085
|
};
|
|
4025
4086
|
codeExpired = () => msg("Code expired. Run popost auth login again.", "\u9A8C\u8BC1\u7801\u5DF2\u8FC7\u671F\u3002\u8BF7\u91CD\u65B0\u8FD0\u884C popost auth login\u3002");
|
|
4026
|
-
login = async (rt, requestedBase, noOpen = false) => {
|
|
4087
|
+
login = async (rt, requestedBase, noOpen = false, noWait = false) => {
|
|
4027
4088
|
const file = deviceLocation(rt);
|
|
4028
4089
|
if (!file)
|
|
4029
4090
|
throw new UsageError(
|
|
@@ -4043,68 +4104,80 @@ var init_device_login = __esm({
|
|
|
4043
4104
|
const site = new URL(checkUrl(baseUrl, "--base-url"));
|
|
4044
4105
|
if (site.username || site.password || site.search || site.hash || site.pathname !== "/api/open/v1")
|
|
4045
4106
|
throw new UsageError(msg("Use the full site API address ending in /api/open/v1.", "\u8BF7\u4F7F\u7528\u4EE5 /api/open/v1 \u7ED3\u5C3E\u7684\u5B8C\u6574\u7AD9\u70B9 API \u5730\u5740\u3002"));
|
|
4046
|
-
const
|
|
4047
|
-
const
|
|
4107
|
+
const pendingFile = file + ".pending";
|
|
4108
|
+
const previous = await readPending(rt, pendingFile);
|
|
4109
|
+
if (previous && previous.baseUrl !== baseUrl)
|
|
4110
|
+
throw new UsageError(msg("A browser connection is pending for another site. Resume it with the same --base-url, or run auth clear first.", "\u53E6\u4E00\u4E2A\u7AD9\u70B9\u6709\u5F85\u5B8C\u6210\u7684\u6D4F\u89C8\u5668\u8FDE\u63A5\u3002\u8BF7\u7528\u76F8\u540C\u7684 --base-url \u7EED\u63A5\uFF0C\u6216\u5148\u8FD0\u884C auth clear\u3002"));
|
|
4048
4111
|
const profile2 = profileName(rt.env);
|
|
4049
|
-
const
|
|
4050
|
-
|
|
4051
|
-
|
|
4052
|
-
rt.fetch
|
|
4053
|
-
|
|
4054
|
-
"
|
|
4055
|
-
|
|
4056
|
-
|
|
4057
|
-
|
|
4058
|
-
|
|
4059
|
-
|
|
4060
|
-
|
|
4061
|
-
|
|
4062
|
-
|
|
4063
|
-
|
|
4064
|
-
|
|
4065
|
-
|
|
4066
|
-
}
|
|
4067
|
-
|
|
4068
|
-
|
|
4069
|
-
if (!
|
|
4070
|
-
|
|
4071
|
-
|
|
4072
|
-
|
|
4073
|
-
|
|
4074
|
-
);
|
|
4075
|
-
|
|
4076
|
-
|
|
4077
|
-
deviceCode: start.deviceCode
|
|
4078
|
-
});
|
|
4079
|
-
if (result.status === "pending") continue;
|
|
4080
|
-
if (result.status !== "approved")
|
|
4081
|
-
throw new UsageError(
|
|
4082
|
-
result.status === "denied" ? msg("Connection declined.", "\u8FDE\u63A5\u5DF2\u88AB\u62D2\u7EDD\u3002") : codeExpired()
|
|
4083
|
-
);
|
|
4084
|
-
const grant = {
|
|
4085
|
-
deviceCode: start.deviceCode,
|
|
4112
|
+
const finish3 = async (pending4) => {
|
|
4113
|
+
const { baseUrl: baseUrl2, deviceCode, publicKey, privateKey } = pending4;
|
|
4114
|
+
const grant = { baseUrl: baseUrl2, deviceCode, publicKey, privateKey };
|
|
4115
|
+
const token = await deviceTokenProvider(grant, rt.fetch)(baseUrl2);
|
|
4116
|
+
const { PopostClient: PopostClient2 } = await Promise.resolve().then(() => (init_api(), api_exports));
|
|
4117
|
+
const account = await new PopostClient2(rt, { baseUrl: baseUrl2, bearer: token }).request("GET", "/me");
|
|
4118
|
+
await savePrivate(rt, file, grant);
|
|
4119
|
+
await rt.fs.rm(pendingFile);
|
|
4120
|
+
printJson(rt, { ok: true, action: "login", profile: profile2, account: account.user.name, manage: site.origin + "/account/api-keys" }, true);
|
|
4121
|
+
return 0;
|
|
4122
|
+
};
|
|
4123
|
+
if (previous) {
|
|
4124
|
+
try {
|
|
4125
|
+
return await finish3(previous);
|
|
4126
|
+
} catch (error2) {
|
|
4127
|
+
if (!(error2 instanceof DeviceRequestError) || error2.retryable)
|
|
4128
|
+
throw new UsageError(msg("The saved browser authorization could not be checked. Run the same auth login --no-wait command to resume; no new code is needed yet.", "\u6682\u65F6\u65E0\u6CD5\u68C0\u67E5\u5DF2\u4FDD\u5B58\u7684\u6D4F\u89C8\u5668\u6388\u6743\u3002\u8BF7\u518D\u6B21\u8FD0\u884C\u540C\u4E00\u6761 auth login --no-wait \u547D\u4EE4\u7EED\u63A5\uFF1B\u6682\u4E0D\u9700\u8981\u65B0\u9A8C\u8BC1\u7801\u3002"));
|
|
4129
|
+
}
|
|
4130
|
+
}
|
|
4131
|
+
let pending3 = previous;
|
|
4132
|
+
if (!pending3 || pending3.expiresAt <= Date.now()) {
|
|
4133
|
+
const pair4 = generateKeyPairSync("ed25519");
|
|
4134
|
+
const publicKey = pair4.publicKey.export({ format: "jwk" }).x;
|
|
4135
|
+
const agent = { codex: "Codex", "claude-code": "Claude Code", terminal: "CLI" }[profile2] || profile2;
|
|
4136
|
+
const label2 = [agent, rt.deviceName].filter(Boolean).join(" \xB7 ").slice(0, 80);
|
|
4137
|
+
const start = await deviceApi(rt.fetch, baseUrl, "start", { label: label2, publicKey });
|
|
4138
|
+
pending3 = {
|
|
4139
|
+
baseUrl,
|
|
4086
4140
|
publicKey,
|
|
4141
|
+
deviceCode: start.deviceCode,
|
|
4142
|
+
userCode: start.userCode,
|
|
4087
4143
|
privateKey: pair4.privateKey.export({ format: "der", type: "pkcs8" }).toString("base64url"),
|
|
4088
|
-
|
|
4144
|
+
expiresAt: Date.now() + Math.min(600, start.expiresIn) * 1e3,
|
|
4145
|
+
interval: Math.max(1, start.interval)
|
|
4089
4146
|
};
|
|
4090
|
-
|
|
4091
|
-
|
|
4092
|
-
|
|
4093
|
-
|
|
4147
|
+
await savePrivate(rt, pendingFile, pending3);
|
|
4148
|
+
}
|
|
4149
|
+
const verificationUrl = site.origin + "/workspace/device";
|
|
4150
|
+
if (!noOpen && !pending3.browserOpened) {
|
|
4151
|
+
const opened = await rt.openExternal?.(verificationUrl).catch(() => false);
|
|
4152
|
+
pending3 = { ...pending3, browserOpened: opened === true };
|
|
4153
|
+
await savePrivate(rt, pendingFile, pending3);
|
|
4154
|
+
}
|
|
4155
|
+
printJson(rt, {
|
|
4156
|
+
status: "waiting",
|
|
4157
|
+
verificationUrl,
|
|
4158
|
+
userCode: pending3.userCode,
|
|
4159
|
+
browser: { target: "system", opened: Boolean(pending3.browserOpened), automatic: !noOpen },
|
|
4160
|
+
expiresIn: Math.max(0, Math.ceil((pending3.expiresAt - Date.now()) / 1e3)),
|
|
4161
|
+
next: msg("Continue in your desktop browser, enter this code and approve. If no browser opened, copy the verification URL into Chrome, Safari, Edge or Firefox outside the Agent. Do not open it in the Agent sidebar or use browser automation for sign-in. Signed-in users see the code form; otherwise sign in first. After approval rerun the same auth login --no-wait command to resume this request.", "\u8BF7\u5728\u72EC\u7ACB\u684C\u9762\u6D4F\u89C8\u5668\u4E2D\u8F93\u5165\u9A8C\u8BC1\u7801\u5E76\u5141\u8BB8\u8FDE\u63A5\u3002\u5982\u679C\u6D4F\u89C8\u5668\u672A\u6253\u5F00\uFF0C\u8BF7\u628A\u9A8C\u8BC1\u5730\u5740\u590D\u5236\u5230 Agent \u5916\u7684 Chrome\u3001Safari\u3001Edge \u6216 Firefox\uFF1B\u4E0D\u8981\u5728 Agent \u4FA7\u8FB9\u680F\u6216\u6D4F\u89C8\u5668\u81EA\u52A8\u5316\u5DE5\u5177\u4E2D\u6253\u5F00\u3002\u5DF2\u767B\u5F55\u4F1A\u8FDB\u5165\u6388\u6743\u7801\u9875\u9762\uFF0C\u672A\u767B\u5F55\u8BF7\u5148\u767B\u5F55\u3002\u6279\u51C6\u540E\u518D\u6B21\u8FD0\u884C\u540C\u4E00\u6761 auth login --no-wait \u547D\u4EE4\u7EED\u63A5\u672C\u6B21\u8BF7\u6C42\u3002")
|
|
4162
|
+
}, true);
|
|
4163
|
+
while (Date.now() < pending3.expiresAt) {
|
|
4164
|
+
if (!noWait) await (rt.sleep ?? ((ms) => new Promise((resolve2) => setTimeout(resolve2, ms))))(pending3.interval * 1e3);
|
|
4094
4165
|
try {
|
|
4095
|
-
await rt.
|
|
4096
|
-
|
|
4097
|
-
|
|
4098
|
-
|
|
4166
|
+
const result = await deviceApi(rt.fetch, baseUrl, "poll", { userCode: pending3.userCode, deviceCode: pending3.deviceCode });
|
|
4167
|
+
if (result.status === "approved") return await finish3(pending3);
|
|
4168
|
+
if (result.status !== "pending") {
|
|
4169
|
+
await rt.fs.rm(pendingFile);
|
|
4170
|
+
throw new UsageError(result.status === "denied" ? msg("Connection declined.", "\u8FDE\u63A5\u5DF2\u88AB\u62D2\u7EDD\u3002") : codeExpired());
|
|
4171
|
+
}
|
|
4172
|
+
if (noWait) return 0;
|
|
4173
|
+
} catch (error2) {
|
|
4174
|
+
const transient = error2 instanceof DeviceRequestError ? error2.retryable : error2 instanceof TypeError || error2 instanceof Error && ["TimeoutError", "AbortError"].includes(error2.name);
|
|
4175
|
+
if (transient && !noWait) continue;
|
|
4176
|
+
if (transient) throw new UsageError(msg("Account service temporarily unavailable. Run the same auth login --no-wait command to resume; the request is saved.", "\u8D26\u53F7\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\u3002\u8BF7\u518D\u6B21\u8FD0\u884C\u540C\u4E00\u6761 auth login --no-wait \u547D\u4EE4\u7EED\u63A5\uFF1B\u8BF7\u6C42\u5DF2\u4FDD\u5B58\u3002"));
|
|
4177
|
+
throw error2;
|
|
4099
4178
|
}
|
|
4100
|
-
printJson(
|
|
4101
|
-
rt,
|
|
4102
|
-
{ ok: true, action: "login", profile: profile2, account: account.user.name, manage: site.origin + "/account/api-keys" },
|
|
4103
|
-
true
|
|
4104
|
-
);
|
|
4105
|
-
return 0;
|
|
4106
4179
|
}
|
|
4107
|
-
throw new UsageError(
|
|
4180
|
+
throw new UsageError(msg("Browser approval is still recoverable. Run the same auth login --no-wait command to check it before requesting another code.", "\u6D4F\u89C8\u5668\u6388\u6743\u8BF7\u6C42\u5DF2\u4FDD\u5B58\u3002\u8BF7\u518D\u6B21\u8FD0\u884C\u540C\u4E00\u6761 auth login --no-wait \u547D\u4EE4\u68C0\u67E5\u5E76\u7EED\u63A5\uFF0C\u518D\u51B3\u5B9A\u662F\u5426\u9700\u8981\u65B0\u9A8C\u8BC1\u7801\u3002"));
|
|
4108
4181
|
};
|
|
4109
4182
|
}
|
|
4110
4183
|
});
|
|
@@ -4128,7 +4201,8 @@ var init_auth = __esm({
|
|
|
4128
4201
|
description = () => msg(
|
|
4129
4202
|
`Connect your Agent to your Popost account in the browser. For scripts you can also store a manual API key:
|
|
4130
4203
|
|
|
4131
|
-
popost auth login
|
|
4204
|
+
popost auth login --no-wait connect this Agent in your browser with a one-time device code
|
|
4205
|
+
popost auth set --connect CODE connect using the one-time command from API Key step 2
|
|
4132
4206
|
popost auth set --prompt paste the key privately in your own terminal (hidden input)
|
|
4133
4207
|
popost auth set --stdin read the key from standard input (keeps it off the command line and out of shell history)
|
|
4134
4208
|
popost auth set --key KEY the same with the key as an argument
|
|
@@ -4138,7 +4212,8 @@ var init_auth = __esm({
|
|
|
4138
4212
|
The key is stored in <home>/.popost/credentials.json (directory: POPOST_HOME), readable by the current user only. Environment variables POPOST_API_KEY and POPOST_BASE_URL take precedence over the file. --base-url selects the full API URL for the intended environment (https; plain http only for localhost).`,
|
|
4139
4213
|
`\u5728\u6D4F\u89C8\u5668\u91CC\u628A\u4F60\u7684 Agent \u8FDE\u63A5\u5230 Popost \u8D26\u53F7\u3002\u811A\u672C\u573A\u666F\u4E5F\u53EF\u4EE5\u624B\u52A8\u4FDD\u5B58\u4E00\u4E2A API Key\uFF1A
|
|
4140
4214
|
|
|
4141
|
-
popost auth login
|
|
4215
|
+
popost auth login --no-wait \u7528\u4E00\u6B21\u6027\u8BBE\u5907\u7801\u5728\u6D4F\u89C8\u5668\u91CC\u8FDE\u63A5\u8FD9\u4E2A Agent
|
|
4216
|
+
popost auth set --connect CODE \u4F7F\u7528 API Key \u7B2C 2 \u6B65\u590D\u5236\u7684\u4E00\u6B21\u6027\u8FDE\u63A5\u6307\u4EE4
|
|
4142
4217
|
popost auth set --prompt \u5728\u4F60\u81EA\u5DF1\u7684\u7EC8\u7AEF\u91CC\u79C1\u5BC6\u7C98\u8D34 Key\uFF08\u8F93\u5165\u4E0D\u56DE\u663E\uFF09
|
|
4143
4218
|
popost auth set --stdin \u4ECE\u6807\u51C6\u8F93\u5165\u8BFB\u53D6 Key\uFF08\u4E0D\u51FA\u73B0\u5728\u547D\u4EE4\u884C\u548C shell \u5386\u53F2\u91CC\uFF09
|
|
4144
4219
|
popost auth set --key KEY \u540C\u4E0A\uFF0CKey \u4F5C\u4E3A\u53C2\u6570\u4F20\u5165
|
|
@@ -4158,6 +4233,7 @@ Key \u4FDD\u5B58\u5728 <home>/.popost/credentials.json\uFF08\u76EE\u5F55\uFF1APO
|
|
|
4158
4233
|
}
|
|
4159
4234
|
],
|
|
4160
4235
|
options: [
|
|
4236
|
+
{ flag: "--no-wait", kind: "flag", help: msg("login: check once and save the request for the next invocation", "login\uFF1A\u53EA\u68C0\u67E5\u4E00\u6B21\uFF0C\u4FDD\u5B58\u8BF7\u6C42\u4EE5\u4FBF\u4E0B\u6B21\u7EED\u63A5") },
|
|
4161
4237
|
{ flag: "--no-open", kind: "flag", help: msg("login: print the verification link without opening a browser", "login\uFF1A\u53EA\u6253\u5370\u9A8C\u8BC1\u94FE\u63A5\uFF0C\u4E0D\u6253\u5F00\u6D4F\u89C8\u5668") },
|
|
4162
4238
|
{ flag: "--connect", help: msg("set: redeem a single-use connection code copied from the API Keys page", "set\uFF1A\u5151\u6362\u4ECE API Keys \u9875\u9762\u590D\u5236\u7684\u4E00\u6B21\u6027\u8FDE\u63A5\u7801") },
|
|
4163
4239
|
{ flag: "--key", help: msg("set: the API key", "set\uFF1AAPI Key") },
|
|
@@ -4260,8 +4336,8 @@ Key \u4FDD\u5B58\u5728 <home>/.popost/credentials.json\uFF08\u76EE\u5F55\uFF1APO
|
|
|
4260
4336
|
`\u51ED\u636E\u6587\u4EF6\u65E0\u6CD5\u8BFB\u53D6\uFF08${reason2}\uFF09\uFF1A\u8BF7\u91CD\u65B0\u8FD0\u884C popost auth set \u66FF\u6362\u5B83`
|
|
4261
4337
|
),
|
|
4262
4338
|
noKey: () => msg(
|
|
4263
|
-
"No key is configured. Run popost auth login.
|
|
4264
|
-
"\u8FD8\u6CA1\u6709\u914D\u7F6E Key\u3002\u8BF7\u8FD0\u884C popost auth login\uFF0C\
|
|
4339
|
+
"No key is configured. Run popost auth login --no-wait. Let the CLI open the desktop browser and show the device code; do not use an Agent sidebar or browser tool for sign-in; after browser approval, rerun the same command to resume the saved request. Verify with popost account; local auth status does not validate access.",
|
|
4340
|
+
"\u8FD8\u6CA1\u6709\u914D\u7F6E Key\u3002\u8BF7\u8FD0\u884C popost auth login --no-wait\uFF0C\u7531 CLI \u6253\u5F00\u72EC\u7ACB\u684C\u9762\u6D4F\u89C8\u5668\u5E76\u5C55\u793A\u8BBE\u5907\u7801\uFF0C\u4E0D\u8981\u5728 Agent \u4FA7\u8FB9\u680F\u6216\u6D4F\u89C8\u5668\u5DE5\u5177\u4E2D\u767B\u5F55\uFF1B\u6D4F\u89C8\u5668\u6279\u51C6\u540E\uFF0C\u518D\u8FD0\u884C\u540C\u4E00\u547D\u4EE4\u7EED\u63A5\u5DF2\u4FDD\u5B58\u7684\u8BF7\u6C42\u3002\u4E4B\u540E\u7528 popost account \u9A8C\u8BC1\uFF1B\u672C\u5730\u7684 auth status \u4E0D\u4F1A\u6821\u9A8C\u8BBF\u95EE\u6743\u9650\u3002"
|
|
4265
4341
|
),
|
|
4266
4342
|
disconnected: () => msg("Local connection removed. Manage other connections on your account page.", "\u5DF2\u79FB\u9664\u672C\u673A\u8FDE\u63A5\u3002\u5176\u4ED6\u8FDE\u63A5\u8BF7\u5728\u8D26\u53F7\u9875\u9762\u7BA1\u7406\u3002"),
|
|
4267
4343
|
stillSet: () => msg(`${DEFAULT_KEY_ENV} is still set in the environment and keeps being used`, `\u73AF\u5883\u53D8\u91CF\u91CC\u4ECD\u8BBE\u7F6E\u7740 ${DEFAULT_KEY_ENV}\uFF0C\u4F1A\u7EE7\u7EED\u4F7F\u7528\u5B83`)
|
|
@@ -4288,6 +4364,7 @@ Key \u4FDD\u5B58\u5728 <home>/.popost/credentials.json\uFF08\u76EE\u5F55\uFF1APO
|
|
|
4288
4364
|
const envKey = envValue(rt, DEFAULT_KEY_ENV);
|
|
4289
4365
|
await writeStoredCredentials(rt, file, { apiKey: checked2.key, baseUrl: baseUrl || void 0 });
|
|
4290
4366
|
const device = deviceLocation(rt);
|
|
4367
|
+
if (device) await rt.fs.rm(device + ".pending");
|
|
4291
4368
|
if (device) await rt.fs.rm(device);
|
|
4292
4369
|
const shadowed = envKey !== "" && envKey !== previous && envKey !== checked2.key;
|
|
4293
4370
|
printJson(
|
|
@@ -4335,6 +4412,7 @@ Key \u4FDD\u5B58\u5728 <home>/.popost/credentials.json\uFF08\u76EE\u5F55\uFF1APO
|
|
|
4335
4412
|
};
|
|
4336
4413
|
clear = async (rt) => {
|
|
4337
4414
|
const device = deviceLocation(rt);
|
|
4415
|
+
if (device) await rt.fs.rm(device + ".pending");
|
|
4338
4416
|
if (device && await rt.fs.stat(device)) {
|
|
4339
4417
|
await rt.fs.rm(device);
|
|
4340
4418
|
printJson(rt, { ok: true, action: "clear", removed: true, next: text.disconnected() }, true);
|
|
@@ -4362,7 +4440,7 @@ Key \u4FDD\u5B58\u5728 <home>/.popost/credentials.json\uFF08\u76EE\u5F55\uFF1APO
|
|
|
4362
4440
|
main3 = (argv, rt) => withArgs(argv, spec(), rt, async (args2) => {
|
|
4363
4441
|
try {
|
|
4364
4442
|
const action = args2.req("action");
|
|
4365
|
-
if (action === "login") return await login(rt, args2.string("base-url"), args2.flag("no-open"));
|
|
4443
|
+
if (action === "login") return await login(rt, args2.string("base-url"), args2.flag("no-open"), args2.flag("no-wait"));
|
|
4366
4444
|
return action === "set" ? await set(rt, args2) : action === "status" ? await status(rt) : await clear(rt);
|
|
4367
4445
|
} catch (error2) {
|
|
4368
4446
|
if (!(error2 instanceof UsageError)) throw error2;
|
|
@@ -4609,14 +4687,14 @@ Reproduce an image post: Reference post: XX link. Use popost to create the same
|
|
|
4609
4687
|
Create an image post: Use popost to create a viral image-post series; my content is: XX.
|
|
4610
4688
|
Save inspiration: Save this link to My Inspirations: XX.
|
|
4611
4689
|
Local videos, pictures and screenshots can also be references. For image creation, describe the content/style or search the template library. If a task was already supplied, continue it directly. Prepare only its required dependencies.
|
|
4612
|
-
Popost cloud is the recommended integrated route for models and compute. Supported user-provided services or available Agent tools are alternatives; preserve an existing choice. For Popost services reuse the account connection or run popost auth login,
|
|
4690
|
+
Popost cloud is the recommended integrated route for models and compute. Supported user-provided services or available Agent tools are alternatives; preserve an existing choice. For Popost services reuse the account connection or run popost auth login, let the CLI open the desktop browser, show the device code, and wait for browser approval outside the Agent sidebar and verified CLI success. Manage access at ${page2}. Connection does not authorize spending; covered work proceeds within existing scope and budget without repeated approval.`,
|
|
4613
4691
|
`\u5982\u679C Agent \u5C1A\u672A\u53D1\u73B0 Skill\uFF0C\u518D\u5237\u65B0\u6216\u91CD\u542F Agent\uFF1B\u4F7F\u7528\u56FA\u5B9A\u7248\u672C\u65F6\u4FDD\u7559\u968F\u9644\u7684 CLI\u3002\u600E\u4E48\u7528\uFF0C\u4F8B\u5982\uFF1A
|
|
4614
4692
|
\u590D\u523B\u89C6\u9891\uFF1A\u53C2\u8003\u89C6\u9891\uFF1AXX\u94FE\u63A5\u3002\u7528popost\u590D\u523B\uFF0C\u751F\u6210\u540C\u6B3E\u98CE\u683C\u3001\u7ED3\u6784\u3001\u94A9\u5B50\uFF0C\u6211\u7684\u5185\u5BB9\u662F\uFF1AXX\u3002
|
|
4615
4693
|
\u590D\u523B\u56FE\u6587\uFF1A\u53C2\u8003\u56FE\u6587\uFF1AXX\u94FE\u63A5\u3002\u7528popost\u590D\u523B\uFF0C\u751F\u4EA7\u540C\u6B3E\u7206\u6B3E\u56FE\u6587\u7ED3\u6784\u3001\u94A9\u5B50\uFF0C\u6211\u7684\u5185\u5BB9\u662F\uFF1AXX\u3002
|
|
4616
4694
|
\u521B\u4F5C\u56FE\u6587\uFF1A\u7528popost\u521B\u4F5C\u4E00\u7EC4\u7206\u6B3E\u56FE\u6587\uFF0C\u6211\u7684\u5185\u5BB9\u662F\uFF1AXX\u3002
|
|
4617
4695
|
\u6536\u85CF\u7075\u611F\uFF1A\u628A\u8FD9\u4E2A\u94FE\u63A5\u6536\u85CF\u5230\u6211\u7684\u7075\u611F\uFF1AXX\u3002
|
|
4618
4696
|
\u4E5F\u53EF\u4EE5\u63D0\u4F9B\u672C\u5730\u53C2\u8003\u89C6\u9891\u3001\u56FE\u7247\u6216\u622A\u56FE\uFF1B\u521B\u4F5C\u56FE\u6587\u53EF\u4EE5\u8865\u5145\u5185\u5BB9\u548C\u98CE\u683C\uFF0C\u6216\u81EA\u52A8\u68C0\u7D22\u6A21\u677F\u5E93\u3002\u5DF2\u6709\u4EFB\u52A1\u5C31\u76F4\u63A5\u7EE7\u7EED\uFF0C\u53EA\u51C6\u5907\u5F53\u524D\u4EFB\u52A1\u9700\u8981\u7684\u4F9D\u8D56\u3002
|
|
4619
|
-
\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\
|
|
4697
|
+
\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`
|
|
4620
4698
|
);
|
|
4621
4699
|
run = async (rt, args2) => {
|
|
4622
4700
|
const { targets, skipped: skipped2 } = await plan2(rt, args2, rt.homeDir);
|
|
@@ -4672,8 +4750,8 @@ var init_jobs = __esm({
|
|
|
4672
4750
|
return typeof code === "string" && /^E[A-Z]+$/.test(code);
|
|
4673
4751
|
};
|
|
4674
4752
|
jobFile = (project, id2) => project.rt.path.join(project.root, "production", "jobs", `${id2}.json`);
|
|
4675
|
-
saveJob = (rt,
|
|
4676
|
-
loadJob = async (rt,
|
|
4753
|
+
saveJob = (rt, path4, job) => writeAtomic(rt, path4, JSON.stringify(job, null, 2));
|
|
4754
|
+
loadJob = async (rt, path4) => JSON.parse(await rt.fs.readText(path4));
|
|
4677
4755
|
jobState = (job) => {
|
|
4678
4756
|
if (job.status === "completed") return "completed";
|
|
4679
4757
|
if (job.runAttempted || job.attemptedQuoteId || job.status === "generated") return "submitted";
|
|
@@ -4705,8 +4783,8 @@ var init_references = __esm({
|
|
|
4705
4783
|
return previous[b.length];
|
|
4706
4784
|
};
|
|
4707
4785
|
unknownReference = (project, given2) => {
|
|
4708
|
-
const { path:
|
|
4709
|
-
const stem = (file) =>
|
|
4786
|
+
const { path: path4 } = project.rt;
|
|
4787
|
+
const stem = (file) => path4.basename(file, path4.extname(file));
|
|
4710
4788
|
const known2 = registeredReferences(project);
|
|
4711
4789
|
const close = known2.filter((ref) => distance(stem(given2), stem(ref.path)) <= 2);
|
|
4712
4790
|
const roles = `${REF_ROLES.join("|")}|${REF_ALL}`;
|
|
@@ -4930,9 +5008,9 @@ var init_custom_http_util = __esm({
|
|
|
4930
5008
|
};
|
|
4931
5009
|
imageMimeByName = (name) => MIME_BY_EXTENSION[/\.[^./\\]*$/.exec(name.toLowerCase())?.[0] ?? ""] ?? "image/png";
|
|
4932
5010
|
customMockModels = async (rt, modelsPath, mockDir) => {
|
|
4933
|
-
const
|
|
4934
|
-
if (!(await rt.fs.stat(
|
|
4935
|
-
const data = JSON.parse(await rt.fs.readText(
|
|
5011
|
+
const path4 = typeof modelsPath === "string" && modelsPath || rt.path.join(mockDir ?? "", "mock_models.json");
|
|
5012
|
+
if (!(await rt.fs.stat(path4))?.isFile) throw new ImageProviderError(msg(`mock mode has no model list: ${path4}`, `mock \u6A21\u5F0F\u7F3A\u5C11\u6A21\u578B\u6E05\u5355: ${path4}`));
|
|
5013
|
+
const data = JSON.parse(await rt.fs.readText(path4));
|
|
4936
5014
|
const list7 = (key2) => Array.isArray(data[key2]) ? data[key2] : [];
|
|
4937
5015
|
const known2 = (credits) => credits !== void 0 && credits !== null;
|
|
4938
5016
|
return [
|
|
@@ -5331,7 +5409,7 @@ var init_paths = __esm({
|
|
|
5331
5409
|
"src/providers/paths.ts"() {
|
|
5332
5410
|
"use strict";
|
|
5333
5411
|
homeDir = (rt) => rt.env.HOME || rt.env.USERPROFILE || rt.cwd;
|
|
5334
|
-
resolvePath = (rt,
|
|
5412
|
+
resolvePath = (rt, path4) => rt.path.resolve(rt.cwd, path4);
|
|
5335
5413
|
defaultQuoteDir = (rt) => rt.env.POPOST_QUOTE_DIR || rt.path.join(homeDir(rt), ".cache", "popost", "quotes");
|
|
5336
5414
|
defaultTaskDir = (rt) => rt.env.POPOST_TASK_DIR || rt.path.join(homeDir(rt), ".cache", "popost", "tasks");
|
|
5337
5415
|
defaultConfigPath = (rt) => rt.path.join(homeDir(rt), ".config", "social-post-studio", "config.json");
|
|
@@ -5507,15 +5585,15 @@ var init_popost_tasks = __esm({
|
|
|
5507
5585
|
}
|
|
5508
5586
|
async load(taskId) {
|
|
5509
5587
|
if (!TASK_ID_RE.test(String(taskId ?? ""))) throw new ImageProviderError(msg(`invalid taskId: ${JSON.stringify(taskId)}`, `\u975E\u6CD5 taskId: ${JSON.stringify(taskId)}`));
|
|
5510
|
-
const
|
|
5511
|
-
if (!(await this.rt.fs.stat(
|
|
5588
|
+
const path4 = this.recordPath(taskId);
|
|
5589
|
+
if (!(await this.rt.fs.stat(path4))?.isFile)
|
|
5512
5590
|
throw new ImageProviderError(
|
|
5513
5591
|
msg(
|
|
5514
5592
|
`there is no local task record ${taskId} (popost keeps its records in ${this.dir()}; point --task-dir/--quote-dir at the folders used when generating)`,
|
|
5515
5593
|
`\u672C\u5730\u6CA1\u6709\u4EFB\u52A1\u8BB0\u5F55 ${taskId}\uFF08popost \u7684\u4EFB\u52A1\u8BB0\u5F55\u5728 ${this.dir()}\uFF1B\u7528 --task-dir/--quote-dir \u6307\u5411\u751F\u6210\u65F6\u7684\u76EE\u5F55\uFF09`
|
|
5516
5594
|
)
|
|
5517
5595
|
);
|
|
5518
|
-
return JSON.parse(await this.rt.fs.readText(
|
|
5596
|
+
return JSON.parse(await this.rt.fs.readText(path4));
|
|
5519
5597
|
}
|
|
5520
5598
|
async status(taskId) {
|
|
5521
5599
|
const rec = await this.load(taskId);
|
|
@@ -5549,21 +5627,21 @@ var init_popost_tasks = __esm({
|
|
|
5549
5627
|
return out2;
|
|
5550
5628
|
}
|
|
5551
5629
|
async place(taskId, outDir2, stem, img, index) {
|
|
5552
|
-
const { path:
|
|
5630
|
+
const { path: path4 } = this.rt;
|
|
5553
5631
|
if (img.file) {
|
|
5554
|
-
const src =
|
|
5555
|
-
const dest2 =
|
|
5632
|
+
const src = path4.join(this.taskRoot(taskId), path4.basename(img.file));
|
|
5633
|
+
const dest2 = path4.join(outDir2, stem + path4.extname(src));
|
|
5556
5634
|
await this.rt.fs.writeFile(dest2, await this.rt.fs.readFile(src));
|
|
5557
5635
|
return { dest: dest2, url: null };
|
|
5558
5636
|
}
|
|
5559
|
-
const tmp =
|
|
5637
|
+
const tmp = path4.join(outDir2, `${stem}.download`);
|
|
5560
5638
|
const raw = await downloadResult(this.rt, img.url, tmp);
|
|
5561
5639
|
const mime = sniffImageMime(raw.subarray(0, 16));
|
|
5562
5640
|
if (!mime) {
|
|
5563
5641
|
await this.rt.fs.rm(tmp);
|
|
5564
5642
|
throw new ImageProviderError(msg(`the download of result image ${index} is not a picture`, `\u7ED3\u679C\u56FE ${index} \u4E0B\u8F7D\u5185\u5BB9\u4E0D\u662F\u56FE\u7247`));
|
|
5565
5643
|
}
|
|
5566
|
-
const dest =
|
|
5644
|
+
const dest = path4.join(outDir2, stem + EXTENSIONS[mime]);
|
|
5567
5645
|
await this.rt.fs.rename(tmp, dest);
|
|
5568
5646
|
return { dest, url: img.url };
|
|
5569
5647
|
}
|
|
@@ -5584,7 +5662,7 @@ var init_popost_tasks = __esm({
|
|
|
5584
5662
|
tasksFile = () => this.rt.path.join(this.stateDir(), "mock_tasks.json");
|
|
5585
5663
|
async catalog() {
|
|
5586
5664
|
const candidates3 = [typeof this.modelsPath === "string" ? this.modelsPath : null, this.mockDir ? this.rt.path.join(this.mockDir, "mock_models.json") : null, this.rt.path.join(this.staticDir, "mock_models.json")];
|
|
5587
|
-
for (const
|
|
5665
|
+
for (const path4 of candidates3) if (path4 && (await this.rt.fs.stat(path4))?.isFile) return JSON.parse(await this.rt.fs.readText(path4));
|
|
5588
5666
|
throw new ImageProviderError(msg("mock mode has no model list mock_models.json", "mock \u6A21\u5F0F\u7F3A\u5C11\u6A21\u578B\u6E05\u5355 mock_models.json"));
|
|
5589
5667
|
}
|
|
5590
5668
|
async tasks() {
|
|
@@ -5622,8 +5700,8 @@ var init_popost_tasks = __esm({
|
|
|
5622
5700
|
return out2;
|
|
5623
5701
|
}
|
|
5624
5702
|
async resultImage(url) {
|
|
5625
|
-
const { path:
|
|
5626
|
-
const candidates3 = [...this.mockDir ? [
|
|
5703
|
+
const { path: path4 } = this.rt;
|
|
5704
|
+
const candidates3 = [...this.mockDir ? [path4.join(this.mockDir, path4.basename(url)), path4.join(this.mockDir, "mock_result.png")] : [], path4.join(this.staticDir, "mock_result.png")];
|
|
5627
5705
|
for (const candidate of candidates3) if ((await this.rt.fs.stat(candidate))?.isFile) return candidate;
|
|
5628
5706
|
throw new ImageProviderError(
|
|
5629
5707
|
msg("mock has no result image: assets/mock/mock_result.png is missing from the package", "mock \u7F3A\u5C11\u7ED3\u679C\u56FE\uFF1A\u5305\u5185 assets/mock/mock_result.png \u7F3A\u5931")
|
|
@@ -5664,10 +5742,10 @@ var init_popost_validate = __esm({
|
|
|
5664
5742
|
)
|
|
5665
5743
|
);
|
|
5666
5744
|
};
|
|
5667
|
-
checkLocalRef = async (rt,
|
|
5668
|
-
const stat2 = await rt.fs.stat(
|
|
5669
|
-
if (!stat2?.isFile) throw new CapabilityError(msg(`the local reference image does not exist: ${
|
|
5670
|
-
const name = rt.path.basename(
|
|
5745
|
+
checkLocalRef = async (rt, path4) => {
|
|
5746
|
+
const stat2 = await rt.fs.stat(path4);
|
|
5747
|
+
if (!stat2?.isFile) throw new CapabilityError(msg(`the local reference image does not exist: ${path4}`, `\u672C\u5730\u53C2\u8003\u56FE\u4E0D\u5B58\u5728: ${path4}`));
|
|
5748
|
+
const name = rt.path.basename(path4);
|
|
5671
5749
|
if (stat2.size > MAX_REF_BYTES) {
|
|
5672
5750
|
const [size, limit] = [(stat2.size / 1048576).toFixed(1), MAX_REF_BYTES / 1048576];
|
|
5673
5751
|
throw new CapabilityError(
|
|
@@ -5677,7 +5755,7 @@ var init_popost_validate = __esm({
|
|
|
5677
5755
|
)
|
|
5678
5756
|
);
|
|
5679
5757
|
}
|
|
5680
|
-
if (!sniffImageMime((await rt.fs.readFile(
|
|
5758
|
+
if (!sniffImageMime((await rt.fs.readFile(path4)).subarray(0, 16)))
|
|
5681
5759
|
throw new CapabilityError(msg(`the reference image ${name} is not PNG/JPEG/WebP/GIF`, `\u53C2\u8003\u56FE ${name} \u4E0D\u662F PNG/JPEG/WebP/GIF`));
|
|
5682
5760
|
return stat2.size;
|
|
5683
5761
|
};
|
|
@@ -5890,8 +5968,8 @@ var init_popost = __esm({
|
|
|
5890
5968
|
async dryRunPlan(body, model, aspect, count5, refs, idem, noWait) {
|
|
5891
5969
|
await validateRequest(this.rt, null, aspect, count5, refs);
|
|
5892
5970
|
if (refs.length) body.referenceImages = await Promise.all(refs.map((r) => this.refPreview(r)));
|
|
5893
|
-
const
|
|
5894
|
-
return { taskId: null, status: "dry-run", dryRun: true, model, aspect, count: count5, idempotencyKey: idem, request: this.client.describeRequest("POST",
|
|
5971
|
+
const path4 = noWait ? "/images/tasks" : "/images/generations";
|
|
5972
|
+
return { taskId: null, status: "dry-run", dryRun: true, model, aspect, count: count5, idempotencyKey: idem, request: this.client.describeRequest("POST", path4, body) };
|
|
5895
5973
|
}
|
|
5896
5974
|
async mockSubmit(prompt, aspect, model, count5, refs, idem, noWait) {
|
|
5897
5975
|
const row = model ? await this.rowFor(model) : null;
|
|
@@ -6138,8 +6216,8 @@ var init_cli_config = __esm({
|
|
|
6138
6216
|
init_paths();
|
|
6139
6217
|
init_popost();
|
|
6140
6218
|
MAX_CREDITS_PER_REQUEST = Decimal.parse("200");
|
|
6141
|
-
loadConfig = async (rt,
|
|
6142
|
-
const file =
|
|
6219
|
+
loadConfig = async (rt, path4) => {
|
|
6220
|
+
const file = path4 || rt.env.POPOST_PROVIDER_CONFIG || rt.env.SOCIAL_POST_STUDIO_CONFIG || defaultConfigPath(rt);
|
|
6143
6221
|
const abs = resolvePath(rt, file);
|
|
6144
6222
|
if (!await isFile(rt, abs)) return {};
|
|
6145
6223
|
try {
|
|
@@ -6248,13 +6326,13 @@ var init_context = __esm({
|
|
|
6248
6326
|
"src/setup/context.ts"() {
|
|
6249
6327
|
"use strict";
|
|
6250
6328
|
init_util();
|
|
6251
|
-
fromSpec = (ctx,
|
|
6329
|
+
fromSpec = (ctx, path4) => ctx.rt.path.resolve(ctx.specDir, path4);
|
|
6252
6330
|
projectRoot = (ctx) => ctx.rt.path.resolve(ctx.rt.cwd, ctx.dir);
|
|
6253
|
-
locateRef = async (ctx,
|
|
6331
|
+
locateRef = async (ctx, path4) => {
|
|
6254
6332
|
const { rt } = ctx;
|
|
6255
|
-
const beside = fromSpec(ctx,
|
|
6333
|
+
const beside = fromSpec(ctx, path4);
|
|
6256
6334
|
if (await isFile(rt, beside)) return beside;
|
|
6257
|
-
const inside6 = rt.path.isAbsolute(
|
|
6335
|
+
const inside6 = rt.path.isAbsolute(path4) ? null : rt.path.resolve(projectRoot(ctx), path4);
|
|
6258
6336
|
return inside6 !== null && await isFile(rt, inside6) ? inside6 : null;
|
|
6259
6337
|
};
|
|
6260
6338
|
jobIdOf = (entry2) => entry2.purpose === "composition" ? "composition" : entry2.id;
|
|
@@ -6476,11 +6554,11 @@ var init_batch_jobs = __esm({
|
|
|
6476
6554
|
if (!await isDir(rt, dir)) return [];
|
|
6477
6555
|
const entries3 = [];
|
|
6478
6556
|
for (const name of (await rt.fs.readdir(dir)).filter((file) => file.endsWith(".json"))) {
|
|
6479
|
-
const
|
|
6557
|
+
const path4 = rt.path.join(dir, name);
|
|
6480
6558
|
try {
|
|
6481
|
-
entries3.push({ id: name.slice(0, -".json".length), path:
|
|
6559
|
+
entries3.push({ id: name.slice(0, -".json".length), path: path4, job: await loadJob(rt, path4) });
|
|
6482
6560
|
} catch (error2) {
|
|
6483
|
-
throw new JobError(msg(`job file ${
|
|
6561
|
+
throw new JobError(msg(`job file ${path4} cannot be read (${errorText(error2)})`, `\u4EFB\u52A1\u6587\u4EF6 ${path4} \u65E0\u6CD5\u8BFB\u53D6\uFF08${errorText(error2)}\uFF09`));
|
|
6484
6562
|
}
|
|
6485
6563
|
}
|
|
6486
6564
|
return entries3;
|
|
@@ -6652,14 +6730,14 @@ var init_ledger = __esm({
|
|
|
6652
6730
|
init_base();
|
|
6653
6731
|
init_i18n();
|
|
6654
6732
|
queues = /* @__PURE__ */ new Map();
|
|
6655
|
-
exclusive = (
|
|
6656
|
-
const next = (queues.get(
|
|
6657
|
-
queues.set(
|
|
6733
|
+
exclusive = (path4, task) => {
|
|
6734
|
+
const next = (queues.get(path4) ?? Promise.resolve()).then(task, task);
|
|
6735
|
+
queues.set(path4, next.then(() => void 0, () => void 0));
|
|
6658
6736
|
return next;
|
|
6659
6737
|
};
|
|
6660
|
-
load2 = async (rt,
|
|
6661
|
-
if (!(await rt.fs.stat(
|
|
6662
|
-
const text13 = await rt.fs.readText(
|
|
6738
|
+
load2 = async (rt, path4) => {
|
|
6739
|
+
if (!(await rt.fs.stat(path4))?.isFile) return { rows: [], text: "" };
|
|
6740
|
+
const text13 = await rt.fs.readText(path4);
|
|
6663
6741
|
const rows3 = text13.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => JSON.parse(line));
|
|
6664
6742
|
return { rows: rows3, text: text13 };
|
|
6665
6743
|
};
|
|
@@ -6668,9 +6746,9 @@ var init_ledger = __esm({
|
|
|
6668
6746
|
for (const row of rows3) if (row.quoteId === quoteId2) hit = row;
|
|
6669
6747
|
return hit;
|
|
6670
6748
|
};
|
|
6671
|
-
append = async (rt,
|
|
6749
|
+
append = async (rt, path4, text13, record2) => {
|
|
6672
6750
|
const lead = text13 && !text13.endsWith("\n") ? "\n" : "";
|
|
6673
|
-
await writeAtomic(rt,
|
|
6751
|
+
await writeAtomic(rt, path4, `${text13}${lead}${canonicalJson(record2, false, false)}
|
|
6674
6752
|
`);
|
|
6675
6753
|
};
|
|
6676
6754
|
get = (rt, ledgerPath, quoteId2) => exclusive(ledgerPath, async () => latest((await load2(rt, ledgerPath)).rows, quoteId2));
|
|
@@ -6806,9 +6884,9 @@ var init_cli_quote = __esm({
|
|
|
6806
6884
|
init_i18n();
|
|
6807
6885
|
readPrompt = async (ctx, a) => {
|
|
6808
6886
|
if (a.promptFile) {
|
|
6809
|
-
const
|
|
6810
|
-
if (!(await ctx.rt.fs.stat(
|
|
6811
|
-
return ctx.rt.fs.readText(
|
|
6887
|
+
const path4 = resolvePath(ctx.rt, a.promptFile);
|
|
6888
|
+
if (!(await ctx.rt.fs.stat(path4))?.isFile) throw new CliReject(2, msg(`the prompt file does not exist: ${a.promptFile}`, `prompt \u6587\u4EF6\u4E0D\u5B58\u5728: ${a.promptFile}`));
|
|
6889
|
+
return ctx.rt.fs.readText(path4);
|
|
6812
6890
|
}
|
|
6813
6891
|
if (a.prompt) return a.prompt;
|
|
6814
6892
|
throw new CliReject(2, msg("give --prompt or --prompt-file", "\u5FC5\u987B\u63D0\u4F9B --prompt \u6216 --prompt-file"));
|
|
@@ -6959,14 +7037,14 @@ var init_cli_quote = __esm({
|
|
|
6959
7037
|
msg(`the request total of ${priced.total} = ${priced.unit}\xD7${count5} credits is above the hard cap of ${cap2}; refused`, `\u5355\u8BF7\u6C42\u603B\u79EF\u5206 ${priced.total} = ${priced.unit}\xD7${count5} \u8D85\u8FC7\u786C\u9876 ${cap2}\uFF0C\u62D2\u7EDD`)
|
|
6960
7038
|
);
|
|
6961
7039
|
const record2 = buildRecord(ctx, name, a, priced, prompt, refs, count5, pcfg);
|
|
6962
|
-
const
|
|
6963
|
-
await writeAtomic(ctx.rt,
|
|
7040
|
+
const path4 = ctx.rt.path.join(quoteDirOf(ctx), `${String(record2.quoteId)}.json`);
|
|
7041
|
+
await writeAtomic(ctx.rt, path4, JSON.stringify(record2, null, 2));
|
|
6964
7042
|
const { unit, total: total2 } = priced;
|
|
6965
7043
|
const snapshot = record2.pricingSnapshot;
|
|
6966
7044
|
return {
|
|
6967
7045
|
ok: true,
|
|
6968
7046
|
quote: record2,
|
|
6969
|
-
quoteFile:
|
|
7047
|
+
quoteFile: path4,
|
|
6970
7048
|
billing: {
|
|
6971
7049
|
unitAmount: unit ? String(unit) : null,
|
|
6972
7050
|
count: count5,
|
|
@@ -7005,18 +7083,18 @@ var init_cli_generate = __esm({
|
|
|
7005
7083
|
priceText = (value) => value === null ? msg("unknown", "\u672A\u77E5") : String(value);
|
|
7006
7084
|
idempotencyKey = (a, record2) => a.idempotencyKey || `skill-${createHash12("sha256").update(`${record2.quoteId}|${record2.requestHash}`, "utf8").digest("hex").slice(0, 40)}`;
|
|
7007
7085
|
loadQuote = async (ctx, quoteId2) => {
|
|
7008
|
-
const
|
|
7009
|
-
if (!(await ctx.rt.fs.stat(
|
|
7086
|
+
const path4 = ctx.rt.path.join(quoteDirOf(ctx), `${quoteId2}.json`);
|
|
7087
|
+
if (!(await ctx.rt.fs.stat(path4))?.isFile) throw new CliReject(1, msg(`quote ${quoteId2} does not exist (run quote first)`, `quote ${quoteId2} \u4E0D\u5B58\u5728\uFF08\u5148\u6267\u884C quote\uFF09`));
|
|
7010
7088
|
let record2;
|
|
7011
7089
|
try {
|
|
7012
|
-
record2 = await readJson(ctx.rt,
|
|
7090
|
+
record2 = await readJson(ctx.rt, path4);
|
|
7013
7091
|
} catch (error2) {
|
|
7014
7092
|
if (!(error2 instanceof SyntaxError)) throw error2;
|
|
7015
7093
|
throw new CliReject(1, msg(`the record of quote ${quoteId2} is not valid JSON (the file may have been edited); refused, quote again`, `quote ${quoteId2} \u8BB0\u5F55\u4E0D\u662F\u5408\u6CD5 JSON\uFF08\u6587\u4EF6\u53EF\u80FD\u88AB\u7F16\u8F91\uFF09\uFF0C\u62D2\u7EDD\u5E76\u91CD\u65B0 quote`));
|
|
7016
7094
|
}
|
|
7017
7095
|
if (!record2.recordHash || recordIntegrityHash(record2) !== record2.recordHash)
|
|
7018
7096
|
throw new CliReject(1, msg("the quote record failed its integrity check (the file may have been edited); refused, quote again", "quote \u8BB0\u5F55\u5B8C\u6574\u6027\u6821\u9A8C\u5931\u8D25\uFF08\u6587\u4EF6\u53EF\u80FD\u88AB\u7F16\u8F91\uFF09\uFF0C\u62D2\u7EDD\u5E76\u91CD\u65B0 quote"));
|
|
7019
|
-
return { record: record2, path:
|
|
7097
|
+
return { record: record2, path: path4 };
|
|
7020
7098
|
};
|
|
7021
7099
|
checkUsable = (ctx, record2, quoteId2) => {
|
|
7022
7100
|
if (record2.status !== "quoted") throw new CliReject(1, msg(`quote ${quoteId2} is ${record2.status} and cannot be submitted`, `quote ${quoteId2} \u72B6\u6001\u4E3A ${record2.status}\uFF0C\u4E0D\u53EF\u7528\u4E8E\u63D0\u4EA4`));
|
|
@@ -7131,9 +7209,9 @@ var init_cli_generate = __esm({
|
|
|
7131
7209
|
await settle(ctx.rt, ledgerPath, record2.quoteId, "ambiguous", { reason: "poll timeout", taskId });
|
|
7132
7210
|
throw new CliReject(1, msg("polling timed out and was recorded as ambiguous; completion is not confirmed, do not submit again", "\u8F6E\u8BE2\u8D85\u65F6\uFF0C\u8BB0 ambiguous\uFF1B\u672A\u786E\u8BA4\u5B8C\u6210\uFF0C\u7981\u6B62\u91CD\u8BD5\u63D0\u4EA4"));
|
|
7133
7211
|
};
|
|
7134
|
-
markConsumed = (ctx, record2,
|
|
7212
|
+
markConsumed = (ctx, record2, path4) => {
|
|
7135
7213
|
record2.status = "consumed";
|
|
7136
|
-
return writeAtomic(ctx.rt,
|
|
7214
|
+
return writeAtomic(ctx.rt, path4, JSON.stringify(record2, null, 2));
|
|
7137
7215
|
};
|
|
7138
7216
|
finish = async (ctx, a, ledgerPath, record2, qpath, prov, submitted) => {
|
|
7139
7217
|
const taskId = submitted.taskId;
|
|
@@ -7586,12 +7664,12 @@ var init_retry = __esm({
|
|
|
7586
7664
|
adoptLegacyAttempt = (job) => {
|
|
7587
7665
|
if (job.runAttempted && !job.attemptedQuoteId && job.quoteId) job.attemptedQuoteId = job.quoteId;
|
|
7588
7666
|
};
|
|
7589
|
-
recordRun = async (project, job,
|
|
7667
|
+
recordRun = async (project, job, path4, quoteId2, wasAttempted) => {
|
|
7590
7668
|
const attempt2 = quoteId2 ? await attempt(project.rt, ledgerPathOf2(project), quoteId2) : null;
|
|
7591
7669
|
if (quoteId2 && attempt2 && !refusedUncharged(attempt2)) job.attemptedQuoteId = quoteId2;
|
|
7592
7670
|
else if (wasAttempted) job.runAttempted = true;
|
|
7593
7671
|
else delete job.runAttempted;
|
|
7594
|
-
await saveJob(project.rt,
|
|
7672
|
+
await saveJob(project.rt, path4, job);
|
|
7595
7673
|
};
|
|
7596
7674
|
}
|
|
7597
7675
|
});
|
|
@@ -7606,16 +7684,16 @@ var init_pending = __esm({
|
|
|
7606
7684
|
init_retry();
|
|
7607
7685
|
init_i18n();
|
|
7608
7686
|
pendingOfJob = (job) => typeof job.pending?.quoteId === "string" ? job.pending : void 0;
|
|
7609
|
-
pendingQuote = async (project, job,
|
|
7687
|
+
pendingQuote = async (project, job, path4) => {
|
|
7610
7688
|
const noted = pendingOfJob(job);
|
|
7611
7689
|
for (const quoteId2 of [...new Set([noted?.quoteId, job.quoteId].filter((q) => typeof q === "string"))]) {
|
|
7612
7690
|
const row = await get(project.rt, ledgerPathOf2(project), quoteId2);
|
|
7613
7691
|
if (row?.state === "submitted") return quoteId2;
|
|
7614
7692
|
}
|
|
7615
|
-
if (noted) await followLedger(project, job,
|
|
7693
|
+
if (noted) await followLedger(project, job, path4, noted.quoteId, null);
|
|
7616
7694
|
return null;
|
|
7617
7695
|
};
|
|
7618
|
-
markPending = async (project, job,
|
|
7696
|
+
markPending = async (project, job, path4, quoteId2, outcome, wasAttempted) => {
|
|
7619
7697
|
const said = outcome.result.pending ?? {};
|
|
7620
7698
|
const earlier = pendingOfJob(job);
|
|
7621
7699
|
const pending3 = {
|
|
@@ -7625,12 +7703,12 @@ var init_pending = __esm({
|
|
|
7625
7703
|
...(earlier?.quoteId === quoteId2 ? earlier.wasAttempted : wasAttempted) ? { wasAttempted: true } : {}
|
|
7626
7704
|
};
|
|
7627
7705
|
Object.assign(job, { status: "submitted", runAttempted: true, pending: pending3 });
|
|
7628
|
-
await saveJob(project.rt,
|
|
7706
|
+
await saveJob(project.rt, path4, job);
|
|
7629
7707
|
};
|
|
7630
|
-
followLedger = async (project, job,
|
|
7708
|
+
followLedger = async (project, job, path4, quoteId2, outcome) => {
|
|
7631
7709
|
const row = await get(project.rt, ledgerPathOf2(project), quoteId2);
|
|
7632
7710
|
if (row?.state === "submitted") {
|
|
7633
|
-
if (outcome) await markPending(project, job,
|
|
7711
|
+
if (outcome) await markPending(project, job, path4, quoteId2, outcome, pendingOfJob(job)?.wasAttempted);
|
|
7634
7712
|
return;
|
|
7635
7713
|
}
|
|
7636
7714
|
const wasAttempted = pendingOfJob(job)?.wasAttempted ?? Boolean(job.attemptedQuoteId);
|
|
@@ -7638,11 +7716,11 @@ var init_pending = __esm({
|
|
|
7638
7716
|
const meta = row?.meta ?? {};
|
|
7639
7717
|
if (row?.state === "consumed" && meta.materializeError === void 0) {
|
|
7640
7718
|
Object.assign(job, { status: "generated", result: outcome?.code === 0 ? outcome.result.materials : meta.materials });
|
|
7641
|
-
await saveJob(project.rt,
|
|
7719
|
+
await saveJob(project.rt, path4, job);
|
|
7642
7720
|
return;
|
|
7643
7721
|
}
|
|
7644
7722
|
job.status = "quoted";
|
|
7645
|
-
await recordRun(project, job,
|
|
7723
|
+
await recordRun(project, job, path4, quoteId2, wasAttempted);
|
|
7646
7724
|
};
|
|
7647
7725
|
pendingNext = (dir, id2) => msg(
|
|
7648
7726
|
`The picture is being made on popost.ai and is paid for. Do the work that does not need it (write the pages), then pick it up with image run --dir ${dir} --id ${id2} (waits for it) or image status --dir ${dir} --id ${id2} (one look); it is never sent or charged again.`,
|
|
@@ -7707,19 +7785,19 @@ var init_run = __esm({
|
|
|
7707
7785
|
};
|
|
7708
7786
|
resultsDir = (project, job) => project.rt.path.join(project.root, "production", "results", job.id);
|
|
7709
7787
|
withNext = (project, job, outcome) => outcome.code === PENDING_EXIT ? { ...outcome, result: { ...outcome.result, next: pendingNext(project.root, job.id) } } : outcome;
|
|
7710
|
-
pickUpJob = async (project, job,
|
|
7788
|
+
pickUpJob = async (project, job, path4, quoteId2, call2) => {
|
|
7711
7789
|
const command2 = { name: "generate", args: { quoteId: quoteId2, confirm: true, pickUp: true, ref: [], refUrl: [], outDir: resultsDir(project, job), ...call2.noWait ? { noWait: true } : {} } };
|
|
7712
7790
|
const outcome = await delegate(project, invocation(project, job.provider, call2, command2));
|
|
7713
|
-
await followLedger(project, job,
|
|
7791
|
+
await followLedger(project, job, path4, quoteId2, outcome);
|
|
7714
7792
|
return withNext(project, job, outcome);
|
|
7715
7793
|
};
|
|
7716
|
-
statusPickUp = async (project, job,
|
|
7717
|
-
const quoteId2 = await pendingQuote(project, job,
|
|
7718
|
-
return quoteId2 ? pickUpJob(project, job,
|
|
7794
|
+
statusPickUp = async (project, job, path4, call2) => {
|
|
7795
|
+
const quoteId2 = await pendingQuote(project, job, path4);
|
|
7796
|
+
return quoteId2 ? pickUpJob(project, job, path4, quoteId2, { ...call2, noWait: true }) : null;
|
|
7719
7797
|
};
|
|
7720
|
-
markAttempted = async (project, job,
|
|
7798
|
+
markAttempted = async (project, job, path4) => {
|
|
7721
7799
|
job.runAttempted = true;
|
|
7722
|
-
await saveJob(project.rt,
|
|
7800
|
+
await saveJob(project.rt, path4, job);
|
|
7723
7801
|
};
|
|
7724
7802
|
refusal = (error2) => ({ code: 1, result: { ok: false, code: 1, error: error2 } });
|
|
7725
7803
|
quoteProblem = async (project, job, quoteId2) => {
|
|
@@ -7745,34 +7823,34 @@ var init_run = __esm({
|
|
|
7745
7823
|
return again(`expired at ${String(record2.expiresAt)}`, `\u5DF2\u4E8E ${String(record2.expiresAt)} \u8FC7\u671F`);
|
|
7746
7824
|
return null;
|
|
7747
7825
|
};
|
|
7748
|
-
quoteJob = async (project, job,
|
|
7826
|
+
quoteJob = async (project, job, path4, call2) => {
|
|
7749
7827
|
const command2 = quoteCommand(job);
|
|
7750
7828
|
adoptLegacyAttempt(job);
|
|
7751
7829
|
const outcome = await delegate(project, invocation(project, job.provider, call2, command2));
|
|
7752
7830
|
if (outcome.code === 0) {
|
|
7753
7831
|
Object.assign(job, { status: "quoted", quoteId: outcome.result.quote.quoteId });
|
|
7754
|
-
await saveJob(project.rt,
|
|
7832
|
+
await saveJob(project.rt, path4, job);
|
|
7755
7833
|
}
|
|
7756
7834
|
return outcome;
|
|
7757
7835
|
};
|
|
7758
|
-
runJob = async (project, job,
|
|
7836
|
+
runJob = async (project, job, path4, call2) => {
|
|
7759
7837
|
const command2 = generateCommand(project, job, call2, await submissionKey(project, job, call2));
|
|
7760
7838
|
const problem4 = call2.quoteId ? await quoteProblem(project, job, call2.quoteId) : null;
|
|
7761
7839
|
if (problem4) return refusal(problem4);
|
|
7762
7840
|
const wasAttempted = job.runAttempted;
|
|
7763
|
-
await markAttempted(project, job,
|
|
7841
|
+
await markAttempted(project, job, path4);
|
|
7764
7842
|
const outcome = await delegate(project, invocation(project, job.provider, call2, command2));
|
|
7765
7843
|
if (outcome.code === 0) {
|
|
7766
7844
|
Object.assign(job, { status: "generated", result: outcome.result.materials });
|
|
7767
|
-
await saveJob(project.rt,
|
|
7768
|
-
} else if (outcome.code === PENDING_EXIT && call2.quoteId) await markPending(project, job,
|
|
7769
|
-
else await recordRun(project, job,
|
|
7845
|
+
await saveJob(project.rt, path4, job);
|
|
7846
|
+
} else if (outcome.code === PENDING_EXIT && call2.quoteId) await markPending(project, job, path4, call2.quoteId, outcome, wasAttempted);
|
|
7847
|
+
else await recordRun(project, job, path4, call2.quoteId, wasAttempted);
|
|
7770
7848
|
return withNext(project, job, outcome);
|
|
7771
7849
|
};
|
|
7772
|
-
quoteOrRun = async (project, job,
|
|
7773
|
-
const making2 = await pendingQuote(project, job,
|
|
7850
|
+
quoteOrRun = async (project, job, path4, action, call2) => {
|
|
7851
|
+
const making2 = await pendingQuote(project, job, path4);
|
|
7774
7852
|
if (making2 && action === "quote") throw new JobError(beingMade(project.root, job.id, making2, "quote"));
|
|
7775
|
-
if (making2) return pickUpJob(project, job,
|
|
7853
|
+
if (making2) return pickUpJob(project, job, path4, making2, call2);
|
|
7776
7854
|
await checkRefsUnchanged(project.rt, job);
|
|
7777
7855
|
if (job.status === "completed") throw new JobError(msg("job is complete; reuse its asset", "\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF1B\u8BF7\u590D\u7528\u5B83\u7684\u7D20\u6750"));
|
|
7778
7856
|
if (job.provider.channel === "host") throw new JobError(
|
|
@@ -7781,9 +7859,9 @@ var init_run = __esm({
|
|
|
7781
7859
|
"host\uFF1A\u7528\u8FD9\u4E2A\u4EFB\u52A1\u7684 prompt \u8C03\u7528\u5B9E\u9645\u53EF\u7528\u7684\u56FE\u7247\u5DE5\u5177\uFF08count=1\uFF09\uFF0C\u518D\u7528\u5B83\u751F\u6210\u7684\u771F\u5B9E\u6587\u4EF6\u8FD0\u884C complete"
|
|
7782
7860
|
)
|
|
7783
7861
|
);
|
|
7784
|
-
return action === "quote" ? quoteJob(project, job,
|
|
7862
|
+
return action === "quote" ? quoteJob(project, job, path4, call2) : runJob(project, job, path4, call2);
|
|
7785
7863
|
};
|
|
7786
|
-
completeJob = async (project, job,
|
|
7864
|
+
completeJob = async (project, job, path4, call2) => {
|
|
7787
7865
|
const { rt } = project;
|
|
7788
7866
|
if (job.status === "completed") throw new JobError(msg("already complete", "\u5DF2\u5B8C\u6210"));
|
|
7789
7867
|
if (!call2.file || !call2.note) throw new JobError(msg("real image file and inspection note required", "\u9700\u8981\u771F\u5B9E\u7684\u56FE\u7247\u6587\u4EF6\uFF08--file\uFF09\u548C\u67E5\u770B\u8BB0\u5F55\uFF08--note\uFF09"));
|
|
@@ -7796,7 +7874,7 @@ var init_run = __esm({
|
|
|
7796
7874
|
}
|
|
7797
7875
|
const asset = job.purpose === "composition" ? await project.importReference(call2.file, "style", null, true) : await project.addAssetBytes(data, job.id + rt.path.extname(call2.file).toLowerCase());
|
|
7798
7876
|
Object.assign(job, { status: "completed", asset, inspection: call2.note, tool: call2.tool ?? null });
|
|
7799
|
-
await saveJob(rt,
|
|
7877
|
+
await saveJob(rt, path4, job);
|
|
7800
7878
|
};
|
|
7801
7879
|
}
|
|
7802
7880
|
});
|
|
@@ -8050,16 +8128,16 @@ var init_prepare = __esm({
|
|
|
8050
8128
|
`job '${id2}' is already quoted (quote ${quoteId2}) and is not replaced: the quote is bound to its prompt, aspect and references. Run it with image run --dir ${dir} --id ${id2} --quote-id ${quoteId2} --confirm once the user authorized the cost, or re-price it unchanged with image quote --dir ${dir} --id ${id2}. To change the request instead, the quote must be discarded; that is safe only while production/ledger.jsonl has no record of quote ${quoteId2} (nothing was submitted): then remove production/jobs/${id2}.json and prepare again.`,
|
|
8051
8129
|
`\u4EFB\u52A1 '${id2}' \u5DF2\u62A5\u4EF7\uFF08\u62A5\u4EF7 ${quoteId2}\uFF09\uFF0C\u4E0D\u4F1A\u88AB\u66FF\u6362\uFF1A\u62A5\u4EF7\u7ED1\u5B9A\u4E86\u5B83\u7684 prompt\u3001\u6BD4\u4F8B\u548C\u53C2\u8003\u56FE\u3002\u7528\u6237\u6388\u6743\u8D39\u7528\u540E\uFF0C\u7528 image run --dir ${dir} --id ${id2} --quote-id ${quoteId2} --confirm \u8FD0\u884C\uFF1B\u6216\u7528 image quote --dir ${dir} --id ${id2} \u539F\u6837\u91CD\u65B0\u62A5\u4EF7\u3002\u5982\u679C\u8981\u6539\u8BF7\u6C42\uFF0C\u5FC5\u987B\u653E\u5F03\u8FD9\u4E2A\u62A5\u4EF7\uFF1B\u53EA\u6709\u5F53 production/ledger.jsonl \u91CC\u6CA1\u6709\u62A5\u4EF7 ${quoteId2} \u7684\u8BB0\u5F55\uFF08\u672A\u63D0\u4EA4\u4EFB\u4F55\u5185\u5BB9\uFF09\u65F6\u624D\u5B89\u5168\uFF1A\u8FD9\u65F6\u5220\u6389 production/jobs/${id2}.json \u540E\u91CD\u65B0 prepare\u3002`
|
|
8052
8130
|
);
|
|
8053
|
-
replacesDraft = async (project,
|
|
8054
|
-
if (await project.rt.fs.stat(
|
|
8131
|
+
replacesDraft = async (project, path4, id2) => {
|
|
8132
|
+
if (await project.rt.fs.stat(path4) === null) return false;
|
|
8055
8133
|
let job;
|
|
8056
8134
|
try {
|
|
8057
|
-
job = await loadJob(project.rt,
|
|
8135
|
+
job = await loadJob(project.rt, path4);
|
|
8058
8136
|
} catch (error2) {
|
|
8059
8137
|
throw new JobError(
|
|
8060
8138
|
msg(
|
|
8061
|
-
`job '${id2}' exists but ${
|
|
8062
|
-
`\u4EFB\u52A1 '${id2}' \u5DF2\u5B58\u5728\uFF0C\u4F46 ${
|
|
8139
|
+
`job '${id2}' exists but ${path4} cannot be read (${errorText(error2)}); fix or remove that file`,
|
|
8140
|
+
`\u4EFB\u52A1 '${id2}' \u5DF2\u5B58\u5728\uFF0C\u4F46 ${path4} \u65E0\u6CD5\u8BFB\u53D6\uFF08${errorText(error2)}\uFF09\uFF1B\u8BF7\u4FEE\u590D\u6216\u5220\u9664\u8FD9\u4E2A\u6587\u4EF6`
|
|
8063
8141
|
)
|
|
8064
8142
|
);
|
|
8065
8143
|
}
|
|
@@ -8288,10 +8366,10 @@ var init_steps = __esm({
|
|
|
8288
8366
|
for (const token of entry2.ref) refs.push(await locateRef(ctx, token) ?? token);
|
|
8289
8367
|
return { id: entry2.id, promptFile: fromSpec(ctx, entry2.promptFile), purpose: entry2.purpose, refs, aspect: entry2.aspect, config: ctx.config };
|
|
8290
8368
|
};
|
|
8291
|
-
existingJob = async (project,
|
|
8292
|
-
if (!await isFile(project.rt,
|
|
8369
|
+
existingJob = async (project, path4) => {
|
|
8370
|
+
if (!await isFile(project.rt, path4)) return null;
|
|
8293
8371
|
try {
|
|
8294
|
-
return await loadJob(project.rt,
|
|
8372
|
+
return await loadJob(project.rt, path4);
|
|
8295
8373
|
} catch {
|
|
8296
8374
|
return null;
|
|
8297
8375
|
}
|
|
@@ -8299,9 +8377,9 @@ var init_steps = __esm({
|
|
|
8299
8377
|
prepareOne = async (project, call2) => {
|
|
8300
8378
|
const composition = call2.purpose === "composition";
|
|
8301
8379
|
const id2 = composition ? "composition" : call2.id;
|
|
8302
|
-
const
|
|
8303
|
-
const earlier = await existingJob(project,
|
|
8304
|
-
if (earlier && sameRequest(project, earlier, (await draftJob(project, call2, { id: id2, path:
|
|
8380
|
+
const path4 = jobFile(project, id2);
|
|
8381
|
+
const earlier = await existingJob(project, path4);
|
|
8382
|
+
if (earlier && sameRequest(project, earlier, (await draftJob(project, call2, { id: id2, path: path4, composition })).job)) return { unchanged: true, notes: [] };
|
|
8305
8383
|
const made = await prepareJob(project, call2);
|
|
8306
8384
|
return { unchanged: false, notes: made.notes };
|
|
8307
8385
|
};
|
|
@@ -9079,12 +9157,12 @@ var init_project_tools = __esm({
|
|
|
9079
9157
|
(source2) => source2.kind === "local-reference" && source2.role === "layout" && typeof source2.path === "string" && /^reference\/[\w.-]+$/.test(source2.path)
|
|
9080
9158
|
);
|
|
9081
9159
|
hasComparison = (project) => project.manifest.mode === "strict" || layoutPaths(project).length > 0;
|
|
9082
|
-
image = (
|
|
9083
|
-
src: base + "/" +
|
|
9084
|
-
name:
|
|
9160
|
+
image = (path4, base = "") => ({
|
|
9161
|
+
src: base + "/" + path4.split("/").map(encodeURIComponent).join("/"),
|
|
9162
|
+
name: path4.split("/").at(-1) ?? "Image"
|
|
9085
9163
|
});
|
|
9086
|
-
readReference2 = async (project,
|
|
9087
|
-
const file = await readProjectFile(project.rt, project.root,
|
|
9164
|
+
readReference2 = async (project, path4) => {
|
|
9165
|
+
const file = await readProjectFile(project.rt, project.root, path4);
|
|
9088
9166
|
if (!file) return null;
|
|
9089
9167
|
try {
|
|
9090
9168
|
const { width, height, mime } = sniffImage(file.data);
|
|
@@ -9324,20 +9402,20 @@ var init_push = __esm({
|
|
|
9324
9402
|
}
|
|
9325
9403
|
};
|
|
9326
9404
|
readPicture = async (rt, project, url) => {
|
|
9327
|
-
const
|
|
9328
|
-
const file =
|
|
9329
|
-
if (!
|
|
9405
|
+
const path4 = assetPath(url);
|
|
9406
|
+
const file = path4 ? await readProjectFile(rt, project.root, path4) : null;
|
|
9407
|
+
if (!path4 || !file)
|
|
9330
9408
|
throw new CloudError("ASSET_MISSING", msg(`a picture the pages use is not in the project's assets folder: ${url}`, `\u9875\u9762\u7528\u5230\u7684\u4E00\u5F20\u56FE\u7247\u4E0D\u5728\u5DE5\u7A0B\u7684 assets \u6587\u4EF6\u5939\u91CC\uFF1A${url}`));
|
|
9331
9409
|
const mime = sniffImageMime(file.data.subarray(0, 16));
|
|
9332
9410
|
if (!mime)
|
|
9333
9411
|
throw new CloudError(
|
|
9334
9412
|
"ASSET_UNSUPPORTED",
|
|
9335
9413
|
msg(
|
|
9336
|
-
`${
|
|
9337
|
-
`${
|
|
9414
|
+
`${path4.slice(1)} is not a PNG, JPEG, GIF or WebP picture, which are the only ones the cloud takes`,
|
|
9415
|
+
`${path4.slice(1)} \u4E0D\u662F PNG\u3001JPEG\u3001GIF \u6216 WebP \u56FE\u7247\uFF0C\u4E91\u7AEF\u53EA\u63A5\u53D7\u8FD9\u51E0\u79CD\u683C\u5F0F`
|
|
9338
9416
|
)
|
|
9339
9417
|
);
|
|
9340
|
-
return { url, file:
|
|
9418
|
+
return { url, file: path4.slice(1), data: file.data, sha: sha256(file.data), mime };
|
|
9341
9419
|
};
|
|
9342
9420
|
ensureUploads = async (rt, client2, pictures, cache2, fresh, out2) => {
|
|
9343
9421
|
for (const picture3 of pictures) {
|
|
@@ -9364,8 +9442,8 @@ var init_push = __esm({
|
|
|
9364
9442
|
const found = [];
|
|
9365
9443
|
for (const issue4 of issues) {
|
|
9366
9444
|
if (!isRecord(issue4)) continue;
|
|
9367
|
-
const
|
|
9368
|
-
const match = /^assets\.(\d+)\.uploadId$/.exec(
|
|
9445
|
+
const path4 = Array.isArray(issue4.path) ? issue4.path.map(String).join(".") : String(issue4.path ?? "");
|
|
9446
|
+
const match = /^assets\.(\d+)\.uploadId$/.exec(path4);
|
|
9369
9447
|
if (match) found.push(Number(match[1]));
|
|
9370
9448
|
}
|
|
9371
9449
|
return found;
|
|
@@ -9594,11 +9672,15 @@ var init_service = __esm({
|
|
|
9594
9672
|
ticket;
|
|
9595
9673
|
tail = Promise.resolve();
|
|
9596
9674
|
timer;
|
|
9675
|
+
lastMode;
|
|
9676
|
+
get runtime() {
|
|
9677
|
+
return this.rt.refreshAccount ? { ...this.rt, ...this.rt.refreshAccount() } : this.rt;
|
|
9678
|
+
}
|
|
9597
9679
|
lang = "en";
|
|
9598
9680
|
get root() {
|
|
9599
9681
|
return this.known ?? this.rootOf();
|
|
9600
9682
|
}
|
|
9601
|
-
mode = () => resolveCloudMode(this.
|
|
9683
|
+
mode = () => resolveCloudMode(this.runtime, this.options.enabled !== false, this.options.loginOnly);
|
|
9602
9684
|
/** A different project is being served (`import-project`): nothing of the old one carries over. */
|
|
9603
9685
|
sync() {
|
|
9604
9686
|
const root = this.rootOf();
|
|
@@ -9624,6 +9706,9 @@ var init_service = __esm({
|
|
|
9624
9706
|
this.sync();
|
|
9625
9707
|
this.purgePending();
|
|
9626
9708
|
const mode = this.mode();
|
|
9709
|
+
const connected2 = this.lastMode === "anonymous" && mode === "keyed";
|
|
9710
|
+
this.lastMode = mode;
|
|
9711
|
+
if (connected2) queueMicrotask(() => this.autoStart());
|
|
9627
9712
|
if (this.phase === "waiting" && this.pending.size === 0) this.phase = "idle";
|
|
9628
9713
|
const project = this.options.project ? void 0 : await Project.load(this.rt, this.root);
|
|
9629
9714
|
const record2 = this.options.project ? await this.options.project.record() : await readCloudRecord(project);
|
|
@@ -9644,7 +9729,7 @@ var init_service = __esm({
|
|
|
9644
9729
|
/** Begin the browser login on the service's `port`; returns the URL to open on popost.ai. */
|
|
9645
9730
|
async start(lang, port) {
|
|
9646
9731
|
this.sync();
|
|
9647
|
-
const client2 = new PopostClient(this.
|
|
9732
|
+
const client2 = new PopostClient(this.runtime);
|
|
9648
9733
|
const metadata = this.options.project ? await this.options.project.info() : await Project.load(this.rt, this.root).then((p) => ({ projectId: p.manifest.projectId, title: String(p.manifest.brief ?? "") || "Popost", pages: p.manifest.pages.length }));
|
|
9649
9734
|
const projectId = metadata.projectId;
|
|
9650
9735
|
if (!/^[A-Za-z0-9-]{8,64}$/.test(projectId ?? ""))
|
|
@@ -9695,9 +9780,9 @@ var init_service = __esm({
|
|
|
9695
9780
|
return result;
|
|
9696
9781
|
}
|
|
9697
9782
|
clientFor(mode) {
|
|
9698
|
-
if (mode === "keyed") return new PopostClient(this.
|
|
9783
|
+
if (mode === "keyed") return new PopostClient(this.runtime);
|
|
9699
9784
|
const ticket2 = this.liveTicket();
|
|
9700
|
-
return ticket2 ? new PopostClient(this.
|
|
9785
|
+
return ticket2 ? new PopostClient(this.runtime, { bearer: ticket2.bearer }) : null;
|
|
9701
9786
|
}
|
|
9702
9787
|
async runPush(force2) {
|
|
9703
9788
|
const mode = this.mode();
|
|
@@ -9711,7 +9796,7 @@ var init_service = __esm({
|
|
|
9711
9796
|
this.error = void 0;
|
|
9712
9797
|
try {
|
|
9713
9798
|
if (this.options.project) await this.options.project.push(client2, force2, this.lang);
|
|
9714
|
-
else await pushProject(this.
|
|
9799
|
+
else await pushProject(this.runtime, { dir: this.root, client: client2, force: force2, locale: this.lang, session: this.options.session });
|
|
9715
9800
|
this.phase = "saved";
|
|
9716
9801
|
if (mode === "anonymous") this.ticket = void 0;
|
|
9717
9802
|
} catch (error2) {
|
|
@@ -9780,7 +9865,7 @@ var init_handoff = __esm({
|
|
|
9780
9865
|
init_errors3();
|
|
9781
9866
|
init_i18n();
|
|
9782
9867
|
init_canvas_state();
|
|
9783
|
-
EDITOR_VERSION = "4.1.
|
|
9868
|
+
EDITOR_VERSION = "4.1.3";
|
|
9784
9869
|
editorInfo = (project) => {
|
|
9785
9870
|
const identity = sha256(project.rt.path.resolve(project.root));
|
|
9786
9871
|
return {
|
|
@@ -9991,8 +10076,8 @@ var init_png = __esm({
|
|
|
9991
10076
|
};
|
|
9992
10077
|
PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
|
|
9993
10078
|
receiptPath = (project, png2) => {
|
|
9994
|
-
const { path:
|
|
9995
|
-
return png2.slice(0, png2.length -
|
|
10079
|
+
const { path: path4 } = project.rt;
|
|
10080
|
+
return png2.slice(0, png2.length - path4.extname(png2).length) + ".render.json";
|
|
9996
10081
|
};
|
|
9997
10082
|
u32 = (data, offset) => (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
|
|
9998
10083
|
cachedPng = async (project, pid, outPath) => {
|
|
@@ -10250,14 +10335,14 @@ var init_routes_get = __esm({
|
|
|
10250
10335
|
};
|
|
10251
10336
|
handleGet = async (ctx) => {
|
|
10252
10337
|
if (!hostAllowed(ctx.req.headers.host, ctx.req.port)) return jsonResponse(ctx.req, 403, { ok: false, error: msg("host rejected", "Host \u88AB\u62D2\u7EDD") });
|
|
10253
|
-
const { path:
|
|
10254
|
-
const exact = EXACT[
|
|
10338
|
+
const { path: path4 } = ctx.req;
|
|
10339
|
+
const exact = EXACT[path4];
|
|
10255
10340
|
if (exact) return exact(ctx);
|
|
10256
|
-
if (
|
|
10257
|
-
if (
|
|
10258
|
-
if (
|
|
10259
|
-
return staticFile(ctx, editorDir(ctx),
|
|
10260
|
-
const response = await staticFile(ctx, ctx.state.root,
|
|
10341
|
+
if (path4.startsWith("/api/comparison/")) return localReferenceImage(ctx);
|
|
10342
|
+
if (path4.startsWith("/_preview/")) return preview(ctx);
|
|
10343
|
+
if (path4.startsWith("/_editor/"))
|
|
10344
|
+
return staticFile(ctx, editorDir(ctx), path4.slice("/_editor/".length), msg("editor resource not found", "\u672A\u627E\u5230\u7F16\u8F91\u5668\u8D44\u6E90"));
|
|
10345
|
+
const response = await staticFile(ctx, ctx.state.root, path4, msg("not found", "\u672A\u627E\u5230"));
|
|
10261
10346
|
response.headers["Content-Security-Policy"] = "sandbox; default-src 'none'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; form-action 'none'; base-uri 'none'";
|
|
10262
10347
|
response.headers["X-Content-Type-Options"] = "nosniff";
|
|
10263
10348
|
return response;
|
|
@@ -10420,9 +10505,9 @@ var init_save = __esm({
|
|
|
10420
10505
|
});
|
|
10421
10506
|
};
|
|
10422
10507
|
restore = async (project, backups) => {
|
|
10423
|
-
for (const [
|
|
10424
|
-
if (text13 === null) await project.rt.fs.rm(
|
|
10425
|
-
else await project.rt.fs.writeFile(
|
|
10508
|
+
for (const [path4, text13] of backups) {
|
|
10509
|
+
if (text13 === null) await project.rt.fs.rm(path4);
|
|
10510
|
+
else await project.rt.fs.writeFile(path4, text13);
|
|
10426
10511
|
}
|
|
10427
10512
|
};
|
|
10428
10513
|
savePayload = async (project, data) => {
|
|
@@ -10433,8 +10518,8 @@ var init_save = __esm({
|
|
|
10433
10518
|
const old = structuredClone(project.manifest);
|
|
10434
10519
|
const backups = /* @__PURE__ */ new Map();
|
|
10435
10520
|
for (const { entry: entry2 } of prepared) {
|
|
10436
|
-
const
|
|
10437
|
-
backups.set(
|
|
10521
|
+
const path4 = project.abs(entry2.htmlPath);
|
|
10522
|
+
backups.set(path4, await isFile(rt, path4) ? await rt.fs.readText(path4) : null);
|
|
10438
10523
|
}
|
|
10439
10524
|
try {
|
|
10440
10525
|
project.manifest.pages = prepared.map((p) => p.entry);
|
|
@@ -11113,8 +11198,8 @@ var init_sheet2 = __esm({
|
|
|
11113
11198
|
}
|
|
11114
11199
|
const pictures = [];
|
|
11115
11200
|
for (const pid of pids) {
|
|
11116
|
-
const
|
|
11117
|
-
pictures.push(picture(pid, relPosix(rt, project.root,
|
|
11201
|
+
const path4 = paths.get(pid);
|
|
11202
|
+
pictures.push(picture(pid, relPosix(rt, project.root, path4), await rt.fs.readFile(path4)));
|
|
11118
11203
|
}
|
|
11119
11204
|
return pictures;
|
|
11120
11205
|
};
|
|
@@ -11129,9 +11214,9 @@ var init_sheet2 = __esm({
|
|
|
11129
11214
|
)
|
|
11130
11215
|
);
|
|
11131
11216
|
const pictures = [];
|
|
11132
|
-
for (const [index,
|
|
11133
|
-
if (!await isFile(rt, project.abs(
|
|
11134
|
-
pictures.push(picture(`ref ${index + 1}`,
|
|
11217
|
+
for (const [index, path4] of paths.entries()) {
|
|
11218
|
+
if (!await isFile(rt, project.abs(path4))) throw new ValueError(msg(`reference file is missing: ${path4}`, `\u53C2\u8003\u56FE\u6587\u4EF6\u7F3A\u5931\uFF1A${path4}`));
|
|
11219
|
+
pictures.push(picture(`ref ${index + 1}`, path4, await rt.fs.readFile(project.abs(path4))));
|
|
11135
11220
|
}
|
|
11136
11221
|
return pictures;
|
|
11137
11222
|
};
|
|
@@ -11157,7 +11242,7 @@ var init_sheet2 = __esm({
|
|
|
11157
11242
|
const size = Math.ceil(only.length / count5);
|
|
11158
11243
|
return Array.from({ length: count5 }, (_, k) => [only.slice(k * size, (k + 1) * size)]);
|
|
11159
11244
|
};
|
|
11160
|
-
partPath = (
|
|
11245
|
+
partPath = (path4, k) => k === 0 ? path4 : path4.replace(/(\.jpe?g)$/i, `-${k + 1}$1`);
|
|
11161
11246
|
drawSheets = async (rt, parts, target2, shown3) => {
|
|
11162
11247
|
const drawn = [];
|
|
11163
11248
|
for (const [k, part] of parts.entries()) {
|
|
@@ -11737,8 +11822,8 @@ var init_edit_plan = __esm({
|
|
|
11737
11822
|
].filter((step3) => step3 !== null);
|
|
11738
11823
|
return { crop, rotate, flip, width: out2.width, height: out2.height, draw: out2.draw, grid, steps: steps2 };
|
|
11739
11824
|
};
|
|
11740
|
-
formatOf = (
|
|
11741
|
-
const ext = /\.([a-z0-9]+)$/i.exec(
|
|
11825
|
+
formatOf = (path4) => {
|
|
11826
|
+
const ext = /\.([a-z0-9]+)$/i.exec(path4)?.[1]?.toLowerCase();
|
|
11742
11827
|
if (ext === "png" || ext === "webp") return ext;
|
|
11743
11828
|
if (ext === "jpg" || ext === "jpeg") return "jpeg";
|
|
11744
11829
|
throw new ValueError(msg("--out must end in .png, .jpg, .jpeg or .webp: the extension picks the format", "--out \u5FC5\u987B\u4EE5 .png\u3001.jpg\u3001.jpeg \u6216 .webp \u7ED3\u5C3E\uFF1A\u6269\u5C55\u540D\u51B3\u5B9A\u683C\u5F0F"));
|
|
@@ -11887,9 +11972,9 @@ var init_single_job = __esm({
|
|
|
11887
11972
|
if (target2.action === "run" && target2.id === void 0 && target2.quoteId !== void 0) return holderOf(project, target2.quoteId);
|
|
11888
11973
|
const id2 = target2.id ?? COMPOSITION;
|
|
11889
11974
|
if (!JOB_ID.test(id2)) throw new JobError(msg(`invalid job id: ${id2}`, `\u65E0\u6548\u7684\u4EFB\u52A1 id\uFF1A${id2}`));
|
|
11890
|
-
const
|
|
11891
|
-
if (!await project.rt.fs.stat(
|
|
11892
|
-
return { id: id2, path:
|
|
11975
|
+
const path4 = jobFile(project, id2);
|
|
11976
|
+
if (!await project.rt.fs.stat(path4)) throw await missingJob(project, id2, target2.id === void 0);
|
|
11977
|
+
return { id: id2, path: path4, job: await loadJob(project.rt, path4) };
|
|
11893
11978
|
};
|
|
11894
11979
|
}
|
|
11895
11980
|
});
|
|
@@ -12120,20 +12205,20 @@ var init_image2 = __esm({
|
|
|
12120
12205
|
const batch = batchOf(a);
|
|
12121
12206
|
if (batch) return actOnBatch(rt, project, a, batch);
|
|
12122
12207
|
if (action === "prepare") return prepare2(rt, project, a);
|
|
12123
|
-
const { path:
|
|
12208
|
+
const { path: path4, job } = await resolveJob(project, { action, id: a.string("id"), quoteId: a.string("quote-id") });
|
|
12124
12209
|
if (action === "quote" || action === "run") {
|
|
12125
|
-
const outcome = await quoteOrRun(project, job,
|
|
12210
|
+
const outcome = await quoteOrRun(project, job, path4, action, { config: a.string("config"), quoteId: a.string("quote-id"), idempotencyKey: a.string("idempotency-key"), confirm: a.flag("confirm"), acceptUnknownCost: a.flag("accept-unknown-cost"), ...a.flag("no-wait") ? { noWait: true } : {} });
|
|
12126
12211
|
printJson(rt, outcome.result, true);
|
|
12127
12212
|
return outcome.code;
|
|
12128
12213
|
}
|
|
12129
|
-
if (action === "complete") await completeJob(project, job,
|
|
12214
|
+
if (action === "complete") await completeJob(project, job, path4, { file: a.string("file"), tool: a.string("tool"), note: a.string("note") });
|
|
12130
12215
|
const executor = job.provider.channel === "host" ? "agent-host-tool" : "provider-cli";
|
|
12131
|
-
const picked2 = action === "status" ? await statusPickUp(project, job,
|
|
12216
|
+
const picked2 = action === "status" ? await statusPickUp(project, job, path4, { config: a.string("config"), acceptUnknownCost: a.flag("accept-unknown-cost") }) : null;
|
|
12132
12217
|
if (picked2) {
|
|
12133
|
-
printJson(rt, { ...picked2.result, jobFile:
|
|
12218
|
+
printJson(rt, { ...picked2.result, jobFile: path4, job, executor }, true);
|
|
12134
12219
|
return picked2.code;
|
|
12135
12220
|
}
|
|
12136
|
-
printJson(rt, { ok: true, jobFile:
|
|
12221
|
+
printJson(rt, { ok: true, jobFile: path4, job, executor }, true);
|
|
12137
12222
|
return 0;
|
|
12138
12223
|
};
|
|
12139
12224
|
jobsMain = (argv, rt) => withProviderArgs(argv, spec5(), rt, async (a) => {
|
|
@@ -12191,22 +12276,22 @@ var init_adapter = __esm({
|
|
|
12191
12276
|
};
|
|
12192
12277
|
normalizeRoleRefs = (refs) => {
|
|
12193
12278
|
const out2 = (refs ?? []).map((ref) => {
|
|
12194
|
-
let
|
|
12279
|
+
let path4;
|
|
12195
12280
|
let role;
|
|
12196
|
-
if (Array.isArray(ref) && ref.length === 2) [
|
|
12197
|
-
else if (ref !== null && typeof ref === "object" && !Array.isArray(ref)) ({ path:
|
|
12281
|
+
if (Array.isArray(ref) && ref.length === 2) [path4, role] = ref;
|
|
12282
|
+
else if (ref !== null && typeof ref === "object" && !Array.isArray(ref)) ({ path: path4, role } = ref);
|
|
12198
12283
|
else throw new AdapterInputError(msg("a ref must be {path,role} or [path,role]", "ref \u5FC5\u987B\u662F {path,role} \u6216 [path,role]"));
|
|
12199
|
-
if (typeof
|
|
12284
|
+
if (typeof path4 !== "string" || !path4) throw new AdapterInputError(msg("ref.path must be a non-empty string", "ref.path \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32"));
|
|
12200
12285
|
if (typeof role !== "string" || !REF_ROLES2.includes(role)) {
|
|
12201
12286
|
const got = role === void 0 ? msg("nothing", "\u7A7A\u503C") : JSON.stringify(role);
|
|
12202
12287
|
throw new AdapterInputError(msg(`ref.role must be one of ${REF_ROLES2.join("/")}, got ${got}`, `ref.role \u5FC5\u987B\u662F ${REF_ROLES2.join("/")} \u4E4B\u4E00\uFF0C\u6536\u5230 ${got}`));
|
|
12203
12288
|
}
|
|
12204
|
-
return { path:
|
|
12289
|
+
return { path: path4, role };
|
|
12205
12290
|
});
|
|
12206
12291
|
const identityRefs = out2.filter((r) => r.role === "identity");
|
|
12207
12292
|
return { refs: out2, identityRefs, hasIdentity: identityRefs.length > 0 };
|
|
12208
12293
|
};
|
|
12209
|
-
refsToProviderArgs = (refs) => [...new Set(refs.map((r) => r.path))].flatMap((
|
|
12294
|
+
refsToProviderArgs = (refs) => [...new Set(refs.map((r) => r.path))].flatMap((path4) => ["--ref", path4]);
|
|
12210
12295
|
checkChannels = async (runner) => {
|
|
12211
12296
|
const channels = {
|
|
12212
12297
|
manual: { status: "available", measured: null, note: msg("local files; register the sha256 with inventory when used", "\u672C\u5730\u6587\u4EF6\uFF1B\u7528\u65F6 inventory \u767B\u8BB0 sha256") },
|
|
@@ -12235,16 +12320,16 @@ var init_adapter = __esm({
|
|
|
12235
12320
|
return { ok: true, channels };
|
|
12236
12321
|
};
|
|
12237
12322
|
blocked = (reason2) => ({ ok: false, status: "blocked", error: { code: "NO_TOOL", msg: reason2 } });
|
|
12238
|
-
sha256Of = async (rt,
|
|
12239
|
-
const abs = resolvePath(rt,
|
|
12323
|
+
sha256Of = async (rt, path4) => {
|
|
12324
|
+
const abs = resolvePath(rt, path4);
|
|
12240
12325
|
return (await rt.fs.stat(abs))?.isFile ? createHash14("sha256").update(await rt.fs.readFile(abs)).digest("hex") : null;
|
|
12241
12326
|
};
|
|
12242
12327
|
tail = (text13) => text13 ? text13.trim().slice(-500) : "";
|
|
12243
|
-
registerManual = async (rt,
|
|
12244
|
-
const sha2562 = await sha256Of(rt,
|
|
12245
|
-
if (sha2562 === null) return blocked(msg(`the manual file does not exist: ${
|
|
12246
|
-
const { code, parsed } = await runJson(["inventory", "--file",
|
|
12247
|
-
return { ok: code === 0, channel: "manual", path:
|
|
12328
|
+
registerManual = async (rt, path4, runner = processRunner(rt)) => {
|
|
12329
|
+
const sha2562 = await sha256Of(rt, path4);
|
|
12330
|
+
if (sha2562 === null) return blocked(msg(`the manual file does not exist: ${path4}`, `manual \u6587\u4EF6\u4E0D\u5B58\u5728: ${path4}`));
|
|
12331
|
+
const { code, parsed } = await runJson(["inventory", "--file", path4, "--json"], runner);
|
|
12332
|
+
return { ok: code === 0, channel: "manual", path: path4, sha256: sha2562, delegated: parsed, exit: code };
|
|
12248
12333
|
};
|
|
12249
12334
|
quoteSlot = async (rt, slot, runner = processRunner(rt)) => {
|
|
12250
12335
|
const { aspect = "1:1", count: count5 = 1, provider = OFFICIAL_CHANNEL } = slot;
|
|
@@ -12274,14 +12359,14 @@ var init_adapter = __esm({
|
|
|
12274
12359
|
const { code, parsed, stderr } = await runJson(argv, runner);
|
|
12275
12360
|
return { ok: code === 0, channel: OFFICIAL_CHANNEL, phase: "generate", delegated: parsed, exit: code, stderr: tail(stderr) };
|
|
12276
12361
|
};
|
|
12277
|
-
importHostAsset = async (rt,
|
|
12278
|
-
const sha2562 = await sha256Of(rt,
|
|
12279
|
-
if (sha2562 === null) return blocked(msg(`the host asset file does not exist: ${
|
|
12362
|
+
importHostAsset = async (rt, path4, license = "", attribution = "") => {
|
|
12363
|
+
const sha2562 = await sha256Of(rt, path4);
|
|
12364
|
+
if (sha2562 === null) return blocked(msg(`the host asset file does not exist: ${path4}`, `host \u8D44\u4EA7\u6587\u4EF6\u4E0D\u5B58\u5728: ${path4}`));
|
|
12280
12365
|
const note = msg(
|
|
12281
12366
|
"supplied by the host; this module neither fetches it, nor tests the connection, nor claims it was measured",
|
|
12282
12367
|
"\u5BBF\u4E3B\u4EE3\u4F9B\uFF1B\u672C\u6A21\u5757\u4E0D\u4EE3\u53D6\u3001\u4E0D\u5B9E\u6D4B\u8FDE\u901A\u3001\u4E0D\u5192\u5145 measured"
|
|
12283
12368
|
);
|
|
12284
|
-
return { ok: true, channel: "host", status: "declared", measured: false, path:
|
|
12369
|
+
return { ok: true, channel: "host", status: "declared", measured: false, path: path4, sha256: sha2562, license, attribution, note };
|
|
12285
12370
|
};
|
|
12286
12371
|
refsFromCli = (items) => items.map((item2) => {
|
|
12287
12372
|
const cut3 = item2.lastIndexOf(":");
|
|
@@ -12422,14 +12507,14 @@ var init_inspiration_plan = __esm({
|
|
|
12422
12507
|
return null;
|
|
12423
12508
|
}
|
|
12424
12509
|
};
|
|
12425
|
-
localImage = async (rt, rid,
|
|
12426
|
-
const full = rt.path.isAbsolute(
|
|
12510
|
+
localImage = async (rt, rid, path4, baseDir, entry2) => {
|
|
12511
|
+
const full = rt.path.isAbsolute(path4) ? path4 : rt.path.join(baseDir, path4);
|
|
12427
12512
|
const stat2 = await rt.fs.stat(full);
|
|
12428
|
-
if (!stat2?.isFile) throw new InputError(msg(`resource ${String(rid)}: the local picture does not exist: ${
|
|
12513
|
+
if (!stat2?.isFile) throw new InputError(msg(`resource ${String(rid)}: the local picture does not exist: ${path4}`, `resource ${String(rid)} \u672C\u5730\u56FE\u7247\u4E0D\u5B58\u5728\uFF1A${path4}`));
|
|
12429
12514
|
if (stat2.size > MAX_UPLOAD_BYTES) throw new InputError(msg(`resource ${String(rid)} is larger than the 30 MiB upload limit`, `resource ${String(rid)} \u8D85\u8FC7 30 MiB \u4E0A\u4F20\u4E0A\u9650`));
|
|
12430
12515
|
const raw = await rt.fs.readFile(full);
|
|
12431
12516
|
const mime = sniffImageMime(raw.subarray(0, 16));
|
|
12432
|
-
if (!mime) throw new InputError(msg(`resource ${String(rid)} is not a PNG/JPEG/WebP/GIF picture: ${
|
|
12517
|
+
if (!mime) throw new InputError(msg(`resource ${String(rid)} is not a PNG/JPEG/WebP/GIF picture: ${path4}`, `resource ${String(rid)} \u4E0D\u662F PNG/JPEG/WebP/GIF \u56FE\u7247\uFF1A${path4}`));
|
|
12433
12518
|
const stem = rt.path.basename(full).replace(/\.[^.]*$/, "");
|
|
12434
12519
|
Object.assign(entry2, { kind: "local", path: rt.path.resolve(full), bytes: stat2.size, mimeType: mime, sha256: createHash15("sha256").update(raw).digest("hex"), fileName: stem + EXTENSIONS[mime] });
|
|
12435
12520
|
return Object.assign(entry2, imageSize(raw) ?? {});
|
|
@@ -12619,12 +12704,12 @@ var init_inspiration = __esm({
|
|
|
12619
12704
|
code;
|
|
12620
12705
|
};
|
|
12621
12706
|
readBundle = async (rt, file) => {
|
|
12622
|
-
const
|
|
12623
|
-
const stat2 = await rt.fs.stat(
|
|
12707
|
+
const path4 = resolvePath(rt, file);
|
|
12708
|
+
const stat2 = await rt.fs.stat(path4);
|
|
12624
12709
|
if (!stat2) throw new FileProblem("FILE_NOT_FOUND", fileErrorText("ENOENT", file));
|
|
12625
12710
|
if (stat2.isDirectory) throw new FileProblem("NOT_A_FILE", fileErrorText("EISDIR", file));
|
|
12626
12711
|
try {
|
|
12627
|
-
return JSON.parse(await rt.fs.readText(
|
|
12712
|
+
return JSON.parse(await rt.fs.readText(path4));
|
|
12628
12713
|
} catch (error2) {
|
|
12629
12714
|
const detail2 = error2.message;
|
|
12630
12715
|
throw new FileProblem("BAD_JSON", msg(`the PostBundle is not valid JSON: ${detail2}`, `PostBundle \u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${detail2}`));
|
|
@@ -12695,7 +12780,7 @@ var init_link_bundle = __esm({
|
|
|
12695
12780
|
};
|
|
12696
12781
|
planPost = (post, fallbackUrl, note) => {
|
|
12697
12782
|
if (!PLATFORMS.includes(post.platform))
|
|
12698
|
-
throw badResponse(msg(
|
|
12783
|
+
throw badResponse(msg(`the platform of the parsed result is not one of ${platformNameList("or")}`, `\u89E3\u6790\u7ED3\u679C\u7684 platform \u4E0D\u662F${platformNameList("or")}\u4E4B\u4E00`));
|
|
12699
12784
|
const sourceUrl = [text3(post.sourceUrl), fallbackUrl ?? ""].find((u) => /^https?:\/\//.test(u));
|
|
12700
12785
|
if (!sourceUrl) throw badResponse(msg("the parsed result has no sourceUrl", "\u89E3\u6790\u7ED3\u679C\u7F3A\u5C11 sourceUrl"));
|
|
12701
12786
|
const serverNote = text3(post.note) || (note ?? "").trim();
|
|
@@ -12757,9 +12842,9 @@ var init_link_bundle = __esm({
|
|
|
12757
12842
|
return { saved, failure: msg(`the download of ${what} is not a PNG/JPEG/WebP/GIF picture; ${retry}`, `${what}\u4E0B\u8F7D\u7684\u5185\u5BB9\u4E0D\u662F PNG/JPEG/WebP/GIF \u56FE\u7247\uFF1B${retry}`) };
|
|
12758
12843
|
}
|
|
12759
12844
|
const file = fileName(index, mime);
|
|
12760
|
-
const
|
|
12761
|
-
await rt.fs.rename(tmp,
|
|
12762
|
-
saved.push({ index, file, path:
|
|
12845
|
+
const path4 = rt.path.join(outDir2, file);
|
|
12846
|
+
await rt.fs.rename(tmp, path4);
|
|
12847
|
+
saved.push({ index, file, path: path4, mimeType: mime, sha256: sha256(raw), bytes: raw.length, ...sizeOf(raw), ...image2.alt ? { alt: image2.alt } : {} });
|
|
12763
12848
|
} catch (error2) {
|
|
12764
12849
|
await rt.fs.rm(tmp).catch(() => void 0);
|
|
12765
12850
|
const message2 = reason(error2);
|
|
@@ -13207,6 +13292,7 @@ var init_inspiration2 = __esm({
|
|
|
13207
13292
|
"src/commands/inspiration.ts"() {
|
|
13208
13293
|
"use strict";
|
|
13209
13294
|
init_i18n();
|
|
13295
|
+
init_post_bundle();
|
|
13210
13296
|
init_cli_args();
|
|
13211
13297
|
init_task();
|
|
13212
13298
|
init_inspiration();
|
|
@@ -13226,8 +13312,8 @@ var init_inspiration2 = __esm({
|
|
|
13226
13312
|
add: {
|
|
13227
13313
|
spec: {
|
|
13228
13314
|
description: msg(
|
|
13229
|
-
|
|
13230
|
-
"\
|
|
13315
|
+
`Save a post URL from ${platformNameList("or")} to the current account's My Inspirations. Check inspiration quote first, then submit with an authorized credit ceiling. Reused links do not charge again.`,
|
|
13316
|
+
`\u628A${platformNameList("or")}\u7684\u5E16\u5B50\u94FE\u63A5\u5B58\u5165\u5F53\u524D\u8D26\u53F7\u7684\u300C\u6211\u7684\u7075\u611F\u300D\u3002\u5148\u7528 inspiration quote \u67E5\u8BE2\u4EF7\u683C\uFF0C\u518D\u5E26\u7528\u6237\u6388\u6743\u7684\u79EF\u5206\u4E0A\u9650\u63D0\u4EA4\u3002\u5DF2\u4FDD\u5B58\u8FC7\u7684\u94FE\u63A5\u4E0D\u4F1A\u518D\u6B21\u6263\u8D39\u3002`
|
|
13231
13317
|
),
|
|
13232
13318
|
positionals: [{ name: "url", help: msg("Public post URL (http/https)", "\u516C\u5F00\u5E16\u5B50\u94FE\u63A5\uFF08http/https\uFF09") }],
|
|
13233
13319
|
options: [
|
|
@@ -13553,6 +13639,7 @@ var init_link2 = __esm({
|
|
|
13553
13639
|
"use strict";
|
|
13554
13640
|
init_pricing2();
|
|
13555
13641
|
init_i18n();
|
|
13642
|
+
init_post_bundle();
|
|
13556
13643
|
init_link();
|
|
13557
13644
|
init_cli_args();
|
|
13558
13645
|
init_task();
|
|
@@ -13594,8 +13681,8 @@ var init_link2 = __esm({
|
|
|
13594
13681
|
parse: {
|
|
13595
13682
|
spec: {
|
|
13596
13683
|
description: msg(
|
|
13597
|
-
|
|
13598
|
-
|
|
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`
|
|
13599
13686
|
),
|
|
13600
13687
|
positionals: [{ name: "url", help: msg("the post link (http/https)", "\u5E16\u5B50\u94FE\u63A5\uFF08http/https\uFF09") }],
|
|
13601
13688
|
options: [
|
|
@@ -13967,9 +14054,9 @@ var init_import_deck = __esm({
|
|
|
13967
14054
|
for (const name of [`${id2}.png`, `${id2}.render.json`]) await project.rt.fs.rm(project.rt.path.join(project.exportsDir, name));
|
|
13968
14055
|
};
|
|
13969
14056
|
restore2 = async (project, backups) => {
|
|
13970
|
-
for (const [
|
|
13971
|
-
if (text13 === null) await project.rt.fs.rm(
|
|
13972
|
-
else await project.rt.fs.writeFile(
|
|
14057
|
+
for (const [path4, text13] of backups) {
|
|
14058
|
+
if (text13 === null) await project.rt.fs.rm(path4);
|
|
14059
|
+
else await project.rt.fs.writeFile(path4, text13);
|
|
13973
14060
|
}
|
|
13974
14061
|
};
|
|
13975
14062
|
writeProject = async (project, pages, diff, entries3, reshaped) => {
|
|
@@ -13979,10 +14066,10 @@ var init_import_deck = __esm({
|
|
|
13979
14066
|
const touched = /* @__PURE__ */ new Set([...diff.changed, ...diff.added]);
|
|
13980
14067
|
try {
|
|
13981
14068
|
for (const page2 of pages.filter((p) => touched.has(p.id))) {
|
|
13982
|
-
const
|
|
13983
|
-
const before = await rt.fs.stat(
|
|
13984
|
-
backups.set(
|
|
13985
|
-
await writeAtomic(rt,
|
|
14069
|
+
const path4 = project.abs(entries3.find((entry2) => entry2.id === page2.id).htmlPath);
|
|
14070
|
+
const before = await rt.fs.stat(path4);
|
|
14071
|
+
backups.set(path4, before?.isFile ? await rt.fs.readText(path4) : null);
|
|
14072
|
+
await writeAtomic(rt, path4, pageFile(page2));
|
|
13986
14073
|
}
|
|
13987
14074
|
project.manifest.pages = entries3;
|
|
13988
14075
|
for (const id2 of [...diff.changed, ...diff.removed]) delete project.manifest.reviews[id2];
|
|
@@ -15720,7 +15807,7 @@ var init_contract = __esm({
|
|
|
15720
15807
|
scope: z.strictObject({ span: frameSpan, reason: text4, evidence: z.array(evidenceSchema).min(1) }).optional(),
|
|
15721
15808
|
review: reviewSchema.optional()
|
|
15722
15809
|
}).superRefine((v, ctx) => {
|
|
15723
|
-
const issue4 = (
|
|
15810
|
+
const issue4 = (path4, message2) => ctx.addIssue({ code: "custom", path: path4, message: message2 });
|
|
15724
15811
|
const ids3 = /* @__PURE__ */ new Set();
|
|
15725
15812
|
const span2 = v.scope?.span ?? [0, v.source.frames];
|
|
15726
15813
|
if (span2[1] > v.source.frames) issue4(["scope", "span"], "The retained interval extends beyond the reference.");
|
|
@@ -16208,7 +16295,7 @@ var init_footage2 = __esm({
|
|
|
16208
16295
|
if (observed.spans) speechObserved = true;
|
|
16209
16296
|
}
|
|
16210
16297
|
const mode = await readModeReceipt(rt, file);
|
|
16211
|
-
return { facts: { width: p.width, height: p.height, fps: p.fps, frames: p.frames, hasAudio: p.hasAudio, ...speech2 ? { speech: speech2 } : {}, ...speechObserved ? { speechObserved } : {}, ...mode ? { sound: mode.sound } : {}, ...mode?.clipMusic ? { clipMusic: mode.clipMusic } : {} }, colour: colourOf(header2.stderr, p.width, p.height) };
|
|
16298
|
+
return { native: /Video: (?:h264|vp8|vp9|av1)\b/.test(header2.stderr) && /\byuv420p(?:[,( ]|$)/.test(header2.stderr), facts: { width: p.width, height: p.height, fps: p.fps, frames: p.frames, hasAudio: p.hasAudio, ...speech2 ? { speech: speech2 } : {}, ...speechObserved ? { speechObserved } : {}, ...mode ? { sound: mode.sound } : {}, ...mode?.clipMusic ? { clipMusic: mode.clipMusic } : {} }, colour: colourOf(header2.stderr, p.width, p.height) };
|
|
16212
16299
|
};
|
|
16213
16300
|
speechSpans = async (rt, file, seconds7) => {
|
|
16214
16301
|
const receipt = await rt.fs.readText(file + ".speech.json").then((t) => JSON.parse(t), () => void 0);
|
|
@@ -16227,14 +16314,14 @@ var init_footage2 = __esm({
|
|
|
16227
16314
|
].join(",");
|
|
16228
16315
|
frameName = (frame2) => framePath("", frame2).slice(1);
|
|
16229
16316
|
extractFrames = async (rt, job) => {
|
|
16230
|
-
const { fs, path:
|
|
16317
|
+
const { fs, path: path4 } = rt;
|
|
16231
16318
|
await fs.mkdir(job.dir);
|
|
16232
16319
|
const have = new Set(await fs.readdir(job.dir));
|
|
16233
16320
|
const missing3 = job.frames.filter((f) => !have.has(frameName(f)));
|
|
16234
16321
|
if (missing3.length === 0) return { extracted: 0, reused: job.frames.length };
|
|
16235
16322
|
const lo = missing3[0] ?? 0;
|
|
16236
16323
|
const hi = missing3[missing3.length - 1] ?? 0;
|
|
16237
|
-
const tmp =
|
|
16324
|
+
const tmp = path4.join(job.dir, ".extract-" + rt.randomUUID());
|
|
16238
16325
|
await fs.mkdir(tmp);
|
|
16239
16326
|
try {
|
|
16240
16327
|
await runFfmpegOk(rt, [
|
|
@@ -16257,13 +16344,13 @@ var init_footage2 = __esm({
|
|
|
16257
16344
|
"1",
|
|
16258
16345
|
"-start_number",
|
|
16259
16346
|
"0",
|
|
16260
|
-
|
|
16347
|
+
path4.join(tmp, "%0" + FRAME_DIGITS + "d.png")
|
|
16261
16348
|
]);
|
|
16262
16349
|
const written2 = new Set(await fs.readdir(tmp));
|
|
16263
16350
|
const absent = missing3.filter((f) => !written2.has(frameName(f - lo)));
|
|
16264
16351
|
if (absent.length > 0)
|
|
16265
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.");
|
|
16266
|
-
for (const f of missing3) await fs.rename(
|
|
16353
|
+
for (const f of missing3) await fs.rename(path4.join(tmp, frameName(f - lo)), path4.join(job.dir, frameName(f)));
|
|
16267
16354
|
return { extracted: missing3.length, reused: job.frames.length - missing3.length };
|
|
16268
16355
|
} finally {
|
|
16269
16356
|
await fs.rm(tmp);
|
|
@@ -17887,8 +17974,8 @@ var init_switch = __esm({
|
|
|
17887
17974
|
const sx = moved.reduce((s, x) => s + x.dx, 0), sy = moved.reduce((s, x) => s + x.dy, 0);
|
|
17888
17975
|
const ax = moved.reduce((s, x) => s + Math.abs(x.dx), 0), ay = moved.reduce((s, x) => s + Math.abs(x.dy), 0);
|
|
17889
17976
|
const horizontal = ax >= ay;
|
|
17890
|
-
const net = horizontal ? sx : sy,
|
|
17891
|
-
if (moved.length < 2 || Math.abs(net) < 0.9 *
|
|
17977
|
+
const net = horizontal ? sx : sy, path4 = horizontal ? ax : ay;
|
|
17978
|
+
if (moved.length < 2 || Math.abs(net) < 0.9 * path4 || path4 < 0.04) return void 0;
|
|
17892
17979
|
const way = side < 0 ? Math.sign(net) : -Math.sign(net);
|
|
17893
17980
|
return horizontal ? way > 0 ? "right" : "left" : way > 0 ? "down" : "up";
|
|
17894
17981
|
};
|
|
@@ -18038,19 +18125,19 @@ var init_kinds = __esm({
|
|
|
18038
18125
|
return { w, h, data: resample(t.rgb[m], t.width, t.height, 3, w, h) };
|
|
18039
18126
|
};
|
|
18040
18127
|
travel = (t, start, end) => {
|
|
18041
|
-
let
|
|
18128
|
+
let path4 = 0, nx = 0, ny = 0, pathX = 0, pathY = 0;
|
|
18042
18129
|
for (let m = start; m < end; m++) {
|
|
18043
18130
|
const a = align(t.gray[m], t.gray[m + 1], t.width, t.height, { search: true });
|
|
18044
18131
|
if (a.coverage < 0.4 || a.texture < 1.5 || !(a.residual < 0.6 * a.before) || Math.abs(Math.log(a.scale)) > 0.05) continue;
|
|
18045
18132
|
const dx = a.tx / t.width, dy = a.ty / t.height;
|
|
18046
|
-
|
|
18133
|
+
path4 += Math.hypot(dx, dy);
|
|
18047
18134
|
pathX += Math.abs(dx);
|
|
18048
18135
|
pathY += Math.abs(dy);
|
|
18049
18136
|
nx += dx;
|
|
18050
18137
|
ny += dy;
|
|
18051
18138
|
}
|
|
18052
18139
|
const heading = Math.abs(nx) >= Math.abs(ny) ? nx < 0 ? "left" : "right" : ny < 0 ? "up" : "down";
|
|
18053
|
-
return { path:
|
|
18140
|
+
return { path: path4, net: Math.hypot(nx, ny), heading, pathX, pathY };
|
|
18054
18141
|
};
|
|
18055
18142
|
coverScale2 = (deg3, w, h) => {
|
|
18056
18143
|
const r = deg3 * Math.PI / 180, c = Math.abs(Math.cos(r)), s = Math.abs(Math.sin(r));
|
|
@@ -18657,11 +18744,11 @@ var init_camera2 = __esm({
|
|
|
18657
18744
|
const zoomPerS = z1 >= 0 ? z1 : z1 / S;
|
|
18658
18745
|
const panPerS = [slope(ts, xs), slope(ts, ys)];
|
|
18659
18746
|
const rates = good.map((s) => [s.tx / s.dt, s.ty / s.dt]);
|
|
18660
|
-
const
|
|
18747
|
+
const path4 = good.reduce((a, s) => a + Math.hypot(s.tx, s.ty), 0), net = Math.hypot(tx, ty);
|
|
18661
18748
|
const flips = rates.slice(1).filter((r, i) => r[0] * rates[i][0] < 0 || r[1] * rates[i][1] < 0).length;
|
|
18662
18749
|
const moving = Math.abs(zoomPerS) >= STILL_ZOOM || Math.hypot(...panPerS) >= STILL_PAN;
|
|
18663
18750
|
const confidence = round2(Math.min(1, good.length / st.length) * (good.length >= 3 ? 0.9 : 0.6), 3);
|
|
18664
|
-
if (
|
|
18751
|
+
if (path4 > 0.03 && path4 > 3 * net && flips >= 0.4 * rates.length) return { kind: "unsteady", zoomPerS: round2(zoomPerS, 4), panPerS: [round2(panPerS[0], 4), round2(panPerS[1], 4)], confidence };
|
|
18665
18752
|
if (!moving) return { kind: "static", zoomPerS: 0, panPerS: [0, 0], confidence };
|
|
18666
18753
|
return { kind: "move", zoomPerS: round2(zoomPerS, 4), panPerS: [round2(panPerS[0], 4), round2(panPerS[1], 4)], confidence };
|
|
18667
18754
|
};
|
|
@@ -19659,8 +19746,8 @@ var init_tracks = __esm({
|
|
|
19659
19746
|
if (all.length < 3) return void 0;
|
|
19660
19747
|
const clear2 = all.filter((x) => x.centre[0] - x.size[0] / 2 > 0.5 / w && x.centre[1] - x.size[1] / 2 > 0.5 / h && x.centre[0] + x.size[0] / 2 < 1 - 0.5 / w && x.centre[1] + x.size[1] / 2 < 1 - 0.5 / h);
|
|
19661
19748
|
const areas = clear2.map((x) => x.size[0] * x.size[1]);
|
|
19662
|
-
const
|
|
19663
|
-
if (areas.length < 2 ||
|
|
19749
|
+
const path4 = pathOf2(all, w, h, t.fps);
|
|
19750
|
+
if (areas.length < 2 || path4.length < TRAVELS || Math.min(...areas) < SAME_SIZE * Math.max(...areas)) return void 0;
|
|
19664
19751
|
const samples = thin(all, MOST_SAMPLES);
|
|
19665
19752
|
return {
|
|
19666
19753
|
id: "shot-" + two(s.index + 1) + "-event-" + (k + 1),
|
|
@@ -19672,7 +19759,7 @@ var init_tracks = __esm({
|
|
|
19672
19759
|
start: samples[0].frame,
|
|
19673
19760
|
end: samples[samples.length - 1].frame,
|
|
19674
19761
|
samples,
|
|
19675
|
-
path:
|
|
19762
|
+
path: path4,
|
|
19676
19763
|
size: medianSize(samples),
|
|
19677
19764
|
confidence: e.confidence
|
|
19678
19765
|
};
|
|
@@ -20766,8 +20853,8 @@ var init_hosted_api = __esm({
|
|
|
20766
20853
|
init_submit_retry();
|
|
20767
20854
|
LONG_SECONDS = 120;
|
|
20768
20855
|
platform = (rt, timeoutSec = 180) => new PopostClient(rt, { timeoutSec });
|
|
20769
|
-
paidPost = (rt,
|
|
20770
|
-
const data = await platform(rt, LONG_SECONDS).request("POST",
|
|
20856
|
+
paidPost = (rt, path4, body, hint, read2) => sendIdempotent(rt, async () => {
|
|
20857
|
+
const data = await platform(rt, LONG_SECONDS).request("POST", path4, { body, ambiguous: true, hint });
|
|
20771
20858
|
try {
|
|
20772
20859
|
return read2(data);
|
|
20773
20860
|
} catch {
|
|
@@ -21873,7 +21960,7 @@ var init_issues = __esm({
|
|
|
21873
21960
|
"use strict";
|
|
21874
21961
|
init_suggest();
|
|
21875
21962
|
isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
21876
|
-
pathText = (
|
|
21963
|
+
pathText = (path4) => path4.reduce((s, k) => typeof k === "number" ? s + "[" + k + "]" : s ? s + "." + String(k) : String(k), "") || "(root)";
|
|
21877
21964
|
show = (v) => {
|
|
21878
21965
|
if (v === void 0) return "nothing";
|
|
21879
21966
|
const text13 = JSON.stringify(v) ?? String(v);
|
|
@@ -21940,72 +22027,72 @@ var init_issues = __esm({
|
|
|
21940
22027
|
focus: "exactly 2 numbers [x, y], fractions of the frame",
|
|
21941
22028
|
shift: "exactly 2 pairs [[x, y] at from, [x, y] at to], fractions of the canvas"
|
|
21942
22029
|
};
|
|
21943
|
-
lastKey = (
|
|
21944
|
-
const k = [...
|
|
22030
|
+
lastKey = (path4) => {
|
|
22031
|
+
const k = [...path4].reverse().find((p) => typeof p === "string");
|
|
21945
22032
|
return typeof k === "string" ? k : "";
|
|
21946
22033
|
};
|
|
21947
|
-
example = (
|
|
21948
|
-
problem = (
|
|
22034
|
+
example = (path4, expected2 = "") => EXAMPLES[lastKey(path4)] ?? TYPE_EXAMPLES[expected2] ?? '"..."';
|
|
22035
|
+
problem = (path4, message2, fix2, allowed) => ({
|
|
21949
22036
|
level: "error",
|
|
21950
|
-
at: pathText(
|
|
22037
|
+
at: pathText(path4),
|
|
21951
22038
|
message: message2,
|
|
21952
22039
|
fix: fix2,
|
|
21953
22040
|
...allowed ? { allowed } : {}
|
|
21954
22041
|
});
|
|
21955
|
-
typeProblem = (i,
|
|
22042
|
+
typeProblem = (i, path4) => {
|
|
21956
22043
|
const what = i.expected === "int" ? "a whole number" : i.expected === "array" || i.expected === "object" ? "an " + i.expected : "a " + i.expected;
|
|
21957
|
-
if (i.input === void 0) return problem(
|
|
21958
|
-
return problem(
|
|
22044
|
+
if (i.input === void 0) return problem(path4, pathText(path4) + " is missing; it must be " + what + ".", 'Add "' + lastKey(path4) + '": ' + example(path4, i.expected) + ".");
|
|
22045
|
+
return problem(path4, pathText(path4) + " must be " + what + ", not " + show(i.input) + ".", "Write " + example(path4, i.expected) + " here.");
|
|
21959
22046
|
};
|
|
21960
|
-
rangeProblem = (i,
|
|
22047
|
+
rangeProblem = (i, path4) => {
|
|
21961
22048
|
const small = i.code === "too_small";
|
|
21962
22049
|
const limit = small ? i.minimum : i.maximum;
|
|
21963
|
-
const key2 = lastKey(
|
|
21964
|
-
if (i.origin === "array" && TUPLES[key2]) return problem(
|
|
21965
|
-
if (i.origin === "array") return problem(
|
|
21966
|
-
if (i.origin === "string") return problem(
|
|
22050
|
+
const key2 = lastKey(path4);
|
|
22051
|
+
if (i.origin === "array" && TUPLES[key2]) return problem(path4, pathText(path4) + " needs " + TUPLES[key2] + ".", "Write " + example(path4) + ".");
|
|
22052
|
+
if (i.origin === "array") return problem(path4, pathText(path4) + " needs " + (small ? "at least " : "at most ") + limit + " item(s).", small ? "Add one, for example " + example(path4) + "." : "Remove the extra items.");
|
|
22053
|
+
if (i.origin === "string") return problem(path4, pathText(path4) + (small ? " must not be empty." : " is longer than " + limit + " characters."), small ? "Write a value, for example " + example(path4, "string") + "." : "Shorten it.");
|
|
21967
22054
|
const bound = small ? i.inclusive ? "at least " : "greater than " : i.inclusive ? "at most " : "less than ";
|
|
21968
|
-
return problem(
|
|
22055
|
+
return problem(path4, pathText(path4) + " is " + show(i.input) + "; it must be " + bound + limit + ".", "Use a value " + bound + limit + ".");
|
|
21969
22056
|
};
|
|
21970
|
-
valueProblem = (i,
|
|
22057
|
+
valueProblem = (i, path4) => {
|
|
21971
22058
|
const allowed = i.values.map((v) => String(v));
|
|
21972
22059
|
const near3 = typeof i.input === "string" ? closest(i.input, allowed) : void 0;
|
|
21973
|
-
return problem(
|
|
22060
|
+
return problem(path4, pathText(path4) + " is " + show(i.input) + ", which is not allowed here.", near3 ? 'Use "' + near3 + '".' : "Use one of the allowed values, for example " + JSON.stringify(i.values[0]) + ".", allowed);
|
|
21974
22061
|
};
|
|
21975
|
-
unionProblems = (i,
|
|
22062
|
+
unionProblems = (i, path4) => {
|
|
21976
22063
|
const rich = i;
|
|
21977
22064
|
if (rich.note === "No matching discriminator") {
|
|
21978
22065
|
const allowed = (rich.options ?? []).map((v) => String(v));
|
|
21979
22066
|
const key2 = rich.discriminator ?? "type";
|
|
21980
22067
|
const value = isObj2(i.input) ? i.input[key2] : i.input;
|
|
21981
22068
|
const near3 = typeof value === "string" ? closest(value, allowed) : void 0;
|
|
21982
|
-
return [problem(
|
|
22069
|
+
return [problem(path4, pathText(path4) + " is " + show(value) + ", which is not a known " + key2 + ".", near3 ? 'Use "' + near3 + '".' : 'Use one of the allowed values, for example "' + (allowed[0] ?? "") + '".', allowed)];
|
|
21983
22070
|
}
|
|
21984
22071
|
const rank = (branch) => Math.max(0, ...branch.filter((b) => b.path.length === 0).map((b) => b.code === "invalid_type" ? 2 : 1));
|
|
21985
22072
|
const ranked = i.errors.map((branch) => ({ branch, r: rank(branch) })).sort((a, b) => a.r - b.r || a.branch.length - b.branch.length);
|
|
21986
22073
|
const best = ranked[0];
|
|
21987
|
-
if (!best || best.r === 2) return [problem(
|
|
21988
|
-
return best.branch.flatMap((b) => issueProblem(b, [...
|
|
22074
|
+
if (!best || best.r === 2) return [problem(path4, pathText(path4) + " is " + show(i.input) + ", which has the wrong type here.", "Write " + example(path4) + " here.")];
|
|
22075
|
+
return best.branch.flatMap((b) => issueProblem(b, [...path4, ...b.path]));
|
|
21989
22076
|
};
|
|
21990
|
-
issueProblem = (i,
|
|
22077
|
+
issueProblem = (i, path4) => {
|
|
21991
22078
|
switch (i.code) {
|
|
21992
22079
|
case "invalid_type":
|
|
21993
|
-
return [typeProblem(i,
|
|
22080
|
+
return [typeProblem(i, path4)];
|
|
21994
22081
|
case "too_small":
|
|
21995
22082
|
case "too_big":
|
|
21996
|
-
return [rangeProblem(i,
|
|
22083
|
+
return [rangeProblem(i, path4)];
|
|
21997
22084
|
case "invalid_value":
|
|
21998
|
-
return [valueProblem(i,
|
|
22085
|
+
return [valueProblem(i, path4)];
|
|
21999
22086
|
case "invalid_union":
|
|
22000
|
-
return unionProblems(i,
|
|
22087
|
+
return unionProblems(i, path4);
|
|
22001
22088
|
case "invalid_format":
|
|
22002
|
-
return [problem(
|
|
22089
|
+
return [problem(path4, pathText(path4) + " " + i.message + " (it is " + show(i.input) + ").", 'Use letters, digits, "-" and "_" only, for example ' + example(path4) + ".")];
|
|
22003
22090
|
case "custom": {
|
|
22004
22091
|
const params2 = i.params ?? {};
|
|
22005
|
-
return [problem(
|
|
22092
|
+
return [problem(path4, pathText(path4) + " " + i.message + " (it is " + show(i.input) + ").", params2.fix ?? "Correct the value.", params2.allowed)];
|
|
22006
22093
|
}
|
|
22007
22094
|
default:
|
|
22008
|
-
return [problem(
|
|
22095
|
+
return [problem(path4, pathText(path4) + ": " + i.message + " (it is " + show(i.input) + ").", "Correct the value, for example " + example(path4) + ".")];
|
|
22009
22096
|
}
|
|
22010
22097
|
};
|
|
22011
22098
|
issueProblems = (issues) => issues.flatMap((i) => issueProblem(i, i.path));
|
|
@@ -22684,7 +22771,7 @@ var init_page_bundle = __esm({
|
|
|
22684
22771
|
"src/video/compile/page-bundle.ts"() {
|
|
22685
22772
|
"use strict";
|
|
22686
22773
|
PAGE_BUNDLE = `"use strict";(()=>{var de=(e,t)=>t<e.start?"before":t<e.end?"spoken":"past",$={padding:.1,radius:.2},D={scale:1,background:!1},me=(e,t)=>!e||t==="before"?D:t==="past"?e.past?{...D,...e.past.color?{color:e.past.color}:{},...e.past.opacity!==void 0?{opacity:e.past.opacity}:{}}:D:{scale:e.scale??1,background:e.background!==void 0,...e.color?{color:e.color}:{},...e.weight?{weight:e.weight}:{}},lt=(e,t,n)=>{let o=0;for(;o<e.length&&(e[o]?.start??1/0)<=n;)o++;return o===0?0:e[o]?.from??t},ue=(e,t,n,o)=>{let s=Math.round(t.chars*n);return e.reveal==="words"&&e.words?Math.min(s,lt(e.words,n,o)):s};var g=e=>e>0?e<1?e:1:0,C=(e,t,n)=>e+(t-e)*n,v=(e,t)=>{let n=g(t);switch(e){case"linear":return n;case"in":return n*n*n;case"out":return 1-(1-n)**3;case"in-out":return n<.5?4*n*n*n:1-(-2*n+2)**3/2}},M=e=>{let t=(Math.imul(e|0,2654435761)^1540483477)>>>0;return t=Math.imul(t^t>>>15,2246822507)>>>0,t=Math.imul(t^t>>>13,3266489909)>>>0,((t^t>>>16)>>>0)/4294967296};var Z={opacity:1,translate:[0,0],scale:1,rotate:0,blur:0,clip:[0,0,0,0],chars:1};var B={left:[-1,0],right:[1,0],up:[0,-1],down:[0,1]},Q={up:0,right:1,down:2,left:3},dt={left:"right",right:"left",up:"down",down:"up"},mt=.6,O=.6,ut=.25,pt=.04,ft=(e,t)=>e<O?C(mt,1+t,v("out",e/O)):C(1+t,1,v("in-out",(e-O)/(1-O))),pe=(e,t,n)=>{switch(e.preset){case"none":return{};case"fade":return{opacity:n};case"pop":return{scale:ft(n,e.overshoot),opacity:g(n/ut)};case"scale-in":return{scale:n};case"slide":{let[o,s]=B[t];return{translate:[-o*e.distance*(1-n),-s*e.distance*(1-n)],opacity:g(n*2)}}case"wipe":{let o=[0,0,0,0];return o[Q[t]]=1-n,{clip:o}}case"type":return{chars:n};case"blur":return{blur:pt*(1-n),opacity:n}}},ee=(e,t,n)=>{let o=e.preset==="type"?g(n):v(e.ease,n),s=t==="enter"?pe(e,e.direction,o):pe(e,dt[e.direction],1-o);return{...Z,...s}};var oe={opacity:1,translate:[0,0],scale:1,rotate:0,blur:0,smear:[0,0],clip:[0,0,0,0],z:0},p=(e={})=>({...oe,...e}),S=()=>p({opacity:0}),W={black:"#000000",white:"#ffffff"},he=1.5,be=.06,ge=.5,ye=.25,xe=.08,ve=.05,te=.08,ht=.15,Se=90,T=e=>e.strength??1,z=e=>1-Math.abs(2*e-1),ne=e=>e<.5?e/.5:(e-.5)/.5,se=e=>B[e in B?e:"left"],we=(e,t)=>{let n=e*Math.PI/180,o=Math.abs(Math.cos(n)),s=Math.abs(Math.sin(n));return Math.max((t.width*o+t.height*s)/t.width,(t.width*s+t.height*o)/t.height)},Te=(e,t)=>Math.min(t-1,Math.max(0,Math.round(e*(t+1))-1)),fe=(e,t,n)=>({old:n<.5?p():S(),next:p({opacity:n<.5?0:1,z:1}),overlay:{color:e,opacity:t}}),bt=(e,t)=>{if(e.direction==="center-out")return{old:p(),next:p({clip:{radius:t},z:1})};if(e.direction==="edges-in")return{old:p({clip:{radius:1-t},z:1}),next:p()};let n=[0,0,0,0];return n[Q[e.direction]]=1-t,{old:p(),next:p({clip:n,z:1})}},gt=(e,t)=>{let[n,o]=se(e.direction),s=[n*t,o*t],r=[n*(t-1),o*(t-1)];return e.mode==="cover"?{old:p(),next:p({translate:r,z:1})}:e.mode==="reveal"?{old:p({translate:s,z:1}),next:p()}:{old:p({translate:s}),next:p({translate:r,z:1})}},yt=(e,t,n,o)=>{let s=v("in-out",ne(t)),r=Se*T(e),a=t<.5?r*s:-r*(1-s),i=p({rotate:a,scale:we(a,o),z:1});return t<.5?{old:i,next:S()}:{old:S(),next:i}},xt=(e,t,n)=>{let o=Te(n,e.frames),s=(o+.5)/e.frames>.3+.4*M(o),r=(M(o+101)-.5)*2*xe*T(e)*z(g(n)),a=p({translate:[r,0],scale:1+2*Math.abs(r),z:1});return s?{old:S(),next:a}:{old:a,next:S()}},vt=(e,t,n)=>{let o=Te(n,e.frames),s=ve*T(e)*(t<.5?t/.5:((1-t)/.5)**2),r=o%2===0?1:-1,a=s*r*(.6+.4*M(o)),i=s*(M(o+7)-.5),c=p({translate:[a,i],scale:1+2*s,z:1});return t<.5?{old:c,next:S()}:{old:S(),next:c}},St=(e,t)=>{let[n,o]=se(e.direction),s=te*T(e)*z(t),r=[Math.abs(n)*s,Math.abs(o)*s];return{old:p({translate:[n*t,o*t],smear:r}),next:p({translate:[n*(t-1),o*(t-1)],smear:r,z:1})}},wt={fade:(e,t)=>fe(W[e.via],g(T(e)*z(t)),t),flash:(e,t)=>fe(W.white,g(he*T(e)*z(t)),t),dissolve:(e,t)=>({old:p(),next:p({opacity:t,z:1})}),wipe:bt,slide:gt,zoom:(e,t)=>({old:p({scale:1+ge*T(e)*t,opacity:1-t,z:1}),next:p({scale:1+ye*T(e)*(1-t)})}),spin:yt,blur:(e,t)=>{let n=be*T(e)*(t<.5?ne(t):1-ne(t));return t<.5?{old:p({blur:n,z:1}),next:S()}:{old:S(),next:p({blur:n,z:1})}},glitch:xt,shake:vt,whip:St},Tt=(e,t)=>{let n=t%2===0?1:-1;return{translate:[e*n*(.6+.4*M(t)),e*(M(t+7)-.5)],scale:1+2*e}},Et={blur:(e,t)=>({layer:{blur:be*t}}),zoom:(e,t,n,o)=>({layer:{scale:1+(o==="before"?ge:ye)*t}}),shake:(e,t,n)=>({layer:Tt(ve*t,n)}),glitch:(e,t,n)=>{let o=(M(n+101)-.5)*2*xe*t;return{layer:{translate:[o,0],scale:1+2*Math.abs(o)}}},whip:(e,t,n,o)=>{let[s,r]=se(e.direction),a=ht*t*(o==="after"?-1:1);return{layer:{translate:[s*a,r*a],scale:1+2*Math.abs(a),smear:[Math.abs(s)*te*t,Math.abs(r)*te*t]}}},spin:(e,t,n,o,s)=>{let r=Se*t*(o==="after"?-1:1);return{layer:{rotate:r,scale:we(r,s)}}},flash:(e,t)=>({layer:{},overlay:{color:W.white,opacity:g(he*t)}}),fade:(e,t)=>({layer:{},overlay:{color:W[e.via],opacity:g(t)}}),dissolve:()=>({layer:{}}),wipe:()=>({layer:{}}),slide:()=>({layer:{}})},Mt=(e,t,n,o)=>{let s=t==="after"?1-v(e.ease,n):v(e.ease,n),r=Math.min(e.frames-1,Math.max(0,Math.round(n*e.frames)-(t==="before"?1:0))),a=Et[e.kind](e,s*T(e),r,t,o),i=p({...a.layer,z:1}),c=t==="after"?{old:S(),next:i}:{old:i,next:S()};return a.overlay&&a.overlay.opacity>0?{...c,overlay:a.overlay}:c},Ee=(e,t,n)=>{let o=e.side??"both";return o==="both"?wt[e.kind](e,v(e.ease,t),g(t),n):Mt(e,o,t,n)};var G={scale:1,translate:[0,0]};var kt=(e,t)=>{let n=C(e.scale[0],e.scale[1],t),o=[C(e.shift[0][0],e.shift[1][0],t),C(e.shift[0][1],e.shift[1][1],t)];return{scale:n,translate:[(1-n)*(e.focus[0]-.5)+(o[0]??0),(1-n)*(e.focus[1]-.5)+(o[1]??0)]}},Me=(e,t)=>{let n=e[0];if(!n)return G;let o=[...e].reverse().find(r=>t>=r.from)??n,s=t<o.from?0:g((t-o.from)/Math.max(1,o.to-o.from));return kt(o,v(o.ease,s))};var k={opacity:1,scale:1,translate:[0,0],rotate:0};var ke=(e,t)=>{let n=2*Math.PI*t/e.period,o=e.amount;switch(e.preset){case"pulse":return{...k,scale:1+o*(1-Math.cos(n))/2};case"float":{let s=o*Math.sin(n);return{...k,translate:[0,s===0?0:-s]}}case"sway":return{...k,rotate:o*Math.sin(n)};case"blink":return{...k,opacity:t%e.period<e.period/2?1:1-o};case"spin":return{...k,rotate:360*o*t/e.period}}};var _=(e,t)=>Math.min(Math.max(0,e.frames-1),Math.max(0,Math.floor(t))),Re=(e,t)=>t>=e.a&&t<e.a+e.frames,Rt=(e,t)=>{let n=e.side??"both";return n==="after"?(t-e.a)/e.frames:n==="before"?(t-e.a+1)/e.frames:(t-e.a+1)/(e.frames+1)},Le=(e,t)=>{let n=e.segments[t],o=n?.transition,s=e.segments[t+1]?.transition;if(!n)return[0,0];let r=o&&(o.side??"both")==="both"?o.a:n.start,a=s&&(s.side??"both")==="both"?s.a+s.frames-1:n.end-1;return[r,a]},re=(e,t,n)=>{let o=e.segments[t]?.base;if(!o||o.kind==="color"||o.kind==="scene")return G;if(o.moves)return Me(o.moves,n);if(o.zoom===0&&o.pan[0]===0&&o.pan[1]===0)return G;let[s,r]=Le(e,t),a=(n-s)/e.canvas.fps,i=(r-s)/e.canvas.fps,c=o.zoom>=0?o.zoom*a:-o.zoom*(i-a),m=Math.max(Math.abs(o.pan[0]),Math.abs(o.pan[1]))*i;return{scale:1+c+m,translate:[o.pan[0]*(a-i/2),o.pan[1]*(a-i/2)]}};var Ce=(e,t,n,o)=>{let s=Ee(n,Rt(n,o),e.canvas),r=n.side??"both",a={index:t,state:s.old,camera:re(e,t,o)},i={index:t+1,state:s.next,camera:re(e,t+1,o)};return{layers:r==="both"?[a,i]:r==="after"?[i]:[a],...s.overlay?{overlay:s.overlay}:{}}},j=(e,t)=>{let n=_(e,t),o=Math.max(0,e.segments.findIndex(a=>n>=a.start&&n<a.end)),s=e.segments[o]?.transition;if(s&&Re(s,n))return Ce(e,o-1,s,n);let r=e.segments[o+1]?.transition;return r&&Re(r,n)?Ce(e,o,r,n):{layers:[{index:o,state:oe,camera:re(e,o,n)}]}},Ct=(e,t)=>{let n=t-e.start,o=e.end-e.start;return e.enter.frames>0&&n<e.enter.frames?ee(e.enter,"enter",(n+1)/e.enter.frames):e.exit.frames>0&&n>=o-e.exit.frames?ee(e.exit,"exit",(n-(o-e.exit.frames))/e.exit.frames):Z},Lt=(e,t)=>{let n=e.start+e.enter.frames,o=Math.max(n,e.end-e.exit.frames);return Math.min(Math.max(0,t-n),o-n)},Ne=(e,t)=>{if(t<e.start||t>=e.end)return;let n=Ct(e,t),o=e.loop?ke(e.loop,Lt(e,t)):k;return o===k&&e.opacity===void 0&&e.rotate===void 0?n:{...n,opacity:n.opacity*o.opacity*(e.opacity??1),scale:n.scale*o.scale,translate:[n.translate[0]+o.translate[0],n.translate[1]+o.translate[1]],rotate:n.rotate+o.rotate+(e.rotate??0)}};var Nt=6,At=(e,t,n,o)=>{let s=Math.max(0,t.frames-1),r=o-e.start;return r<=0?Math.min(e.in,s):Math.min(s,e.in+Math.round(r*t.fps*e.speed/n))},It=(e,t)=>e+"/"+String(t).padStart(Nt,"0")+".png",ae=(e,t,n)=>{let o=e.footage?.[t.material];return o?.dir===void 0?void 0:It(o.dir,At(t,o,e.canvas.fps,n))};var Ae="popost-times=";var Pt=e=>{let t=new Map;for(let n of e.items){if(!n.cue)continue;let o=n.cue.track+"#"+n.cue.index,s=t.get(o);t.set(o,s?[Math.min(s[0],n.start),Math.max(s[1],n.end)]:[n.start,n.end])}return[...t.values()]},Dt=(e,t)=>{let n=e.canvas.fps,o=t.base.kind==="scene"?t.base.offset??0:0,s=d=>Math.round(Math.max(o,(d-t.start)/n+o)*1e3)/1e3,r=Math.round(.2*n),a=d=>d>=t.start-r&&d<t.end,i=e.speech?.voice??[],c=(i.length?i:Pt(e)).filter(([d])=>a(d)).sort((d,l)=>d[0]-l[0]),m=(e.words??[]).flatMap(d=>d.tokens).filter(d=>a(d.start)).sort((d,l)=>d.start-l.start);if(!(!c.length&&!m.length))return{seconds:s(t.end),lines:c.map(([d,l])=>({at:s(d),end:s(l)})),words:m.map(d=>({text:d.text,at:s(d.start),end:s(d.end)}))}},Ie=(e,t,n)=>{let o=Dt(e,t);return o?n+"#"+Ae+encodeURIComponent(JSON.stringify(o)):n},K=e=>e.split("#"+Ae)[0]??e;var _t=(e,t)=>{e.querySelectorAll("[data-slot]").forEach(n=>{let o=t[n.getAttribute("data-slot")??""];o!==void 0&&(n instanceof(e.defaultView??globalThis).HTMLImageElement?n.setAttribute("src",o):n.textContent=o)})},Pe=e=>[e?.__popostScene?.timeline,...Object.values(e?.__timelines??{})].filter(t=>typeof t=="object"&&t!==null&&(typeof t.seek=="function"||typeof t.time=="function")),De=e=>{let t=e.frame.contentDocument;if(t)for(let n of t.getAnimations())e.animations.includes(n)||e.animations.push(n)},Ft=e=>e?.picture?'The picture "'+e.picture.src+'" of the scene "'+e.scene+'" could not be loaded. Check its path: it is relative to the scene file.':'The scene "'+(e?.scene??"")+'" could not be loaded. Check that the file exists in the project directory and is an HTML page.',L=class extends Error{name="SceneLoadError";failures;constructor(t){super(Ft(t[0])),this.failures=t}},Ht=async(e,t,n)=>{let o=Array.from(t.images),s=await Promise.allSettled(o.map(r=>r.decode()));return o.flatMap((r,a)=>{if(s[a]?.status!=="rejected")return[];let i=r.getAttribute("data-slot"),c=i!==null&&e.slots?.[i]!==void 0;return[{segment:e.segment,scene:n,picture:{src:r.getAttribute("src")??"",url:r.currentSrc||r.src,...c?{slot:i}:{}}}]})},Ot=async e=>{let{frame:t}=e,n=K(e.source??t.getAttribute("src")??""),o=Bt(t);try{await Wt(e,n)}finally{o()}},Bt=e=>{let t=e.parentElement;return!t||t.style.display!=="none"?()=>{}:(t.style.display="block",t.style.visibility="hidden",()=>{t.style.visibility==="hidden"&&(t.style.removeProperty("visibility"),t.style.display="none")})},Wt=async(e,t)=>{let{frame:n}=e;await new Promise(r=>{let a=()=>{n.contentDocument?.readyState!=="complete"||n.contentDocument.URL==="about:blank"||(n.removeEventListener("load",a),r())};n.addEventListener("load",a),e.source&&(n.src=e.source),a()});let o=n.contentDocument;if(!o?.body)throw new L([{segment:e.segment,scene:t}]);e.slots&&_t(o,e.slots),await o.fonts.ready;let s=await Ht(e,o,t);if(s.length)throw new L(s);De(e),zt(e)},_e=e=>e.ready??=Ot(e),zt=e=>{for(let t of e.animations)t.playState!=="paused"&&t.pause(),t.currentTime=0;for(let t of Pe(e.frame.contentWindow))t.pause?.()},Fe=(e,t,n)=>{De(e);let o=Math.max(0,t)*1e3,s=!1,r=[];for(let l of e.animations){l.playState!=="paused"&&l.pause(),l.currentTime=o;let u=Number(l.effect?.getComputedTiming().endTime??0);r.push(Math.min(o,u)),o>=u||(s=!0)}let a=e.frame.contentWindow,i=Math.max(0,t);for(let l of Pe(a)){l.pause?.(),typeof l.seek=="function"?l.seek(i,!1):l.time?.(i);let u=typeof l.totalDuration=="function"?l.totalDuration():typeof l.duration=="function"?l.duration():1/0;r.push(Math.min(i,u)),i>=u||(s=!0)}let c=a?.__popostScene?.render;typeof c=="function"&&(c(Math.max(0,t),n),s=!0);let m=r.join("|"),d=e.clock!==m;return e.clock=m,s||d};var Gt='"Noto Sans CJK SC", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif',V={font:Gt,size:.045,weight:700,color:"#ffffff",align:"center",italic:!1},A=1.25;var so={headline:{...V,size:.065,weight:800,stroke:{color:"#000000",width:.12}},subtitle:{...V,size:.04,weight:700,stroke:{color:"#000000",width:.1}},label:{...V,size:.032,weight:700,color:"#111111",background:{color:"#ffffff",padding:.35,radius:.3}},caption:{...V,size:.036,weight:600,background:{color:"rgba(0, 0, 0, 0.6)",padding:.3,radius:.2}}};var He=(e,t)=>{let n=Array.from(e),o=[...t??[]].sort((a,i)=>a.from-i.from),s=[],r=0;for(let a of o){let i=Math.min(n.length,Math.max(r,a.from)),c=Math.min(n.length,a.to);i>r&&s.push({text:n.slice(r,i).join("")}),c>i?(s.push({text:n.slice(i,c).join(""),span:a}),r=c):r=i}return r<n.length&&s.push({text:n.slice(r).join("")}),s};var R=e=>String(Math.round(e*1e4)/1e4),f=e=>R(e)+"px",b=(e,t,n,o)=>{let s=e.createElement(t);return s.style.cssText=n,o.appendChild(s),s},I=(e,t,n,o)=>{let s=(e.padding??.3)*t,r=(e.radius??0)*t;return"background:"+e.color+";padding:"+[s,o?s:0,s,n?s:0].map(f).join(" ")+";border-radius:"+[n?r:0,o?r:0,o?r:0,n?r:0].map(f).join(" ")+";"},U=e=>e?(e.color?"color:"+e.color+";":"")+(e.weight?"font-weight:"+e.weight+";":"")+(e.italic!==void 0?"font-style:"+(e.italic?"italic":"normal")+";":""):"";var jt=(e,t)=>{let n=new Array(t).fill(void 0);for(let o of e??[])for(let s=Math.max(0,o.from);s<Math.min(t,o.to);s++)n[s]=o;return n},Be=(e,t,n,o)=>U(e)+(e?.background?I(e.background,o,t===e.from,t===Math.min(e.to,n)-1):""),We=(e,t,n,o)=>{let s=Be(e.spans[t],t,e.chars.length,e.size),r=b(e.doc,"span",s,n);r.textContent=e.chars[t]??"",e.out.chars.push(r),e.out.charCss.push(s),e.out.owner.push(o)},Kt=e=>{let t=e.s.spoken?.background;if(!t)return"";let n=(t.padding??$.padding)*e.size,o=((e.s.lineHeight??A)-1.1)/2*e.size-n;return"position:absolute;left:"+f(-n)+";right:"+f(-n)+";top:"+f(o)+";bottom:"+f(o)+";z-index:0;transform-origin:50% 50%;background:"+t.color+";border-radius:"+f((t.radius??$.radius)*e.size)+";"},Oe="position:absolute;left:0;top:0;width:100%;height:100%;text-align:center;white-space:pre;transform-origin:50% 50%;",Vt=(e,t,n,o,s)=>{let r=b(e.doc,"span","display:inline-block;position:relative;white-space:nowrap;",s),a=b(e.doc,"span","visibility:hidden;",r),i=e.s.spoken?.weight;for(let l=n;l<o;l++){let u=e.spans[l]?.weight??e.s.weight,h=b(e.doc,"span",Be(e.spans[l],l,e.chars.length,e.size)+(i&&i>u?"font-weight:"+i+";":""),a);h.textContent=e.chars[l]??""}let c=Kt(e),m=c?b(e.doc,"span",c+"display:none;",r):void 0,d=b(e.doc,"span",Oe+"z-index:1;",r);d.dataset.glyphs="1";for(let l=n;l<o;l++)We(e,l,d,{token:t,gap:!1});e.out.tokens.push({layer:d,layerCss:Oe,...m?{box:m}:{},boxCss:c})},ze=(e,t,n,o,s)=>{let r=Array.from(t.text??""),a=t.words??[],i={doc:e,chars:r,spans:jt(n.spans,r.length),s:n,size:o,out:{chars:[],charCss:[],owner:[],tokens:[]}},c=0,m=0;for(;c<r.length;){let d=a[m];if(d&&c>=d.from){Vt(i,m,d.from,Math.max(d.from,Math.min(d.to,r.length)),s),c=Math.max(c,d.to),m++;continue}let l=Math.min(r.length,d?d.from:r.length),u=b(e,"span","position:relative;z-index:1;",s);for(let h=c;h<l;h++)We(i,h,u,{token:m-1,gap:!0});c=l}return i.out},Ut=e=>e?(e.color?"color:"+e.color+";":"")+(e.weight?"font-weight:"+e.weight+";":"")+(e.opacity!==void 0?"opacity:"+R(e.opacity)+";":""):"",Ge=(e,t,n,o)=>{let r=(t.words??[]).map(i=>de(i,n)),a=r.map(i=>me(t.style?.spoken,i));e.tokens.forEach((i,c)=>{let m=a[c]??D,d="transform:"+(m.scale!==1?"scale("+R(m.scale)+")":"none")+";";i.layer.style.cssText=i.layerCss+"z-index:"+(r[c]==="spoken"?2:1)+";"+d,i.box&&(i.box.style.cssText=i.boxCss+"display:"+(m.background?"block":"none")+";"+d)}),e.chars.forEach((i,c)=>{let m=e.owner[c]??{token:-1,gap:!0},d=m.token<0?void 0:m.gap?r[m.token]==="past"?a[m.token]:void 0:a[m.token];i.style.cssText=(e.charCss[c]??"")+Ut(d)+"visibility:"+(c<o?"visible":"hidden")+";"})};var E=e=>String(Math.round(e*1e4)/1e4),F=e=>E(e)+"px",Yt=e=>E(e*100)+"%",Xt=e=>({W:e.canvas.width,H:e.canvas.height,min:Math.min(e.canvas.width,e.canvas.height),halfDiagonal:Math.hypot(e.canvas.width,e.canvas.height)/2}),Ke=e=>e.every(t=>t<=0)?"none":"inset("+e.map(Yt).join(" ")+")",qt=(e,t)=>Array.isArray(e)?Ke(e):"circle("+F(Math.max(0,e.radius)*t.halfDiagonal)+" at 50% 50%)",ie=(e,t,n,o)=>e===0&&t===0&&n===0&&o===1?"none":"translate("+F(e)+","+F(t)+") rotate("+E(n)+"deg) scale("+E(o)+")",Jt=(e,t,n)=>{if(!t){e.layer.style.cssText=e.layerCss+"display:none;",e.smear.setAttribute("stdDeviation","0 0"),e.img&&(e.img.style.cssText=e.imgCss);return}let o=t.state,s=o.smear[0]>0||o.smear[1]>0,r=o.blur>0?"blur("+F(o.blur*n.min)+")":s?"url(#"+e.filterId+")":"none";e.layer.style.cssText=e.layerCss+"display:block;z-index:"+(o.z+1)+";opacity:"+E(o.opacity)+";transform:"+ie(o.translate[0]*n.W,o.translate[1]*n.H,o.rotate,o.scale)+";filter:"+r+";clip-path:"+qt(o.clip,n)+";",e.smear.setAttribute("stdDeviation",E(o.smear[0]*n.min)+" "+E(o.smear[1]*n.min));let a=t.camera;e.img&&(e.img.style.cssText=e.imgCss+"transform:"+ie(a.translate[0]*n.W,a.translate[1]*n.H,0,a.scale)+";")},$t=(e,t,n)=>{let o=[e.shadow,t>0?"blur("+F(t*n.min)+")":""].filter(s=>s!=="");return o.length>0?o.join(" "):"none"},Zt=(e,t,n)=>e.css+"display:"+e.display+";opacity:"+E(t.opacity)+";transform:"+ie(t.translate[0]*n.min,t.translate[1]*n.min,t.rotate,t.scale)+";filter:"+$t(e,t.blur,n)+";clip-path:"+Ke(t.clip)+";",Qt=(e,t,n,o,s)=>{e.el.style.cssText=n?Zt(e,n,o):e.css+"display:none;";let r=n?ue(t,n,e.chars.length,s):e.chars.length;e.words?Ge(e.words,t,s,r):e.chars.forEach((a,i)=>{a.style.visibility=i<r?"visible":"hidden"})},je=(e,t,n)=>{if(e){if(t===void 0){e.hasAttribute("src")&&e.removeAttribute("src");return}e.getAttribute("src")!==t&&e.setAttribute("src",t),n.push(e)}},Y=(e,t,n,o=!0,s=!0)=>{let r=Xt(t),a=_(t,n),i=j(t,a),c=[];return e.live=!1,e.shown=[],e.segments.forEach((m,d)=>{let l=i.layers.find(y=>y.index===d);Jt(m,l,r);let u=t.segments[d]?.base,h=(a-(t.segments[d]?.start??0))/t.canvas.fps+(u?.kind==="scene"?u.offset??0:0);m.scene&&l&&e.shown.push({segment:d,seconds:Math.max(0,h)}),s&&m.scene&&l&&Fe(m.scene,h,t.canvas.fps)&&(e.live=!0),o&&u?.kind==="video"&&je(m.img,l?ae(t,u.play,a):void 0,c)}),e.overlay.style.cssText=i.overlay?e.overlayCss+"display:block;background:"+i.overlay.color+";opacity:"+E(i.overlay.opacity)+";":e.overlayCss+"display:none;",t.items.forEach((m,d)=>{let l=e.items[d];if(!l)return;let u=Ne(m,a);Qt(l,m,u,r,a),o&&m.play&&je(l.img,u?ae(t,m.play,a):void 0,c)}),c};var Ve=e=>String(Math.round(e*1e4)/1e4);var ce=e=>{let t=e.stops.map(n=>n.color+" "+Ve(n.at*100)+"%").join(", ");return e.type==="linear"?"linear-gradient("+Ve(e.angle??180)+"deg, "+t+")":"radial-gradient(farthest-corner at 50% 50%, "+t+")"};var q="http://www.w3.org/2000/svg",X=e=>"position:absolute;left:0;top:0;width:"+f(e.canvas.width)+";height:"+f(e.canvas.height)+";",qe=e=>Math.min(e.canvas.width,e.canvas.height),Ue=e=>'"'+e.replace(/["\\\\]/g,"\\\\$&").replace(/\\n/g,"\\\\a ")+'"',Je=(e,t)=>f(e.x*t)+" "+f(e.y*t)+" "+f(e.blur*t)+" "+e.color,en=(e,t,n,o,s)=>{let r=n.base.kind==="color"?n.base:n.base.kind==="scene"?void 0:n.base.ground,a=r?"background:"+(r.gradient?ce(r.gradient):r.color)+";":"",i=X(t)+"overflow:hidden;transform-origin:50% 50%;"+a,c=b(e,"div",i+"display:none;",o);c.dataset.segment=n.id;let m="popost-smear-"+n.index,d=e.createElementNS(q,"filter");d.setAttribute("id",m),d.setAttribute("color-interpolation-filters","sRGB");let l=e.createElementNS(q,"feGaussianBlur");if(l.setAttribute("stdDeviation","0 0"),l.setAttribute("edgeMode","duplicate"),d.appendChild(l),s.appendChild(d),n.base.kind==="color")return{layer:c,layerCss:i,imgCss:"",smear:l,filterId:m};if(n.base.kind==="scene"){let y=b(e,"iframe","position:absolute;left:0;top:0;width:100%;height:100%;border:0;display:block;pointer-events:none;background:transparent;",c);return y.setAttribute("sandbox","allow-scripts allow-same-origin"),y.setAttribute("scrolling","no"),y.setAttribute("tabindex","-1"),{layer:c,layerCss:i,imgCss:"",smear:l,filterId:m,scene:{frame:y,source:Ie(t,n,n.base.src),segment:n.index,animations:[],...n.base.slots?{slots:n.base.slots}:{}}}}let u="position:absolute;left:0;top:0;width:100%;height:100%;display:block;transform-origin:50% 50%;object-fit:"+n.base.fit+";",h=b(e,"img",u,c);return h.alt="",n.base.kind==="image"&&(h.src=n.base.src),{layer:c,layerCss:i,img:h,imgCss:u,smear:l,filterId:m}},tn={left:"flex-start",center:"center",right:"flex-end"},Ye=e=>U(e.span),nn=(e,t,n,o,s)=>t.flatMap(r=>{let a=r.span?.background;if(!o){let m=b(e,"span",Ye(r)+(a?I(a,n,!0,!0)+"-webkit-box-decoration-break:clone;box-decoration-break:clone;":""),s);return m.textContent=r.text,[]}let i=b(e,"span",Ye(r),s),c=Array.from(r.text);return c.map((m,d)=>{let l=b(e,"span",a?I(a,n,d===0,d===c.length-1):"",i);return l.textContent=m,l})}),on=(e,t)=>"width:100%;text-align:"+e.align+";font-family:"+e.font+";font-size:"+f(t)+";font-weight:"+e.weight+";font-style:"+(e.italic?"italic":"normal")+";color:"+e.color+";line-height:"+R(e.lineHeight??A)+";white-space:pre-wrap;overflow-wrap:break-word;"+(e.letterSpacing?"letter-spacing:"+f(e.letterSpacing*t)+";":"")+(e.shadow?"text-shadow:"+Je(e.shadow,t)+";":"")+(e.opacity!==void 0&&e.opacity!==1?"opacity:"+R(e.opacity)+";":""),sn=(e,t,n,o)=>{let s=n.style;if(!s||n.text===void 0)return{chars:[]};let r=s.size*t.canvas.height,a=b(e,"div",on(s,r),o),i=s.stroke?"-webkit-text-stroke:"+f(s.stroke.width*r)+" "+s.stroke.color+";paint-order:stroke fill;":"",c=s.background?I(s.background,r,!0,!0)+"-webkit-box-decoration-break:clone;box-decoration-break:clone;":"",m=b(e,"span",i+c,a);if(n.words){let l=ze(e,n,s,r,m);return{chars:l.chars,block:a,words:l}}let d=n.enter.preset==="type"||n.exit.preset==="type";return{chars:nn(e,He(n.text,s.spans),r,d,m),block:a}},rn=(e,t)=>{let[n,o,s,r]=t.box,a=e.canvas.width,i=e.canvas.height,c=t.border?"border:"+f(t.border.width*qe(e))+" solid "+t.border.color+";":"";return"position:absolute;left:"+f(n*a)+";top:"+f(o*i)+";width:"+f(s*a)+";height:"+f(r*i)+";z-index:"+t.z+";transform-origin:50% 50%;"+c},Xe=(e,t)=>{if(t.shape==="ellipse"||t.mask==="ellipse")return"border-radius:50%;";let n=(t.radius??0)*Math.min(t.box[2]*e.canvas.width,t.box[3]*e.canvas.height);return n>0?"border-radius:"+f(n)+";":""},an=(e,t,n,o)=>{let s=rn(t,n),r=n.shadow?"drop-shadow("+Je(n.shadow,qe(t))+")":"";if(n.type==="text"){let c=s+"align-items:center;justify-content:"+tn[n.style?.align??"center"]+";",m=b(e,"div",c+"display:none;",o);return m.dataset.item=n.id,{el:m,css:c,display:"flex",shadow:r,...sn(e,t,n,m)}}if(n.type==="image"||n.type==="video"){let c=Xe(t,n),m=s+(c||n.type==="video"?"overflow:hidden;"+c:""),d=b(e,"div",m+"display:none;",o);d.dataset.item=n.id;let l=b(e,"img","width:100%;height:100%;display:block;object-fit:"+(n.fit??"contain")+";",d);return l.alt="",n.type==="image"&&(l.src=n.src??""),{el:d,css:m,display:"block",shadow:r,chars:[],img:l}}let a=s+"background:"+(n.gradient?ce(n.gradient):n.color??"#ffffff")+";"+Xe(t,n),i=b(e,"div",a+"display:none;",o);return i.dataset.item=n.id,{el:i,css:a,display:"block",shadow:r,chars:[]}},cn=e=>(e.fonts??[]).map(t=>"@font-face{font-family:"+Ue(t.family)+";src:url("+Ue(t.src)+");font-weight:1 1000;font-display:block}").join(\`
|
|
22687
|
-
\`),$e=(e,t,n,o)=>{let s=n.canvas.width,r=n.canvas.height;if((n.fonts??[]).length>0){let x=e.createElement("style");x.textContent=cn(n),e.head.appendChild(x)}let a=b(e,"div","position:relative;overflow:hidden;width:"+f(Math.round(s*o))+";height:"+f(Math.round(r*o))+";",t),i=b(e,"div","position:relative;overflow:hidden;background:#000;width:"+f(s)+";height:"+f(r)+";transform-origin:0 0;"+(o===1?"":"transform:scale("+R(o)+");"),a),c=e.createElementNS(q,"svg");c.setAttribute("width","0"),c.setAttribute("height","0"),c.setAttribute("style","position:absolute;width:0;height:0;");let m=e.createElementNS(q,"defs");c.appendChild(m),i.appendChild(c);let d=b(e,"div",X(n)+"z-index:0;isolation:isolate;",i),l=n.segments.map(x=>en(e,n,x,d,m)),u=X(n)+"z-index:1;",h=b(e,"div",u+"display:none;",i),y=b(e,"div",X(n)+"z-index:2;isolation:isolate;",i),H=n.items.map(x=>an(e,n,x,y)),N=[...l.filter((x,P)=>n.segments[P]?.base.kind==="image"),...H.filter((x,P)=>n.items[P]?.type==="image")].flatMap(x=>x.img?[x.img]:[]);return{stage:i,segments:l,overlay:h,overlayCss:u,items:H,images:N,live:!1,shown:[]}};var ln=.3333333333333333,dn=80,mn=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TITLE"]),un=e=>Array.from(e.childNodes).some(t=>t.nodeType===3&&(t.textContent??"").trim()!==""),Ze=(e,t)=>e.right>t.left&&e.left<t.right&&e.bottom>t.top&&e.top<t.bottom,pn=(e,t)=>{let n=e,o=n.offsetWidth??0,s=n.offsetHeight??0;return o>0&&s>0?Math.min(t.width/o,t.height/s):1},fn=(e,t,n)=>{if(e.getClientRects().length===0||t.getComputedStyle(e).visibility!=="visible")return!1;let o=e.getBoundingClientRect();if(!(o.width>0&&o.height>0)||!Ze(o,n)||pn(e,o)<ln)return!1;let s=e.ownerDocument.documentElement,r=e.ownerDocument.body,a=1;for(let i=e;i;i=i.parentElement){let c=t.getComputedStyle(i);if(a*=Number(c.opacity),i!==e&&i!==s&&i!==r&&c.display!=="inline"&&(c.overflowX!=="visible"||c.overflowY!=="visible")&&!Ze(o,i.getBoundingClientRect()))return!1}return a>=.5},Qe=e=>{let t=e.defaultView;if(!t||!e.body)return[];let n={left:0,top:0,right:t.innerWidth,bottom:t.innerHeight},o=[];return Array.from(e.body.querySelectorAll("*")).forEach((s,r)=>{if(mn.has(s.tagName.toUpperCase())||!un(s))return;let a=(s.textContent??"").replace(/\\s+/g," ").trim().slice(0,dn);o.push({index:r,text:a,visible:fn(s,t,n)})}),o};var hn=1,bn=(e,t)=>e?{left:Math.min(e.left,t.left),top:Math.min(e.top,t.top),right:Math.max(e.right,t.right),bottom:Math.max(e.bottom,t.bottom)}:t,gn=(e,t,n)=>{if(!e)return{top:0,bottom:0,box:0};e.font=t.fontStyle+" "+t.fontWeight+" "+t.fontSize+" "+t.fontFamily;let o=e.measureText(n.replace(/\\s+/g,""));return{top:Math.max(0,o.fontBoundingBoxAscent-o.actualBoundingBoxAscent),bottom:Math.max(0,o.fontBoundingBoxDescent-o.actualBoundingBoxDescent),box:o.fontBoundingBoxAscent+o.fontBoundingBoxDescent}},yn=e=>{let t=e.ownerDocument,n=t.defaultView,o=t.createElement("canvas").getContext("2d"),s=t.createRange(),r=t.createTreeWalker(e,NodeFilter.SHOW_TEXT),a;for(let i=r.nextNode();i;i=r.nextNode()){let c=i.textContent??"",m=i.parentElement;if(!c.trim()||!m||!n)continue;let d=gn(o,n.getComputedStyle(m),c);for(let l=0;l<c.length;l++){if(/\\s/.test(c.charAt(l)))continue;let u=(c.codePointAt(l)??0)>65535?2:1;s.setStart(i,l),s.setEnd(i,l+u),l+=u-1;let h=s.getBoundingClientRect();if(h.width<=0||h.height<=0)continue;let y=d.box>0?h.height/d.box:1;a=bn(a,{left:h.left,right:h.right,top:h.top+d.top*y,bottom:h.bottom-d.bottom*y})}}return a},et=e=>{let t=e.getBoundingClientRect(),n=e.offsetWidth>0?t.width/e.offsetWidth:1,o=e.offsetHeight>0?t.height/e.offsetHeight:1,s=t.left+e.clientLeft*n,r=t.top+e.clientTop*o;return{left:s,top:r,right:s+e.clientWidth*n,bottom:r+e.clientHeight*o}},tt=(e,t,n,o)=>{let r=[...n?[["left",t.left-e.left],["right",e.right-t.right]]:[],...o?[["top",t.top-e.top],["bottom",e.bottom-t.bottom]]:[]].reduce((a,i)=>!a||i[1]>a[1]?i:a,void 0);return r&&r[1]>hn?{side:r[0],px:Math.round(r[1])}:void 0},xn=e=>{let t=e.tagName.toLowerCase();if(e.id)return t+"#"+e.id;let n=Array.from(e.classList);return n.length?t+"."+n.join("."):t},vn=(e,t)=>{let n=e.ownerDocument.defaultView,o=e.ownerDocument.body;for(let s=e.parentElement;s&&n&&s!==o&&s!==e.ownerDocument.documentElement;s=s.parentElement){let r=n.getComputedStyle(s),a=r.overflowX!=="visible",i=r.overflowY!=="visible";if(r.display==="inline"||!a&&!i)continue;let c=tt(t,et(s),a,i);if(c)return{ancestor:xn(s),...c}}},Sn=e=>{let t=[],n=[];for(let o of Array.from(e.querySelectorAll("[data-slot]"))){if(!(o instanceof(e.defaultView??globalThis).HTMLElement)||o.tagName==="IMG")continue;let s=yn(o);if(!s)continue;let r={slot:o.getAttribute("data-slot")??"",text:(o.textContent??"").trim().slice(0,40)},a=o.clientWidth>0&&o.clientHeight>0?tt(s,et(o),!0,!0):void 0,i=a?void 0:vn(o,s);a?t.push({...r,...a}):i&&n.push({...r,...i})}return{overflowing:t,clipped:n}},wn=e=>{let t=e;if(!t||typeof t.at!="number"||!Number.isFinite(t.at)||t.at<0||typeof t.cue!="string"||!t.cue)return[];let n=typeof t.gain=="number"&&Number.isFinite(t.gain)?Math.min(1,Math.max(0,t.gain)):.7;return[{at:Math.round(t.at*1e3)/1e3,cue:t.cue,gain:Math.round(n*1e3)/1e3,...typeof t.effect=="string"?{effect:t.effect}:{}}]},Tn=e=>{let t=e.defaultView?.__popostScene?.cues,n=[];try{n=JSON.parse(e.getElementById("popost-cues")?.textContent??"[]")}catch{n=[]}return[...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]].flatMap(wn).sort((o,s)=>o.at-s.at)},nt=(e,t)=>e.segments.flatMap(n=>{let o=n.scene?.frame.contentDocument;if(!n.scene||!o||t!==void 0&&n.scene.segment!==t)return[];let s=o.documentElement;return[{segment:n.scene.segment,src:K(n.scene.frame.getAttribute("src")??""),width:Math.max(s.scrollWidth,o.body?.scrollWidth??0),height:Math.max(s.scrollHeight,o.body?.scrollHeight??0),...Sn(o),elements:o.body?o.body.querySelectorAll("*").length:0,texts:Qe(o),cues:Tn(o)}]});var ot=.5,En=e=>{let t=[],n=document.createRange(),o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(let s=o.nextNode();s;s=o.nextNode()){if(s.parentElement?.closest("[data-glyphs]"))continue;let r=s.textContent??"";for(let a=0;a<r.length;a++){if(/\\s/.test(r.charAt(a)))continue;let i=r.codePointAt(a)!==void 0&&(r.codePointAt(a)??0)>65535?2:1;n.setStart(s,a),n.setEnd(s,a+i);let c=n.getBoundingClientRect();c.width>0&&c.height>0&&t.push({left:c.left,top:c.top,right:c.right,bottom:c.bottom}),a+=i-1}}return t},Mn=(e,t)=>{let n=e.map(o=>(o.top+o.bottom)/2).sort((o,s)=>o-s);return n.reduce((o,s,r)=>r===0||s-(n[r-1]??s)>t/2?o+1:o,0)},kn=(e,t)=>{let n=e.style,o=document.createElement("canvas").getContext("2d");if(!n||!o)return[0,0];o.font=(n.italic?"italic ":"")+n.weight+" "+t+"px "+n.font;let s=o.measureText((e.text??"").replace(/\\s+/g,""));return[Math.max(0,s.fontBoundingBoxAscent-s.actualBoundingBoxAscent),Math.max(0,s.fontBoundingBoxDescent-s.actualBoundingBoxDescent)]},Rn=(e,t,n,o,s,r)=>{let a=o.canvas.width*r,i=o.canvas.height*r,c=(n.style?.size??0)*o.canvas.height,m=e.el.getBoundingClientRect(),d=t.getBoundingClientRect(),l=En(t),u=Math.min(...l.map(w=>w.left)),h=Math.max(...l.map(w=>w.right)),[y,H]=kn(n,c),N=(n.style?.stroke?.width??0)*c*r/2,x=Math.min(...l.map(w=>w.top))+y*r-N,P=Math.max(...l.map(w=>w.bottom))-H*r+N,J=(w,le,it,ct)=>[(w-s.left)/a,(le-s.top)/i,(it-w)/a,(ct-le)/i],at=l.length>0?h-u:0;return{id:n.id,fits:d.height<=m.height+ot*r&&at<=m.width+ot*r,lines:Mn(l,(n.style?.lineHeight??A)*c*r),ink:l.length>0?J(u-N,x,h+N,P):[0,0,0,0],block:l.length>0?J(u,d.top,h,d.bottom):J(d.left,d.top,d.left,d.bottom)}},st=(e,t,n)=>{let o=e.stage.getBoundingClientRect();return t.items.flatMap((s,r)=>{let a=e.items[r];if(s.type!=="text"||!a?.block)return[];let i=a.el.style.cssText;a.el.style.cssText=a.css+"display:"+a.display+";";try{return[Rn(a,a.block,s,t,o,n)]}finally{a.el.style.cssText=i}})};var Cn=()=>{let e=document.getElementById("popost-data");if(!e?.textContent)throw new Error('popost video page: the <script id="popost-data"> element with the timeline is missing. Build the page with compilePage.');return JSON.parse(e.textContent)},Ln=e=>[...new Set(e.resolved.items.flatMap(t=>{let n=t.style;return t.type!=="text"||!n?[]:[n.weight,...t.words&&n.spoken?.weight?[n.spoken.weight]:[]].map(s=>(n.italic?"italic ":"")+s+" "+Math.round(n.size*e.resolved.canvas.height)+"px "+n.font)}))],Nn=e=>e.replace(/^["']|["']$/g,""),An=async e=>{let t=e.resolved.fonts??[];if(t.length===0)return;let n=[];document.fonts.forEach(o=>{n.push(o)}),await Promise.all(t.map(async o=>{let s=n.filter(a=>Nn(a.family)===o.family),r=()=>new Error('Font "'+o.family+'" ('+o.src+") could not be loaded. Check that the file exists in the project directory and is a WOFF2, WOFF, TTF or OTF font.");if(s.length===0)throw r();await Promise.all(s.map(a=>a.load())).catch(()=>{throw r()})}))},In=async(e,t)=>{let n=Object.entries(t.resolved.footage??{}).filter(([,s])=>s.dir===void 0).map(([s])=>'"'+s+'"');if(n.length>0)throw new Error("Video material "+n.join(", ")+" has no extracted frames: the page was compiled from resolve() alone. Build it with buildPage, which extracts them into the project's .cache directory.");await Promise.all(e.images.map(s=>s.decode().catch(()=>{throw new Error('Image "'+(s.getAttribute("src")??"")+'" could not be loaded. Check that the file exists in the project directory and is a PNG, JPEG or WebP picture.')}))),await An(t);let o=t.resolved.items.map(s=>s.text??"").join("");await Promise.all(Ln(t).map(s=>document.fonts.load(s,o).catch(()=>[]))),await document.fonts.ready},rt=async e=>{let t=await Promise.allSettled(e.map(_e)),n=t.flatMap(s=>s.status==="rejected"&&s.reason instanceof L?s.reason.failures:[]);if(n.length>0)throw new L(n);let o=t.find(s=>s.status==="rejected");if(o)throw o.reason},Pn=()=>{let e=[],t=async()=>{let n=e,o=await Promise.allSettled(n.map(r=>r.decode()));if(n!==e)return t();let s=o.findIndex(r=>r.status==="rejected");if(s>=0)throw new Error('The video frame picture "'+(n[s]?.getAttribute("src")??"")+\`" could not be loaded. Build the page again: buildPage extracts the frames into the project's .cache directory.\`)};return{settle:t,set:n=>{e=n}}},Dn=(e,t)=>{let n,o=()=>n??=In(e,t),s=e.segments.flatMap(r=>r.scene?[r.scene]:[]);return{all:async()=>{await o(),await rt(s)},frame:async r=>{await o();let a=j(t.resolved,_(t.resolved,r)).layers.map(i=>i.index);await rt(s.filter(i=>a.includes(i.segment)))}}},_n=e=>{let t=e.cloneNode(!0);return t.querySelectorAll("*").forEach(n=>{n instanceof HTMLElement&&n.style.display==="none"&&n.remove()}),t.innerHTML},Fn=()=>{let e=Cn(),t=e.resolved,n=$e(document,document.body,t,e.scale),o=Pn(),s=Dn(n,e),r,a={frames:t.frames,fps:t.canvas.fps,width:t.canvas.width,height:t.canvas.height,scale:e.scale,prepare:async()=>{await s.all(),await o.settle()},preparePreview:s.frame,applyFrame:i=>o.set(Y(n,t,i)),previewFrame:i=>o.set(Y(n,t,i,!1)),settle:()=>o.settle(),layout:()=>st(n,t,e.scale),scenes:i=>nt(n,i),state:i=>(i!==void 0&&o.set(Y(n,t,i,!0,!1)),{markup:_n(n.stage),scenes:n.shown.map(c=>({...c}))}),changed:()=>{let i=n.stage.innerHTML,c=i===r;return r=i,!c||n.live}};a.applyFrame(0),window.__popostVideo=a};Fn();})();
|
|
22774
|
+
\`),$e=(e,t,n,o)=>{let s=n.canvas.width,r=n.canvas.height;if((n.fonts??[]).length>0){let x=e.createElement("style");x.textContent=cn(n),e.head.appendChild(x)}let a=b(e,"div","position:relative;overflow:hidden;width:"+f(Math.round(s*o))+";height:"+f(Math.round(r*o))+";",t),i=b(e,"div","position:relative;overflow:hidden;background:#000;width:"+f(s)+";height:"+f(r)+";transform-origin:0 0;"+(o===1?"":"transform:scale("+R(o)+");"),a),c=e.createElementNS(q,"svg");c.setAttribute("width","0"),c.setAttribute("height","0"),c.setAttribute("style","position:absolute;width:0;height:0;");let m=e.createElementNS(q,"defs");c.appendChild(m),i.appendChild(c);let d=b(e,"div",X(n)+"z-index:0;isolation:isolate;",i),l=n.segments.map(x=>en(e,n,x,d,m)),u=X(n)+"z-index:1;",h=b(e,"div",u+"display:none;",i),y=b(e,"div",X(n)+"z-index:2;isolation:isolate;",i),H=n.items.map(x=>an(e,n,x,y)),N=[...l.filter((x,P)=>n.segments[P]?.base.kind==="image"),...H.filter((x,P)=>n.items[P]?.type==="image")].flatMap(x=>x.img?[x.img]:[]);return{stage:i,segments:l,overlay:h,overlayCss:u,items:H,images:N,live:!1,shown:[]}};var ln=.3333333333333333,dn=80,mn=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","TITLE"]),un=e=>Array.from(e.childNodes).some(t=>t.nodeType===3&&(t.textContent??"").trim()!==""),Ze=(e,t)=>e.right>t.left&&e.left<t.right&&e.bottom>t.top&&e.top<t.bottom,pn=(e,t)=>{let n=e,o=n.offsetWidth??0,s=n.offsetHeight??0;return o>0&&s>0?Math.min(t.width/o,t.height/s):1},fn=(e,t,n)=>{if(e.getClientRects().length===0||t.getComputedStyle(e).visibility!=="visible")return!1;let o=e.getBoundingClientRect();if(!(o.width>0&&o.height>0)||!Ze(o,n)||pn(e,o)<ln)return!1;let s=e.ownerDocument.documentElement,r=e.ownerDocument.body,a=1;for(let i=e;i;i=i.parentElement){let c=t.getComputedStyle(i);if(a*=Number(c.opacity),i!==e&&i!==s&&i!==r&&c.display!=="inline"&&(c.overflowX!=="visible"||c.overflowY!=="visible")&&!Ze(o,i.getBoundingClientRect()))return!1}return a>=.5},Qe=e=>{let t=e.defaultView;if(!t||!e.body)return[];let n={left:0,top:0,right:t.innerWidth,bottom:t.innerHeight},o=[];return Array.from(e.body.querySelectorAll("*")).forEach((s,r)=>{if(mn.has(s.tagName.toUpperCase())||!un(s))return;let a=(s.textContent??"").replace(/\\s+/g," ").trim().slice(0,dn);o.push({index:r,text:a,visible:fn(s,t,n)})}),o};var hn=1,bn=(e,t)=>e?{left:Math.min(e.left,t.left),top:Math.min(e.top,t.top),right:Math.max(e.right,t.right),bottom:Math.max(e.bottom,t.bottom)}:t,gn=(e,t,n)=>{if(!e)return{top:0,bottom:0,box:0};e.font=t.fontStyle+" "+t.fontWeight+" "+t.fontSize+" "+t.fontFamily;let o=e.measureText(n.replace(/\\s+/g,""));return{top:Math.max(0,o.fontBoundingBoxAscent-o.actualBoundingBoxAscent),bottom:Math.max(0,o.fontBoundingBoxDescent-o.actualBoundingBoxDescent),box:o.fontBoundingBoxAscent+o.fontBoundingBoxDescent}},yn=e=>{let t=e.ownerDocument,n=t.defaultView,o=t.createElement("canvas").getContext("2d"),s=t.createRange(),r=t.createTreeWalker(e,NodeFilter.SHOW_TEXT),a;for(let i=r.nextNode();i;i=r.nextNode()){let c=i.textContent??"",m=i.parentElement;if(!c.trim()||!m||!n)continue;let d=gn(o,n.getComputedStyle(m),c);for(let l=0;l<c.length;l++){if(/\\s/.test(c.charAt(l)))continue;let u=(c.codePointAt(l)??0)>65535?2:1;s.setStart(i,l),s.setEnd(i,l+u),l+=u-1;let h=s.getBoundingClientRect();if(h.width<=0||h.height<=0)continue;let y=d.box>0?h.height/d.box:1;a=bn(a,{left:h.left,right:h.right,top:h.top+d.top*y,bottom:h.bottom-d.bottom*y})}}return a},et=e=>{let t=e.getBoundingClientRect(),n=e.offsetWidth>0?t.width/e.offsetWidth:1,o=e.offsetHeight>0?t.height/e.offsetHeight:1,s=t.left+e.clientLeft*n,r=t.top+e.clientTop*o;return{left:s,top:r,right:s+e.clientWidth*n,bottom:r+e.clientHeight*o}},tt=(e,t,n,o)=>{let r=[...n?[["left",t.left-e.left],["right",e.right-t.right]]:[],...o?[["top",t.top-e.top],["bottom",e.bottom-t.bottom]]:[]].reduce((a,i)=>!a||i[1]>a[1]?i:a,void 0);return r&&r[1]>hn?{side:r[0],px:Math.round(r[1])}:void 0},xn=e=>{let t=e.tagName.toLowerCase();if(e.id)return t+"#"+e.id;let n=Array.from(e.classList);return n.length?t+"."+n.join("."):t},vn=(e,t)=>{let n=e.ownerDocument.defaultView,o=e.ownerDocument.body;for(let s=e.parentElement;s&&n&&s!==o&&s!==e.ownerDocument.documentElement;s=s.parentElement){let r=n.getComputedStyle(s),a=r.overflowX!=="visible",i=r.overflowY!=="visible";if(r.display==="inline"||!a&&!i)continue;let c=tt(t,et(s),a,i);if(c)return{ancestor:xn(s),...c}}},Sn=e=>{let t=[],n=[];for(let o of Array.from(e.querySelectorAll("[data-slot]"))){if(!(o instanceof(e.defaultView??globalThis).HTMLElement)||o.tagName==="IMG")continue;let s=yn(o);if(!s)continue;let r={slot:o.getAttribute("data-slot")??"",text:(o.textContent??"").trim().slice(0,40)},a=o.clientWidth>0&&o.clientHeight>0?tt(s,et(o),!0,!0):void 0,i=a?void 0:vn(o,s);a?t.push({...r,...a}):i&&n.push({...r,...i})}return{overflowing:t,clipped:n}},wn=e=>{let t=e;if(!t||typeof t.at!="number"||!Number.isFinite(t.at)||t.at<0||typeof t.cue!="string"||!t.cue)return[];let n=typeof t.gain=="number"&&Number.isFinite(t.gain)?Math.min(1,Math.max(0,t.gain)):.7;return[{at:Math.round(t.at*1e3)/1e3,cue:t.cue,gain:Math.round(n*1e3)/1e3,...typeof t.effect=="string"?{effect:t.effect}:{}}]},Tn=e=>{let t=e.defaultView?.__popostScene?.cues,n=[];try{n=JSON.parse(e.getElementById("popost-cues")?.textContent??"[]")}catch{n=[]}return[...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]].flatMap(wn).sort((o,s)=>o.at-s.at)},nt=(e,t)=>e.segments.flatMap(n=>{let o=n.scene?.frame.contentDocument;if(!n.scene||!o||t!==void 0&&n.scene.segment!==t)return[];let s=o.documentElement;return[{segment:n.scene.segment,src:K(n.scene.frame.getAttribute("src")??""),width:Math.max(s.scrollWidth,o.body?.scrollWidth??0),height:Math.max(s.scrollHeight,o.body?.scrollHeight??0),...Sn(o),elements:o.body?o.body.querySelectorAll("*").length:0,texts:Qe(o),cues:Tn(o)}]});var ot=.5,En=e=>{let t=[],n=document.createRange(),o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(let s=o.nextNode();s;s=o.nextNode()){if(s.parentElement?.closest("[data-glyphs]"))continue;let r=s.textContent??"";for(let a=0;a<r.length;a++){if(/\\s/.test(r.charAt(a)))continue;let i=r.codePointAt(a)!==void 0&&(r.codePointAt(a)??0)>65535?2:1;n.setStart(s,a),n.setEnd(s,a+i);let c=n.getBoundingClientRect();c.width>0&&c.height>0&&t.push({left:c.left,top:c.top,right:c.right,bottom:c.bottom}),a+=i-1}}return t},Mn=(e,t)=>{let n=e.map(o=>(o.top+o.bottom)/2).sort((o,s)=>o-s);return n.reduce((o,s,r)=>r===0||s-(n[r-1]??s)>t/2?o+1:o,0)},kn=(e,t)=>{let n=e.style,o=document.createElement("canvas").getContext("2d");if(!n||!o)return[0,0];o.font=(n.italic?"italic ":"")+n.weight+" "+t+"px "+n.font;let s=o.measureText((e.text??"").replace(/\\s+/g,""));return[Math.max(0,s.fontBoundingBoxAscent-s.actualBoundingBoxAscent),Math.max(0,s.fontBoundingBoxDescent-s.actualBoundingBoxDescent)]},Rn=(e,t,n,o,s,r)=>{let a=o.canvas.width*r,i=o.canvas.height*r,c=(n.style?.size??0)*o.canvas.height,m=e.el.getBoundingClientRect(),d=t.getBoundingClientRect(),l=En(t),u=Math.min(...l.map(w=>w.left)),h=Math.max(...l.map(w=>w.right)),[y,H]=kn(n,c),N=(n.style?.stroke?.width??0)*c*r/2,x=Math.min(...l.map(w=>w.top))+y*r-N,P=Math.max(...l.map(w=>w.bottom))-H*r+N,J=(w,le,it,ct)=>[(w-s.left)/a,(le-s.top)/i,(it-w)/a,(ct-le)/i],at=l.length>0?h-u:0;return{id:n.id,fits:d.height<=m.height+ot*r&&at<=m.width+ot*r,lines:Mn(l,(n.style?.lineHeight??A)*c*r),ink:l.length>0?J(u-N,x,h+N,P):[0,0,0,0],block:l.length>0?J(u,d.top,h,d.bottom):J(d.left,d.top,d.left,d.bottom)}},st=(e,t,n)=>{let o=e.stage.getBoundingClientRect();return t.items.flatMap((s,r)=>{let a=e.items[r];if(s.type!=="text"||!a?.block)return[];let i=a.el.style.cssText;a.el.style.cssText=a.css+"display:"+a.display+";";try{return[Rn(a,a.block,s,t,o,n)]}finally{a.el.style.cssText=i}})};var Cn=()=>{let e=document.getElementById("popost-data");if(!e?.textContent)throw new Error('popost video page: the <script id="popost-data"> element with the timeline is missing. Build the page with compilePage.');return JSON.parse(e.textContent)},Ln=e=>[...new Set(e.resolved.items.flatMap(t=>{let n=t.style;return t.type!=="text"||!n?[]:[n.weight,...t.words&&n.spoken?.weight?[n.spoken.weight]:[]].map(s=>(n.italic?"italic ":"")+s+" "+Math.round(n.size*e.resolved.canvas.height)+"px "+n.font)}))],Nn=e=>e.replace(/^["']|["']$/g,""),An=async e=>{let t=e.resolved.fonts??[];if(t.length===0)return;let n=[];document.fonts.forEach(o=>{n.push(o)}),await Promise.all(t.map(async o=>{let s=n.filter(a=>Nn(a.family)===o.family),r=()=>new Error('Font "'+o.family+'" ('+o.src+") could not be loaded. Check that the file exists in the project directory and is a WOFF2, WOFF, TTF or OTF font.");if(s.length===0)throw r();await Promise.all(s.map(a=>a.load())).catch(()=>{throw r()})}))},In=async(e,t)=>{let n=Object.entries(t.resolved.footage??{}).filter(([,s])=>s.dir===void 0).map(([s])=>'"'+s+'"');if(n.length>0&&!t.nativeFootage)throw new Error("Video material "+n.join(", ")+" has no extracted frames: the page was compiled from resolve() alone. Build it with buildPage, which extracts them into the project's .cache directory.");await Promise.all(e.images.map(s=>s.decode().catch(()=>{throw new Error('Image "'+(s.getAttribute("src")??"")+'" could not be loaded. Check that the file exists in the project directory and is a PNG, JPEG or WebP picture.')}))),await An(t);let o=t.resolved.items.map(s=>s.text??"").join("");await Promise.all(Ln(t).map(s=>document.fonts.load(s,o).catch(()=>[]))),await document.fonts.ready},rt=async e=>{let t=await Promise.allSettled(e.map(_e)),n=t.flatMap(s=>s.status==="rejected"&&s.reason instanceof L?s.reason.failures:[]);if(n.length>0)throw new L(n);let o=t.find(s=>s.status==="rejected");if(o)throw o.reason},Pn=()=>{let e=[],t=async()=>{let n=e,o=await Promise.allSettled(n.map(r=>r.decode()));if(n!==e)return t();let s=o.findIndex(r=>r.status==="rejected");if(s>=0)throw new Error('The video frame picture "'+(n[s]?.getAttribute("src")??"")+\`" could not be loaded. Build the page again: buildPage extracts the frames into the project's .cache directory.\`)};return{settle:t,set:n=>{e=n}}},Dn=(e,t)=>{let n,o=()=>n??=In(e,t),s=e.segments.flatMap(r=>r.scene?[r.scene]:[]);return{all:async()=>{await o(),await rt(s)},frame:async r=>{await o();let a=j(t.resolved,_(t.resolved,r)).layers.map(i=>i.index);await rt(s.filter(i=>a.includes(i.segment)))}}},_n=e=>{let t=e.cloneNode(!0);return t.querySelectorAll("*").forEach(n=>{n instanceof HTMLElement&&n.style.display==="none"&&n.remove()}),t.innerHTML},Fn=()=>{let e=Cn(),t=e.resolved,n=$e(document,document.body,t,e.scale),o=Pn(),s=Dn(n,e),r,a={frames:t.frames,fps:t.canvas.fps,width:t.canvas.width,height:t.canvas.height,scale:e.scale,prepare:async()=>{await s.all(),await o.settle()},preparePreview:s.frame,applyFrame:i=>o.set(Y(n,t,i)),previewFrame:i=>o.set(Y(n,t,i,!1)),settle:()=>o.settle(),layout:()=>st(n,t,e.scale),scenes:i=>nt(n,i),state:i=>(i!==void 0&&o.set(Y(n,t,i,!0,!1)),{markup:_n(n.stage),scenes:n.shown.map(c=>({...c}))}),changed:()=>{let i=n.stage.innerHTML,c=i===r;return r=i,!c||n.live}};a.applyFrame(0),window.__popostVideo=a};Fn();})();
|
|
22688
22775
|
`;
|
|
22689
22776
|
}
|
|
22690
22777
|
});
|
|
@@ -22701,7 +22788,7 @@ var init_page = __esm({
|
|
|
22701
22788
|
const scale = opts.scale ?? 1;
|
|
22702
22789
|
if (!(scale > 0 && scale <= 4)) throw new Error("compilePage: scale is " + scale + "; it must be greater than 0 and at most 4. Use 1 for full size or 0.5 for half.");
|
|
22703
22790
|
const js = PAGE_BUNDLE.replace(/<\/script/gi, "<\\/script");
|
|
22704
|
-
const data = { resolved, scale };
|
|
22791
|
+
const data = { resolved, scale, ...opts.nativeFootage ? { nativeFootage: true } : {} };
|
|
22705
22792
|
return '<!doctype html>\n<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>popost video</title><style>' + CSS2 + '</style></head><body><script type="application/json" id="popost-data">' + scriptJson2(data) + "</script><script>" + js + "</script></body></html>\n";
|
|
22706
22793
|
};
|
|
22707
22794
|
}
|
|
@@ -22732,6 +22819,7 @@ var init_footage3 = __esm({
|
|
|
22732
22819
|
}
|
|
22733
22820
|
});
|
|
22734
22821
|
return {
|
|
22822
|
+
native: Object.fromEntries(read2.map((x) => [x.id, "native" in x && x.native])),
|
|
22735
22823
|
info: Object.fromEntries(read2.map((x) => [x.id, "facts" in x ? x.facts : { error: x.error ?? "unreadable" }])),
|
|
22736
22824
|
colour: Object.fromEntries(read2.flatMap((x) => "colour" in x ? [[x.id, x.colour]] : []))
|
|
22737
22825
|
};
|
|
@@ -24280,7 +24368,8 @@ var init_compile = __esm({
|
|
|
24280
24368
|
problems2.push(...await checkSpeechLocks(rt, dir, plain2), ...speechOverlap(plain2), ...musicOverlap(plain2), ...speakingCuts(plain2), ...nativeSpeechSplices(plain2, project, probed.info), ...await clipMusicRecords(rt, dir, plain2), ...await soundRecords(rt, dir, project), ...await effectLevels(rt, dir, project, plain2), ...await musicEndingProblems(rt, dir, project, plain2), ...await musicBreakProblems(rt, dir, project, plain2));
|
|
24281
24369
|
if (problems2.some((p) => p.level === "error")) return { problems: problems2, project };
|
|
24282
24370
|
const shows = Object.keys(plain2.footage ?? {}).length > 0;
|
|
24283
|
-
const
|
|
24371
|
+
const native = opts.nativeFootage && Object.keys(plain2.footage ?? {}).every((id2) => probed.native?.[id2] === true);
|
|
24372
|
+
const { resolved, stats } = shows && !native ? await extractFootage(rt, plain2, projectDir, probed, { scale: opts.scale }) : { resolved: plain2, stats: void 0 };
|
|
24284
24373
|
return { html: await compilePage(resolved, opts), resolved, project, problems: problems2, ...stats ? { footage: stats } : {} };
|
|
24285
24374
|
};
|
|
24286
24375
|
}
|
|
@@ -26123,8 +26212,8 @@ var init_describe = __esm({
|
|
|
26123
26212
|
const inShot = (c, sh) => shownIn(c, sh, step2);
|
|
26124
26213
|
const k = s.index;
|
|
26125
26214
|
const together2 = p.joined.has(k - 1) ? ", one effect with #" + two7(k) + " before it" : "";
|
|
26126
|
-
const
|
|
26127
|
-
const parts = ["#" + two7(k + 1) + " " + sec(s.start, fps) + "-" + sec(s.end, fps) + " @" + s.start + "-" + s.end, "in " + transitionText(into, sheetInto(into, k, p)) + together2 + (
|
|
26215
|
+
const path4 = pathInto(p, k);
|
|
26216
|
+
const parts = ["#" + two7(k + 1) + " " + sec(s.start, fps) + "-" + sec(s.end, fps) + " @" + s.start + "-" + s.end, "in " + transitionText(into, sheetInto(into, k, p)) + together2 + (path4 ? "; " + trackBrief(path4, fps) : ""), "camera " + cameraText(s)];
|
|
26128
26217
|
if (p.joined.has(k)) parts.push(joinedText(s, fps, sheetInto(out2, k + 1, p)));
|
|
26129
26218
|
const range2 = beatRange(beats2, s);
|
|
26130
26219
|
if (range2) parts.push(range2);
|
|
@@ -28672,9 +28761,9 @@ var init_profile3 = __esm({
|
|
|
28672
28761
|
init_wallet();
|
|
28673
28762
|
init_production();
|
|
28674
28763
|
readVoices = async (rt, dir) => {
|
|
28675
|
-
const
|
|
28676
|
-
if (!await rt.fs.stat(
|
|
28677
|
-
const data = JSON.parse(await rt.fs.readText(
|
|
28764
|
+
const path4 = rt.path.join(dir, "voices.json");
|
|
28765
|
+
if (!await rt.fs.stat(path4)) return { version: 1, speakers: [] };
|
|
28766
|
+
const data = JSON.parse(await rt.fs.readText(path4));
|
|
28678
28767
|
if (data.version !== 1 || !Array.isArray(data.speakers)) throw new Error("voices.json must contain version 1 and a speakers list.");
|
|
28679
28768
|
return data;
|
|
28680
28769
|
};
|
|
@@ -29099,9 +29188,9 @@ var init_questions = __esm({
|
|
|
29099
29188
|
const doubts = b && b.kind !== "cut" ? [...fitsPoorly(b) ? ["does not fit the frames well"] : [], ...b.confidence < 0.4 ? ["unsure"] : []] : [];
|
|
29100
29189
|
const into = !b ? "start" : b.kind === "cut" ? "a cut" : measuredLabel(b) + " " + Math.max(0, b.end - b.start - 1) + "f" + (doubts.length ? ", " + doubts.join(", ") : "");
|
|
29101
29190
|
const track = transitionTrack2(m, k + 1);
|
|
29102
|
-
const
|
|
29191
|
+
const path4 = track ? "; measured " + trackBrief(track, fps) + " (shots/" + String(k + 1).padStart(2, "0") + '.md, "Paths")' : "";
|
|
29103
29192
|
const part = joined.has(k) ? "; very short, on a flat ground with something moving: most likely part of the change into shot " + (k + 2) : "";
|
|
29104
|
-
return { shot: k + 1, time: [two10(s.start / fps), two10(s.end / fps)], frames: shotSheetFile(k + 1), ...transition2 ? { transition: transition2 } : {}, in: into +
|
|
29193
|
+
return { shot: k + 1, time: [two10(s.start / fps), two10(s.end / fps)], frames: shotSheetFile(k + 1), ...transition2 ? { transition: transition2 } : {}, in: into + path4 + part };
|
|
29105
29194
|
});
|
|
29106
29195
|
};
|
|
29107
29196
|
textPart = (m, text13) => {
|
|
@@ -30054,10 +30143,10 @@ var init_cloud2 = __esm({
|
|
|
30054
30143
|
if (has(head, 0, "RIFF") && has(head, 8, "WAVE")) return "audio/wav";
|
|
30055
30144
|
return has(head, 0, "ID3") || head[0] === 255 && ((head[1] ?? 0) & 224) === 224 ? "audio/mpeg" : null;
|
|
30056
30145
|
};
|
|
30057
|
-
readReference3 = async (rt, kind,
|
|
30058
|
-
const name = rt.path.basename(
|
|
30059
|
-
const bytes = await rt.fs.readFile(
|
|
30060
|
-
throw new GenerateError("The reference file " +
|
|
30146
|
+
readReference3 = async (rt, kind, path4, where3, what) => {
|
|
30147
|
+
const name = rt.path.basename(path4);
|
|
30148
|
+
const bytes = await rt.fs.readFile(path4).catch(() => {
|
|
30149
|
+
throw new GenerateError("The reference file " + path4 + " cannot be read; nothing was sent.", 2);
|
|
30061
30150
|
});
|
|
30062
30151
|
const mimeType2 = mediaType(kind, bytes.subarray(0, 16));
|
|
30063
30152
|
if (!mimeType2) throw new GenerateError(name + ' in "' + where3 + '" is not ' + what + "; nothing was sent.", 2);
|
|
@@ -30065,7 +30154,7 @@ var init_cloud2 = __esm({
|
|
|
30065
30154
|
};
|
|
30066
30155
|
readReferences = async (rt, request) => {
|
|
30067
30156
|
const out2 = [];
|
|
30068
|
-
for (const [kind, list7, what] of LISTS2) for (const
|
|
30157
|
+
for (const [kind, list7, what] of LISTS2) for (const path4 of request[list7] ?? []) out2.push(await readReference3(rt, kind, path4, list7, what));
|
|
30069
30158
|
const { firstFrame, lastFrame } = request;
|
|
30070
30159
|
if (firstFrame === void 0 && lastFrame === void 0) return out2;
|
|
30071
30160
|
if (out2.length) throw new GenerateError('"firstFrame" and "lastFrame" cannot be combined with "images", "videos" or "audios": a clip starts from a frame or follows references, not both. Nothing was sent.', 2);
|
|
@@ -30489,10 +30578,10 @@ var init_generate2 = __esm({
|
|
|
30489
30578
|
}
|
|
30490
30579
|
const frames = {};
|
|
30491
30580
|
for (const key2 of ["firstFrame", "lastFrame"]) {
|
|
30492
|
-
const
|
|
30493
|
-
if (
|
|
30494
|
-
if (typeof
|
|
30495
|
-
frames[key2] = userPath(rt,
|
|
30581
|
+
const path4 = data[key2];
|
|
30582
|
+
if (path4 === void 0) continue;
|
|
30583
|
+
if (typeof path4 !== "string" || !path4.trim()) throw new GenerateError('"' + key2 + '" is the path of a picture.', 2);
|
|
30584
|
+
frames[key2] = userPath(rt, path4);
|
|
30496
30585
|
}
|
|
30497
30586
|
return { prompt: data.prompt, ...seconds7 !== void 0 ? { seconds: seconds7 } : {}, ...aspect !== void 0 ? { aspect } : {}, ...lists, ...frames, ...data.audio === false ? { audio: false } : {}, ...data.priceOnly === true ? { priceOnly: true } : {} };
|
|
30498
30587
|
};
|
|
@@ -36482,17 +36571,17 @@ var init_stage = __esm({
|
|
|
36482
36571
|
const found = name ? leaves.map((leaf) => name + " " + leaf).find(unique3) : void 0;
|
|
36483
36572
|
if (found) return found;
|
|
36484
36573
|
}
|
|
36485
|
-
const
|
|
36574
|
+
const path4 = [];
|
|
36486
36575
|
let cur = el;
|
|
36487
36576
|
while (cur.parentElement && cur !== document.documentElement) {
|
|
36488
36577
|
const parent = cur.parentElement;
|
|
36489
|
-
|
|
36490
|
-
if (
|
|
36578
|
+
path4.unshift(part(cur, 1) + nth(cur));
|
|
36579
|
+
if (path4.length > 1 && unique3(path4.join(" > "))) return path4.join(" > ");
|
|
36491
36580
|
const a = anchor(parent);
|
|
36492
|
-
if (a && unique3(a + " > " +
|
|
36581
|
+
if (a && unique3(a + " > " + path4.join(" > "))) return a + " > " + path4.join(" > ");
|
|
36493
36582
|
cur = parent;
|
|
36494
36583
|
}
|
|
36495
|
-
return
|
|
36584
|
+
return path4.join(" > ");
|
|
36496
36585
|
};
|
|
36497
36586
|
const transparent = (c) => c === "transparent" || /rgba\([^)]*,\s*0(\.0+)?\)$/.test(c);
|
|
36498
36587
|
const paints = (el) => {
|
|
@@ -37657,10 +37746,10 @@ var SHELL_BUNDLE;
|
|
|
37657
37746
|
var init_shell_bundle = __esm({
|
|
37658
37747
|
"src/video/preview/shell-bundle.ts"() {
|
|
37659
37748
|
"use strict";
|
|
37660
|
-
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,be=(e,t,n)=>e*n/t,io=(e,t,n)=>Math.floor((e+.5)*n/t),q=e=>{if(e.resolved)return e.resolved.frames;let t=se(e),n=[e.measure,e.referenceMeasure].map(o=>o?Math.round(be(o.measure.source.frames,o.measure.source.fps,t)):0);return Math.max(0,...n)},me=(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),pe=(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",fe=(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]}},_t=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 _e={schema:null,status:null,problems:[],render:null,playRender:!1},Ve=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)})}},Vt=[.25,.5,1],Be=e=>e.state?q(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 l=Math.max(0,Be(a)-1),i=Math.min(l,t.frame+Math.floor((s-t.time)/1e3*lo(a)*a.speed));if(i>=l)return e.set({frame:l,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:me(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",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",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),ge=(e,t)=>T(e)&&Array.isArray(e[t])?e[t]:[],ee=e=>ge(e.source,"tracks").filter(T),te=e=>ge(e.source,"segments").filter(T),ye=(e,t)=>ge(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},W=(e,t)=>{if(!t||!T(e.source))return;let n=ge(e.source,"tracks");if(t.kind==="segment"){let i=gt(ge(e.source,"segments"),t.id),d=ge(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,l=n[a];return s&&T(l)&&s.index<ge(l,"cues").length?{kind:"cue",index:a,cue:s.index,track:l}: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},qt=(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}},ve=(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(l=>l.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}},Wt=(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(be(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"),l=Math.max(0,t-r.start),i=Math.max(l+1,Math.min(r.end-r.start,l+2*o.canvas.fps)),d={id:a,type:"text",text:n,box:[.1,.42,.8,.12],during:{segment:r.id,from:l,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=ge(t.track,"cues")[t.cue],s=e.resolved,a=s&&T(r)?ve(s,r.during):void 0;if(!T(r)||!s||!a||!T(r.during))return;let l=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:l}},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(m=>T(m)&&T(m.during)&&m.during.segment===o.id):[];if(!d.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)}:{},...d.length?{cues:d.map(m=>({...m,during:a(m.during)}))}:{}};s.push(c)}let l=n.map(i=>structuredClone(i));return l.splice(t+1,0,{...structuredClone(o),id:r}),{source:{...e.source,segments:l,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,l=a?.querySelector('[data-item="'+CSS.escape(String(o.id))+'"] > div');if(!a||!l||!r?.style)return t;let i=r.box[2]*e.resolved.canvas.width,d=r.box[3]*e.resolved.canvas.height,c=l.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 m=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<=d+.5&&c.scrollWidth<=i+.5);try{if(h(m))return t;let f=1,p=m;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(l=>l.id===t.id):t.kind==="audio"?o?.audio.find(l=>l.id===t.id):t.kind==="segment"||t.kind==="slot"?o?.segments.find(l=>l.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),l=r.end-r.start,i=String(a[0].id),d=f=>f<=r.start?f:f>=r.end?f-l:r.start,c=(f,p)=>({segment:i,from:d(f),to:d(p)}),m=ee(e),h=[];for(let f of m){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||d(R.end)<=d(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=ve(n,p.during),y=g?.start??b?.start??0,v=g?.end??b?.end??n.frames;if(d(v)<=d(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([...m,...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=W(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),l=o.kind==="cue"&&Array.isArray(a.cues)?a.cues[o.cue]:void 0,i=o.kind==="cue"?l: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 d=ve(r,i.during);if(!d||n<=d.start||n>=d.end)return;let c=i.during,m={...i,during:{...c,to:n-d.segment.start}},h={...i,during:{...c,from:n-d.segment.start}},f=ee(e).map(g=>structuredClone(g));if(o.kind==="cue")return a.cues.splice(o.cue,1,m,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-d.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-d.start)*(a.bed?(r.footage?.[String(a.material)]?.fps??r.canvas.fps)/r.canvas.fps:1))),delete m.exit,delete h.enter,f.splice(o.index,1,m,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}},qe=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:""}]}}},We=(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)},l=(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:me(e.get().frame,q(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"&&!W(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?W(f.state,f.pinned):void 0},d=(f,p,g)=>{n({saving:!0});let b=r.then(()=>xo(f,typeof p=="function"?p():p)).then(y=>(s=l(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)=>d("/api/edit",()=>tn(e.get().state,f),p),m=async()=>{for(;o.size;)await Promise.all([...o])},h=async f=>{if(document.activeElement instanceof HTMLElement&&document.activeElement.blur(),await m(),!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 d("/api/source",{source:p.source,base:f.state?.source})&&a(p.select)},replace:(f,p)=>d("/api/source",{source:f,base:p}),undo:async()=>{await m(),await d("/api/undo")},redo:async()=>{await m(),await d("/api/redo")},remove:()=>h(async(f,p)=>{if(p.kind==="segment"){let g=nn(f,p.index);g&&await d("/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 d("/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)),l=s.kind==="frame"?1/0:Math.abs(s.frame-(e.end+t)),i=a<=l&&a!==1/0?r.frame-e.start:l!==1/0?s.frame-e.end:Math.round(t),d=a<=l&&a!==1/0?r:l!==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=q(t),l=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+l)+" ("+(l>=0?"+":"")+l+")"+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,l=a?JSON.parse(a):void 0;if(l?.kind!=="item"&&l?.kind!=="audio")return;let i=W(e,l),d=i?ht(i):void 0,c=l.kind==="audio"?r.audio.find(p=>p.id===l.id):void 0,m=(i&&d?on(i):void 0)??(c?{segment:r.segments[0]?.id,from:c.start,to:c.end??r.frames}:void 0);if(!i||!m)return;let h=ve(r,m);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:m,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=q(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 l=n.track.getBoundingClientRect().width/Math.max(1,a);if(!Number.isFinite(l)||l<=0)return;let i=o.timeline?.snapping===!1?[]:Wt(s,o.frame,n.mode!=="border"),d=ko(n.mode==="border"?{mode:"end",start:n.start,end:n.end}:n,(r-n.x0)/l,i,l);if(n.mode!=="border")if(n.mode==="move"){let h=Math.min(a,n.end-n.start);d.start=Math.max(0,Math.min(a-h,d.start)),d.end=d.start+h}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 c=e.querySelector(".playhead-layer");if(!c)return;let m=d.snap.kind!=="frame"?d.snap.frame:n.mode==="end"||n.mode==="border"?d.end:d.start;c.append(Q(t.guide,m,a)),t.guide.classList.toggle("snapped",d.snap.kind!=="frame"),t.label.textContent=Mo(o.lang,s,n,d),c.append(Q(t.label,Math.min(m,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 c=i.target.closest("[data-sel]")?.dataset.sel;c&&n.select(JSON.parse(c));let m=c?JSON.parse(c):void 0;if(m?.kind==="segment"&&!i.target.closest(".seg-grip")){let h=d.resolved?.segments.findIndex(p=>p.id===m.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(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 c=a.track.getBoundingClientRect(),m=(i.clientX-c.left)/c.width*d.frames;a.to=Math.max(0,d.segments.findIndex(p=>m<p.end)),m>=d.frames&&(a.to=d.segments.length-1);let h=d.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,d.frames),Q(o.label,Math.min(h,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 l=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 d=r;if(r=void 0,[o.ghost,o.guide,o.label].forEach(h=>h.remove()),!d?.moved)return;s=!0,setTimeout(()=>{s=!1},0);let c=t.get().state;if(d.phrase)return n.note("phraseSpan");let m=c?Ro(d,c):void 0;m&&i.type!=="pointercancel"&&n.send(m)};e.addEventListener("pointerup",l),e.addEventListener("pointercancel",l),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,Se=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={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={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)},xe=(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){xe(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 he=(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 l=[];for(let i of Array.from(a.querySelectorAll("iframe"))){let d=i.contentDocument,c=i.contentWindow;if(!d||!c||i.parentElement?.dataset.segment!==s.id)continue;let m=i.getBoundingClientRect();if(!(!m.width||!m.height)&&c.getComputedStyle(i).visibility!=="hidden")for(let h of Array.from(d.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&&l.push({selection:{kind:"slot",id:s.id,name:b},box:[(m.left+g.left*m.width/(i.clientWidth||r.canvas.width))/r.canvas.width,(m.top+g.top*m.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 l},an=new WeakMap,He=(e,t,n)=>{let o=t.get(),r=o.state?.resolved?.segments.find(m=>m.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,l=a?.querySelector('[data-segment="'+CSS.escape(n)+'"] > iframe')?.contentDocument;if(!a||!l||l.URL==="about:blank"||l.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===l)return d.frames;let c=new Map;try{for(let m=0;m<=32;m++){let h=Math.min(r.end-1,r.start+Math.floor((r.end-r.start)*m/33));s.applyFrame(h);for(let f of he(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:l,frames:c}),c},Qe=(e,t,n)=>e&&he(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),l=$(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(h=>h.segment===o.id&&h.name===o.name);if(!d)return;let c=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"}});c.value=d.value;let m=h=>{let f=G($(G(e.get().state?.source).segments)[l]?.base);t.send({op:"set",path:["segments",l,"base","slots"],value:{...G(f.slots),[d.name]:h}})};if(c.addEventListener("change",()=>m(c.value)),c.addEventListener("keydown",h=>{let f=h;(f.ctrlKey||f.metaKey)&&f.key==="Enter"&&c.blur()}),d.kind==="image"){let h=G($(a.segments)[l]?.base),f=String(h.scene??""),p=new URL(d.value,location.origin+"/project/"+f);p.origin===location.origin&&p.pathname.startsWith("/project/")&&r.append(u("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=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:""}}),...g.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=g.find(v=>v.id===b.value);y&&m("../".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(u("details",{},[u("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 l=r;l&&(r=void 0,a&&l.dispatchEvent(new Event("commit")),l.remove())};e.addEventListener("studio:inline-edit",a=>{if(r)return;let l=n.get(),i=l.pinned;if(!i||!l.state||a.target.closest(".handle"))return;let d=W(l.state,i),c=i.kind==="item"?l.state.resolved?.items.find(g=>g.id===i.id):void 0,m=i.kind==="slot"?he(t,n).find(g=>g.selection.id===i.id&&g.selection.name===i.name):void 0;if(m?.image||d?.kind==="track"&&d.track.type==="image"){document.querySelector('#slot-inspector select, #edit-form select[data-path$=".material"]')?.focus();return}let h=m?.value??c?.text,f=m?.box??(d?Re(l.state,d):void 0);if(h===void 0||!f)return;s(!0),a.preventDefault(),a.stopPropagation();let p=u("textarea",{id:"stage-text-editor",class:"stage-text-editor",attrs:{"aria-label":l.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)*(l.state.resolved?.canvas.height??1)*e.clientWidth/(l.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 d?.kind==="cue"?o.send({op:"set",path:["tracks",d.index,"cues",d.cue,"text"],value:p.value}):d?.kind==="track"&&o.send({op:"set",path:["tracks",d.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,l)=>{(a.pinned!==l.pinned||a.state!==l.state||a.frame!==l.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 pe(n,e.frame).some(r=>r.id===o)},Io=(e,t,n,o,r,s)=>{let[a,l,i,d]=e.box0,c=(E,M)=>Math.round(E*M)/M;if(e.mode==="move")return[c(a+t,o),c(l+n,r),i,d];let[m,h,f,p]=[a,l,a+i,l+d];if(e.mode.includes("w")&&(m+=t),e.mode.includes("e")&&(f+=t),e.mode.includes("n")&&(h+=n),e.mode.includes("s")&&(p+=n),s){let E=i*o/(d*r),M=f-m,k=p-h;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")?h=p-L:(e.mode.includes("s")||(h=l+d/2-L/2),p=h+L)}else{let L=k*r*E/o;e.mode.includes("w")?m=f-L:(e.mode.includes("e")||(m=a+i/2-L/2),f=m+L)}}let[g,b,y,v]=[c(m,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:l}=$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]*l+"px",width:r[2]*a+"px",height:r[3]*l+"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,l=(o-s.top)/s.height;return[...pe(r,t.frame)].reverse().find(i=>a>=i.box[0]&&a<=i.box[0]+i.box[2]&&l>=i.box[1]&&l<=i.box[1]+i.box[3])?.id},zo=(e,t,n)=>{let o=t.state?W(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:l}=$e(t);e.readout.textContent=Fo(n,a,l)}},cn=e=>{let t=e.state?W(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"})]),l={layer:u("div",{class:"edit-layer",id:"edit-layer"},[r,s]),sel:r,readout:s};l.layer.append(a),e.append(l.layer),ln(e,t,n,o);let i=Do(t,n),d,c,m,h,f=!0,p=()=>{let v=n.get();zo(l,v,d&&!d.moved?void 0:m?.box);let E=v.pinned,M=E?.kind==="slot"?he(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(),m=void 0,p()})},b=(v,E)=>{m={box:E,target:v},i.move(v,E),p()};l.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"?he(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=he(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&&(d={mode:k??"move",x0:v.clientX,y0:v.clientY,box0:m?.box??H.box,moved:!1,target:H.t},l.layer.setPointerCapture(v.pointerId),v.preventDefault())}),l.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,m=void 0,c=void 0,i.restore(),p();return}let E=d;d=void 0,E&&!E.moved&&(c={time:performance.now(),x:E.x0,y:E.y0}),E?.moved&&m&&(c=void 0,g(E.target,m.box)),p()};return l.layer.addEventListener("pointerup",y),l.layer.addEventListener("pointercancel",y),n.subscribe((v,E)=>{v.state!==E.state&&i.forget(),(v.pinned!==E.pinned||v.state!==E.state)&&(f=!0),!d&&(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=m?.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),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:l=>(l.state?.edit?.undo??0)>0},{id:"edit-redo",icon:"redo",title:"redo",run:()=>{n.redo()},enabled:l=>(l.state?.edit?.redo??0)>0},{id:"edit-add-text",icon:"addText",title:"addText",run:()=>{n.addText()},enabled:l=>!!l.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:l=>{let i=n.target();return!!(i&&(i.kind!=="segment"||(l.state?.resolved?.segments.length??0)>1))}},{id:"edit-render",icon:"render",title:"renderTool",run:()=>{n.render()},enabled:l=>!!l.state?.resolved&&l.edit.render?.state!=="running"}].map(l=>{let i=u("button",{id:l.id,class:"tbtn",attrs:{type:"button"}},[Y(l.icon)]);return["edit-add-text","edit-duplicate","edit-delete"].includes(l.id)&&i.append(u("span",{class:"tool-label"})),i.addEventListener("click",()=>{l.run(),i.blur()}),{tool:l,el:i}}),s=(l,i)=>u("span",{class:"tool-group"},r.slice(l,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=l=>{for(let i of r){i.el.title=S(l.lang,i.tool.title);let d=i.el.querySelector(".tool-label");d&&(d.textContent=i.tool.id==="edit-add-text"?l.lang==="zh"?"\\u6587\\u5B57":"Text":i.tool.id==="edit-duplicate"?l.lang==="zh"?"\\u590D\\u5236":"Duplicate":l.lang==="zh"?"\\u5220\\u9664":"Delete"),i.el.setAttribute("aria-label",S(l.lang,i.tool.title)),i.el.disabled=!!l.edit.saving||!i.tool.enabled(l)}};a(t.get()),t.subscribe((l,i)=>{(l.state!==i.state||l.lang!==i.lang||l.pinned!==i.pinned||l.edit.render!==i.edit.render||l.edit.saving!==i.edit.saving)&&a(l)})},Bo={set:"saved",insert:"added",remove:"removed",move:"moved",outside:"outside"},_o=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},Vo=(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=_o(a),o.classList.toggle("bad",a.edit.status?.kind==="refused"),r.replaceChildren(...Vo(a,n,a.lang))};s(t.get()),t.subscribe((a,l)=>{(a.edit!==l.edit||a.lang!==l.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 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 l=a.audio;(l.length!==t.length||t.some((d,c)=>d.source!==l[c]?.src))&&(o(),n??=new AudioContext,t=l.map(d=>{let c=new Audio;c.crossOrigin="anonymous",c.preload="auto",c.src=Ce(d.src);let m=n.createGain();return n.createMediaElementSource(c).connect(m).connect(n.destination),{audio:c,gain:m,source:d.src}})),s.playing&&n?.state==="suspended"&&n.resume().catch(()=>{});let i=s.frame/a.canvas.fps;t.forEach((d,c)=>{let m=l[c];if(!m)return;d.gain.gain.value=s.muted?0:10**((m.gain-pn(m.duck,s.frame))/20);let h=s.frame>=m.start&&(m.end===void 0||s.frame<m.end),f=Math.max(0,(i-m.start/a.canvas.fps)*(m.speed??1)+(m.from?m.from.frame/m.from.fps:0));d.audio.playbackRate=s.speed*(m.speed??1),h&&!d.audio.seeking&&Math.abs(d.audio.currentTime-f)>.2&&(d.audio.currentTime=f),s.playing&&h&&!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),l=[];for(let i=0;i<500;i++){let d=Math.floor(i*a.length/500),c=Math.floor((i+1)*a.length/500),m=0;for(let h=d;h<c;h+=8)m=Math.max(m,Math.abs(a[h]??0));l.push(m)}return l}finally{await o.close()}})();return fn.set(e,n),n};var En=" \\xB7 ",Ne=e=>({sel:JSON.stringify(e)}),ce=(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),qo=(e,t,n)=>ce("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"}),Wo=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 l=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"})),l&&i.prepend(u("span",{class:"swatch",style:"background:"+l}));let d=a.transition;if(!d)return a.index===0?[i]:[i,Q(u("div",{class:"tick"}),a.start,r)];let c=Nt(d),m=ae("band",d.a,d.a+d.frames,r,"",c+": mixed frames "+d.a+".."+(d.a+d.frames-1)+", takes over at "+d.boundary,{kind:"segment",id:a.id});return m.append(u("span",{class:"band-label",text:c})),[i,m,Q(u("div",{class:"tick"}),a.start,r)]});return ce("segments",S(t,"segments"),n?[...s,...Wo(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 ce("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 c=document.createElementNS(d.namespaceURI,"path");c.setAttribute("d",i.map((m,h)=>"M"+h+" "+(14-Math.max(1,m*13))+"v"+Math.max(2,m*26)).join("")),c.setAttribute("stroke","#69967c"),c.setAttribute("stroke-width","0.8"),d.append(c),a.append(d),a.classList.add("wave-ready")}).catch(()=>{});let l=["start","end"].map(i=>Q(u("div",{class:"grip "+i,data:{grip:i,...Ne(r)}}),i==="start"?e.start:e.end??t,t));return ce("audio-"+e.id,S(n,"audio"),[a,...o?l:[]],{labelSel:r})},Go=(e,t,n)=>ce("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=>be(i,s.source.fps,o),l=s.boundaries.flatMap((i,d)=>{let c={kind:"boundary",source:t,index:d},m=It(i),h=m+": frames "+i.start+".."+i.end+" of the measured file, takes over at "+i.frame,f=Q(u("div",{class:"mark",title:h,data:Ne(c)},[u("span",{class:"mark-label",text:m})]),a(i.frame),n);return i.kind==="cut"?[f]:[ae("mband",a(i.start+1),a(i.end),n,"",h,c),f]});return ce(t+"-boundaries",S(r,t==="render"?"renderBoundaries":"referenceBoundaries"),l,{cls:"measure "+t})},Sn=14,Xo=4,Zo=(e,t,n,o,r)=>{let s=e.measure,a=Ft(s).map(c=>({start:be(c.event.start,s.source.fps,o),end:be(c.event.end,s.source.fps,o),value:c})),l=mt(a,Xo),i=l.map(c=>{let m=ze(c.value.event),h=ae("ev",c.start,c.end,n,m,m+": 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}),d=Math.max(1,...l.map(c=>c.row+1));return ce(t+"-events",S(r,t==="render"?"renderEvents":"referenceEvents"),i,{cls:"measure "+t,height:6+d*Sn})},Qo=(e,t,n)=>{let o=q(e),r=se(e),s=e.resolved,a=e.edit!==void 0,l=[qo(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",l.push(i);let d=[{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?[]:d){let m=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,...m.map(f=>f.row+1));for(let f=0;f<h;f++){let p=m.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});l.push(ce(c.id+"-"+f,c.label+(f?" "+(f+1):""),p,{cls:c.cls}))}}if(n.timeline?.layers!==!1)for(let c of n.slots??[]){let m=s.segments.find(g=>g.id===c.segment);if(!m)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",m.start,m.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),l.push(ce("slot-"+c.segment+"-"+c.name,t==="zh"?"\\u573A\\u666F\\u5185\\u5BB9":"Scene content",[p],{cls:"caption-lane"}))}l.push(...s.audio.map(c=>vn(c,o,t,!0)))}else l.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&&l.push(Yo(i,d,o,r,t),Zo(i,d,o,r,t));return l},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=c=>c.state?q(c.state):0,l=c=>{Le(r,c.frame,c.frame+1,a(c))},i=c=>{o.querySelectorAll("[data-sel]").forEach(m=>{m.setAttribute("aria-pressed",String(c.pinned!==null&&fe(JSON.parse(m.dataset.sel??"null"),c.pinned))),m.classList.toggle("selected",c.pinned!==null&&fe(JSON.parse(m.dataset.sel??"null"),c.pinned))})},d=c=>{o.replaceChildren(...c.state?Qo(c.state,c.lang,c):[],s),l(c),i(c)};o.addEventListener("click",c=>{let m=c.target,h=m.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=m.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=m.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 m=c.target.closest("[data-sel]");m&&(c.preventDefault(),m.click())}),e.addEventListener("wheel",c=>{c.shiftKey&&!c.deltaX&&(e.scrollLeft+=c.deltaY,c.preventDefault())},{passive:!1}),d(t.get()),t.subscribe((c,m)=>{if(c.state!==m.state||c.lang!==m.lang||c.timeline?.layers!==m.timeline?.layers||c.slots!==m.slots?d(c):c.frame!==m.frame&&l(c),c.pinned!==m.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=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(\`
|
|
37661
|
-
\`).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 l=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,...l?[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:"")}))])},V=(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,l=e.state.resolved?.segments.find(h=>h.id===s.segment),i=h=>h==="from"?0:h==="to"&&l?l.end-l.start:void 0,d=(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 V(r,[[{kind:"text",label:"fPhrase",path:[...t,"phrase"],value:s.phrase,wide:!0}],[d("occurrence","fOccurrence"),d("lead","fLead"),d("hold","fHold")]],e,c);let m={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 V(r,[[m,d("from","fFrom"),d("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 l=["tracks",t.index,"cues",a],i=e.state.resolved?.items.find(m=>m.id===o+"#"+a),d={kind:"textarea",label:S(e.lang,"fCue")+" "+a,path:[...l,"text"],value:T(s)?s.text:void 0},c=V("#"+a,[[d]],e,[Tt(e,[...l,"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 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??""),l=e.schema.transition,i=o?.transition,d=(p,g,b,y)=>({kind:b,label:g,path:[...r,p],value:s?.[p],resolved:i?.[p==="transition"?"kind":p],range:Se(j(l,p)),options:y??X(j(l,p)),step:p==="strength"?.1:void 0}),c={kind:"select",label:"fKind",path:[...r,"transition"],value:s?.transition,options:X(j(l,"transition")),empty:S(e.lang,"fHardCut"),commit:p=>p===void 0?e.commit(r,void 0):e.commit([...r,"transition"],p)},m=ar(a,e),h=Rn.includes(a),f=[[c,s&&a!=="cut"?d("frames","fFrames","number"):null],[m.length?d("direction","fDirection","select",m):null,a==="slide"?d("mode","fMode","select"):null,a==="fade"?d("via","fVia","select"):null],[h?d("side","fSide","select"):null,s&&a!=="cut"?d("ease","fEase","select"):null,s&&a!=="cut"?d("strength","fStrength","number"):null]];return V(S(e.lang,"fTransition"),f.filter(p=>p.some(g=>g!==null)),e)},dr=(e,t,n)=>{let o=e.schema.base,r=ye(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:{},c=Object.entries(d).filter(m=>typeof m[1]=="string").map(([m,h])=>[{kind:"textarea",label:m,path:[...t,"slots",m],value:h,wide:!0}]);return V(S(e.lang,"fBaseScene"),[[a],...c],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 V(S(e.lang,"fBase"),[[a,d]],e)}let l=ye(e.state,["video"]).includes(String(n.material)),i=(d,c,m)=>({kind:"number",label:c,path:[...t,d],value:n[d],range:Se(j(o,d)),...m?{step:m}:{}});return V(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"))},...l?[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=V(e.lang==="zh"?"\\u955C\\u5934\\u65F6\\u957F":"Shot duration",[[s]],e,o?[Pn(e,o.start,o.end)]:[]),l=t.segment;return[a,...t.index>0?[ir(e,n,l.in,o)]:[],...T(l.base)?[dr(e,[...n,"base"],l.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),l=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(l?.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)},m=(p,g,b={})=>({kind:g,label:"f"+p[0]?.toUpperCase()+p.slice(1),path:[...r,p],value:l?.[p],resolved:o?.[p],commit:c(p),range:Se(j(s,p)),options:X(j(s,p)),...b}),h={kind:"select",label:"fNamed",path:r,value:typeof n=="string"?n:l?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=m("font","select",{value:l?.font??o?.font,options:[...new Set([String(l?.font??o?.font??"sans-serif"),...ye(e.state,["font"]),"sans-serif","serif","monospace"])],label:e.lang==="zh"?"\\u5B57\\u4F53":"Font",wide:!0});return V(S(e.lang,"fStyle"),[[f],[h,d],[m("color","color",{label:"fColour"}),m("weight","number",{step:100}),m("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,l=T(o)?o:void 0,i=(m,h,f)=>({kind:h,label:f,path:[...s,m],value:l?.[m],resolved:r?.[m],disabled:!l,range:Se(j(a,m)),options:X(j(a,m))}),d={kind:"select",label:"fPreset",path:[...s,"preset"],value:l?.preset,options:X(j(a,"preset")),empty:S(e.lang,"fNone"),commit:m=>m===void 0?e.commit(s,void 0):e.commit([...s,"preset"],m)},c=lr.has(String(l?.preset??""));return V(S(e.lang,n==="enter"?"fEnter":"fExit"),[[d,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:Se(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,l)=>{let i=[...t,"box",l],d=l%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:c=>e.commit(i,Number(c)/d)})});return V(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)=>V(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 m=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 V(S(e.lang,"fShape"),[[Ie(e,[...t,"shape"],"fShape",X(j(s,"shape")),{empty:null}),m,a]],e)}if(r!=="image"&&r!=="video")return null;let l=Ie(e,[...t,"material"],"fMaterial",ye(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")}),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 V(S(e.lang,r==="video"?"fFootage":"fPicture"),[[l,i],[a,d,...c]],e)},mr=(e,t)=>{let n=V(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 V(S(e.lang,"fAudio"),[[Ie(e,[...t,"material"],"fMaterial",ye(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),l=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,l)]},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:_t(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?pe(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=W(t,e.pinned);if(s){let a={lang:e.lang,problems:e.edit.problems,state:t,schema:r,commit:(l,i)=>{let d=qt(t.source,l,i);d&&n.send(d)},set:(l,i)=>{n.send({op:"set",path:l,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"}),l=u("section",{id:"measures"}),i=u("section",{id:"notes"});e.append(r,s,a,l,i);let d="",c="",m=f=>{let p=f.state,g=p?.resolved&&!f.pinned?[Z(p.resolved,f.frame)?.id,pe(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===d)return;let v=JSON.stringify(f.pinned)!==c;c=JSON.stringify(f.pinned),d=y;let E=r.contains(document.activeElement)?document.activeElement.dataset.path:void 0,M=f.pinned?[u("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"),[u("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?u("ul",{},p.problems.map(b=>br(b,g))):u("p",{class:"muted",text:S(g,"noProblems")})),a.replaceChildren(Fe(S(g,"score")),p.score?vr(p.score,g):u("p",{class:"muted",text:S(g,"noScore")})),l.replaceChildren(Fe(S(g,"measurements")),...Sr(p,g)),i.hidden=!p.notes,i.replaceChildren(Fe(S(g,"notes")+" ("+(p.notes?.length??0)+")"),u("ul",{},(p.notes??[]).map(b=>u("li",{class:"note-item"},[u("code",{text:b.at})," ",u("b",{text:b.kind}),u("div",{text:b.message})]))))};h(t.get()),m(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)&&m(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=(l,i)=>{let d=e.querySelector(l+" > img");d&&n.push({img:d,play:i,active:!1})};t.segments.forEach(l=>{l.base.kind==="video"&&o('[data-segment="'+CSS.escape(l.id)+'"]',l.base.play)}),t.items.forEach(l=>{l.play&&o('[data-item="'+CSS.escape(l.id)+'"]',l.play)});let r=(l,i)=>{if(l.video)return;let d=t.footage?.[l.play.material],c=l.img.parentElement;if(!d||!c)return;let m=e.createElement("video");m.muted=!0,m.playsInline=!0,m.preload="auto",m.hidden=!0,m.style.display="none",m.dataset.previewVideo=l.play.material;let h=Lt(l.play,d,t.canvas.fps,Math.max(i,l.play.start))/d.fps;m.addEventListener("loadedmetadata",()=>{m.paused&&m.isConnected&&(m.currentTime=h)},{once:!0}),m.src="/project/"+d.src.split("/").map(encodeURIComponent).join("/"),c.append(m),l.video=m},s=l=>{l.video?.pause(),l.video?.removeAttribute("src"),l.video?.load(),l.video?.remove(),l.video=void 0,l.active=!1,l.img.style.visibility=""};return{sync:(l,i,d)=>{let c=n.filter(m=>m.play.start>l).sort((m,h)=>m.play.start-h.play.start).slice(0,2);for(let m of n)c.includes(m)||m.img.parentElement?.style.display!=="none"?r(m,l):m.video&&s(m);for(let m of n){let h=t.footage?.[m.play.material],f=m.img.parentElement;if(!(i&&!!h&&!!f&&f.style.display!=="none")){m.video?.pause(),m.video&&(m.video.hidden=!0,m.video.style.display="none"),m.img.style.visibility="",m.active=!1;continue}if(!h||!f)continue;let g=m.video;g.hidden=!1,g.style.cssText=m.img.style.cssText+";position:absolute;inset:0;pointer-events:none;",m.img.style.visibility=g.readyState>=2?"hidden":"",g.style.visibility=g.readyState>=2?"":"hidden";let b=Lt(m.play,h,t.canvas.fps,l)/h.fps,y=d*m.play.speed;g.playbackRate=Math.max(.0625,Math.min(16,y));let v=m.active?.25:1/h.fps;!g.seeking&&Math.abs(g.currentTime-b)>v&&(g.currentTime=b),l<m.play.start||b>=(h.frames-1)/h.fps?g.pause():g.paused&&g.play().catch(()=>{}),m.active=!0}},dispose:()=>{n.forEach(s)}}};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=(e.root.clientWidth-24-(n?16:0))/(n?2:1),r=e.root.clientHeight-16-e.render.caption.offsetHeight-e.render.note.offsetHeight-8,s=t.state?.resolved?.canvas;if(e.render.box.classList.toggle("problems",!s),s){let c=Bn(s.width,s.height,o,r);e.render.box.style.cssText="width:"+s.width*c+"px;height:"+s.height*c+"px;",e.scaler.style.cssText="width:"+s.width+"px;height:"+s.height+"px;transform:scale("+c+");"}else e.render.box.style.cssText="width:"+Math.max(0,o)+"px;height:"+Math.max(0,r)+"px;",e.scaler.style.cssText="width:100%;height:100%;";if(!n)return;let a=t.state?.referenceMeasure?.measure.source,l=e.video.videoWidth||a?.width||s?.width||16,i=e.video.videoHeight||a?.height||s?.height||9,d=Bn(l,i,o,r);e.reference.box.style.cssText="width:"+l*d+"px;height:"+i*d+"px;"},_n=(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 pe(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&&(_n(e.render.overlay,o.measure?.measure,t.frame,r),_n(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,"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")},Vn=(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,l,i=()=>{let c=n;if(!c)return;let m=t.get(),h=m.frame,f=++s;(c.preparePreview?.(h)??Promise.resolve()).then(async()=>{f===s&&(m.playing&&c.previewFrame&&a?c.previewFrame(h):c.applyFrame(h),a?.sync(h,m.playing,m.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!==l&&(l=y,document.dispatchEvent(new Event("studio:scene-ready")))})};return e.addEventListener("load",()=>{let c=++r,m=e.contentWindow?.__popostVideo;if(n=void 0,l=void 0,!m){document.body.dataset.ready="error";return}(m.preparePreview?.(t.get().frame)??m.prepare()).then(()=>null,f=>f instanceof Error?f.message:String(f)).then(f=>{if(c!==r)return;n=m;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?"/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 l=wr(o,t);new ResizeObserver(()=>Rt(a,t.get())).observe(e),s.addEventListener("loadedmetadata",()=>{Rt(a,t.get()),Vn(s,t.get(),t.get(),!0)});let i="";return t.subscribe((d,c)=>{let m=kr(d);m!==i&&(i=m,m&&!a.reference.root.isConnected&&e.append(a.reference.root),m||a.reference.root.remove(),m?s.src=m:s.removeAttribute("src")),d.state&&d.state.generation!==l.loaded()&&l.load(d.state.generation),(d.frame!==c.frame||d.playing!==c.playing||d.speed!==c.speed)&&l.apply(),(d.frame!==c.frame||d.overlays!==c.overlays||d.state!==c.state)&&xr(a,d,n),(d.frame!==c.frame||d.playing!==c.playing||d.speed!==c.speed)&&Vn(s,d,c,!1),(d.compare!==c.compare||d.lang!==c.lang||d.state!==c.state||d.pageError!==c.pageError||d.edit!==c.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"},Vt.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=l=>()=>{t.pause(),l()},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?q(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 l of r.segments){let i=l.base,d=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,l.id),"studio-shot "+(fe(t.get().pinned,{kind:"segment",id:l.id})?"selected":""));c.append(sn(l.start+Math.floor((l.end-l.start)/2),o?.generation??0),u("span",{class:"studio-shot-copy"},[u("strong",{text:String(l.index+1).padStart(2,"0")+" "+l.id}),u("small",{text:d+" \\xB7 "+((l.end-l.start)/r.canvas.fps).toFixed(2)+"s"})])),c.dataset.selection=JSON.stringify({kind:"segment",id:l.id}),c.draggable=!!o?.edit,c.addEventListener("dragstart",m=>m.dataTransfer?.setData("application/x-popost-segment",String(l.index))),c.addEventListener("dragover",m=>m.preventDefault()),c.addEventListener("drop",m=>{m.preventDefault();let h=Number(m.dataTransfer?.getData("application/x-popost-segment"));Number.isInteger(h)&&h!==l.index&&n.send({op:"move",path:["segments",h],to:l.index})}),s.append(c)}let a=Oe("",x(t,"search"));return a.placeholder=x(t,"search"),a.addEventListener("input",()=>s.querySelectorAll(".studio-shot").forEach(l=>{l.hidden=!l.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 l=t.kind,i=String(t.id);if(!n&&["image","video"].includes(String(l))){await r.send({op:"set",path:["segments",a.index,"base"],value:{material:i,fit:"cover"}});return}let d=$(G(s.source).tracks),c=["audio","voice","speech"].includes(String(l))?"audio":l;if(!["image","video","audio"].includes(String(c)))return;let m={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",d.length],value:m},{kind:c==="audio"?"audio":"item",id:m.id})},qn=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){xe(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),l=Ce(String(s.file??"")),i=s.kind==="image"?u("img",{attrs:{src:l,alt:a,loading:"lazy"}}):s.kind==="video"?u("video",{attrs:{src:l,controls:"",preload:"metadata"}}):u("audio",{attrs:{src:l,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])},Wn=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,l)=>{a.type==="caption"&&$(a.cues).forEach((i,d)=>{s.push(String(i.text));let c=o?.resolved?.items.find(b=>b.cue?.track===a.id&&b.cue?.index===d),m=u("textarea",{class:"studio-input",attrs:{"aria-label":x(t,"subtitles")+" "+(d+1),rows:"2"}});m.value=String(i.text),m.addEventListener("change",()=>{n.send({op:"set",path:["tracks",l,"cues",d,"text"],value:m.value}),xe(t,x(t,"pendingVoice"))});let h=c?{kind:"item",id:c.id}:void 0,f=()=>{h&&n.reveal(h)};m.addEventListener("focus",f);let p=C(Ze(c?.start??0,o?.resolved?.canvas.fps??30),f),g=u("article",{class:"studio-sentence"+(h&&fe(h,t.get().pinned)?" selected":""),data:h?{selection:JSON.stringify(h)}:{}},[p,m]);g.addEventListener("click",f),r.append(g)})}),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(\`
|
|
37662
|
-
\`)).then(()=>
|
|
37663
|
-
\`+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,l=!1,i,d=()=>{s=e.get().state?.source,n.value=JSON.stringify(s,null,2)??"",a=!1,o.textContent=x(e,"autosave")},c=async()=>{if(!a||l)return;let p;try{p=JSON.parse(n.value)}catch(y){o.textContent=x(e,"invalid")+": "+(y instanceof Error?y.message:"");return}l=!0,o.textContent=x(e,"saving");let g=n.value,b=await t.replace(p,s);l=!1,b?(s=e.get().state?.source,a=g!==n.value,o.textContent=x(e,"sourceChanged"),a&&setTimeout(()=>{m()},0)):o.textContent=e.get().edit.problems[0]?.message??x(e,"conflict")},m=()=>r??=c().finally(()=>{r=void 0});n.addEventListener("input",()=>{a=!0,i&&clearTimeout(i),i=setTimeout(()=>{m()},650)}),n.addEventListener("keydown",p=>{(p.ctrlKey||p.metaKey)&&p.key.toLowerCase()==="s"&&(p.preventDefault(),m()),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=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"),h),C(x(e,"download"),()=>rn(n.value,"video.json"))]),n,o,C(x(e,"reload"),d)]);return e.subscribe((p,g)=>{p.state?.source!==g.state?.source&&(!a&&!l?d():!l&&JSON.stringify(p.state?.source)!==JSON.stringify(s)&&(o.textContent=x(e,"conflict")))}),d(),{root:f,flush:async()=>(clearTimeout(i),r&&await r,a&&await m(),!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,l,i,d="push",c="",m="",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)=>u("span",{class:"studio-cloud-state"+(D?" bad":""),text:O,attrs:{role:"status"},title:l?.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=>{l={code:"NETWORK",message:O instanceof Error?O.message:String(O)}},M=async()=>{try{a=await J("/api/cloud/status")}catch{}p&&(F(),clearTimeout(g),(!a||i||a?.state==="waiting"||a?.state==="uploading"||a?.mode==="keyed"&&a.state==="idle"&&a.dirty)&&(g=setTimeout(()=>{M()},2e3)))},k=async()=>{if(i)return;let O=window.open("about:blank","_blank");d="start",l=void 0,f=!1,i="start",F();try{if(!await n()){O?.close(),l={code:"LOCAL_SAVE_FAILED",message:""};return}m=(await J("/api/studio/cloud/start",{lang:t.get().lang})).result.authorizeUrl,h=!O,O&&(O.opener=null,O.location.href=m),d="push",await M()}catch(D){O?.close(),E(D)}finally{i=void 0,await M()}},H=async(O=!1)=>{if(!i){d="push",l=void 0,i="push",F();try{if(!await n()){l={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(m),f=!0}catch{h=!0}F()},R=()=>{let O=l?.code??a?.error?.code;d==="start"||a?.mode==="anonymous"&&(O==="LOGIN_REQUIRED"||O==="UNAUTHORIZED")?k():H()},F=()=>{let O=JSON.stringify([a,l,i,m,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":l?"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&&m){let w=u("input",{class:"studio-cloud-link",attrs:{readonly:"","aria-label":r("\\u767B\\u5F55\\u94FE\\u63A5","Login link")}});w.value=m,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(l?.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{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)),l=r.filter(p=>a.has(String(p.track.id))),i=l.findIndex(p=>p.index===t.index),d=l[i+n];if(!d)return;let c=r.findIndex(p=>p.index===t.index),m=r.indexOf(d);if(c<0||m<0||m>=r.length)return;let h=r.splice(c,1)[0];r.splice(m,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=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=(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},l=a("layers",s?"\\u56FE\\u5C42":"Layers");l.prepend(Y("layers"));let i=a("snapping",s?"\\u5438\\u9644":"Snap"),d=C(s?"\\u5206\\u5272":"Split",()=>{n.split()});d.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)}}),m=c(-1),h=c(1);m.id="scene-earlier",h.id="scene-later";let f=u("span",{id:"timeline-selection",class:"timeline-selection"});e.append(u("span",{id:"edit-slot"}),d,m,h,u("span",{class:"timeline-divider"}),l,i,f,u("span",{class:"spacer"}),C(x(t,"viewAll"),()=>{o.value="100",r()}),o);let p=()=>{let g=t.get(),b=n.target();l.classList.toggle("selected",g.timeline?.layers!==!1),i.classList.toggle("selected",g.timeline?.snapping!==!1),l.setAttribute("aria-pressed",String(g.timeline?.layers!==!1)),i.setAttribute("aria-pressed",String(g.timeline?.snapping!==!1)),d.disabled=!!g.edit.saving||!n.canSplit(),m.hidden=h.hidden=!b||b.kind!=="segment"&&b.track.type==="audio",m.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",m.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&&(m.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&&(d.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(),l.remove(),document.getElementById("studio-export-open")?.focus())},l=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.")),c=u("div",{attrs:{role:"status"}}),m=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=m.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(),xe(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=m.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(u("div",{class:"studio-export-header"},[U(o("\\u5DF2\\u5BFC\\u5165","Imported into ")+r),h]),d,c,u("div",{class:"studio-draft-actions"},[m,...t.canOpen?[p]:[]])),document.body.append(l,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:m).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,_)=>r?P:_,a="video",l="jianying",i="1080",d="",c="",m=!1,h=!1,f,p=!1,g,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=()=>{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=u("div",{class:"studio-scrim",on:{click:R}}),D=(P,_,I)=>u("div",{class:"studio-segments"},P.map(([ue,de])=>{let Ot=C(de,()=>I(ue),ue===_?"selected":"");return Ot.setAttribute("aria-pressed",String(ue===_)),Ot})),w=(P,_)=>(_.setAttribute("role","group"),_.setAttribute("aria-label",P),u("div",{class:"studio-field"},[u("span",{text:P}),_])),N=()=>{if(v.hidden=a!=="video",H.replaceChildren(...[["video",x(e,"video")],["draft",s("\\u526A\\u6620","Draft")]].map(([I,ue])=>{let de=C(ue,()=>{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."))]),ue=g?.find(de=>de.target===l);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"]],l,de=>{l=de,b=void 0,N(),B()})),I),g?ue?.usable||k.append(A(ue?.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()}),_=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"),_])),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"])],c,x(e,"bitrate"),I=>{c=I}))),v.replaceChildren(),!m){let I=P.lastElementChild;I&&I.append(u("span",{class:"export-pro",text:"PRO"}))}i==="2160"&&!m&&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=>{m=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:l,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:d?Number(d):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,_=h||a==="video"&&P?.state==="running";if(k.disabled=_,z.disabled=_||a==="video"&&i==="2160"&&!m||a==="draft"&&!g?.find(I=>I.target===l)?.usable,K.disabled=h,H.querySelectorAll("button").forEach(I=>{I.disabled=_}),M.hidden=!_,z.textContent=_?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,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=>{m=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,_)=>{L.isConnected&&P.edit.render!==_.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"}),l=Qn(t,o),i=l.root,d={store:t,actions:n,edit:o,meta:{hash:"",slots:[],versions:[],comments:[]},refresh:()=>{}},c=()=>{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:qn,script:Wn,elements:Gn,checks:Yn,versions:Xn};a.replaceChildren(B[r](d))},m=w=>{r=w,c()};for(let[w,N,z]of Ar){let B=u("button",{data:{panel:w},attrs:{type:"button",title:x(t,N)},on:{click:()=>m(w)}},[Y(z),u("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;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),c()}catch{}};d.refresh=()=>{h()},e.prepend(s,a);let f=document.querySelector(".studio-topbar"),p=u("strong",{class:"studio-brand",text:"popost"}),g=u("span",{class:"studio-project"}),b=u("span",{class:"studio-save"}),y=u("span",{class:"studio-global-actions"}),v=ne(x(t,"compare"),"compare",()=>{t.get().edit.playRender&&o.togglePlayRender(),t.set({compare:!t.get().compare})}),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",()=>m("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 l.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=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)),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?W(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,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:m,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",l=parseFloat(getComputedStyle(document.documentElement).getPropertyValue(a)),i=c=>{let m=(n?c.clientY:c.clientX)-s,h=Math.min(n?innerHeight*.65:innerWidth*.4,Math.max(n?150:210,l+(t==="left"?m:-m)));document.documentElement.style.setProperty(a,h+"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 c=u("span");return{name:i,input:d,text:c,el:u("label",{class:"toggle"},[d,c])}}),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 l=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(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 l(e.get()),e.subscribe((i,d)=>{(i.state!==d.state||i.lang!==d.lang||i.connected!==d.connected||i.overlays!==d.overlays)&&l(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),qe(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=Ve({state:null,frame:0,playing:!1,speed:1,lang:e,pinned:null,overlays:{boxes:!1,events:!0,safe:!1},connected:!0,pageError:null,edit:_e}),n=Ke(t),o=We(t,n),r=document.getElementById("app")??document.body,s=u("div",{class:"stage-area",id:"stage"}),a=u("div",{class:"transport",id:"transport"}),l=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,l]),i]));let d=dt(s,t,n);lt(a,t,n),rt(l,t,n),it(i,t,n,o);let c=new EventSource("/api/events"),m=!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:me(t.get().frame,q(f)),connected:!0}),f.edit&&!m&&(m=!0,Nr({store:t,edit:o,stage:d,lanes:l.querySelector("#lanes")??l,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=Ve({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:_e}),r=Ke(o),s=We(o,r),a=document.getElementById("app")??document.body,l=u("header",{class:"studio-topbar"}),i=u("div",{class:"stage-area",id:"stage"}),d=u("div",{class:"transport",id:"transport"}),c=u("div",{class:"timeline",id:"timeline"}),m=u("aside",{class:"panel",id:"panel"}),h=u("div",{class:"main"},[u("div",{class:"left"},[u("div",{id:"studio-stage-heading",class:"studio-stage-heading"}),i,d]),m]),f=u("div",{class:"studio-timeline-toolbar"}),p=u("div",{class:"studio-timeline-wrap"},[f,c]),g=u("footer",{class:"studio-footer"},["Popost Video Studio","video.json"]);a.append(l,h,p,g,u("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(d,o,r),rt(c,o,r),it(m,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:me(H.frame,q(k)),connected:!0}),k.edit&&!v){v=!0,document.body.classList.add("editing"),tt(document.getElementById("edit-slot"),o,s),nt(m,o,s);let L=et(b.frameBox,b.iframe,o,s);Ge(c.querySelector("#lanes")??c,o,s),ot(o,s,L.nudge),qe(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();})();
|
|
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();})();
|
|
37664
37753
|
`;
|
|
37665
37754
|
}
|
|
37666
37755
|
});
|
|
@@ -37847,7 +37936,7 @@ body.studio{font:13px/1.45 'Helvetica Neue','PingFang SC',system-ui,sans-serif;b
|
|
|
37847
37936
|
.studio #app{grid-template-rows:48px minmax(240px,1fr) var(--timeline-height) 24px;height:100dvh}.studio .main{display:grid;grid-template-rows:minmax(0,1fr);grid-template-columns:64px var(--left-width) minmax(0,1fr) var(--right-width);min-height:0;position:relative}.studio .left{overflow:hidden;min-height:0;min-width:0;display:flex;flex-direction:column}.studio .panel{width:auto;min-width:0;overflow:auto;background:var(--pc-surface);border-left:1px solid var(--pc-border);padding:12px 16px}.studio .panel>#problems,.studio .panel>#score,.studio .panel>#measures,.studio .panel>#notes{display:none}.studio .panel h2{font-size:12px;color:var(--pc-muted)}.studio .sel-title{font-size:13px;padding-bottom:10px;border-bottom:1px solid var(--pc-border);color:var(--pc-text);overflow-wrap:anywhere}.studio .status-line{font-size:11px;max-height:80px;overflow:auto}.studio #render-status{display:none}
|
|
37848
37937
|
.studio-topbar{display:flex;align-items:center;gap:12px;padding:0 16px;background:var(--pc-surface-2);border-bottom:1px solid var(--pc-border);min-width:0;white-space:nowrap}.studio-brand{font-size:23px;font-weight:800;letter-spacing:-1.3px;margin-right:8px}.studio-brand:after{content:'\u2022';color:var(--pc-accent);font-size:15px;vertical-align:top;letter-spacing:0}.studio-project{min-width:80px;max-width:30%;overflow:hidden;text-overflow:ellipsis;flex:1}.studio-save{font-size:11px;color:var(--pc-muted)}.studio-save:before{content:'\u25CF';font-size:9px;color:#2e9e6b;margin-right:7px}.studio-actions{display:flex;align-items:center;gap:6px;flex-wrap:wrap}.studio-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;min-height:32px;padding:5px 10px;border:1px solid var(--pc-border);border-radius:8px;background:var(--pc-surface);text-decoration:none;font-size:12px;cursor:pointer}.studio-btn:hover{background:var(--pc-hover)}.studio-btn.primary{background:#292929;color:#fff;border-color:#292929}.dark .studio-btn.primary{background:#f2f2f0;color:#222}.studio-btn.selected{background:var(--pc-accent-soft);border-color:#ffb47c;color:#c76520}.studio-btn.ghost{border-color:transparent;background:transparent}.studio .tbtn{height:30px;min-width:30px;border:0;background:transparent;border-radius:7px}.studio .tbtn:hover{background:var(--pc-hover)}.studio #edit-render{display:none}.studio .edit-tools{gap:6px}.studio .tool-group{gap:2px}
|
|
37849
37938
|
.studio-rail{min-height:0;overflow-y:auto;display:flex;flex-direction:column;gap:5px;padding:12px 5px;background:var(--pc-surface-2);border-right:1px solid var(--pc-border)}.studio-rail button{height:57px;flex:none;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:4px;background:transparent;border:0;border-radius:8px;color:var(--pc-muted);font-size:11px;cursor:pointer}.studio-rail button.active{background:var(--pc-accent-soft);color:#e8711c}.studio-rail svg{width:19px;height:19px}.studio-content{min-height:0;overflow:auto;background:var(--pc-surface);border-right:1px solid var(--pc-border)}.studio-side-body{padding:14px 14px 20px;display:flex;flex-direction:column;gap:12px}.studio-heading{display:flex;align-items:center;justify-content:space-between;gap:8px;min-height:24px}.studio-heading h2{margin:0;font-size:14px;font-weight:600;color:var(--pc-text)}.studio-heading small{font-size:10px;color:var(--pc-muted)}.studio-note{font-size:11px;line-height:1.7;color:var(--pc-muted);margin:0;overflow-wrap:anywhere}.studio-note.notice{padding:10px;border:1px solid #f0d5b9;border-radius:8px;background:var(--pc-accent-soft);color:#9a5c2d}.studio-note.bad{color:var(--err)}.studio-input{border:1px solid var(--pc-border);border-radius:7px;background:var(--pc-surface-2);width:100%;min-height:34px;padding:7px 9px;resize:vertical;min-width:0}.studio-field{display:flex;flex-direction:column;gap:6px;font-size:11px;color:var(--pc-muted)}.studio-field .studio-input{font-size:12px;color:var(--pc-text)}.studio-field-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}
|
|
37850
|
-
.studio-shot-list{display:flex;flex-direction:column;gap:7px}.studio-shot{width:100%;min-height:70px;justify-content:flex-start;text-align:left;padding:7px;gap:10px}.studio-thumb{display:block;width:74px;height:55px;object-fit:cover;border-radius:5px;background:var(--pc-stage);flex:none}.studio-shot-copy{display:flex;flex-direction:column;min-width:0;gap:7px}.studio-shot-copy strong{font-size:12px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:145px}.studio-shot-copy small{font-size:10px;color:var(--pc-muted)}.studio-media-list{display:grid;gap:12px}.studio-media-card,.studio-review-card,.studio-sentence{border:1px solid var(--pc-border);border-radius:8px;padding:10px;display:flex;flex-direction:column;gap:9px}.studio-media-card>img,.studio-media-card>video{width:100%;max-height:150px;object-fit:contain;background:var(--pc-stage);border-radius:5px}.studio-media-card>audio{width:100%;height:30px}.studio-media-card>strong{font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.studio-media-card .studio-btn{font-size:10px;padding:4px 6px}.studio-script-list{display:flex;flex-direction:column;gap:8px}.studio-sentence>button{align-self:flex-start;font-size:10px;min-height:24px}.studio-sentence textarea{font-size:12px}.studio-item{justify-content:flex-start;overflow-wrap:anywhere;text-align:left}.studio-slot-image{max-width:100%;max-height:150px;object-fit:contain}.studio-stage-heading{display:flex;align-items:center;justify-content:space-between;height:40px;flex:none;padding:0 18px;background:var(--pc-surface-2);border-bottom:1px solid var(--pc-border);font-size:12px}.studio-stage-heading small{font-size:10px;color:var(--pc-muted)}.studio .stage-area{min-height:0!important;padding:14px 18px;gap:14px;background:var(--pc-stage);min-height:160px}.studio .frame-box{box-shadow:0 2px 7px #0002,0 12px 30px #0001}.studio .caption{font-size:11px}.studio .note{font-size:10px;max-width:350px}.studio .transport{height:76px;min-height:76px;flex-wrap:wrap;align-content:center;background:var(--pc-surface-2);padding:4px 12px;gap:7px}.studio .transport .readout{font-size:11px;gap:8px;order:2;flex:1 0 calc(100% - 100px)}.studio .transport #jump{order:3;width:80px;font-size:10px}.studio .transport .speed{order:1;font-size:10px}.studio .transport .tbtn{min-width:24px;padding:0 4px}.studio .transport #back10,.studio .transport #fwd10{display:none}.studio .transport .slider-wrap{min-width:50px}
|
|
37939
|
+
.studio-shot-list{display:flex;flex-direction:column;gap:7px}.studio-shot{width:100%;min-height:70px;justify-content:flex-start;text-align:left;padding:7px;gap:10px}.studio-thumb{display:block;width:74px;height:55px;object-fit:cover;border-radius:5px;background:var(--pc-stage);flex:none}.studio-shot-copy{display:flex;flex-direction:column;min-width:0;gap:7px}.studio-shot-copy strong{font-size:12px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:145px}.studio-shot-copy small{font-size:10px;color:var(--pc-muted)}.studio-media-list{display:grid;gap:12px}.studio-media-card,.studio-review-card,.studio-sentence{border:1px solid var(--pc-border);border-radius:8px;padding:10px;display:flex;flex-direction:column;gap:9px}.studio-media-card>img,.studio-media-card>video{width:100%;max-height:150px;object-fit:contain;background:var(--pc-stage);border-radius:5px}.studio-media-card>audio{width:100%;height:30px}.studio-media-card>strong{font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.studio-media-card .studio-btn{font-size:10px;padding:4px 6px}.studio-script-list{display:flex;flex-direction:column;gap:8px}.studio-sentence>button{align-self:flex-start;font-size:10px;min-height:24px}.studio-sentence textarea{font-size:12px}.studio-item{justify-content:flex-start;overflow-wrap:anywhere;text-align:left}.studio-slot-image{max-width:100%;max-height:150px;object-fit:contain}.studio-stage-heading{display:flex;align-items:center;justify-content:space-between;height:40px;flex:none;padding:0 18px;background:var(--pc-surface-2);border-bottom:1px solid var(--pc-border);font-size:12px}.studio-stage-heading small{font-size:10px;color:var(--pc-muted)}.studio .stage-area{min-height:0!important;padding:14px 18px;gap:14px;background:var(--pc-stage);min-height:160px}.studio .stage-area.comparing{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-items:center;gap:16px}.studio .stage-area.comparing .viewer{width:100%;min-height:0;align-self:stretch;justify-content:center;padding:8px;border:1px solid var(--pc-border);border-radius:10px;background:var(--pc-surface-2)}.studio .stage-area.comparing .caption{width:100%;font-weight:600;color:var(--pc-text);padding:0 4px 5px}.studio .stage-area.comparing .note{width:100%;padding-inline:4px}.studio .frame-box{box-shadow:0 2px 7px #0002,0 12px 30px #0001}.studio .caption{font-size:11px}.studio .note{font-size:10px;max-width:350px}.studio .transport{height:76px;min-height:76px;flex-wrap:wrap;align-content:center;background:var(--pc-surface-2);padding:4px 12px;gap:7px}.studio .transport .readout{font-size:11px;gap:8px;order:2;flex:1 0 calc(100% - 100px)}.studio .transport #jump{order:3;width:80px;font-size:10px}.studio .transport .speed{order:1;font-size:10px}.studio .transport .tbtn{min-width:24px;padding:0 4px}.studio .transport #back10,.studio .transport #fwd10{display:none}.studio .transport .slider-wrap{min-width:50px}
|
|
37851
37940
|
.studio-timeline-wrap{position:relative;display:flex;flex-direction:column;min-height:0;border-top:1px solid var(--pc-border);background:var(--pc-surface)}.studio-timeline-toolbar{height:39px;flex:none;display:flex;align-items:center;gap:8px;padding:0 14px;border-bottom:1px solid var(--pc-border);background:var(--pc-surface-2)}.studio-timeline-toolbar .spacer{flex:1}.studio-timeline-toolbar input[type=range]{width:105px;accent-color:var(--pc-accent)}.studio .timeline{min-height:0;flex:1;max-height:none;overflow:auto}.studio .lanes{--label:160px;width:calc(100% * var(--timeline-zoom,1));min-width:100%;padding-bottom:9px}.studio .lane{height:34px;border-color:var(--pc-border)}.studio .lane-label{position:sticky;left:0;z-index:9;background:var(--pc-surface);line-height:33px;font-size:11px;padding-left:15px}.studio .ruler{height:28px;background:var(--pc-surface-2);position:sticky;top:0;z-index:10}.studio .ruler .lane-label{background:var(--pc-surface-2);line-height:27px}.studio .rtick{font-size:10px;color:var(--pc-muted)}.studio .lane.segments{height:70px}.studio .blk.seg{height:58px;top:5px;bottom:auto;line-height:13px;padding:0 4px;border:1px solid #aebfcb;background:#e8eef3;color:#4c6474}.studio .blk.seg img{display:block;position:absolute;left:0;top:0;width:100%;height:39px;object-fit:cover;pointer-events:none}.studio .blk.seg .segment-name{position:absolute;bottom:1px;left:4px;right:2px;font-size:9px;overflow:hidden;text-overflow:ellipsis}.studio .blk.seg.selected{border:2px solid var(--pc-accent);background:#fff0e2}.studio .blk.item{background:#eee8fa;color:#8c70a9;border:1px solid #d8c9ef;font-size:10px;top:5px;bottom:5px}.studio .lane.caption-lane .blk.item{background:#f5efdf;color:#8e7950;border-color:#e6dcc1}.studio .lane.caption-lane .blk.selected{border-color:var(--pc-accent)}.studio .blk.audio{background:#e7f2e9;color:#537b60;border:1px solid #b3d1bd;top:5px;bottom:5px;font-size:10px}.studio .blk.audio.wave-ready{color:transparent}.studio .blk.audio svg{width:100%;height:100%;position:absolute;inset:0;pointer-events:none}.studio .measure,.studio .lane.words-lane{display:none}.studio.show-analysis .measure,.studio.show-analysis .lane.words-lane{display:grid}.studio .band{z-index:2;opacity:.7}.studio .seg-grip{height:66px;top:2px}.studio .playhead{background:#292929;min-width:1px}.studio .selected{outline-color:var(--pc-accent)}
|
|
37852
37941
|
.studio-footer{height:24px;background:var(--pc-surface-2);border-top:1px solid var(--pc-border);display:flex;align-items:center;justify-content:space-between;padding:0 14px;font-size:10px;color:var(--pc-muted)}.studio-handle{position:absolute;z-index:15;touch-action:none}.studio-handle.vertical{width:5px;top:0;bottom:0;cursor:col-resize}.studio-handle.horizontal{height:5px;left:0;right:0;top:-3px;cursor:row-resize}.studio-handle:hover{background:var(--pc-accent);opacity:.35}.studio.focus-preview .main{grid-template-columns:64px 0 minmax(0,1fr) 0}.studio.focus-preview .studio-content,.studio.focus-preview .panel{visibility:hidden;padding:0;overflow:hidden}.studio.panel-code{--left-width:min(480px,35vw)}
|
|
37853
37942
|
.studio-code-wrap{display:flex;flex-direction:column;gap:10px;height:100%;padding:14px}.studio-json{flex:1;min-height:240px;white-space:pre;overflow:auto;resize:none;width:100%;font:12px/1.65 ui-monospace,SFMono-Regular,Menlo,monospace!important;border:1px solid var(--pc-border);border-radius:8px;background:var(--pc-surface-2);padding:12px;tab-size:2}.studio-code-status{font-size:11px;color:var(--pc-muted);overflow-wrap:anywhere}.studio-scrim{position:fixed;inset:0;background:#0003;z-index:80}.studio-export{position:fixed;right:0;top:0;bottom:0;width:440px;max-width:100vw;overflow:auto;padding:18px 22px;background:var(--pc-surface);z-index:81;box-shadow:-12px 0 40px #0002;display:flex;flex-direction:column;gap:18px}.studio-export-header{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--pc-border);padding-bottom:14px}.studio-export-fields{border:0;margin:0;padding:0;display:flex;flex-direction:column;gap:16px;min-width:0}.studio-export-fields>.studio-field{display:grid;grid-template-columns:95px 1fr;align-items:center;gap:12px;font-size:13px}.studio-segments{display:flex;padding:3px;background:var(--pc-bg);border-radius:8px;gap:3px}.studio-segments button{flex:1;border:0;background:transparent;border-radius:6px;padding:7px}.studio-segments button.selected{background:var(--pc-surface);color:var(--pc-text)}.studio-resolutions{display:grid;grid-template-columns:repeat(3,1fr);gap:5px}.studio-resolutions button{position:relative;padding:5px;min-width:0}.export-gem{color:var(--pc-accent);display:inline-flex;align-items:center;justify-content:center;font-size:20px;line-height:15px;margin-left:3px}.studio-paid-info:empty{display:none}.studio-paid-info{border:1px solid #e9cfb8;background:var(--pc-accent-soft);border-radius:8px;padding:10px;font-size:11px}.studio-paid-info a{color:#df711e;margin-right:12px}.studio-paid-info p{color:var(--pc-text);margin-bottom:6px}.studio-check{display:flex;align-items:center;gap:8px;font-size:12px}.studio-check input{accent-color:var(--pc-accent)}.studio-export>progress{width:100%;accent-color:var(--pc-accent)}.studio-export-result{display:flex;gap:10px;flex-direction:column}.studio-export-result:empty{display:none}#studio-message{position:fixed;left:50%;bottom:35px;transform:translateX(-50%);max-width:min(650px,85vw);padding:11px 16px;background:#292929;color:white;box-shadow:0 5px 20px #0003;border-radius:8px;z-index:100;opacity:0;pointer-events:none;font-size:12px}#studio-message.visible{opacity:1}
|
|
@@ -38051,7 +38140,7 @@ var init_ops = __esm({
|
|
|
38051
38140
|
FORBIDDEN = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
38052
38141
|
isObj3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
38053
38142
|
isIndex = (k) => typeof k === "number" && Number.isInteger(k) && k >= 0;
|
|
38054
|
-
refuse2 = (
|
|
38143
|
+
refuse2 = (path4, message2, fix2) => ({ level: "error", at: path4.length ? pathText(path4) : "(root)", message: message2, fix: fix2 });
|
|
38055
38144
|
KEY_RE = /\[(\d+)\]|([^.[\]]+)/g;
|
|
38056
38145
|
parsePath = (text13) => {
|
|
38057
38146
|
const keys2 = Array.from(text13.matchAll(KEY_RE), (m) => m[1] !== void 0 ? Number(m[1]) : m[2] ?? "");
|
|
@@ -38067,32 +38156,32 @@ var init_ops = __esm({
|
|
|
38067
38156
|
readOp = (body) => {
|
|
38068
38157
|
if (!isObj3(body) || typeof body.op !== "string" || !OP_KINDS.includes(body.op))
|
|
38069
38158
|
return { problem: { level: "error", at: "(request)", message: 'The body is not an edit operation: "op" must be one of ' + OP_KINDS.join(", ") + ".", allowed: [...OP_KINDS], fix: OP_FIX } };
|
|
38070
|
-
const
|
|
38071
|
-
if (typeof
|
|
38072
|
-
if (
|
|
38073
|
-
const forbidden =
|
|
38074
|
-
if (forbidden !== void 0) return { problem: refuse2(
|
|
38159
|
+
const path4 = readPath(body.path);
|
|
38160
|
+
if (typeof path4 === "string") return { problem: { level: "error", at: "(request)", message: "The operation cannot be applied: " + path4 + ".", fix: OP_FIX } };
|
|
38161
|
+
if (path4.length === 0 || path4.length > MAX_DEPTH) return { problem: refuse2(path4, "The path must name a field inside the project, at most " + MAX_DEPTH + " keys deep.", 'Name the field, for example ["tracks", 0, "text"].') };
|
|
38162
|
+
const forbidden = path4.find((k) => typeof k === "string" && FORBIDDEN.has(k));
|
|
38163
|
+
if (forbidden !== void 0) return { problem: refuse2(path4, 'The key "' + String(forbidden) + '" is not a field of video.json.', "Use the names of the project format only.") };
|
|
38075
38164
|
const kind = body.op;
|
|
38076
|
-
if ((kind === "set" || kind === "insert") && !("value" in body)) return { problem: refuse2(
|
|
38077
|
-
if (kind === "move" && !isIndex(body.to)) return { problem: refuse2(
|
|
38165
|
+
if ((kind === "set" || kind === "insert") && !("value" in body)) return { problem: refuse2(path4, '"' + kind + '" needs a "value".', kind === "set" ? 'Add "value", or use "remove" to delete the field.' : 'Add "value": the entry to insert.') };
|
|
38166
|
+
if (kind === "move" && !isIndex(body.to)) return { problem: refuse2(path4, '"move" needs "to", a whole index from 0.', 'Add "to": the index the entry should have afterwards.') };
|
|
38078
38167
|
switch (kind) {
|
|
38079
38168
|
case "set":
|
|
38080
38169
|
case "insert":
|
|
38081
|
-
return { op: { op: kind, path:
|
|
38170
|
+
return { op: { op: kind, path: path4, value: body.value } };
|
|
38082
38171
|
case "remove":
|
|
38083
|
-
return { op: { op: kind, path:
|
|
38172
|
+
return { op: { op: kind, path: path4 } };
|
|
38084
38173
|
case "move":
|
|
38085
|
-
return { op: { op: kind, path:
|
|
38174
|
+
return { op: { op: kind, path: path4, to: body.to } };
|
|
38086
38175
|
}
|
|
38087
38176
|
};
|
|
38088
38177
|
kindOf4 = (v) => Array.isArray(v) ? "a list" : isObj3(v) ? "an object" : v === void 0 ? "nothing" : "a " + (v === null ? "null" : typeof v) + " value";
|
|
38089
|
-
walk2 = (json4,
|
|
38178
|
+
walk2 = (json4, path4) => {
|
|
38090
38179
|
let node2 = json4;
|
|
38091
|
-
for (let i = 0; i <
|
|
38092
|
-
const key2 =
|
|
38093
|
-
const here =
|
|
38180
|
+
for (let i = 0; i < path4.length - 1; i++) {
|
|
38181
|
+
const key2 = path4[i];
|
|
38182
|
+
const here = path4.slice(0, i + 1);
|
|
38094
38183
|
if (Array.isArray(node2) ? !(isIndex(key2) && key2 < node2.length) : !(isObj3(node2) && typeof key2 === "string" && Object.hasOwn(node2, key2)))
|
|
38095
|
-
return { problem: refuse2(here, "There is nothing at " + pathText(here) + ": " + (i > 0 ? pathText(
|
|
38184
|
+
return { problem: refuse2(here, "There is nothing at " + pathText(here) + ": " + (i > 0 ? pathText(path4.slice(0, i)) : "the project") + " is " + kindOf4(node2) + (Array.isArray(node2) ? " of " + node2.length + " entries" : "") + ".", "Set the nearest field that exists, with the whole value under it.") };
|
|
38096
38185
|
node2 = Array.isArray(node2) ? node2[key2] : node2[key2];
|
|
38097
38186
|
}
|
|
38098
38187
|
return { parent: node2 };
|
|
@@ -38133,9 +38222,9 @@ var init_ops = __esm({
|
|
|
38133
38222
|
if (op.op === "remove") return Object.fromEntries(Object.entries(obj3).filter(([k]) => k !== key2));
|
|
38134
38223
|
return { ...obj3, [key2]: op.value };
|
|
38135
38224
|
};
|
|
38136
|
-
replaceAt = (node2,
|
|
38137
|
-
if (
|
|
38138
|
-
const [key2, ...rest] =
|
|
38225
|
+
replaceAt = (node2, path4, fn) => {
|
|
38226
|
+
if (path4.length === 0) return fn(node2);
|
|
38227
|
+
const [key2, ...rest] = path4;
|
|
38139
38228
|
if (Array.isArray(node2)) return node2.map((x, j) => j === key2 ? replaceAt(x, rest, fn) : x);
|
|
38140
38229
|
return { ...node2, [key2]: replaceAt(node2[key2], rest, fn) };
|
|
38141
38230
|
};
|
|
@@ -38146,13 +38235,13 @@ var init_ops = __esm({
|
|
|
38146
38235
|
if (problem4) return { problem: problem4 };
|
|
38147
38236
|
return { json: replaceAt(json4, op.path.slice(0, -1), (parent) => changeLast(op, parent)) };
|
|
38148
38237
|
};
|
|
38149
|
-
valueAt = (json4,
|
|
38238
|
+
valueAt = (json4, path4) => path4.reduce((node2, k) => Array.isArray(node2) ? node2[k] : isObj3(node2) ? Object.hasOwn(node2, String(k)) ? node2[String(k)] : void 0 : void 0, json4);
|
|
38150
38239
|
ID_LISTS = /* @__PURE__ */ new Set(["tracks", "segments", "materials"]);
|
|
38151
|
-
labelOf2 = (json4,
|
|
38152
|
-
const [list7, index, ...rest] =
|
|
38240
|
+
labelOf2 = (json4, path4) => {
|
|
38241
|
+
const [list7, index, ...rest] = path4;
|
|
38153
38242
|
const entry2 = typeof list7 === "string" && ID_LISTS.has(list7) && typeof index === "number" ? valueAt(json4, [list7, index]) : void 0;
|
|
38154
38243
|
const id2 = isObj3(entry2) && typeof entry2.id === "string" ? entry2.id : void 0;
|
|
38155
|
-
if (id2 === void 0) return pathText(
|
|
38244
|
+
if (id2 === void 0) return pathText(path4);
|
|
38156
38245
|
return rest.length ? id2 + (typeof rest[0] === "number" ? "" : ".") + pathText(rest) : id2;
|
|
38157
38246
|
};
|
|
38158
38247
|
opLabel = (before, after, op) => op.op === "remove" ? labelOf2(before, op.path) : op.op === "move" ? labelOf2(after, [...op.path.slice(0, -1), op.to]) : labelOf2(after, op.path);
|
|
@@ -38531,6 +38620,41 @@ var init_routes = __esm({
|
|
|
38531
38620
|
}
|
|
38532
38621
|
});
|
|
38533
38622
|
|
|
38623
|
+
// src/video/preview/reference.ts
|
|
38624
|
+
var REFERENCE_INFO, referenceDescriptor, savedReference, prepareReference;
|
|
38625
|
+
var init_reference = __esm({
|
|
38626
|
+
"src/video/preview/reference.ts"() {
|
|
38627
|
+
"use strict";
|
|
38628
|
+
init_files();
|
|
38629
|
+
REFERENCE_INFO = ".studio/reference.json";
|
|
38630
|
+
referenceDescriptor = (rt, dir, file) => {
|
|
38631
|
+
const relative = rt.path.relative(dir, file).replace(/\\/g, "/");
|
|
38632
|
+
const inside6 = relative && !relative.startsWith("../") && !rt.path.isAbsolute(relative);
|
|
38633
|
+
return { name: rt.path.basename(file), ...inside6 ? { url: "/project/" + relative.split("/").map(encodeURIComponent).join("/") } : {} };
|
|
38634
|
+
};
|
|
38635
|
+
savedReference = async (rt, dir) => {
|
|
38636
|
+
const info = rt.path.join(dir, REFERENCE_INFO);
|
|
38637
|
+
if (!await rt.fs.stat(info)) return void 0;
|
|
38638
|
+
const data = JSON.parse(await rt.fs.readText(info));
|
|
38639
|
+
if (typeof data.file !== "string" || rt.path.isAbsolute(data.file)) return void 0;
|
|
38640
|
+
const file = await resolveInside(rt, dir, data.file);
|
|
38641
|
+
return file && (await rt.fs.stat(file))?.isFile ? file : void 0;
|
|
38642
|
+
};
|
|
38643
|
+
prepareReference = async (rt, dir, explicit) => {
|
|
38644
|
+
if (!explicit) return savedReference(rt, dir);
|
|
38645
|
+
const source2 = rt.path.resolve(rt.cwd, explicit);
|
|
38646
|
+
const relative = ".studio/reference/" + rt.path.basename(source2);
|
|
38647
|
+
const target2 = rt.path.join(dir, relative);
|
|
38648
|
+
if (source2 !== target2) {
|
|
38649
|
+
if (rt.fs.copyFile) await rt.fs.copyFile(source2, target2);
|
|
38650
|
+
else await rt.fs.writeFile(target2, await rt.fs.readFile(source2));
|
|
38651
|
+
}
|
|
38652
|
+
await rt.fs.writeFile(rt.path.join(dir, REFERENCE_INFO), JSON.stringify({ file: relative }));
|
|
38653
|
+
return target2;
|
|
38654
|
+
};
|
|
38655
|
+
}
|
|
38656
|
+
});
|
|
38657
|
+
|
|
38534
38658
|
// src/video/preview/project.ts
|
|
38535
38659
|
var RENDER_MEASURE_NAMES, REFERENCE_MEASURE_NAMES, NOTES_FILE2, PROJECT_FILE2, PROJECT_URL_PREFIX, readJson5, isRecord4, measureShapeError, MEASURE_FIX, findMeasure, loadMeasure, isNote, loadNotes2, scoreOf, materialFiles, withUrl, withProjectUrls, pageOf, safeBuild, loadAll, createLoader;
|
|
38536
38660
|
var init_project3 = __esm({
|
|
@@ -38539,6 +38663,7 @@ var init_project3 = __esm({
|
|
|
38539
38663
|
init_compile();
|
|
38540
38664
|
init_score();
|
|
38541
38665
|
init_html();
|
|
38666
|
+
init_reference();
|
|
38542
38667
|
RENDER_MEASURE_NAMES = ["measure.json", "render.measure.json", "replica.measure.json"];
|
|
38543
38668
|
REFERENCE_MEASURE_NAMES = ["reference.measure.json", "reference-measure.json", "truth.json"];
|
|
38544
38669
|
NOTES_FILE2 = "draft-notes.json";
|
|
@@ -38631,8 +38756,8 @@ var init_project3 = __esm({
|
|
|
38631
38756
|
footage: Object.fromEntries(Object.entries(r.footage ?? {}).map(([id2, f]) => [id2, { ...f, src: withUrl(f.src), ...f.dir === void 0 ? {} : { dir: withUrl(f.dir) } }])),
|
|
38632
38757
|
fonts: (r.fonts ?? []).map((f) => ({ ...f, src: withUrl(f.src) }))
|
|
38633
38758
|
});
|
|
38634
|
-
pageOf = async (resolved, problems2, dir) => resolved ? { status: 200, html: await compilePage(withProjectUrls(resolved)) } : { status: 422, html: errorPageHtml(problems2, dir) };
|
|
38635
|
-
safeBuild = (rt, dir) => buildPage(rt, dir, { fetchEffects: true }).catch((e) => ({
|
|
38759
|
+
pageOf = async (resolved, problems2, dir) => resolved ? { status: 200, html: await compilePage(withProjectUrls(resolved), { nativeFootage: true }) } : { status: 422, html: errorPageHtml(problems2, dir) };
|
|
38760
|
+
safeBuild = (rt, dir) => buildPage(rt, dir, { fetchEffects: true, nativeFootage: true }).catch((e) => ({
|
|
38636
38761
|
problems: [{ level: "error", at: "(root)", message: "Building the page failed: " + (e instanceof Error ? e.message : String(e)), fix: 'Run "popost video check ' + dir + '" and report the failure if check passes.' }]
|
|
38637
38762
|
}));
|
|
38638
38763
|
loadAll = async (rt, o, generation) => {
|
|
@@ -38656,7 +38781,7 @@ var init_project3 = __esm({
|
|
|
38656
38781
|
referenceMeasure,
|
|
38657
38782
|
score,
|
|
38658
38783
|
notes: notes2,
|
|
38659
|
-
reference: o.reference ?
|
|
38784
|
+
reference: o.reference ? referenceDescriptor(rt, dir, o.reference) : null,
|
|
38660
38785
|
messages,
|
|
38661
38786
|
...o.edit ? { source: raw.value ?? null } : {}
|
|
38662
38787
|
};
|
|
@@ -39360,28 +39485,28 @@ var init_studio_actions = __esm({
|
|
|
39360
39485
|
init_lifecycle();
|
|
39361
39486
|
init_targets();
|
|
39362
39487
|
TYPES2 = { ".png": "image", ".jpg": "image", ".jpeg": "image", ".webp": "image", ".mp4": "video", ".webm": "video", ".mov": "video", ".mp3": "audio", ".m4a": "audio", ".wav": "audio", ".ogg": "audio" };
|
|
39363
|
-
studioAction = async (rt, dir, editor, state,
|
|
39364
|
-
if (
|
|
39488
|
+
studioAction = async (rt, dir, editor, state, path4, body) => {
|
|
39489
|
+
if (path4 === "/api/studio/draft") {
|
|
39365
39490
|
if (typeof body.requestId !== "string") throw new Error("Reload this editor page to use direct Jianying Pro or CapCut export.");
|
|
39366
39491
|
return exportNativeDraft(rt, dir, JSON.parse(await editor.snapshot()), readTarget(body.target), body.requestId);
|
|
39367
39492
|
}
|
|
39368
|
-
if (
|
|
39493
|
+
if (path4 === "/api/studio/draft-targets") return { applications: await Promise.all(["jianying", "capcut"].map(async (target2) => {
|
|
39369
39494
|
try {
|
|
39370
39495
|
return await detectDraftApplication(rt, target2);
|
|
39371
39496
|
} catch (error2) {
|
|
39372
39497
|
return { target: target2, usable: false, supported: true, running: false, error: String(error2) };
|
|
39373
39498
|
}
|
|
39374
39499
|
})) };
|
|
39375
|
-
if (
|
|
39376
|
-
if (
|
|
39377
|
-
if (
|
|
39500
|
+
if (path4 === "/api/studio/draft-open") return openNativeDraft(rt, dir, String(body.receiptId ?? ""));
|
|
39501
|
+
if (path4 === "/api/studio/version") return saveVersion(rt, dir, JSON.parse(await editor.snapshot()), String(body.name ?? "Version"));
|
|
39502
|
+
if (path4 === "/api/studio/restore") {
|
|
39378
39503
|
const source2 = await readVersion(rt, dir, String(body.id));
|
|
39379
39504
|
const result = await editor.replace(source2, body.base);
|
|
39380
39505
|
if (!result.ok) throw new Error(result.problems[0]?.message);
|
|
39381
39506
|
return result;
|
|
39382
39507
|
}
|
|
39383
|
-
if (
|
|
39384
|
-
if (
|
|
39508
|
+
if (path4 === "/api/studio/comment") return saveComment(rt, dir, body, state.resolved?.frames ?? 0);
|
|
39509
|
+
if (path4 === "/api/studio/import") {
|
|
39385
39510
|
const ext = rt.path.extname(String(body.name ?? "")).toLowerCase();
|
|
39386
39511
|
const kind = TYPES2[ext];
|
|
39387
39512
|
if (!kind || typeof body.data !== "string" || !/^[A-Za-z0-9+/]*={0,2}$/.test(body.data)) throw new Error("Choose a PNG, JPEG, WebP, video or audio file.");
|
|
@@ -39568,17 +39693,20 @@ var init_cloud3 = __esm({
|
|
|
39568
39693
|
init_api();
|
|
39569
39694
|
init_files();
|
|
39570
39695
|
init_extract();
|
|
39696
|
+
init_reference();
|
|
39571
39697
|
object3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
39572
39698
|
rows2 = (v) => Array.isArray(v) ? v.map(object3) : [];
|
|
39573
39699
|
hashes = /* @__PURE__ */ new Map();
|
|
39574
39700
|
MAX_FILE = 250 * 1024 * 1024;
|
|
39575
39701
|
projectFiles = async (rt, dir, source2) => {
|
|
39576
39702
|
const pending3 = [...rows2(object3(source2).materials).flatMap((m) => [m.file, m.words].filter((v) => typeof v === "string")), ...rows2(object3(source2).segments).flatMap((s) => typeof object3(s.base).scene === "string" ? [String(object3(s.base).scene)] : [])];
|
|
39703
|
+
const reference2 = await savedReference(rt, dir);
|
|
39704
|
+
if (reference2) pending3.push(REFERENCE_INFO, rt.path.relative(dir, reference2));
|
|
39577
39705
|
const seen = /* @__PURE__ */ new Set(), files = [];
|
|
39578
39706
|
while (pending3.length) {
|
|
39579
|
-
const
|
|
39580
|
-
const absolute = await resolveInside(rt, dir,
|
|
39581
|
-
if (!absolute) throw new Error("Cloud save: project dependency is outside the project: " +
|
|
39707
|
+
const path4 = pending3.shift();
|
|
39708
|
+
const absolute = await resolveInside(rt, dir, path4);
|
|
39709
|
+
if (!absolute) throw new Error("Cloud save: project dependency is outside the project: " + path4);
|
|
39582
39710
|
const relative = rt.path.relative(dir, absolute).replace(/\\/g, "/");
|
|
39583
39711
|
if (seen.has(relative)) continue;
|
|
39584
39712
|
seen.add(relative);
|
|
@@ -39593,7 +39721,7 @@ var init_cloud3 = __esm({
|
|
|
39593
39721
|
hashes.set(absolute, { signature: signature2, hash: hash5 });
|
|
39594
39722
|
}
|
|
39595
39723
|
files.push({ path: relative, hash: hash5, bytes: stat2.size, absolute });
|
|
39596
|
-
if (/\.(html?|css|js)$/i.test(
|
|
39724
|
+
if (/\.(html?|css|js)$/i.test(path4)) {
|
|
39597
39725
|
const text13 = await rt.fs.readText(absolute);
|
|
39598
39726
|
const refs = [...text13.matchAll(/(?:src|href)\s*=\s*["']([^"']+)["']|url\(\s*["']?([^"')]+)|(?:import\s*.*?from\s*|import\s*|import\()?["'](\.[^"']+\.(?:js|css))["']/g)].map((m) => m[1] ?? m[2] ?? m[3] ?? "");
|
|
39599
39727
|
for (const ref of refs) {
|
|
@@ -39606,26 +39734,29 @@ var init_cloud3 = __esm({
|
|
|
39606
39734
|
return files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
39607
39735
|
};
|
|
39608
39736
|
createVideoCloud = (rt, dir, state, enabled = true) => {
|
|
39609
|
-
const
|
|
39737
|
+
const path4 = rt.path.join(dir, ".studio", "cloud.json");
|
|
39610
39738
|
let queue = Promise.resolve();
|
|
39611
|
-
const scope2 = () =>
|
|
39739
|
+
const scope2 = () => {
|
|
39740
|
+
const current = rt.refreshAccount ? { ...rt, ...rt.refreshAccount() } : rt;
|
|
39741
|
+
return sha256(new PopostClient(current).baseUrl + "|" + (current.credentialScope ?? current.env.POPOST_API_KEY ?? "browser-or-device"));
|
|
39742
|
+
};
|
|
39612
39743
|
const read2 = async () => {
|
|
39613
39744
|
try {
|
|
39614
|
-
return JSON.parse(await rt.fs.readText(
|
|
39745
|
+
return JSON.parse(await rt.fs.readText(path4));
|
|
39615
39746
|
} catch {
|
|
39616
39747
|
return { projectId: rt.randomUUID() };
|
|
39617
39748
|
}
|
|
39618
39749
|
};
|
|
39619
39750
|
const write2 = async (value) => {
|
|
39620
|
-
const temp =
|
|
39751
|
+
const temp = path4 + ".tmp";
|
|
39621
39752
|
await rt.fs.writeFile(temp, JSON.stringify(value, null, 2));
|
|
39622
|
-
await rt.fs.rename(temp,
|
|
39753
|
+
await rt.fs.rename(temp, path4);
|
|
39623
39754
|
};
|
|
39624
39755
|
const saved = async () => {
|
|
39625
39756
|
let value;
|
|
39626
39757
|
queue = queue.then(async () => {
|
|
39627
39758
|
value = await read2();
|
|
39628
|
-
if (!await rt.fs.stat(
|
|
39759
|
+
if (!await rt.fs.stat(path4)) await write2(value);
|
|
39629
39760
|
});
|
|
39630
39761
|
await queue;
|
|
39631
39762
|
return value;
|
|
@@ -39746,6 +39877,7 @@ var init_server2 = __esm({
|
|
|
39746
39877
|
init_studio_actions();
|
|
39747
39878
|
init_routes_cloud();
|
|
39748
39879
|
init_cloud3();
|
|
39880
|
+
init_reference();
|
|
39749
39881
|
init_thumbnails();
|
|
39750
39882
|
createEventHub = () => {
|
|
39751
39883
|
const clients = /* @__PURE__ */ new Set();
|
|
@@ -39901,18 +40033,18 @@ var init_server2 = __esm({
|
|
|
39901
40033
|
editContext = async (ctx, hosts) => ({
|
|
39902
40034
|
editor: await createEditor(ctx.rt, ctx.projectDir),
|
|
39903
40035
|
exportAccess: () => exportAccess(ctx.rt),
|
|
39904
|
-
studio: async (
|
|
39905
|
-
if (
|
|
40036
|
+
studio: async (path4, body) => {
|
|
40037
|
+
if (path4 === "/api/studio/cloud/start" && ctx.cloud) {
|
|
39906
40038
|
if (ctx.cloud.mode() !== "anonymous") throw new Error("Browser authorization is only needed when no key is configured.");
|
|
39907
40039
|
return ctx.cloud.start(body.lang === "en" ? "en" : "zh", Number([...ctx.hosts][0].split(":").pop()));
|
|
39908
40040
|
}
|
|
39909
|
-
if (
|
|
40041
|
+
if (path4 === "/api/studio/cloud/push" && ctx.cloud) {
|
|
39910
40042
|
if (ctx.cloud.mode() === "off") throw new Error("Cloud save is disabled.");
|
|
39911
40043
|
return ctx.cloud.push({ lang: body.lang === "en" ? "en" : "zh", force: body.force === true });
|
|
39912
40044
|
}
|
|
39913
40045
|
const { state } = await ctx.loader.load();
|
|
39914
40046
|
if (!ctx.edit) throw new Error("Studio is read-only.");
|
|
39915
|
-
return studioAction(ctx.rt, ctx.projectDir, ctx.edit.editor, withEdit(ctx, state),
|
|
40047
|
+
return studioAction(ctx.rt, ctx.projectDir, ctx.edit.editor, withEdit(ctx, state), path4, body);
|
|
39916
40048
|
},
|
|
39917
40049
|
render: createRenderJob(ctx.rt, ctx.projectDir, (info) => ctx.hub.send(RENDER_EVENT, info)),
|
|
39918
40050
|
origins: new Set([...hosts].map((h) => "http://" + h)),
|
|
@@ -39941,7 +40073,8 @@ var init_server2 = __esm({
|
|
|
39941
40073
|
const host = opts.host ?? "127.0.0.1";
|
|
39942
40074
|
if (opts.edit && !LOOPBACK.has(host))
|
|
39943
40075
|
throw new PreviewInputError('preview: edit mode is offered on the loopback address only (127.0.0.1); "' + host + '" would let other machines change the project. Leave out --host, or leave out --edit.');
|
|
39944
|
-
const
|
|
40076
|
+
const reference2 = opts.edit ? await prepareReference(rt, projectDir, opts.reference) : opts.reference ? rt.path.resolve(rt.cwd, opts.reference) : await savedReference(rt, projectDir);
|
|
40077
|
+
const sources = { ...opts, projectDir, ...reference2 ? { reference: reference2 } : {} };
|
|
39945
40078
|
const loader = createLoader(rt, sources);
|
|
39946
40079
|
await loader.load();
|
|
39947
40080
|
const hub = createEventHub();
|
|
@@ -40080,7 +40213,7 @@ var init_record = __esm({
|
|
|
40080
40213
|
const next = await compareCommand(rt, out2, record2.compares.at(-1));
|
|
40081
40214
|
return { ...uncompared ? { warning: "the last render (" + shown(rt, uncompared.out) + " at " + clock2(uncompared.at) + ") was not compared with the reference: run compare before changing more" } : {}, next };
|
|
40082
40215
|
};
|
|
40083
|
-
findRender = async (rt, video,
|
|
40216
|
+
findRender = async (rt, video, path4) => {
|
|
40084
40217
|
const dir = reviewsDir(rt);
|
|
40085
40218
|
const names = (await rt.fs.readdir(dir).catch(() => [])).filter((n) => n.endsWith(".json"));
|
|
40086
40219
|
const records = (await Promise.all(names.map(async (n) => {
|
|
@@ -40088,7 +40221,7 @@ var init_record = __esm({
|
|
|
40088
40221
|
return record2 ? [{ file: rt.path.join(dir, n), record: record2 }] : [];
|
|
40089
40222
|
}))).flat();
|
|
40090
40223
|
const latest2 = (test2) => records.flatMap(({ file, record: record2 }) => record2.renders.filter(test2).map((render3) => ({ file, record: record2, render: render3 }))).sort((a, b) => a.render.at.localeCompare(b.render.at)).at(-1);
|
|
40091
|
-
return latest2((r) => r.video === video) ?? latest2((r) => r.out ===
|
|
40224
|
+
return latest2((r) => r.video === video) ?? latest2((r) => r.out === path4);
|
|
40092
40225
|
};
|
|
40093
40226
|
projectOf3 = async (rt, file) => {
|
|
40094
40227
|
const real_ = await real(rt, file);
|
|
@@ -40769,12 +40902,12 @@ var init_library = __esm({
|
|
|
40769
40902
|
versionIn = (rt, dir) => rt.fs.readText(rt.path.join(dir, "package.json")).then((t) => String(JSON.parse(t).version ?? "unknown"), () => "unknown");
|
|
40770
40903
|
located = async (rt, from) => {
|
|
40771
40904
|
if ("skillFile" in from) {
|
|
40772
|
-
const
|
|
40773
|
-
return await rt.fs.stat(
|
|
40905
|
+
const path4 = rt.path.join(rt.skillRoot, from.skillFile);
|
|
40906
|
+
return await rt.fs.stat(path4) === null ? void 0 : { path: path4, version: await versionIn(rt, rt.skillRoot) };
|
|
40774
40907
|
}
|
|
40775
40908
|
for (const root of roots(rt, from.package)) {
|
|
40776
|
-
const
|
|
40777
|
-
if (await rt.fs.stat(
|
|
40909
|
+
const path4 = rt.path.join(root, from.source);
|
|
40910
|
+
if (await rt.fs.stat(path4) !== null) return { path: path4, version: await versionIn(rt, root) };
|
|
40778
40911
|
}
|
|
40779
40912
|
return void 0;
|
|
40780
40913
|
};
|
|
@@ -41683,10 +41816,10 @@ var init_examples = __esm({
|
|
|
41683
41816
|
readExample = async (rt, name) => {
|
|
41684
41817
|
const entry2 = EXAMPLES2.includes(name) ? void 0 : (await readCatalogue(rt)).entries.find((e) => e.name === name);
|
|
41685
41818
|
if (!EXAMPLES2.includes(name) && !entry2) throw new ExampleError('There is no example scene named "' + name + '". Known: ' + EXAMPLES2.join(", ") + ', and the entries of the catalogue: popost video scene example --search "<words>" finds one.');
|
|
41686
|
-
const
|
|
41687
|
-
const file = rt.path.join(rt.skillRoot,
|
|
41819
|
+
const path4 = entry2?.file ?? exampleFile(name);
|
|
41820
|
+
const file = rt.path.join(rt.skillRoot, path4);
|
|
41688
41821
|
const html2 = await rt.fs.readText(file).catch(() => {
|
|
41689
|
-
throw new ExampleError("The file " +
|
|
41822
|
+
throw new ExampleError("The file " + path4 + " of the popost Skill is missing. Reinstall popost (npm install -g popost).");
|
|
41690
41823
|
});
|
|
41691
41824
|
const block = BLOCK3.exec(html2)?.[1];
|
|
41692
41825
|
const parsed = block ? JSON.parse(block) : void 0;
|
|
@@ -46222,7 +46355,7 @@ var init_pairs = __esm({
|
|
|
46222
46355
|
const parsed = validatePairs(value), files = {}, failures = [];
|
|
46223
46356
|
for (const file of new Set(parsed.pairs.flatMap((p) => [p.reference.file, p.remake.file]))) {
|
|
46224
46357
|
try {
|
|
46225
|
-
const
|
|
46358
|
+
const path4 = rt.path.resolve(dir, file), bytes = await rt.fs.readFile(path4), measured2 = await (o.probe ?? probe2)(rt, path4);
|
|
46226
46359
|
files[file] = { sha256: sha256(bytes), fps: measured2.fps, frames: measured2.frames };
|
|
46227
46360
|
} catch {
|
|
46228
46361
|
issue3(failures, "files." + file, "The declared source file could not be read and measured locally.");
|
|
@@ -46423,24 +46556,24 @@ var init_schema3 = __esm({
|
|
|
46423
46556
|
return void 0;
|
|
46424
46557
|
};
|
|
46425
46558
|
described = (s, value) => typeof s.description === "string" ? value + ": " + s.description : value;
|
|
46426
|
-
fieldPath = (
|
|
46427
|
-
objectEntries = (s,
|
|
46559
|
+
fieldPath = (path4, name, required2) => (path4 ? path4 + "." : "") + name + (required2 ? "" : "?");
|
|
46560
|
+
objectEntries = (s, path4) => {
|
|
46428
46561
|
const required2 = new Set(Array.isArray(s.required) ? s.required : []);
|
|
46429
|
-
return Object.entries(node(s.properties)).flatMap(([name, sub3]) => entries2(node(sub3), fieldPath(
|
|
46562
|
+
return Object.entries(node(s.properties)).flatMap(([name, sub3]) => entries2(node(sub3), fieldPath(path4, name, required2.has(name))));
|
|
46430
46563
|
};
|
|
46431
|
-
listEntries2 = (s,
|
|
46432
|
-
const items = entries2(node(s.items),
|
|
46564
|
+
listEntries2 = (s, path4) => {
|
|
46565
|
+
const items = entries2(node(s.items), path4 + "[]");
|
|
46433
46566
|
const least = typeof s.minItems === "number" && s.minItems > 0 ? " (at least " + s.minItems + ")" : "";
|
|
46434
46567
|
const [only] = items;
|
|
46435
46568
|
if (!least) return items;
|
|
46436
|
-
return items.length === 1 && only ? [[only[0], only[1] + least]] : [[
|
|
46569
|
+
return items.length === 1 && only ? [[only[0], only[1] + least]] : [[path4, "list" + least], ...items];
|
|
46437
46570
|
};
|
|
46438
|
-
entries2 = (s,
|
|
46571
|
+
entries2 = (s, path4) => {
|
|
46439
46572
|
const one = scalar(s);
|
|
46440
|
-
if (one !== void 0) return [[
|
|
46441
|
-
if (s.type === "array") return listEntries2(s,
|
|
46442
|
-
if (s.type === "object" && Object.keys(node(s.properties)).length) return objectEntries(s,
|
|
46443
|
-
return [[
|
|
46573
|
+
if (one !== void 0) return [[path4, described(s, one)]];
|
|
46574
|
+
if (s.type === "array") return listEntries2(s, path4);
|
|
46575
|
+
if (s.type === "object" && Object.keys(node(s.properties)).length) return objectEntries(s, path4);
|
|
46576
|
+
return [[path4, "object"]];
|
|
46444
46577
|
};
|
|
46445
46578
|
formatOf2 = (json4) => ({
|
|
46446
46579
|
fields: Object.fromEntries(entries2(json4, "")),
|
|
@@ -47452,14 +47585,15 @@ init_cpu_budget();
|
|
|
47452
47585
|
init_credentials();
|
|
47453
47586
|
init_device_login();
|
|
47454
47587
|
init_browser();
|
|
47455
|
-
import { spawn } from "node:child_process";
|
|
47456
|
-
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
47588
|
+
import { execFile, spawn } from "node:child_process";
|
|
47589
|
+
import { createHash as createHash19, randomUUID as randomUUID2 } from "node:crypto";
|
|
47457
47590
|
import { accessSync, closeSync, constants as fsConstants, existsSync as existsSync2, openSync, readFileSync } from "node:fs";
|
|
47458
47591
|
import * as fsp from "node:fs/promises";
|
|
47459
47592
|
import { createServer } from "node:http";
|
|
47460
47593
|
import { availableParallelism, constants as osConstants, homedir as homedir2, hostname, platform as platform3, setPriority, tmpdir } from "node:os";
|
|
47461
|
-
import
|
|
47594
|
+
import path3 from "node:path";
|
|
47462
47595
|
import { fileURLToPath } from "node:url";
|
|
47596
|
+
import { promisify } from "node:util";
|
|
47463
47597
|
|
|
47464
47598
|
// src/node-secret.ts
|
|
47465
47599
|
init_i18n();
|
|
@@ -47518,22 +47652,65 @@ var readTerminalSecret = (input, write2) => new Promise((resolve2, reject) => {
|
|
|
47518
47652
|
|
|
47519
47653
|
// src/node-runtime.ts
|
|
47520
47654
|
init_i18n();
|
|
47655
|
+
|
|
47656
|
+
// src/system-browser.ts
|
|
47657
|
+
import path2 from "node:path";
|
|
47658
|
+
var macDefaultBrowser = (handlers) => {
|
|
47659
|
+
const entry2 = handlers.match(/\{[^{}]*\}/g)?.find((item2) => /LSHandlerURLScheme\s*=\s*"?https"?\s*;/.test(item2));
|
|
47660
|
+
return entry2?.match(/LSHandlerRoleAll\s*=\s*"?([\w.-]+)"?\s*;/)?.[1]?.toLowerCase() ?? "";
|
|
47661
|
+
};
|
|
47662
|
+
var browserCommands = (os, env, preferred, url) => {
|
|
47663
|
+
if (os === "darwin") {
|
|
47664
|
+
const ids3 = ["com.apple.safari", "com.google.chrome", "org.mozilla.firefox", "com.microsoft.edgemac", "com.brave.browser", "com.operasoftware.opera", "company.thebrowser.browser"];
|
|
47665
|
+
return [.../* @__PURE__ */ new Set([...ids3.includes(preferred) ? [preferred] : [], ...ids3])].map((id2) => ({ command: "/usr/bin/open", args: ["-b", id2, url], wait: true }));
|
|
47666
|
+
}
|
|
47667
|
+
if (os === "win32") {
|
|
47668
|
+
const apps2 = [
|
|
47669
|
+
["MSEdgeHTM", "Microsoft/Edge/Application/msedge.exe"],
|
|
47670
|
+
["ChromeHTML", "Google/Chrome/Application/chrome.exe"],
|
|
47671
|
+
["FirefoxURL", "Mozilla Firefox/firefox.exe"],
|
|
47672
|
+
["BraveHTML", "BraveSoftware/Brave-Browser/Application/brave.exe"]
|
|
47673
|
+
];
|
|
47674
|
+
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] }));
|
|
47676
|
+
}
|
|
47677
|
+
if (os !== "linux" || !env.DISPLAY && !env.WAYLAND_DISPLAY) return [];
|
|
47678
|
+
const apps = ["google-chrome", "chromium", "chromium-browser", "firefox", "microsoft-edge", "brave-browser", "opera"];
|
|
47679
|
+
const first = apps.find((app) => preferred.startsWith(app + ".") || preferred.startsWith(app + "-"));
|
|
47680
|
+
const roots2 = ["/usr/bin", "/usr/local/bin", "/opt/bin", "/snap/bin"];
|
|
47681
|
+
return [.../* @__PURE__ */ new Set([...first ? [first] : [], ...apps])].flatMap((app) => roots2.map((root) => ({ command: path2.posix.join(root, app), args: [url] })));
|
|
47682
|
+
};
|
|
47683
|
+
var openSystemBrowser = async (url, host) => {
|
|
47684
|
+
try {
|
|
47685
|
+
const target2 = new URL(url);
|
|
47686
|
+
if (target2.protocol !== "https:" || target2.username || target2.password) return false;
|
|
47687
|
+
if (host.env.SSH_CONNECTION || host.env.SSH_TTY) return false;
|
|
47688
|
+
const preferred = await host.preferred();
|
|
47689
|
+
for (const command2 of browserCommands(host.os, host.env, preferred, url)) {
|
|
47690
|
+
if (await host.available(command2.command) && await host.launch(command2)) return true;
|
|
47691
|
+
}
|
|
47692
|
+
} catch {
|
|
47693
|
+
}
|
|
47694
|
+
return false;
|
|
47695
|
+
};
|
|
47696
|
+
|
|
47697
|
+
// src/node-runtime.ts
|
|
47521
47698
|
var missing2 = (error2) => error2?.code === "ENOENT";
|
|
47522
47699
|
var nodeFileSystem = {
|
|
47523
47700
|
realpath: (p) => fsp.realpath(p),
|
|
47524
47701
|
readFile: async (p) => new Uint8Array(await fsp.readFile(p)),
|
|
47525
47702
|
readText: (p) => fsp.readFile(p, "utf8"),
|
|
47526
47703
|
copyFile: async (from, to) => {
|
|
47527
|
-
await fsp.mkdir(
|
|
47704
|
+
await fsp.mkdir(path3.dirname(to), { recursive: true });
|
|
47528
47705
|
await fsp.copyFile(from, to, fsConstants.COPYFILE_FICLONE);
|
|
47529
47706
|
},
|
|
47530
47707
|
writeFile: async (p, data, options) => {
|
|
47531
47708
|
if (!options?.private) {
|
|
47532
|
-
await fsp.mkdir(
|
|
47709
|
+
await fsp.mkdir(path3.dirname(p), { recursive: true });
|
|
47533
47710
|
await fsp.writeFile(p, data);
|
|
47534
47711
|
return;
|
|
47535
47712
|
}
|
|
47536
|
-
await fsp.mkdir(
|
|
47713
|
+
await fsp.mkdir(path3.dirname(p), { recursive: true, mode: 448 });
|
|
47537
47714
|
await fsp.writeFile(p, data, { mode: 384 });
|
|
47538
47715
|
await fsp.chmod(p, 384).catch(() => void 0);
|
|
47539
47716
|
},
|
|
@@ -47568,7 +47745,7 @@ var findNice = () => {
|
|
|
47568
47745
|
if (niceProgram === void 0) niceProgram = platform3() === "win32" ? null : ["/usr/bin/nice", "/bin/nice"].find(executable) ?? null;
|
|
47569
47746
|
return niceProgram ?? void 0;
|
|
47570
47747
|
};
|
|
47571
|
-
var startable = (exe, cwd) => exe.includes("/") ? executable(
|
|
47748
|
+
var startable = (exe, cwd) => exe.includes("/") ? executable(path3.resolve(cwd ?? process.cwd(), exe)) : (process.env.PATH ?? "").split(path3.delimiter).some((dir) => dir !== "" && executable(path3.join(dir, exe)));
|
|
47572
47749
|
var commandLine = (exe, args2, options) => {
|
|
47573
47750
|
const nice = options.lowPriority ? findNice() : void 0;
|
|
47574
47751
|
if (nice && startable(exe, options.cwd)) return [nice, ["-n", String(LOW_PRIORITY), exe, ...args2], false];
|
|
@@ -47653,11 +47830,11 @@ var budget;
|
|
|
47653
47830
|
var nodeCpuBudget = () => budget ??= cpuBudget(process.env.POPOST_CPUS, {
|
|
47654
47831
|
affinity: affinity(),
|
|
47655
47832
|
cgroup: readQuietly("/proc/self/cgroup"),
|
|
47656
|
-
readCgroupFile: (file) => readQuietly(
|
|
47833
|
+
readCgroupFile: (file) => readQuietly(path3.join("/sys/fs/cgroup", file))
|
|
47657
47834
|
});
|
|
47658
47835
|
var nodePrograms = {
|
|
47659
47836
|
run: runProgram,
|
|
47660
|
-
tempDir: (prefix) => fsp.mkdtemp(
|
|
47837
|
+
tempDir: (prefix) => fsp.mkdtemp(path3.join(tmpdir(), prefix)),
|
|
47661
47838
|
get parallelism() {
|
|
47662
47839
|
return nodeCpuBudget().cpus;
|
|
47663
47840
|
},
|
|
@@ -47665,7 +47842,7 @@ var nodePrograms = {
|
|
|
47665
47842
|
return nodeCpuBudget().source;
|
|
47666
47843
|
}
|
|
47667
47844
|
};
|
|
47668
|
-
var packageRoot = () =>
|
|
47845
|
+
var packageRoot = () => path3.resolve(path3.dirname(fileURLToPath(import.meta.url)), "..");
|
|
47669
47846
|
var userHome = () => {
|
|
47670
47847
|
try {
|
|
47671
47848
|
return homedir2() || void 0;
|
|
@@ -47694,27 +47871,56 @@ var readOptional = (file) => {
|
|
|
47694
47871
|
throw error2;
|
|
47695
47872
|
}
|
|
47696
47873
|
};
|
|
47697
|
-
var
|
|
47698
|
-
|
|
47699
|
-
|
|
47700
|
-
|
|
47701
|
-
|
|
47702
|
-
|
|
47874
|
+
var browserExec = promisify(execFile);
|
|
47875
|
+
var readBrowserPreference = async (command2, args2) => {
|
|
47876
|
+
try {
|
|
47877
|
+
return (await browserExec(command2, args2, { timeout: 3e3, maxBuffer: 65536 })).stdout;
|
|
47878
|
+
} catch {
|
|
47879
|
+
return "";
|
|
47880
|
+
}
|
|
47881
|
+
};
|
|
47882
|
+
var preferredSystemBrowser = async () => {
|
|
47883
|
+
if (platform3() === "darwin") return macDefaultBrowser(await readBrowserPreference("/usr/bin/defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]));
|
|
47884
|
+
if (platform3() === "win32") return readBrowserPreference("reg.exe", ["query", "HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice", "/v", "ProgId"]);
|
|
47885
|
+
return (await readBrowserPreference("/usr/bin/xdg-settings", ["get", "default-web-browser"])).trim();
|
|
47886
|
+
};
|
|
47887
|
+
var launchSystemBrowser = async ({ command: command2, args: args2, wait }) => {
|
|
47888
|
+
if (wait) {
|
|
47889
|
+
try {
|
|
47890
|
+
await browserExec(command2, args2, { timeout: 5e3, maxBuffer: 65536 });
|
|
47891
|
+
return true;
|
|
47892
|
+
} catch {
|
|
47893
|
+
return false;
|
|
47894
|
+
}
|
|
47895
|
+
}
|
|
47896
|
+
return new Promise((resolve2) => {
|
|
47897
|
+
const child = spawn(command2, args2, { stdio: "ignore", detached: true, env: { ...process.env, BROWSER: void 0 } });
|
|
47898
|
+
child.once("error", () => resolve2(false));
|
|
47899
|
+
child.once("spawn", () => {
|
|
47900
|
+
child.unref();
|
|
47901
|
+
resolve2(true);
|
|
47902
|
+
});
|
|
47703
47903
|
});
|
|
47704
|
-
|
|
47904
|
+
};
|
|
47905
|
+
var systemBrowserHost = {
|
|
47906
|
+
os: platform3(),
|
|
47907
|
+
env: process.env,
|
|
47908
|
+
preferred: preferredSystemBrowser,
|
|
47909
|
+
launch: launchSystemBrowser,
|
|
47910
|
+
available: async (command2) => executable(command2)
|
|
47705
47911
|
};
|
|
47706
47912
|
var createNodeRuntime = (profile2) => {
|
|
47707
47913
|
const cliPath = fileURLToPath(import.meta.url);
|
|
47708
47914
|
const cwd = process.cwd();
|
|
47709
47915
|
const homeDir2 = userHome();
|
|
47710
|
-
const distribution = readOptional(
|
|
47916
|
+
const distribution = readOptional(path3.join(packageRoot(), "dist", "distribution.json"));
|
|
47711
47917
|
const site = distribution ? String(JSON.parse(distribution).origin) : void 0;
|
|
47712
47918
|
const raw = {
|
|
47713
47919
|
...process.env,
|
|
47714
47920
|
...profile2 ? { POPOST_AGENT_PROFILE: profile2 } : {},
|
|
47715
47921
|
POPOST_DISTRIBUTION_SITE: site
|
|
47716
47922
|
};
|
|
47717
|
-
const location = { cwd, homeDir: homeDir2, path:
|
|
47923
|
+
const location = { cwd, homeDir: homeDir2, path: path3, env: raw };
|
|
47718
47924
|
let grant = null;
|
|
47719
47925
|
if (!raw.POPOST_API_KEY?.trim()) {
|
|
47720
47926
|
try {
|
|
@@ -47740,15 +47946,37 @@ var createNodeRuntime = (profile2) => {
|
|
|
47740
47946
|
const matchingManual = !site || site === manualSite;
|
|
47741
47947
|
const env = { ...applyStoredCredentials(raw, grant || !matchingManual ? null : manual) };
|
|
47742
47948
|
env.POPOST_BASE_URL ||= grant?.baseUrl || site && site + "/api/open/v1";
|
|
47949
|
+
const access = grant ? deviceTokenProvider(grant, globalThis.fetch) : void 0;
|
|
47950
|
+
const accountFile = (file) => {
|
|
47951
|
+
try {
|
|
47952
|
+
return readOptional(file);
|
|
47953
|
+
} catch {
|
|
47954
|
+
return null;
|
|
47955
|
+
}
|
|
47956
|
+
};
|
|
47957
|
+
const signature2 = () => [accountFile(deviceLocation(location)), accountFile(credentialsFile(location))].join("\n");
|
|
47958
|
+
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 };
|
|
47743
47961
|
return {
|
|
47962
|
+
refreshAccount: () => {
|
|
47963
|
+
const next = signature2();
|
|
47964
|
+
if (next !== lastSignature) {
|
|
47965
|
+
const fresh = createNodeRuntime(profile2);
|
|
47966
|
+
account = { env: fresh.env, deviceAccess: fresh.deviceAccess, credentialScope: fresh.credentialScope };
|
|
47967
|
+
lastSignature = next;
|
|
47968
|
+
}
|
|
47969
|
+
return account;
|
|
47970
|
+
},
|
|
47744
47971
|
fs: nodeFileSystem,
|
|
47745
|
-
path:
|
|
47972
|
+
path: path3,
|
|
47746
47973
|
cwd,
|
|
47747
47974
|
env,
|
|
47748
47975
|
deviceName: hostname().replace(/[^\p{L}\p{N}._-]/gu, "-").slice(0, 38),
|
|
47749
47976
|
explicitApiKey: Boolean(raw.POPOST_API_KEY?.trim()),
|
|
47750
|
-
deviceAccess:
|
|
47751
|
-
|
|
47977
|
+
deviceAccess: access,
|
|
47978
|
+
credentialScope,
|
|
47979
|
+
openExternal: (url) => openSystemBrowser(url, systemBrowserHost),
|
|
47752
47980
|
homeDir: homeDir2,
|
|
47753
47981
|
platform: platform3(),
|
|
47754
47982
|
stdin: readStdin,
|
|
@@ -47763,7 +47991,7 @@ var createNodeRuntime = (profile2) => {
|
|
|
47763
47991
|
randomUUID: randomUUID2,
|
|
47764
47992
|
processes: {
|
|
47765
47993
|
spawnDetached: async (argv, options) => {
|
|
47766
|
-
await fsp.mkdir(
|
|
47994
|
+
await fsp.mkdir(path3.dirname(options.logFile), { recursive: true });
|
|
47767
47995
|
const log = openSync(options.logFile, "a");
|
|
47768
47996
|
try {
|
|
47769
47997
|
const child = spawn(argv[0], argv.slice(1), {
|