// Citation links for a generated report (release 27, S5): built from the // channel slug, the video id and the second, on the article's CITATION // ORIGIN — never from a build's moment_base, which is null on a private build // (corpus.ts: a private site has no siteUrl) and then falls back to the // platform's URL. // // - `rewriteMomentBases` gives every recording a tool result shows the // origin's moment_base, so the model copies a right link from the start. // - `rewriteLinks` is the backstop over the finished markdown: a video cited // by its platform URL, or an archive link on another origin, becomes the // moment (or post) link on the citation origin, when the recording is in // the run's corpus. import { parseCitationHref } from "../../convertShared"; import { siteVideoId } from "../../../videoDirId.mjs"; import { extractJsonObject } from "../../../parseStdoutJson"; import type { CorpusToolsLike } from "./types"; // `platform`, when the caller knows it, maps a Twitch VOD's directory id `` // to the record id `v` the archive serves (siteVideoId — never keyed on the // id being digits). An id from a tool result is already the archive's. export function momentHref(origin: string, slug: string, id: string, seconds: number, platform?: string | null): string { return `${origin}/?v=${encodeURIComponent(`${slug}/${siteVideoId(id, platform)}`)}&t=${Math.max(0, Math.floor(seconds))}`; } export function postLinkHref(origin: string, slug: string, id: string): string { return `${origin}/?v=${encodeURIComponent(`${slug}/${id}`)}&vm=post`; } export const momentBaseOf = (origin: string, slug: string, id: string, platform?: string | null) => `${origin}/?v=${encodeURIComponent(`${slug}/${siteVideoId(id, platform)}`)}&t=`; // Which channel (slug) holds a recording: read off a moment link when there is // one, else asked of the corpus (get_video_metadata over the run's channels). export type SlugResolver = { slugOf(videoId: string): Promise; remember(videoId: string, slug: string): void; }; export function slugResolver(corpus: Pick, channels: readonly string[]): SlugResolver { const known = new Map>(); const ask = async (videoId: string): Promise => { const tries: Record[] = channels.length ? channels.map((channel) => ({ video_id: videoId, channel })) : [{ video_id: videoId }]; for (const args of tries) { try { const meta = extractJsonObject(await corpus.call("get_video_metadata", args)) as { channelSlug?: unknown; id?: unknown } | null; if (meta && typeof meta.channelSlug === "string" && meta.channelSlug) return meta.channelSlug; } catch { // not in this channel } } return null; }; return { slugOf(videoId) { let p = known.get(videoId); if (!p) { p = ask(videoId); known.set(videoId, p); } return p; }, remember(videoId, slug) { known.set(videoId, Promise.resolve(slug)); }, }; } const VIDEO_ID_LINE = /video_id: (\S+)/; const MOMENT_BASE_LINE = /^(\s*-?\s*)moment_base: (\S*)\s*$/m; const SOURCE_LINE = /^(\s*-?\s*)source: \S+.*$/m; // get_transcripts' blocks (`## title`, `- video_id: …`, `- moment_base: …`), // separated by `---`: each block's moment_base made the origin's. A block // whose recording cannot be placed keeps what it had. export async function rewriteMomentBases(text: string, resolver: SlugResolver, origin: string): Promise { const blocks = text.split(/\n---\n/); const out: string[] = []; for (const block of blocks) { const id = VIDEO_ID_LINE.exec(block)?.[1]; if (!id) { out.push(block); continue; } const mb = MOMENT_BASE_LINE.exec(block); let slug: string | null = null; if (mb) { const parsed = parseCitationHref(`${mb[2]}0`); if (parsed?.kind === "span" && parsed.id === id) slug = parsed.channel; } slug ??= await resolver.slugOf(id); if (!slug) { out.push(block); continue; } resolver.remember(id, slug); const base = momentBaseOf(origin, slug, id); if (mb) out.push(block.replace(MOMENT_BASE_LINE, `${mb[1]}moment_base: ${base}`)); else { const src = SOURCE_LINE.exec(block); out.push( src ? block.replace(SOURCE_LINE, (line) => `${line}\n${src[1]}moment_base: ${base}`) : block.replace(VIDEO_ID_LINE, (line) => `${line}\n- moment_base: ${base}`), ); } } return out.join("\n---\n"); } const MD_LINK = /\]\((https?:\/\/[^)\s]+)\)/g; // A platform's watch URL: `?v=` (no slash in it) or youtu.be/, or a // Twitch VOD's `twitch.tv/videos/` (served by the archive as `v`: // siteVideoId, on the platform the host names), and its `t` (`t=90`, `t=90s`, // `t=1h2m3s`). export function platformVideo(href: string): { id: string; seconds: number } | null { let u: URL; try { u = new URL(href); } catch { return null; } let id: string | null = null; const twitch = /^\/videos\/(\d+)\/?$/.exec(u.pathname); if (u.hostname === "youtu.be") id = u.pathname.slice(1).split("/")[0] || null; else if (/(^|\.)twitch\.tv$/.test(u.hostname)) id = twitch ? siteVideoId(twitch[1]!, "twitch") : null; else { const v = u.searchParams.get("v"); if (v && !v.includes("/")) id = v; } if (!id) return null; const t = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?$/.exec(u.searchParams.get("t") ?? ""); const seconds = t ? Number(t[1] ?? 0) * 3600 + Number(t[2] ?? 0) * 60 + Number(t[3] ?? 0) : 0; return { id, seconds }; } // The backstop over finished markdown. Answers the text and how many links it // rewrote. export async function rewriteLinks( md: string, resolver: SlugResolver, origin: string, ): Promise<{ md: string; fixed: number }> { const hrefs = new Set(); for (const m of md.matchAll(MD_LINK)) hrefs.add(m[1]!); const to = new Map(); for (const href of hrefs) { if (href.startsWith(`${origin}/`)) continue; const parsed = parseCitationHref(href); if (parsed?.kind === "span") { to.set(href, momentHref(origin, parsed.channel, parsed.id, parsed.seconds)); continue; } if (parsed?.kind === "post") { to.set(href, postLinkHref(origin, parsed.channel, parsed.id)); continue; } if (parsed) continue; // a post on its own platform: convert places it const v = platformVideo(href); if (!v) continue; const slug = await resolver.slugOf(v.id); if (slug) to.set(href, momentHref(origin, slug, v.id, v.seconds)); } if (!to.size) return { md, fixed: 0 }; let fixed = 0; const out = md.replace(MD_LINK, (whole, href: string) => { const next = to.get(href); if (!next) return whole; fixed++; return `](${next})`; }); return { md: out, fixed }; }