// THE REMOTE-ARCHIVE RESOLVER's network half (./remoteArchives.ts is the pure // one): what a published archive says about itself, read from its // `/corpus.json` — the title, the totals and the channels the Connect form // shows before anything is saved. // // One request per probe, sequential, never in a loop. The fetch is injectable // (every test passes a fake; no test calls a real site). import { archiveOriginOf, sameOrigin } from "./remoteArchives"; import { corpusUrl, manifestUrl, pageUrl } from "./archive/contract"; import { detectPlatform } from "./detectPlatform.mjs"; export type FetchLike = (url: string, init?: { signal?: AbortSignal; headers?: Record }) => Promise; export type ArchiveProbeChannel = { slug: string; name: string; videoCount: number | null; // Spec 6 (corpus.json carries them); absent from an older archive's entry. platform?: string; url?: string; }; export type ArchiveProbe = { origin: string; // corpus.json's own: site.id, site.title, spec, generatedAt. siteId: string | null; title: string; description: string; spec: number | null; generatedAt: string | null; totals: { channels: number; videos: number }; channels: ArchiveProbeChannel[]; }; export class ArchiveProbeError extends Error { constructor( message: string, readonly status = 400, ) { super(message); this.name = "ArchiveProbeError"; } } const PROBE_TIMEOUT_MS = 15_000; const MAX_REDIRECTS = 3; // The largest archive document read (demo epic D1 review follow-up): a shard // page is up to 8 MB; anything past 32 MB is refused, not buffered. export const MAX_ARCHIVE_DOCUMENT_BYTES = 32 * 1024 * 1024; export class OversizeError extends Error { constructor(message: string) { super(message); this.name = "OversizeError"; } } /** A response's body as text, refused past `max` bytes (by its Content-Length, then as it streams). */ export async function readBounded(res: Response, url: string, max = MAX_ARCHIVE_DOCUMENT_BYTES): Promise { const declared = Number(res.headers.get("content-length")); const over = () => new OversizeError(`${url} is over ${Math.round(max / 1024 / 1024)} MB: an archive document that large is not read`); if (Number.isFinite(declared) && declared > max) { await res.body?.cancel().catch(() => {}); throw over(); } if (!res.body) return ""; const reader = res.body.getReader(); const chunks: Uint8Array[] = []; let total = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; total += value.byteLength; if (total > max) { await reader.cancel().catch(() => {}); throw over(); } chunks.push(value); } return Buffer.concat(chunks).toString("utf8"); } export class OffOriginError extends Error { constructor(message: string) { super(message); this.name = "OffOriginError"; } } /** * A GET that stays on `url`'s own origin (demo epic D1 review, blocker 2): a * redirect is followed (up to three) only to the same scheme, host and port; * one that leaves it is refused before it is followed. An archive is someone * else's server, and nothing it answers may send this machine elsewhere. */ export async function fetchOnOrigin(doFetch: FetchLike, url: string, init: { signal?: AbortSignal; headers?: Record } = {}): Promise { let at = url; for (let hop = 0; ; hop++) { const res = await doFetch(at, { ...init, redirect: "manual" } as never); if (res.status < 300 || res.status > 399 || res.status === 304) return res; const location = res.headers.get("location"); if (!location) return res; const next = new URL(location, at).href; if (!sameOrigin(next, url)) throw new OffOriginError(`${at} redirects to ${new URL(next).origin}: an archive's documents are read from its own origin only`); if (hop >= MAX_REDIRECTS) throw new OffOriginError(`${url} redirects more than ${MAX_REDIRECTS} times`); at = next; } } const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : null); const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null); /** * Read `/corpus.json` and say what the archive is. Refused, with a * sentence: not an origin, unreachable, not JSON, a federation hub (connect * one of its sites), a cited-only site (it publishes reports, no corpus), or * a site listing no channels. */ export async function probeArchive(rawOrigin: string, opts: { fetch?: FetchLike; timeoutMs?: number } = {}): Promise { const origin = archiveOriginOf(rawOrigin); if (!origin) throw new ArchiveProbeError(`"${rawOrigin}" is not an archive's address — type its origin, e.g. https://jeralyzer.pages.dev`); const doFetch = opts.fetch ?? (fetch as unknown as FetchLike); const url = `${origin}/corpus.json`; let res: Response; try { res = await fetchOnOrigin(doFetch, url, { signal: AbortSignal.timeout(opts.timeoutMs ?? PROBE_TIMEOUT_MS), headers: { accept: "application/json" } }); } catch (e) { if (e instanceof OffOriginError) throw new ArchiveProbeError(e.message, 502); throw new ArchiveProbeError(`${url} did not answer: ${(e as Error).message}`, 502); } if (!res.ok) throw new ArchiveProbeError(`${url} answered HTTP ${res.status} — is ${origin} a published archive?`, 502); let j: Record; try { j = JSON.parse(await readBounded(res, url)) as Record; } catch (e) { if (e instanceof OversizeError) throw new ArchiveProbeError(e.message, 502); throw new ArchiveProbeError(`${url} is not JSON — ${origin} does not serve an archive's contract`, 502); } if (!j || typeof j !== "object" || Array.isArray(j)) throw new ArchiveProbeError(`${url} is not an archive's corpus.json`, 502); if (j.kind === "hub" || Array.isArray(j.sites)) { const sites = Array.isArray(j.sites) ? (j.sites as Record[]) : []; const names = sites .map((s) => str(s?.url)) .filter((u): u is string => !!u) .slice(0, 6); throw new ArchiveProbeError( `${origin} is a federation hub of ${sites.length} site(s), not one archive — connect one of its sites${names.length ? `: ${names.join(", ")}` : ""}`, ); } const site = (j.site && typeof j.site === "object" ? j.site : {}) as Record; if (site.scope === "cited") { throw new ArchiveProbeError(`${origin} publishes only its reports and the moments they cite — it has no corpus to search`); } const rawChannels = Array.isArray(j.channels) ? (j.channels as Record[]) : []; const channels: ArchiveProbeChannel[] = []; for (const c of rawChannels) { const slug = str(c?.slug); if (!slug) continue; const platform = str(c.platform); const curl = str(c.url); channels.push({ slug, name: str(c.name) ?? slug, videoCount: num(c.videoCount), ...(platform ? { platform } : {}), ...(curl ? { url: curl } : {}), }); } if (channels.length === 0) throw new ArchiveProbeError(`${origin}'s corpus.json lists no channels — there is nothing to search`); const totals = (j.totals && typeof j.totals === "object" ? j.totals : {}) as Record; return { origin, siteId: str(site.id), title: str(site.title) ?? origin.replace(/^https?:\/\//, ""), description: str(site.description) ?? "", spec: num(j.spec), generatedAt: str(j.generatedAt), totals: { channels: num(totals.channels) ?? channels.length, videos: num(totals.videos) ?? channels.reduce((n, c) => n + (c.videoCount ?? 0), 0), }, channels, }; } // ─── A channel's facts: where it is (demo epic D1 item 4) ─── export type ArchiveChannelFacts = { slug: string; name: string; // The platform its recordings are on, or null when the archive does not say // and no record names one. platform: string | null; // Its page on that platform (corpus.json spec 6), or null. url: string | null; // Where the facts came from: corpus.json's channel entry (spec 6), the // channel's first shard record (an older archive), or nowhere. from: "corpus" | "record" | "none"; // A record's own page (the fallback's evidence), when one was read. sampleVideoUrl?: string; }; export class ArchiveChannelError extends Error { constructor( message: string, readonly status = 404, ) { super(message); this.name = "ArchiveChannelError"; } } // One JSON document over HTTP: a throw on anything but a 200. Injectable as // `getJson` so the cached reader (item 6) is the one every lookup goes through. export type GetJson = (url: string) => Promise; export function plainGetJson(doFetch: FetchLike = fetch as unknown as FetchLike): GetJson { return async (url) => { const res = await fetchOnOrigin(doFetch, url, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS), headers: { accept: "application/json" } }); if (!res.ok) throw new ArchiveChannelError(`${url} answered HTTP ${res.status}`, res.status === 404 ? 404 : 502); return JSON.parse(await readBounded(res, url)); }; } /** * Where an archive's channel is: corpus.json's `platform` and `url` (spec 6); * for an OLDER archive whose entry has no platform, the channel's first shard * record — the transcripts manifest's lowest page, its first record with a * `webpageUrl` — gives the platform (the record's own, else its page's host). * Sequential: at most three documents, one after another. A slug the archive * does not list is refused. */ export async function archiveChannelFacts(origin: string, slug: string, opts: { getJson?: GetJson; fetch?: FetchLike } = {}): Promise { const base = archiveOriginOf(origin); if (!base) throw new ArchiveChannelError(`"${origin}" is not an archive's address`, 400); const getJson = opts.getJson ?? plainGetJson(opts.fetch); const corpus = (await getJson(corpusUrl(base))) as { channels?: Record[] } | null; const entry = (Array.isArray(corpus?.channels) ? corpus!.channels : []).find((c) => c?.slug === slug); if (!entry) throw new ArchiveChannelError(`${base} lists no channel "${slug}"`); const name = str(entry.name) ?? slug; const platform = str(entry.platform); const url = str(entry.url); if (platform) return { slug, name, platform, url: url && /^https?:\/\//i.test(url) ? url : null, from: "corpus" }; // An older archive: the first record's page. const manifests = (entry.manifests && typeof entry.manifests === "object" ? entry.manifests : {}) as Record; // Only the archive's own origin is read: a manifest the corpus names elsewhere is not followed. const named = str(manifests.transcripts); const manifestAt = named && sameOrigin(named, base) ? named : manifestUrl("transcripts", slug, base); const manifest = (await getJson(manifestAt).catch(() => null)) as { slugToPage?: Record } | null; const pages = Object.values(manifest?.slugToPage ?? {}).filter((n): n is number => typeof n === "number" && Number.isInteger(n) && n >= 0); if (pages.length > 0) { const first = Math.min(...pages); const records = (await getJson(pageUrl("transcripts", slug, first, base)).catch(() => null)) as Record[] | null; for (const r of Array.isArray(records) ? records : []) { const page = str(r?.webpageUrl); if (!page) continue; const p = str(r.platform) ?? detectPlatform(page); return { slug, name, platform: p, url: url && /^https?:\/\//i.test(url) ? url : null, from: p ? "record" : "none", sampleVideoUrl: page }; } } return { slug, name, platform: null, url: url && /^https?:\/\//i.test(url) ? url : null, from: "none" }; }