fablecut 1.15.0 → 1.17.0

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/projects.js ADDED
@@ -0,0 +1,324 @@
1
+ /* ═══════════════════════════════════════════════════════════════════════════
2
+ Projects: several projects in one data folder.
3
+
4
+ ./project.json stays THE open project — the editor, the MCP server, agents
5
+ and scripts all keep reading and writing that one file. Every project also
6
+ has its own folder:
7
+
8
+ projects/index.json {active: "<id>"}
9
+ projects/<id>/meta.json {id, created, opened, archived, notes, tags}
10
+ projects/<id>/project.json the document (stale while that project is open:
11
+ the live copy is ./project.json)
12
+ projects/<id>/thumb.jpg the editor's last picture of it
13
+ library/project-templates/<id>.json saved templates {name, created, project}
14
+
15
+ Opening another project parks ./project.json in the open project's folder,
16
+ then copies the chosen one over it with a revision above both, so a save
17
+ from an editor tab or agent that read the old project is refused (409 /
18
+ CONFLICT) instead of landing on the new one. media/, exports/ and analysis/
19
+ are shared, so a duplicate or a template copies no footage.
20
+ ═══════════════════════════════════════════════════════════════════════════ */
21
+ "use strict";
22
+ const crypto = require("crypto");
23
+ const fs = require("fs");
24
+ const path = require("path");
25
+
26
+ /* Canvas presets offered next to the user's saved templates. */
27
+ const BUILTIN_TEMPLATES = [
28
+ { id: "landscape-1080", name: "Landscape 16:9 · 1080p", width: 1920, height: 1080, fps: 30 },
29
+ { id: "vertical-1080", name: "Vertical 9:16 · Reels, Shorts, TikTok", width: 1080, height: 1920, fps: 30 },
30
+ { id: "square-1080", name: "Square 1:1", width: 1080, height: 1080, fps: 30 },
31
+ { id: "portrait-1350", name: "Portrait 4:5 · feed post", width: 1080, height: 1350, fps: 30 },
32
+ { id: "uhd-4k", name: "4K UHD 16:9", width: 3840, height: 2160, fps: 30 },
33
+ { id: "landscape-720", name: "Landscape 16:9 · 720p", width: 1280, height: 720, fps: 30 },
34
+ ];
35
+ const FPS_CHOICES = [23.976, 24, 25, 29.97, 30, 50, 59.94, 60];
36
+ const MAX_NOTES = 4000, MAX_TAGS = 12, MAX_NAME = 120;
37
+
38
+ const readJSON = (file) => JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, ""));
39
+ function writeJSON(file, obj) {
40
+ fs.mkdirSync(path.dirname(file), { recursive: true });
41
+ // unique tmp: the editor and the MCP server may write at once
42
+ const tmp = `${file}.${crypto.randomUUID()}.tmp`;
43
+ fs.writeFileSync(tmp, JSON.stringify(obj, null, 2));
44
+ fs.renameSync(tmp, file);
45
+ }
46
+ const newId = () => "p_" + crypto.randomBytes(5).toString("hex");
47
+ const validId = (id) => typeof id === "string" && /^p_[a-z0-9]{4,24}$/.test(id);
48
+ const slug = (s) => String(s || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
49
+ const cleanName = (s) => String(s ?? "").replace(/[\u0000-\u001f]/g, " ").trim().slice(0, MAX_NAME);
50
+ function cleanTags(v) {
51
+ const list = Array.isArray(v) ? v : String(v ?? "").split(",");
52
+ const out = [];
53
+ for (const t of list) {
54
+ const s = String(t ?? "").trim().replace(/^#+/, "").trim().slice(0, 32);
55
+ if (s && !out.some((x) => x.toLowerCase() === s.toLowerCase())) out.push(s);
56
+ }
57
+ return out.slice(0, MAX_TAGS);
58
+ }
59
+ const timelineEnd = (doc) => (Array.isArray(doc.clips) ? doc.clips : [])
60
+ .reduce((m, c) => Math.max(m, (+c.start || 0) + (+c.duration || 0)), 0);
61
+ const blankProject = (name, t) => ({
62
+ name, width: t.width, height: t.height, fps: t.fps, revision: 0, media: [], clips: [],
63
+ });
64
+
65
+ function createProjects({ dataDir, projectFile, libraryDir }) {
66
+ const DIR = path.join(dataDir, "projects");
67
+ const INDEX = path.join(DIR, "index.json");
68
+ const TEMPLATES = path.join(libraryDir, "project-templates");
69
+ const folder = (id) => path.join(DIR, id);
70
+ const metaFile = (id) => path.join(folder(id), "meta.json");
71
+ const docFile = (id) => path.join(folder(id), "project.json");
72
+ const thumbFile = (id) => path.join(folder(id), "thumb.jpg");
73
+
74
+ const readRoot = () => {
75
+ try { return readJSON(projectFile); }
76
+ catch (e) { throw new Error(`project.json can't be read (${e.message}) — fix or replace it before switching projects`); }
77
+ };
78
+ const readMeta = (id) => { try { return readJSON(metaFile(id)); } catch { return null; } };
79
+ const writeMeta = (id, meta) => writeJSON(metaFile(id), meta);
80
+ const exists = (id) => validId(id) && fs.existsSync(metaFile(id));
81
+
82
+ /* The open project's id. The first call gives the existing ./project.json
83
+ a folder of its own, so a data folder from before projects just works. */
84
+ function activeId() {
85
+ let id = null;
86
+ try { id = readJSON(INDEX).active; } catch { }
87
+ if (exists(id)) return id;
88
+ id = newId();
89
+ let created = new Date().toISOString();
90
+ try { created = fs.statSync(projectFile).mtime.toISOString(); } catch { }
91
+ writeMeta(id, { id, created, opened: new Date().toISOString(), archived: false, notes: "", tags: [] });
92
+ writeJSON(INDEX, { active: id });
93
+ return id;
94
+ }
95
+ /* The open project's id without creating anything (null before the first dashboard use). */
96
+ function peekActive() {
97
+ try { const id = readJSON(INDEX).active; return exists(id) ? id : null; } catch { return null; }
98
+ }
99
+ const mustExist = (id) => {
100
+ if (!exists(id)) throw new Error(`no project ${JSON.stringify(id)} (fablecut_projects {action:"list"} lists them)`);
101
+ };
102
+ /* The document of a project: ./project.json for the open one. */
103
+ const readDoc = (id) => (id === activeId() ? readRoot() : readJSON(docFile(id)));
104
+ const writeDoc = (id, doc) => {
105
+ if (id !== activeId()) { writeJSON(docFile(id), doc); return; }
106
+ // the open project: bump the revision like any other save, so tabs reload
107
+ const cur = readRoot();
108
+ writeJSON(projectFile, { ...doc, revision: Math.max(cur.revision || 0, doc.revision || 0) + 1 });
109
+ };
110
+
111
+ function summary(id, active) {
112
+ const meta = readMeta(id) || { id };
113
+ let doc = null, modified = null;
114
+ const file = id === active ? projectFile : docFile(id);
115
+ try { doc = readJSON(file); modified = fs.statSync(file).mtime.toISOString(); } catch { }
116
+ let thumb = null;
117
+ try { thumb = Math.round(fs.statSync(thumbFile(id)).mtimeMs); } catch { }
118
+ return {
119
+ id, name: doc?.name || "Untitled Project", active: id === active,
120
+ archived: !!meta.archived, notes: meta.notes || "", tags: meta.tags || [],
121
+ created: meta.created || null, opened: meta.opened || null, modified,
122
+ width: doc?.width ?? null, height: doc?.height ?? null, fps: doc?.fps ?? null,
123
+ duration: doc ? +timelineEnd(doc).toFixed(2) : null,
124
+ clips: doc?.clips?.length ?? 0, media: doc?.media?.length ?? 0,
125
+ thumb, unreadable: !doc,
126
+ };
127
+ }
128
+
129
+ function list({ archived = "exclude" } = {}) {
130
+ const active = activeId();
131
+ let ids = [];
132
+ try { ids = fs.readdirSync(DIR, { withFileTypes: true }).filter((e) => e.isDirectory() && exists(e.name)).map((e) => e.name); } catch { }
133
+ let projects = ids.map((id) => summary(id, active));
134
+ if (archived === "exclude") projects = projects.filter((p) => !p.archived || p.active);
135
+ else if (archived === "only") projects = projects.filter((p) => p.archived);
136
+ projects.sort((a, b) => String(b.opened || b.modified || "").localeCompare(String(a.opened || a.modified || "")));
137
+ return { active, projects };
138
+ }
139
+
140
+ /* Park the open project in its folder, then put `id` in ./project.json. */
141
+ function open(id) {
142
+ mustExist(id);
143
+ const cur = activeId();
144
+ if (id === cur) return { id, already: true, project: summary(id, cur) };
145
+ const root = readRoot();
146
+ let next;
147
+ try { next = readJSON(docFile(id)); }
148
+ catch (e) { throw new Error(`project ${id} can't be read (${e.message})`); }
149
+ writeJSON(docFile(cur), root);
150
+ next.revision = Math.max(root.revision || 0, next.revision || 0) + 1;
151
+ try {
152
+ writeJSON(projectFile, next);
153
+ writeJSON(INDEX, { active: id });
154
+ } catch (e) {
155
+ // ./project.json and index.json must agree: put the open project back
156
+ try { writeJSON(projectFile, { ...root, revision: next.revision + 1 }); } catch { }
157
+ throw new Error(`switching to ${id} failed (${e.message}) — ${cur} is still open`);
158
+ }
159
+ const meta = readMeta(id) || { id };
160
+ writeMeta(id, { ...meta, opened: new Date().toISOString(), archived: false });
161
+ return { id, from: cur, project: summary(id, id) };
162
+ }
163
+
164
+ function add(doc, { name, notes, tags, template } = {}) {
165
+ const id = newId();
166
+ const now = new Date().toISOString();
167
+ const out = { ...doc, name: cleanName(name) || doc.name || "Untitled Project", revision: 0 };
168
+ writeJSON(docFile(id), out);
169
+ const meta = { id, created: now, opened: null, archived: false, notes: String(notes || "").slice(0, MAX_NOTES), tags: cleanTags(tags) };
170
+ if (template) meta.template = template;
171
+ writeMeta(id, meta);
172
+ return id;
173
+ }
174
+
175
+ function findTemplate(tid) {
176
+ const b = BUILTIN_TEMPLATES.find((t) => t.id === tid);
177
+ if (b) return { builtin: true, ...b };
178
+ const s = templates().find((t) => t.id === tid);
179
+ if (!s) throw new Error(`no project template ${JSON.stringify(tid)} (built-in: ${BUILTIN_TEMPLATES.map((t) => t.id).join(", ")}${templates().some((t) => !t.builtin) ? "; saved: " + templates().filter((t) => !t.builtin).map((t) => t.id).join(", ") : ""})`);
180
+ return s;
181
+ }
182
+
183
+ /* A new project from a template (default: 1080p landscape), optionally opened. */
184
+ function create({ name, template = "landscape-1080", fps, width, height, notes, tags, open: andOpen = true } = {}) {
185
+ const t = findTemplate(template);
186
+ let doc;
187
+ if (t.builtin) doc = blankProject("", t);
188
+ else doc = structuredClone(readJSON(path.join(TEMPLATES, t.id + ".json")).project);
189
+ if (fps != null) {
190
+ if (!(Number(fps) > 0 && Number(fps) <= 120)) throw new Error("fps must be a frame rate between 1 and 120");
191
+ doc.fps = Number(fps);
192
+ }
193
+ for (const [k, v] of [["width", width], ["height", height]]) {
194
+ if (v == null) continue;
195
+ if (!Number.isInteger(v) || v < 16 || v > 8192 || v % 2) throw new Error(`${k} must be an even number of pixels, 16…8192`);
196
+ doc[k] = v;
197
+ }
198
+ const id = add(doc, { name: cleanName(name) || "Untitled Project", notes, tags, template: t.id });
199
+ return andOpen ? open(id) : { id, project: summary(id, activeId()) };
200
+ }
201
+
202
+ function duplicate(id, { name, open: andOpen = false } = {}) {
203
+ mustExist(id);
204
+ const src = readDoc(id);
205
+ const meta = readMeta(id) || {};
206
+ const nid = add(structuredClone(src), { name: cleanName(name) || `${src.name || "Untitled Project"} copy`, notes: meta.notes, tags: meta.tags });
207
+ try { fs.copyFileSync(thumbFile(id), thumbFile(nid)); } catch { }
208
+ return andOpen ? open(nid) : { id: nid, project: summary(nid, activeId()) };
209
+ }
210
+
211
+ /* Rename / notes / tags. */
212
+ function update(id, { name, notes, tags } = {}) {
213
+ mustExist(id);
214
+ if (name != null) {
215
+ const n = cleanName(name);
216
+ if (!n) throw new Error("name can't be empty");
217
+ const doc = readDoc(id);
218
+ if (doc.name !== n) writeDoc(id, { ...doc, name: n });
219
+ }
220
+ if (notes != null || tags != null) {
221
+ const meta = readMeta(id) || { id };
222
+ if (notes != null) meta.notes = String(notes).slice(0, MAX_NOTES);
223
+ if (tags != null) meta.tags = cleanTags(tags);
224
+ writeMeta(id, meta);
225
+ }
226
+ return { id, project: summary(id, activeId()) };
227
+ }
228
+
229
+ function archive(id, on = true) {
230
+ mustExist(id);
231
+ if (on && id === activeId()) throw new Error("the open project can't be archived — open another project first");
232
+ writeMeta(id, { ...(readMeta(id) || { id }), archived: !!on });
233
+ return { id, project: summary(id, activeId()) };
234
+ }
235
+
236
+ /* Deleting is for archived projects only, so it always takes two steps. */
237
+ function remove(id) {
238
+ mustExist(id);
239
+ if (id === activeId()) throw new Error("the open project can't be deleted");
240
+ if (!readMeta(id)?.archived) throw new Error("archive the project first — only archived projects can be deleted");
241
+ fs.rmSync(folder(id), { recursive: true, force: true });
242
+ return { id, deleted: true };
243
+ }
244
+
245
+ /* A project file from elsewhere (an old backup, another machine). */
246
+ function importDoc(doc, { name, open: andOpen = false } = {}) {
247
+ if (!doc || typeof doc !== "object" || !Array.isArray(doc.clips) || !Array.isArray(doc.media))
248
+ throw new Error("not a FableCut project (it needs clips and media arrays)");
249
+ const id = add(structuredClone(doc), { name: cleanName(name) || doc.name });
250
+ return andOpen ? open(id) : { id, project: summary(id, activeId()) };
251
+ }
252
+
253
+ function templates() {
254
+ const out = BUILTIN_TEMPLATES.map((t) => ({ ...t, builtin: true, clips: 0 }));
255
+ let files = [];
256
+ try { files = fs.readdirSync(TEMPLATES).filter((f) => f.toLowerCase().endsWith(".json")).sort(); } catch { }
257
+ for (const f of files) {
258
+ try {
259
+ const t = readJSON(path.join(TEMPLATES, f));
260
+ const p = t.project || {};
261
+ out.push({ id: f.slice(0, -5), name: t.name || f.slice(0, -5), builtin: false, created: t.created || null,
262
+ width: p.width, height: p.height, fps: p.fps, clips: (p.clips || []).length, duration: +timelineEnd(p).toFixed(2) });
263
+ } catch { }
264
+ }
265
+ return out;
266
+ }
267
+
268
+ /* Save a project — its canvas, tracks, clips and media references — as a template. */
269
+ function saveTemplate(id, { name } = {}) {
270
+ mustExist(id);
271
+ const doc = structuredClone(readDoc(id));
272
+ const label = cleanName(name) || doc.name || "Template";
273
+ const tid = slug(label);
274
+ if (!tid) throw new Error("name the template (letters or digits)");
275
+ if (BUILTIN_TEMPLATES.some((t) => t.id === tid)) throw new Error(`"${label}" is a built-in template — pick another name`);
276
+ delete doc.revision;
277
+ writeJSON(path.join(TEMPLATES, tid + ".json"), { name: label, created: new Date().toISOString(), project: doc });
278
+ return { template: templates().find((t) => t.id === tid) };
279
+ }
280
+
281
+ function deleteTemplate(tid) {
282
+ if (BUILTIN_TEMPLATES.some((t) => t.id === tid)) throw new Error("built-in templates can't be deleted");
283
+ const file = path.join(TEMPLATES, slug(tid) + ".json");
284
+ if (!slug(tid) || !fs.existsSync(file)) throw new Error(`no saved template ${JSON.stringify(tid)}`);
285
+ fs.unlinkSync(file);
286
+ return { template: tid, deleted: true };
287
+ }
288
+
289
+ function setThumb(id, buf) {
290
+ mustExist(id);
291
+ if (!Buffer.isBuffer(buf) || buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) throw new Error("thumbnail must be a JPEG");
292
+ if (buf.length > 1024 * 1024) throw new Error("thumbnail too large (1 MB max)");
293
+ const tmp = `${thumbFile(id)}.${crypto.randomUUID()}.tmp`;
294
+ fs.writeFileSync(tmp, buf);
295
+ fs.renameSync(tmp, thumbFile(id));
296
+ return { id, ok: true };
297
+ }
298
+ const thumbPath = (id) => (exists(id) && fs.existsSync(thumbFile(id)) ? thumbFile(id) : null);
299
+
300
+ /* One entry point for the REST API and the MCP tool. */
301
+ function act(a = {}) {
302
+ switch (a.action) {
303
+ case "list": return { ...list({ archived: a.archived }), templates: templates() };
304
+ case "open": return open(a.id);
305
+ case "new": return create(a);
306
+ case "duplicate": return duplicate(a.id, a);
307
+ case "update": case "rename": return update(a.id, a);
308
+ case "archive": return archive(a.id, true);
309
+ case "unarchive": return archive(a.id, false);
310
+ case "delete": return remove(a.id);
311
+ case "import": return importDoc(a.project, a);
312
+ case "templates": return { templates: templates() };
313
+ case "save_template": return saveTemplate(a.id, a);
314
+ case "delete_template": return deleteTemplate(a.template);
315
+ default:
316
+ throw new Error(`unknown action ${JSON.stringify(a.action)} (list|open|new|duplicate|update|archive|unarchive|delete|import|templates|save_template|delete_template)`);
317
+ }
318
+ }
319
+
320
+ return { DIR, INDEX, TEMPLATES, activeId, peekActive, mustExist, readRoot, readDoc, writeDoc, list, open, create, duplicate, update, archive, remove, importDoc,
321
+ templates, saveTemplate, deleteTemplate, setThumb, thumbPath, act };
322
+ }
323
+
324
+ module.exports = { createProjects, BUILTIN_TEMPLATES, FPS_CHOICES };
package/sequences.js ADDED
@@ -0,0 +1,216 @@
1
+ /* FableCut sequences — several timelines in one project. Zero dependencies.
2
+ Loaded by the editor as a plain script (global `FableCutSeq`) and required
3
+ by the MCP server, project-ops and the tests.
4
+
5
+ The OPEN sequence is the project's top level, as it always was: `clips`,
6
+ `tracks`, `markers`, the canvas, the mix and the delivery settings. Every
7
+ tool, agent and export keeps reading and writing those. The others are kept
8
+ in `project.sequences`, each with its own copy of the same keys:
9
+
10
+ "sequence": "main", // the open one
11
+ "sequences": [
12
+ { "id": "main", "name": "Main" }, // the open one: its timeline is the top level
13
+ { "id": "seq_v", "name": "Vertical", "width": 1080, "height": 1920, "fps": 30, "clips": [ … ], … }
14
+ ]
15
+
16
+ Opening another sequence parks the top-level keys in the open one's entry
17
+ and brings the other's up. Media, folders, collections and compositions
18
+ are the project's, shared by every sequence. A project with one sequence
19
+ has neither key: untouched projects stay byte-identical. */
20
+ (function (root, factory) {
21
+ const node = typeof module === "object" && module.exports;
22
+ const api = factory();
23
+ if (node) module.exports = api;
24
+ else root.FableCutSeq = api;
25
+ })(typeof self !== "undefined" ? self : this, function () {
26
+ "use strict";
27
+
28
+ /** What a sequence owns: its timeline, canvas, frame rate, mix and delivery. */
29
+ const KEYS = ["width", "height", "fps", "background", "exportFrame", "clips", "tracks", "markers", "inPoint", "outPoint",
30
+ "disabledTracks", "lockedTracks", "untargetedTracks", "master", "buses", "delivery", "outputs", "encodeProfile"];
31
+ const MAIN = { id: "main", name: "Main" };
32
+ const MAX = 64;
33
+ const isObj = (v) => v != null && typeof v === "object" && !Array.isArray(v);
34
+ const clone = (v) => (v === undefined ? undefined : JSON.parse(JSON.stringify(v)));
35
+ const uid = () => Math.random().toString(36).slice(2, 8);
36
+ const r2 = (v) => Math.round(v * 100) / 100;
37
+
38
+ /** The sequence entries, the open one included (a project without the key has one: Main). */
39
+ function entries(doc) {
40
+ return doc && Array.isArray(doc.sequences) && doc.sequences.length ? doc.sequences : [{ ...MAIN }];
41
+ }
42
+ function activeId(doc) {
43
+ const list = entries(doc);
44
+ return doc && list.some((s) => s.id === doc.sequence) ? doc.sequence : list[0].id;
45
+ }
46
+ function find(doc, id) { return entries(doc).find((s) => s.id === id) || null; }
47
+ /** The sequences that are not open: [{id, name, clips, …}] — media and comp usage scans read these too. */
48
+ function others(doc) {
49
+ const act = activeId(doc);
50
+ return entries(doc).filter((s) => s.id !== act);
51
+ }
52
+ const lengthOf = (clips) => (Array.isArray(clips) ? clips : []).reduce((m, c) => Math.max(m, (+c.start || 0) + (+c.duration || 0)), 0);
53
+
54
+ /** One row per sequence, in order: {id, name, active, width, height, fps, clips, duration}. */
55
+ function list(doc) {
56
+ const act = activeId(doc);
57
+ return entries(doc).map((s) => {
58
+ const src = s.id === act ? doc : s;
59
+ return { id: s.id, name: s.name || s.id, active: s.id === act, width: src.width, height: src.height, fps: src.fps,
60
+ clips: Array.isArray(src.clips) ? src.clips.length : 0, duration: r2(lengthOf(src.clips)) };
61
+ });
62
+ }
63
+
64
+ /** Check and tidy doc.sequences in place (throws on a bad entry). One sequence named Main → both keys go. */
65
+ function normalize(doc) {
66
+ if (doc.sequences == null) { delete doc.sequence; return doc; }
67
+ if (!Array.isArray(doc.sequences)) throw new Error("sequences must be a list of {id, name, …}");
68
+ if (doc.sequences.length > MAX) throw new Error(`a project holds up to ${MAX} sequences`);
69
+ const seen = new Set();
70
+ const out = [];
71
+ for (const s of doc.sequences) {
72
+ if (!isObj(s)) throw new Error("every sequence is an object {id, name, …}");
73
+ const id = typeof s.id === "string" ? s.id.trim().slice(0, 40) : "";
74
+ if (!id) throw new Error("every sequence needs an id");
75
+ if (seen.has(id)) throw new Error(`two sequences have the id ${id} — sequence ids must be unique`);
76
+ seen.add(id);
77
+ const name = typeof s.name === "string" && s.name.trim() ? s.name.trim().slice(0, 120) : id;
78
+ out.push({ ...s, id, name });
79
+ }
80
+ if (!out.length) { delete doc.sequences; delete doc.sequence; return doc; }
81
+ // without a valid `sequence`, the open one is an entry without a timeline of its own: never strip one that has one
82
+ const named = out.some((s) => s.id === doc.sequence);
83
+ const bare = out.find((s) => !KEYS.some((k) => s[k] !== undefined));
84
+ if (!named && !bare) throw new Error(`sequence must name the open sequence (${out.map((s) => s.id).join(", ")}): every entry carries a timeline of its own`);
85
+ const act = named ? doc.sequence : bare.id;
86
+ for (const s of out) {
87
+ if (s.id === act) { for (const k of KEYS) delete s[k]; continue; }
88
+ // a parked sequence carries its own timeline
89
+ if (s.clips == null) s.clips = [];
90
+ if (!Array.isArray(s.clips)) throw new Error(`sequence ${s.id}: clips must be a list`);
91
+ for (const c of s.clips) if (!isObj(c) || typeof c.id !== "string" || typeof c.start !== "number" || typeof c.duration !== "number")
92
+ throw new Error(`sequence ${s.id}: every clip needs id, numeric start and duration`);
93
+ for (const k of ["width", "height", "fps"]) if (s[k] != null && !(typeof s[k] === "number" && s[k] > 0)) throw new Error(`sequence ${s.id}: ${k} must be a positive number`);
94
+ }
95
+ if (out.length === 1 && out[0].id === MAIN.id && out[0].name === MAIN.name) { delete doc.sequences; delete doc.sequence; return doc; }
96
+ doc.sequences = out;
97
+ doc.sequence = act;
98
+ return doc;
99
+ }
100
+
101
+ /** Make the list explicit (before adding to it). */
102
+ function materialize(doc) {
103
+ if (!Array.isArray(doc.sequences) || !doc.sequences.length) doc.sequences = [{ ...MAIN }];
104
+ doc.sequence = activeId(doc);
105
+ return doc;
106
+ }
107
+ /** The open sequence's keys, copied out of the top level. */
108
+ function takeTop(doc) {
109
+ const out = {};
110
+ for (const k of KEYS) if (doc[k] !== undefined) out[k] = clone(doc[k]);
111
+ if (!Array.isArray(out.clips)) out.clips = [];
112
+ return out;
113
+ }
114
+
115
+ /** Open sequence `id`: the open one's timeline is parked in its entry, `id`'s comes up. */
116
+ function open(doc, id) {
117
+ const target = find(doc, id);
118
+ if (!target) throw new Error(`no sequence ${id} (${entries(doc).map((s) => s.id).join(", ")})`);
119
+ const act = activeId(doc);
120
+ if (id === act) return doc;
121
+ materialize(doc);
122
+ const parked = takeTop(doc);
123
+ const keep = { width: doc.width, height: doc.height, fps: doc.fps };
124
+ doc.sequences = doc.sequences.map((s) => {
125
+ if (s.id === act) return { id: s.id, name: s.name, ...parked };
126
+ if (s.id === id) return { id: s.id, name: s.name };
127
+ return s;
128
+ });
129
+ for (const k of KEYS) {
130
+ if (target[k] !== undefined) doc[k] = target[k];
131
+ else delete doc[k];
132
+ }
133
+ // a sequence always has a canvas and a timeline
134
+ for (const k of ["width", "height", "fps"]) if (!(doc[k] > 0)) doc[k] = keep[k];
135
+ if (!Array.isArray(doc.clips)) doc.clips = [];
136
+ doc.sequence = id;
137
+ return doc;
138
+ }
139
+
140
+ /** A new sequence: {name?, id?, from?: "empty" | "open" | <sequence id>, width?, height?, fps?}.
141
+ * Empty takes the open one's canvas, frame rate and background; a copy takes everything.
142
+ * It is added after the open one (or after `from`) and not opened. */
143
+ function add(doc, opts = {}) {
144
+ materialize(doc);
145
+ const from = opts.from || "empty";
146
+ const id = opts.id ? String(opts.id).trim().slice(0, 40) : "seq_" + uid();
147
+ if (!id) throw new Error("addSequence: the id is empty");
148
+ if (find(doc, id)) throw new Error(`addSequence: sequence ${id} already exists`);
149
+ if (doc.sequences.length >= MAX) throw new Error(`addSequence: a project holds up to ${MAX} sequences`);
150
+ const act = activeId(doc);
151
+ let body, after = act;
152
+ if (from === "empty") {
153
+ body = { width: doc.width, height: doc.height, fps: doc.fps, clips: [] };
154
+ if (doc.background) body.background = doc.background;
155
+ } else if (from === "open" || from === act) {
156
+ body = takeTop(doc);
157
+ } else {
158
+ const src = find(doc, from);
159
+ if (!src) throw new Error(`addSequence: no sequence ${from} to copy`);
160
+ const { id: _i, name: _n, ...rest } = clone(src);
161
+ body = rest;
162
+ after = src.id;
163
+ }
164
+ for (const k of ["width", "height", "fps"]) if (opts[k] != null) {
165
+ const v = +opts[k];
166
+ if (!(v > 0) || (k !== "fps" && (v < 16 || v > 8192)) || (k === "fps" && v > 240)) throw new Error(`addSequence: ${k} ${opts[k]} is out of range`);
167
+ body[k] = k === "fps" ? v : Math.round(v);
168
+ }
169
+ if (from !== "empty" && (opts.width != null || opts.height != null)) delete body.exportFrame; // the crop was for the other size
170
+ const srcName = from === "empty" ? null : (find(doc, from === "open" ? act : from) || {}).name;
171
+ const name = typeof opts.name === "string" && opts.name.trim() ? opts.name.trim().slice(0, 120)
172
+ : srcName ? `${srcName} copy` : `Sequence ${doc.sequences.length + 1}`;
173
+ const entry = { id, name, ...body };
174
+ const at = doc.sequences.findIndex((s) => s.id === after);
175
+ doc.sequences.splice(at + 1, 0, entry);
176
+ return entry;
177
+ }
178
+
179
+ /** Rename (the only thing set on an entry — the open one's timeline is edited at the top level). */
180
+ function rename(doc, id, name) {
181
+ const s = find(doc, id);
182
+ if (!s) throw new Error(`no sequence ${id}`);
183
+ const n = String(name == null ? "" : name).trim().slice(0, 120);
184
+ if (!n) throw new Error("a sequence needs a name");
185
+ materialize(doc);
186
+ doc.sequences = doc.sequences.map((x) => (x.id === id ? { ...x, name: n } : x));
187
+ return normalize(doc);
188
+ }
189
+ /** Move sequence `id` to position `index` (0-based) in the list. */
190
+ function move(doc, id, index) {
191
+ materialize(doc);
192
+ const i = doc.sequences.findIndex((s) => s.id === id);
193
+ if (i < 0) throw new Error(`no sequence ${id}`);
194
+ const [s] = doc.sequences.splice(i, 1);
195
+ doc.sequences.splice(Math.max(0, Math.min(doc.sequences.length, Math.round(+index) || 0)), 0, s);
196
+ return doc;
197
+ }
198
+ /** Delete sequence `id`. The last one stays; deleting the open one opens its neighbour first. */
199
+ function remove(doc, id) {
200
+ const list = entries(doc);
201
+ const i = list.findIndex((s) => s.id === id);
202
+ if (i < 0) throw new Error(`no sequence ${id}`);
203
+ if (list.length === 1) throw new Error("a project keeps at least one sequence");
204
+ if (activeId(doc) === id) open(doc, (list[i + 1] || list[i - 1]).id);
205
+ doc.sequences = doc.sequences.filter((s) => s.id !== id);
206
+ return normalize(doc);
207
+ }
208
+
209
+ /** One line per sequence, for status readouts. */
210
+ function describe(row) {
211
+ const t = Math.round(row.duration), m = Math.floor(t / 60), s = t % 60;
212
+ return `${row.id} "${row.name}"${row.active ? " (open)" : ""} ${row.width}x${row.height}@${row.fps}, ${row.clips} clip(s), ${m}:${String(s).padStart(2, "0")}`;
213
+ }
214
+
215
+ return { KEYS, MAIN, MAX, entries, activeId, find, others, list, normalize, materialize, open, add, rename, move, remove, describe };
216
+ });