// Do the cut's QR links open? (UI notes 2026-10-30, #8) // // On the Ember cut the Twitch links used the bare id, which the site does not // open (its record is `v`), and anilyzer's deploy was three weeks old with // no Ember channels at all -- so most QRs were dead in drafts 1–11, and the // fix took a headless browser. This resolves every clip's QR against the // target site's own published contract instead: // // corpus.json -> channels[].manifests.transcripts -> slugToPage[] // -> page-.json (zero-padded to 4) -> the record whose id is // // (report-to-video/cues.mjs walks the same contract for cues, through the same // on-disk JSON cache, so a shard the build already read is not fetched again.) // // POLITE: one request at a time per host, at least LINK_GAP_MS apart (jittered // upward, common/lib/jitter.mjs -- the operator's "≥3 s between metadata // requests, one stream per host"), each URL at most once per check. corpus.json // and the channel manifests are re-read every check (a deploy changes them); // a shard page is read from the cache, and fetched again only when the record // slugToPage promised is not in the cached copy. // // OFFLINE: a site that does not answer is a state, not an error -- its links // are `unverified` with the reason, and the check row says "couldn't reach". // // The result is RECORDED (out/links.json), like the availability preflight's: // the decisions reducer reads it and never fetches (lib/projects/report.mjs). // // Plain ESM: the CLI runs it under bare node. import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { createJsonCache, DEFAULT_CACHE_DIR, pagesVersionOf, pageUrlFrom, transcriptsManifestUrl } from "umtool-report-to-video/cues"; import { qrsOf } from "umtool-report-to-video/lint"; import { jitterUp } from "yt-dlp-transcript-common/lib/jitter.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const LINKS_FILE = "links.json"; export const linksFile = (dir) => path.join(dir, "out", LINKS_FILE); const FETCH_TIMEOUT_MS = 20_000; /** The floor between two requests to one host (a cache hit asks nothing and waits for nothing). */ export const LINK_GAP_MS = 3000; /** * An archive viewer link's parts: `/?v=/&t=…`, or null * for anything else (a platform's own page, a mirror) -- which this check * does not judge. * * @param {string} url * @returns {null | { origin: string, channel: string, id: string, t: string | null }} */ export function archiveLinkOf(url) { let u; try { u = new URL(String(url)); } catch { return null; } if (u.protocol !== "http:" && u.protocol !== "https:") return null; const v = u.searchParams.get("v"); if (!v || !v.includes("/")) return null; const cut = v.indexOf("/"); const channel = v.slice(0, cut); const id = v.slice(cut + 1); if (!channel || !id) return null; return { origin: u.origin, channel, id, t: u.searchParams.get("t") }; } /** * Every clip QR the cut draws, `{ clip, url }`, by the build's own rules * (lint.mjs qrsOf: a clip's citeUrl, else its archive moment; none when the * cut draws no code). * * @param {Record} m */ export function linksOf(m) { const clips = new Set((m?.timeline ?? []).filter((e) => e?.type === "clip").map((e) => e.id)); let qrs = []; try { qrs = qrsOf(m); } catch { qrs = []; } const out = []; const seen = new Set(); for (const q of qrs) { if (q.source !== "entry" || !clips.has(q.id) || !q.url) continue; const key = `${q.id}\u0000${q.url}`; if (seen.has(key)) continue; seen.add(key); out.push({ clip: q.id, url: String(q.url) }); } return out; } /** An archive link with its `?v=/` id swapped for `to`, everything else as it was. Pure. */ export function withArchiveId(url, from, to) { const esc = String(from).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); return String(url).replace(new RegExp(`([?&]v=[^&#]*?)(%2F|/)${esc}(?=&|#|$)`, "i"), `$1$2${to}`); } /** A fetch that gives up: a site that hangs is a site that does not answer. */ function withTimeout(fetchImpl, ms) { return (url, init = {}) => fetchImpl(url, { ...init, signal: AbortSignal.timeout(ms) }); } const errText = (e) => { const m = e instanceof Error ? e.message : String(e); const cause = e instanceof Error && e.cause instanceof Error ? ` (${e.cause.message})` : ""; return `${m}${cause}`; }; /** * Resolve the links. Pure over `fetchImpl` (and the cache dir). * * @param {Array<{ clip: string, url: string }>} links * `siteIdOf({clip, channel, id})`: the id the archive serves a recording * under when the link names the corpus's own (a Rumble URL-slug directory: * its embed id, shareLine.mjs siteVideoFor), else null -- a link to the folder * id is then dead with the embed id's link as its `fix` and `fixSiteVideo`. * * @param {{ fetchImpl?: typeof fetch, cacheDir?: string | null, now?: () => Date, log?: (s: string) => void, gapMs?: number, sleep?: (ms: number) => Promise, * siteIdOf?: (q: { clip: string, channel: string, id: string }) => Promise }} [opts] * @returns {Promise<{ * version: 1, checkedAt: string, fetched: number, * origins: Record, * links: Array<{ clip: string, url: string, state: "ok" | "dead" | "unverified" | "direct", origin?: string, why?: string, fix?: string, fixSiteVideo?: string }>, * }>} */ export async function checkLinks( links, { fetchImpl = globalThis.fetch, cacheDir = DEFAULT_CACHE_DIR, now = () => new Date(), log = () => {}, gapMs = LINK_GAP_MS, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), siteIdOf = null } = {}, ) { let fetched = 0; /** host -> when its last request was sent (ms) */ const lastAt = new Map(); const counting = withTimeout(async (url, init) => { const host = new URL(String(url)).host; const last = lastAt.get(host); if (last != null && gapMs > 0) { const wait = last + jitterUp(gapMs) - Date.now(); if (wait > 0) await sleep(wait); } lastAt.set(host, Date.now()); fetched += 1; return fetchImpl(url, init); }, FETCH_TIMEOUT_MS); const { getJson } = createJsonCache({ cacheDir, fetchImpl: counting, log }); /** @type {Record} */ const origins = {}; const corpusOf = new Map(); const manifestOf = new Map(); async function corpus(origin) { if (corpusOf.has(origin)) return corpusOf.get(origin); let doc = null; try { doc = await getJson(`${origin}/corpus.json`, { refresh: true }); origins[origin] = { state: "ok", generatedAt: typeof doc?.generatedAt === "string" ? doc.generatedAt : null, title: typeof doc?.site?.title === "string" ? doc.site.title : null, }; } catch (e) { const msg = errText(e); // A 404 is a site that answered and publishes no contract; anything // else (DNS, refused, timeout, 5xx) is a site that did not answer. origins[origin] = / -> 404$/.test(msg) ? { state: "no-corpus", error: msg } : { state: "unreachable", error: msg }; doc = null; } corpusOf.set(origin, doc); return doc; } async function channelManifest(url) { if (manifestOf.has(url)) return manifestOf.get(url); let doc = null; let error = null; try { doc = await getJson(url, { refresh: true }); } catch (e) { error = errText(e); } const r = { doc, error }; manifestOf.set(url, r); return r; } const out = []; for (const { clip, url } of links) { const a = archiveLinkOf(url); if (!a) { out.push({ clip, url, state: "direct" }); continue; } const host = new URL(a.origin).host; const c = await corpus(a.origin); if (!c) { const o = origins[a.origin]; out.push({ clip, url, state: "unverified", origin: a.origin, why: o.state === "no-corpus" ? `${host} publishes no corpus.json` : `couldn't reach ${host} (${o.error})`, }); continue; } if (c.site?.scope === "cited") { out.push({ clip, url, state: "unverified", origin: a.origin, why: `${host} is a cited report site: it publishes no transcripts to look the record up in` }); continue; } const ch = (c.channels ?? []).find((x) => x?.slug === a.channel); if (!ch) { out.push({ clip, url, state: "dead", origin: a.origin, why: `the channel "${a.channel}" is not on ${host}${origins[a.origin].generatedAt ? ` (its deploy of ${origins[a.origin].generatedAt.slice(0, 10)})` : ""} — publish the site with it, or link elsewhere`, }); continue; } if (typeof ch.manifests?.transcripts !== "string" || !ch.manifests.transcripts) { out.push({ clip, url, state: "dead", origin: a.origin, why: `${host} publishes no transcripts for "${a.channel}"` }); continue; } // The manifest the corpus names, when it is on the archive's own origin; // one named elsewhere is not followed (report-to-video/archive-fetch.mjs). const manifestUrl = transcriptsManifestUrl(a.origin, ch); const man = await channelManifest(manifestUrl); if (!man.doc) { out.push({ clip, url, state: "unverified", origin: a.origin, why: `couldn't read ${a.channel}'s manifest on ${host} (${man.error})` }); continue; } const s2p = man.doc.slugToPage ?? {}; const page = s2p[a.id]; if (page === undefined) { // The Twitch trap: the corpus directory is the bare id, the site's record is `v`. const alt = /^\d+$/.test(a.id) && s2p[`v${a.id}`] !== undefined ? `v${a.id}` : null; // The Rumble trap: the corpus directory is the URL slug, the site's record the embed id (siteIdOf). const embed = !alt && siteIdOf ? await siteIdOf({ clip, channel: a.channel, id: a.id }).catch(() => null) : null; const rumble = embed && embed !== a.id && s2p[embed] !== undefined ? embed : null; out.push({ clip, url, state: "dead", origin: a.origin, why: alt ? `"${a.id}" is not a record on ${host}; the site's record is "${alt}"` : rumble ? `"${a.id}" is the recording's folder (its Rumble URL slug), not a record on ${host}; the site's record is its embed id "${rumble}"` : `"${a.id}" is not published in ${a.channel} on ${host}${origins[a.origin].generatedAt ? ` (deployed ${origins[a.origin].generatedAt.slice(0, 10)})` : ""}`, ...(alt ? { fix: url.replace(/([?&]v=[^&#]*?)(%2F|\/)(\d+)(?=&|#|$)/i, `$1$2v$3`) } : {}), ...(rumble ? { fix: withArchiveId(url, a.id, rumble), fixSiteVideo: rumble } : {}), }); continue; } const pageUrl = pageUrlFrom(manifestUrl, Number(page)); const has = (doc) => Array.isArray(doc) && doc.some((r) => r?.id === a.id || r?.slug === a.id); let found = false; let error = null; try { // Keyed by the manifest's generation (cues.mjs pagesVersionOf), so a shard cached from an older deploy is // fetched again rather than read. const version = pagesVersionOf(man.doc); found = has(await getJson(pageUrl, { version })); // A cached shard older than the deploy: read it again, once. if (!found) found = has(await getJson(pageUrl, { refresh: true, version })); } catch (e) { error = errText(e); } if (error) out.push({ clip, url, state: "unverified", origin: a.origin, why: `couldn't read ${path.posix.basename(new URL(pageUrl).pathname)} on ${host} (${error})` }); else if (!found) out.push({ clip, url, state: "dead", origin: a.origin, why: `${host}'s slugToPage puts "${a.id}" on page ${page}, but no record there has that id — the deploy is inconsistent` }); else out.push({ clip, url, state: "ok", origin: a.origin }); } return { version: 1, checkedAt: now().toISOString(), fetched, origins, links: out }; } /** * A project's `siteIdOf` for checkLinks: the clip's recording, when the link * names it as the corpus keeps it, looked up in the project's channels trees * (its shadow, then the corpus behind it) for the id the archive serves * (shareLine.mjs siteVideoFor: a Rumble folder's embed id). * @param {string} dir * @param {Record} manifest */ export async function projectSiteIdOf(dir, manifest) { const [{ channelsLayersFor, hasShadowChannels }, { siteVideoFor }] = await Promise.all([import("../projects/report.mjs"), import("./shareLine.mjs")]); const layers = channelsLayersFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) }); const byId = new Map((manifest?.timeline ?? []).filter((e) => e?.type === "clip").map((e) => [e.id, e])); return async ({ clip, id }) => { const e = byId.get(clip); if (!e || e.siteVideo || String(e.video) !== id) return null; const slug = e.channel ?? manifest?.provenance?.channelSlug ?? null; for (const d of layers) { const got = await siteVideoFor({ channelsDir: d, slug, video: id }); if (got) return got; } return null; }; } /** * Check the project's links now and record the answer in out/links.json. * * @param {string} dir * @param {Record} manifest * @param {{ fetchImpl?: typeof fetch, cacheDir?: string | null, now?: () => Date, log?: (s: string) => void }} [opts] */ export async function runLinkCheck(dir, manifest, opts = {}) { const doc = await checkLinks(linksOf(manifest), { siteIdOf: await projectSiteIdOf(dir, manifest), ...opts }); const file = linksFile(dir); await mkdir(path.dirname(file), { recursive: true }); const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(tmp, file); return doc; } /** The last recorded check, or null. */ export async function readLinkCheck(dir) { try { const doc = JSON.parse(await readFile(linksFile(dir), "utf8")); return doc && Array.isArray(doc.links) ? doc : null; } catch { return null; } } /** * The recorded check read against the manifest as it is NOW: what is dead, * what could not be verified (by site), and which of today's links the * check never saw (a link changed since). * * @param {Record} m * @param {Awaited>} doc */ export function linkVerdicts(m, doc) { const current = linksOf(m); const archive = current.filter((l) => archiveLinkOf(l.url)); const byKey = new Map((doc?.links ?? []).map((l) => [`${l.clip}\u0000${l.url}`, l])); const dead = []; const unverified = []; const unchecked = []; let ok = 0; for (const l of archive) { const r = byKey.get(`${l.clip}\u0000${l.url}`); if (!r) unchecked.push(l); else if (r.state === "dead") dead.push(r); else if (r.state === "unverified") unverified.push(r); else if (r.state === "ok") ok += 1; } return { checkedAt: doc?.checkedAt ?? null, origins: doc?.origins ?? {}, archive: archive.length, direct: current.length - archive.length, ok, dead, unverified, unchecked }; }