// `umtool links [--json] [--fix]`: do the cut's QR links open on the // sites they link? (linkCheck.mjs says how, and why it is polite and cached.) // The same check the project page's Check links runs (POST /api/report/links), // recorded in out/links.json, which `umtool check` and the decisions read. // // --fix rewrite every dead link the check knows the fix for (the Twitch // trap: `?v=/` where the site's record is `v`) // through the window writer, then check again. // // Exit 1 when a link is dead, 0 otherwise (unverified is not dead). // Plain ESM: the CLI runs it under bare node. import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readManifest } from "../projects/report.mjs"; import { kindMakesTakes } from "../projects/kinds.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { AUTO_SNAPSHOT_PREFIX, updateClip } from "./manifest.mjs"; import { createSnapshot } from "./snapshots.mjs"; import { runLinkCheck } from "./linkCheck.mjs"; export const LINKS_USAGE = [ "usage: umtool links [--json] [--fix]", "", "Resolves every clip QR the cut draws against the site it links: corpus.json -> the channel's", "transcripts manifest -> slugToPage -> page-NNNN.json -> the record. One request at a time per host,", "at least 3 s apart (jittered); shard", "pages from the cue cache, read again only on a miss. A site that does not answer leaves its links", "unverified (not dead). Writes out/links.json: `umtool check` reports link-dead (blocking),", "links-unverified and links-unchecked from it. --fix rewrites the dead links it knows the fix for", "(a Twitch id the site serves as v) through the window writer, then checks again.", "Exit 1 when a link is dead.", " umtool links --embed-ids [--clips a,b] [--dry-run] [--json]", "every clip citing a Rumble URL-slug folder the archive does not serve gets the embed id it serves (siteVideo,", "from the folder's metadata.info.json; a citeUrl naming the folder moves with it): no network, one write.", ].join("\n"); class CliError extends Error {} /** One line per site and per dead or unverified link. */ export function linksSummary(doc) { const lines = []; const n = (s) => doc.links.filter((l) => l.state === s).length; lines.push( `${doc.links.length} clip QR link(s): ${n("ok")} open · ${n("dead")} dead · ${n("unverified")} not verified · ${n("direct")} not archive links (not checked) · ${doc.fetched} request(s)`, ); for (const [origin, o] of Object.entries(doc.origins ?? {})) { lines.push( ` ${origin}: ${o.state === "ok" ? `corpus.json${o.generatedAt ? `, deployed ${o.generatedAt.slice(0, 16).replace("T", " ")}` : ""}` : o.state === "no-corpus" ? "no corpus.json" : `couldn't reach — ${o.error}`}`, ); } for (const l of doc.links) { if (l.state === "dead") lines.push(`DEAD ${l.clip} ${l.why}${l.fix ? `\n fix: ${l.fix}` : ""}`); else if (l.state === "unverified") lines.push(`UNVERIFIED ${l.clip} ${l.why}`); } return lines.join("\n"); } /** * @param {string[]} args the words after `links` * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, fetchImpl?: typeof fetch, cacheDir?: string | null, gapMs?: number }} [opts] * @returns {Promise} */ export async function linksCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), fetchImpl, cacheDir, gapMs } = {}) { // The published embed ids, from this disk (the Links panel's "use the published embed id"; inspectorCli.mjs). if (args.includes("--embed-ids")) return (await import("./inspectorCli.mjs")).embedIdsCommand(args.filter((a) => a !== "--embed-ids"), { root, out, err }); try { const words = args.filter((a) => !a.startsWith("--")); const flags = new Set(args.filter((a) => a.startsWith("--"))); for (const f of flags) if (!["--json", "--fix", "--help"].includes(f)) throw new CliError(`unknown flag ${f}`); if (!words[0] || flags.has("--help")) { (flags.has("--help") ? out : err)(LINKS_USAGE); return flags.has("--help") ? 0 : 2; } const r = await resolveProject(words[0], root); if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CliError(`no project matches "${words[0]}"`); const project = r.project; if (!kindMakesTakes(project.kind)) throw new CliError(`${project.id} is a ${project.kind}, not a report video`); const opts = { ...(fetchImpl ? { fetchImpl } : {}), ...(cacheDir !== undefined ? { cacheDir } : {}), ...(gapMs !== undefined ? { gapMs } : {}), log: flags.has("--json") ? () => {} : (s) => err(` ${s}`), }; let m = await readManifest(project.dir); if (!m) throw new CliError(`${project.id} has no video.manifest.json`); let doc = await runLinkCheck(project.dir, m, opts); const fixed = []; let undo = null; if (flags.has("--fix")) { const r = await applyLinkFixes(project, m, doc); fixed.push(...r.fixed); undo = r.undo; if (fixed.length) { m = await readManifest(project.dir); doc = await runLinkCheck(project.dir, m, opts); } } const dead = doc.links.filter((l) => l.state === "dead").length; if (flags.has("--json")) { out(JSON.stringify({ ok: dead === 0, project: project.id, ...doc, ...(flags.has("--fix") ? { fixed, ...(undo ? { undo: undo.rel } : {}) } : {}) }, null, 2)); return dead ? 1 : 0; } if (undo) out(`undo point: ${undo.rel}`); for (const f of fixed) out(`fixed ${f.clip}: ${f.from} -> ${f.to}${f.siteVideo ? ` (siteVideo ${f.siteVideo}: the Rumble embed id)` : ""}`); out(`${project.id} · ${linksSummary(doc)}`); out(`recorded in out/links.json (umtool check ${project.id} reads it)`); return dead ? 1 : 0; } catch (e) { err(`umtool links: ${e instanceof Error ? e.message : String(e)}`); return e instanceof CliError ? 2 : 1; } } export const PATCH_MARKERS_USAGE = [ "usage: umtool patch-markers [.patch.json] [--fix] [--json]", "", "The take patches beside the manifest (*.patch.json, what `umtool take --patch` reads) whose deck markers", "name a clip that is not in the cut -- a take made with one is refused. Structural writes re-anchor them", "by themselves; this is for the rest. --fix: each such marker takes the `after` of the cut's marker with", "the same label; one no marker of the cut shares a label with is left, and named. Exit 1 when one is left.", ].join("\n"); /** * `umtool patch-markers …` * @param {string[]} args the words after `patch-markers` * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts] * @returns {Promise} */ export async function patchMarkersCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { // The published embed ids, from this disk (the Links panel's "use the published embed id"; inspectorCli.mjs). if (args.includes("--embed-ids")) return (await import("./inspectorCli.mjs")).embedIdsCommand(args.filter((a) => a !== "--embed-ids"), { root, out, err }); try { const words = args.filter((a) => !a.startsWith("--")); const flags = new Set(args.filter((a) => a.startsWith("--"))); for (const f of flags) if (!["--json", "--fix", "--help"].includes(f)) throw new CliError(`unknown flag ${f}`); if (!words[0] || flags.has("--help")) { (flags.has("--help") ? out : err)(PATCH_MARKERS_USAGE); return flags.has("--help") ? 0 : 2; } const r = await resolveProject(words[0], root); if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CliError(`no project matches "${words[0]}"`); const project = r.project; const m = await readManifest(project.dir); if (!m) throw new CliError(`${project.id} has no video.manifest.json`); const { stalePatchMarkers, fixStalePatchMarkers } = await import("./patchMarkers.mjs"); let stale = await stalePatchMarkers(project.dir, m); if (words[1]) stale = stale.filter((s) => s.file === words[1]); const fixed = []; if (flags.has("--fix")) { for (const s of stale) if (!s.error) fixed.push(await fixStalePatchMarkers(project.dir, m, s.file)); stale = (await stalePatchMarkers(project.dir, m)).filter((s) => !words[1] || s.file === words[1]); } if (flags.has("--json")) { out(JSON.stringify({ ok: stale.length === 0, project: project.id, stale, ...(flags.has("--fix") ? { fixed } : {}) }, null, 2)); return stale.length ? 1 : 0; } for (const f of fixed) for (const n of f.notes) out(`${f.file}: ${n}`); if (!stale.length) out(`${project.id}: every take patch's markers name clips of the cut`); for (const s of stale) { if (s.error) out(`${s.file}: does not read (${s.error})`); for (const mk of s.markers) out(`${s.file}: ${mk.label ? `"${mk.label}"` : `marker ${mk.index}`} is after ${mk.after}, which is not in the cut`); } return stale.length ? 1 : 0; } catch (e) { err(`umtool patch-markers: ${e instanceof Error ? e.message : String(e)}`); return e instanceof CliError ? 2 : 1; } } export const LINK_POLICY_USAGE = [ "usage: umtool link-policy [--via ] [--direct ] [--clear] [--fix] [--json]", "", "The project's link policy, provenance.linkPolicy: \"cite via site X; these channels direct\". --via names the", "archive every clip's QR opens (a site id from transcripts/sites, or its address; '' goes back to", "provenance.siteOrigin); --direct the channels whose clips link the platform's own page at the cite ('' none);", "--clear removes the policy. New clips are written by it (the inserters); the clips already in the cut that", "break it are `umtool check`'s clip-link-policy rows. --fix rewrites each of them that has a fix through the", "window writer. With no flag, prints the policy and what breaks it. Exit 1 when a clip still breaks it.", ].join("\n"); /** * `umtool link-policy …` * @param {string[]} args the words after `link-policy` * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, sitesDir?: string }} [opts] * @returns {Promise} */ export async function linkPolicyCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), sitesDir } = {}) { try { const { linkPolicyOf, normalizeLinkPolicy, policyBreaks, webpageReader } = await import("./linkPolicy.mjs"); const { sitesByOrigin } = await import("./siteDeploys.mjs"); const { updateLinkPolicy } = await import("./manifest.mjs"); const { channelsDirFor, hasShadowChannels } = await import("../projects/report.mjs"); const { SITES_DIR } = await import("../paths.mjs"); const words = []; /** @type {Map} */ const flags = new Map(); for (let i = 0; i < args.length; i += 1) { const a = args[i]; if (a === "--via" || a === "--direct") { if (i + 1 >= args.length) throw new CliError(`${a} needs a value ('' clears it)`); flags.set(a, args[++i]); } else if (["--clear", "--fix", "--json", "--help"].includes(a)) flags.set(a, true); else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`); else words.push(a); } if (!words[0] || flags.has("--help")) { (flags.has("--help") ? out : err)(LINK_POLICY_USAGE); return flags.has("--help") ? 0 : 2; } const r = await resolveProject(words[0], root); if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CliError(`no project matches "${words[0]}"`); const project = r.project; if (!kindMakesTakes(project.kind)) throw new CliError(`${project.id} is a ${project.kind}, not a report video`); let m = await readManifest(project.dir); if (!m) throw new CliError(`${project.id} has no video.manifest.json`); const notes = []; if (flags.has("--clear") || flags.has("--via") || flags.has("--direct")) { if (flags.has("--clear") && (flags.has("--via") || flags.has("--direct"))) throw new CliError("--clear takes no --via or --direct"); let next = null; if (!flags.has("--clear")) { const was = linkPolicyOf(m) ?? { via: null, direct: [] }; let via = was.via; if (flags.has("--via")) { const v = String(flags.get("--via")).trim(); if (!v) via = null; else if (/^https?:\/\//i.test(v)) via = v; else { const hit = [...sitesByOrigin(sitesDir ?? SITES_DIR)].find(([, s]) => s.siteId === v); if (!hit) throw new CliError(`--via ${v}: no site of that id has a siteUrl (transcripts/sites//site.json); pass its address`); via = hit[0]; } } const direct = flags.has("--direct") ? String(flags.get("--direct")) : was.direct; next = normalizeLinkPolicy({ via, direct }); } const res = await withEditNotes(project, () => updateLinkPolicy(project.dir, next)); notes.push(res.result.changed ? "link policy saved" : "link policy unchanged"); m = await readManifest(project.dir); } const shadowExists = await hasShadowChannels(project.dir); const read = webpageReader(channelsDirFor(project.dir, m, { shadowExists })); const web = new Map(); for (const e of m.timeline ?? []) { if (e?.type === "clip") web.set(e.id, await read(e.channel ?? m.provenance?.channelSlug, e.video)); } let breaks = policyBreaks(m, { webpageOf: (e) => web.get(e.id) ?? null }); const fixed = []; if (flags.has("--fix")) { for (const b of breaks) { if (!b.fix) continue; await withEditNotes(project, () => updateClip(project.dir, b.clip, { citeUrl: b.fix })); fixed.push({ clip: b.clip, from: b.current, to: b.fix }); } if (fixed.length) { m = await readManifest(project.dir); breaks = policyBreaks(m, { webpageOf: (e) => web.get(e.id) ?? null }); } } const policy = linkPolicyOf(m); if (flags.has("--json")) { out(JSON.stringify({ ok: breaks.length === 0, project: project.id, policy, breaks, ...(flags.has("--fix") ? { fixed } : {}) }, null, 2)); return breaks.length ? 1 : 0; } for (const n of notes) out(n); for (const f of fixed) out(`fixed ${f.clip}: ${f.from} -> ${f.to}`); if (!policy) out(`${project.id}: no link policy (every QR opens provenance.siteOrigin, or the clip's own citeUrl)`); else out(`${project.id}: cite via ${policy.via ?? `provenance.siteOrigin (${m.provenance?.siteOrigin ?? "unset"})`}; direct: ${policy.direct.length ? policy.direct.join(", ") : "none"}`); for (const b of breaks) out(`BREAKS ${b.clip} ${b.why}${b.fix ? `\n fix: ${b.fix}` : ""}`); if (policy && !breaks.length) out("every clip's QR keeps it"); return breaks.length ? 1 : 0; } catch (e) { err(`umtool link-policy: ${e instanceof Error ? e.message : String(e)}`); return e instanceof CliError ? 2 : 1; } } /** * Rewrite every dead link `doc` knows the fix for, through the window writer, * after ONE undo point (revisions/-auto-before-links-fix: `umtool * timeline

undo` takes them all back). The CLI's `--fix` over a check it * just ran, and the page's (POST /api/report/links `fix`: the Checks list's * and the Inbox's "Use embed ids") over the RECORDED one -- `guard`: only a * clip still as that check saw it (its citeUrl the dead link, or no siteVideo * yet for a Rumble folder id); an edit since is somebody's decision. * * A Rumble folder id (linkCheck.mjs siteIdOf, L1's mapping): the clip names the * embed id the archive serves (`siteVideo`), and a citeUrl that was the dead * link moves with it; a QR built from the moment needs nothing else. Any other * fix (a Twitch id as v) is the clip's citeUrl. * * @param {{ id: string, dir: string }} project * @param {Record} m the manifest the check read * @param {{ links?: Array> } | null} doc * @param {{ guard?: boolean }} [o] */ export async function applyLinkFixes(project, m, doc, { guard = false } = {}) { const byId = new Map((m?.timeline ?? []).map((e) => [e?.id, e])); const todo = (doc?.links ?? []).filter((l) => { if (l.state !== "dead" || !l.fix) return false; if (!guard) return true; const e = byId.get(l.clip); if (!e) return false; return l.fixSiteVideo ? !e.siteVideo : e.citeUrl === l.url; }); const fixed = []; if (!todo.length) return { fixed, undo: null }; const undo = await createSnapshot(project.dir, { label: `${AUTO_SNAPSHOT_PREFIX}links-fix` }); for (const l of todo) { if (l.fixSiteVideo) { const e = byId.get(l.clip); const patch = { siteVideo: l.fixSiteVideo, ...(e?.citeUrl === l.url ? { citeUrl: l.fix } : {}) }; await withEditNotes(project, () => updateClip(project.dir, l.clip, patch)); fixed.push({ clip: l.clip, from: l.url, to: l.fix, siteVideo: l.fixSiteVideo }); continue; } await withEditNotes(project, () => updateClip(project.dir, l.clip, { citeUrl: l.fix })); fixed.push({ clip: l.clip, from: l.url, to: l.fix }); } return { fixed, undo }; }