// The inspector's CLI twins (umtool redesign L6; every knob the UI sets has one, docs/knobs.md): // // umtool provenance [ls] [--json] // umtool provenance set [--site-origin URL|""] [--channel-slug SLUG|""] [--channel "Name"|""] [--json] // umtool title [""] [--subtitle "…" | --no-subtitle] [--json] // umtool still <project> <clip> --at <source s> [--take <take>] [--json] | umtool still <project> ls [--json] // umtool timeline <project> teaser-insert [--at start|end | --after <id> | --before <id>] [--id ID] [--beat S] // --line "<text>" [--break "<words>"] [--hold S] [--line …] | --lines-json <json|@file> [--json] // umtool links <project> --embed-ids [--clips a,b] [--dry-run] [--json] // // Each the same writer as its inspector panel (inspectorEdits.mjs, stillGrab.mjs): the draft written, one undo // point per write (`umtool timeline <p> undo` takes it back). Exit 0 done, 1 refused, 2 a usage error. // Plain ESM: the CLI runs it under bare node. import { readFile } from "node:fs/promises"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { StaleToken, StructureRefused, manifestToken } from "./manifest.mjs"; import { insertTeaser, provenanceView, setSiteVideos, updateProvenance, updateTitle } from "./inspectorEdits.mjs"; class CliError extends Error {} export const PROVENANCE_USAGE = [ "usage: umtool provenance <project> [ls] [--json]", " umtool provenance <project> set [--site-origin <https://…>] [--channel-slug <slug>] [--channel \"<name>\"] [--json]", " THE PROJECT'S PROVENANCE: provenance.siteOrigin (the archive its QRs open), provenance.channelSlug (the channel a", " clip with no `channel` is from -- `check` blocks without it), provenance.channel (the sweep's display name). An", " empty value removes a key. One write, one undo point. The link policy: umtool link-policy <p>.", ].join("\n"); export const TITLE_USAGE = [ "usage: umtool title <project> [\"<title>\"] [--subtitle \"<line>\" | --no-subtitle] [--json]", " the project's TITLE and SUBTITLE (the manifest's `title` / `subtitle`: the head, the intro's title card, the", " posting artifacts). With no words, prints them. One write, one undo point.", ].join("\n"); export const STILL_USAGE = [ "usage: umtool still <project> <clip> --at <source seconds> [--take <take>] [--json]", " umtool still <project> ls [--json]", " A STILL AT SECOND N: one frame of the clip's fetched window at that SOURCE second (the second Play's Still", " button reads off the playhead), saved as shots/still-<clip>-<s>s.png beside the project's other shots; nothing", " fetched (a second no fetched window holds is refused). ls: the project's shots/, newest first.", ].join("\n"); export const TEASER_INSERT_USAGE = [ "usage: umtool timeline <project> teaser-insert [--at start|end | --after <id> | --before <id>] [--id ID] [--beat S]", " --line \"<text>\" [--break \"<its end>\"] [--hold S] [--line …] | --lines-json '<json>'|@file [--json]", " A TEASER OR CLOSING CARD inserted (type teaser): the first line its title, each --line the next, a --break / --hold", " after a --line that line's; default at the end (id \"close\"; at the start \"cold\"). Checked by the build's teaser", " rules; one write, one undo point.", ].join("\n"); async function projectOf(arg, root) { if (!arg) throw new CliError("which project?"); const r = await resolveProject(arg, root); if (r.ambiguous) throw new CliError(`"${arg}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CliError(`no project matches "${arg}"`); return r.project; } /** Words, and `--key value` / `--key=value` flags (the booleans named), in order (a repeated flag kept each time). */ function parse(args, booleans = []) { const words = []; /** @type {Array<[string, string | true]>} */ const seq = []; for (let i = 0; i < args.length; i += 1) { const a = args[i]; if (!a.startsWith("--")) { words.push(a); continue; } const eq = a.indexOf("="); if (eq > 0) seq.push([a.slice(2, eq), a.slice(eq + 1)]); else if (booleans.includes(a.slice(2))) seq.push([a.slice(2), true]); else { if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); seq.push([a.slice(2), args[i + 1]]); i += 1; } } const flags = new Map(seq); return { words, flags, seq }; } /** The exit code for a writer's refusal, said on stderr. */ function refused(err, who, e) { if (e instanceof StructureRefused) err(`umtool ${who}: refused — the build would not take it:\n${e.errors.map((x) => ` ${x}`).join("\n")}`); else if (e instanceof StaleToken) err(`umtool ${who}: ${e.message} — somebody else wrote it; run it again`); else err(`umtool ${who}: ${e instanceof Error ? e.message : String(e)}`); return e instanceof CliError ? 2 : 1; } const undoLine = (r) => (r?.snapshot?.rel && !r.snapshot.skipped ? ` undo point: ${r.snapshot.rel}` : null); const write = (project, fn) => withEditNotes(project, async () => fn(await manifestToken(project.dir))); /** `umtool provenance`. */ export async function provenanceCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { try { const { words, flags } = parse(args, ["json", "help"]); const [projectArg, verb = "ls"] = words; if (!projectArg || flags.has("help")) { err(PROVENANCE_USAGE); return 2; } const json = flags.get("json") === true; const project = await projectOf(projectArg, root); if (verb === "ls") { const m = await readManifest(project.dir); if (!m) throw new CliError(`${project.id} has no video.manifest.json`); const view = { ...provenanceView(m), linkPolicy: m.provenance?.linkPolicy ?? null }; if (json) out(JSON.stringify({ project: project.id, provenance: view, token: await manifestToken(project.dir) }, null, 2)); else for (const [k, v] of Object.entries(view)) out(`${k.padEnd(12)} ${v === null ? "—" : typeof v === "string" ? v : JSON.stringify(v)}`); return 0; } if (verb !== "set") throw new CliError(`unknown: provenance ${verb} — ls or set`); /** @type {Record<string, string>} */ const keys = { "--site-origin": "siteOrigin", "--channel-slug": "channelSlug", "--channel": "channel" }; const patch = {}; for (const [f, v] of flags) { if (f === "json") continue; if (!(`--${f}` in keys)) throw new CliError(`unknown flag --${f} (--site-origin, --channel-slug, --channel)`); patch[keys[`--${f}`]] = v === true ? "" : v; } if (!Object.keys(patch).length) throw new CliError("set needs --site-origin, --channel-slug or --channel"); const { result } = await write(project, (token) => updateProvenance(project.dir, patch, { token })); if (json) out(JSON.stringify({ ok: true, project: project.id, ...result }, null, 2)); else { const changed = Object.entries(result.changed); out(changed.length ? changed.map(([k, [a, b]]) => `${k}: ${a ?? "—"} -> ${b ?? "—"}`).join("\n") : "unchanged"); const u = undoLine(result); if (u) out(u); } return 0; } catch (e) { return refused(err, "provenance", e); } } /** `umtool title`. */ export async function titleCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { try { const { words, flags } = parse(args, ["json", "help", "no-subtitle"]); const [projectArg, ...rest] = words; if (!projectArg || flags.has("help")) { err(TITLE_USAGE); return 2; } for (const f of flags.keys()) if (!["json", "subtitle", "no-subtitle"].includes(f)) throw new CliError(`unknown flag --${f}`); const json = flags.get("json") === true; const project = await projectOf(projectArg, root); const patch = {}; if (rest.length) patch.title = rest.join(" "); const SUBTITLE = "--subtitle"; if (flags.has(SUBTITLE.slice(2))) patch.subtitle = String(flags.get(SUBTITLE.slice(2))); if (flags.has("no-subtitle")) patch.subtitle = null; if (!Object.keys(patch).length) { const m = await readManifest(project.dir); if (!m) throw new CliError(`${project.id} has no video.manifest.json`); const view = { title: m.title ?? null, subtitle: typeof m.subtitle === "string" ? m.subtitle : null }; if (json) out(JSON.stringify({ project: project.id, ...view, token: await manifestToken(project.dir) }, null, 2)); else out(`${view.title ?? "—"}${view.subtitle ? `\n ${view.subtitle}` : ""}`); return 0; } const { result } = await write(project, (token) => updateTitle(project.dir, patch, { token })); if (json) out(JSON.stringify({ ok: true, project: project.id, ...result }, null, 2)); else { out(`title: ${result.title}${result.subtitle ? `\nsubtitle: ${result.subtitle}` : "\nsubtitle: —"}`); const u = undoLine(result); if (u) out(u); } return 0; } catch (e) { return refused(err, "title", e); } } /** `umtool still`. */ export async function stillCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { try { const { words, flags } = parse(args, ["json", "help"]); const [projectArg, clip] = words; if (!projectArg || !clip || flags.has("help")) { err(STILL_USAGE); return 2; } for (const f of flags.keys()) if (!["json", "at", "take"].includes(f)) throw new CliError(`unknown flag --${f}`); const json = flags.get("json") === true; const project = await projectOf(projectArg, root); const { grabStill, listShots } = await import("./stillGrab.mjs"); if (clip === "ls") { const shots = await listShots(project.dir); if (json) out(JSON.stringify({ project: project.id, shots }, null, 2)); else { for (const s of shots) out(`${s.rel} ${s.still ? `${s.still.clip} @ ${s.still.at} s` : ""} ${s.mtime.slice(0, 16).replace("T", " ")}`); out(`${shots.length} picture(s) in shots/`); } return 0; } if (!flags.has("at")) throw new CliError("--at <source seconds> is the second to grab"); const take = flags.has("take") ? String(flags.get("take")) : null; let m = take ? (await (await import("./takeManifest.mjs")).resolveTakeManifest(project.dir, take)).manifest : await readManifest(project.dir); if (!m) throw new CliError(`${project.id} has no video.manifest.json`); const r = await grabStill(project, m, clip, Number(flags.get("at"))); if (json) out(JSON.stringify({ ok: true, project: project.id, ...r }, null, 2)); else out(`${r.rel} (${r.clip} @ ${r.at} s of ${r.video}, ${r.bytes} bytes)`); return 0; } catch (e) { return refused(err, "still", e); } } /** A `--lines-json` value: JSON, or `@file` of it. */ async function jsonArg(v) { const text = String(v).startsWith("@") ? await readFile(String(v).slice(1), "utf8") : String(v); try { return JSON.parse(text); } catch (e) { throw new CliError(`--lines-json is not JSON: ${e instanceof Error ? e.message : e}`); } } /** The flags teaser-insert reads besides --line / --break / --hold (lib/cli/verbs.mjs's form names them). */ const TEASER_INSERT_FLAGS = ["--json", "--at", "--after", "--before", "--id", "--beat", "--lines-json"]; /** `umtool timeline <p> teaser-insert …` (timelineCli.mjs hands it the words after the verb). */ export async function teaserInsertVerb(project, args, { out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { try { const { flags, seq, words } = parse(args, ["json", "help"]); if (flags.has("help")) { err(TEASER_INSERT_USAGE); return 2; } if (words.length) throw new CliError(`teaser-insert takes flags, not ${words.join(" ")} (--line "…")`); const json = flags.get("json") === true; /** @type {Array<string | Record<string, unknown>>} */ let lines = []; for (const [k, v] of seq) { if (k === "line") lines.push({ text: String(v) }); else if (k === "break" || k === "hold") { const last = lines.at(-1); if (!last || typeof last === "string") throw new CliError(`--${k} goes after the --line it belongs to`); last[k] = k === "hold" ? Number(v) : String(v); } else if (!TEASER_INSERT_FLAGS.includes(`--${k}`)) throw new CliError(`unknown flag --${k}`); } if (flags.has("lines-json")) { if (lines.length) throw new CliError("--lines-json or --line, not both"); const j = await jsonArg(flags.get("lines-json")); if (!Array.isArray(j)) throw new CliError("--lines-json is a list of lines"); lines = j; } lines = lines.map((l) => (typeof l === "object" && l && Object.keys(l).length === 1 && "text" in l ? String(l.text) : l)); const at = flags.get("at"); const position = flags.has("after") ? { after: String(flags.get("after")) } : flags.has("before") ? { before: String(flags.get("before")) } : at === "start" ? "start" : at === undefined || at === "end" ? "end" : null; if (position === null) throw new CliError("--at is start or end (--after <id> / --before <id> for elsewhere)"); const spec = { lines, ...(flags.has("id") ? { id: String(flags.get("id")) } : {}), ...(flags.has("beat") ? { beat: Number(flags.get("beat")) } : {}) }; const { result } = await write(project, (token) => insertTeaser(project.dir, spec, position, { token })); if (json) out(JSON.stringify({ ok: true, project: project.id, op: "teaser-insert", inserted: { id: result.id, at: result.at, entry: result.entry }, token: result.token }, null, 2)); else { out(`inserted teaser ${result.id} at ${result.at}: ${JSON.stringify(result.entry.lines)}`); const u = undoLine(result); if (u) out(u); } return 0; } catch (e) { return refused(err, "timeline teaser-insert", e); } } /** `umtool links <p> --embed-ids [--clips a,b] [--dry-run] [--json]` (linksCli.mjs hands it over). */ export async function embedIdsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { try { const { words, flags } = parse(args, ["json", "help", "dry-run"]); if (!words[0] || flags.has("help")) { err("usage: umtool links <project> --embed-ids [--clips a,b] [--dry-run] [--json]\n every clip citing a Rumble URL-slug folder the archive does not serve gets the EMBED id it serves (siteVideo),\n read from the folder's metadata.info.json; a citeUrl naming the folder moves with it. No network; one write."); return 2; } for (const f of flags.keys()) if (!["json", "clips", "dry-run"].includes(f)) throw new CliError(`unknown flag --${f}`); const json = flags.get("json") === true; const project = await projectOf(words[0], root); const m = await readManifest(project.dir); if (!m) throw new CliError(`${project.id} has no video.manifest.json`); const { embedIdFixes, embedIdRows } = await import("./embedIds.mjs"); const { readLinkCheck } = await import("./linkCheck.mjs"); const rows = await embedIdRows(project.dir, m, { doc: await readLinkCheck(project.dir) }); const clips = flags.has("clips") ? String(flags.get("clips")).split(",").map((s) => s.trim()).filter(Boolean) : null; if (!rows.length && !clips) { if (json) out(JSON.stringify({ ok: true, project: project.id, rows: [], fixed: [] }, null, 2)); else out("no clip cites a folder id the archive does not serve"); return 0; } const fixes = embedIdFixes(rows, clips); if (flags.has("dry-run")) { if (json) out(JSON.stringify({ ok: true, project: project.id, rows, would: fixes }, null, 2)); else for (const f of fixes) out(`would: ${f.clip} siteVideo ${f.siteVideo}${f.citeUrl ? ` citeUrl ${f.citeUrl}` : ""}`); return 0; } const { result } = await write(project, (token) => setSiteVideos(project.dir, fixes, { token })); if (json) out(JSON.stringify({ ok: true, project: project.id, rows, fixed: result.fixed, token: result.token }, null, 2)); else { for (const f of result.fixed) out(`fixed ${f.clip}: ${f.video} -> siteVideo ${f.siteVideo} (the Rumble embed id)${f.citeUrl ? `, citeUrl ${f.citeUrl}` : ""}`); out(" `umtool links <p>` checks them against the site"); const u = undoLine(result); if (u) out(u); } return 0; } catch (e) { return refused(err, "links --embed-ids", e); } }