// Capturing PAGE RECORDS (release 37 S4, platform "webpage"): a screenshot of // each record as the Wayback Machine replays its capture, and the images it // names, into `posts-media//` (postCapture.ts owns the layout and the // record) — what `capture-posts` does for a Wayback pages channel. // // THE RENDER is the capture's replay with the `if_` modifier (no toolbar: // lib/wayback.ts waybackFrameUrl) in a headless Chromium, one fresh context // with no profile and no cookies, JavaScript OFF (the archive rewrites a // capture's links and styles server-side; the capture's own scripts would only // ask the archive for more), and every request that is not to the archive // refused — a render never reaches the live web. Fonts, stylesheets and images // load from the archive; audio/video are refused. // - a WHOLE-PAGE record (lib/waybackPages/toPost.ts isWholePageRecord) is // shot full page, cut at PAGE_SHOT_MAX_HEIGHT CSS px (`trimmed`); // - a SPLIT record (a tweet, a Tumblr post, a forum post — one item of a // capture that holds several) is shot clipped to its own element, found by // the id the extractor used (`pageItemTarget`); an item the render cannot // find is shot as the whole page, `shotScope: "page"`, and the log says so. // // THE IMAGES in a record's `media` are saved through their own Wayback URLs // (`im_`, waybackFileUrl) — at most PAGE_MEDIA_MAX per record, each capped. // // POLITE: every contact is the process's Wayback client's — the page load runs // inside its chain and gap (`paced`), the images through `getArchivedFile` — // and the job runs on the `platform:archive.org` queue. A page load answered // 429/503 stops the run there, the rest left for a later run. // // A capture says nothing about whether the ORIGINAL is still up, so no outcome // carries an availability: the posts-availability sidecar of a page record is // the original's state (release 37 S5), never this render's. import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import type { Post } from "../lib/posts"; import { waybackFileUrl, waybackFrameUrl } from "../lib/wayback"; import { WAYBACK_ORIGIN, waybackClient, waybackTestOrigin } from "../lib/waybackClient"; import { isWholePageRecord } from "../lib/waybackPages/toPost"; import type { PostCaptureInput, PostCaptureOutcome, PostCaptureResult } from "./fetchers"; import { importPlaywright, type PageLike } from "./playwrightRuntime"; import { captureWork, describeCapturedFile, postCaptureDir, readPostCapture, SHOT_FILENAME, writePostCapture, type CapturedFile, type CaptureMediaState, type PostCaptureRecord, type PostCaptureState, } from "./postCapture"; // A whole page is shot to this height (CSS px) and no further. export const PAGE_SHOT_MAX_HEIGHT = 8000; // The window the page renders in. export const PAGE_VIEWPORT = { width: 1280, height: 1600 }; // The images one record's capture saves. export const PAGE_MEDIA_MAX = 20; // How long a replay may take to load. export const PAGE_LOAD_TIMEOUT_MS = 60_000; // ─── Which element is the record ─── export type PageShotTarget = | { scope: "page" } | { scope: "item"; kind: string; // The item's own id as the page carries it (a status id, a Tumblr post // id, a forum post id). nativeId: string; // CSS selectors that name the item directly, most specific first. selectors: string[]; // A link whose href matches this (a regexp source, tested on the // href's path) is the item's permalink; a link matching `anyPermalink` // with another id is another item's. permalink?: string; anyPermalink?: string; }; const reEscape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const cssString = (s: string) => JSON.stringify(s); // What to shoot for a record: the whole page, or the item's element. Derived // from the record's kind and id (the ids lane C's extractors make — // plans/FACTS.md "Release 37 lane C"), so no locator is stored. export function pageItemTarget(post: Pick): PageShotTarget { if (!post.page || isWholePageRecord(post)) return { scope: "page" }; const kind = post.page.kind; if (kind === "tweet") { const id = post.id.replace(/^tweet-/, ""); if (!/^\d+$/.test(id)) return { scope: "page" }; return { scope: "item", kind, nativeId: id, selectors: [ `div.tweet[data-tweet-id=${cssString(id)}]`, `[data-tweet-id=${cssString(id)}]`, `li[data-item-id=${cssString(id)}]`, `[data-item-id=${cssString(id)}]`, ], permalink: `/status(?:es)?/${reEscape(id)}(?:[/?#]|$)`, anyPermalink: `/status(?:es)?/\\d+(?:[/?#]|$)`, }; } if (kind === "tumblr-post") { const id = post.id.replace(/^tumblr-/, ""); if (!/^\d+$/.test(id)) return { scope: "page" }; return { scope: "item", kind, nativeId: id, selectors: [`#post-${id}`, `#post_${id}`, `[data-post-id=${cssString(id)}]`], permalink: `/post/${reEscape(id)}(?:[/?#]|$)`, anyPermalink: `/post/\\d+(?:[/?#]|$)`, }; } if (kind === "forum-post") { const id = post.id; if (!/^\d+$/.test(id)) return { scope: "page" }; return { scope: "item", kind, nativeId: id, selectors: [`#js-post-${id}`, `article[data-content=${cssString(`post-${id}`)}]`, `#post-${id}`], permalink: `/posts/${reEscape(id)}(?:[/?#]|$)`, anyPermalink: `/posts/\\d+(?:[/?#]|$)`, }; } if (kind === "x-profile") { return { scope: "item", kind, nativeId: post.id, selectors: [".ProfileHeaderCard", ".profile-card", ".profile-details", ".ProfileCanopy"], }; } // A yt-about record, or a kind this module does not know: the page. return { scope: "page" }; } // Marks the item's element (`data-archilyzer-capture`) and answers its box in // document coordinates, or null when the page holds no such item: // 1. the first selector that matches exactly one element; // 2. else the LARGEST element around a link to the item's permalink that // holds no link to another item's permalink (lane C's Tumblr rule). export const LOCATE_ITEM_SCRIPT = (t: Extract) => `(() => { const selectors = ${JSON.stringify(t.selectors)}; const own = ${t.permalink ? `new RegExp(${JSON.stringify(t.permalink)})` : "null"}; const any = ${t.anyPermalink ? `new RegExp(${JSON.stringify(t.anyPermalink)})` : "null"}; for (const el of document.querySelectorAll("[data-archilyzer-capture]")) el.removeAttribute("data-archilyzer-capture"); const pathOf = (a) => { try { return new URL(a.getAttribute("href"), location.href).pathname; } catch { return ""; } }; let found = null; for (const sel of selectors) { let hits = []; try { hits = Array.from(document.querySelectorAll(sel)); } catch { hits = []; } if (hits.length === 1) { found = hits[0]; break; } if (hits.length > 1) { found = hits[0].closest(".tweet") || hits[0]; break; } } if (!found && own) { const links = Array.from(document.querySelectorAll("a[href]")); const mine = links.filter((a) => own.test(pathOf(a))); const others = any ? links.filter((a) => any.test(pathOf(a)) && !own.test(pathOf(a))) : []; let best = null; for (const a of mine) { let el = a.parentElement; let top = null; while (el && el !== document.body && el !== document.documentElement) { if (others.some((o) => el.contains(o))) break; top = el; el = el.parentElement; } if (top && (!best || (top.contains(best)))) best = top; } found = best; } if (!found) return null; found.setAttribute("data-archilyzer-capture", ""); const r = found.getBoundingClientRect(); return { x: r.left + window.scrollX, y: r.top + window.scrollY, width: r.width, height: r.height }; })()`; // The page's own size, for a whole-page shot. export const PAGE_SIZE_SCRIPT = `(() => { const d = document.documentElement, b = document.body; return { width: Math.max(d ? d.scrollWidth : 0, b ? b.scrollWidth : 0, window.innerWidth), height: Math.max(d ? d.scrollHeight : 0, b ? b.scrollHeight : 0, 1), }; })()`; // Let the images finish loading (each capped at 5 s), so a shot is not of // grey boxes. const IMAGES_LOADED_SCRIPT = `(() => { const imgs = Array.from(document.images).filter((i) => !i.complete); return Promise.all(imgs.map((i) => new Promise((r) => { i.addEventListener("load", r, { once: true }); i.addEventListener("error", r, { once: true }); setTimeout(r, 5000); }))).then(() => imgs.length); })()`; type Rect = { x: number; y: number; width: number; height: number }; // ─── Deps ─── export type WaybackPageCaptureDeps = { // A page in a fresh browser context: opened on the first shot, closed at // the end of the run. openPage: () => Promise<{ page: PageLike; close: () => Promise }>; // Run a page load inside the Wayback client's chain and gap. paced: (fn: () => Promise, signal: AbortSignal) => Promise; // One archived file (an image) through the Wayback client; null when the // archive does not hold it. fetchFile: (url: string, signal: AbortSignal) => Promise<{ body: Buffer; contentType: string | null } | null>; // The URL to load for a web.archive.org URL (the e2e suite's fake origin). loadUrl?: (url: string) => string; now?: () => Date; pageTimeoutMs?: number; }; // A headless Chromium with a fresh context: no profile, no cookies, no // JavaScript, and nothing but `allowOrigin` reachable. export async function openWaybackRenderPage( allowOrigin: string, ): Promise<{ page: PageLike; close: () => Promise }> { const { chromium } = await importPlaywright(); const browser = await chromium.launch({ headless: true }); try { const context = (await browser.newContext({ viewport: PAGE_VIEWPORT, deviceScaleFactor: 1, locale: "en-US", colorScheme: "light", javaScriptEnabled: false, })) as unknown as { newPage: () => Promise; close: () => Promise; route: ( match: (url: URL) => boolean, handler: (route: { request: () => { url: () => string; resourceType: () => string }; abort: () => Promise; continue: () => Promise; }) => unknown, ) => Promise; }; const origin = new URL(allowOrigin).origin; await context.route( () => true, (route) => { const req = route.request(); let ok = false; try { const u = new URL(req.url()); ok = u.origin === origin || u.protocol === "data:"; } catch { ok = false; } const type = req.resourceType(); if (!ok || type === "media" || type === "websocket" || type === "eventsource") return route.abort(); return route.continue(); }, ); const page = await context.newPage(); return { page, close: async () => { await context.close().catch(() => {}); await browser.close().catch(() => {}); }, }; } catch (err) { await browser.close().catch(() => {}); throw err; } } // The process's deps: the process's Wayback client (its chain, gap and // back-off), and the e2e suite's fake origin when E2E_WAYBACK_ORIGIN_FILE // names one (lib/waybackClient.ts waybackTestOrigin). export function liveWaybackPageCaptureDeps(): WaybackPageCaptureDeps { const testOrigin = waybackTestOrigin(); const loadUrl = (u: string) => (testOrigin ? u.replace(/^https?:\/\/(?:web|wayback)\.archive\.org/, testOrigin) : u); return { openPage: () => openWaybackRenderPage(testOrigin ?? WAYBACK_ORIGIN), paced: (fn, signal) => waybackClient.paced(fn, { signal }), fetchFile: (url, signal) => waybackClient.getArchivedFile(url, { signal }), loadUrl, }; } // ─── One record's shot ─── export type PageShotResult = { state: PostCaptureState; shot?: CapturedFile; shotScope?: "item" | "page"; trimmed?: boolean; error?: string; // The page load answered 429/503: the run stops. rateLimited?: boolean; note?: string; }; function firstLine(err: unknown): string { return ((err as Error)?.message ?? String(err)).split("\n")[0]; } // Shoot one record: load `url` (inside `paced`), find the item (or take the // page), write shot.png into `dir`. `canonicalUrl` is what the record names. export async function shootPageRecord( page: PageLike, o: { url: string; canonicalUrl: string; target: PageShotTarget; dir: string; signal: AbortSignal; paced: WaybackPageCaptureDeps["paced"]; pageTimeoutMs?: number; }, ): Promise { let status: number | undefined; try { status = await o.paced(async () => { const response = await page.goto(o.url, { waitUntil: "load", timeout: o.pageTimeoutMs ?? PAGE_LOAD_TIMEOUT_MS }); await page.evaluate(IMAGES_LOADED_SCRIPT).catch(() => 0); return (response as { status?: () => number } | null)?.status?.(); }, o.signal); } catch (err) { if (o.signal.aborted) return { state: "error", error: "cancelled" }; return { state: "error", error: `Could not load ${o.canonicalUrl}: ${firstLine(err)}` }; } if (status === 429 || status === 503) { return { state: "error", error: `the Wayback Machine answered ${status}`, rateLimited: true }; } if (status !== undefined && status >= 400) { return { state: "error", error: `the Wayback Machine answered HTTP ${status} for ${o.canonicalUrl}` }; } let rect: Rect | null = null; let scope: "item" | "page" = "page"; let note: string | undefined; if (o.target.scope === "item") { rect = (await page.evaluate(LOCATE_ITEM_SCRIPT(o.target)).catch(() => null)) as Rect | null; if (rect && rect.width >= 1 && rect.height >= 1) scope = "item"; else { rect = null; note = `the ${o.target.kind} ${o.target.nativeId} was not found on the rendered page; shot the whole page`; } } let trimmed = false; if (!rect) { const size = (await page.evaluate(PAGE_SIZE_SCRIPT).catch(() => null)) as { width: number; height: number } | null; const width = Math.max(1, Math.min(size?.width ?? PAGE_VIEWPORT.width, PAGE_VIEWPORT.width * 2)); const height = Math.max(1, size?.height ?? PAGE_VIEWPORT.height); trimmed = height > PAGE_SHOT_MAX_HEIGHT; rect = { x: 0, y: 0, width, height: Math.min(height, PAGE_SHOT_MAX_HEIGHT) }; } else if (rect.height > PAGE_SHOT_MAX_HEIGHT) { trimmed = true; rect = { ...rect, height: PAGE_SHOT_MAX_HEIGHT }; } let png: Uint8Array; try { png = await page.screenshot({ type: "png", fullPage: true, clip: { x: Math.max(0, Math.floor(rect.x)), y: Math.max(0, Math.floor(rect.y)), width: Math.ceil(rect.width), height: Math.ceil(rect.height), }, }); } catch (err) { return { state: "error", error: `The screenshot failed: ${firstLine(err)}` }; } await mkdir(o.dir, { recursive: true }); await writeFile(path.join(o.dir, SHOT_FILENAME), png); return { state: "captured", shot: await describeCapturedFile(o.dir, SHOT_FILENAME, o.canonicalUrl), shotScope: scope, ...(trimmed ? { trimmed } : {}), ...(note ? { note } : {}), }; } // ─── The images ─── const EXT_BY_TYPE: Record = { "image/jpeg": "jpg", "image/png": "png", "image/gif": "gif", "image/webp": "webp", "image/avif": "avif", "image/svg+xml": "svg", }; function imageExt(url: string, contentType: string | null): string { const ct = (contentType ?? "").split(";")[0].trim().toLowerCase(); if (EXT_BY_TYPE[ct]) return EXT_BY_TYPE[ct]; let pathname = url; try { pathname = new URL(url).pathname; } catch { /* the raw string */ } const m = /\.([a-z0-9]{2,5})$/i.exec(pathname); return m ? m[1].toLowerCase().replace("jpeg", "jpg") : "bin"; } // The images a record's capture saves: its `media` of kind image, each by its // own Wayback URL at the record's capture time, deduplicated, at most // PAGE_MEDIA_MAX. export function pageRecordImages(post: Pick): { url: string; source: string }[] { const ts = post.page?.captureTs; if (!ts) return []; const out: { url: string; source: string }[] = []; for (const m of post.media ?? []) { if (m.kind !== "image" || !/^https?:\/\//.test(m.url)) continue; const url = waybackFileUrl(ts, m.url); if (out.some((x) => x.url === url)) continue; out.push({ url, source: m.url }); if (out.length >= PAGE_MEDIA_MAX) break; } return out; } // ─── The run ─── const STOP_AFTER_ERRORS = 3; export type PageCaptureInput = Pick< PostCaptureInput, "ids" | "outDir" | "shots" | "media" | "force" | "signal" | "drain" | "onLog" > & { // The archived records, by id (capturePosts reads them). records: ReadonlyMap; }; export async function captureWaybackPageRecords( input: PageCaptureInput, deps: WaybackPageCaptureDeps, ): Promise { const { signal, onLog } = input; const wanted = { shots: input.shots ?? true, media: input.media ?? true, force: input.force ?? false }; const now = deps.now ?? (() => new Date()); const load = deps.loadUrl ?? ((u: string) => u); const outcomes: PostCaptureOutcome[] = []; const stopped = (why: string): PostCaptureResult => { onLog?.(why); return { outcomes, stoppedEarly: why }; }; let browser: { page: PageLike; close: () => Promise } | undefined; let errorsInARow = 0; try { for (const [i, id] of input.ids.entries()) { if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run."); const post = input.records.get(id); if (!post?.page) { onLog?.(`${id}: not a page record (no capture facts) — skipped.`); outcomes.push({ id, state: "error", files: 0, error: "not a page record" }); continue; } const dir = postCaptureDir(input.outDir, id); const existing = await readPostCapture(dir); const work = captureWork(existing, { ...wanted, articles: false }); if (!work.shot && !work.media) { onLog?.(`${id}: already captured (${existing?.state ?? "nothing asked for"}) — skipped.`); continue; } onLog?.(`[${i + 1}/${input.ids.length}] ${id}`); const frameUrl = waybackFrameUrl(post.page); let state: PostCaptureState | undefined = work.shot ? undefined : existing?.state; let shot = work.shot ? undefined : existing?.shot; let shotScope = work.shot ? undefined : existing?.shotScope; let trimmed = work.shot ? undefined : existing?.trimmed; let error: string | undefined; let stop: string | undefined; if (work.shot) { browser ??= await deps.openPage(); const res = await shootPageRecord(browser.page, { url: load(frameUrl), canonicalUrl: frameUrl, target: pageItemTarget(post), dir, signal, paced: deps.paced, ...(deps.pageTimeoutMs ? { pageTimeoutMs: deps.pageTimeoutMs } : {}), }); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); state = res.state; shot = res.shot; shotScope = res.shotScope; trimmed = res.trimmed; error = res.error; if (res.note) onLog?.(`${id}: ${res.note}.`); if (res.rateLimited) stop = `${res.error}; stopping.`; } let mediaState: CaptureMediaState = work.media ? "skipped" : (existing?.mediaState ?? "skipped"); let media: CapturedFile[] = work.media ? [] : (existing?.media ?? []); if (work.media && !stop && (state === undefined || state === "captured")) { const images = pageRecordImages(post); if (images.length === 0) { mediaState = "none"; } else { let failed = 0; for (const [n, im] of images.entries()) { if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); let got; try { got = await deps.fetchFile(im.url, signal); } catch (err) { failed++; onLog?.(`${id}: image ${n + 1} failed: ${firstLine(err)}`); if ((err as { rateLimited?: boolean }).rateLimited) { stop = `${firstLine(err)}; stopping.`; break; } continue; } if (!got) { failed++; onLog?.(`${id}: image ${n + 1} is not in the archive (or over the cap): ${im.source}`); continue; } const name = `media-${n + 1}.${imageExt(im.source, got.contentType)}`; await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, name), got.body); media.push(await describeCapturedFile(dir, name, im.url)); } mediaState = failed > 0 ? "error" : "ok"; if (failed > 0) error = error ? `${error}; ${failed} image(s) failed` : `${failed} image(s) failed`; } state ??= existing?.state ?? "captured"; } const finalState: PostCaptureState = state ?? "error"; const record: PostCaptureRecord = { version: 1, id, url: frameUrl, capturedAt: now().toISOString(), state: finalState, ...(shot ? { shot } : {}), ...(shot && shotScope ? { shotScope } : {}), ...(shot && trimmed ? { trimmed } : {}), mediaState, media, ...(error ? { error } : {}), }; await writePostCapture(dir, record); outcomes.push({ id, state: finalState, files: (shot ? 1 : 0) + media.length, ...(error ? { error } : {}) }); onLog?.( `${id}: ${finalState}` + (work.shot && shot ? `, shot (${shotScope ?? "page"}${trimmed ? ", trimmed" : ""})` : "") + (mediaState === "ok" ? `, ${media.length} image(s)` : mediaState === "none" ? ", no images" : "") + (error ? ` — ${error}` : ""), ); if (stop) return stopped(`${stop} Stopped at ${id}; the rest are left for a later run.`); errorsInARow = finalState === "error" ? errorsInARow + 1 : 0; if (errorsInARow >= STOP_AFTER_ERRORS) { return stopped(`${STOP_AFTER_ERRORS} records in a row failed; stopping rather than going through the rest.`); } } return { outcomes }; } finally { await browser?.close().catch(() => {}); } }