// `channels//wayback-scan.json` — what a Wayback pages channel's scan // found (release 37 S2; written by controller/waybackScan.ts, read by the // channel page's Captures tab and the download lane's `wayback.auto` pick). // Every distinct (original URL, digest) the CDX API listed for the channel's // targets — no bodies: a scan never fetches one, only `import-page` does. // // Shape: `{format: "archilyzer-wayback-scan", version: 1, slug, pass, // passStartedAt, previousPassStartedAt?, lastScanAt?, jobId?, targets, rows, // summary}`. // targets[] per target: {key, url, match, from?, to?, resumeKey?, complete, // rows (CDX rows read this pass), lastScanAt?, completedAt?, // passFrom?, excluded?} // rows[] {originalUrl, digest, firstTs, lastTs, count, mimetype, status, // pass (the pass that first listed it)} // summary {pages, versions, byYear (first seen), byPrefix (first one and // two path segments, host first)} // // A PASS is one walk of every target to its end. A pass that is cut (the row // cap, a refusal, a drain) keeps each target's resume key and the next run // continues it; once every target is complete the next run starts a new pass, // asking only for captures from 30 days before the previous pass started (the // CDX index lags the crawl). A row is NEW when a pass after the first listed it // in the current pass. Imported state is NOT stored here — it is derived from // the channel's posts (imported.ts). // // Pure, client-safe (types, merge, summaries). import type { WaybackMatchType } from "./targets"; import type { CdxScanRow } from "./scanCdx"; export const WAYBACK_SCAN_FORMAT = "archilyzer-wayback-scan"; export const WAYBACK_SCAN_VERSION = 1; export const WAYBACK_SCAN_FILENAME = "wayback-scan.json"; // How far before the previous pass's start a later pass asks from. export const PASS_OVERLAP_DAYS = 30; export type WaybackScanTarget = { key: string; url: string; match: WaybackMatchType; from?: string; to?: string; resumeKey?: string; complete: boolean; // CDX rows read for this target in the current pass. rows: number; lastScanAt?: string; completedAt?: string; // The lower bound this pass asks from (a later pass only). passFrom?: string; // Release 38 lane C: this pass's listing was refused as excluded — // WAYBACK_EXCLUDED_PHRASE. Cleared when a new pass starts. excluded?: string; }; export type WaybackScanRow = { originalUrl: string; digest: string; // YYYYMMDDhhmmss: the earliest and latest capture of this content listed. // With collapse=digest a run of identical captures is listed once, at its // first; `count` counts the listed captures, not every crawl. firstTs: string; lastTs: string; count: number; mimetype: string; status: number; pass: number; }; export type WaybackScanSummary = { // Distinct original URLs, and distinct (URL, digest). pages: number; versions: number; byYear: Record; byPrefix: Record; }; export type WaybackScanFile = { format: typeof WAYBACK_SCAN_FORMAT; version: typeof WAYBACK_SCAN_VERSION; slug: string; pass: number; passStartedAt: string; previousPassStartedAt?: string; lastScanAt?: string; jobId?: string; targets: WaybackScanTarget[]; rows: WaybackScanRow[]; summary: WaybackScanSummary; }; export function isWaybackScanFile(v: unknown): v is WaybackScanFile { const f = v as WaybackScanFile | null; return ( !!f && typeof f === "object" && f.format === WAYBACK_SCAN_FORMAT && f.version === WAYBACK_SCAN_VERSION && typeof f.slug === "string" && typeof f.pass === "number" && Array.isArray(f.targets) && Array.isArray(f.rows) ); } export function emptyScanFile(slug: string, now: string): WaybackScanFile { return { format: WAYBACK_SCAN_FORMAT, version: WAYBACK_SCAN_VERSION, slug, pass: 1, passStartedAt: now, targets: [], rows: [], summary: { pages: 0, versions: 0, byYear: {}, byPrefix: {} }, }; } export function scanRowKey(r: Pick): string { return `${r.originalUrl}\u0000${r.digest}`; } // Fold one page of CDX rows into `file.rows` (mutated): a new (URL, digest) // is added under the current pass; a known one widens its first/last seen and // counts the capture when it lies outside what was already seen. Answers how // many rows were added. `index` is the caller's key → row map, kept across // pages so a 50,000-row file is not rescanned per page. export function mergeCdxRows( file: WaybackScanFile, rows: ReadonlyArray, index: Map = indexScanRows(file), ): number { let added = 0; for (const r of rows) { const key = scanRowKey(r); const have = index.get(key); if (!have) { const row: WaybackScanRow = { originalUrl: r.originalUrl, digest: r.digest, firstTs: r.timestamp, lastTs: r.timestamp, count: 1, mimetype: r.mimetype, status: r.status, pass: file.pass, }; file.rows.push(row); index.set(key, row); added++; continue; } if (r.timestamp < have.firstTs) { have.firstTs = r.timestamp; have.count++; } else if (r.timestamp > have.lastTs) { have.lastTs = r.timestamp; have.count++; } } return added; } export function indexScanRows(file: Pick): Map { return new Map(file.rows.map((r) => [scanRowKey(r), r])); } // A row is new when a pass after the first listed it in the current pass. export function isNewRow(file: Pick, row: Pick): boolean { return file.pass > 1 && row.pass === file.pass; } // "example.org" for every www./port spelling of one host. export function normalHost(host: string): string { return host.toLowerCase().replace(/^www\./, "").replace(/:(80|443)$/, ""); } function parseUrl(u: string): URL | null { try { return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(u) ? u : `http://${u}`); } catch { return null; } } // The first `depth` path segments of a URL, host first: "example.org/blog/", // "example.org/blog/2014/". A URL with fewer segments is its own path's // directory ("example.org/"). export function pathPrefixOf(originalUrl: string, depth: 1 | 2): string { const u = parseUrl(originalUrl); if (!u) return originalUrl; const segs = u.pathname.split("/").filter(Boolean); // The last segment of a path that does not end in "/" is a page, not a dir. const dirs = u.pathname.endsWith("/") ? segs : segs.slice(0, -1); const take = dirs.slice(0, depth); return `${normalHost(u.host)}/${take.map((s) => `${s}/`).join("")}`; } // What the table shows for a URL: its path and query, with the host first // when the scan spans hosts. export function displayPathOf(originalUrl: string, withHost: boolean): string { const u = parseUrl(originalUrl); if (!u) return originalUrl; const p = `${u.pathname}${u.search}`; return withHost ? `${normalHost(u.host)}${p}` : p; } export function hostsOf(rows: ReadonlyArray>): Set { const out = new Set(); for (const r of rows) { const u = parseUrl(r.originalUrl); if (u) out.add(normalHost(u.host)); } return out; } // Prefixes kept in the summary: every one-segment prefix, and the two-segment // ones that hold more than one row (a two-segment prefix per post would be a // copy of the rows), at most this many of each, most rows first. export const SUMMARY_PREFIXES_MAX = 200; export function summarizeScan(rows: ReadonlyArray): WaybackScanSummary { const pages = new Set(); const byYear: Record = {}; const one = new Map(); const two = new Map(); for (const r of rows) { pages.add(r.originalUrl); const y = r.firstTs.slice(0, 4); byYear[y] = (byYear[y] ?? 0) + 1; const p1 = pathPrefixOf(r.originalUrl, 1); const p2 = pathPrefixOf(r.originalUrl, 2); one.set(p1, (one.get(p1) ?? 0) + 1); if (p2 !== p1) two.set(p2, (two.get(p2) ?? 0) + 1); } const top = (m: Map, min: number) => [...m.entries()] .filter(([, n]) => n >= min) .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) .slice(0, SUMMARY_PREFIXES_MAX); const byPrefix: Record = {}; for (const [k, n] of [...top(one, 1), ...top(two, 2)].sort((a, b) => a[0].localeCompare(b[0]))) byPrefix[k] = n; return { pages: pages.size, versions: rows.length, byYear, byPrefix }; } // Rows in table order: by URL, then by first seen. export function sortScanRows(rows: WaybackScanRow[]): WaybackScanRow[] { return rows.sort((a, b) => a.originalUrl.localeCompare(b.originalUrl) || a.firstTs.localeCompare(b.firstTs)); } // YYYYMMDDhhmmss of an ISO time, minus `days`. export function cdxTsBefore(iso: string, days: number): string { const ms = Date.parse(iso) - days * 86_400_000; const d = new Date(Number.isFinite(ms) ? ms : 0); const p = (n: number, w = 2) => String(n).padStart(w, "0"); return `${p(d.getUTCFullYear(), 4)}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}`; } // "2014-05-06" of a CDX timestamp. export function cdxTsDate(ts: string): string { return ts.length >= 8 ? `${ts.slice(0, 4)}-${ts.slice(4, 6)}-${ts.slice(6, 8)}` : ts; }