fablecut 1.18.0 → 1.19.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/CLAUDE.md +82 -7
- package/README.md +17 -16
- package/app.js +577 -72
- package/command-search.js +79 -0
- package/export-jobs.js +4 -2
- package/index.html +31 -0
- package/mcp-server.js +71 -4
- package/media-files.js +271 -0
- package/package.json +2 -2
- package/server.js +210 -4
- package/style.css +73 -0
- package/transcripts.js +10 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/* FableCut command search (Ctrl/Cmd+K) — how typed words find editor actions,
|
|
2
|
+
panels, settings, Inspector sections, media, clips and shortcuts. Zero
|
|
3
|
+
dependencies. Loaded by the editor as a plain script (global
|
|
4
|
+
`FableCutSearch`) and required by the tests; the editor builds the items
|
|
5
|
+
(app.js) and runs the one that is picked.
|
|
6
|
+
|
|
7
|
+
rank(query, items, limit?) → items that match, best first
|
|
8
|
+
item: {label, group?, keywords?, ...anything}
|
|
9
|
+
score(query, item) → a number, 0 = no match
|
|
10
|
+
|
|
11
|
+
Every typed word has to be found in the item's label, group or keywords:
|
|
12
|
+
at the start of a word (best), inside a word, or as letters in order
|
|
13
|
+
from the start of a word in the label ("rpdl" finds "Ripple delete",
|
|
14
|
+
weakest). Case, accents and punctuation don't matter; letters of any script
|
|
15
|
+
count ("猫" finds "猫.mp4"). A query of symbols only (";") matches items
|
|
16
|
+
whose `keys` hold it. An empty query matches everything, in the order given. */
|
|
17
|
+
(function (root, factory) {
|
|
18
|
+
const api = factory();
|
|
19
|
+
if (typeof module === "object" && module.exports) module.exports = api;
|
|
20
|
+
else root.FableCutSearch = api;
|
|
21
|
+
})(typeof self !== "undefined" ? self : this, function () {
|
|
22
|
+
"use strict";
|
|
23
|
+
|
|
24
|
+
const fold = (s) => String(s == null ? "" : s).toLowerCase().normalize("NFD")
|
|
25
|
+
// accents on Latin, Greek and Cyrillic letters go (Café = cafe); other scripts' marks are
|
|
26
|
+
// part of the letter (दिन is not दीन), so they stay
|
|
27
|
+
.replace(/(\p{Script=Latin}|\p{Script=Greek}|\p{Script=Cyrillic})\p{M}+/gu, "$1")
|
|
28
|
+
.replace(/[^\p{L}\p{N}\p{M}]+/gu, " ").trim();
|
|
29
|
+
const words = (s) => fold(s).split(" ").filter(Boolean);
|
|
30
|
+
|
|
31
|
+
/** How well one typed word matches a text (folded, its words given): 0 when it doesn't.
|
|
32
|
+
Letters in order count only when asked (the label), starting at one of its words. */
|
|
33
|
+
function wordScore(w, text, parts, loose) {
|
|
34
|
+
if (parts.some((p) => p === w)) return 10;
|
|
35
|
+
if (parts.some((p) => p.startsWith(w))) return 8;
|
|
36
|
+
if (text.includes(w)) return 5;
|
|
37
|
+
if (!loose || w.length < 2) return 0;
|
|
38
|
+
for (let s = 0; s < text.length; s++) {
|
|
39
|
+
if (text[s] !== w[0] || (s && text[s - 1] !== " ")) continue;
|
|
40
|
+
let i = 1;
|
|
41
|
+
for (let k = s + 1; k < text.length && i < w.length; k++) if (text[k] === w[i]) i++;
|
|
42
|
+
if (i === w.length) return 2;
|
|
43
|
+
}
|
|
44
|
+
return 0;
|
|
45
|
+
}
|
|
46
|
+
/** A query with no letters or digits: the items whose `keys` hold exactly that. */
|
|
47
|
+
const symbolOnly = (query) => !words(query).length && String(query || "").trim() !== "";
|
|
48
|
+
const symbolScore = (query, item) => {
|
|
49
|
+
const q = String(query).trim();
|
|
50
|
+
// "+ / -" holds "+"; "Shift+;" holds ";"
|
|
51
|
+
return (item.keys || []).some((k) => String(k).trim() === q || String(k).split(/[\s/,·]+/).includes(q) || String(k).split(/[\s/,+·]+/).includes(q)) ? 10 : 0;
|
|
52
|
+
};
|
|
53
|
+
function score(query, item) {
|
|
54
|
+
if (symbolOnly(query)) return symbolScore(query, item);
|
|
55
|
+
const q = words(query);
|
|
56
|
+
if (!q.length) return 1;
|
|
57
|
+
const label = fold(item.label), lp = label.split(" ");
|
|
58
|
+
const extra = fold([item.group, ...(item.keywords || [])].join(" ")), ep = extra.split(" ").filter(Boolean);
|
|
59
|
+
let total = 0;
|
|
60
|
+
for (const w of q) {
|
|
61
|
+
const inLabel = wordScore(w, label, lp, true);
|
|
62
|
+
const inExtra = wordScore(w, extra, ep, false) * 0.6; // the label counts for more than group and keywords
|
|
63
|
+
const s = Math.max(inLabel, inExtra);
|
|
64
|
+
if (!s) return 0;
|
|
65
|
+
total += s;
|
|
66
|
+
}
|
|
67
|
+
if (label.startsWith(q.join(" "))) total += 6; // the label begins with what was typed
|
|
68
|
+
return total - Math.min(label.length, 60) / 100; // a shorter label wins a tie
|
|
69
|
+
}
|
|
70
|
+
function rank(query, items, limit = 50) {
|
|
71
|
+
if (!words(query).length && !symbolOnly(query)) return items.slice(0, limit);
|
|
72
|
+
return items.map((it, i) => ({ it, i, s: score(query, it) }))
|
|
73
|
+
.filter((x) => x.s > 0)
|
|
74
|
+
.sort((a, b) => b.s - a.s || a.i - b.i)
|
|
75
|
+
.slice(0, limit)
|
|
76
|
+
.map((x) => x.it);
|
|
77
|
+
}
|
|
78
|
+
return { rank, score, fold };
|
|
79
|
+
});
|
package/export-jobs.js
CHANGED
|
@@ -112,7 +112,7 @@ function createExportJobs(opts) {
|
|
|
112
112
|
* kind "transcribe" turns files' speech into words and saves them (fablecut_transcribe).
|
|
113
113
|
* A scopes job's `image` flag also returns that still as a JPEG data URL,
|
|
114
114
|
* which is how fablecut_frame shows an agent the composed program picture. */
|
|
115
|
-
request({ kind = "export", range, profile, delivery = null, deliveries = null, time, revision, where = "auto", matte = null, mask = null, track = null, transcribe = null, image = false }) {
|
|
115
|
+
request({ kind = "export", range, profile, delivery = null, deliveries = null, name = null, time, revision, project = null, where = "auto", matte = null, mask = null, track = null, transcribe = null, image = false }) {
|
|
116
116
|
if (!["auto", "tab", "headless"].includes(where)) throw Object.assign(new Error("where must be auto, tab or headless"), { code: 400 });
|
|
117
117
|
if (!["export", "scopes", "track", "transcribe"].includes(kind)) throw Object.assign(new Error("kind must be export, scopes, track or transcribe"), { code: 400 });
|
|
118
118
|
if (time != null && !(Number.isFinite(time) && time >= 0)) throw Object.assign(new Error("time must be seconds ≥ 0"), { code: 400 });
|
|
@@ -125,7 +125,9 @@ function createExportJobs(opts) {
|
|
|
125
125
|
const j = {
|
|
126
126
|
id: "x_" + Math.random().toString(36).slice(2, 10), kind, status: "pending", progress: 0,
|
|
127
127
|
range: range || null, profile: profile || null, delivery: kind === "export" && delivery ? delivery : null,
|
|
128
|
+
name: kind === "export" && typeof name === "string" && name.trim() ? name.trim().slice(0, 120) : null,
|
|
128
129
|
deliveries: kind === "export" && Array.isArray(deliveries) && deliveries.length ? deliveries : null, time: time ?? null, revision: Number.isFinite(revision) ? revision : null,
|
|
130
|
+
project: typeof project === "string" && project ? project : null, // the project it was asked for
|
|
129
131
|
matte: kind === "scopes" && matte ? { clip: String(matte.clip), layer: matte.layer } : null,
|
|
130
132
|
mask: kind === "scopes" && mask ? { clip: String(mask.clip) } : null,
|
|
131
133
|
track: kind === "track" && track ? track : null,
|
|
@@ -142,7 +144,7 @@ function createExportJobs(opts) {
|
|
|
142
144
|
},
|
|
143
145
|
get(id) { const j = jobs.get(id); return j ? view(j) : null; },
|
|
144
146
|
/** What a tab needs to run the job (headless pages fetch it by id). */
|
|
145
|
-
ticket(id) { const j = jobs.get(id); return j ? { id: j.id, kind: j.kind, range: j.range, profile: j.profile, delivery: j.delivery || null, deliveries: j.deliveries || null, time: j.time, revision: j.revision, matte: j.matte || null, mask: j.mask || null, track: j.track || null, transcribe: j.transcribe || null, image: !!j.image, status: j.status } : null; },
|
|
147
|
+
ticket(id) { const j = jobs.get(id); return j ? { id: j.id, kind: j.kind, range: j.range, profile: j.profile, delivery: j.delivery || null, deliveries: j.deliveries || null, name: j.name || null, time: j.time, revision: j.revision, project: j.project || null, matte: j.matte || null, mask: j.mask || null, track: j.track || null, transcribe: j.transcribe || null, image: !!j.image, status: j.status } : null; },
|
|
146
148
|
/** First tab to claim a pending job runs it. */
|
|
147
149
|
claim(id) {
|
|
148
150
|
const j = jobs.get(id);
|
package/index.html
CHANGED
|
@@ -30,6 +30,9 @@
|
|
|
30
30
|
<button type="button" class="btn tiny" data-track-size="l" title="Large tracks">L</button>
|
|
31
31
|
</span>
|
|
32
32
|
</span>
|
|
33
|
+
<button class="btn ghost" id="btnSearch" title="Search actions, panels, settings, media and shortcuts (Ctrl/Cmd+K)" aria-label="Search">
|
|
34
|
+
<svg class="ico" viewBox="0 0 16 16" width="15" height="15" aria-hidden="true"><circle cx="7" cy="7" r="4.6" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M10.4 10.4L14 14" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>
|
|
35
|
+
</button>
|
|
33
36
|
<button class="btn ghost" id="btnSettings" title="Settings" aria-label="Settings">
|
|
34
37
|
<svg class="ico" viewBox="0 0 16 16" width="15" height="15" aria-hidden="true">
|
|
35
38
|
<path fill="currentColor" fill-rule="evenodd" d="M6.71 2.81L6.88.94L9.12.94L9.29 2.81L10.76 3.41L12.2 2.22L13.78 3.8L12.59 5.24L13.19 6.71L15.06 6.88L15.06 9.12L13.19 9.29L12.59 10.76L13.78 12.2L12.2 13.78L10.76 12.59L9.29 13.19L9.12 15.06L6.88 15.06L6.71 13.19L5.24 12.59L3.8 13.78L2.22 12.2L3.41 10.76L2.81 9.29L.94 9.12L.94 6.88L2.81 6.71L3.41 5.24L2.22 3.8L3.8 2.22L5.24 3.41Z M5.15 8a2.85 2.85 0 1 0 5.7 0a2.85 2.85 0 1 0-5.7 0"/>
|
|
@@ -303,6 +306,11 @@
|
|
|
303
306
|
<div class="dialog export-dialog" role="dialog" aria-modal="true" aria-labelledby="exportSetupTitle">
|
|
304
307
|
<h2 id="exportSetupTitle">Export</h2>
|
|
305
308
|
<div class="export-body">
|
|
309
|
+
<div class="export-profile-row" id="exportNameRow">
|
|
310
|
+
<label class="export-profile-label" for="exportName">Save as</label>
|
|
311
|
+
<input type="text" class="export-name" id="exportName" maxlength="120" spellcheck="false" aria-describedby="exportNameNote">
|
|
312
|
+
<p class="dim export-profile-note" id="exportNameNote"></p>
|
|
313
|
+
</div>
|
|
306
314
|
<div class="export-profile-row" id="exportRangeRow">
|
|
307
315
|
<label class="export-profile-label" for="exportRangeSel">Range</label>
|
|
308
316
|
<select class="export-profile-sel" id="exportRangeSel" aria-describedby="exportRangeNote">
|
|
@@ -443,6 +451,7 @@
|
|
|
443
451
|
<div class="export-track-warn hidden" id="exportTrackWarn" role="status"></div>
|
|
444
452
|
</div>
|
|
445
453
|
<div class="dialog-actions">
|
|
454
|
+
<label class="export-skip" title="The Export button then renders straight away with these settings. Settings brings this dialog back."><input type="checkbox" id="exportSkipAsk"> Don't ask again</label>
|
|
446
455
|
<button class="btn dlv-queue-open" id="btnOpenQueue" title="Show the export queue">Queue</button>
|
|
447
456
|
<button class="btn" id="btnCancelSetup">Cancel</button>
|
|
448
457
|
<button class="btn" id="btnBatchExport" title="Queue every checked batch output and start">Export checked</button>
|
|
@@ -491,10 +500,30 @@
|
|
|
491
500
|
</span>
|
|
492
501
|
</label>
|
|
493
502
|
</div>
|
|
503
|
+
<div class="settings-section">
|
|
504
|
+
<h3>Export</h3>
|
|
505
|
+
<label class="settings-row">
|
|
506
|
+
<input type="checkbox" id="setExportAsk">
|
|
507
|
+
<span>
|
|
508
|
+
<span class="settings-label">Ask before exporting</span>
|
|
509
|
+
<span class="settings-hint">Export opens a dialog to name the file and check the settings before it renders. Off: Export renders straight away with the last settings. On by default.</span>
|
|
510
|
+
</span>
|
|
511
|
+
</label>
|
|
512
|
+
</div>
|
|
494
513
|
<div class="dialog-actions"><button class="btn primary" id="btnCloseSettings">Close</button></div>
|
|
495
514
|
</div>
|
|
496
515
|
</div>
|
|
497
516
|
|
|
517
|
+
<!-- ══════════ COMMAND SEARCH (Ctrl/Cmd+K) ══════════ -->
|
|
518
|
+
<div class="overlay hidden" id="cmdkOverlay">
|
|
519
|
+
<div class="cmdk" role="dialog" aria-modal="true" aria-label="Search">
|
|
520
|
+
<input type="text" id="cmdkInput" class="cmdk-input" placeholder="Search actions, panels, settings, media, shortcuts…" autocomplete="off" spellcheck="false"
|
|
521
|
+
role="combobox" aria-expanded="true" aria-controls="cmdkList" aria-autocomplete="list">
|
|
522
|
+
<ul class="cmdk-list" id="cmdkList" role="listbox"></ul>
|
|
523
|
+
<div class="cmdk-foot dim"><kbd>↑</kbd> <kbd>↓</kbd> to move · <kbd>Enter</kbd> to run · <kbd>Esc</kbd> to close</div>
|
|
524
|
+
</div>
|
|
525
|
+
</div>
|
|
526
|
+
|
|
498
527
|
<!-- ══════════ HELP OVERLAY ══════════ -->
|
|
499
528
|
<div class="overlay hidden" id="helpOverlay">
|
|
500
529
|
<div class="dialog help">
|
|
@@ -506,6 +535,7 @@
|
|
|
506
535
|
<section class="keys-sec">
|
|
507
536
|
<h3>Playback</h3>
|
|
508
537
|
<table class="keys">
|
|
538
|
+
<tr><td><kbd>Ctrl</kbd>/<kbd>⌘</kbd>+<kbd>K</kbd></td><td>Search: actions, panels, settings, Inspector sections, media, clips and shortcuts</td></tr>
|
|
509
539
|
<tr><td><kbd>Space</kbd></td><td>Play / pause (Source or Program — whichever is active)</td></tr>
|
|
510
540
|
<tr><td><kbd>J</kbd> <kbd>K</kbd> <kbd>L</kbd></td><td>Shuttle — <kbd>L</kbd> plays forward, <kbd>J</kbd> in reverse (silent); tap again for 1.5× · 2× · 4×, the other key turns around; <kbd>K</kbd> stops</td></tr>
|
|
511
541
|
<tr><td><kbd>K</kbd>+<kbd>J</kbd> / <kbd>K</kbd>+<kbd>L</kbd></td><td>Hold <kbd>K</kbd> and tap to step one frame; hold both to crawl at ¼ speed</td></tr>
|
|
@@ -691,6 +721,7 @@
|
|
|
691
721
|
<script src="sequences.js"></script>
|
|
692
722
|
<script src="templates.js"></script>
|
|
693
723
|
<script src="media-lib.js"></script>
|
|
724
|
+
<script src="command-search.js"></script>
|
|
694
725
|
<script src="delivery.js"></script>
|
|
695
726
|
<script src="mp4-demux.js"></script>
|
|
696
727
|
<script src="app.js"></script>
|
package/mcp-server.js
CHANGED
|
@@ -50,8 +50,8 @@ const ROOT = APP_DIR;
|
|
|
50
50
|
ensureDirs();
|
|
51
51
|
const PORT = process.env.FABLECUT_PORT || 7777;
|
|
52
52
|
const BASE = `http://localhost:${PORT}`;
|
|
53
|
-
// Requests go to the address the server binds
|
|
54
|
-
// resolve to ::1 first
|
|
53
|
+
// Requests go to the address the server binds rather than "localhost", which
|
|
54
|
+
// can resolve to ::1 first; this does not rely on a fallback to 127.0.0.1.
|
|
55
55
|
const API = `http://${process.env.HOST === "::1" ? "[::1]" : "127.0.0.1"}:${PORT}`;
|
|
56
56
|
|
|
57
57
|
/* MCP initialize must echo a version we actually speak. Echoing an unknown
|
|
@@ -231,6 +231,22 @@ const TOOLS = [
|
|
|
231
231
|
required: ["path"],
|
|
232
232
|
},
|
|
233
233
|
},
|
|
234
|
+
{
|
|
235
|
+
name: "fablecut_files",
|
|
236
|
+
description: "The project's files on disk, inside ./media/ (the folder fablecut_import_media copies into): list a folder, make folders, move or rename files and folders, and throw away what isn't needed. Nothing is deleted: trash moves a file into media/.trash/ and restore puts it back. A move repoints every project's media entries at the new place, so no clip goes offline, and the file keeps its transcript. Trash refuses a file a project still uses (removeMedia it first, or force:true to trash it anyway: it goes offline there until restored). The media bin's folders (folderId) are separate: they organize entries, these are the real folders. Paths are relative to media/ ('b-roll/day 1/a.mp4') or /media/… srcs. Move, rename and trash only when the user asked for it.",
|
|
237
|
+
inputSchema: {
|
|
238
|
+
type: "object",
|
|
239
|
+
properties: {
|
|
240
|
+
action: { type: "string", enum: ["list", "mkdir", "move", "trash", "trash-list", "restore"], description: "list (default) · mkdir · move (also renames) · trash · trash-list · restore" },
|
|
241
|
+
dir: { type: "string", description: "list: the folder (default media/ itself) · mkdir: the folder to make (parents too)" },
|
|
242
|
+
from: { type: "string", description: "move: the file or folder" },
|
|
243
|
+
to: { type: "string", description: "move: an existing folder to move it into, or the new path (a rename)" },
|
|
244
|
+
paths: { type: "array", items: { type: "string" }, description: "trash: files or folders" },
|
|
245
|
+
force: { type: "boolean", description: "trash: even files a project still uses (they go offline until restored); move: even while a project can't be read (the file goes offline there)" },
|
|
246
|
+
id: { type: "string", description: "restore: a trashed item's id (trash-list shows them)" },
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
},
|
|
234
250
|
{
|
|
235
251
|
name: "fablecut_encode_profiles",
|
|
236
252
|
description: "List what fablecut_export can make. DELIVERY PRESETS (structured settings, the Export dialog's Preset list): youtube, youtube-shorts, instagram-reels, tiktok, x, linkedin, master (project size), broadcast (ProRes 422 HQ), web (720p), archive (lossless FFV1), custom — plus presets the user saved — each a spec of resolution, fps, codec (h264, hevc, av1, vp9, prores, dnxhr, mpeg2 XDCAM, ffv1), rate control (crf / vbr / cbr), keyframe interval, pixel format, color, container, audio, a file-name template and metadata. {preset:'youtube'} returns one preset's full spec; the encoders this ffmpeg can use are listed (hardware ones only when they work on this machine). ENCODING PROFILES (encoding-profiles.json): raw ffmpeg argument lists plus jpegQuality, extension and color, for anything the presets do not cover; edit the file on disk (hot-reloaded); {profile:'hq'} returns one, detail:true includes every args array. Both are dry-run against ffmpeg when an export starts, so bad settings are refused before rendering.",
|
|
@@ -455,6 +471,7 @@ const TOOLS = [
|
|
|
455
471
|
type: "object",
|
|
456
472
|
properties: {
|
|
457
473
|
range: { type: "string", enum: ["entire", "in-out"], description: "Whole timeline, or the project's inPoint→outPoint (default: in-out when either is set)" },
|
|
474
|
+
name: { type: "string", description: "The file's name, without the extension. Default: a delivery preset's filename pattern, which starts with the project's name (with an encoding profile, the project's name) — so name the file after what it is (e.g. 'salon-promo-15s') whenever the project holds more than this one video. The editor's own Export dialog asks the user for a name; this is that answer. Only the name changes: the preset, delivery or encoding profile the export uses stays the same. Not with outputs" },
|
|
458
475
|
preset: { type: "string", description: "Delivery preset: youtube, youtube-shorts, instagram-reels, tiktok, x, linkedin, master, broadcast, web, archive, custom, or a saved preset's id (fablecut_encode_profiles lists them). The output is reframed to the preset's size — cropped from the middle (or from the project's exportFrame), or padded with reframe:'fit'" },
|
|
459
476
|
delivery: { type: "object", description: "Delivery settings over the preset (or over custom): {width, height (null = the picture's size), fps (null = the project's), reframe:'fill'|'fit'|'stretch', container:'mp4'|'mov'|'mkv'|'webm'|'mxf', video:{codec:'h264'|'hevc'|'av1'|'vp9'|'prores'|'dnxhr'|'mpeg2'|'ffv1', encoder?, rate:'crf'|'vbr'|'cbr', crf, bitrate (kb/s), maxrate (kb/s), keyint (s), pixFmt, speed:'fast'|'balanced'|'best', profile (prores: proxy|lt|standard|hq|4444|4444xq · dnxhr: lb|sq|hq|hqx|444)}, audio:{codec:'aac'|'opus'|'mp3'|'pcm16'|'pcm24'|'flac'|'none', bitrate (kb/s), sampleRate, channels, loudness (LUFS target: -14 streaming/social, -16 podcast, -23 EBU R128, -24 ATSC; null = as mixed), truePeak (dBTP ceiling, default -1)}, color:'bt709'|'bt709-full'|'bt601-625'|'bt601-525', filename:'{project}_{preset}_{res}' (tokens {project} {preset} {res} {w} {h} {fps} {codec} {date} {time} {range} {n}), metadata:{title, artist, description, copyright, date, keywords}}. Anything left out comes from the preset; impossible combinations are corrected and the reply says how. Every finished file is checked against what was asked (size, fps, frames, codecs, length, loudness, true peak, file size) and the reply lists the checks" },
|
|
460
477
|
outputs: { description: "Several files, rendered once per frame rate (up to 8 outputs per render): true = the project's checked batch outputs (project.outputs, set with setProject {outputs:[…]}), or a list like [{preset:'master'}, {preset:'youtube'}, {preset:'instagram-reels'}, {preset:'custom', width:1080, height:1080, filename:'{project}_square_{res}'}, {preset:'web', filename:'{project}_preview_{res}'}]. Outputs with the same fps share one render; the reply lists every file", anyOf: [{ type: "boolean" }, { type: "array", items: { anyOf: [{ type: "string" }, { type: "object" }] } }] },
|
|
@@ -1345,6 +1362,51 @@ async function proxyTool(args) {
|
|
|
1345
1362
|
};
|
|
1346
1363
|
return list.map(line).join("\n") + (busy() ? "\nStill working — call fablecut_proxy again (without create) to check." : "");
|
|
1347
1364
|
}
|
|
1365
|
+
/* ── Files in media/ (fablecut_files) ── */
|
|
1366
|
+
async function filesTool(args) {
|
|
1367
|
+
if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
|
|
1368
|
+
const action = args.action || "list";
|
|
1369
|
+
const body = { action, dir: args.dir, from: args.from, to: args.to, paths: args.paths, force: args.force, id: args.id };
|
|
1370
|
+
const r = await apiJSON("POST", "/api/files", body);
|
|
1371
|
+
const name = (src) => { try { return decodeURIComponent(String(src).replace(/^\/media\//, "")); } catch { return src; } };
|
|
1372
|
+
const restoreWith = (t) => `Trashed ${name(t.src)} (id ${t.id} — restore with {action:"restore", id:"${t.id}"})${t.warning ? ` — ${t.warning}` : ""}`;
|
|
1373
|
+
if (r.status !== 200) {
|
|
1374
|
+
// a trash that stopped part-way: the ones that went still need their ids
|
|
1375
|
+
if (r.body?.trashed?.length) throw new Error(r.body.error + "\n" + r.body.trashed.map(restoreWith).join("\n"));
|
|
1376
|
+
throw new Error(r.body?.error || `files request failed (${r.status})`);
|
|
1377
|
+
}
|
|
1378
|
+
const b = r.body;
|
|
1379
|
+
const kb = (n) => n >= 1048576 ? (n / 1048576).toFixed(1) + " MB" : Math.max(1, Math.round(n / 1024)) + " KB";
|
|
1380
|
+
if (action === "list") {
|
|
1381
|
+
const lines = [`media/${b.dir ? b.dir + "/" : ""} — ${b.folders.length} folder${b.folders.length === 1 ? "" : "s"}, ${b.files.length} file${b.files.length === 1 ? "" : "s"}`];
|
|
1382
|
+
for (const f of b.folders) lines.push(` ${f}/`);
|
|
1383
|
+
for (const f of b.files) lines.push(` ${f.name} ${kb(f.size)} ${f.src}`);
|
|
1384
|
+
return lines.join("\n");
|
|
1385
|
+
}
|
|
1386
|
+
if (action === "mkdir") return `Made media/${b.dir}/`;
|
|
1387
|
+
if (action === "move") {
|
|
1388
|
+
if (b.from === b.to) return "Nothing moved (it is already there).";
|
|
1389
|
+
if (!b.moved.length) return `Moved ${name(b.from)}/ → ${name(b.to)}/ (an empty folder)`;
|
|
1390
|
+
const lines = [`Moved ${b.moved.length} file${b.moved.length === 1 ? "" : "s"}:`, ...b.moved.slice(0, 20).map((m) => ` ${name(m.from)} → ${name(m.to)}`)];
|
|
1391
|
+
if (b.moved.length > 20) lines.push(` … +${b.moved.length - 20} more`);
|
|
1392
|
+
lines.push(b.repointed.length ? "Media entries repointed: " + b.repointed.map((x) => `${x.media} in ${x.open ? "the open project" : `"${x.project}"`}`).join(", ") : "No project used them.");
|
|
1393
|
+
if (b.warning) lines.push("Warning: " + b.warning);
|
|
1394
|
+
return lines.join("\n");
|
|
1395
|
+
}
|
|
1396
|
+
if (action === "trash") {
|
|
1397
|
+
const lines = b.trashed.map(restoreWith);
|
|
1398
|
+
if (b.stillThere?.length) lines.push("Still playing (part of the original stayed): " + b.stillThere.map((u) => `"${u.name}"`).join(", "));
|
|
1399
|
+
if (b.offline.length) lines.push("Now OFFLINE: " + b.offline.map((u) => `"${u.name}" in ${u.open ? "the open project" : `"${u.project}"`}`).join(", "));
|
|
1400
|
+
return lines.join("\n");
|
|
1401
|
+
}
|
|
1402
|
+
if (action === "trash-list") {
|
|
1403
|
+
if (!b.items.length) return "The trash is empty.";
|
|
1404
|
+
return b.items.map((t) => `${t.id} ${name(t.src)}${t.kind === "folder" ? `/ (${t.size} files)` : " " + kb(t.size)} trashed ${t.trashed}`).join("\n");
|
|
1405
|
+
}
|
|
1406
|
+
if (action === "restore") return `Restored ${name(b.restored.src)}` + (b.restored.warning ? ` — ${b.restored.warning}` : "");
|
|
1407
|
+
return JSON.stringify(b);
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1348
1410
|
async function exportTool(args) {
|
|
1349
1411
|
if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
|
|
1350
1412
|
let startNote = "";
|
|
@@ -1359,7 +1421,10 @@ async function exportTool(args) {
|
|
|
1359
1421
|
if (r.status !== 200) throw new Error(r.body?.error || "no such export job");
|
|
1360
1422
|
job = r.body;
|
|
1361
1423
|
} else {
|
|
1362
|
-
|
|
1424
|
+
if (args.name != null && typeof args.name !== "string") throw new Error("name is a string: the file's name, without the extension");
|
|
1425
|
+
const name = args.name?.trim() || undefined;
|
|
1426
|
+
if (name && args.outputs) throw new Error("name goes with one file, not with outputs (give each output its own filename)");
|
|
1427
|
+
const r = await apiJSON("POST", "/api/export/request", { range: args.range, profile: args.profile, preset: args.preset, delivery: args.delivery, outputs: args.outputs, name, where: args.where || "auto" });
|
|
1363
1428
|
if (r.status !== 200) throw new Error(r.body?.error || `export request failed (${r.status})`);
|
|
1364
1429
|
job = r.body;
|
|
1365
1430
|
if (job.notes && job.notes.length) startNote = `Settings adjusted: ${job.notes.join("; ")}\n`;
|
|
@@ -1911,6 +1976,8 @@ async function callTool(name, args, attempt = 0) {
|
|
|
1911
1976
|
`REMAKE RECIPE: 1) set project width/height/fps to ${bp.width}x${bp.height} @ ${bp.fps} — 2) write beats[] into project markers — 3) extracted music on A1 — 4) one clip per shots[] entry at the same start/duration on V1 (hard cuts; footage energy should track each shot's energy value) — 5) biggest moment on drop (${bp.drop}s)${bp.bpm ? ` — tempo ${bp.bpm} BPM` : ""}. Full recipe: fablecut_docs → "Remake a reference video".`,
|
|
1912
1977
|
].join("\n");
|
|
1913
1978
|
}
|
|
1979
|
+
case "fablecut_files":
|
|
1980
|
+
return filesTool(args);
|
|
1914
1981
|
case "fablecut_import_media": {
|
|
1915
1982
|
const src = args.path;
|
|
1916
1983
|
if (!src) throw new Error("path is required");
|
|
@@ -2013,7 +2080,7 @@ async function handle(msg) {
|
|
|
2013
2080
|
result: {
|
|
2014
2081
|
protocolVersion: negotiateProtocolVersion(params?.protocolVersion),
|
|
2015
2082
|
capabilities: { tools: {} },
|
|
2016
|
-
serverInfo: { name: "fablecut", version: "1.
|
|
2083
|
+
serverInfo: { name: "fablecut", version: "1.19.0" },
|
|
2017
2084
|
},
|
|
2018
2085
|
});
|
|
2019
2086
|
}
|
package/media-files.js
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
/* The project's files on disk: folders, moves and a trash, all inside media/.
|
|
2
|
+
|
|
3
|
+
The media bin's folders and collections only organize entries in
|
|
4
|
+
project.json; this is the folder itself — so an agent (or the user) can
|
|
5
|
+
tidy downloads into subfolders, rename a file, and throw away what isn't
|
|
6
|
+
used, without leaving the editor. Nothing here deletes a file: "trash"
|
|
7
|
+
moves it into media/.trash/<id>/files/ beside a note of where it came from
|
|
8
|
+
(<id>/item.json), and "restore" puts it back. Dot-folders are never listed,
|
|
9
|
+
served as media or offered by Relink, so trashed files are out of the way
|
|
10
|
+
but still there.
|
|
11
|
+
|
|
12
|
+
createMediaFiles({mediaDir}) → {
|
|
13
|
+
list(dir?) → {dir, folders:[name], files:[{name, src, size}]} (one level)
|
|
14
|
+
mkdir(dir) → {dir} (parents too; an existing one is fine)
|
|
15
|
+
move(from, to, {exact}?) → {from, to, moved:[{from, to}]} (srcs: the item, and every file in it;
|
|
16
|
+
exact: `to` is the new path itself, never a folder to go into)
|
|
17
|
+
trash(paths) → {trashed:[{id, src}], moved:[{from, to}]}
|
|
18
|
+
trashList() → [{id, src, kind, size, trashed}]
|
|
19
|
+
restore(id) → {restored:{id, src}, moved:[{from, to}]}
|
|
20
|
+
filesOf(path) → the /media/… srcs of the files at or under a path
|
|
21
|
+
pathOf(src) → the absolute path of a /media/… src inside media/, or null
|
|
22
|
+
}
|
|
23
|
+
canonicalSrc(src) → a /media/… src decoded with doubled slashes folded,
|
|
24
|
+
the form two srcs of the same file share
|
|
25
|
+
Paths are relative to media/ ("b-roll/day 1/a.mp4") or /media/… srcs; "..",
|
|
26
|
+
dot-segments and symlinks on the way are refused. `moved` lists every file
|
|
27
|
+
that changed place as /media/… srcs, so callers can repoint media entries. */
|
|
28
|
+
"use strict";
|
|
29
|
+
const fs = require("fs");
|
|
30
|
+
const path = require("path");
|
|
31
|
+
|
|
32
|
+
const TRASH = ".trash";
|
|
33
|
+
const toSrc = (rel) => "/media/" + rel.split(/[\\/]/).map(encodeURIComponent).join("/");
|
|
34
|
+
function canonicalSrc(src) {
|
|
35
|
+
let s = String(src || "").split("?")[0];
|
|
36
|
+
try { s = decodeURIComponent(s); } catch { }
|
|
37
|
+
return s.replace(/\\/g, "/").replace(/\/{2,}/g, "/");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function createMediaFiles({ mediaDir }) {
|
|
41
|
+
const root = path.resolve(mediaDir);
|
|
42
|
+
const trashDir = path.join(root, TRASH);
|
|
43
|
+
|
|
44
|
+
/** Throws when a path on the way from media/ to `abs` (as far as it exists) is a symlink. */
|
|
45
|
+
function noLinks(abs) {
|
|
46
|
+
const parts = path.relative(root, abs).split(path.sep).filter(Boolean);
|
|
47
|
+
let cur = root;
|
|
48
|
+
for (const part of parts) {
|
|
49
|
+
cur = path.join(cur, part);
|
|
50
|
+
let st;
|
|
51
|
+
try { st = fs.lstatSync(cur); } catch { return; } // nothing there yet: nothing to follow
|
|
52
|
+
if (st.isSymbolicLink()) throw new Error(`${JSON.stringify(path.relative(root, cur).split(path.sep).join("/"))} is a link — FableCut only moves real files and folders in media/`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** "a/b.mp4" or "/media/a/b.mp4" → {rel, abs}; throws on anything outside media/.
|
|
56
|
+
raw: a path as stored (no "/media" / "media" shorthand for the folder itself). */
|
|
57
|
+
function resolve(p, { allowRoot = false, raw = false } = {}) {
|
|
58
|
+
let s = String(p == null ? "" : p).replace(/\\/g, "/");
|
|
59
|
+
if (!raw) s = s.trim(); // a stored path keeps its spaces: " take.mp4" is a real name
|
|
60
|
+
if (!raw) {
|
|
61
|
+
if (s.startsWith("/media/")) { try { s = decodeURIComponent(s.slice(7)); } catch { throw new Error(`bad path ${JSON.stringify(p)}`); } }
|
|
62
|
+
else if (s === "/media" || s === "media" || s === "media/") s = "";
|
|
63
|
+
}
|
|
64
|
+
s = s.replace(/^\/+|\/+$/g, "");
|
|
65
|
+
const parts = s ? s.split("/") : [];
|
|
66
|
+
if (parts.some((x) => !x || x === "." || x === ".." || x.startsWith(".")))
|
|
67
|
+
throw new Error(`${JSON.stringify(p)} is not a path inside media/ (no "..", no dot-folders)`);
|
|
68
|
+
if (parts.some((x) => /[<>:"|?*\x00-\x1f]/.test(x) || x.length > 120))
|
|
69
|
+
throw new Error(`${JSON.stringify(p)} has a name that isn't allowed (< > : " | ? * or over 120 characters)`);
|
|
70
|
+
if (!parts.length && !allowRoot) throw new Error("name a file or folder inside media/");
|
|
71
|
+
const rel = parts.join("/");
|
|
72
|
+
const abs = rel ? path.join(root, ...parts) : root;
|
|
73
|
+
noLinks(abs);
|
|
74
|
+
return { rel, abs };
|
|
75
|
+
}
|
|
76
|
+
const stat = (abs) => { try { return fs.statSync(abs); } catch { return null; } };
|
|
77
|
+
/** Every file under `abs` as paths relative to media/ (a file: itself). */
|
|
78
|
+
function filesUnder(abs) {
|
|
79
|
+
const st = stat(abs);
|
|
80
|
+
if (!st) return [];
|
|
81
|
+
if (st.isFile()) return [path.relative(root, abs).split(path.sep).join("/")];
|
|
82
|
+
const out = [];
|
|
83
|
+
const walk = (d) => {
|
|
84
|
+
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
|
85
|
+
const full = path.join(d, e.name);
|
|
86
|
+
if (e.isSymbolicLink()) throw new Error(`${JSON.stringify(path.relative(root, full).split(path.sep).join("/"))} is a link — FableCut only moves real files and folders in media/`);
|
|
87
|
+
if (e.isDirectory()) walk(full); else if (e.isFile()) out.push(path.relative(root, full).split(path.sep).join("/"));
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
walk(abs);
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
const relOf = (abs) => path.relative(root, abs).split(path.sep).join("/");
|
|
94
|
+
const taken = (toAbs) => Object.assign(new Error(`${JSON.stringify(relOf(toAbs))} already exists — pick another name`), { code: "EEXIST" });
|
|
95
|
+
/** Put `fromAbs` at `toAbs` without replacing anything there: a file is hard-linked to
|
|
96
|
+
its new name (which fails if the name is taken) and then unlinked; a folder is
|
|
97
|
+
renamed, which never lands on a folder with something in it. */
|
|
98
|
+
function publish(fromAbs, toAbs) {
|
|
99
|
+
if (fs.lstatSync(fromAbs).isFile()) {
|
|
100
|
+
try { fs.linkSync(fromAbs, toAbs); }
|
|
101
|
+
catch (e) {
|
|
102
|
+
if (e.code === "EEXIST") throw taken(toAbs);
|
|
103
|
+
if (e.code === "EXDEV") throw e;
|
|
104
|
+
// a file system without hard links: check, then rename
|
|
105
|
+
if (fs.existsSync(toAbs)) throw taken(toAbs);
|
|
106
|
+
fs.renameSync(fromAbs, toAbs);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
fs.unlinkSync(fromAbs);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
// a folder: Windows never renames onto an existing folder; elsewhere an empty folder made
|
|
113
|
+
// here first holds the name (mkdir fails if it is taken), and the rename replaces only it
|
|
114
|
+
if (process.platform === "win32") {
|
|
115
|
+
if (fs.existsSync(toAbs)) throw taken(toAbs);
|
|
116
|
+
fs.renameSync(fromAbs, toAbs);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
try { fs.mkdirSync(toAbs); } catch (e) { if (e.code === "EEXIST") throw taken(toAbs); throw e; }
|
|
120
|
+
try { fs.renameSync(fromAbs, toAbs); }
|
|
121
|
+
catch (e) { try { fs.rmdirSync(toAbs); } catch { } throw e.code === "ENOTEMPTY" || e.code === "EEXIST" ? taken(toAbs) : e; }
|
|
122
|
+
}
|
|
123
|
+
/** Move `fromAbs` to `toAbs` (both inside media/), creating the folder above; a name
|
|
124
|
+
taken meanwhile is refused, never replaced. Across drives the copy goes to a staging
|
|
125
|
+
name first (timestamps kept, so the file's transcript still matches it) and takes
|
|
126
|
+
the final name only once it is complete. If removing the original then fails, the
|
|
127
|
+
error says so with `published: true`: the copy is whole and stays. */
|
|
128
|
+
function rename(fromAbs, toAbs) {
|
|
129
|
+
fs.mkdirSync(path.dirname(toAbs), { recursive: true });
|
|
130
|
+
try { publish(fromAbs, toAbs); return; }
|
|
131
|
+
catch (e) { if (e.code !== "EXDEV") throw e; }
|
|
132
|
+
const stage = path.join(path.dirname(toAbs), `.fc-move-${process.pid}-${Date.now().toString(36)}`);
|
|
133
|
+
try {
|
|
134
|
+
fs.cpSync(fromAbs, stage, { recursive: true, errorOnExist: true, force: false, preserveTimestamps: true });
|
|
135
|
+
publish(stage, toAbs);
|
|
136
|
+
} catch (e) {
|
|
137
|
+
fs.rmSync(stage, { recursive: true, force: true });
|
|
138
|
+
throw e;
|
|
139
|
+
}
|
|
140
|
+
try { fs.rmSync(fromAbs, { recursive: true, force: true }); }
|
|
141
|
+
catch (e) {
|
|
142
|
+
throw Object.assign(new Error(`copied to ${relOf(toAbs)}, but the original could not be removed (${e.code || e.message}) — both copies are there`), { published: true });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** [{from, to}] srcs for what moved from `fromRel` to `toRel`, given the files that were under fromRel. */
|
|
146
|
+
const pairs = (files, fromRel, toRel) => files.map((f) => ({ from: toSrc(f), to: toSrc(toRel + f.slice(fromRel.length)) }));
|
|
147
|
+
const readItem = (id) => {
|
|
148
|
+
if (!/^t[a-z0-9]{4,20}$/.test(String(id || ""))) return null;
|
|
149
|
+
try { return JSON.parse(fs.readFileSync(path.join(trashDir, id, "item.json"), "utf8")); } catch { return null; }
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
filesOf(p) { const r = resolve(p); if (!stat(r.abs)) throw new Error(`no file or folder ${JSON.stringify(r.rel)} in media/`); return filesUnder(r.abs).map(toSrc); },
|
|
154
|
+
pathOf(src) { try { const r = resolve(src); return stat(r.abs)?.isFile() ? r.abs : null; } catch { return null; } },
|
|
155
|
+
list(dir) {
|
|
156
|
+
const { rel, abs } = resolve(dir, { allowRoot: true });
|
|
157
|
+
const st = stat(abs);
|
|
158
|
+
if (!st || !st.isDirectory()) throw new Error(`no folder ${rel ? JSON.stringify(rel) : "media/"}`);
|
|
159
|
+
const folders = [], files = [];
|
|
160
|
+
for (const e of fs.readdirSync(abs, { withFileTypes: true })) {
|
|
161
|
+
if (e.name.startsWith(".") || e.isSymbolicLink()) continue;
|
|
162
|
+
const r = rel ? rel + "/" + e.name : e.name;
|
|
163
|
+
if (e.isDirectory()) folders.push(e.name);
|
|
164
|
+
else if (e.isFile()) files.push({ name: e.name, src: toSrc(r), size: stat(path.join(abs, e.name))?.size || 0 });
|
|
165
|
+
}
|
|
166
|
+
const byName = (a, b) => String(a.name || a).localeCompare(String(b.name || b), undefined, { numeric: true });
|
|
167
|
+
return { dir: rel, folders: folders.sort(byName), files: files.sort(byName) };
|
|
168
|
+
},
|
|
169
|
+
mkdir(dir) {
|
|
170
|
+
const { rel, abs } = resolve(dir);
|
|
171
|
+
const st = stat(abs);
|
|
172
|
+
if (st && !st.isDirectory()) throw new Error(`${JSON.stringify(rel)} is a file`);
|
|
173
|
+
fs.mkdirSync(abs, { recursive: true });
|
|
174
|
+
return { dir: rel };
|
|
175
|
+
},
|
|
176
|
+
move(from, to, { exact = false } = {}) {
|
|
177
|
+
if (to == null || String(to).trim() === "") throw new Error("say where to move it: a folder, a new name, or \"/media/\" for the top of media/");
|
|
178
|
+
const a = resolve(from), b = resolve(to, { allowRoot: true });
|
|
179
|
+
const st = stat(a.abs);
|
|
180
|
+
if (!st) throw new Error(`no file or folder ${JSON.stringify(a.rel)} in media/`);
|
|
181
|
+
// into an existing folder keeps the name; otherwise `to` is the new path
|
|
182
|
+
const into = !exact && stat(b.abs)?.isDirectory();
|
|
183
|
+
const destRel = into ? (b.rel ? b.rel + "/" : "") + path.basename(a.abs) : b.rel;
|
|
184
|
+
const destAbs = into ? path.join(b.abs, path.basename(a.abs)) : b.abs;
|
|
185
|
+
if (destAbs === a.abs) return { from: toSrc(a.rel), to: toSrc(a.rel), moved: [] };
|
|
186
|
+
if (st.isDirectory() && (destAbs + path.sep).startsWith(a.abs + path.sep)) throw new Error(`can't move ${JSON.stringify(a.rel)} into itself`);
|
|
187
|
+
if (stat(destAbs)) throw new Error(`${JSON.stringify(destRel)} already exists — pick another name`);
|
|
188
|
+
noLinks(destAbs);
|
|
189
|
+
const files = filesUnder(a.abs);
|
|
190
|
+
const result = { from: toSrc(a.rel), to: toSrc(destRel), moved: pairs(files, a.rel, destRel) };
|
|
191
|
+
// a copy that is whole at the new place but left part of the original: it moved (with a warning)
|
|
192
|
+
try { rename(a.abs, destAbs); } catch (e) { if (e.published) e.result = result; throw e; }
|
|
193
|
+
return result;
|
|
194
|
+
},
|
|
195
|
+
trash(paths) {
|
|
196
|
+
const list = (Array.isArray(paths) ? paths : [paths]).map((p) => resolve(p));
|
|
197
|
+
for (const r of list) if (!stat(r.abs)) throw new Error(`no file or folder ${JSON.stringify(r.rel)} in media/`);
|
|
198
|
+
// one item inside another would be gone by the time its turn came
|
|
199
|
+
for (const r of list) for (const o of list) {
|
|
200
|
+
if (r === o) continue;
|
|
201
|
+
if (r.rel === o.rel) throw new Error(`${JSON.stringify(r.rel)} is listed twice`);
|
|
202
|
+
if ((r.rel + "/").startsWith(o.rel + "/")) throw new Error(`${JSON.stringify(r.rel)} is inside ${JSON.stringify(o.rel)} — trash the folder, or the file, not both`);
|
|
203
|
+
}
|
|
204
|
+
const trashed = [], moved = [];
|
|
205
|
+
// a failure part-way through says what already went (`partial`), so those can be restored
|
|
206
|
+
const fail = (e, src) => { throw Object.assign(e, { partial: { trashed, moved, failed: src } }); };
|
|
207
|
+
fs.mkdirSync(trashDir, { recursive: true });
|
|
208
|
+
for (const r of list) {
|
|
209
|
+
const st = stat(r.abs);
|
|
210
|
+
const files = filesUnder(r.abs);
|
|
211
|
+
// each item's folder is made without `recursive`, so a taken id is never shared
|
|
212
|
+
let id, box;
|
|
213
|
+
for (let i = 0; ; i++) {
|
|
214
|
+
id = "t" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
|
|
215
|
+
box = path.join(trashDir, id);
|
|
216
|
+
try { fs.mkdirSync(box); break; }
|
|
217
|
+
catch (e) { if (e.code !== "EEXIST" || i > 20) fail(e, toSrc(r.rel)); }
|
|
218
|
+
}
|
|
219
|
+
// the record goes first: if the move then fails it is removed, and nothing is lost either way
|
|
220
|
+
try {
|
|
221
|
+
fs.writeFileSync(path.join(box, "item.json"), JSON.stringify({
|
|
222
|
+
id, src: toSrc(r.rel), rel: r.rel, kind: st.isDirectory() ? "folder" : "file",
|
|
223
|
+
size: st.isDirectory() ? files.length : st.size, trashed: new Date().toISOString(),
|
|
224
|
+
}, null, 2));
|
|
225
|
+
rename(r.abs, path.join(box, "files", path.basename(r.abs)));
|
|
226
|
+
} catch (e) {
|
|
227
|
+
if (e.published) {
|
|
228
|
+
// the trash holds a whole copy, and part of the original may be gone: keep the copy
|
|
229
|
+
trashed.push({ id, src: toSrc(r.rel), warning: e.message });
|
|
230
|
+
for (const f of files) moved.push({ from: toSrc(f), to: null });
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
fs.rmSync(box, { recursive: true, force: true });
|
|
234
|
+
fail(e, toSrc(r.rel));
|
|
235
|
+
}
|
|
236
|
+
trashed.push({ id, src: toSrc(r.rel) });
|
|
237
|
+
for (const f of files) moved.push({ from: toSrc(f), to: null });
|
|
238
|
+
}
|
|
239
|
+
return { trashed, moved };
|
|
240
|
+
},
|
|
241
|
+
trashList() {
|
|
242
|
+
let ids = [];
|
|
243
|
+
try { ids = fs.readdirSync(trashDir); } catch { return []; }
|
|
244
|
+
const out = [];
|
|
245
|
+
for (const id of ids) {
|
|
246
|
+
const it = readItem(id);
|
|
247
|
+
if (it) out.push({ id: it.id, src: it.src, kind: it.kind, size: it.size, trashed: it.trashed });
|
|
248
|
+
}
|
|
249
|
+
return out.sort((a, b) => String(b.trashed).localeCompare(String(a.trashed)));
|
|
250
|
+
},
|
|
251
|
+
restore(id) {
|
|
252
|
+
const it = readItem(id);
|
|
253
|
+
if (!it) throw new Error(`no trashed item ${JSON.stringify(id)} (list the trash first)`);
|
|
254
|
+
const back = resolve(it.rel, { raw: true });
|
|
255
|
+
if (stat(back.abs)) throw new Error(`${JSON.stringify(it.rel)} exists again — move it away first, then restore`);
|
|
256
|
+
const src = path.join(trashDir, id, "files", path.basename(back.abs));
|
|
257
|
+
if (!fs.existsSync(src)) throw new Error(`trashed item ${id} has no files left to restore`);
|
|
258
|
+
const inner = filesUnder(src).map((f) => f.slice((TRASH + "/" + id + "/files/").length));
|
|
259
|
+
let warning;
|
|
260
|
+
try { rename(src, back.abs); }
|
|
261
|
+
catch (e) { if (!e.published) throw e; warning = e.message; }
|
|
262
|
+
// the file is back: a record left behind is only clutter in the trash list
|
|
263
|
+
try { if (!warning) fs.rmSync(path.join(trashDir, id), { recursive: true, force: true }); }
|
|
264
|
+
catch (e) { warning = `restored, but its trash entry ${id} couldn't be removed (${e.code || e.message})`; }
|
|
265
|
+
const parent = back.rel.slice(0, back.rel.length - path.basename(back.abs).length);
|
|
266
|
+
return { restored: { id, src: it.src, ...(warning ? { warning } : {}) }, moved: inner.map((f) => ({ from: null, to: toSrc(parent + f) })) };
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
module.exports = { createMediaFiles, canonicalSrc, TRASH };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fablecut",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.19.0",
|
|
4
4
|
"description": "Zero-dependency browser video editor that AI agents can drive — JSON timeline, MCP server, REST API, live-reloading UI.",
|
|
5
5
|
"main": "server.js",
|
|
6
6
|
"bin": {
|
|
@@ -42,6 +42,6 @@
|
|
|
42
42
|
"mcpName": "io.github.ronak-create/fablecut",
|
|
43
43
|
"license": "MIT",
|
|
44
44
|
"engines": {
|
|
45
|
-
"node": ">=
|
|
45
|
+
"node": ">=22"
|
|
46
46
|
}
|
|
47
47
|
}
|