// Export one clip (clipExport.mjs): the file name from the clip, the plan -- // which seconds, which gaps, where the sound is silenced -- from the render's // cut or the manifest's edges, the ffmpeg arguments that cut it, and one real // export of a synthetic window measured back (needs ffmpeg). Open folder's // pure half (openFolder.mjs): who may ask, and what it would run. // // Run with: pnpm test:scripts import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { mkdirSync, mkdtempSync, readdirSync, writeFileSync } from "node:fs"; import { rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import test from "node:test"; const CORPUS = mkdtempSync(path.join(os.tmpdir(), "clipexport-corpus-")); const CACHE = mkdtempSync(path.join(os.tmpdir(), "clipexport-cache-")); process.env.CHANNELS_DIR = CORPUS; process.env.UMTOOL_CACHE_DIR = CACHE; const { EXPORT_CONTEXT, contextSeconds, exportArgs, exportClip, exportDate, exportFileOf, exportName, exportNeeds, exportSlug, exportSpan, exportSteps, listExports, planExport, planSeconds, planSummary, spanOf, } = await import("./clipExport.mjs"); const { cannotOpen, hostName, isLoopbackHost, localRequest, openFolder, openersFor } = await import("./openFolder.mjs"); const roots = []; test.after(async () => { for (const r of [CORPUS, CACHE, ...roots]) await rm(r, { recursive: true, force: true }); }); const near = (a, b, what, tol = 1e-6) => assert.ok(Math.abs(a - b) <= tol, `${what}: ${a} vs ${b}`); // ---- names ------------------------------------------------------------------ test("the slug: the first words, lower case, the bleeps and ASR notes left out", () => { assert.equal( exportSlug("So, actual trans people, I've got your back every day, all day. Like Senko, [ __ ] bye."), "so-actual-trans-people-ive-got", ); assert.equal(exportSlug("[ __ ] deal with it [ASR; likely 'time']"), "deal-with-it"); assert.equal(exportSlug("Café crème — très bien"), "cafe-creme-tres-bien"); assert.equal(exportSlug(""), ""); assert.equal(exportSlug(undefined), ""); assert.ok(exportSlug("a".repeat(30) + " " + "b".repeat(30)).length <= 48); }); test("the date: the clip's own, else the on-screen date, else the upload date", () => { assert.equal(exportDate({ date: "2026-08-12" }), "2026-08-12"); assert.equal(exportDate({ date: "12 Aug 2026" }), "2026-08-12"); assert.equal(exportDate({ onscreen: { title: "2 Sept 2025" } }), "2025-09-02"); assert.equal(exportDate({ uploadDate: "20240102" }), "2024-01-02"); assert.equal(exportDate({}), null); }); test("the name: [-raw]--.mp4, the shape of the hand-made exports", () => { const e = { id: "tr3", date: "2026-08-12", quote: "Deal with it, autogynephiliac [ __ ] okay then bye", video: "sx5" }; assert.equal(exportName(e), "tr3-2026-08-12-deal-with-it-autogynephiliac-okay-then.mp4"); assert.equal(exportName(e, { kind: "raw" }), "tr3-raw-2026-08-12-deal-with-it-autogynephiliac-okay-then.mp4"); // No date: today's; no quote: the title; neither: the video id. assert.equal(exportName({ id: "c1", title: "A Stream", video: "v" }, { today: "2026-10-31" }), "c1-2026-10-31-a-stream.mp4"); assert.equal(exportName({ id: "c1", video: "AbC_d" }, { today: "2026-10-31" }), "c1-2026-10-31-abc-d.mp4"); // A clip id is made safe, never a path. assert.match(exportName({ id: "../x y", video: "v" }, { today: "2026-10-31" }), /^x-y-2026-10-31-v\.mp4$/); }); test("an export's file: one plain mp4 name under exports/, nothing else", () => { assert.equal(exportFileOf("/p", "c1-2026-01-01-x.mp4"), path.join("/p", "exports", "c1-2026-01-01-x.mp4")); for (const bad of ["../x.mp4", "a/b.mp4", "x.mov", ".hidden.mp4", "", null, "x..mp4"]) { assert.equal(exportFileOf("/p", bad), null, String(bad)); } }); // ---- the plan ----------------------------------------------------------------- const SRC = { path: "/w/vid_100.00-140.00.mp4", fetchStart: 100 }; const ENTRY = { type: "clip", id: "c1", video: "vid", start: 103, end: 137, cutStart: 110, cutEnd: 130, quote: "hello there" }; test("a cut with no render row: the manifest's play window (the lead-in before the cut), its gaps", () => { const entry = { ...ENTRY, gaps: [{ from: 115, to: 117 }, { from: 120, to: 121.5 }] }; const p = planExport({ entry, render: { fps: 30 }, source: SRC, media: { duration: 40, hasVideo: true } }); assert.equal(p.edges, "manifest"); near(p.from, 109.6, "from: cutStart less the 0.4 s lead-in"); near(p.to, 130, "to"); assert.deepEqual(p.gaps, [{ from: 115, to: 117 }, { from: 120, to: 121.5 }]); near(planSeconds(p), 20.4 - 3.5, "kept seconds"); assert.equal(p.mute, null); assert.ok(p.notes.some((n) => /manifest/.test(n))); }); test("a cut with the render's row: its snapped edges, room's muted picture left off, its gain", () => { const row = { id: "c1", cutStart: 109.2, cutEnd: 131.0, sound: [109.2, 130.4], gaps: [{ from: 115, to: 117 }], gainDb: -2.5 }; const p = planExport({ entry: { ...ENTRY, gaps: [{ from: 115, to: 117 }] }, render: { fps: 30 }, source: SRC, media: { duration: 40 }, row }); assert.equal(p.edges, "render"); near(p.from, 109.2, "from"); near(p.to, 130.4, "to: where the sound stops, not room's tail"); assert.deepEqual(p.gaps, [{ from: 115, to: 117 }]); assert.equal(p.gainDb, -2.5); assert.deepEqual(p.notes, []); }); test("the mute mark: on the export's own clock, after the gaps before it", () => { const entry = { ...ENTRY, gaps: [{ from: 115, to: 117 }], muteFrom: 125 }; const p = planExport({ entry, render: { fps: 30 }, source: SRC, media: { duration: 40 } }); // 125 − 109.6 − 2 s of gap. near(p.mute, 13.4, "mute", 1e-3); }); test("a cut reaching past the cached window starts at its first frame, and says so", () => { const p = planExport({ entry: { ...ENTRY, start: 101, cutStart: 101.2 }, render: {}, source: { path: "/w/x.mp4", fetchStart: 102 }, media: { duration: 30 } }); near(p.from, 102, "from"); near(p.to, 130, "to"); assert.ok(p.notes.some((n) => /before the cached window/.test(n))); }); test("raw: the fetched window -- the clip and the fetch pad, clamped to the file -- with nothing applied", () => { const entry = { ...ENTRY, gaps: [{ from: 115, to: 117 }], muteFrom: 125, audio: { gain: 3 } }; const p = planExport({ entry, render: { fetchPad: 3 }, source: SRC, media: { duration: 36 }, kind: "raw" }); assert.equal(p.kind, "raw"); near(p.from, 100, "from"); near(p.to, 136, "to: the file ends before the pad"); assert.deepEqual(p.gaps, []); assert.equal(p.mute, null); assert.equal(p.audio, null); assert.match(planSummary(p), /the whole window/); }); // ---- the arguments -------------------------------------------------------------- test("the arguments: cut on the input, the gaps out with the build's filter, x264 crf 18, aac 192k, faststart", () => { const entry = { ...ENTRY, gaps: [{ from: 115, to: 117 }], muteFrom: 125 }; const p = planExport({ entry, render: { fps: 30 }, source: SRC, media: { duration: 40 } }); const a = exportArgs(p, "/out/x.mp4"); const at = (flag) => a[a.indexOf(flag) + 1]; assert.equal(at("-ss"), "9.6"); assert.equal(at("-to"), "30"); assert.equal(at("-i"), SRC.path); const fc = at("-filter_complex"); assert.match(fc, /\[0:a\]aresample=async=1/); assert.match(fc, /split=2/); assert.match(fc, /trim=start=0:end=5.4/); assert.match(fc, /trim=start=7.4:end=20.4/); assert.match(fc, /concat=n=2:v=1:a=0\[gv\]/); assert.match(fc, /afade=t=out:st=13.36:d=0.04\[aout\]/, "silent from the mute mark, the fade ending on it"); assert.deepEqual(a.slice(a.indexOf("-map"), a.indexOf("-map") + 4), ["-map", "[gv]", "-map", "[aout]"]); assert.equal(at("-crf"), "18"); assert.equal(at("-c:v"), "libx264"); assert.equal(at("-b:a"), "192k"); assert.equal(at("-movflags"), "+faststart"); assert.equal(a.at(-1), "/out/x.mp4"); }); test("no gaps: the picture mapped straight through; an audio offset reads the sound again, shifted", () => { const p = planExport({ entry: { ...ENTRY, audio: { offset: 200, gain: -3 } }, render: {}, source: SRC, media: { duration: 40 } }); const a = exportArgs(p, "/o.mp4"); assert.deepEqual(a.filter((x) => x === "-i").length, 2, "a second input for the shifted sound"); const second = a.lastIndexOf("-ss"); assert.equal(a[second + 1], "9.4", "the sound read 0.2 s earlier: it plays 0.2 s later"); const fc = a[a.indexOf("-filter_complex") + 1]; assert.match(fc, /^\[1:a\]aresample/); assert.match(fc, /volume=-3dB/); assert.ok(a.includes("0:v:0")); }); test("a source with no picture: sound only", () => { const p = planExport({ entry: ENTRY, render: {}, source: SRC, media: { duration: 40, hasVideo: false } }); const a = exportArgs(p, "/o.mp4"); assert.ok(!a.includes("libx264")); assert.ok(!a.includes("0:v:0")); }); // ---- one real export ------------------------------------------------------------ const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); const probeDuration = (file) => Number(spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file]).stdout.toString().trim()); test("export a clip: the kept seconds land in exports/ under the clip's name; raw is the whole window", { skip: !have && "needs ffmpeg" }, async () => { const root = mkdtempSync(path.join(os.tmpdir(), "clipexport-")); roots.push(root); mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true }); const raw = path.join(root, "out", "clips-raw", "vid1_0.00-12.00.mp4"); const r = spawnSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=s=320x180:r=30:d=12", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=12", "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw, ]); assert.equal(r.status, 0, String(r.stderr)); writeFileSync(path.join(root, "video.manifest.json"), JSON.stringify({ slug: "exp", title: "Export", provenance: { channelSlug: "synth", channelsDir: CORPUS }, render: { width: 320, height: 180, fps: 30, fetchPad: 1, transition: 0 }, timeline: [ { type: "clip", id: "c1", channel: "synth", video: "vid1", start: 2, end: 9, date: "2026-08-12", quote: "Deal with it", gaps: [{ from: 4, to: 5.5 }] }, ], })); const project = { id: "exp", dir: root }; const cut = await exportClip(project, "c1", { kind: "cut" }); assert.equal(cut.name, "c1-2026-08-12-deal-with-it.mp4"); assert.equal(cut.rel, "exports/c1-2026-08-12-deal-with-it.mp4"); near(probeDuration(cut.abs), cut.seconds, "the file plays the kept seconds", 0.12); assert.ok(cut.seconds < 9 - 2, "the gap is out"); const rawExp = await exportClip(project, "c1", { kind: "raw" }); assert.equal(rawExp.name, "c1-raw-2026-08-12-deal-with-it.mp4"); near(probeDuration(rawExp.abs), 9, "1 s pad either side of 2–9 s, no gap", 0.12); // With context: what the cut plays (2–9) and 1 s either side, as recorded -- no gap taken out. const ctx = await exportClip(project, "c1", { kind: "context", context: 1 }); assert.equal(ctx.name, "c1-ctx1-2026-08-12-deal-with-it.mp4"); near(probeDuration(ctx.abs), 9, "1 s either side of 2–9 s, as recorded", 0.15); // The full exchange: a span of its own, its seconds in the name; one past the file is clamped and said. const full = await exportClip(project, "c1", { kind: "raw", span: { from: 0.5, to: 11.5 } }); assert.equal(full.name, "c1-raw-0-12-2026-08-12-deal-with-it.mp4"); near(probeDuration(full.abs), 11, "0.5–11.5 s", 0.15); const past = await exportClip(project, "c1", { kind: "raw", span: { from: 6, to: 20 } }); assert.match(past.notes.join(" "), /ends 8\.00 s before what was asked/); // What a context export needs that is not on disk: 30 s either side is past the 0–12 window. const need = await exportNeeds(project, "c1", { kind: "context", context: 30 }); assert.equal(need.held, false); // The pads are from the clip's extent (2–9), as the editor's fetch-window takes them; the recording starts at 0. assert.deepEqual([need.padBefore, need.padAfter], [2, 30]); const listed = await listExports(root); assert.deepEqual(listed.map((x) => x.name).sort(), [cut.name, rawExp.name, ctx.name, full.name, past.name].sort()); assert.deepEqual(readdirSync(path.join(root, "exports")).filter((n) => n.startsWith(".")), [], "no part file left"); await assert.rejects(exportClip(project, "nope"), /no clip nope/); }); /** The mean luma of a box of the frame at `t` s (0–255). */ function lumaAt(file, t, { x, y, w, h }) { const r = spawnSync("ffmpeg", ["-v", "error", "-ss", String(t), "-i", file, "-frames:v", "1", "-vf", `crop=${w}:${h}:${x}:${y},format=gray`, "-f", "rawvideo", "-"]); assert.equal(r.status, 0, String(r.stderr)); return r.stdout.reduce((n, v) => n + v, 0) / r.stdout.length; } test("hidden regions: a cut and a context export hide them; a raw export is refused unless --uncensored-raw, which says so", { skip: !have && "needs ffmpeg" }, async () => { const root = mkdtempSync(path.join(os.tmpdir(), "clipexport-")); roots.push(root); mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true }); const raw = path.join(root, "out", "clips-raw", "vid2_0.00-12.00.mp4"); const r = spawnSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=white:s=320x180:r=30:d=12", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=12", "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw, ]); assert.equal(r.status, 0, String(r.stderr)); writeFileSync(path.join(root, "video.manifest.json"), JSON.stringify({ slug: "expc", title: "Export", provenance: { channelSlug: "synth", channelsDir: CORPUS }, render: { width: 320, height: 180, fps: 30, fetchPad: 1, transition: 0, censor: [{ video: "vid2", boxes: [[0.5, 0, 0.5, 1]], style: "black" }] }, timeline: [{ type: "clip", id: "c1", channel: "synth", video: "vid2", start: 2, end: 9, date: "2026-08-12", quote: "Deal with it", gaps: [{ from: 4, to: 5.5 }] }], })); const project = { id: "expc", dir: root }; const RIGHT = { x: 200, y: 20, w: 100, h: 140 }; const LEFT = { x: 20, y: 20, w: 100, h: 140 }; for (const o of [{ kind: "cut" }, { kind: "context", context: 1 }]) { const x = await exportClip(project, "c1", o); assert.match(x.notes.join(" "), /1 region\(s\) hidden/); for (const t of [0.5, 4]) { assert.ok(lumaAt(x.abs, t, RIGHT) < 30, `${o.kind}: hidden at ${t} s (${lumaAt(x.abs, t, RIGHT)})`); assert.ok(lumaAt(x.abs, t, LEFT) > 220, `${o.kind}: the rest as recorded at ${t} s`); } } await assert.rejects(exportClip(project, "c1", { kind: "raw" }), (e) => e.status === 409 && /c1 hides 1 region\(s\).*--uncensored-raw/.test(e.message)); const un = await exportClip(project, "c1", { kind: "raw", uncensoredRaw: true }); assert.match(un.notes.join(" "), /UNCENSORED: 1 region\(s\) this clip hides are SHOWN/); assert.ok(lumaAt(un.abs, 1, RIGHT) > 220, "as recorded"); // The job the app runs carries the flag only when asked. const steps = await exportSteps(project, "c1", { kind: "raw", uncensoredRaw: true }); assert.ok(steps.at(-1).argv.includes("--uncensored-raw")); assert.ok(!(await exportSteps(project, "c1", { kind: "raw" })).at(-1).argv.includes("--uncensored-raw")); }); test("export a clip whose window is not on disk: refused, fetch it first", async () => { const root = mkdtempSync(path.join(os.tmpdir(), "clipexport-")); roots.push(root); writeFileSync(path.join(root, "video.manifest.json"), JSON.stringify({ slug: "exp2", provenance: { channelSlug: "synth", channelsDir: CORPUS }, render: { fps: 30 }, timeline: [{ type: "clip", id: "c9", channel: "synth", video: "nothere", start: 2, end: 9 }], })); await assert.rejects(exportClip({ id: "exp2", dir: root }, "c9"), (e) => e.status === 409 && /fetch it first/.test(e.message)); }); test("context and a raw span: their bounds, the span they ask for, and the job that makes them", async () => { assert.equal(contextSeconds(undefined), EXPORT_CONTEXT.default); assert.equal(contextSeconds("12"), 12); for (const bad of [0, 121, "x", -1]) assert.throws(() => contextSeconds(bad), (e) => e.status === 400); assert.equal(spanOf(undefined), null); assert.deepEqual(spanOf({ from: 1.234, to: 9 }), { from: 1.23, to: 9 }); for (const bad of [{ from: 5, to: 5.2 }, { from: -1, to: 4 }, { from: 0, to: 4000 }, {}]) assert.throws(() => spanOf(bad), (e) => e.status === 400); const e = { id: "c1", start: 103, end: 137, cutStart: 110, cutEnd: 130 }; assert.deepEqual(exportSpan(e, { leadIn: 0.4 }, { kind: "cut" }), { from: 109.6, to: 130 }); assert.deepEqual(exportSpan(e, { leadIn: 0.4 }, { kind: "context", context: 10 }), { from: 99.6, to: 140 }); assert.deepEqual(exportSpan(e, { fetchPad: 3 }, { kind: "raw" }), { from: 100, to: 140 }); assert.deepEqual(exportSpan(e, {}, { kind: "raw", span: { from: 50, to: 200 } }), { from: 50, to: 200 }); // Names: the kind in the name, so the three never overwrite each other. const named = { id: "ss1", date: "2026-07-22", quote: "side scrollers full exchange" }; assert.equal(exportName(named, { kind: "context", context: 10 }), "ss1-ctx10-2026-07-22-side-scrollers-full-exchange.mp4"); assert.equal(exportName(named, { kind: "raw", span: { from: 1832.4, to: 1910.2 } }), "ss1-raw-1832-1911-2026-07-22-side-scrollers-full-exchange.mp4"); // The job: the editor's fetch first when asked (its pads), then `umtool export … --progress ndjson`. const steps = await exportSteps({ id: "reports/x", dir: "/r/x" }, "c1", { kind: "context", context: 10, fetch: { padBefore: 14, padAfter: 9 } }); assert.equal(steps.length, 2); assert.ok(steps[0].argv.some((a) => String(a).endsWith("fetch-via-editor.mjs")), "the editor's fetch-window path"); assert.deepEqual(steps[0].argv.slice(-6), ["--pad-before", "14", "--pad-after", "9", "--progress", "ndjson"]); assert.deepEqual(steps[1].argv.slice(2), ["export", "reports/x", "c1", "--context", "10", "--progress", "ndjson"]); assert.equal(steps[1].ndjson, true); const raw = await exportSteps({ id: "reports/x", dir: "/r/x" }, "c1", { kind: "raw", span: { from: 5, to: 50 }, take: "t1" }); assert.equal(raw.length, 1, "nothing to fetch: the export alone"); assert.deepEqual(raw[0].argv.slice(2), ["export", "reports/x", "c1", "--raw", "--from", "5", "--to", "50", "--take", "t1", "--progress", "ndjson"]); assert.match(planSummary({ kind: "context", context: 10, from: 0, to: 30, gaps: [], mute: null, soundFrom: null, edges: "window" }), /the cut with 10 s either side, as recorded/); }); // ---- open folder ---------------------------------------------------------------- test("who may ask to open a folder: this machine, by the headers a browser sends", () => { const h = (o) => ({ get: (k) => o[k] ?? null }); assert.ok(localRequest(h({ host: "localhost:3050" })).ok); assert.ok(localRequest(h({ host: "127.0.0.1:3050", origin: "http://127.0.0.1:3050" })).ok); assert.ok(localRequest(h({ host: "[::1]:3050" })).ok); assert.equal(localRequest(h({ host: "192.168.1.20:3050" })).ok, false); assert.equal(localRequest(h({ host: "localhost:3050", "x-forwarded-for": "10.0.0.5" })).ok, false); assert.equal(localRequest(h({ host: "localhost:3050", origin: "http://phone.lan:3050" })).ok, false); assert.equal(hostName("[::1]:3050"), "::1"); assert.ok(isLoopbackHost("127.0.0.2")); assert.ok(!isLoopbackHost("example.com")); }); test("what would open it: the file manager's ShowItems then xdg-open on Linux, Finder on macOS, nothing elsewhere", () => { const linux = openersFor({ dir: "/p/exports", file: "/p/exports/a b.mp4", platform: "linux" }); assert.deepEqual(linux.map((o) => o.cmd), ["dbus-send", "xdg-open"]); assert.ok(linux[0].args.includes("array:string:file:///p/exports/a%20b.mp4")); assert.deepEqual(linux[1].args, ["/p/exports"]); assert.deepEqual(openersFor({ dir: "/p/exports", platform: "linux" }).map((o) => o.cmd), ["xdg-open"]); assert.deepEqual(openersFor({ dir: "/d", file: "/d/f.mp4", platform: "darwin" }).map((o) => o.args), [["-R", "/d/f.mp4"], ["/d"]]); assert.deepEqual(openersFor({ dir: "/d", platform: "win32" }), []); assert.match(cannotOpen({ platform: "linux", container: true }), /container/); assert.match(cannotOpen({ platform: "win32", container: false }), /win32/); assert.equal(cannotOpen({ platform: "linux", container: false }), null); }); test("open folder: the first opener that answers; every one failing is the reason, never a throw", async () => { const saved = process.env.E2E_UMTOOL_OPEN_FOLDER_LOG; delete process.env.E2E_UMTOOL_OPEN_FOLDER_LOG; try { const asked = []; const ok = await openFolder({ dir: "/d", file: "/d/f.mp4", platform: "linux", container: false, run: async (op) => (asked.push(op.cmd), { code: op.cmd === "dbus-send" ? 1 : 0 }) }); assert.deepEqual(ok, { ok: true, how: "xdg-open", selected: false }); assert.deepEqual(asked, ["dbus-send", "xdg-open"]); const no = await openFolder({ dir: "/d", platform: "linux", container: false, run: async () => ({ code: null, error: "xdg-open is not installed" }) }); assert.equal(no.ok, false); assert.match(no.error, /xdg-open is not installed/); const docker = await openFolder({ dir: "/d", platform: "linux", container: true, run: async () => assert.fail("must not run") }); assert.match(docker.error, /container/); } finally { if (saved !== undefined) process.env.E2E_UMTOOL_OPEN_FOLDER_LOG = saved; } });