// Release 37 S5: find-copy's page mode on the fake Wayback — a cited page // whose original is gone gets the capture nearest its date imported into the // channel whose targets cover it, and the answer names the record to cite (and // the citation as a post citation of it); a dry run imports nothing; a live // page, an uncovered one and one the archive never captured are left with // their reason; a page already held is not fetched again; a cited page record // whose original is gone is "held" when its capture is stored, imported again // when it is not. The original sites are a stub; no network. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/findCopyPages.test.ts import test, { after } from "node:test"; import assert from "node:assert/strict"; import { mkdtempSync, rmSync } from "node:fs"; import { mkdir, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { startFakeWayback, PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_TS, PAGE_ARTICLE_URL, PAGE_TOOLBAR_TS, PAGE_TOOLBAR_URL, } from "../testing/web/fakeWayback.mjs"; import type { Paths } from "../lib/paths"; import type { Citation } from "../lib/citations/schema"; import type { ReportHost } from "./reportHost"; import type { OriginalCheck } from "../lib/waybackPages/liveness"; import { WaybackClient } from "../lib/waybackClient"; import { readAllPosts, upsertPosts, writePostAvailability } from "../lib/posts-server"; import { pageRecordId } from "../lib/waybackPages/types"; import { importPage } from "../controller/importPage"; import { captureAtOf, channelsCovering, findPageCopies, pageCitationAsPost, recordForQuote, targetCoversUrl } from "./findCopyPages"; const ROOT = mkdtempSync(path.join(tmpdir(), "find-page-copy-")); after(() => rmSync(ROOT, { recursive: true, force: true })); const paths = { channelsDir: path.join(ROOT, "channels"), transcriptsDir: ROOT, jobsDir: path.join(ROOT, "jobs") } as unknown as Paths; const SETTINGS = { social: { x: { visibility: "private" } } }; const HOST = { id: "demo-site" } as unknown as ReportHost; const NOW = new Date("2026-10-20T12:00:00Z"); async function pagesChannel(slug: string, target: string, match = "prefix") { const dir = path.join(paths.channelsDir, slug); await mkdir(dir, { recursive: true }); await writeFile( path.join(dir, "config.json"), JSON.stringify({ name: slug, handling: "transcribe", sourceKind: "social", platform: "webpage", socialHandle: target.split("/")[0], url: `https://web.archive.org/web/*/${target}*`, wayback: { targets: [{ url: target, match }] }, }), ); return dir; } const verdict = (url: string, availability: OriginalCheck["availability"], status: number | null): OriginalCheck => ({ url, availability, status, reason: status ? `HTTP ${status}` : "no answer", }); test("which channel covers a page; the date a citation asks for; the record a quote is from; a page citation as a post", () => { assert.equal(targetCoversUrl({ url: "blog.example/2014/", match: "prefix" }, "https://www.blog.example/2014/03/a.html"), true); assert.equal(targetCoversUrl({ url: "blog.example/2015/", match: "prefix" }, "https://blog.example/2014/03/a.html"), false); assert.equal(targetCoversUrl({ url: "https://blog.example/a", match: "exact" }, "http://blog.example/a/"), true); assert.equal(targetCoversUrl({ url: "blog.example", match: "host" }, "https://sub.blog.example/"), false); assert.equal(targetCoversUrl({ url: "blog.example", match: "domain" }, "https://sub.blog.example/"), true); assert.deepEqual( channelsCovering( [ { slug: "vids", config: { url: "x" } as never }, { slug: "blog", config: { sourceKind: "social", platform: "webpage", wayback: { targets: [{ url: "blog.example", match: "host" }] } } }, ], "https://blog.example/a", ), ["blog"], ); assert.equal(captureAtOf({ date: "2015-06-01" }, NOW), "20150601"); assert.equal(captureAtOf({ date: "2015" }, NOW), "2015"); assert.equal(captureAtOf({ archiveUrl: `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}` }, NOW), PAGE_ARTICLE_TS); assert.equal(captureAtOf({}, NOW), "20261020"); assert.equal(recordForQuote([{ id: "a", text: "one thing" }, { id: "b", text: "Another “thing” said" }], 'another "thing"'), "b"); assert.equal(recordForQuote([{ id: "a", text: "x" }], "not there"), "a"); assert.deepEqual( pageCitationAsPost({ kind: "page", url: PAGE_ARTICLE_URL, title: "T", archiveUrl: "https://web.archive.org/web/1/x", quote: "q", label: "L", note: "n" }, { channel: "blog", id: "r1" }), { kind: "post", channel: "blog", id: "r1", quote: "q", label: "L", note: "n", fallback: { kind: "page", url: PAGE_ARTICLE_URL, title: "T", archiveUrl: "https://web.archive.org/web/1/x" }, }, ); }); test("a gone cited page: dry run names the nearest capture; the run imports it and names the record to cite; again = held", async () => { const wb = await startFakeWayback(); try { const client = new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0 }); const dir = await pagesChannel("old-blog", "blog.example/"); const citations: Record = { c1: { kind: "page", url: PAGE_ARTICLE_URL, date: "2015-06", quote: "Update: the fourth loaf rose.", label: "The post" }, c2: { kind: "page", url: "https://live.example/up", quote: "still here" }, c3: { kind: "page", url: "https://elsewhere.example/gone", quote: "nobody covers this" }, c4: { kind: "page", url: "https://blog.example/never-captured.html", quote: "never captured" }, c5: { kind: "video", channel: "v", id: "abc", start: 1, end: 2, quote: "a video" }, }; const reports = [ { id: "r1", citations }, { id: "r2", citations: { x1: { kind: "page", url: PAGE_ARTICLE_URL, quote: "The first loaf came out flat" } as Citation } }, ]; const checks = new Map([ [PAGE_ARTICLE_URL, verdict(PAGE_ARTICLE_URL, "deleted", 404)], ["https://live.example/up", verdict("https://live.example/up", "available", 200)], ["https://elsewhere.example/gone", verdict("https://elsewhere.example/gone", "deleted", 410)], ["https://blog.example/never-captured.html", verdict("https://blog.example/never-captured.html", "deleted", 404)], ]); const asked: string[] = []; const deps = { reports: async () => reports, check: async (url: string) => { asked.push(url); return checks.get(url) ?? verdict(url, "error", null); }, nearest: (url: string, at: string) => client.closestCapture(url, at), importCapture: (o: { slug: string; url: string }) => importPage({ paths, slug: o.slug, url: o.url, client, settings: SETTINGS }), now: () => NOW, }; const lines: string[] = []; const dry = await findPageCopies({ paths, host: HOST, dryRun: true, deps, onLog: (l) => lines.push(l) }); assert.deepEqual([dry.pages, dry.posts], [4, 0]); const byUrl = (r: typeof dry) => new Map(r.items.map((i) => [i.url, i])); const d = byUrl(dry); assert.equal(d.get(PAGE_ARTICLE_URL)!.outcome, "would-import"); assert.equal(d.get(PAGE_ARTICLE_URL)!.capture!.timestamp, PAGE_ARTICLE_LATER_TS, "the capture nearest 2015-06"); assert.deepEqual(d.get(PAGE_ARTICLE_URL)!.citedBy, ["r1#c1", "r2#x1"]); assert.equal(d.get("https://live.example/up")!.outcome, "live"); assert.equal(d.get("https://elsewhere.example/gone")!.outcome, "no-channel"); assert.equal(d.get("https://blog.example/never-captured.html")!.outcome, "none-found"); assert.deepEqual(await readAllPosts(dir), [], "a dry run imports nothing"); assert.ok(lines.some((l) => /1 capture\(s\) would be imported \(dry run: nothing imported\)/.test(l))); const run = await findPageCopies({ paths, host: HOST, deps }); const item = byUrl(run).get(PAGE_ARTICLE_URL)!; const id = pageRecordId(PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_URL); assert.equal(item.outcome, "imported", item.detail); assert.deepEqual(item.pointTo, { channel: "old-blog", id }); assert.deepEqual(item.as, { kind: "post", channel: "old-blog", id, date: "2015-06", quote: "Update: the fourth loaf rose.", label: "The post", fallback: { kind: "page", url: PAGE_ARTICLE_URL }, }); assert.deepEqual((await readAllPosts(dir)).map((p) => p.id), [id]); // Again: the channel holds the page — nothing fetched. const before = wb.requests.length; const again = await findPageCopies({ paths, host: HOST, deps }); assert.equal(byUrl(again).get(PAGE_ARTICLE_URL)!.outcome, "held"); assert.deepEqual(byUrl(again).get(PAGE_ARTICLE_URL)!.pointTo, { channel: "old-blog", id }); assert.equal(wb.requests.length - before, 1, "only the never-captured page's CDX lookup"); // `max` leaves the rest for a later run. const capped = await findPageCopies({ paths, host: HOST, deps, max: 1, dryRun: true }); assert.deepEqual([capped.items.length, capped.left], [1, 3]); // A named channel that is not a pages channel is refused. await assert.rejects(findPageCopies({ paths, host: HOST, deps, channel: "nope" }), /not a Wayback pages channel/); } finally { await wb.close(); } }); test("a cited page record whose original is gone: held when its capture is stored, imported again when it is not", async () => { const wb = await startFakeWayback(); try { const client = new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0 }); const dir = await pagesChannel("home-site", "home.example/"); // One record whose capture is stored (imported), one whose is not (its // record written alone). const imp = await importPage({ paths, slug: "home-site", url: `https://web.archive.org/web/${PAGE_TOOLBAR_TS}/${PAGE_TOOLBAR_URL}`, client, settings: SETTINGS }); assert.equal(imp.ok, true, imp.error); const stored = imp.records![0]!; const loose = (await readAllPosts(dir))[0]!; const looseUrl = "https://home.example/links"; const looseTs = "20150101000000"; const looseId = pageRecordId(looseTs, looseUrl); await upsertPosts(dir, [ { ...loose, id: looseId, slug: `home-site/${looseId}`, url: looseUrl, page: { ...loose.page!, originalUrl: looseUrl, captureTs: looseTs, waybackUrl: `https://web.archive.org/web/${looseTs}/${looseUrl}`, rawUrl: `https://web.archive.org/web/${looseTs}id_/${looseUrl}` }, }, ]); await writePostAvailability(dir, { [stored]: { availability: "deleted", checkedAt: "2026-10-19T00:00:00Z", status: 404, reason: "HTTP 404" }, [looseId]: { availability: "deleted", checkedAt: "2026-10-19T00:00:00Z", status: 404, reason: "HTTP 404" }, }); const imported: string[] = []; const deps = { reports: async () => [ { id: "r9", citations: { a: { kind: "post", channel: "home-site", id: stored, quote: "zines" } as Citation, b: { kind: "post", channel: "home-site", id: looseId, quote: "links" } as Citation, c: { kind: "post", channel: "not-a-pages-channel", id: "1", quote: "x" } as Citation, }, }, ], check: async (url: string) => verdict(url, "error", null), nearest: (url: string, at: string) => client.closestCapture(url, at), importCapture: async (o: { slug: string; url: string }) => { imported.push(o.url); return { ok: true, slug: o.slug, url: o.url, written: 0, updated: 0, unchanged: 1, records: [looseId] }; }, now: () => NOW, }; const dry = await findPageCopies({ paths, host: HOST, dryRun: true, deps }); assert.equal(dry.posts, 2); const of = (r: typeof dry, id: string) => r.items.find((i) => i.record?.id === id)!; assert.equal(of(dry, stored).outcome, "held"); assert.equal(of(dry, looseId).outcome, "would-import"); assert.deepEqual(imported, []); const run = await findPageCopies({ paths, host: HOST, deps }); assert.equal(of(run, looseId).outcome, "imported"); assert.deepEqual(imported, [`https://web.archive.org/web/${looseTs}/${looseUrl}`]); assert.deepEqual(of(run, stored).pointTo, { channel: "home-site", id: stored }); } finally { await wb.close(); } }); test("find-copy's `as` and Import this capture write the same citation (one builder, the page as its fallback)", async () => { const { pageCitationAsPost: shared } = await import("../lib/citations/pageAsPost"); assert.equal(pageCitationAsPost, shared); });