Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 7d7a2c3a35b01d10493fc2ef9800d1821780e4c3
parent 6e886bef66ca55f2628a5b974ffbff6718487fb5
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 12:07:25 -0400

Merge r37/core: Wayback page captures as records — platform webpage, raw captures, pages/ store, generic extractor, import-page, reextract, the Wayback pages channel kind

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCHANNEL.md | 3++-
MCITATIONS.md | 4++--
MCOMMANDS.md | 4++++
MENVIRONMENT.md | 1+
MOPERATING.md | 30++++++++++++++++++++++++++++++
Mcommon/bin/archilyzer.ts | 36++++++++++++++++++++++++++++++++++++
Acommon/bin/compose-site.waybackPages.test.ts | 155+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/wayback-pages.ts | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/fetchPosts.ts | 9+++++++++
Acommon/controller/importPage.test.ts | 234+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/importPage.ts | 373+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/reextractPages.ts | 192+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.ts | 29+++++++++++++++++++++++++++++
Mcommon/lib/archiveOrgClient.ts | 84++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/lib/channelConfig.ts | 10++++++++--
Mcommon/lib/channelConfigSchema.test.ts | 2+-
Mcommon/lib/channelConfigSchema.ts | 1+
Mcommon/lib/citations/schema.ts | 4++--
Mcommon/lib/envVars.ts | 1+
Mcommon/lib/platform.ts | 19+++++++++++++++++--
Mcommon/lib/posts-server.ts | 58+++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcommon/lib/posts.ts | 31++++++++++++++++++++++++++++---
Mcommon/lib/postsVisibility.ts | 29++++++++++++++++++++++++-----
Mcommon/lib/report/convert-server.ts | 9++++++++-
Mcommon/lib/report/convertManifest.ts | 11++++++++---
Acommon/lib/waybackClient.pages.test.ts | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/waybackClient.ts | 190++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Acommon/lib/waybackPages/config.test.ts | 177+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/config.ts | 147+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extract.test.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extract.ts | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/waybackPages/extractors/__fixtures__/capture.ts | 2+-
Acommon/lib/waybackPages/extractors/generic.test.ts | 204+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/generic.ts | 477+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/waybackPages/extractors/tumblr.ts | 7+++----
Acommon/lib/waybackPages/parse.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/store-server.ts | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/toPost.test.ts | 162+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/toPost.ts | 196+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/waybackPages/types.ts | 3+++
Acommon/lib/waybackPages/urls.ts | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/README.md | 2+-
Mcommon/testing/web/fakeWayback.d.mts | 19+++++++++++++++++++
Mcommon/testing/web/fakeWayback.mjs | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Meditor/CHANGELOG.md | 1+
Aeditor/app/api/ops/import-page/route.ts | 34++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/reextract-pages/route.ts | 17+++++++++++++++++
Aeditor/app/channels/[slug]/components/WaybackPagesPanel.tsx | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/page.tsx | 38++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/socialActions.ts | 5+++++
Aeditor/app/channels/[slug]/waybackPagesActions.ts | 38++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/components/ChannelForm.tsx | 35+++++++++++++++++++++++++++++++----
Aeditor/app/channels/components/WaybackTargetsField.tsx | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/components/channelConfigToForm.ts | 10++++++++++
Meditor/app/channels/components/parseChannelForm.test.ts | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/components/parseChannelForm.ts | 59++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/e2e/servers.ts | 8++++++++
Aeditor/e2e/wayback-pages.spec.ts | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/playwright.config.ts | 5+++++
Mmcp/src/server.ts | 2+-
Mplans/FACTS.md | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aplans/release-37/core.md | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 35+++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.test.mjs | 18++++++++++++++++++
64 files changed, 4756 insertions(+), 46 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -19,7 +19,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `postFetcher` | config | Social channels only: which social fetcher drives ingest (e.g. `"bluesky-atproto"`, `"x-gallery-dl"`). Absent = resolve by URL detection. Trimmed. | | `socialHandle` | config | Social channels only: the bare account handle (a leading "@" is stripped). Derived from `url` at creation but stored, so a later URL-format change upstream cannot silently re-point ingest at a different account. | | `postPagePauseSeconds` | config | Social channels that are read page by page (a forum thread) only: the pause between two page loads, in seconds; each pause is jittered to 0.85–1.65× of it. Absent = the fetcher's own (12 s, so 10–20 s); floored at 5, capped at 600. | -| `platform` | config | The source platform: youtube, rumble, odysee, twitch, kick, archiveorg (archive.org items — imported, never listed; see README.md, "archive.org items"), bitchute (BitChute videos and channels; see README.md, "BitChute"), twitter, bluesky or xenforo (a forum thread). An unknown value is dropped. | +| `platform` | config | The source platform: youtube, rumble, odysee, twitch, kick, archiveorg (archive.org items — imported, never listed; see README.md, "archive.org items"), bitchute (BitChute videos and channels; see README.md, "BitChute"), twitter, bluesky, xenforo (a forum thread) or webpage (Wayback Machine captures of pages; see `wayback`). An unknown value is dropped. | | `name` | config | Display name. | | `url` | config | The channel / playlist / account URL syncs enumerate. Absent = the channel is never auto-synced. | | `audioFormat` | config | `"m4a"`, `"mp3"` or `"opus"`: the audio a transcribe-handling download keeps. | @@ -50,6 +50,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `browserLookup` | config | `true`, with `storedUrlDownloads` `fallback` or `only`: when a video's record stores no media URL — `only`, or a `fallback` whose yt-dlp lookup was refused (a 429) — the managed download opens the video's page in a headless browser, reads the record from the page's own API answers and writes `metadata.info.json` (marked `_source: "browser"`), then downloads from the media URL the page named. Odysee only; one page a minute; the channel's `--match-filter title~='…'` and download filters still decide. Absent = off. The video page's **Read from the page** and the channel's **List from the page** ask for it once, whatever this says. | | `recordedDate` | config | For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped. See [`recordedDate`](#recordeddate). | | `mirror` | config | For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped. See [`mirror`](#mirror). | +| `wayback` | config | A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest"}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture's original URL. Each capture imported (`pnpm ops import-page`, the channel page's **Import a capture**) becomes a page record in the channel's posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. | #### `downloadFilter` diff --git a/CITATIONS.md b/CITATIONS.md @@ -74,7 +74,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | Key | Required | Description | |---|---|---| -| `kind` | yes | `"post"`. | +| `kind` | yes | `"post"`: a post record — an X, Bluesky or forum post, or a page record (a Wayback Machine capture imported into a Wayback pages channel, platform `webpage`). | | `channel` | yes | The post's channel slug. A path segment of the moment page. The citing site must name it in `channels` or `citedChannels` (see [SITE.md](SITE.md)), and may carry the post (the post visibility rule). | | `id` | yes | The post's id. A path segment of the moment page. | | `thread` | no | True to show the post with the thread it belongs to. Absent = the post alone. | @@ -91,7 +91,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | Key | Required | Description | |---|---|---| -| `kind` | yes | `"page"`: a web page outside the corpus. | +| `kind` | yes | `"page"`: a web page outside the corpus. A capture of it imported into a Wayback pages channel is a page record, cited as a `post`. | | `url` | yes | The page's address: an http(s) URL. | | `title` | no | The page's title. | | `archiveUrl` | no | An archived copy of the page (an http(s) URL), shown beside the live link. | diff --git a/COMMANDS.md b/COMMANDS.md @@ -56,6 +56,8 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer run` | `<operation> <channel> [ids…] [--lane local\|remote]` | run one catalogued operation over a channel offline, as the editor's job does (sync, downloads and transcription are refused: they run in the editor; it does not see the editor's lanes, so not beside one on the same channel) | | `archilyzer archive-org refresh` | `<slug> [--dry-run]` | bring a channel's archive.org file records up to their provenance: a name-only mirror's title (where the item gives the file none) and upload date from its file name; offline, through the metadata history; prints old → new | | `archilyzer wayback refresh` | `<slug> [--titles <json>] [--dry-run]` | bring a channel's Wayback Machine copies up to the Wayback rules: wayback.json (original URL, capture time), the dir renamed to its canonical id through the snapshot's reconcile (roster moved with it), and with --titles (a file of id → {title, upload\_date}) a raw file's title and date; offline, skips a record a live job holds; prints old → new | +| `archilyzer wayback pages import` | `<slug> <url> [--at YYYYMMDD] [--dry-run]` | import ONE Wayback Machine capture of a page that is not a video into a Wayback pages channel: a capture's replay URL, or the page's URL and --at for the capture nearest that date; the raw body stored under pages/, its records in the channel's posts. In-process, through this process's own paced client — while an editor runs, prefer `pnpm ops import-page` | +| `archilyzer wayback pages reextract` | `<slug> [--dry-run]` | re-derive a Wayback pages channel's records from the raw captures it stores (no request): every capture read by the extractor it goes to now, the records replaced when anything differs; --dry-run counts. Writes the channel's posts — with the editor stopped, or use `pnpm ops reextract-pages` | | `archilyzer feeds backfill-metadata` | `<slug> [--feed <url>] [--dry-run]` | complete a podcast channel's records (title, date, description, duration) from its RSS feed: one fetch of the feed (default: the channel's url), no media; --dry-run counts matched / unmatched / already complete and writes nothing | | `archilyzer media attach` | `<slug> <source> [--items <json\|@file>] [--match <regex>] [--create-records] [--replace] [--dry-run]` | give a channel's held videos their media from a LOCAL archive (a directory, a .zip read in place, a .7z) into the saved-video store, provenance recorded (archive, entry, sha256); the id from the folder's "(&lt;id&gt;)" or the file's yt-dlp suffix; --create-records writes a record for a video not held; --dry-run lists each folder's class and writes nothing; offline, nothing fetched | | `archilyzer media playable` | `<slug> [--ids <a,b>] [--trackers <url,url>] [--root <dir>] [--dry-run]` | remux a channel's saved containers losslessly (-c copy) into browser-playable mp4 (+faststart) or webm, one single-file torrent each (no web seed; --trackers is the announce list, outside the infohash), under playable/ beside the saved-video store; keyed by the source's sha256, so a re-run is a no-op; offline | @@ -155,6 +157,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -&gt; {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. {"youtubeId", "limit"?: 10} looks for mirrors of one YouTube upload instead: items OF it (their identifier, a file name or their original URL names the id; a title or description that mentions it is not enough), each read for its files -&gt; {query, found, items: \[{identifier, title?, file, url, source, size?, seconds?, namedBy}\], skipped: \[{identifier, why}\]}: each mirror's direct video file URL, an original preferred. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'`<br>`pnpm ops archive-search --json '{"youtubeId":"dQw4w9WgXcQ"}'` | | `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -&gt; {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` | | `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/&lt;handle&gt;/status/&lt;id&gt;) or a Bluesky post (bsky.app/profile/&lt;handle&gt;/post/&lt;id&gt;, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` | +| `import-page` | import-page imports ONE Wayback Machine capture of a page that is not a video into a Wayback pages channel (platform "webpage"): {"slug", "url"} — a capture's replay URL (web.archive.org/web/&lt;timestamp&gt;/&lt;page&gt;) — or {"slug", "url": &lt;the page&gt;, "at": "YYYYMMDD\[hhmmss\]"} for the capture nearest that date (one CDX lookup). An import-page job on the archive.org queue, at archive.org's pace: the raw (id\_) body, at most 2 MB, html, plain text or JSON only, redirects followed inside the archive only and the FINAL capture recorded; stored under the channel's pages/, read by the first site extractor that claims it (else the generic one), its page records written to the channel's posts. Refused, before any job: no such channel, not a Wayback pages channel, a URL that names no capture, a video (use import-video), an X capture outside an X channel while social.x.visibility is "private". A capture already stored is not fetched again. "dryRun" answers what it would fetch and starts nothing. The log ends with @@import-page {ok, slug, url, captureTs, originalUrl, records, written, updated, unchanged, extractor, already?, error?}. | `pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}'`<br>`pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait` | +| `reextract-pages` | reextract-pages re-derives a Wayback pages channel's records from the raw captures it stores: {"slug", "dryRun"?}. No request. A reextract-pages job on the archive.org queue (never beside an import into the channel): every stored capture read again by the extractor it goes to now, the records replaced when anything differs. The log ends with @@reextract-pages {captures, stale, records: {added, changed, removed, unchanged, kept}, written}. | `pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait` | | `wayback-lookup` | wayback-lookup answers the Wayback Machine's captures of a page (its CDX API): {"url"} or a record's {"slug", "id"} (its metadata's page, else its availability check's, else the playlist's), "okOnly"?: only the captures that recorded a 200, "limit"?: 100 (at most 500) -&gt; {url, found, captures: \[{timestamp, status, mimetype?, replayUrl}\]}, oldest first. One request through the editor's Wayback client, with archive.org's manners (one at a time, 2 s apart, 429s waited out). Read only. | `pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'` | | `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?, "retryFailed"? -&gt; {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -&gt; {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.&lt;fmt&gt;; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait` | | `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -&gt; {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration reads only their pages and answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped; transcribe-bucket is skipped, and said, while transcription is paused or no worker is enabled), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0 — or partial, naming what a capped search did not reach. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. "verdicts" proposes a verdict for each UNRULED claim of a fact-check ("article"; "claims"? only those; "model"?, "maxUsd"?): the verdict bench's prompt, one claim per call, on a model in settings.generation.verdicts.models only (refused otherwise; none named: the first of them on the verdicts route). No iteration (iteration 0): the proposals go to the article's verdicts.proposed.json, never report.json; a claim the operator ruled, or whose proposal was reviewed, is not asked. Its log ends with @@report-draft {…, verdicts: {proposed, failed, skipped, promptVersion}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait`<br>`pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait` | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -234,6 +234,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts | | `E2E_ODYSEE_PAGE_FIXTURE` | unset (a headless browser) | A JSON file of recorded Odysee page reads keyed by page URL (`"*"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`). | common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts | | `E2E_UMTOOL_ORIGIN_FILE` | unset (UMTOOL_URL) | A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored. | common/lib/umtoolUrl.ts | +| `E2E_WAYBACK_ORIGIN_FILE` | unset (the real Wayback Machine) | A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/waybackClient.ts | | `E2E_BLUESKY_ORIGIN_FILE` | unset (the real Bluesky) | A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored. | common/social/blueskyEndpoints.ts | | `E2E_AUDIO_CHECK_DEBUG_PAUSE_MS` | off | A debugging pause inside the audio check. | common/ytdlp/audioCheckedDownload.ts | | `E2E_FAKE_YTDLP_AUDIO_CHECK_MODE` | — | Fake yt-dlp: which audio-check scenario to act out. | editor/e2e/fixtures/bin/fake-ytdlp.mjs | diff --git a/OPERATING.md b/OPERATING.md @@ -82,6 +82,36 @@ pnpm ops import-video --json '{"slug":"example","url":"https://web.archive `pnpm archilyzer archive-org refresh <slug> --dry-run`, `pnpm archilyzer wayback refresh <slug> --dry-run`, `pnpm archilyzer feeds backfill-metadata <slug> --dry-run` (or `pnpm ops feed-metadata` on the editor). +### Pages from the Wayback Machine + +```sh +pnpm ops create-channel --json '{"fields":{"name":"Old blog","handling":"transcribe","url":"https://web.archive.org/web/*/blog.example/*"}}' +pnpm ops import-page --json '{"slug":"old-blog","url":"https://web.archive.org/web/<timestamp>/https://blog.example/a-post.html","dryRun":true}' +pnpm ops import-page --json '{"slug":"old-blog","url":"https://web.archive.org/web/<timestamp>/https://blog.example/a-post.html"}' --wait +pnpm ops import-page --json '{"slug":"old-blog","url":"https://blog.example/a-post.html","at":"20140301"}' --wait +pnpm ops reextract-pages --json '{"slug":"old-blog","dryRun":true}' --wait +``` + +- A capture of a page that is NOT a video (a blog post, an About page, a deleted document, a group's old site) is + a page record in a **Wayback pages** channel (platform `webpage`): the New channel form makes one of a Wayback + URL of such a page (`web.archive.org/web/*/<target>*` is a prefix, `*.<host>` a domain, one page exact), or + choose "Wayback pages" and edit the targets (`config.wayback`, CHANNEL.md). A capture of a video stays + `import-video`'s. +- `import-page` imports ONE capture: its replay URL, or the page's own URL and `at` (`YYYYMMDD[hhmmss]`) for the + capture nearest that date. The channel page's **Import a capture** is the same, with a date picker. One job per + capture, on archive.org's queue and pace; the raw (`id_`) body is fetched (at most 2 MB; html, plain text or + JSON), redirects followed inside the archive only, and the record names the capture it landed on. A capture + already held is not fetched again. +- The body is kept under `channels/<slug>/pages/<captureTs>-<hash>/` (`raw.html.gz`, `capture.json`); the records + are the channel's posts (search, the MCP, a site build — the index picks them up on its next build). A record's + date is the page's own when it says one, else the capture's; a later capture of the same page is a version of + the first (`page.versionOf`). +- `reextract-pages` (the channel page's **Re-extract**) re-reads every stored body with the extractor it goes to + now — no request — and replaces the records when anything changed. Offline with the editor stopped: + `pnpm archilyzer wayback pages reextract <slug> --dry-run`. +- An x.com / twitter.com capture is private exactly as X posts are (`social.x.visibility`): while X is private, + only a Wayback pages channel whose target is on X takes one, and a public site leaves that channel out. + ## Fetch and capture posts ```sh diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -677,6 +677,42 @@ export const COMMANDS: Command[] = [ }, }, { + path: ["wayback", "pages", "import"], + usage: + "<slug> <url> [--at YYYYMMDD] [--dry-run] import ONE Wayback Machine capture of a page that is not a video into a Wayback pages channel: a capture's replay URL, or the page's URL and --at for the capture nearest that date; the raw body stored under pages/, its records in the channel's posts. In-process, through this process's own paced client — while an editor runs, prefer `pnpm ops import-page`", + flags: { at: "string", "dry-run": "boolean" }, + maxPositionals: 2, + run: async ({ positionals, flags }) => { + const [slug, url] = positionals; + if (!slug || !url) { + console.error("wayback pages import: pass the channel slug, then a capture's URL (or the page's URL and --at)."); + return 2; + } + return (await import("./wayback-pages")).importMain({ + slug, + url, + ...(typeof flags.at === "string" ? { at: flags.at } : {}), + dryRun: flags["dry-run"] === true, + signal: interrupted(), + }); + }, + }, + { + path: ["wayback", "pages", "reextract"], + usage: + "<slug> [--dry-run] re-derive a Wayback pages channel's records from the raw captures it stores (no request): every capture read by the extractor it goes to now, the records replaced when anything differs; --dry-run counts. Writes the channel's posts — with the editor stopped, or use `pnpm ops reextract-pages`", + flags: { "dry-run": "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => { + const [slug] = positionals; + if (!slug) { + console.error("wayback pages reextract: which channel? Pass its slug."); + return 2; + } + return (await import("./wayback-pages")).reextractMain({ slug, dryRun: flags["dry-run"] === true }); + }, + }, + { path: ["feeds", "backfill-metadata"], usage: "<slug> [--feed <url>] [--dry-run] complete a podcast channel's records (title, date, description, duration) from its RSS feed: one fetch of the feed (default: the channel's url), no media; --dry-run counts matched / unmatched / already complete and writes nothing", diff --git a/common/bin/compose-site.waybackPages.test.ts b/common/bin/compose-site.waybackPages.test.ts @@ -0,0 +1,155 @@ +// Integration (release 37 S1): page records imported from the fake Wayback +// flow through the REAL index build and the REAL site compose with no reader +// of their own — the shared posts tree carries them with their `page`, a +// site's posts manifest lists the channel as platform "webpage", and the +// served page holds the record. A Wayback pages channel scoped on X is an X +// channel for `social.x.visibility`: a public site leaves it out while X is +// private, a private site carries it. +// +// Run with: node_modules/.bin/tsx --test common/bin/compose-site.waybackPages.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "wayback-pages-compose-")); +const PINNED: Record<string, string> = { + TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), + SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"), + SITES_DIR: path.join(ROOT, "transcripts", "sites"), + SETTINGS_FILE: path.join(ROOT, "settings.json"), + EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), + EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), + EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), + EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"), + EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"), + CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"), + SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"), + CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"), + ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"), + ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"), +}; +Object.assign(process.env, PINNED); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { buildIndex } = await import("../controller/buildIndex"); +const { importPage } = await import("../controller/importPage"); +const { WaybackClient } = await import("../lib/waybackClient"); +const { pageRecordId } = await import("../lib/waybackPages/types"); +const { draftToPost } = await import("../lib/waybackPages/toPost"); +const { upsertPosts } = await import("../lib/posts-server"); +const { main: composeSite } = await import("./compose-site"); +const fake = await import("../testing/web/fakeWayback.mjs"); + +const paths = getPaths(); +const BLOG = "old-blog-pages"; +const XP = "old-x-pages"; +const writeJson = (file: string, value: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(value, null, 2)); +}; +const readJson = <T>(file: string): T => JSON.parse(readFileSync(file, "utf8")) as T; +const quiet = () => {}; + +const pagesConfig = (name: string, target: string) => ({ + handling: "transcribe", + name, + sourceKind: "social", + platform: "webpage", + socialHandle: target.split("/")[0], + url: `https://web.archive.org/web/*/${target}*`, + wayback: { targets: [{ url: target, match: "prefix" }] }, +}); + +async function compose(siteId: string) { + const log = console.log; + console.log = quiet; + try { + await composeSite({ siteId, paths }); + } finally { + console.log = log; + } + const pub = paths.exportPublicDir; + return { + postsManifest: readJson<{ channels: { slug: string; platform: string; postCount: number }[] }>(path.join(pub, "posts", "manifest.json")), + page: (slug: string) => readJson<Record<string, unknown>[]>(path.join(pub, "posts", slug, "page-0000.json")), + has: (slug: string) => + existsSync(path.join(pub, "posts", slug, "manifest.json")) && + readJson<{ pageCount: number }>(path.join(pub, "posts", slug, "manifest.json")).pageCount > 0, + }; +} + +test("page records: through the index and a site compose as posts; an X-scoped pages channel private by the X rule", async () => { + writeJson(path.join(paths.channelsDir, BLOG, "config.json"), pagesConfig("Old blog", "blog.example/")); + writeJson(path.join(paths.channelsDir, XP, "config.json"), pagesConfig("Old X", "twitter.com/someone")); + const site = (siteId: string, extra: Record<string, unknown> = {}) => + writeJson(path.join(paths.sitesDir, siteId, "site.json"), { + siteId, + siteTitle: siteId, + siteDescription: "fixture", + headerTitle: siteId, + homeTagline: "", + socialLinks: [], + groups: [{ id: "default", name: "All channels", selectedByDefault: true }], + defaultGroupId: "default", + channels: [BLOG, XP].map((slug) => ({ slug, groupId: "default" })), + siteUrl: `https://${siteId}.example.test`, + archives: false, + ...extra, + }); + site("pub"); + site("priv", { audience: "private" }); + writeJson(paths.settingsFile, { social: { x: { visibility: "private" } } }); + + const wb = await fake.startFakeWayback(); + try { + const client = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); + const r = await importPage({ + paths, + slug: BLOG, + url: `https://web.archive.org/web/${fake.PAGE_ARTICLE_TS}/${fake.PAGE_ARTICLE_URL}`, + client, + settings: { social: { x: { visibility: "private" } } }, + }); + assert.equal(r.ok, true, r.error); + } finally { + await wb.close(); + } + // The X-scoped channel's record, as an X extractor (S3) would make it. + await upsertPosts(path.join(paths.channelsDir, XP), [ + draftToPost( + { kind: "tweet", itemId: "tweet-1001", url: "https://twitter.com/someone/status/1001", author: "someone", text: "a captured tweet", links: [] }, + { channelSlug: XP, capture: { originalUrl: "https://twitter.com/someone", captureTs: "20140101000000" }, extractor: { name: "x", version: 1 } }, + ), + ]); + + await buildIndex({ paths, onLog: quiet }); + const id = pageRecordId(fake.PAGE_ARTICLE_TS, fake.PAGE_ARTICLE_URL); + const shared = readJson<Record<string, unknown>[]>(path.join(paths.exportSharedPostsDir, BLOG, "page-0000.json")); + assert.equal(shared.length, 1); + assert.equal(shared[0].id, id); + assert.equal(shared[0].platform, "webpage"); + assert.equal((shared[0].page as { title?: string }).title, "A Post About Bread"); + // The shared tree is corpus-wide: the X-scoped channel is in it. + assert.ok(existsSync(path.join(paths.exportSharedPostsDir, XP, "manifest.json"))); + const sitePosts = (siteId: string) => + readJson<{ channels: { slug: string; platform: string }[] }>(path.join(paths.exportSitesIndexDir, siteId, "posts", "manifest.json")); + assert.deepEqual(sitePosts("pub").channels.map((c) => [c.slug, c.platform]), [[BLOG, "webpage"]]); + assert.deepEqual(sitePosts("priv").channels.map((c) => c.slug).sort(), [BLOG, XP].sort()); + + const pub = await compose("pub"); + assert.deepEqual(pub.postsManifest.channels.map((c) => c.slug), [BLOG]); + assert.equal(pub.has(BLOG), true); + assert.equal(pub.has(XP), false); + const served = pub.page(BLOG)[0]; + assert.equal(served.id, id); + assert.ok(String(served.text).includes("The first loaf came out flat")); + assert.equal((served.page as { waybackUrl?: string }).waybackUrl, `https://web.archive.org/web/${fake.PAGE_ARTICLE_TS}/${fake.PAGE_ARTICLE_URL}`); + + const priv = await compose("priv"); + assert.equal(priv.has(XP), true); + assert.equal(priv.page(XP)[0].id, "tweet-1001"); +}); diff --git a/common/bin/wayback-pages.ts b/common/bin/wayback-pages.ts @@ -0,0 +1,67 @@ +// `archilyzer wayback pages import <slug> <url> [--at YYYYMMDD] [--dry-run]` +// and `archilyzer wayback pages reextract <slug> [--dry-run]` — a Wayback pages +// channel (release 37 S1) from the command line, in-process. +// +// import ONE capture (controller/importPage.ts), through this process's +// own polite Wayback client (one stream, the 2 s gap). While an +// editor runs, prefer `pnpm ops import-page` — its imports share +// the editor's one archive.org queue; this command does not. +// reextract every record re-derived from the stored captures +// (controller/reextractPages.ts), no request. It writes the +// channel's posts: run it with the editor stopped, or use +// `pnpm ops reextract-pages` / the channel page's Re-extract, +// which queue it beside the channel's imports. + +import { isValidChannelSlug } from "../controller/channels"; +import { importPage } from "../controller/importPage"; +import { reextractPages } from "../controller/reextractPages"; +import { getPaths, type Paths } from "../lib/paths"; + +export async function importMain(opts: { + slug: string; + url: string; + at?: string; + dryRun: boolean; + paths?: Paths; + signal?: AbortSignal; +}): Promise<number> { + if (!isValidChannelSlug(opts.slug)) { + console.error(`wayback pages import: "${opts.slug}" is not a channel slug`); + return 2; + } + const r = await importPage({ + paths: opts.paths ?? getPaths(), + slug: opts.slug, + url: opts.url, + ...(opts.at ? { at: opts.at } : {}), + dryRun: opts.dryRun, + onLog: (line) => console.log(line), + ...(opts.signal ? { signal: opts.signal } : {}), + }); + if (!r.ok) { + console.error(`wayback pages import: ${r.error}`); + return 1; + } + if (r.dryRun) console.log(`dry run: would fetch ${r.wouldFetch}`); + else if (r.already) console.log(`already stored: ${r.captureTs} of ${r.originalUrl}`); + else console.log(`imported ${r.captureTs} of ${r.originalUrl}: ${r.records?.length ?? 0} record(s), ${r.written} new, ${r.updated} updated.`); + return 0; +} + +export async function reextractMain(opts: { slug: string; dryRun: boolean; paths?: Paths }): Promise<number> { + if (!isValidChannelSlug(opts.slug)) { + console.error(`wayback pages reextract: "${opts.slug}" is not a channel slug`); + return 2; + } + const r = await reextractPages({ + paths: opts.paths ?? getPaths(), + slug: opts.slug, + dryRun: opts.dryRun, + onLog: (line) => console.log(line), + }); + if (!r.ok) { + console.error(`wayback pages reextract: ${r.error}`); + return 1; + } + return 0; +} diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -14,6 +14,7 @@ import { import type { Paths } from "../lib/paths"; import type { Post } from "../lib/posts"; import { isSocialChannel } from "../lib/channelConfig"; +import { isWaybackPagesChannel } from "../lib/waybackPages/config"; import { alwaysCookies, resolveCookiePolicy, @@ -101,6 +102,11 @@ export type FetchPostsOptions = { drain?: AbortSignal; }; +// A Wayback pages channel (release 37) has no account to fetch: its captures +// are imported one by one (import-page), as chosen. +export const WAYBACK_PAGES_NOT_FETCHED = + "A Wayback pages channel is not fetched: import its captures (import-page, the channel page's Import a capture)."; + // The refusal for both walks at once, shared with the server action so the // button, the ops route and this controller say the same thing. export const OLDER_FROM_REFUSAL = "A start date (\"from\") applies only to an older-posts fetch."; @@ -189,6 +195,9 @@ export async function fetchPosts( error: `Channel ${slug} is not a social source (sourceKind=${config.sourceKind ?? "video"})`, }; } + if (isWaybackPagesChannel(config)) { + return { ok: false, written: 0, skipped: 0, complete: false, error: WAYBACK_PAGES_NOT_FETCHED }; + } const accountUrl = config.url ?? ""; const fetcher = resolveSocialFetcher(config.postFetcher, accountUrl); diff --git a/common/controller/importPage.test.ts b/common/controller/importPage.test.ts @@ -0,0 +1,234 @@ +// Release 37 S1: `import-page` end to end on the fake Wayback — refusals +// before any request, a capture stored under pages/ and its records in the +// channel's posts, the nearest capture for a date, a capture never fetched +// twice, versions of one page — and `reextract-pages` over what is stored. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/importPage.test.ts + +import test, { after } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdtempSync, rmSync } from "node:fs"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { gunzipSync } from "node:zlib"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { + startFakeWayback, + PAGE_ARTICLE_LATER_TS, + PAGE_ARTICLE_TS, + PAGE_ARTICLE_URL, + PAGE_IMAGE_TS, + PAGE_IMAGE_URL, + PAGE_TOOLBAR_TS, + PAGE_TOOLBAR_URL, +} from "../testing/web/fakeWayback.mjs"; +import type { Paths } from "../lib/paths"; +import { WaybackClient } from "../lib/waybackClient"; +import { importPage, planImportPage, queueImportPage, WAYBACK_PAGES_QUEUE } from "./importPage"; +import { reextractPages } from "./reextractPages"; +import { readAllPosts, upsertPosts } from "../lib/posts-server"; +import { pageRecordId } from "../lib/waybackPages/types"; +import { listStoredCaptures, pageCaptureDir, readStoredCapture, updateStoredCapture } from "../lib/waybackPages/store-server"; +import { draftToPost } from "../lib/waybackPages/toPost"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "import-page-")); +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 PUBLIC = { social: { x: { visibility: "public" } } }; +const PRIVATE = { social: { x: { visibility: "private" } } }; + +async function channel(slug: string, config: Record<string, unknown>) { + const dir = path.join(paths.channelsDir, slug); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config })); + return dir; +} +const pagesChannel = (slug: string, target: string, match = "prefix") => + channel(slug, { + sourceKind: "social", + platform: "webpage", + socialHandle: "blog.example", + url: `https://web.archive.org/web/*/${target}*`, + wayback: { targets: [{ url: target, match }] }, + }); +const replay = (ts: string, url: string) => `https://web.archive.org/web/${ts}/${url}`; + +test("refused before any request: no channel, not a pages channel, no capture named, a video, an X capture outside an X channel", async () => { + await pagesChannel("old-blog", "blog.example/"); + await channel("a-video-channel", { url: "https://www.youtube.com/@x/videos" }); + await channel("an-x-channel", { sourceKind: "social", platform: "twitter", url: "https://x.com/a", socialHandle: "a" }); + const ask = (slug: string, url: string, at?: string, settings = PUBLIC) => planImportPage(paths, { slug, url, ...(at ? { at } : {}), settings }); + const err = async (p: ReturnType<typeof ask>) => { + const r = await p; + return r.ok ? "" : r.error; + }; + assert.match(await err(ask("nope", replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL))), /No such channel: nope/); + assert.match(await err(ask("a-video-channel", replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL))), /not a Wayback pages channel/); + assert.match(await err(ask("an-x-channel", replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL))), /not a Wayback pages channel/); + assert.match(await err(ask("old-blog", "https://web.archive.org/web/*/blog.example/*")), /a Wayback Machine listing, not one capture/); + assert.match(await err(ask("old-blog", PAGE_ARTICLE_URL)), /not a Wayback Machine capture/); + assert.match( + await err(ask("old-blog", replay("20140101000000", "https://www.youtube.com/watch?v=abc"))), + /is a video \(YouTube\), not a page: use import-video/, + ); + // X captures: private X keeps them out of a channel not scoped on X. + assert.match(await err(ask("old-blog", replay("2014", "https://twitter.com/someone"), undefined, PRIVATE)), /on X, whose posts are private here/); + assert.equal((await ask("old-blog", replay("2014", "https://twitter.com/someone"), undefined, PUBLIC)).ok, true); + await pagesChannel("old-x", "twitter.com/someone"); + assert.equal((await ask("old-x", replay("2014", "https://twitter.com/someone"), undefined, PRIVATE)).ok, true); + // The job door refuses the same way, and starts nothing. + const q = await queueImportPage({ paths, slug: "a-video-channel", url: replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL), settings: PUBLIC }); + assert.equal(q.ok, false); + assert.equal(WAYBACK_PAGES_QUEUE, "platform:archive.org"); +}); + +test("a capture by its replay URL: stored raw under pages/, its record in the posts; again = nothing fetched", async () => { + const wb = await startFakeWayback(); + try { + const client = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); + const root = await pagesChannel("blog-a", "blog.example/"); + const dry = await importPage({ paths, slug: "blog-a", url: replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL), dryRun: true, client, settings: PUBLIC }); + assert.equal(dry.ok, true); + assert.equal(dry.wouldFetch, `https://web.archive.org/web/${PAGE_ARTICLE_TS}id_/${PAGE_ARTICLE_URL}`); + assert.equal(wb.requests.length, 0); + + const logs: string[] = []; + const r = await importPage({ + paths, + slug: "blog-a", + url: replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL), + client, + settings: PUBLIC, + onLog: (l) => logs.push(l), + now: () => new Date("2026-10-20T00:00:00.000Z"), + }); + assert.equal(r.ok, true, r.error); + const id = pageRecordId(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL); + assert.deepEqual(r.records, [id]); + assert.equal(r.written, 1); + assert.equal(r.extractor, "generic v1"); + const dir = pageCaptureDir(root, PAGE_ARTICLE_TS, PAGE_ARTICLE_URL); + assert.equal(path.basename(dir), id); + const stored = await readStoredCapture(dir); + assert.equal(stored?.originalUrl, PAGE_ARTICLE_URL); + assert.equal(stored?.mimetype, "text/html"); + assert.equal(stored?.extractor, "generic"); + assert.equal(stored?.fetchedAt, "2026-10-20T00:00:00.000Z"); + assert.deepEqual(stored?.records, [id]); + const raw = gunzipSync(await readFile(path.join(dir, "raw.html.gz"))).toString("utf8"); + assert.ok(raw.includes("A Post About Bread")); + assert.equal(stored?.bytes, Buffer.byteLength(raw)); + + const [post] = await readAllPosts(root); + assert.equal(post.id, id); + assert.equal(post.platform, "webpage"); + assert.equal(post.createdAt, "2014-03-04T18:30:00.000Z"); + assert.equal(post.page?.title, "A Post About Bread"); + assert.equal(post.page?.waybackUrl, replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL)); + assert.ok(post.text.includes("The first loaf came out flat")); + assert.ok(post.links.includes("https://blog.example/2014/02/starter.html")); + assert.equal(post.media?.[0]?.url, `https://web.archive.org/web/${PAGE_ARTICLE_TS}im_/https://blog.example/images/loaf.jpg`); + // The month shard and the posts archive, as a fetch writes them. + assert.ok(existsSync(path.join(root, "posts", "2014-03.jsonl"))); + assert.match(await readFile(path.join(root, "posts-archive"), "utf8"), new RegExp(`^webpage ${id}$`, "m")); + + const n = wb.requests.length; + const again = await importPage({ paths, slug: "blog-a", url: replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL), client, settings: PUBLIC }); + assert.equal(again.already, true); + assert.equal(wb.requests.length, n, "nothing fetched for a stored capture"); + } finally { + await wb.close(); + } +}); + +test("the nearest capture to a date; a later capture is a version of the first; a toolbar body reads clean", async () => { + const wb = await startFakeWayback(); + try { + const client = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); + const root = await pagesChannel("blog-b", "blog.example/"); + const later = await importPage({ paths, slug: "blog-b", url: PAGE_ARTICLE_URL, at: "20150601", client, settings: PUBLIC }); + assert.equal(later.ok, true, later.error); + assert.equal(later.captureTs, PAGE_ARTICLE_LATER_TS); + assert.match(wb.requests[0].path, /^\/cdx\/search\/cdx\?.*closest=20150601/); + // A replay URL whose timestamp the archive holds nothing at: the + // redirect's capture is the one recorded. + const first = await importPage({ paths, slug: "blog-b", url: replay("20140301000000", PAGE_ARTICLE_URL), client, settings: PUBLIC }); + assert.equal(first.ok, true, first.error); + assert.equal(first.captureTs, PAGE_ARTICLE_TS); + const firstId = pageRecordId(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL); + const laterId = pageRecordId(PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_URL); + const stored = await readStoredCapture(pageCaptureDir(root, PAGE_ARTICLE_TS, PAGE_ARTICLE_URL)); + assert.equal(stored?.requestedTs, "20140301000000"); + const byId = new Map((await readAllPosts(root)).map((p) => [p.id, p])); + assert.equal(byId.get(firstId)?.page?.versionOf, undefined); + assert.equal(byId.get(laterId)?.page?.versionOf, firstId, "the earlier-imported later capture now names the first"); + assert.ok(byId.get(laterId)?.text.includes("the fourth loaf rose")); + // Both versions group as one thread. + assert.equal(byId.get(firstId)?.threadId, byId.get(laterId)?.threadId); + + const tb = await importPage({ paths, slug: "blog-b", url: replay(PAGE_TOOLBAR_TS, PAGE_TOOLBAR_URL), client, settings: PUBLIC }); + assert.equal(tb.ok, true, tb.error); + const about = (await readAllPosts(root)).find((p) => p.page?.originalUrl === PAGE_TOOLBAR_URL)!; + assert.ok(!about.text.includes("Wayback Machine"), about.text); + assert.ok(about.text.includes("We are a small group")); + assert.deepEqual(about.links, ["https://home.example/contact", "https://home.example/links"]); + + const img = await importPage({ paths, slug: "blog-b", url: replay(PAGE_IMAGE_TS, PAGE_IMAGE_URL), client, settings: PUBLIC }); + assert.equal(img.ok, false); + assert.match(img.error ?? "", /image\/jpeg, not a page/); + } finally { + await wb.close(); + } +}); + +test("reextract-pages: nothing stale changes nothing; a stale capture is redone; a record its capture no longer makes goes, one with no capture stays", async () => { + const wb = await startFakeWayback(); + try { + const client = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); + const root = await pagesChannel("blog-c", "blog.example/"); + assert.equal((await importPage({ paths, slug: "blog-c", url: replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL), client, settings: PUBLIC })).ok, true); + assert.equal((await importPage({ paths, slug: "blog-c", url: replay(PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_URL), client, settings: PUBLIC })).ok, true); + const requests = wb.requests.length; + + const clean = await reextractPages({ paths, slug: "blog-c" }); + assert.equal(clean.ok, true, clean.error); + assert.equal(clean.captures, 2); + assert.equal(clean.stale, 0); + assert.deepEqual(clean.records, { added: 0, changed: 0, removed: 0, unchanged: 2, kept: 0 }); + assert.equal(clean.written, false); + + // A capture made by an older extractor, a stray record of a stored + // capture, and a record whose capture is not stored at all. + const [entry] = await listStoredCaptures(root); + await updateStoredCapture(entry.dir, { ...entry.capture, extractorVersion: 0 }); + const stray = draftToPost( + { kind: "tumblr-post", itemId: "tumblr-9", text: "an item an old extractor split out", links: [] }, + { channelSlug: "blog-c", capture: { originalUrl: PAGE_ARTICLE_URL, captureTs: PAGE_ARTICLE_TS }, extractor: { name: "old", version: 1 } }, + ); + const orphan = draftToPost( + { kind: "generic", text: "imported before its body was kept", links: [] }, + { channelSlug: "blog-c", capture: { originalUrl: "https://blog.example/gone", captureTs: "20120101000000" }, extractor: { name: "generic", version: 1 } }, + ); + await upsertPosts(root, [stray, orphan]); + + const dry = await reextractPages({ paths, slug: "blog-c", dryRun: true }); + assert.equal(dry.stale, 1); + assert.deepEqual(dry.records, { added: 0, changed: 0, removed: 1, unchanged: 2, kept: 1 }); + assert.equal((await readAllPosts(root)).length, 4, "a dry run writes nothing"); + + const done = await reextractPages({ paths, slug: "blog-c" }); + assert.equal(done.written, true); + const ids = (await readAllPosts(root)).map((p) => p.id).sort(); + assert.deepEqual(ids, [orphan.id, pageRecordId(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL), pageRecordId(PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_URL)].sort()); + assert.equal((await readStoredCapture(entry.dir))?.extractorVersion, 1); + assert.equal(wb.requests.length, requests, "a re-extract asks the archive nothing"); + const again = await reextractPages({ paths, slug: "blog-c" }); + assert.equal(again.stale, 0); + assert.equal(again.written, false); + + const refused = await reextractPages({ paths, slug: "a-video-channel" }); + assert.match(refused.error ?? "", /not a Wayback pages channel/); + } finally { + await wb.close(); + } +}); diff --git a/common/controller/importPage.ts b/common/controller/importPage.ts @@ -0,0 +1,373 @@ +// IMPORT ONE PAGE CAPTURE (release 37 S1, `import-page`): one Wayback Machine +// capture of a page that is not a video, into a Wayback pages channel +// (platform "webpage"), as page records in its posts. +// +// {slug, url: <replay URL>} web.archive.org/web/<ts>[mod]/<original> +// {slug, url: <original>, at} the capture nearest `at` (YYYYMMDD[hhmmss]), +// found through the CDX API +// +// The job: (the nearest capture, through CDX) → the raw `id_` body +// (WaybackClient.getCapture: 2 MB cap, html/plain/json only, redirects inside +// the archive followed, the FINAL capture recorded) → stored under the +// channel's `pages/` → extracted (lib/waybackPages/extract.ts) → page records +// upserted into the posts store (the split-record merge) — exactly where a +// post fetch writes, and, as for a fetch, the index picks them up on its next +// build. One capture per job: nothing here crawls. +// +// Refused before any request, with the sentence a caller shows: no such +// channel; a channel that is not a Wayback pages channel; a URL that names no +// capture (a calendar page, a bare URL with no date); a capture of a VIDEO +// ("use import-video"); an x.com/twitter.com capture into a channel that does +// not target X while `social.x.visibility` is "private" (X captures are +// private exactly as X posts are). After the fetch: a body that is not a page +// (its mimetype), too large, or a redirect off the archive. +// +// POLITE: every request goes through the process's Wayback client (one +// stream, the 2 s gap, 429/503 waited out), and the job runs on the +// `platform:archive.org` queue — one import at a time. A capture already +// stored is not fetched again. + +import path from "node:path"; +import { getPaths, type Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { readChannelConfig } from "./channels"; +import { readAllPosts, upsertPosts } from "../lib/posts-server"; +import { getSettings } from "../lib/settings"; +import { queueKeyForUrl } from "../lib/platform"; +import { waybackPageUrl, waybackRawUrl } from "../lib/wayback"; +import { ArchiveOrgRequestError } from "../lib/archiveOrgClient"; +import { + waybackClient as defaultWaybackClient, + WaybackCaptureRefusal, + type WaybackClient, +} from "../lib/waybackClient"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { isWaybackPagesChannel } from "../lib/waybackPages/config"; +import { isXHostUrl, parsePageCaptureAsk, videoPageOf, type PageCaptureAsk } from "../lib/waybackPages/urls"; +import { decodeCaptureBody, extractPage } from "../lib/waybackPages/extract"; +import { assignPageVersions, draftToPost } from "../lib/waybackPages/toPost"; +import { + hasStoredCapture, + pageCaptureDir, + readStoredCapture, + writeStoredCapture, + type StoredCapture, +} from "../lib/waybackPages/store-server"; +import { isXPostsChannel, xPostsVisibility } from "../lib/postsVisibility"; +import type { Post } from "../lib/posts"; + +export const IMPORT_PAGE_JOB_KIND = "import-page"; +export const IMPORT_PAGE_RESULT_MARKER = "@@import-page "; + +// Every Wayback request is archive.org's; the page imports run one at a time +// on the queue a web.archive.org URL routes to. +export const WAYBACK_PAGES_QUEUE = queueKeyForUrl("https://web.archive.org/"); + +type VisibilitySettings = { social?: { x?: { visibility?: unknown } } }; + +export type ImportPagePlan = { + config: ChannelConfig; + ask: PageCaptureAsk; +}; + +// The refusal an X capture meets in this channel, or null. +export function xCaptureRefusal( + config: ChannelConfig, + slug: string, + originalUrl: string, + settings: VisibilitySettings, +): string | null { + if (!isXHostUrl(originalUrl)) return null; + if (xPostsVisibility(settings) !== "private") return null; + if (isXPostsChannel(config)) return null; + return ( + `${originalUrl} is on X, whose posts are private here (social.x.visibility "private"); ` + + `import an X capture into a Wayback pages channel whose target is on x.com or twitter.com, which a public site leaves out — not into ${slug}` + ); +} + +// Everything checked before a job: the plan, or the refusal. +export async function planImportPage( + paths: Paths, + opts: { slug: string; url: string; at?: string; settings?: VisibilitySettings }, +): Promise<{ ok: true; plan: ImportPagePlan } | { ok: false; error: string }> { + const config = await readChannelConfig(paths, opts.slug); + if (!config) return { ok: false, error: `No such channel: ${opts.slug}` }; + if (!isWaybackPagesChannel(config)) { + return { + ok: false, + error: `${opts.slug} is not a Wayback pages channel; import-page imports into a channel on platform "webpage"`, + }; + } + const parsed = parsePageCaptureAsk(opts.url, opts.at); + if (!parsed.ok) return parsed; + const video = videoPageOf(parsed.ask.originalUrl); + if (video) { + return { + ok: false, + error: `${parsed.ask.originalUrl} is a video (${video}), not a page: use import-video for a capture of a video`, + }; + } + const x = xCaptureRefusal(config, opts.slug, parsed.ask.originalUrl, opts.settings ?? getSettings()); + if (x) return { ok: false, error: x }; + return { ok: true, plan: { config, ask: parsed.ask } }; +} + +export type ImportPageResult = { + ok: boolean; + slug: string; + url: string; + // The capture imported (after the nearest lookup and any redirect). + captureTs?: string; + originalUrl?: string; + waybackUrl?: string; + // The capture was already stored; nothing was fetched. + already?: boolean; + dryRun?: boolean; + // What a dry run would fetch. + wouldFetch?: string; + records?: string[]; + written: number; + updated: number; + unchanged: number; + extractor?: string; + error?: string; +}; + +// THE CAPTURE'S RECORDS, from its stored body: what an import and a re-extract +// both make. Pure but for the extractor registry. +export function recordsOfCapture( + slug: string, + capture: StoredCapture, + body: Buffer, +): { posts: Post[]; extractor: { name: string; version: number }; fallback?: StoredCapture["extractorFallback"] } { + const html = decodeCaptureBody(body, capture.contentType ?? capture.mimetype); + const facts = { + originalUrl: capture.originalUrl, + captureTs: capture.captureTs, + mimetype: capture.mimetype, + ...(capture.digest ? { digest: capture.digest } : {}), + }; + const res = extractPage({ + html, + capture: { + ...facts, + waybackUrl: waybackPageUrl(facts), + rawUrl: waybackRawUrl(facts), + }, + }); + const posts = res.drafts.map((d) => + draftToPost(d, { + channelSlug: slug, + capture: facts, + extractor: res.extractor, + ...(res.fallback ? { fallback: res.fallback } : {}), + }), + ); + return { posts, extractor: res.extractor, ...(res.fallback ? { fallback: res.fallback } : {}) }; +} + +export async function importPage(opts: { + paths: Paths; + slug: string; + url: string; + at?: string; + dryRun?: boolean; + settings?: VisibilitySettings; + client?: WaybackClient; + onLog?: (line: string) => void; + signal?: AbortSignal; + now?: () => Date; +}): Promise<ImportPageResult> { + const log = (line: string) => opts.onLog?.(line); + const base: ImportPageResult = { ok: false, slug: opts.slug, url: opts.url, written: 0, updated: 0, unchanged: 0 }; + const settings = opts.settings ?? getSettings(); + const planned = await planImportPage(opts.paths, { slug: opts.slug, url: opts.url, at: opts.at, settings }); + if (!planned.ok) return { ...base, error: planned.error }; + const { config, ask } = planned.plan; + const client = opts.client ?? defaultWaybackClient; + const channelRoot = path.join(opts.paths.channelsDir, opts.slug); + + if (opts.dryRun) { + const wouldFetch = + ask.kind === "capture" + ? waybackRawUrl(ask) + : `the capture of ${ask.originalUrl} nearest ${ask.at} (one CDX lookup), then its raw body`; + const already = ask.kind === "capture" && /^\d{14}$/.test(ask.captureTs) && (await hasStoredCapture(channelRoot, ask.captureTs, ask.originalUrl)); + return { + ...base, + ok: true, + dryRun: true, + ...(already ? { already: true } : {}), + wouldFetch: already ? "nothing (the capture is already stored)" : wouldFetch, + ...(ask.kind === "capture" ? { captureTs: ask.captureTs } : {}), + originalUrl: ask.originalUrl, + }; + } + + try { + let ts: string; + // The URL as the archive captured it: CDX's `original` for a nearest + // lookup (it may differ from the one typed: http/https, a trailing slash). + let original = ask.originalUrl; + if (ask.kind === "nearest") { + log(`Looking up the capture of ${ask.originalUrl} nearest ${ask.at} (CDX).`); + const near = await client.closestCapture(ask.originalUrl, ask.at, { signal: opts.signal }); + if (!near) return { ...base, error: `the Wayback Machine holds no capture of ${ask.originalUrl} that recorded a page (HTTP 200)` }; + ts = near.timestamp; + original = near.original; + log(`Nearest capture: ${near.timestamp} (${near.original}).`); + } else { + ts = ask.captureTs; + } + if (/^\d{14}$/.test(ts) && (await hasStoredCapture(channelRoot, ts, original))) { + log(`The capture ${ts} of ${original} is already in ${opts.slug}; nothing fetched.`); + return { + ...base, + ok: true, + already: true, + captureTs: ts, + originalUrl: original, + waybackUrl: waybackPageUrl({ captureTs: ts, originalUrl: original }), + }; + } + log(`Fetching ${waybackRawUrl({ captureTs: ts, originalUrl: original })}`); + const cap = await client.getCapture(ts, original, { raw: true, signal: opts.signal }); + if (cap.finalTs !== ts || cap.originalUrl !== ask.originalUrl) { + log(`The archive answered with the capture ${cap.finalTs} of ${cap.originalUrl}.`); + const video = videoPageOf(cap.originalUrl); + if (video) return { ...base, error: `the capture redirects to a video (${video}, ${cap.originalUrl}): use import-video for it` }; + const x = xCaptureRefusal(config, opts.slug, cap.originalUrl, settings); + if (x) return { ...base, error: x }; + } + const fetchedAt = (opts.now?.() ?? new Date()).toISOString(); + const stored: StoredCapture = { + originalUrl: cap.originalUrl, + captureTs: cap.finalTs, + mimetype: cap.mimetype, + contentType: cap.contentType, + bytes: cap.bytes, + sha256: cap.sha256, + fetchedAt, + extractor: "", + extractorVersion: 0, + ...(cap.finalTs !== ts ? { requestedTs: ts } : {}), + ...(cap.originalUrl !== ask.originalUrl ? { requestedUrl: ask.originalUrl } : {}), + }; + const made = recordsOfCapture(opts.slug, stored, cap.body); + stored.extractor = made.extractor.name; + stored.extractorVersion = made.extractor.version; + if (made.fallback) { + stored.extractorFallback = made.fallback; + log(`The ${made.fallback.from} extractor failed (${made.fallback.error}); the generic extractor read the page.`); + } + stored.records = made.posts.map((p) => p.id); + const dir = await writeStoredCapture(channelRoot, stored, cap.body); + log(`Stored ${cap.bytes} bytes (${cap.mimetype}) in ${path.relative(opts.paths.channelsDir, dir)}.`); + + // Versions of one page: the earliest held capture of the original is the + // one the others are versions of. + const held = (await readAllPosts(channelRoot)).filter((p) => p.page); + const byId = new Map(held.map((p) => [p.id, p])); + for (const p of made.posts) byId.set(p.id, { ...(byId.get(p.id) ?? {}), ...p } as Post); + const versioned = new Map(assignPageVersions([...byId.values()]).map((p) => [p.id, p])); + const own = new Set(made.posts.map((p) => p.id)); + const batch = made.posts.map((p) => { + const v = versioned.get(p.id); + return v ? { ...p, page: v.page } : p; + }); + // Earlier-held versions that now point at a new first capture. + for (const v of versioned.values()) if (!own.has(v.id)) batch.push(v); + + const res = await upsertPosts(channelRoot, batch); + log( + `${made.posts.length} record(s) from the capture (${made.extractor.name} v${made.extractor.version}): ` + + `${res.written} new, ${res.updated} updated, ${res.unchanged} unchanged. The index picks them up on its next build.`, + ); + return { + ...base, + ok: true, + captureTs: cap.finalTs, + originalUrl: cap.originalUrl, + waybackUrl: waybackPageUrl({ captureTs: cap.finalTs, originalUrl: cap.originalUrl }), + records: made.posts.map((p) => p.id), + written: res.written, + updated: res.updated, + unchanged: res.unchanged, + extractor: `${made.extractor.name} v${made.extractor.version}`, + }; + } catch (e) { + if (e instanceof WaybackCaptureRefusal) return { ...base, error: e.message }; + if (e instanceof ArchiveOrgRequestError) return { ...base, error: e.message }; + throw e; + } +} + +// THE JOB: an `import-page` job on the archive.org queue, refused (no job) +// with the plan's sentence. What the channel page's field, the ops action and +// lane B's batch all start. The job's log ends with `@@import-page {…}`. +export async function queueImportPage(opts: { + paths: Paths; + slug: string; + url: string; + at?: string; + requestedBy?: string; + settings?: VisibilitySettings; + client?: WaybackClient; + onDone?: (result: ImportPageResult) => void; +}): Promise<StreamActionResult> { + const settings = opts.settings ?? getSettings(); + const planned = await planImportPage(opts.paths, { slug: opts.slug, url: opts.url, at: opts.at, settings }); + if (!planned.ok) return { ok: false, error: planned.error }; + return runManagedFunction({ + kind: IMPORT_PAGE_JOB_KIND, + queueKey: WAYBACK_PAGES_QUEUE, + paths: opts.paths, + channelSlug: opts.slug, + fn: async (onLog, signal) => { + onLog(`Import page: ${opts.url}${opts.at ? ` nearest ${opts.at}` : ""} into ${opts.slug}${opts.requestedBy ? ` for ${opts.requestedBy}` : ""}`); + const result = await importPage({ + paths: opts.paths, + slug: opts.slug, + url: opts.url, + ...(opts.at ? { at: opts.at } : {}), + settings, + ...(opts.client ? { client: opts.client } : {}), + onLog, + signal, + }); + onLog(`${IMPORT_PAGE_RESULT_MARKER}${JSON.stringify(result)}`); + opts.onDone?.(result); + if (!result.ok) throw new Error(result.error ?? "Page import failed"); + }, + }); +} + +export class ImportPageRefusal extends Error { + constructor(message: string) { + super(message); + this.name = "ImportPageRefusal"; + } +} + +// LANE B's DOOR (release 37 S2, "Import selected"): one `import-page` job for +// one capture. Throws ImportPageRefusal with the sentence when it is refused. +export async function startImportPageJob(opts: { + slug: string; + url: string; + at?: string; + requestedBy?: string; + paths?: Paths; +}): Promise<{ jobId: string }> { + const res = await queueImportPage({ ...opts, paths: opts.paths ?? getPaths() }); + if (!res.ok) throw new ImportPageRefusal(res.error); + void res.stream.cancel(); + return { jobId: res.jobId }; +} + +// The capture's stored facts, for a caller holding a record (lane D's moment +// page, a re-extract). +export async function storedCaptureOf(paths: Paths, slug: string, post: Pick<Post, "page">): Promise<StoredCapture | null> { + if (!post.page) return null; + return readStoredCapture(pageCaptureDir(path.join(paths.channelsDir, slug), post.page.captureTs, post.page.originalUrl)); +} diff --git a/common/controller/reextractPages.ts b/common/controller/reextractPages.ts @@ -0,0 +1,192 @@ +// RE-EXTRACT A WAYBACK PAGES CHANNEL (release 37 S1, `reextract-pages`, +// `archilyzer wayback pages reextract`): every page record re-derived from +// the raw bodies the channel stores under `pages/` — no request, no network. +// What an improved (or new) extractor is for: the captures whose extractor or +// version is no longer the one a capture would go to now are STALE, and a +// re-extract makes the channel's records what an import today would make. +// +// The records are recomputed from EVERY stored capture (oldest first, merged +// as an import merges them), the versions re-assigned, and the channel's page +// records replaced whole (posts-server replaceChannelPosts) when anything +// differs — so a record may move month (a page's own date read at last), and +// an id the new extraction no longer makes is removed. A record whose capture +// is NOT stored (nothing to re-derive it from) is kept as it is. +// +// One writer: in the editor it runs as a job on the archive.org queue, the +// queue every import into the channel runs on. The CLI runs it in-process, +// with the editor stopped (or no import running on the channel). + +import path from "node:path"; +import { getPaths, type Paths } from "../lib/paths"; +import type { Post } from "../lib/posts"; +import { readAllPosts, replaceChannelPosts } from "../lib/posts-server"; +import { readChannelConfig } from "./channels"; +import { isWaybackPagesChannel } from "../lib/waybackPages/config"; +import { chooseExtractor, decodeCaptureBody } from "../lib/waybackPages/extract"; +import { asStored, assignPageVersions, mergePageRecord, stableRecordJson } from "../lib/waybackPages/toPost"; +import { + listStoredCaptures, + pageCaptureDirName, + readStoredCaptureBody, + updateStoredCapture, +} from "../lib/waybackPages/store-server"; +import { waybackPageUrl, waybackRawUrl } from "../lib/wayback"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { recordsOfCapture, WAYBACK_PAGES_QUEUE } from "./importPage"; + +export const REEXTRACT_PAGES_JOB_KIND = "reextract-pages"; +export const REEXTRACT_PAGES_RESULT_MARKER = "@@reextract-pages "; + +export type ReextractPagesResult = { + ok: boolean; + slug: string; + dryRun: boolean; + captures: number; + // Captures whose stored extractor/version is not what they would go to now. + stale: number; + // Captures whose body could not be read. + unreadable: number; + records: { added: number; changed: number; removed: number; unchanged: number; kept: number }; + written: boolean; + error?: string; +}; + +function samePost(a: Post, b: Post): boolean { + return stableRecordJson(asStored(a)) === stableRecordJson(asStored(b)); +} + +export async function reextractPages(opts: { + paths: Paths; + slug: string; + dryRun?: boolean; + onLog?: (line: string) => void; +}): Promise<ReextractPagesResult> { + const log = (line: string) => opts.onLog?.(line); + const dryRun = opts.dryRun === true; + const out: ReextractPagesResult = { + ok: false, + slug: opts.slug, + dryRun, + captures: 0, + stale: 0, + unreadable: 0, + records: { added: 0, changed: 0, removed: 0, unchanged: 0, kept: 0 }, + written: false, + }; + const config = await readChannelConfig(opts.paths, opts.slug); + if (!config) return { ...out, error: `No such channel: ${opts.slug}` }; + if (!isWaybackPagesChannel(config)) { + return { ...out, error: `${opts.slug} is not a Wayback pages channel (platform "webpage")` }; + } + const channelRoot = path.join(opts.paths.channelsDir, opts.slug); + const captures = await listStoredCaptures(channelRoot); + out.captures = captures.length; + + const desired = new Map<string, Post>(); + // Captures whose records are re-derived (stored and readable). + const derivable = new Set<string>(); + const captureUpdates: { dir: string; next: (typeof captures)[number]["capture"] }[] = []; + for (const { dir, name, capture } of captures) { + let body: Buffer; + try { + body = await readStoredCaptureBody(dir); + } catch (e) { + out.unreadable++; + log(`${name}: the stored body is unreadable (${(e as Error).message}); its records are kept as they are.`); + continue; + } + derivable.add(name); + const html = decodeCaptureBody(body, capture.contentType ?? capture.mimetype); + const facts = { originalUrl: capture.originalUrl, captureTs: capture.captureTs }; + const now = chooseExtractor({ + html, + capture: { ...facts, mimetype: capture.mimetype, waybackUrl: waybackPageUrl(facts), rawUrl: waybackRawUrl(facts) }, + }); + const isStale = + now.name !== capture.extractor || now.version !== capture.extractorVersion || !!capture.extractorFallback; + if (isStale) out.stale++; + const made = recordsOfCapture(opts.slug, capture, body); + for (const p of made.posts) { + const prev = desired.get(p.id); + desired.set(p.id, prev ? (mergePageRecord(prev, p) ?? prev) : p); + } + const next = { + ...capture, + extractor: made.extractor.name, + extractorVersion: made.extractor.version, + records: made.posts.map((p) => p.id), + }; + if (made.fallback) next.extractorFallback = made.fallback; + else delete next.extractorFallback; + if (JSON.stringify(next) !== JSON.stringify(capture)) captureUpdates.push({ dir, next }); + } + for (const v of assignPageVersions([...desired.values()])) desired.set(v.id, v); + + // What the channel holds now. A record is re-derivable when its capture is + // stored and readable; anything else stays exactly as it is. + const existing = await readAllPosts(channelRoot); + const final = new Map<string, Post>(desired); + for (const p of existing) { + const capName = p.page ? pageCaptureDirName(p.page.captureTs, p.page.originalUrl) : null; + const rederivable = capName !== null && derivable.has(capName); + const want = desired.get(p.id); + if (want) { + if (samePost(p, want)) out.records.unchanged++; + else out.records.changed++; + } else if (rederivable) { + out.records.removed++; + } else { + final.set(p.id, p); + out.records.kept++; + } + } + const existingIds = new Set(existing.map((p) => p.id)); + for (const id of desired.keys()) if (!existingIds.has(id)) out.records.added++; + + const r = out.records; + const dirty = r.added + r.changed + r.removed > 0; + log( + `${opts.slug}: ${out.captures} stored capture(s), ${out.stale} stale; records ${r.added} new, ${r.changed} changed, ` + + `${r.removed} removed, ${r.unchanged} unchanged${r.kept ? `, ${r.kept} kept (no stored capture)` : ""}.`, + ); + if (dryRun) { + log("Dry run: nothing written."); + return { ...out, ok: true }; + } + if (dirty) { + await replaceChannelPosts(channelRoot, [...final.values()]); + out.written = true; + log("The channel's page records are rewritten; the index picks them up on its next build."); + } + for (const u of captureUpdates) await updateStoredCapture(u.dir, u.next); + if (!dirty && captureUpdates.length === 0) log("Nothing to change."); + return { ...out, ok: true }; +} + +// THE JOB (the channel page's Re-extract button, `pnpm ops reextract-pages`): +// on the archive.org queue, so it never runs beside an import into the +// channel. +export async function queueReextractPages(opts: { + paths?: Paths; + slug: string; + dryRun?: boolean; +}): Promise<StreamActionResult> { + const paths = opts.paths ?? getPaths(); + const config = await readChannelConfig(paths, opts.slug); + if (!config) return { ok: false, error: `No such channel: ${opts.slug}` }; + if (!isWaybackPagesChannel(config)) { + return { ok: false, error: `${opts.slug} is not a Wayback pages channel (platform "webpage")` }; + } + return runManagedFunction({ + kind: REEXTRACT_PAGES_JOB_KIND, + queueKey: WAYBACK_PAGES_QUEUE, + paths, + channelSlug: opts.slug, + fn: async (onLog) => { + onLog(`Re-extract the stored captures of ${opts.slug}${opts.dryRun ? " (dry run)" : ""}`); + const result = await reextractPages({ paths, slug: opts.slug, dryRun: opts.dryRun, onLog }); + onLog(`${REEXTRACT_PAGES_RESULT_MARKER}${JSON.stringify(result)}`); + if (!result.ok) throw new Error(result.error ?? "Re-extract failed"); + }, + }); +} diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -592,6 +592,32 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: false, queueKeyStrategy: "platform", }, + // ONE Wayback Machine capture of a page that is not a video into a Wayback + // pages channel (release 37 S1, controller/importPage.ts): the raw body + // stored under `pages/`, its page records upserted into the posts. On the + // archive.org queue (`platform:archive.org`), so imports go one at a time at + // archive.org's pace; text only. Not drainable (one capture); not + // replayable (a capture already stored is not fetched again anyway). + "import-page": { + kind: "import-page", + label: "Import a page capture", + drainable: false, + replayable: false, + queueKeyStrategy: "platform", + needsText: true, + }, + // A Wayback pages channel's records re-derived from its stored captures + // (release 37 S1, controller/reextractPages.ts): offline, no request. On + // the same queue as import-page so it never runs beside an import into the + // channel. Not drainable (one pass); not replayable. + "reextract-pages": { + kind: "reextract-pages", + label: "Re-extract page captures", + drainable: false, + replayable: false, + queueKeyStrategy: "platform", + needsText: true, + }, // A screenshot and the attached media of specific archived posts (and the X // Article a post links to), into the channel's `posts-media/` // (controller/capturePosts.ts). On the PLATFORM queue, like fetch-posts: @@ -1261,6 +1287,9 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([ "fetch-posts", "import-forum-pages", "import-post", + // A page capture's records (release 37), and their re-derivation. + "import-page", + "reextract-pages", "capture-posts", "check-post-availability", "sync", diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts @@ -74,6 +74,19 @@ export type ArchiveOrgClientOpts = { idleTimeoutMs?: number; }; +// What getBounded answers: a body within the cap, a redirect, or "too large". +export type BoundedResponse = { + status: number; + headers: Headers; + // A 3xx's Location, absolute; null for anything else. + location: string | null; + // The body, when it was read whole within the cap. + body: Buffer | null; + // Bytes read (or declared, when the Content-Length alone was over the cap). + bytes: number; + tooLarge: boolean; +}; + export type DownloadFileProgress = { bytes: number; total: number | null }; export type DownloadFileOpts = { @@ -155,8 +168,16 @@ export class ArchiveOrgClient { return Math.round(exp * jitter); } - // One GET, with the gap before it and the retry policy around it. - private async getOnce(url: string, accept: string, signal?: AbortSignal, extraHeaders: Record<string, string> = {}): Promise<Response> { + // One GET, with the gap before it and the retry policy around it. With + // `manualRedirect`, a 3xx is answered as it is (the caller decides whether + // to follow it) instead of followed. + private async getOnce( + url: string, + accept: string, + signal?: AbortSignal, + extraHeaders: Record<string, string> = {}, + o: { manualRedirect?: boolean } = {}, + ): Promise<Response> { let lastError = ""; for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) { const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now(); @@ -167,7 +188,7 @@ export class ArchiveOrgClient { const timeout = AbortSignal.timeout(this.opts.timeoutMs); res = await this.deps.fetch(url, { signal: signal ? AbortSignal.any([signal, timeout]) : timeout, - redirect: "follow", + redirect: o.manualRedirect ? "manual" : "follow", headers: { accept, "user-agent": ARCHIVE_ORG_USER_AGENT, ...extraHeaders }, }); } catch (err) { @@ -177,6 +198,7 @@ export class ArchiveOrgClient { this.lastDoneAt = this.deps.now(); } if (res && res.ok) return res; + if (res && o.manualRedirect && res.status >= 300 && res.status < 400) return res; if (res && !RETRYABLE.has(res.status)) { throw new ArchiveOrgRequestError( `archive.org answered HTTP ${res.status} for ${url}`, @@ -226,6 +248,62 @@ export class ArchiveOrgClient { }); } + // A BOUNDED body (release 37, the Wayback page import): one GET through the + // same chain, gap and back-off, its body read up to `maxBytes` and no + // further — a longer one (by its Content-Length, or as it streams) is + // dropped unread past the cap and answered `tooLarge`. With + // `manualRedirect`, a 3xx comes back as `location` (absolute, resolved + // against `url`) with no body, for the caller to follow or refuse. The gap + // runs from the END of the body. Throws ArchiveOrgRequestError as getText + // does (a 404 with its status; `rateLimited` when archive.org kept refusing). + getBounded( + url: string, + accept: string, + o: { maxBytes: number; signal?: AbortSignal; manualRedirect?: boolean }, + ): Promise<BoundedResponse> { + return this.serial(async () => { + const res = await this.getOnce(url, accept, o.signal, {}, { manualRedirect: o.manualRedirect === true }); + try { + if (res.status >= 300 && res.status < 400) { + await res.body?.cancel().catch(() => {}); + const loc = res.headers.get("location"); + let location: string | null = null; + if (loc) { + try { + location = new URL(loc, url).toString(); + } catch { + location = null; + } + } + return { status: res.status, headers: res.headers, location, body: null, bytes: 0, tooLarge: false }; + } + const declared = Number(res.headers.get("content-length")); + if (Number.isFinite(declared) && declared > o.maxBytes) { + await res.body?.cancel().catch(() => {}); + return { status: res.status, headers: res.headers, location: null, body: null, bytes: declared, tooLarge: true }; + } + const reader = res.body?.getReader(); + const chunks: Buffer[] = []; + let bytes = 0; + if (reader) { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + bytes += value.byteLength; + if (bytes > o.maxBytes) { + await reader.cancel().catch(() => {}); + return { status: res.status, headers: res.headers, location: null, body: null, bytes, tooLarge: true }; + } + chunks.push(Buffer.from(value)); + } + } + return { status: res.status, headers: res.headers, location: null, body: Buffer.concat(chunks), bytes, tooLarge: false }; + } finally { + this.lastDoneAt = this.deps.now(); + } + }); + } + getJson(url: string, signal?: AbortSignal): Promise<unknown> { return this.serial(async () => { const res = await this.getOnce(url, "application/json", signal); diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -1,4 +1,5 @@ import { PLATFORM_VALUES, type Platform } from "./platform"; +import { coerceWaybackPagesConfig, type WaybackPagesConfig } from "./waybackPages/config"; import { isDownloadFormatPreset, isSourceVideoQuality, @@ -157,6 +158,8 @@ export type ChannelConfig = { browserLookup?: boolean; recordedDate?: RecordedDateRule; mirror?: MirrorConfig; + // Release 37: a Wayback pages channel's scope (lib/waybackPages/config.ts). + wayback?: WaybackPagesConfig; }; // In the order parseChannelConfig emits (and CHANNEL.md lists) them. @@ -171,7 +174,7 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { 'Social channels only: the bare account handle (a leading "@" is stripped). Derived from `url` at creation but stored, so a later URL-format change upstream cannot silently re-point ingest at a different account.', postPagePauseSeconds: "Social channels that are read page by page (a forum thread) only: the pause between two page loads, in seconds; each pause is jittered to 0.85–1.65× of it. Absent = the fetcher's own (12 s, so 10–20 s); floored at 5, capped at 600.", - platform: "The source platform: youtube, rumble, odysee, twitch, kick, archiveorg (archive.org items — imported, never listed; see README.md, \"archive.org items\"), bitchute (BitChute videos and channels; see README.md, \"BitChute\"), twitter, bluesky or xenforo (a forum thread). An unknown value is dropped.", + platform: "The source platform: youtube, rumble, odysee, twitch, kick, archiveorg (archive.org items — imported, never listed; see README.md, \"archive.org items\"), bitchute (BitChute videos and channels; see README.md, \"BitChute\"), twitter, bluesky, xenforo (a forum thread) or webpage (Wayback Machine captures of pages; see `wayback`). An unknown value is dropped.", name: "Display name.", url: "The channel / playlist / account URL syncs enumerate. Absent = the channel is never auto-synced.", audioFormat: '`"m4a"`, `"mp3"` or `"opus"`: the audio a transcribe-handling download keeps.', @@ -222,7 +225,9 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { recordedDate: "For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped.", mirror: - "For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped." + "For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped.", + wayback: + 'A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest"}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture\'s original URL. Each capture imported (`pnpm ops import-page`, the channel page\'s **Import a capture**) becomes a page record in the channel\'s posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped.', }; // Every key a config.json may carry, in emission order. The unknown-key oracle: @@ -430,6 +435,7 @@ export const CHANNEL_CONFIG_COERCIONS: { browserLookup: (v) => (v === true ? true : undefined), recordedDate: coerceRecordedDateRule, mirror: coerceMirrorConfig, + wayback: coerceWaybackPagesConfig, }; // A channel's config.json as a ChannelConfig, or null when it is not a channel diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts @@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it", assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]); - assert.equal(CHANNEL_CONFIG_KEYS.length, 36); + assert.equal(CHANNEL_CONFIG_KEYS.length, 37); // release 37: `wayback` assert.equal(sameKeys, true); assert.equal(fits, true); for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k); diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts @@ -79,6 +79,7 @@ export const channelConfigObjectSchema = z.object({ browserLookup: field("browserLookup"), recordedDate: field("recordedDate"), mirror: field("mirror"), + wayback: field("wayback"), }); // Drop every own key whose value is `undefined` (the OMIT rule, above). diff --git a/common/lib/citations/schema.ts b/common/lib/citations/schema.ts @@ -185,7 +185,7 @@ export const CITATION_PAD_FIELD_DOCS: FieldDocs<CitationPad> = { }; export const POST_CITATION_FIELD_DOCS: FieldDocs<Own<PostCitation>> = { - kind: '`"post"`.', + kind: '`"post"`: a post record — an X, Bluesky or forum post, or a page record (a Wayback Machine capture imported into a Wayback pages channel, platform `webpage`).', channel: "The post's channel slug. A path segment of the moment page. The citing site must name it in `channels` or `citedChannels` (see [SITE.md](SITE.md)), and may carry the post (the post visibility rule).", id: "The post's id. A path segment of the moment page.", @@ -200,7 +200,7 @@ export const SOURCE_CITATION_FIELD_DOCS: FieldDocs<Own<SourceCitation>> = { }; export const PAGE_CITATION_FIELD_DOCS: FieldDocs<Own<PageCitation>> = { - kind: '`"page"`: a web page outside the corpus.', + kind: '`"page"`: a web page outside the corpus. A capture of it imported into a Wayback pages channel is a page record, cited as a `post`.', url: "The page's address: an http(s) URL.", title: "The page's title.", archiveUrl: "An archived copy of the page (an http(s) URL), shown beside the live link.", diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -231,6 +231,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." }, { name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." }, { name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." }, + { name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." }, { name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." }, { name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." }, { name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." }, diff --git a/common/lib/platform.ts b/common/lib/platform.ts @@ -15,7 +15,12 @@ export type Platform = | "bitchute" | "twitter" | "bluesky" - | "xenforo"; + | "xenforo" + // Wayback Machine captures of pages that are not videos (release 37, + // lib/waybackPages/): a posts channel whose records are page records. + // Never detected from a URL — a web.archive.org URL is a capture of + // something else, which import-video or import-page decides. + | "webpage"; export const PLATFORM_VALUES: ReadonlyArray<Platform> = [ "youtube", @@ -28,6 +33,7 @@ export const PLATFORM_VALUES: ReadonlyArray<Platform> = [ "twitter", "bluesky", "xenforo", + "webpage", ]; // The subset that carries social posts rather than videos. A channel on one of @@ -37,10 +43,16 @@ export const SOCIAL_PLATFORM_VALUES: ReadonlyArray<Platform> = [ "twitter", "bluesky", "xenforo", + "webpage", ]; export function isSocialPlatform(platform: Platform | null | undefined): boolean { - return platform === "twitter" || platform === "bluesky" || platform === "xenforo"; + return ( + platform === "twitter" || + platform === "bluesky" || + platform === "xenforo" || + platform === "webpage" + ); } // Host → platform. Lives in `detectPlatform.mjs` (plain JS so umtool's `.mjs` @@ -77,6 +89,9 @@ export function defaultWebpageUrl(platform: Platform, id: string): string { // carry; every archived forum post has its own `url`. A thread URL passed as // the id is returned as it is. if (platform === "xenforo") return /^https?:\/\//.test(id) ? id : ""; + // A page record's URL is its capture's original, which every record + // carries; an id (a timestamp and a hash) names none. + if (platform === "webpage") return /^https?:\/\//.test(id) ? id : ""; return `https://www.youtube.com/watch?v=${id}`; } diff --git a/common/lib/posts-server.ts b/common/lib/posts-server.ts @@ -13,8 +13,9 @@ import { writeJsonAtomic } from "./jsonFile-server"; import path from "node:path"; -import { readdir, mkdir, readFile } from "node:fs/promises"; +import { readdir, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { appendFile } from "node:fs/promises"; +import { mergePageRecord } from "./waybackPages/toPost"; import { readArchive } from "./archive"; import { comparePostsNewestFirst, @@ -172,11 +173,13 @@ export async function upsertPosts( channelRoot: string, posts: ReadonlyArray<Post>, ): Promise<UpsertPostsResult> { - // One record per id from the batch: the newest of them. + // One record per id from the batch: the newest of them (two page records + // of one item merge — lib/waybackPages/toPost.ts, mergePageRecord). const batch = new Map<string, Post>(); for (const p of posts) { const prev = batch.get(p.id); - if (!prev || supersedesPost(prev, p)) batch.set(p.id, p); + if (prev?.page && p.page) batch.set(p.id, mergePageRecord(prev, p) ?? prev); + else if (!prev || supersedesPost(prev, p)) batch.set(p.id, p); } const seen = await readSeenPostIds(channelRoot); const fresh = [...batch.values()].filter((p) => !seen.has(p.id)); @@ -191,7 +194,11 @@ export async function upsertPosts( const byShard = new Map<string, Post[]>(); for (const p of known) { const old = stored.get(p.id); - if (old && !supersedesPost(old, p)) { + // A PAGE RECORD seen again (the same item in a later capture, or the + // same capture imported again): the split-record merge decides — the + // later capture's facts, the first capture kept in page.firstSeenTs. + const pageMerged = old?.page && p.page ? mergePageRecord(old, p) : undefined; + if (pageMerged === null || (pageMerged === undefined && old && !supersedesPost(old, p))) { unchanged++; continue; } @@ -199,7 +206,7 @@ export async function upsertPosts( // change with an edit. const shard = monthShardFromCreatedAt(old?.createdAt ?? p.createdAt); const bucket = byShard.get(shard); - const rec = old ? { ...p, createdAt: old.createdAt, uploadDate: old.uploadDate } : p; + const rec = pageMerged ?? (old ? { ...p, createdAt: old.createdAt, uploadDate: old.uploadDate } : p); if (bucket) bucket.push(rec); else byShard.set(shard, [rec]); updated++; @@ -220,6 +227,47 @@ export async function upsertPosts( }; } +// REPLACE a channel's posts WHOLE (release 37: a Wayback pages channel's +// re-extract, which re-derives every page record from the stored captures — +// and may move a record to another month when a better extractor reads the +// page's own date). Every month shard is rewritten atomically (tmp + rename), +// shards no longer needed are removed, then the posts archive is rewritten to +// exactly these ids. A crash part-way leaves whole shards, never a torn one, +// and a second run puts the rest right. For a channel whose writer is the +// caller alone (the re-extract runs on the same queue as every import into +// the channel); never for a fetched account, whose JSONL is append-only. +export async function replaceChannelPosts( + channelRoot: string, + posts: ReadonlyArray<Post>, +): Promise<{ shards: string[]; written: number }> { + const dir = channelPostsDir(channelRoot); + await mkdir(dir, { recursive: true }); + const byId = new Map<string, Post>(); + for (const p of posts) byId.set(p.id, p); + const byShard = new Map<string, Post[]>(); + for (const p of byId.values()) { + const shard = monthShardFromCreatedAt(p.createdAt); + const bucket = byShard.get(shard); + if (bucket) bucket.push(p); + else byShard.set(shard, [p]); + } + const tmpSuffix = `.tmp-${process.pid}-${Date.now()}`; + for (const [shard, list] of byShard) { + list.sort((a, b) => -comparePostsNewestFirst(a, b)); + const file = shardPath(channelRoot, shard); + await writeFile(file + tmpSuffix, list.map((p) => JSON.stringify(p)).join("\n") + "\n", "utf8"); + await rename(file + tmpSuffix, file); + } + for (const shard of await listPostShards(channelRoot)) { + if (!byShard.has(shard)) await rm(shardPath(channelRoot, shard), { force: true }); + } + const archive = channelPostsArchivePath(channelRoot); + const lines = [...byId.values()].map((p) => `${p.platform} ${p.id}\n`).join(""); + await writeFile(archive + tmpSuffix, lines, "utf8"); + await rename(archive + tmpSuffix, archive); + return { shards: [...byShard.keys()].sort(), written: byId.size }; +} + // List the channel's month shards, oldest first. export async function listPostShards( channelRoot: string, diff --git a/common/lib/posts.ts b/common/lib/posts.ts @@ -9,20 +9,26 @@ // availability.ts). The server-side store lives in posts-server.ts. import { pageFileName } from "./manifest"; +import type { PagePostInfo } from "./waybackPages/types"; +import { parsePagePostInfo } from "./waybackPages/parse"; // "xenforo" is a forum THREAD read as a posts source: the channel is one // thread, each forum post a Post. It is named for the forum software, not a // host — which forum a thread is on is its URL (and `Post.forum.host`). -export type PostPlatform = "twitter" | "bluesky" | "xenforo"; +// "webpage" (release 37) is a Wayback Machine capture of a page that is not a +// video: one captured state of one page, or one item a capture holds +// (`Post.page`; lib/waybackPages/). +export type PostPlatform = "twitter" | "bluesky" | "xenforo" | "webpage"; export const POST_PLATFORM_VALUES: ReadonlyArray<PostPlatform> = [ "twitter", "bluesky", "xenforo", + "webpage", ]; export function isPostPlatform(v: unknown): v is PostPlatform { - return v === "twitter" || v === "bluesky" || v === "xenforo"; + return v === "twitter" || v === "bluesky" || v === "xenforo" || v === "webpage"; } // The platform's name as a reader sees it. @@ -30,6 +36,7 @@ export function postPlatformLabel(platform: PostPlatform | string | undefined): if (platform === "twitter") return "X"; if (platform === "bluesky") return "Bluesky"; if (platform === "xenforo") return "Forum"; + if (platform === "webpage") return "Web page"; return "Post"; } @@ -126,6 +133,9 @@ export type Post = { media?: PostMedia[]; // Forum-specific facts (platform "xenforo"). forum?: ForumPostInfo; + // The capture a page record came from (platform "webpage"): its original + // URL, capture time, replay and raw URLs, kind and extractor. + page?: PagePostInfo; engagement?: PostEngagement; // Merged in at index time from the channel's availability sidecar (the same // shape videos use: the stored record is the source of truth, the flag on @@ -282,6 +292,9 @@ export function postPermalink( if (platform === "xenforo") { return `${(base ?? "").replace(/\/+$/, "")}/posts/${id}/`; } + // A page record's permalink is the page it is a capture of (`base`, its + // `page.originalUrl`); an id alone names none. + if (platform === "webpage") return base ?? ""; return `https://x.com/${author || "i"}/status/${id}`; } @@ -319,7 +332,11 @@ export function parsePost(raw: unknown): Post | null { r.platform, author, r.id, - r.platform === "xenforo" ? forumBaseOf(r.forum) : undefined, + r.platform === "xenforo" + ? forumBaseOf(r.forum) + : r.platform === "webpage" + ? pageOriginalOf(r.page) + : undefined, ), platform: r.platform, isReply: r.isReply === true, @@ -352,9 +369,17 @@ export function parsePost(raw: unknown): Post | null { if (media) post.media = media; const forum = parseForumInfo(r.forum); if (forum) post.forum = forum; + // A malformed `page` is dropped, never the post. + const page = parsePagePostInfo(r.page); + if (page) post.page = page; return post; } +function pageOriginalOf(raw: unknown): string | undefined { + const url = (raw as { originalUrl?: unknown } | null)?.originalUrl; + return typeof url === "string" && url ? url : undefined; +} + function forumBaseOf(raw: unknown): string | undefined { const host = (raw as { host?: unknown } | null)?.host; return typeof host === "string" && host ? `https://${host}` : undefined; diff --git a/common/lib/postsVisibility.ts b/common/lib/postsVisibility.ts @@ -31,12 +31,31 @@ import { isSocialChannel, type ChannelConfig } from "./channelConfig"; import { isPrivateSite, type Site } from "./siteSchema"; import type { XPostsVisibility } from "../social/xCookieSource"; +import { isWaybackPagesChannel } from "./waybackPages/config"; +import { isXTargetUrl } from "./waybackPages/urls"; -// An X channel: the posts of a social channel whose platform is X. +// What the rule reads of a config: its kind and platform, and for a Wayback +// pages channel its scope. +type VisibilityConfig = Pick<ChannelConfig, "sourceKind" | "platform"> & + Partial<Pick<ChannelConfig, "url" | "wayback">>; + +// An X channel: the posts of a social channel whose platform is X — and +// (release 37) a Wayback pages channel whose scope is on X (a target on +// x.com, twitter.com or mobile.twitter.com, or such a URL as its own): X's +// captures are X posts, private by the same setting. import-page keeps X +// captures out of every other Wayback pages channel while X is private +// (controller/importPage.ts, xCaptureRefusal). export function isXPostsChannel( - config: Pick<ChannelConfig, "sourceKind" | "platform"> | null | undefined, + config: VisibilityConfig | null | undefined, ): boolean { - return isSocialChannel(config) && config?.platform === "twitter"; + if (!isSocialChannel(config)) return false; + if (config?.platform === "twitter") return true; + if (!isWaybackPagesChannel(config)) return false; + if (config?.wayback?.targets.some((t) => isXTargetUrl(t.url))) return true; + const url = config?.url ?? ""; + if (!url) return false; + const inner = /^https?:\/\/(?:web|wayback)\.archive\.org\/web\/[^/]*\/(.+)$/i.exec(url)?.[1]; + return isXTargetUrl(inner ?? url); } // `social.x.visibility`, resolved: absent (or anything unknown) is "public". @@ -51,7 +70,7 @@ export function xPostsVisibility(settings: { // knows, and is left to whatever already decides its fate. export function postsVisibleTo( site: Pick<Site, "audience">, - config: Pick<ChannelConfig, "sourceKind" | "platform"> | null | undefined, + config: VisibilityConfig | null | undefined, settings: { social?: { x?: { visibility?: unknown } } }, ): boolean { if (!isXPostsChannel(config)) return true; @@ -66,7 +85,7 @@ export function publishedMemberSlugs( site: Pick<Site, "audience" | "channels">, configOf: ( slug: string, - ) => Pick<ChannelConfig, "sourceKind" | "platform"> | null | undefined, + ) => VisibilityConfig | null | undefined, settings: { social?: { x?: { visibility?: unknown } } }, ): string[] { return site.channels diff --git a/common/lib/report/convert-server.ts b/common/lib/report/convert-server.ts @@ -115,7 +115,14 @@ export function diskPostOf(channelsDir: string): PostOf { const post = (await p).get(id); if (!post) return null; const rec: PostRecord = { - platform: post.platform === "bluesky" ? "bluesky" : post.platform === "xenforo" ? "forum" : "x", + platform: + post.platform === "bluesky" + ? "bluesky" + : post.platform === "xenforo" + ? "forum" + : post.platform === "webpage" + ? "webpage" + : "x", url: post.url, createdAt: post.createdAt, author: post.author, diff --git a/common/lib/report/convertManifest.ts b/common/lib/report/convertManifest.ts @@ -362,9 +362,10 @@ export async function manifestToReport(manifest: unknown, opts: ManifestConvertO // What a post record says that a post citation does not (the CLI reads it off // the channel's archive). export type PostRecord = { - // "forum": a forum-thread post (platform "xenforo"), which a video manifest - // does not carry yet — it is left out with a warning, never relabelled. - platform: "x" | "bluesky" | "forum"; + // "forum": a forum-thread post (platform "xenforo"), and "webpage" a page + // record (a Wayback capture, release 37), which a video manifest does not + // carry yet — each is left out with a warning, never relabelled. + platform: "x" | "bluesky" | "forum" | "webpage"; url: string; createdAt?: string; author?: string; @@ -505,6 +506,10 @@ export async function reportToManifest(raw: unknown, opts: ManifestOptions = {}) warnings.push(`${cid}: post ${c.channel}/${c.id} is a forum post, which a video manifest does not carry — left out of posts`); return; } + if (rec?.platform === "webpage") { + warnings.push(`${cid}: post ${c.channel}/${c.id} is a web page capture, which a video manifest does not carry — left out of posts`); + return; + } const platform = rec?.platform ?? (/^\d+$/.test(c.id) ? "x" : null); const url = rec?.url ?? (platform === "x" ? `https://x.com/i/status/${c.id}` : null); const date = c.date ?? rec?.createdAt; diff --git a/common/lib/waybackClient.pages.test.ts b/common/lib/waybackClient.pages.test.ts @@ -0,0 +1,134 @@ +// Release 37 S1: WaybackClient.getCapture and closestCapture on the fake +// Wayback (common/testing/web/fakeWayback.mjs) — the raw `id_` body, the 2 MB +// cap, the mimetype refusal, redirects followed inside the archive only (the +// FINAL capture recorded), and the polite client's gap between requests. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackClient.pages.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdtemp, rm, 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_BIG_TS, + PAGE_BIG_URL, + PAGE_IMAGE_TS, + PAGE_IMAGE_URL, + PAGE_JUMP_TS, + PAGE_JUMP_URL, + PAGE_PLAIN_TS, + PAGE_PLAIN_URL, +} from "../testing/web/fakeWayback.mjs"; +import { WaybackCaptureRefusal, WaybackClient, waybackCdxUrl, waybackTestOrigin, WAYBACK_PAGE_MAX_BYTES } from "./waybackClient"; + +const refused = (code: string) => (e: unknown) => e instanceof WaybackCaptureRefusal && e.code === code; + +test("getCapture: the raw id_ body of a page, its mimetype, size and sha256", async () => { + const wb = await startFakeWayback(); + try { + const c = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); + const cap = await c.getCapture(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL, { raw: true }); + assert.equal(cap.mimetype, "text/html"); + assert.match(cap.contentType, /charset=utf-8/); + assert.equal(cap.finalTs, PAGE_ARTICLE_TS); + assert.equal(cap.originalUrl, PAGE_ARTICLE_URL); + assert.ok(cap.body.toString("utf8").includes("A Post About Bread")); + assert.equal(cap.bytes, cap.body.byteLength); + assert.equal(cap.sha256, createHash("sha256").update(cap.body).digest("hex")); + assert.deepEqual(wb.requests.map((r) => r.path), [`/web/${PAGE_ARTICLE_TS}id_/${PAGE_ARTICLE_URL}`]); + const plain = await c.getCapture(PAGE_PLAIN_TS, PAGE_PLAIN_URL); + assert.equal(plain.mimetype, "text/plain"); + } finally { + await wb.close(); + } +}); + +test("getCapture: over the cap is refused unread past it; an image is refused by its mimetype", async () => { + const wb = await startFakeWayback(); + try { + const c = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); + assert.equal(WAYBACK_PAGE_MAX_BYTES, 2 * 1024 * 1024); + await assert.rejects(c.getCapture(PAGE_BIG_TS, PAGE_BIG_URL), refused("too-large")); + // A smaller cap of the caller's own. + await assert.rejects(c.getCapture(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL, { maxBytes: 100 }), refused("too-large")); + await assert.rejects(c.getCapture(PAGE_IMAGE_TS, PAGE_IMAGE_URL), (e: unknown) => + refused("mimetype")(e) && (e as WaybackCaptureRefusal).mimetype === "image/jpeg" && /image\/jpeg, not a page/.test((e as Error).message), + ); + await assert.rejects(c.getCapture("20200101000000", "https://never.example/"), refused("not-archived")); + } finally { + await wb.close(); + } +}); + +test("getCapture: a redirect to another capture is followed (the final timestamp is the capture's); one off the archive is refused", async () => { + const wb = await startFakeWayback(); + try { + const c = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); + const near = await c.getCapture("20140301000000", PAGE_ARTICLE_URL); + assert.equal(near.finalTs, PAGE_ARTICLE_TS); + assert.deepEqual(wb.requests.map((r) => r.path), [ + `/web/20140301000000id_/${PAGE_ARTICLE_URL}`, + `/web/${PAGE_ARTICLE_TS}id_/${PAGE_ARTICLE_URL}`, + ]); + await assert.rejects(c.getCapture(PAGE_JUMP_TS, PAGE_JUMP_URL), (e: unknown) => + refused("offsite-redirect")(e) && /elsewhere\.example/.test((e as Error).message), + ); + } finally { + await wb.close(); + } +}); + +test("closestCapture: the nearest 200 capture to a date, through one CDX request; none for a page never captured", async () => { + const wb = await startFakeWayback(); + try { + const c = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); + assert.equal((await c.closestCapture(PAGE_ARTICLE_URL, "20150601"))?.timestamp, PAGE_ARTICLE_LATER_TS); + assert.equal((await c.closestCapture(PAGE_ARTICLE_URL, "2014"))?.timestamp, PAGE_ARTICLE_TS); + assert.equal(await c.closestCapture("https://never.example/", "2014"), null); + assert.equal(wb.requests.length, 3); + assert.match(wb.requests[0].path, /closest=20150601/); + assert.match(wb.requests[0].path, /filter=statuscode%3A200/); + assert.equal( + waybackCdxUrl("https://a.example/", { closest: "2014", limit: 5 }), + "https://web.archive.org/cdx/search/cdx?url=https%3A%2F%2Fa.example%2F&output=json&limit=5&closest=2014&sort=closest", + ); + } finally { + await wb.close(); + } +}); + +test("polite: every request of a capture (its redirects too) waits out the client's gap", async () => { + const wb = await startFakeWayback(); + try { + const gap = 150; + const c = new WaybackClient({ fetch: wb.fetch }, { minGapMs: gap }); + await c.closestCapture(PAGE_ARTICLE_URL, "2014"); + await c.getCapture("20140301000000", PAGE_ARTICLE_URL); + const at = wb.requests.map((r) => r.at); + assert.equal(at.length, 3); + for (let i = 1; i < at.length; i++) assert.ok(at[i] - at[i - 1] >= gap - 5, `request ${i} came ${at[i] - at[i - 1]} ms after the last`); + } finally { + await wb.close(); + } +}); + +test("the e2e origin file: a loopback origin is used, anything else ignored", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "wb-origin-")); + try { + const file = path.join(dir, "origin"); + assert.equal(waybackTestOrigin({}), null); + assert.equal(waybackTestOrigin({ E2E_WAYBACK_ORIGIN_FILE: file }), null); + await writeFile(file, "http://127.0.0.1:4567/\n"); + assert.equal(waybackTestOrigin({ E2E_WAYBACK_ORIGIN_FILE: file }), "http://127.0.0.1:4567"); + await writeFile(file, "https://web.archive.org"); + assert.equal(waybackTestOrigin({ E2E_WAYBACK_ORIGIN_FILE: file }), null); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts @@ -12,12 +12,16 @@ // the page as captured, which is also what yt-dlp's Wayback extractor reads // a YouTube watch page's video from. +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; import { ArchiveOrgClient, ArchiveOrgRequestError, type ArchiveOrgClientDeps, type ArchiveOrgClientOpts, } from "./archiveOrgClient"; +import { isWaybackHost, parseWaybackUrl, waybackRawUrl } from "./wayback"; +import { bareMimetype, isPageMimetype, PAGE_MIMETYPES } from "./waybackPages/urls"; export const WAYBACK_ORIGIN = "https://web.archive.org"; @@ -37,12 +41,21 @@ export function waybackReplayUrl(timestamp: string, original: string): string { return `${WAYBACK_ORIGIN}/web/${timestamp}/${original}`; } -export function waybackCdxUrl(url: string, o: { limit?: number; okOnly?: boolean } = {}): string { +export function waybackCdxUrl( + url: string, + o: { limit?: number; okOnly?: boolean; closest?: string } = {}, +): string { const q = new URLSearchParams(); q.set("url", url); q.set("output", "json"); if (o.okOnly) q.set("filter", "statuscode:200"); if (o.limit) q.set("limit", String(o.limit)); + // Release 37: the captures nearest a time first (the page import's + // `{url, at}` form). + if (o.closest) { + q.set("closest", o.closest); + q.set("sort", "closest"); + } return `${WAYBACK_ORIGIN}/cdx/search/cdx?${q.toString()}`; } @@ -141,6 +154,43 @@ export type WaybackVideoStream = { probes: { url: string; status: number }[]; }; +// A page capture's raw body is read up to this (release 37): a page larger +// than this is a dump, not a page, and is refused unread past the cap. +export const WAYBACK_PAGE_MAX_BYTES = 2 * 1024 * 1024; + +// How many redirects inside the archive a capture fetch follows. +export const WAYBACK_MAX_REDIRECTS = 5; + +const PAGE_ACCEPT = "text/html,application/xhtml+xml;q=0.9,text/plain;q=0.8,application/json;q=0.8,*/*;q=0.1"; + +// One capture's bytes (getCapture). +export type WaybackRawCapture = { + body: Buffer; + // The bare mimetype ("text/html"), and the Content-Type as served (its + // charset, when it names one). + mimetype: string; + contentType: string; + // The capture the redirects (if any) ended at. + finalTs: string; + originalUrl: string; + bytes: number; + sha256: string; +}; + +export type WaybackCaptureRefusalCode = "mimetype" | "too-large" | "offsite-redirect" | "redirect-loop" | "not-archived"; + +// A capture getCapture will not hand back, with the sentence a caller shows. +export class WaybackCaptureRefusal extends Error { + readonly code: WaybackCaptureRefusalCode; + readonly mimetype?: string; + constructor(code: WaybackCaptureRefusalCode, message: string, mimetype?: string) { + super(message); + this.name = "WaybackCaptureRefusal"; + this.code = code; + if (mimetype) this.mimetype = mimetype; + } +} + export class WaybackClient { private readonly http: ArchiveOrgClient; @@ -193,6 +243,116 @@ export class WaybackClient { return out; } + // THE CAPTURE NEAREST `at` (release 37: the page import's `{url, at}`): + // one CDX request, `closest` + `sort=closest`, a few rows, the 200s only. + // Null when the Wayback Machine holds no capture of `url` that recorded a + // 200. + async closestCapture(url: string, at: string, o: { signal?: AbortSignal } = {}): Promise<WaybackCapture | null> { + const body = await this.http.getText( + waybackCdxUrl(url, { okOnly: true, limit: 5, closest: at }), + "application/json", + o.signal, + ); + let rows: WaybackCapture[]; + try { + rows = parseCdxJson(body); + } catch (e) { + throw new ArchiveOrgRequestError(`${(e as Error).message} for ${url}`, null, false); + } + if (rows.length === 0) return null; + // `sort=closest` is the server's; ordering by distance here keeps the + // answer right when a server (or a fake) ignores it. + const want = Number(at.padEnd(14, "0")); + return rows + .map((r) => ({ r, d: Math.abs(Number(r.timestamp) - want) })) + .sort((a, b) => a.d - b.d || a.r.timestamp.localeCompare(b.r.timestamp))[0].r; + } + + // ONE CAPTURE'S RAW BODY (release 37, the page import): the `id_` form, + // `/web/<ts>id_/<url>` — the bytes as captured, no toolbar, no rewritten + // links — through the client's own chain and gap. + // - At most `maxBytes` (default WAYBACK_PAGE_MAX_BYTES, 2 MB); a longer + // body is refused unread past the cap ("too-large"). + // - text/html, text/plain or application/json only; anything else is + // refused by its mimetype ("mimetype"). + // - Redirects are followed by hand, inside the Wayback Machine only and at + // most WAYBACK_MAX_REDIRECTS times: the archive answers a timestamp it + // holds no capture at with the NEAREST capture's URL, and a capture that + // recorded a redirect with the capture of its target. The answer is the + // FINAL capture (`finalTs`, `originalUrl`). A redirect off the archive + // is refused ("offsite-redirect"). + // - A capture the archive does not hold is refused ("not-archived"). + // Throws WaybackCaptureRefusal for those, ArchiveOrgRequestError when the + // archive kept refusing (`rateLimited`) or answered another error. + async getCapture( + ts: string, + url: string, + o: { raw?: true; maxBytes?: number; signal?: AbortSignal } = {}, + ): Promise<WaybackRawCapture> { + const maxBytes = o.maxBytes ?? WAYBACK_PAGE_MAX_BYTES; + let at = waybackRawUrl({ captureTs: ts, originalUrl: url }); + const seen = new Set<string>(); + for (let hop = 0; hop <= WAYBACK_MAX_REDIRECTS; hop++) { + seen.add(at); + let res; + try { + res = await this.http.getBounded(at, PAGE_ACCEPT, { maxBytes, signal: o.signal, manualRedirect: true }); + } catch (e) { + if (e instanceof ArchiveOrgRequestError && (e.status === 404 || e.status === 410)) { + throw new WaybackCaptureRefusal("not-archived", `the Wayback Machine holds no capture of ${url} at ${ts}`); + } + throw e; + } + if (res.location !== null || (res.status >= 300 && res.status < 400)) { + const next = res.location; + if (!next) throw new WaybackCaptureRefusal("offsite-redirect", `the Wayback Machine answered ${at} with a redirect that names no URL`); + let host = ""; + try { + host = new URL(next).hostname; + } catch { + host = ""; + } + const ref = isWaybackHost(host) ? parseWaybackUrl(next) : null; + if (!ref) { + throw new WaybackCaptureRefusal( + "offsite-redirect", + `the capture of ${url} redirects off the Wayback Machine (${next}); only redirects inside the archive are followed`, + ); + } + // Stay on the raw form whatever modifier the redirect named. + at = waybackRawUrl(ref); + if (seen.has(at)) throw new WaybackCaptureRefusal("redirect-loop", `the capture of ${url} redirects in a loop (${at})`); + continue; + } + const contentType = res.headers.get("content-type"); + const mimetype = bareMimetype(contentType); + if (!isPageMimetype(contentType)) { + throw new WaybackCaptureRefusal( + "mimetype", + `the capture of ${url} is ${mimetype || "of no stated type"}, not a page (${PAGE_MIMETYPES.join(", ")})`, + mimetype || undefined, + ); + } + if (res.tooLarge || !res.body) { + throw new WaybackCaptureRefusal( + "too-large", + `the capture of ${url} is over ${Math.round(maxBytes / 1024)} KB (${res.bytes} bytes and counting); not fetched`, + ); + } + const final = parseWaybackUrl(at)!; + return { + body: res.body, + mimetype, + contentType: contentType ?? mimetype, + finalTs: final.captureTs, + originalUrl: final.originalUrl, + bytes: res.body.byteLength, + sha256: createHash("sha256").update(res.body).digest("hex"), + }; + } + throw new WaybackCaptureRefusal("redirect-loop", `the capture of ${url} redirected more than ${WAYBACK_MAX_REDIRECTS} times`); + } + // The captures of `url`, oldest first: every capture, or (`okOnly`) only the // ones that recorded a 200. Throws ArchiveOrgRequestError when the API kept // refusing (`rateLimited`) or answered an error. @@ -209,5 +369,31 @@ export class WaybackClient { } } +// TEST-ONLY: E2E_WAYBACK_ORIGIN_FILE names a file holding ONE loopback origin +// (`http://127.0.0.1:<port>`). While that file exists, the process's Wayback +// client sends every https://web.archive.org request there — the editor e2e +// suite's fake Wayback (common/testing/web/fakeWayback.mjs), which a spec +// starts and names in the file (read per request, so a spec can start its fake +// after the server booted). Anything but a loopback origin is ignored. Unset +// everywhere but the editor's e2e server; unit tests pass `fetch` directly. +const LOOPBACK_ORIGIN = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d{1,5})?$/; + +export function waybackTestOrigin(env: Readonly<Record<string, string | undefined>> = process.env): string | null { + const file = env.E2E_WAYBACK_ORIGIN_FILE; + if (!file) return null; + let origin = ""; + try { + origin = readFileSync(file, "utf8").trim().replace(/\/$/, ""); + } catch { + return null; + } + return LOOPBACK_ORIGIN.test(origin) ? origin : null; +} + +function processWaybackFetch(url: string, init: RequestInit): Promise<Response> { + const origin = waybackTestOrigin(); + return fetch(origin ? url.replace(/^https?:\/\/(?:web|wayback)\.archive\.org/, origin) : url, init); +} + // THE process's Wayback client: one chain, one gap. -export const waybackClient = new WaybackClient(); +export const waybackClient = new WaybackClient({ fetch: processWaybackFetch }); diff --git a/common/lib/waybackPages/config.test.ts b/common/lib/waybackPages/config.test.ts @@ -0,0 +1,177 @@ +// Release 37 S1: a Wayback pages channel's scope (`config.wayback`), what the +// New channel form derives from a URL, and the URL readers of an import. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/config.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { + coerceWaybackPagesConfig, + isWaybackPagesChannel, + waybackTargetFromUrl, + waybackTargetHost, +} from "./config"; +import { + captureTsIso, + isCaptureAt, + isPageMimetype, + isWaybackPagesUrl, + isXHostUrl, + isXTargetUrl, + parsePageCaptureAsk, + videoPageOf, +} from "./urls"; +import { parseChannelConfig } from "../channelConfig"; +import { channelConfigSchema } from "../channelConfigSchema"; +import { isXPostsChannel, postsVisibleTo } from "../postsVisibility"; + +test("config.wayback: valid targets kept, invalid ones dropped one by one, none = the key omitted", () => { + assert.deepEqual( + coerceWaybackPagesConfig({ + targets: [ + { url: " example.com/blog ", match: "prefix", from: "2014", to: "20161231", mime: ["Text/HTML", "nonsense"], include: "\\.html$" }, + { url: "example.com", match: "everything" }, + { match: "exact" }, + { url: "a b.example", match: "exact" }, + { url: "example.org", match: "domain", from: "14" }, + ], + collapse: "digest", + }), + { + targets: [ + { url: "example.com/blog", match: "prefix", from: "2014", to: "20161231", mime: ["text/html"], include: "\\.html$" }, + { url: "example.org", match: "domain" }, + ], + collapse: "digest", + }, + ); + assert.equal(coerceWaybackPagesConfig({ targets: [{ url: "x", match: "nope" }] }), undefined); + assert.equal(coerceWaybackPagesConfig({ targets: [] }), undefined); + assert.equal(coerceWaybackPagesConfig([]), undefined); + assert.equal(coerceWaybackPagesConfig("example.com"), undefined); +}); + +test("the client-safe parser and the zod schema agree on config.wayback", () => { + const raw = { + handling: "transcribe", + sourceKind: "social", + platform: "webpage", + name: "Old blog", + url: "https://web.archive.org/web/*/blog.example/*", + socialHandle: "blog.example", + wayback: { targets: [{ url: "blog.example/", match: "prefix" }, { url: "", match: "exact" }] }, + }; + const a = parseChannelConfig(raw); + const b = channelConfigSchema.parse(raw); + assert.deepEqual(a, b); + assert.deepEqual(a?.wayback, { targets: [{ url: "blog.example/", match: "prefix" }] }); + assert.equal(a?.platform, "webpage"); + assert.equal(isWaybackPagesChannel(a), true); + assert.equal(isWaybackPagesChannel({ sourceKind: "social", platform: "twitter" }), false); + assert.equal(isWaybackPagesChannel({ platform: "webpage" }), false); +}); + +test("a target from a URL: the Wayback listing forms, a capture, a bare URL", () => { + assert.deepEqual(waybackTargetFromUrl("https://web.archive.org/web/*/example.com/blog*"), { url: "example.com/blog", match: "prefix" }); + assert.deepEqual(waybackTargetFromUrl("https://web.archive.org/web/*/*.example.com*"), { url: "example.com", match: "domain" }); + assert.deepEqual(waybackTargetFromUrl("https://web.archive.org/web/*/https://example.com/about"), { url: "https://example.com/about", match: "exact" }); + assert.deepEqual(waybackTargetFromUrl("https://web.archive.org/web/2014*/example.com/*"), { + url: "example.com/", + match: "prefix", + from: "2014", + to: "2014", + }); + assert.deepEqual( + waybackTargetFromUrl("https://web.archive.org/web/20140305120000/https://blog.example/a.html"), + { url: "https://blog.example/a.html", match: "exact" }, + ); + assert.deepEqual(waybackTargetFromUrl("blog.example/2014/*"), { url: "blog.example/2014/", match: "prefix" }); + assert.deepEqual(waybackTargetFromUrl("*.example.net"), { url: "example.net", match: "domain" }); + assert.equal(waybackTargetFromUrl(""), null); + assert.equal(waybackTargetFromUrl("not a url"), null); + assert.equal(waybackTargetFromUrl("https://web.archive.org/"), null); + assert.equal(waybackTargetHost({ url: "https://www.Example.com/x" }), "example.com"); + assert.equal(waybackTargetHost({ url: "example.com/blog" }), "example.com"); +}); + +test("an import's ask: a capture URL, or a page and a date; everything else refused with a sentence", () => { + const cap = parsePageCaptureAsk("https://web.archive.org/web/20140305120000/https://blog.example/a.html"); + assert.deepEqual(cap, { ok: true, ask: { kind: "capture", captureTs: "20140305120000", originalUrl: "https://blog.example/a.html" } }); + const raw = parsePageCaptureAsk("https://web.archive.org/web/2014id_/http://blog.example/a.html"); + assert.deepEqual(raw, { ok: true, ask: { kind: "capture", captureTs: "2014", originalUrl: "http://blog.example/a.html" } }); + assert.deepEqual(parsePageCaptureAsk("https://blog.example/a.html", "20140301"), { + ok: true, + ask: { kind: "nearest", at: "20140301", originalUrl: "https://blog.example/a.html" }, + }); + const listing = parsePageCaptureAsk("https://web.archive.org/web/*/blog.example/*"); + assert.equal(listing.ok, false); + assert.match(!listing.ok ? listing.error : "", /a Wayback Machine listing, not one capture/); + const bare = parsePageCaptureAsk("https://blog.example/a.html"); + assert.match(!bare.ok ? bare.error : "", /is not a Wayback Machine capture/); + const both = parsePageCaptureAsk("https://web.archive.org/web/20140305120000/https://blog.example/a.html", "2015"); + assert.match(!both.ok ? both.error : "", /"at" goes with a page's own URL/); + const badAt = parsePageCaptureAsk("https://blog.example/a.html", "March"); + assert.match(!badAt.ok ? badAt.error : "", /"at" must be a date/); + assert.equal(parsePageCaptureAsk("ftp://x.example/").ok, false); + assert.equal(parsePageCaptureAsk("").ok, false); + assert.equal(isCaptureAt("2014"), true); + assert.equal(isCaptureAt("20140305120000"), true); + assert.equal(isCaptureAt("201403051"), false); +}); + +test("capture time as ISO; a timestamp that is no real time is none", () => { + assert.equal(captureTsIso("20140305120000"), "2014-03-05T12:00:00.000Z"); + assert.equal(captureTsIso("2014"), "2014-01-01T00:00:00.000Z"); + assert.equal(captureTsIso("201403"), "2014-03-01T00:00:00.000Z"); + assert.equal(captureTsIso("20140231000000"), ""); + assert.equal(captureTsIso("abc"), ""); +}); + +test("a video is import-video's; a channel page, an About page or a post is not a video", () => { + assert.equal(videoPageOf("https://www.youtube.com/watch?v=abc"), "YouTube"); + assert.equal(videoPageOf("https://youtu.be/abc"), "YouTube"); + assert.equal(videoPageOf("https://www.youtube.com/shorts/abc"), "YouTube"); + assert.equal(videoPageOf("https://www.youtube.com/@someone/about"), null); + assert.equal(videoPageOf("https://www.youtube.com/c/someone"), null); + assert.equal(videoPageOf("https://rumble.com/v4abc-a-title.html"), "Rumble"); + assert.equal(videoPageOf("https://rumble.com/c/someone"), null); + assert.equal(videoPageOf("https://cdn.example/clip.mp4"), "a media file"); + assert.equal(videoPageOf("https://x.com/someone/status/1"), null); + assert.equal(videoPageOf("https://blog.example/a.html"), null); + assert.equal(isWaybackPagesUrl("https://web.archive.org/web/*/blog.example/*"), true); + assert.equal(isWaybackPagesUrl("https://web.archive.org/web/20140305120000/https://blog.example/a.html"), true); + assert.equal(isWaybackPagesUrl("https://web.archive.org/web/20140305120000/https://www.youtube.com/watch?v=abc"), false); + assert.equal(isWaybackPagesUrl("https://blog.example/a.html"), false); + assert.equal(isPageMimetype("text/html; charset=UTF-8"), true); + assert.equal(isPageMimetype("application/json"), true); + assert.equal(isPageMimetype("image/jpeg"), false); +}); + +test("X: a capture of x.com/twitter.com is X's; a Wayback pages channel scoped on X is an X channel for the visibility rule", () => { + assert.equal(isXHostUrl("https://twitter.com/someone"), true); + assert.equal(isXHostUrl("https://mobile.twitter.com/someone/status/1"), true); + assert.equal(isXHostUrl("https://x.com/someone"), true); + assert.equal(isXHostUrl("https://notx.com/"), false); + assert.equal(isXTargetUrl("twitter.com/someone"), true); + const xPages = { + sourceKind: "social" as const, + platform: "webpage" as const, + wayback: { targets: [{ url: "twitter.com/someone", match: "prefix" as const }] }, + }; + const blogPages = { + sourceKind: "social" as const, + platform: "webpage" as const, + wayback: { targets: [{ url: "blog.example/", match: "prefix" as const }] }, + }; + assert.equal(isXPostsChannel(xPages), true); + assert.equal(isXPostsChannel(blogPages), false); + assert.equal( + isXPostsChannel({ sourceKind: "social", platform: "webpage", url: "https://web.archive.org/web/*/twitter.com/someone*" }), + true, + ); + const priv = { social: { x: { visibility: "private" } } }; + assert.equal(postsVisibleTo({}, xPages, priv), false); + assert.equal(postsVisibleTo({ audience: "private" }, xPages, priv), true); + assert.equal(postsVisibleTo({}, blogPages, priv), true); + assert.equal(postsVisibleTo({}, xPages, {}), true); +}); diff --git a/common/lib/waybackPages/config.ts b/common/lib/waybackPages/config.ts @@ -0,0 +1,147 @@ +// A WAYBACK PAGES CHANNEL (release 37, plans/release-37/wayback-pages.md, "What +// a channel is"): a named scope of Wayback Machine captures — a channel on +// platform "webpage", `sourceKind: "social"`, whose records are page records +// (Post.page). `config.wayback` says which captures are in scope: one or more +// targets, each a URL and how it matches (one page, a path prefix, a host, a +// whole domain), optionally bounded by capture date. +// +// Client-safe and a LEAF (no imports): lib/channelConfig.ts composes the +// coercion below into its one set of coercions, and the channel form imports +// both. + +export const WAYBACK_TARGET_MATCHES = ["exact", "prefix", "host", "domain"] as const; +export type WaybackTargetMatch = (typeof WAYBACK_TARGET_MATCHES)[number]; + +export type WaybackTarget = { + // The page, path prefix, host or domain, as the CDX API takes it (a scheme + // is optional; for "host" and "domain" only the host counts). + url: string; + match: WaybackTargetMatch; + // Capture-time bounds, a Wayback timestamp prefix (4–14 digits: + // yyyy[MM[dd[hh[mm[ss]]]]]), inclusive. + from?: string; + to?: string; + // Mimetypes kept (default: text/html). + mime?: string[]; + // Regex sources over a capture's original URL: kept when it matches + // `include` (if set) and not `exclude`. + include?: string; + exclude?: string; +}; + +export type WaybackPagesConfig = { + targets: WaybackTarget[]; + // How a scan folds repeated captures: "digest" = one row per distinct body. + collapse?: "digest"; +}; + +const TS_PREFIX_RE = /^\d{4,14}$/; + +const trimmed = (v: unknown): string | undefined => + typeof v === "string" && v.trim() ? v.trim() : undefined; + +export function coerceWaybackTarget(v: unknown): WaybackTarget | undefined { + if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; + const r = v as Record<string, unknown>; + const url = trimmed(r.url); + if (!url || /\s/.test(url)) return undefined; + const match = (WAYBACK_TARGET_MATCHES as readonly string[]).includes(r.match as string) + ? (r.match as WaybackTargetMatch) + : undefined; + if (!match) return undefined; + const out: WaybackTarget = { url, match }; + const from = trimmed(r.from); + if (from && TS_PREFIX_RE.test(from)) out.from = from; + const to = trimmed(r.to); + if (to && TS_PREFIX_RE.test(to)) out.to = to; + if (Array.isArray(r.mime)) { + const mime = r.mime + .map((m) => (typeof m === "string" ? m.trim().toLowerCase() : "")) + .filter((m) => /^[a-z0-9.+-]+\/[a-z0-9.+*-]+$/.test(m)); + if (mime.length > 0) out.mime = [...new Set(mime)]; + } + const include = trimmed(r.include); + if (include) out.include = include; + const exclude = trimmed(r.exclude); + if (exclude) out.exclude = exclude; + return out; +} + +// `config.wayback`: an object with at least one valid target, else omitted. +// Invalid targets are dropped one by one, never repaired. +export function coerceWaybackPagesConfig(v: unknown): WaybackPagesConfig | undefined { + if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; + const r = v as Record<string, unknown>; + if (!Array.isArray(r.targets)) return undefined; + const targets = r.targets.map(coerceWaybackTarget).filter((t): t is WaybackTarget => !!t); + if (targets.length === 0) return undefined; + const out: WaybackPagesConfig = { targets }; + if (r.collapse === "digest") out.collapse = "digest"; + return out; +} + +// A Wayback pages channel: a posts channel on platform "webpage". Structural, +// so this leaf needs no import of the channel config's type. +export function isWaybackPagesChannel( + config: { sourceKind?: string; platform?: string } | null | undefined, +): boolean { + return config?.sourceKind === "social" && config.platform === "webpage"; +} + +const WAYBACK_HOST_RE = /^(?:web|wayback)\.archive\.org$/i; + +// The Wayback Machine's own LISTING forms name a scope, not one capture: +// web.archive.org/web/*/example.com/blog* → prefix example.com/blog +// web.archive.org/web/*/*.example.com* → the domain example.com +// web.archive.org/web/*/example.com/about → exactly that page +// web.archive.org/web/2014*/example.com* → a prefix, captures of 2014 +// and a capture URL (web.archive.org/web/<ts>/<original>) names one page, +// exactly. A URL that is not on the Wayback Machine is taken as the target +// itself: a trailing `*` makes it a prefix, a leading `*.` a domain. +// Null for anything that names no target. +export function waybackTargetFromUrl(input: string): WaybackTarget | null { + const raw = input.trim(); + if (!raw) return null; + let rest = raw; + let from: string | undefined; + let to: string | undefined; + let u: URL | null = null; + try { + u = new URL(raw); + } catch { + u = null; + } + if (u && WAYBACK_HOST_RE.test(u.hostname)) { + const m = /^\/(?:web\/)?(\d{0,14})(\*?)(?:[a-z]{2}_)?\/(.+)$/s.exec(u.pathname + u.search); + if (!m) return null; + const [, digits, star, original] = m; + rest = original; + if (star && digits) { + from = digits; + to = digits; + } + // A capture URL (digits, no star) is one page at one time; its target is + // the page. + } + rest = rest.replace(/^(https?):\/(?!\/)/i, "$1://"); + let match: WaybackTargetMatch = "exact"; + if (rest.endsWith("*")) { + match = "prefix"; + rest = rest.replace(/\*+$/, ""); + } + const bare = rest.replace(/^https?:\/\//i, ""); + if (bare.startsWith("*.")) { + const host = bare.slice(2).split(/[/?#]/)[0]; + if (!host || !host.includes(".")) return null; + return { url: host.toLowerCase(), match: "domain", ...(from ? { from } : {}), ...(to ? { to } : {}) }; + } + const host = bare.split(/[/?#]/)[0]; + if (!host || !host.includes(".") || /\s/.test(rest)) return null; + return { url: rest, match, ...(from ? { from } : {}), ...(to ? { to } : {}) }; +} + +// The host a target names (no "www."), for a channel's handle. +export function waybackTargetHost(target: Pick<WaybackTarget, "url">): string { + const bare = target.url.replace(/^https?:\/\//i, ""); + return bare.split(/[/?#:]/)[0].toLowerCase().replace(/^www\./, ""); +} diff --git a/common/lib/waybackPages/extract.test.ts b/common/lib/waybackPages/extract.test.ts @@ -0,0 +1,61 @@ +// Release 37: the dispatcher over the REGISTERED site extractors (lane C's) +// with their synthetic fixtures — each capture reaches its own extractor, an +// unknown page reaches the generic one — and their drafts as page records +// (an item's own id; a shell or a document one record per capture). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/extract.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { chooseExtractor, extractPage } from "./extract"; +import { SITE_EXTRACTORS } from "./extractors/index"; +import { captureOf, fixture } from "./extractors/__fixtures__/capture"; +import { draftToPost, isWholePageRecord } from "./toPost"; +import { pageRecordId } from "./types"; + +const input = (file: string, url: string, ts: string) => ({ html: fixture(file), capture: captureOf(url, ts) }); + +test("a registered site's capture reaches its extractor; an unknown page reaches generic", () => { + const cases: [string, string, string, string][] = [ + ["tumblr-2012-classic-post.html", "http://teapot-notes.tumblr.com/post/20000000001/on-spouts", "20120601000000", "tumblr"], + ["x-2016-status.html", "https://twitter.com/TeapotFan/status/697374449464250369", "20160211000000", "x"], + ["yt-about-2013.html", "http://www.youtube.com/user/teapotchannel/about", "20131001000000", "yt-about"], + ]; + for (const [file, url, ts, want] of cases) { + const i = input(file, url, ts); + assert.equal(chooseExtractor(i).name, want, file); + const res = extractPage(i); + assert.equal(res.extractor.name, want, file); + assert.equal(res.fallback, undefined, file); + assert.ok(res.drafts.length > 0, file); + } + const unknown = { html: "<html><body><article><p>An ordinary page with words enough to read.</p></article></body></html>", capture: captureOf("https://plain.example/page", "20150101000000") }; + assert.equal(chooseExtractor(unknown).name, "generic"); + assert.equal(extractPage(unknown).drafts[0].kind, "generic"); + assert.ok(SITE_EXTRACTORS.length >= 5); +}); + +test("site drafts as page records: a tweet is its own record with X's refs; a shell is one record per capture", () => { + const ts = "20160211000000"; + const url = "https://twitter.com/TeapotFan/status/697374449464250369"; + const res = extractPage(input("x-2016-status.html", url, ts)); + const posts = res.drafts.map((d) => + draftToPost(d, { channelSlug: "pages", capture: { originalUrl: url, captureTs: ts }, extractor: res.extractor }), + ); + const tweet = posts.find((p) => p.id === "tweet-697374449464250369"); + assert.ok(tweet, posts.map((p) => p.id).join(", ")); + assert.equal(tweet!.platform, "webpage"); + assert.equal(tweet!.page?.kind, "tweet"); + assert.equal(tweet!.page?.firstSeenTs, ts); + assert.equal(isWholePageRecord(tweet!), false); + + const shellTs = "20221101000000"; + const shellUrl = "https://twitter.com/TeapotFan"; + const shell = extractPage(input("x-2022-shell.html", shellUrl, shellTs)); + const [rec] = shell.drafts.map((d) => + draftToPost(d, { channelSlug: "pages", capture: { originalUrl: shellUrl, captureTs: shellTs }, extractor: shell.extractor }), + ); + assert.equal(rec.id, pageRecordId(shellTs, shellUrl)); + assert.equal(rec.page?.noContent, true); + assert.equal(isWholePageRecord(rec), true); +}); diff --git a/common/lib/waybackPages/extract.ts b/common/lib/waybackPages/extract.ts @@ -0,0 +1,92 @@ +// THE DISPATCHER (release 37 S1): a capture goes to the FIRST site extractor +// (extractors/index.ts, SITE_EXTRACTORS) whose `matches` is true, else to the +// generic extractor. A site extractor that throws, or hands back no record, +// falls back to the generic one, and the record says so +// (`page.extractorFallback`). Site extractors are offered HTML only; a +// text/plain or JSON capture is the generic extractor's. +// +// Pure apart from TextDecoder (no node imports): what a capture's bytes say, +// decoded by the charset the capture names. + +import { SITE_EXTRACTORS } from "./extractors/index"; +import { genericExtractor } from "./extractors/generic"; +import type { PageExtractInput, PageExtractor, PageRecordDraft } from "./types"; +import { bareMimetype } from "./urls"; + +export type ExtractPageResult = { + drafts: PageRecordDraft[]; + // Which extractor made the drafts. + extractor: { name: string; version: number }; + // The site extractor that claimed the capture and failed, when one did. + fallback?: { from: string; fromVersion: number; error: string }; +}; + +// Which extractor a capture goes to (before it runs): the first that claims +// it, else the generic one. What a re-extract compares against the stored +// capture's extractor and version. +export function chooseExtractor( + input: PageExtractInput, + extractors: readonly PageExtractor[] = SITE_EXTRACTORS, +): PageExtractor { + if (bareMimetype(input.capture.mimetype ?? "text/html") !== "text/html") return genericExtractor; + let url: URL; + try { + url = new URL(input.capture.originalUrl); + } catch { + return genericExtractor; + } + for (const x of extractors) { + try { + if (x.matches(url, input.html)) return x; + } catch { + // A matcher that throws claims nothing. + } + } + return genericExtractor; +} + +export function extractPage( + input: PageExtractInput, + extractors: readonly PageExtractor[] = SITE_EXTRACTORS, +): ExtractPageResult { + const chosen = chooseExtractor(input, extractors); + const generic = (): PageRecordDraft[] => genericExtractor.extract(input); + const self = { name: chosen.name, version: chosen.version }; + if (chosen === genericExtractor) return { drafts: generic(), extractor: self }; + let error: string; + try { + const drafts = chosen.extract(input); + if (drafts.length > 0) return { drafts, extractor: self }; + error = "it made no record of the capture"; + } catch (e) { + error = (e as Error)?.message || String(e); + } + return { + drafts: generic(), + extractor: { name: genericExtractor.name, version: genericExtractor.version }, + fallback: { from: chosen.name, fromVersion: chosen.version, error }, + }; +} + +// ─── Bytes → text ─── + +// The charset a Content-Type names, else the one the document declares in its +// first 4 KB (`<meta charset>`, `<meta http-equiv content="…charset=">`, an +// XML declaration), else UTF-8. A label TextDecoder does not know is UTF-8. +export function decodeCaptureBody(body: Uint8Array, contentType?: string | null): string { + const fromHeader = /charset\s*=\s*["']?([\w.:-]+)/i.exec(contentType ?? "")?.[1]; + let label = fromHeader; + if (!label) { + const head = new TextDecoder("latin1").decode(body.subarray(0, 4096)); + label = + /<meta[^>]+charset\s*=\s*["']?([\w.:-]+)/i.exec(head)?.[1] ?? + /<\?xml[^>]+encoding\s*=\s*["']([\w.:-]+)/i.exec(head)?.[1]; + } + let decoder: TextDecoder; + try { + decoder = new TextDecoder(label ?? "utf-8"); + } catch { + decoder = new TextDecoder("utf-8"); + } + return decoder.decode(body).replace(/^/, ""); +} diff --git a/common/lib/waybackPages/extractors/__fixtures__/capture.ts b/common/lib/waybackPages/extractors/__fixtures__/capture.ts @@ -15,5 +15,5 @@ export function captureOf(originalUrl: string, captureTs: string): PageExtractIn } export function fixture(name: string): string { - return readFileSync(new URL(`./${name}`, import.meta.url), "utf8"); + return readFileSync(/* turbopackIgnore: true */ new URL(`./${name}`, import.meta.url), "utf8"); } diff --git a/common/lib/waybackPages/extractors/generic.test.ts b/common/lib/waybackPages/extractors/generic.test.ts @@ -0,0 +1,204 @@ +// Release 37 S1: the generic extractor over synthetic captures — main content, +// furniture dropped, Wayback chrome stripped, title/author/date, links +// un-rewritten and absolute, images by their Wayback URLs — and the +// dispatcher's fallback rules. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/extractors/generic.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { + absoluteOriginalUrl, + extractGeneric, + genericExtractor, + NO_CONTENT_TEXT, + stripWaybackChrome, + unrewriteWaybackUrl, +} from "./generic"; +import { chooseExtractor, decodeCaptureBody, extractPage } from "../extract"; +import type { PageExtractInput, PageExtractor } from "../types"; + +const cap = (originalUrl: string, captureTs: string, mimetype = "text/html") => ({ + originalUrl, + captureTs, + mimetype, + waybackUrl: `https://web.archive.org/web/${captureTs}/${originalUrl}`, + rawUrl: `https://web.archive.org/web/${captureTs}id_/${originalUrl}`, +}); + +const ARTICLE = `<!doctype html><html><head> +<title>A Post About Bread | Example Blog</title> +<meta property="og:title" content="A Post About Bread"> +<meta property="article:published_time" content="2014-03-04T18:30:00Z"> +<meta name="author" content="Pat Example"> +</head><body> +<nav><a href="/">Home</a> <a href="/archive">Archive</a></nav> +<header class="site"><h1>Example Blog</h1></header> +<aside><h3>Blogroll</h3><a href="https://other.example/">Other</a></aside> +<article> +<header><h1>A Post About Bread</h1></header> +<p>The first loaf came out flat, and the second, and the third.</p> +<p>See <a href="/web/20140305120000/https://blog.example/2014/02/starter.html">the starter post</a> and <a href="../about">about</a>.</p> +<blockquote><p>Bake it until it sounds hollow.</p></blockquote> +<ul><li>Flour, 500 g</li><li>Water, 350 g</li></ul> +<img src="/images/loaf.jpg" alt="A flat loaf"> +<pre> day 1: feed + day 2: feed</pre> +</article> +<footer>Copyright 2014. <a href="/about">About</a></footer> +<script>var x = "script text must not show";</script> +</body></html>`; + +test("an article: its main content block by block, the furniture gone, facts from the meta", () => { + const d = extractGeneric({ html: ARTICLE, capture: cap("https://blog.example/2014/03/a-post.html", "20140305120000") }); + assert.equal(d.kind, "generic"); + assert.equal(d.title, "A Post About Bread"); + assert.equal(d.author, "Pat Example"); + assert.equal(d.publishedAt, "2014-03-04T18:30:00.000Z"); + assert.equal( + d.text, + [ + "A Post About Bread", + "The first loaf came out flat, and the second, and the third.", + "See the starter post and about.", + "> Bake it until it sounds hollow.", + "- Flour, 500 g", + "- Water, 350 g", + "[Image: A flat loaf]", + " day 1: feed\n day 2: feed", + ].join("\n\n"), + ); + for (const gone of ["Home", "Blogroll", "Copyright", "script text", "Example Blog"]) { + assert.ok(!d.text.includes(gone), `${gone} is furniture`); + } + assert.deepEqual(d.links, ["https://blog.example/2014/02/starter.html", "https://blog.example/2014/about"]); + assert.deepEqual(d.media, [ + { kind: "image", url: "https://web.archive.org/web/20140305120000im_/https://blog.example/images/loaf.jpg", name: "A flat loaf" }, + ]); + assert.equal(d.noContent, undefined); +}); + +test("a body that still carries the Wayback toolbar: the insert, its scripts and rewritten links undone", () => { + const html = `<html><head><script src="/_static/js/wombat.js?v=1"></script> +<script>__wm.init("https://web.archive.org/web");</script> +<link rel="stylesheet" href="/_static/css/banner-styles.css"><title>About Us</title></head><body> +<!-- BEGIN WAYBACK TOOLBAR INSERT --> +<div id="wm-ipp-base"><div id="wm-ipp"><p>The Wayback Machine toolbar text</p></div></div> +<!-- END WAYBACK TOOLBAR INSERT --> +<div id="content"><h2>About us</h2> +<p>We are a small group that makes zines about our town, and have since 2009.</p> +<p>Write through the <a href="https://web.archive.org/web/20150101000000/https://home.example/contact">contact page</a> +or see <a href="/web/20150101000000/https://home.example/links">links</a>.</p></div> +</body></html>`; + assert.ok(!stripWaybackChrome(html).includes("wombat")); + const d = extractGeneric({ html, capture: cap("https://home.example/about", "20150101000000") }); + assert.equal(d.title, "About Us"); + assert.ok(!d.text.includes("toolbar"), d.text); + assert.ok(d.text.includes("We are a small group that makes zines")); + assert.deepEqual(d.links, ["https://home.example/contact", "https://home.example/links"]); + // A toolbar insert cut short (no END marker) still goes, by its element. + const cut = extractGeneric({ + html: `<body><!-- BEGIN WAYBACK TOOLBAR INSERT --><div id="wm-ipp-base">toolbar</div><p>Real words of the page, long enough to count as a paragraph.</p></body>`, + capture: cap("https://home.example/", "2015"), + }); + assert.ok(!cut.text.includes("toolbar")); +}); + +test("no <main> or <article>: the densest block wins over the link lists", () => { + const html = `<html><body> +<div id="side"><a href="/a">A link</a> <a href="/b">B link</a> <a href="/c">C link, and more, and more</a></div> +<div id="post"> +<p>This is the first paragraph of the real writing, with commas, clauses, and words.</p> +<p>And a second paragraph, which also carries some weight, so the block wins.</p> +</div> +<div id="foot"><p>Short.</p></div> +</body></html>`; + const d = extractGeneric({ html, capture: cap("https://site.example/page", "20100101000000") }); + assert.ok(d.text.startsWith("This is the first paragraph"), d.text); + assert.ok(!d.text.includes("A link")); + assert.ok(!d.text.includes("Short.")); + // No title anywhere → none. + assert.equal(d.title, undefined); +}); + +test("dates: JSON-LD, <time>, and none believed after the capture", () => { + const ld = extractGeneric({ + html: `<html><head><script type="application/ld+json">{"@graph":[{"@type":"BlogPosting","datePublished":"2013-07-01","author":{"name":"Sam"}}]}</script></head> +<body><article><p>Words enough to be a paragraph of the article itself.</p></article></body></html>`, + capture: cap("https://site.example/p", "20140101000000"), + }); + assert.equal(ld.publishedAt, "2013-07-01T00:00:00.000Z"); + assert.equal(ld.author, "Sam"); + const time = extractGeneric({ + html: `<body><article><time datetime="2012-05-06">May 6</time><p>Words enough to be a paragraph.</p></article></body>`, + capture: cap("https://site.example/p", "20140101000000"), + }); + assert.equal(time.publishedAt, "2012-05-06T00:00:00.000Z"); + const future = extractGeneric({ + html: `<head><meta property="article:published_time" content="2020-01-01"></head><body><p>Words enough to be a paragraph here.</p></body>`, + capture: cap("https://site.example/p", "20140101000000"), + }); + assert.equal(future.publishedAt, undefined); +}); + +test("a page with no readable text says so; plain text and JSON are their text", () => { + const empty = extractGeneric({ html: `<html><body><nav><a href="/">Home</a></nav><script>app()</script></body></html>`, capture: cap("https://app.example/", "2020") }); + assert.equal(empty.noContent, true); + assert.equal(empty.text, NO_CONTENT_TEXT); + const plain = extractGeneric({ html: "README\r\n\r\nNotes.\n", capture: cap("https://n.example/readme.txt", "2018", "text/plain") }); + assert.equal(plain.text, "README\n\nNotes."); + assert.deepEqual(plain.links, []); + const json = extractGeneric({ html: '{"a": 1}', capture: cap("https://n.example/a.json", "2018", "application/json") }); + assert.equal(json.text, '{"a": 1}'); +}); + +test("hrefs: Wayback-rewritten ones un-rewritten; relative ones resolved against the original; the rest dropped", () => { + assert.equal(unrewriteWaybackUrl("/web/20140101000000/http://a.example/x"), "http://a.example/x"); + assert.equal(unrewriteWaybackUrl("//web.archive.org/web/2014im_/https://a.example/i.png"), "https://a.example/i.png"); + assert.equal(unrewriteWaybackUrl("https://web.archive.org/web/20140101000000/a.example/y"), "http://a.example/y"); + assert.equal(unrewriteWaybackUrl("/plain/path"), "/plain/path"); + assert.equal(absoluteOriginalUrl("/x#frag", "https://a.example/dir/page"), "https://a.example/x"); + assert.equal(absoluteOriginalUrl("#top", "https://a.example/"), null); + assert.equal(absoluteOriginalUrl("javascript:void(0)", "https://a.example/"), null); + assert.equal(absoluteOriginalUrl("mailto:a@b.example", "https://a.example/"), null); +}); + +test("the dispatcher: the first site extractor that claims a capture; a throw or no record falls back to generic and says so", () => { + const input: PageExtractInput = { html: ARTICLE, capture: cap("https://blog.example/2014/03/a-post.html", "20140305120000") }; + const claims = (name: string, extract: PageExtractor["extract"], version = 3): PageExtractor => ({ + name, + version, + matches: (u) => u.hostname === "blog.example", + extract, + }); + const never: PageExtractor = { name: "never", version: 1, matches: () => false, extract: () => [] }; + const ok = claims("blogx", () => [{ kind: "tumblr-post", itemId: "tumblr-1", text: "one", links: [] }]); + assert.equal(chooseExtractor(input, [never, ok]).name, "blogx"); + assert.equal(chooseExtractor(input, [never]), genericExtractor); + const res = extractPage(input, [never, ok]); + assert.deepEqual(res.extractor, { name: "blogx", version: 3 }); + assert.equal(res.drafts[0].itemId, "tumblr-1"); + assert.equal(res.fallback, undefined); + + const boom = extractPage(input, [claims("blogx", () => { throw new Error("layout changed"); })]); + assert.deepEqual(boom.extractor, { name: "generic", version: 1 }); + assert.deepEqual(boom.fallback, { from: "blogx", fromVersion: 3, error: "layout changed" }); + assert.equal(boom.drafts[0].title, "A Post About Bread"); + + const none = extractPage(input, [claims("blogx", () => [])]); + assert.equal(none.fallback?.error, "it made no record of the capture"); + + // A matcher that throws claims nothing; a non-HTML capture is generic's. + const badMatch: PageExtractor = { name: "bad", version: 1, matches: () => { throw new Error("x"); }, extract: () => [] }; + assert.equal(chooseExtractor(input, [badMatch]), genericExtractor); + assert.equal(chooseExtractor({ ...input, capture: { ...input.capture, mimetype: "text/plain" } }, [ok]), genericExtractor); +}); + +test("bytes to text: the header's charset, else the document's, else UTF-8", () => { + const latin = Buffer.from([0x63, 0x61, 0x66, 0xe9]); // "café" in latin1 + assert.equal(decodeCaptureBody(latin, "text/html; charset=ISO-8859-1"), "café"); + const declared = Buffer.concat([Buffer.from('<meta charset="windows-1252"><p>'), latin]); + assert.ok(decodeCaptureBody(declared, "text/html").endsWith("café")); + assert.equal(decodeCaptureBody(Buffer.from("café", "utf8"), "text/html"), "café"); + assert.equal(decodeCaptureBody(Buffer.from("café", "utf8"), "text/html; charset=no-such-charset"), "café"); +}); diff --git a/common/lib/waybackPages/extractors/generic.ts b/common/lib/waybackPages/extractors/generic.ts @@ -0,0 +1,477 @@ +// THE GENERIC EXTRACTOR (release 37 S1): any captured page as ONE record — its +// readable text, title, author, date, links and images — for every capture no +// site extractor claims (articles, personal sites, Newgrounds pages, a group's +// old site). Pure: no network, no disk, no clock (a PageExtractor). +// +// What it does, in order: +// 1. Wayback's own chrome goes: the injected toolbar (`<!-- BEGIN WAYBACK +// TOOLBAR INSERT -->` … `END`, and any `#wm-ipp*` element left by a +// truncated one), its scripts (`/_static/`, `wombat`, `__wm.` calls) and +// stylesheets. An `id_` body usually has none; a framed one does. +// 2. The page's furniture goes: nav, header and footer (a header INSIDE an +// article stays — it holds the title), aside, script, style, noscript, +// form, iframe, svg, buttons, the hidden. +// 3. The main content: `<main>` / `[role=main]`, else the page's top-level +// `<article>`s, else the densest block (each paragraph scores its parent +// fully and its grandparent by half, the total cut by the block's link +// density; the first highest wins). +// 4. Its text, block by block: headings, paragraphs, list items ("- "), +// blockquotes ("> "), `<pre>` as written, link text, image alts. +// 5. Title from og:title, else `<title>`, else the first h1; author and date +// from JSON-LD, `<meta>` (author, article:published_time, og:*, +// twitter:*, dc.*) and `<time datetime>` — a date after the capture is +// not believed. +// 6. links[] absolute (resolved against the ORIGINAL url, Wayback-rewritten +// hrefs un-rewritten to the original); media[] the images, each by its +// own Wayback URL (`/web/<ts>im_/<src>`). +// A text/plain or application/json body is its text as it is. + +import { parseHtml, type HtmlElement, type HtmlNode } from "../../../social/htmlReader"; +import { parseWaybackUrl } from "../../wayback"; +import type { PostMedia } from "../../posts"; +import type { PageExtractInput, PageExtractor, PageRecordDraft } from "../types"; +import { bareMimetype, captureTsIso } from "../urls"; + +export const GENERIC_EXTRACTOR_NAME = "generic"; +export const GENERIC_EXTRACTOR_VERSION = 1; + +export const NO_CONTENT_TEXT = "No readable text in this capture."; + +const MAX_LINKS = 500; +const MAX_MEDIA = 200; + +// ─── Wayback's chrome ─── + +const TOOLBAR_RE = /<!--\s*BEGIN WAYBACK TOOLBAR INSERT\s*-->[\s\S]*?<!--\s*END WAYBACK TOOLBAR INSERT\s*-->/gi; +const WAYBACK_SCRIPT_RE = /<script\b[^>]*\bsrc\s*=\s*["']?[^"'>\s]*(?:\/_static\/|wombat|archive\.org\/static\/)[^>]*>[\s\S]*?<\/script\s*>/gi; +const WM_INLINE_SCRIPT_RE = /<script\b[^>]*>(?:(?!<\/script)[\s\S])*?(?:__wm\.|wombat|_wb_wombat|WB_wombat)(?:(?!<\/script)[\s\S])*?<\/script\s*>/gi; +const WAYBACK_LINK_RE = /<link\b[^>]*\bhref\s*=\s*["']?[^"'>\s]*\/_static\/[^>]*>/gi; + +// The page with the Wayback Machine's own insertions taken out. +export function stripWaybackChrome(html: string): string { + return html + .replace(TOOLBAR_RE, "") + .replace(WAYBACK_SCRIPT_RE, "") + .replace(WM_INLINE_SCRIPT_RE, "") + .replace(WAYBACK_LINK_RE, ""); +} + +// A Wayback-rewritten href (`/web/<ts>[mod]/<original>`, on or off the +// archive's host) as the original URL it points at; any other href as given. +export function unrewriteWaybackUrl(href: string): string { + const h = href.trim(); + let abs: string | null = null; + if (/^\/web\/\d{1,14}/i.test(h)) abs = `https://web.archive.org${h}`; + else if (/^\/\/(?:web|wayback)\.archive\.org\//i.test(h)) abs = `https:${h}`; + else if (/^https?:\/\/(?:web|wayback)\.archive\.org\/web\/\d{1,14}/i.test(h)) abs = h; + if (!abs) return h; + return parseWaybackUrl(abs)?.originalUrl ?? h; +} + +// An href as an absolute http(s) URL of the original web, or null. +export function absoluteOriginalUrl(href: string | undefined, originalUrl: string): string | null { + if (!href) return null; + const h = unrewriteWaybackUrl(href); + if (!h || h.startsWith("#") || /^(?:javascript|mailto|tel|data|about):/i.test(h)) return null; + try { + const u = new URL(h, originalUrl); + if (u.protocol !== "http:" && u.protocol !== "https:") return null; + u.hash = ""; + return u.toString(); + } catch { + return null; + } +} + +// An image of the capture, as the Wayback Machine serves it. +export function waybackImageUrl(captureTs: string, src: string): string { + return `https://web.archive.org/web/${captureTs}im_/${src}`; +} + +// ─── The tree ─── + +const isEl = (n: HtmlNode): n is HtmlElement => typeof n !== "string"; + +function walk(el: HtmlElement, visit: (e: HtmlElement, parent: HtmlElement) => boolean | void): void { + for (const c of el.children) { + if (!isEl(c)) continue; + if (visit(c, el) === false) continue; + walk(c, visit); + } +} + +function findAll(el: HtmlElement, pred: (e: HtmlElement) => boolean, nested = true): HtmlElement[] { + const out: HtmlElement[] = []; + walk(el, (e) => { + if (pred(e)) { + out.push(e); + if (!nested) return false; + } + }); + return out; +} + +function first(el: HtmlElement, pred: (e: HtmlElement) => boolean): HtmlElement | null { + let hit: HtmlElement | null = null; + walk(el, (e) => { + if (hit) return false; + if (pred(e)) { + hit = e; + return false; + } + }); + return hit; +} + +function rawText(el: HtmlElement): string { + let s = ""; + for (const c of el.children) s += isEl(c) ? rawText(c) : c; + return s; +} + +const collapse = (s: string) => s.replace(/[\s ]+/g, " ").trim(); + +const DROP_TAGS = new Set([ + "head", "script", "style", "noscript", "template", "nav", "aside", "form", "iframe", "frame", "frameset", + "svg", "button", "select", "option", "input", "textarea", "canvas", "object", "embed", "menu", "dialog", + "link", "meta", +]); +const DROP_ROLES = new Set(["navigation", "banner", "contentinfo", "complementary", "search", "menu", "menubar", "dialog"]); + +function isHidden(e: HtmlElement): boolean { + if ("hidden" in e.attrs) return true; + if (e.attrs["aria-hidden"] === "true") return true; + return /display\s*:\s*none|visibility\s*:\s*hidden/i.test(e.attrs.style ?? ""); +} + +function isWaybackChrome(e: HtmlElement): boolean { + const id = e.attrs.id ?? ""; + return /^(?:wm-ipp|donato|wm-capinfo)/i.test(id); +} + +// The tree with the furniture pruned (a copy; the input is untouched). +function prune(el: HtmlElement, inArticle = false): HtmlElement { + const children: HtmlNode[] = []; + for (const c of el.children) { + if (!isEl(c)) { + children.push(c); + continue; + } + if (DROP_TAGS.has(c.tag) || isHidden(c) || isWaybackChrome(c)) continue; + if (DROP_ROLES.has((c.attrs.role ?? "").toLowerCase())) continue; + if (c.tag === "footer") continue; + if (c.tag === "header" && !inArticle) continue; + children.push(prune(c, inArticle || c.tag === "article")); + } + return { tag: el.tag, attrs: el.attrs, children }; +} + +// ─── Main content ─── + +const CANDIDATE_TAGS = new Set(["div", "section", "td", "body", "article", "main", "#root", "center", "font", "span"]); +const PARAGRAPH_TAGS = new Set(["p", "pre", "blockquote"]); + +function linkDensity(el: HtmlElement): number { + const all = collapse(rawText(el)).length; + if (all === 0) return 0; + let linked = 0; + for (const a of findAll(el, (e) => e.tag === "a", false)) linked += collapse(rawText(a)).length; + return Math.min(1, linked / all); +} + +function pickMain(root: HtmlElement): HtmlElement[] { + const main = first(root, (e) => e.tag === "main" || (e.attrs.role ?? "").toLowerCase() === "main"); + if (main) return [main]; + const articles = findAll(root, (e) => e.tag === "article", false); + if (articles.length > 0) return articles; + const parent = new Map<HtmlElement, HtmlElement>(); + const order: HtmlElement[] = []; + const scores = new Map<HtmlElement, number>(); + walk(root, (e, p) => { + parent.set(e, p); + order.push(e); + }); + for (const e of order) { + if (!PARAGRAPH_TAGS.has(e.tag)) continue; + const text = collapse(rawText(e)); + if (text.length < 25) continue; + const score = 1 + (text.match(/,/g)?.length ?? 0) + Math.min(Math.floor(text.length / 100), 3); + const p = parent.get(e); + if (p && CANDIDATE_TAGS.has(p.tag)) scores.set(p, (scores.get(p) ?? 0) + score); + const g = p ? parent.get(p) : undefined; + if (g && CANDIDATE_TAGS.has(g.tag)) scores.set(g, (scores.get(g) ?? 0) + score / 2); + } + let best: HtmlElement | null = null; + let bestScore = 0; + // Document order, and a strict `>`: the first of equal scores wins. + for (const e of [root, ...order]) { + const s = scores.get(e); + if (s === undefined) continue; + const final = s * (1 - linkDensity(e)); + if (final > bestScore) { + best = e; + bestScore = final; + } + } + if (best) return [best]; + const body = first(root, (e) => e.tag === "body"); + return [body ?? root]; +} + +// ─── Text ─── + +const BLOCK_TAGS = new Set([ + "p", "div", "section", "article", "main", "header", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li", + "blockquote", "pre", "table", "thead", "tbody", "tr", "dl", "dt", "dd", "figure", "figcaption", "address", + "hr", "center", "body", "#root", +]); + +type Ctx = { blocks: string[]; line: string[] }; + +function flush(ctx: Ctx): void { + const t = collapse(ctx.line.join("")); + if (t) ctx.blocks.push(t); + ctx.line = []; +} + +function renderChildren(el: HtmlElement, ctx: Ctx): void { + for (const c of el.children) renderNode(c, ctx); +} + +function sub(el: HtmlElement): string[] { + const ctx: Ctx = { blocks: [], line: [] }; + renderChildren(el, ctx); + flush(ctx); + return ctx.blocks; +} + +function renderNode(n: HtmlNode, ctx: Ctx): void { + if (!isEl(n)) { + ctx.line.push(n); + return; + } + switch (n.tag) { + case "br": + flush(ctx); + return; + case "img": { + const alt = collapse(n.attrs.alt ?? ""); + if (alt) ctx.line.push(` [Image: ${alt}] `); + return; + } + case "pre": { + flush(ctx); + const t = rawText(n).replace(/\r\n?/g, "\n").replace(/^\n+|\s+$/g, ""); + if (t) ctx.blocks.push(t); + return; + } + case "li": { + flush(ctx); + const t = sub(n).join(" "); + if (t) ctx.blocks.push(`- ${t}`); + return; + } + case "blockquote": { + flush(ctx); + for (const b of sub(n)) ctx.blocks.push(b.split("\n").map((l) => `> ${l}`).join("\n")); + return; + } + case "td": + case "th": + renderChildren(n, ctx); + ctx.line.push(" "); + return; + } + if (BLOCK_TAGS.has(n.tag)) { + flush(ctx); + renderChildren(n, ctx); + flush(ctx); + return; + } + renderChildren(n, ctx); +} + +function renderText(nodes: HtmlElement[]): string { + const blocks: string[] = []; + for (const n of nodes) { + const ctx: Ctx = { blocks: [], line: [] }; + renderNode(n, ctx); + flush(ctx); + blocks.push(...ctx.blocks); + } + return blocks.join("\n\n"); +} + +// ─── Metadata ─── + +type Meta = Map<string, string>; + +function readMeta(root: HtmlElement): Meta { + const meta: Meta = new Map(); + walk(root, (e) => { + if (e.tag !== "meta") return; + const key = (e.attrs.property ?? e.attrs.name ?? e.attrs.itemprop ?? "").trim().toLowerCase(); + const content = collapse(e.attrs.content ?? ""); + if (key && content && !meta.has(key)) meta.set(key, content); + }); + return meta; +} + +const JSON_LD_RE = /<script\b[^>]*\btype\s*=\s*["']?application\/ld\+json["']?[^>]*>([\s\S]*?)<\/script\s*>/gi; + +type LdFacts = { author?: string; datePublished?: string; headline?: string }; + +function readJsonLd(html: string): LdFacts { + const out: LdFacts = {}; + const nameOf = (a: unknown): string | undefined => { + if (typeof a === "string") return collapse(a) || undefined; + if (Array.isArray(a)) return a.map(nameOf).find(Boolean); + if (a && typeof a === "object") return nameOf((a as Record<string, unknown>).name); + return undefined; + }; + const visit = (v: unknown): void => { + if (Array.isArray(v)) return v.forEach(visit); + if (!v || typeof v !== "object") return; + const o = v as Record<string, unknown>; + if (!out.datePublished && typeof o.datePublished === "string") out.datePublished = o.datePublished; + if (!out.author && o.author !== undefined) out.author = nameOf(o.author); + if (!out.headline && typeof o.headline === "string") out.headline = collapse(o.headline) || undefined; + if (o["@graph"]) visit(o["@graph"]); + }; + for (const m of html.matchAll(JSON_LD_RE)) { + try { + visit(JSON.parse(m[1].trim())); + } catch { + // A malformed block says nothing. + } + } + return out; +} + +// A date the page gives, as ISO-8601, or undefined: unparseable, or after the +// capture (a page cannot have been written after it was captured; a +// "modified" date some templates fill with the render time is not believed). +function believableDate(raw: string | undefined, captureTs: string): string | undefined { + if (!raw) return undefined; + const ms = Date.parse(raw.trim()); + if (!Number.isFinite(ms)) return undefined; + const cap = Date.parse(captureTsIso(captureTs)); + if (Number.isFinite(cap) && ms > cap + 24 * 3600 * 1000) return undefined; + if (ms < Date.UTC(1990, 0, 1)) return undefined; + return new Date(ms).toISOString(); +} + +const isUrlish = (s: string) => /^https?:\/\//i.test(s); + +// ─── The extractor ─── + +export function extractGeneric(input: PageExtractInput): PageRecordDraft { + const { capture } = input; + const mime = bareMimetype(capture.mimetype); + if (mime === "text/plain" || mime === "application/json") { + const text = input.html.replace(/\r\n?/g, "\n").trim(); + return text + ? { kind: "generic", text, links: [] } + : { kind: "generic", text: NO_CONTENT_TEXT, links: [], noContent: true }; + } + const html = stripWaybackChrome(input.html); + const root = parseHtml(html); + const meta = readMeta(root); + const ld = readJsonLd(html); + + const titleEl = first(root, (e) => e.tag === "title"); + const h1 = first(root, (e) => e.tag === "h1"); + const title = + meta.get("og:title") ?? + (titleEl ? collapse(rawText(titleEl)) || undefined : undefined) ?? + (h1 ? collapse(rawText(h1)) || undefined : undefined) ?? + ld.headline; + + const pruned = prune(root); + const main = pickMain(pruned); + + const authorCandidates = [ + ld.author, + meta.get("author"), + meta.get("article:author"), + meta.get("dc.creator"), + meta.get("twitter:creator"), + ].filter((a): a is string => !!a && !isUrlish(a)); + const author = authorCandidates[0]; + + let timeAttr: string | undefined; + for (const n of main) { + const t = first(n, (e) => e.tag === "time" && !!e.attrs.datetime); + if (t) { + timeAttr = t.attrs.datetime; + break; + } + } + const dateCandidates = [ + meta.get("article:published_time"), + meta.get("og:published_time"), + meta.get("datepublished"), + meta.get("date"), + meta.get("pubdate"), + meta.get("publishdate"), + meta.get("dc.date.issued"), + meta.get("dc.date"), + ld.datePublished, + timeAttr, + ]; + let publishedAt: string | undefined; + for (const d of dateCandidates) { + publishedAt = believableDate(d, capture.captureTs); + if (publishedAt) break; + } + + let text = renderText(main); + if (title && text && !collapse(text.slice(0, title.length + 20)).startsWith(collapse(title))) { + text = `${title}\n\n${text}`; + } + + const links: string[] = []; + const seenLinks = new Set<string>(); + const media: PostMedia[] = []; + const seenMedia = new Set<string>(); + for (const n of main) { + walk(n, (e) => { + if (e.tag === "a" && links.length < MAX_LINKS) { + const abs = absoluteOriginalUrl(e.attrs.href, capture.originalUrl); + if (abs && !seenLinks.has(abs)) { + seenLinks.add(abs); + links.push(abs); + } + } + if (e.tag === "img" && media.length < MAX_MEDIA) { + const abs = absoluteOriginalUrl(e.attrs.src ?? e.attrs["data-src"], capture.originalUrl); + if (abs && !seenMedia.has(abs)) { + seenMedia.add(abs); + const alt = collapse(e.attrs.alt ?? ""); + media.push({ kind: "image", url: waybackImageUrl(capture.captureTs, abs), ...(alt ? { name: alt } : {}) }); + } + } + }); + } + + const draft: PageRecordDraft = { + kind: "generic", + text: text || NO_CONTENT_TEXT, + links, + }; + if (!text) draft.noContent = true; + if (title) draft.title = title; + // A page's author is a name, not a handle: `author` alone (a reader shows + // "@author" only beside an authorName). + if (author) draft.author = author.replace(/^@/, ""); + if (publishedAt) draft.publishedAt = publishedAt; + if (media.length > 0) draft.media = media; + return draft; +} + +export const genericExtractor: PageExtractor = { + name: GENERIC_EXTRACTOR_NAME, + version: GENERIC_EXTRACTOR_VERSION, + matches: () => true, + extract: (input) => [extractGeneric(input)], +}; diff --git a/common/lib/waybackPages/extractors/tumblr.ts b/common/lib/waybackPages/extractors/tumblr.ts @@ -9,7 +9,7 @@ // A page holding no post (an about or ask page) → one whole-page // `tumblr-index` draft with the page's text. -import type { PostRef, PostPlatform } from "../../posts"; +import type { PostRef } from "../../posts"; import type { PageExtractInput, PageExtractor, PageRecordDraft } from "../types"; import { absoluteUrl, @@ -31,9 +31,8 @@ import { type HtmlElement, } from "./util"; -// Lane A registers "webpage" as a PostPlatform; a reblog points at another -// page record, so its ref is on that platform. -const WEBPAGE = "webpage" as PostPlatform; +// A reblog points at another page record, so its ref is on that platform. +const WEBPAGE = "webpage" as const; const NOT_BLOGS = /^(www|assets|static|api|secure|media|data|vt|va|vtt|\d+\.media|[a-z0-9]+\.media)\.tumblr\.com$/; diff --git a/common/lib/waybackPages/parse.ts b/common/lib/waybackPages/parse.ts @@ -0,0 +1,66 @@ +// Runtime validation for `Post.page` (a page record's capture facts) read back +// off disk or off the wire. The parsePost stance: unknown keys dropped, and a +// `page` missing its provenance or its extractor is dropped WHOLE — never the +// post, never repaired. Client-safe: types only from ./types (whose urlHash is +// node:crypto), so this file pulls nothing node into a browser bundle. + +import type { PageKind, PagePostInfo } from "./types"; + +const TS_RE = /^\d{4,14}$/; +// A kind is a short lowercase word. Not checked against PAGE_KINDS on +// purpose: a record made by a newer extractor stays readable by an older +// reader (it shows as a page, its kind as written). +const KIND_RE = /^[a-z][a-z0-9-]{0,39}$/; + +const str = (v: unknown): string | undefined => (typeof v === "string" && v ? v : undefined); + +export function parsePagePostInfo(raw: unknown): PagePostInfo | null { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const r = raw as Record<string, unknown>; + const originalUrl = str(r.originalUrl); + const captureTs = str(r.captureTs); + const waybackUrl = str(r.waybackUrl); + const rawUrl = str(r.rawUrl); + const kind = str(r.kind); + const extractor = str(r.extractor); + const extractorVersion = r.extractorVersion; + if (!originalUrl || !captureTs || !TS_RE.test(captureTs) || !waybackUrl || !rawUrl) return null; + if (!kind || !KIND_RE.test(kind) || !extractor) return null; + if (typeof extractorVersion !== "number" || !Number.isInteger(extractorVersion) || extractorVersion < 0) return null; + const out: PagePostInfo = { + originalUrl, + captureTs, + waybackUrl, + rawUrl, + kind: kind as PageKind, + extractor, + extractorVersion, + }; + const title = str(r.title); + if (title) out.title = title; + const mimetype = str(r.mimetype); + if (mimetype) out.mimetype = mimetype; + const digest = str(r.digest); + if (digest) out.digest = digest; + if (typeof r.status === "number" && Number.isInteger(r.status) && r.status >= 100 && r.status < 600) out.status = r.status; + const publishedAt = str(r.publishedAt); + if (publishedAt && Number.isFinite(Date.parse(publishedAt))) out.publishedAt = publishedAt; + const firstSeenTs = str(r.firstSeenTs); + if (firstSeenTs && TS_RE.test(firstSeenTs)) out.firstSeenTs = firstSeenTs; + const versionOf = str(r.versionOf); + if (versionOf) out.versionOf = versionOf; + if (r.noContent === true) out.noContent = true; + const fb = r.extractorFallback; + if (fb && typeof fb === "object" && !Array.isArray(fb)) { + const f = fb as Record<string, unknown>; + const from = str(f.from); + if (from && typeof f.fromVersion === "number" && Number.isInteger(f.fromVersion)) { + out.extractorFallback = { from, fromVersion: f.fromVersion, error: typeof f.error === "string" ? f.error : "" }; + } + } + if (Array.isArray(r.tags)) { + const tags = r.tags.filter((t): t is string => typeof t === "string" && t.trim() !== ""); + if (tags.length > 0) out.tags = tags; + } + return out; +} diff --git a/common/lib/waybackPages/store-server.ts b/common/lib/waybackPages/store-server.ts @@ -0,0 +1,171 @@ +// THE CAPTURES A WAYBACK PAGES CHANNEL HOLDS (release 37 S1), on disk beside +// its posts: +// +// channels/<slug>/pages/<captureTs>-<urlHash>/raw.html.gz the body as captured (gzip) +// channels/<slug>/pages/<captureTs>-<urlHash>/capture.json what it is (StoredCapture) +// +// The directory name is pageRecordId(captureTs, originalUrl) — a whole-page +// record's id. TEXT, on the corpus disk: `pages/` is at the channel's root, +// never under `data/<id>/`, so the media tier (lib/mediaTier.ts, which names +// files inside a video dir) never moves it; a channel rename moves it with the +// channel. The raw body is kept so a better extractor re-derives every record +// offline (`archilyzer wayback pages reextract`), with no request. +// +// Writes are atomic (tmp + rename), the body first: a capture.json is only +// ever beside a whole body, so a capture.json IS a stored capture. + +import path from "node:path"; +import { mkdir, readdir, readFile, rename, writeFile } from "node:fs/promises"; +import { gunzipSync, gzipSync } from "node:zlib"; +import { writeJsonAtomic } from "../jsonFile-server"; +import { pageRecordId } from "./types"; + +export const PAGES_DIRNAME = "pages"; +export const PAGE_RAW_FILENAME = "raw.html.gz"; +export const PAGE_CAPTURE_FILENAME = "capture.json"; + +export type StoredCapture = { + originalUrl: string; + captureTs: string; + digest?: string; + // The bare mimetype, and the Content-Type as served (its charset). + mimetype: string; + contentType?: string; + bytes: number; + sha256: string; + fetchedAt: string; + // What made the records, so a re-extract knows what is stale. + extractor: string; + extractorVersion: number; + extractorFallback?: { from: string; fromVersion: number; error: string }; + // The URL the import asked for, when the archive redirected it elsewhere + // (another timestamp, or the page the capture recorded a redirect to). + requestedTs?: string; + requestedUrl?: string; + // The record ids this capture made, at the last extraction. + records?: string[]; +}; + +export function channelPagesDir(channelRoot: string): string { + return path.join(channelRoot, PAGES_DIRNAME); +} + +export function pageCaptureDirName(captureTs: string, originalUrl: string): string { + return pageRecordId(captureTs, originalUrl); +} + +export function pageCaptureDir(channelRoot: string, captureTs: string, originalUrl: string): string { + return path.join(channelPagesDir(channelRoot), pageCaptureDirName(captureTs, originalUrl)); +} + +const NAME_RE = /^\d{4,14}-[0-9a-f]{12}$/; + +function parseStoredCapture(raw: unknown): StoredCapture | null { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const r = raw as Record<string, unknown>; + const s = (k: string) => (typeof r[k] === "string" && r[k] ? (r[k] as string) : undefined); + const originalUrl = s("originalUrl"); + const captureTs = s("captureTs"); + const mimetype = s("mimetype"); + const sha256 = s("sha256"); + const fetchedAt = s("fetchedAt"); + const extractor = s("extractor"); + if (!originalUrl || !captureTs || !/^\d{4,14}$/.test(captureTs) || !mimetype || !sha256 || !fetchedAt || !extractor) return null; + if (typeof r.bytes !== "number" || typeof r.extractorVersion !== "number") return null; + const out: StoredCapture = { + originalUrl, + captureTs, + mimetype, + bytes: r.bytes, + sha256, + fetchedAt, + extractor, + extractorVersion: r.extractorVersion, + }; + const digest = s("digest"); + if (digest) out.digest = digest; + const contentType = s("contentType"); + if (contentType) out.contentType = contentType; + const requestedTs = s("requestedTs"); + if (requestedTs) out.requestedTs = requestedTs; + const requestedUrl = s("requestedUrl"); + if (requestedUrl) out.requestedUrl = requestedUrl; + const fb = r.extractorFallback as Record<string, unknown> | undefined; + if (fb && typeof fb.from === "string" && typeof fb.fromVersion === "number") { + out.extractorFallback = { from: fb.from, fromVersion: fb.fromVersion, error: typeof fb.error === "string" ? fb.error : "" }; + } + if (Array.isArray(r.records)) out.records = r.records.filter((x): x is string => typeof x === "string"); + return out; +} + +// Whether the capture is already stored (its capture.json is there). +export async function hasStoredCapture(channelRoot: string, captureTs: string, originalUrl: string): Promise<boolean> { + return (await readStoredCapture(pageCaptureDir(channelRoot, captureTs, originalUrl))) !== null; +} + +export async function readStoredCapture(dir: string): Promise<StoredCapture | null> { + try { + return parseStoredCapture(JSON.parse(await readFile(path.join(dir, PAGE_CAPTURE_FILENAME), "utf8"))); + } catch { + return null; + } +} + +// Store one capture: the body (gzip), then its capture.json. Answers the +// directory. +export async function writeStoredCapture( + channelRoot: string, + capture: StoredCapture, + body: Buffer, +): Promise<string> { + const dir = pageCaptureDir(channelRoot, capture.captureTs, capture.originalUrl); + await mkdir(dir, { recursive: true }); + const raw = path.join(dir, PAGE_RAW_FILENAME); + const tmp = `${raw}.tmp-${process.pid}-${Date.now()}`; + await writeFile(tmp, gzipSync(body)); + await rename(tmp, raw); + await writeJsonAtomic(path.join(dir, PAGE_CAPTURE_FILENAME), capture); + return dir; +} + +// Rewrite a stored capture's capture.json (after a re-extract). +export async function updateStoredCapture(dir: string, capture: StoredCapture): Promise<void> { + await writeJsonAtomic(path.join(dir, PAGE_CAPTURE_FILENAME), capture); +} + +export async function readStoredCaptureBody(dir: string): Promise<Buffer> { + return gunzipSync(await readFile(path.join(dir, PAGE_RAW_FILENAME))); +} + +export type StoredCaptureEntry = { dir: string; name: string; capture: StoredCapture }; + +// Every stored capture of a channel, oldest capture first (then by name). A +// directory with no readable capture.json (an interrupted write) is skipped. +export async function listStoredCaptures(channelRoot: string): Promise<StoredCaptureEntry[]> { + const root = channelPagesDir(channelRoot); + let names: string[]; + try { + names = (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name); + } catch { + return []; + } + const out: StoredCaptureEntry[] = []; + for (const name of names.filter((n) => NAME_RE.test(n)).sort()) { + const dir = path.join(root, name); + const capture = await readStoredCapture(dir); + if (capture) out.push({ dir, name, capture }); + } + return out.sort( + (a, b) => + a.capture.captureTs.padEnd(14, "0").localeCompare(b.capture.captureTs.padEnd(14, "0")) || a.name.localeCompare(b.name), + ); +} + +// How many captures a channel holds (a readdir; no capture.json is read). +export async function countStoredCaptures(channelRoot: string): Promise<number> { + try { + return (await readdir(channelPagesDir(channelRoot))).filter((n) => NAME_RE.test(n)).length; + } catch { + return 0; + } +} diff --git a/common/lib/waybackPages/toPost.test.ts b/common/lib/waybackPages/toPost.test.ts @@ -0,0 +1,162 @@ +// Release 37 S1: a draft as a page record, the split-record merge through +// upsertPosts, versions of one page, and parsePost keeping (or dropping) a +// record's `page`. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/toPost.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { assignPageVersions, draftToPost, isWholePageRecord, mergePageRecord } from "./toPost"; +import { pageRecordId, pageThreadId, type PageRecordDraft } from "./types"; +import { parsePost, postPlatformLabel, isPostPlatform, type Post } from "../posts"; +import { readAllPosts, replaceChannelPosts, upsertPosts, countPosts } from "../posts-server"; + +const URL_A = "https://blog.example/2014/03/a-post.html"; +const ctx = (captureTs: string, originalUrl = URL_A, extra: Partial<Parameters<typeof draftToPost>[1]> = {}) => ({ + channelSlug: "old-blog", + capture: { originalUrl, captureTs, mimetype: "text/html" }, + extractor: { name: "generic", version: 1 }, + ...extra, +}); +const draft = (over: Partial<PageRecordDraft> = {}): PageRecordDraft => ({ kind: "generic", text: "Words.", links: [], ...over }); + +test("a whole-page draft: id, dates, author, url, thread and provenance", () => { + const p = draftToPost(draft({ title: "A Post", publishedAt: "2014-03-04T18:30:00Z" }), ctx("20140305120000")); + assert.equal(p.id, pageRecordId("20140305120000", URL_A)); + assert.equal(p.slug, `old-blog/${p.id}`); + assert.equal(p.platform, "webpage"); + assert.equal(p.createdAt, "2014-03-04T18:30:00.000Z"); + assert.equal(p.uploadDate, "20140304"); + assert.equal(p.author, "blog.example"); + assert.equal(p.url, URL_A); + assert.equal(p.threadId, pageThreadId(URL_A)); + assert.deepEqual(p.page, { + originalUrl: URL_A, + captureTs: "20140305120000", + waybackUrl: `https://web.archive.org/web/20140305120000/${URL_A}`, + rawUrl: `https://web.archive.org/web/20140305120000id_/${URL_A}`, + kind: "generic", + extractor: "generic", + extractorVersion: 1, + title: "A Post", + mimetype: "text/html", + publishedAt: "2014-03-04T18:30:00.000Z", + }); + assert.equal(isWholePageRecord(p), true); + // No date of its own: the capture time is when it was said, as best known. + const undated = draftToPost(draft(), ctx("20140305120000")); + assert.equal(undated.createdAt, "2014-03-05T12:00:00.000Z"); + // A fallback is on the record. + const fb = draftToPost(draft(), ctx("2014", URL_A, { fallback: { from: "tumblr", fromVersion: 2, error: "x" } })); + assert.deepEqual(fb.page?.extractorFallback, { from: "tumblr", fromVersion: 2, error: "x" }); +}); + +test("an item draft keeps its own id and url; a tweet keeps X's thread ids", () => { + const item = draftToPost(draft({ kind: "tumblr-post", itemId: "tumblr-77", url: "https://b.example/post/77", author: "b" }), ctx("20140101000000")); + assert.equal(item.id, "tumblr-77"); + assert.equal(item.url, "https://b.example/post/77"); + assert.equal(item.author, "b"); + assert.equal(item.page?.firstSeenTs, "20140101000000"); + assert.equal(isWholePageRecord(item), false); + const tweet = draftToPost(draft({ kind: "tweet", itemId: "tweet-1001", url: "https://twitter.com/s/status/1001" }), ctx("2014", "https://twitter.com/s")); + assert.equal(tweet.threadId, "1001"); + const reply = draftToPost( + draft({ kind: "tweet", itemId: "tweet-1002", replyTo: { platform: "twitter", id: "1001" } }), + ctx("2014", "https://twitter.com/s"), + ); + assert.equal(reply.threadId, "1001"); + assert.equal(reply.isReply, true); +}); + +test("parsePost keeps a page record's page, drops a malformed page (never the post); the platform reads as a Web page", () => { + const p = draftToPost(draft({ title: "T" }), ctx("20140305120000")); + const back = parsePost(JSON.parse(JSON.stringify(p))); + assert.deepEqual(back?.page, p.page); + assert.equal(back?.url, URL_A); + const broken = parsePost({ ...JSON.parse(JSON.stringify(p)), page: { originalUrl: URL_A, kind: "generic" } }); + assert.ok(broken); + assert.equal(broken!.page, undefined); + // A record with no url of its own takes its page's original. + const { url: _u, ...noUrl } = JSON.parse(JSON.stringify(p)); + assert.equal(parsePost(noUrl)?.url, URL_A); + assert.equal(isPostPlatform("webpage"), true); + assert.equal(postPlatformLabel("webpage"), "Web page"); +}); + +test("the split-record merge: the later capture's facts, the first capture kept", () => { + const first = draftToPost(draft({ kind: "tumblr-post", itemId: "tumblr-77", text: "v1" }), ctx("20140101000000")); + const later = draftToPost(draft({ kind: "tumblr-post", itemId: "tumblr-77", text: "v2" }), ctx("20150101000000")); + const m = mergePageRecord(first, later)!; + assert.equal(m.text, "v2"); + assert.equal(m.page?.captureTs, "20150101000000"); + assert.equal(m.page?.firstSeenTs, "20140101000000"); + // An earlier capture arriving after a later one replaces nothing but the + // first sighting. + const m2 = mergePageRecord(later, first)!; + assert.equal(m2.text, "v2"); + assert.equal(m2.page?.captureTs, "20150101000000"); + assert.equal(m2.page?.firstSeenTs, "20140101000000"); + // The same capture again: unchanged. + assert.equal(mergePageRecord(first, draftToPost(draft({ kind: "tumblr-post", itemId: "tumblr-77", text: "v1" }), ctx("20140101000000"))), null); +}); + +test("versions of one page: every later whole-page capture names the first", () => { + const a = draftToPost(draft(), ctx("20140305120000")); + const b = draftToPost(draft(), ctx("20150611090000")); + const c = draftToPost(draft(), ctx("20130101000000")); + const other = draftToPost(draft(), ctx("20150611090000", "https://blog.example/other")); + const changed = new Map(assignPageVersions([a, b, other]).map((p) => [p.id, p.page?.versionOf])); + assert.deepEqual([...changed], [[b.id, a.id]]); + const again = new Map(assignPageVersions([{ ...a }, { ...b, page: { ...b.page!, versionOf: a.id } }, c]).map((p) => [p.id, p.page?.versionOf])); + assert.deepEqual(again.get(a.id), c.id); + assert.deepEqual(again.get(b.id), c.id); + assert.equal(again.has(c.id), false); +}); + +test("upsertPosts: an item seen in a later capture is ONE record, updated in place; the same capture again changes nothing", async () => { + // The directory IS the channel (readPostShard re-derives the slug from it). + const tmp = await mkdtemp(path.join(tmpdir(), "page-upsert-")); + const root = path.join(tmp, "old-blog"); + try { + const first = draftToPost(draft({ kind: "tumblr-post", itemId: "tumblr-77", text: "v1", publishedAt: "2013-06-01T00:00:00Z" }), ctx("20140101000000")); + const whole = draftToPost(draft({ text: "index page" }), ctx("20140101000000")); + const r1 = await upsertPosts(root, [first, whole]); + assert.equal(r1.written, 2); + const again = await upsertPosts(root, [first, whole]); + assert.equal(again.written, 0); + assert.equal(again.updated, 0); + assert.equal(again.unchanged, 2); + const later = draftToPost(draft({ kind: "tumblr-post", itemId: "tumblr-77", text: "v2", publishedAt: "2013-06-01T00:00:00Z" }), ctx("20150101000000")); + const r2 = await upsertPosts(root, [later]); + assert.equal(r2.updated, 1); + const all = await readAllPosts(root); + assert.equal(all.length, 2); + const item = all.find((p) => p.id === "tumblr-77")!; + assert.equal(item.text, "v2"); + assert.equal(item.page?.firstSeenTs, "20140101000000"); + assert.equal(item.createdAt, "2013-06-01T00:00:00.000Z"); + assert.equal(await countPosts(root), 2); + } finally { + await rm(tmp, { recursive: true, force: true }); + } +}); + +test("replaceChannelPosts: the store rewritten whole — a record may move month, an id may go, the archive matches", async () => { + const root = await mkdtemp(path.join(tmpdir(), "page-replace-")); + try { + const a = draftToPost(draft(), ctx("20140305120000")); + const b = draftToPost(draft(), ctx("20150611090000", "https://blog.example/other")); + await upsertPosts(root, [a, b]); + const moved: Post = { ...a, createdAt: "2013-01-02T00:00:00.000Z", uploadDate: "20130102" }; + const res = await replaceChannelPosts(root, [moved]); + assert.deepEqual(res.shards, ["2013-01"]); + const all = await readAllPosts(root); + assert.deepEqual(all.map((p) => [p.id, p.createdAt]), [[a.id, "2013-01-02T00:00:00.000Z"]]); + assert.equal(await countPosts(root), 1); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/common/lib/waybackPages/toPost.ts b/common/lib/waybackPages/toPost.ts @@ -0,0 +1,196 @@ +// DRAFT → POST (release 37 S1): what an extractor read from a capture, as the +// page record the posts store keeps (platform "webpage", `Post.page`), and the +// rules that make the same item seen in two captures ONE record. +// +// id the draft's `itemId` (an item inside a capture: "tumblr-<id>", +// "tweet-<id>"), else pageRecordId(captureTs, originalUrl) — one +// captured state of one page. +// createdAt the content's own date (`publishedAt`), else the capture time: +// the sort key is when it was said, not when the crawler came by. +// author the draft's author, else the page's host (no "www."). +// url the item's own permalink, else the capture's original URL. +// threadId pageThreadId(originalUrl), so a page's versions group as one +// thread; a tweet keeps X's thread ids (its status id, or the +// status it answers) so it joins the X records of the same talk. +// +// Pure (no I/O). pageRecordId/urlHash are node:crypto, so server-side only. + +import { parsePost, uploadDateFromCreatedAt, type Post } from "../posts"; +import { waybackPageUrl, waybackRawUrl } from "../wayback"; +import { pageRecordId, pageThreadId, type PagePostInfo, type PageRecordDraft } from "./types"; +import { captureTsIso } from "./urls"; + +// The capture a draft came from: its provenance and what is known about it. +export type PageCaptureFacts = { + originalUrl: string; + captureTs: string; + mimetype?: string; + digest?: string; + status?: number; + title?: string; +}; + +export type DraftToPostContext = { + channelSlug: string; + capture: PageCaptureFacts; + extractor: { name: string; version: number }; + fallback?: { from: string; fromVersion: number; error: string }; +}; + +function hostOf(url: string): string { + try { + return new URL(url).hostname.toLowerCase().replace(/^www\./, ""); + } catch { + return ""; + } +} + +function tweetStatusId(draft: PageRecordDraft): string | undefined { + const fromItem = /^tweet-(\d+)$/.exec(draft.itemId ?? "")?.[1]; + if (fromItem) return fromItem; + return /\/status(?:es)?\/(\d+)/.exec(draft.url ?? "")?.[1]; +} + +export function draftToPost(draft: PageRecordDraft, ctx: DraftToPostContext): Post { + const { capture } = ctx; + const whole = !draft.itemId; + const id = draft.itemId ?? pageRecordId(capture.captureTs, capture.originalUrl); + const published = draft.publishedAt && Number.isFinite(Date.parse(draft.publishedAt)) + ? new Date(Date.parse(draft.publishedAt)).toISOString() + : undefined; + const createdAt = published ?? (captureTsIso(capture.captureTs) || new Date(0).toISOString()); + const ref = { captureTs: capture.captureTs, originalUrl: capture.originalUrl }; + const page: PagePostInfo = { + originalUrl: capture.originalUrl, + captureTs: capture.captureTs, + waybackUrl: waybackPageUrl(ref), + rawUrl: waybackRawUrl(ref), + kind: draft.kind, + extractor: ctx.extractor.name, + extractorVersion: ctx.extractor.version, + }; + const title = draft.title ?? capture.title; + if (title) page.title = title; + if (capture.mimetype) page.mimetype = capture.mimetype; + if (capture.digest) page.digest = capture.digest; + if (capture.status) page.status = capture.status; + if (published) page.publishedAt = published; + // An item seen in a capture: its first sighting, kept through later ones. + if (!whole) page.firstSeenTs = capture.captureTs; + if (draft.noContent) page.noContent = true; + if (draft.tags?.length) page.tags = [...draft.tags]; + if (ctx.fallback) page.extractorFallback = { ...ctx.fallback }; + + let threadId = pageThreadId(capture.originalUrl); + if (draft.kind === "tweet") { + const status = tweetStatusId(draft); + threadId = draft.replyTo?.id ?? status ?? threadId; + } + + const post: Post = { + id, + slug: `${ctx.channelSlug}/${id}`, + channelSlug: ctx.channelSlug, + author: draft.author || hostOf(capture.originalUrl), + createdAt, + uploadDate: uploadDateFromCreatedAt(createdAt), + text: draft.text, + url: draft.url || capture.originalUrl, + platform: "webpage", + threadId, + isReply: draft.isReply === true || !!draft.replyTo, + isRepost: draft.isRepost === true || !!draft.repostOf, + links: [...draft.links], + page, + }; + if (draft.authorName) post.authorName = draft.authorName; + if (draft.media?.length) { + post.media = draft.media.map((m) => ({ ...m })); + post.mediaCount = draft.media.length; + } + if (draft.replyTo) post.replyTo = { ...draft.replyTo }; + if (draft.quoted) post.quoted = { ...draft.quoted }; + if (draft.repostOf) post.repostOf = { ...draft.repostOf }; + if (draft.forum) post.forum = { ...draft.forum }; + return post; +} + +// A record as JSON with its keys sorted at every level: two records that say +// the same thing compare equal whichever writer built them (parsePost and +// draftToPost add keys in different orders). +export function stableRecordJson(v: unknown): string { + return JSON.stringify(v, (_k, val: unknown) => + val && typeof val === "object" && !Array.isArray(val) + ? Object.fromEntries(Object.entries(val as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) + : val, + ); +} + +// A record as a reader reads it back (parsePost over its JSON): what to +// compare a freshly made record against a stored one by. +export function asStored(p: Post): Post { + return parsePost(JSON.parse(JSON.stringify(p))) ?? p; +} + +// Whether a page record is a WHOLE page (one captured state of one page), as +// opposed to an item a capture holds. +export function isWholePageRecord(post: Pick<Post, "id" | "page">): boolean { + return !!post.page && post.id === pageRecordId(post.page.captureTs, post.page.originalUrl); +} + +const minTs = (a: string, b: string) => (a.length === b.length ? (a < b ? a : b) : a.padEnd(14, "0") < b.padEnd(14, "0") ? a : b); + +// THE SPLIT-RECORD MERGE: `incoming` is a record of an id already held as +// `stored`. The LATER capture's facts win (a capture of the same time or later +// replaces the fields; an earlier one replaces nothing), `page.firstSeenTs` +// is the earliest capture either has seen the item in, and `page.versionOf` +// survives a record that does not carry it. Answers the record to store, or +// null when it is the stored one unchanged. The stored createdAt (and so its +// month shard) is kept, as for every upsert: the JSONL is append-only and a +// reader takes an id's last line. +export function mergePageRecord(stored: Post, incoming: Post): Post | null { + if (!stored.page || !incoming.page) return null; + const sp = stored.page; + const ip = incoming.page; + const firstSeen = minTs(sp.firstSeenTs ?? sp.captureTs, ip.firstSeenTs ?? ip.captureTs); + const laterOrSame = minTs(sp.captureTs, ip.captureTs) === sp.captureTs; + const base = laterOrSame ? incoming : stored; + const merged: Post = { + ...base, + createdAt: stored.createdAt, + uploadDate: stored.uploadDate, + page: { ...base.page! }, + }; + if (!isWholePageRecord(merged) || sp.firstSeenTs || ip.firstSeenTs) merged.page!.firstSeenTs = firstSeen; + const versionOf = base.page!.versionOf ?? (laterOrSame ? sp.versionOf : ip.versionOf); + if (versionOf && versionOf !== merged.id) merged.page!.versionOf = versionOf; + return stableRecordJson(asStored(merged)) === stableRecordJson(asStored(stored)) ? null : merged; +} + +// VERSIONS OF ONE PAGE: every whole-page record of an original URL but the +// earliest names the earliest as `page.versionOf` (and the earliest names +// none). Over `records` (the channel's page records, any order); answers the +// records whose `versionOf` this changes, already changed (copies). +export function assignPageVersions(records: readonly Post[]): Post[] { + const byUrl = new Map<string, Post[]>(); + for (const p of records) { + if (!isWholePageRecord(p)) continue; + const list = byUrl.get(p.page!.originalUrl); + if (list) list.push(p); + else byUrl.set(p.page!.originalUrl, [p]); + } + const changed: Post[] = []; + for (const list of byUrl.values()) { + list.sort((a, b) => a.page!.captureTs.padEnd(14, "0").localeCompare(b.page!.captureTs.padEnd(14, "0"))); + const firstId = list[0].id; + for (const [i, p] of list.entries()) { + const want = i === 0 ? undefined : firstId; + if (p.page!.versionOf === want) continue; + const page = { ...p.page! }; + if (want) page.versionOf = want; + else delete page.versionOf; + changed.push({ ...p, page }); + } + } + return changed; +} diff --git a/common/lib/waybackPages/types.ts b/common/lib/waybackPages/types.ts @@ -49,6 +49,9 @@ export type PagePostInfo = WaybackProvenance & { // what is stale. extractor: string; extractorVersion: number; + // The site extractor that claimed the capture and threw: the record is the + // generic extractor's, and says which one failed and why (release 37 S1). + extractorFallback?: { from: string; fromVersion: number; error: string }; // Tags the page gives the item (Tumblr tags). tags?: string[]; }; diff --git a/common/lib/waybackPages/urls.ts b/common/lib/waybackPages/urls.ts @@ -0,0 +1,164 @@ +// What a Wayback pages import is asked for, read from what a person types: a +// capture's replay URL (web.archive.org/web/<ts>[mod]/<original>), or an +// original URL and a date (`at`, "YYYYMMDD[hhmmss]") for the capture nearest +// it. Client-safe: no node imports. + +import { isWaybackHost, parseWaybackUrl } from "../wayback"; + +// The bodies a page import keeps. Anything else is refused by its mimetype. +export const PAGE_MIMETYPES = ["text/html", "text/plain", "application/json"] as const; + +// The bare mimetype of a Content-Type ("text/html; charset=utf-8" → "text/html"). +export function bareMimetype(contentType: string | null | undefined): string { + return (contentType ?? "").split(";")[0].trim().toLowerCase(); +} + +export function isPageMimetype(contentType: string | null | undefined): boolean { + return (PAGE_MIMETYPES as readonly string[]).includes(bareMimetype(contentType)); +} + +// "YYYYMMDD[hhmmss]" — or any whole-unit prefix of a Wayback timestamp +// (yyyy, yyyyMM, … yyyyMMddhhmmss). +export function isCaptureAt(v: string): boolean { + return /^\d{4}(?:\d{2}){0,5}$/.test(v); +} + +// A Wayback timestamp (4–14 digits) as an ISO-8601 instant, UTC; the missing +// units are the start of the period. "" for one that is not a real time. +export function captureTsIso(ts: string): string { + if (!/^\d{4,14}$/.test(ts)) return ""; + const p = ts + "00000101000000".slice(ts.length); + const [y, mo, d, h, mi, s] = [p.slice(0, 4), p.slice(4, 6), p.slice(6, 8), p.slice(8, 10), p.slice(10, 12), p.slice(12, 14)]; + const iso = `${y}-${mo}-${d}T${h}:${mi}:${s}.000Z`; + const ms = Date.parse(iso); + if (!Number.isFinite(ms)) return ""; + // Date.parse rolls 2014-02-31 over to March; a timestamp that does that is + // not a real time. + return new Date(ms).toISOString() === iso ? iso : ""; +} + +export type PageCaptureAsk = + // One capture, by its timestamp (as the URL gives it: 4–14 digits; the + // Wayback Machine answers a short one with the nearest capture). + | { kind: "capture"; captureTs: string; originalUrl: string } + // The capture of `originalUrl` nearest `at`, found through the CDX API. + | { kind: "nearest"; at: string; originalUrl: string }; + +export const NOT_A_CAPTURE_URL = + "give a Wayback Machine capture's URL (https://web.archive.org/web/<timestamp>/<page>), " + + 'or the page\'s own URL and a date ("at": YYYYMMDD)'; + +// What `{url, at?}` asks for, or the sentence why it asks for nothing. +export function parsePageCaptureAsk( + url: string, + at?: string, +): { ok: true; ask: PageCaptureAsk } | { ok: false; error: string } { + const given = url.trim(); + const when = (at ?? "").trim(); + if (!given) return { ok: false, error: NOT_A_CAPTURE_URL }; + let u: URL; + try { + u = new URL(given); + } catch { + return { ok: false, error: `"${given}" is not a URL: ${NOT_A_CAPTURE_URL}` }; + } + if (u.protocol !== "http:" && u.protocol !== "https:") { + return { ok: false, error: `"${given}" is not an http(s) URL: ${NOT_A_CAPTURE_URL}` }; + } + if (when && !isCaptureAt(when)) { + return { ok: false, error: `"at" must be a date as YYYYMMDD (or YYYYMMDDhhmmss), not "${when}"` }; + } + if (isWaybackHost(u.hostname)) { + const ref = parseWaybackUrl(given); + if (!ref) { + return { + ok: false, + error: `${given} is a Wayback Machine listing, not one capture: ${NOT_A_CAPTURE_URL}`, + }; + } + if (when) { + return { ok: false, error: `"at" goes with a page's own URL; ${given} already names its capture (${ref.captureTs})` }; + } + return { ok: true, ask: { kind: "capture", captureTs: ref.captureTs, originalUrl: ref.originalUrl } }; + } + if (!when) { + return { ok: false, error: `${given} is not a Wayback Machine capture: ${NOT_A_CAPTURE_URL}` }; + } + return { ok: true, ask: { kind: "nearest", at: when, originalUrl: given } }; +} + +const MEDIA_FILE_RE = /\.(?:mp4|m4v|webm|mkv|mov|flv|avi|wmv|mpg|mpeg|ts|m3u8|mp3|m4a|aac|ogg|oga|opus|wav|flac)$/i; + +// The platform when `url` is a VIDEO (or a media file) — what `import-video` +// imports from a capture — else null. A channel's page, an About page, a +// profile or a post is not a video. +export function videoPageOf(url: string): string | null { + let u: URL; + try { + u = new URL(url); + } catch { + return null; + } + const host = u.hostname.toLowerCase().replace(/^www\./, ""); + const segs = u.pathname.split("/").filter(Boolean); + if (MEDIA_FILE_RE.test(u.pathname)) return "a media file"; + if (host === "youtu.be") return segs[0] ? "YouTube" : null; + if (host === "youtube.com" || host.endsWith(".youtube.com") || host === "youtube-nocookie.com") { + if (u.pathname === "/watch" && u.searchParams.get("v")) return "YouTube"; + if (["shorts", "embed", "live", "v"].includes(segs[0] ?? "") && segs[1]) return "YouTube"; + return null; + } + if (host.endsWith("rumble.com")) { + return /^v[0-9a-z]+-/i.test(segs[0] ?? "") || segs[0] === "embed" ? "Rumble" : null; + } + if (host.endsWith("odysee.com")) { + return segs.length >= 2 && segs[1].includes(":") ? "Odysee" : null; + } + if (host.endsWith("twitch.tv")) { + return segs.includes("videos") || segs.includes("clip") || host === "clips.twitch.tv" ? "Twitch" : null; + } + if (host.endsWith("kick.com")) { + return segs.includes("video") || segs.includes("videos") || segs.includes("clips") ? "Kick" : null; + } + if (host.endsWith("bitchute.com")) { + return segs[0] === "video" || segs[0] === "embed" ? "BitChute" : null; + } + if (host === "archive.org") return segs[0] === "details" || segs[0] === "download" ? "archive.org" : null; + return null; +} + +const X_HOSTS = new Set(["x.com", "twitter.com", "mobile.twitter.com", "mobile.x.com"]); + +// Whether `url` is on X (x.com, twitter.com, mobile.twitter.com): a capture of +// it follows `social.x.visibility` exactly as X posts do. +export function isXHostUrl(url: string): boolean { + try { + return X_HOSTS.has(new URL(url).hostname.toLowerCase().replace(/^www\./, "")); + } catch { + return false; + } +} + +// Whether a target URL (scheme optional) is on X. +export function isXTargetUrl(url: string): boolean { + return isXHostUrl(/^https?:\/\//i.test(url) ? url : `https://${url.replace(/^\*\./, "")}`); +} + +// Whether `url` is a Wayback Machine URL (a capture or a listing) of something +// that is NOT a video: what the New channel form makes a Wayback pages channel +// of. A capture of a video is import-video's. +export function isWaybackPagesUrl(url: string): boolean { + let u: URL; + try { + u = new URL(url.trim()); + } catch { + return false; + } + if (!isWaybackHost(u.hostname)) return false; + const m = /^\/(?:web\/)?\d{0,14}\*?(?:[a-z]{2}_)?\/(.+)$/s.exec(u.pathname + u.search); + if (!m) return false; + let inner = m[1].replace(/\*+$/, "").replace(/^\*\./, ""); + inner = inner.replace(/^(https?):\/(?!\/)/i, "$1://"); + if (!/^https?:\/\//i.test(inner)) inner = `http://${inner}`; + return videoPageOf(inner) === null; +} diff --git a/common/testing/README.md b/common/testing/README.md @@ -23,7 +23,7 @@ transcript, channel or person goes in these fixtures, ever. | `draft/manifests/full`, `flips` | Release 28: every media field a draft task writes, as the build accepts it today — per-entry `onscreen`, a narrated card, a teaser, `claim` verdicts, `render.chrome.threads` with a `thread` per clip (`full`), or `render.chrome.flips` (`flips`: one THEN/NOW pair over clips of different dates). Hand-written, not derived; `umtool/report-to-video/fixtures-r28.test.mjs` keeps them lint-clean. | | `draft/reports/ruled.report.json` | Release 28: a synthetic fact-check whose claims carry verdicts standing for operator rulings — every verdict at least once, each cited quote a cue of the corpus. The verdict bench's tests read it. | | `social/fakeBluesky.mjs` | Release 29: a fake Bluesky on loopback — the public AppView (`resolveHandle`, `getPosts` answering only live posts, images as `embed.images[].fullsize`), a bsky.app-shaped post page (`pageUrl(handle, rkey)`: the post in `[data-testid="postThreadItem-by-<handle>"]` inside page chrome, "Post not found" for a deleted one) for a headless screenshot, and PNG images. `bsky.fetch` sends `https://public.api.bsky.app`, `https://bsky.app` and `https://cdn.bsky.app` to it; `busyTimes` answers 429 first. | -| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. | +| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. Release 37 (lane A): PAGE captures served raw (`PAGE_CAPTURES`, `opts.pageCaptures`) — an article with nav/header/footer around an `<article>` (two captures), a body still carrying the toolbar insert and rewritten hrefs, a 3 MB page, a `text/plain` and an `image/jpeg` capture, and one that redirects off the archive; a timestamp with no capture of a known page answers 302 to the nearest; CDX honours `closest=`. | | `web/fakeRangedCdn.mjs` | Release 32 R7: a fake media CDN shaped like Odysee's `player.odycdn.com` — ranged GETs with a Referer answer 206 (`Content-Range`), unranged 429, no Referer 403, past the end 416; `refuseAfterBytes` (429/403 once a budget is served), `corruptOnce`, `ignoreRange`, `requireUnlock` + `unlockBytes` (served only after `cdn.unlock()` — a player's page open — lapsing after a budget; `cdn.lock()` takes it back). Release 32 R10: `dropAfterBytes` / `drops` / `dropGapBytes` cut the connection mid-body (undici's body read throws) or before any response (the fetch throws `fetch failed`); a cut request is `dropped: true`. `cdn.fetch` sends `https://player.odycdn.com` to it. | | `draft/corpus.mjs` `GONE_RECORD`, `GONE_AVAILABILITY` | Release 29: a recording deleted on its platform (`state: "deleted"`, cues kept; add it with `withRecords`) and the `availability.json` it carries on disk. The fake Wayback has one capture of its watch page. | | `audio/corruptAudio.mjs` | Release 30 lane Q: damaged audio for the salvage and refetch tests — `makeToneFile` (an AAC-in-MP4 tone-burst recording: a 0.3 s burst every 4 s, the bursts being the clock), `corruptBytes` (the same with a seeded run of its bytes overwritten: the frames there fail to decode, their timestamps survive), `readWavMono16`, `toneOnsets` (burst onsets in decoded samples), `burstTimes`, `hasFfmpeg`. Needs ffmpeg; the tests that use it skip without. | diff --git a/common/testing/web/fakeWayback.d.mts b/common/testing/web/fakeWayback.d.mts @@ -1,6 +1,23 @@ export type FakeWaybackCapture = { original: string; timestamp: string; statuscode: string; mimetype?: string }; export const CAPTURES: FakeWaybackCapture[]; + +// Release 37 (lane A): page captures, served raw (`id_`). +export type FakePageCapture = FakeWaybackCapture & { body?: () => string | Buffer; offsite?: string }; +export const PAGE_CAPTURES: FakePageCapture[]; +export const PAGE_ARTICLE_URL: string; +export const PAGE_ARTICLE_TS: string; +export const PAGE_ARTICLE_LATER_TS: string; +export const PAGE_TOOLBAR_URL: string; +export const PAGE_TOOLBAR_TS: string; +export const PAGE_BIG_URL: string; +export const PAGE_BIG_TS: string; +export const PAGE_PLAIN_URL: string; +export const PAGE_PLAIN_TS: string; +export const PAGE_IMAGE_URL: string; +export const PAGE_IMAGE_TS: string; +export const PAGE_JUMP_URL: string; +export const PAGE_JUMP_TS: string; export const VIDEOS: string[]; export type FakeWayback = { @@ -18,4 +35,6 @@ export function startFakeWayback(opts?: { busyTimes?: number; downTimes?: number; streamBusyTimes?: number; + // (release 37) the page captures served raw (default PAGE_CAPTURES). + pageCaptures?: FakePageCapture[]; }): Promise<FakeWayback>; diff --git a/common/testing/web/fakeWayback.mjs b/common/testing/web/fakeWayback.mjs @@ -22,6 +22,9 @@ // (`/web/2id_/<url>`): fake bytes (a Range is answered 206) when the format's `id` // is in opts.streams (default: opts.videos), 404 otherwise — an id in `videos` but // not in `streams` is the live case, the index listing a video Wayback does not hold +// GET /web/<ts>[id_|if_]/<original> (release 37) a PAGE capture's body (PAGE_CAPTURES, +// or opts.pageCaptures) with its own mimetype; a timestamp with no capture of a +// known page answers 302 to the nearest one; a capture with `offsite` answers 302 there // opts.busyTimes: the first N CDX requests answer 429 (Retry-After: 1); opts.downTimes: then 503s. // opts.streamBusyTimes: the first N stream requests answer 429 (Retry-After: 1). @@ -46,11 +49,131 @@ const urlkey = (u) => { } }; +// ─── Release 37 (lane A): page captures, served raw (`id_`) ─────────────── +// +// Invented pages. Each is a capture of a page that is not a video, with the +// body the archive would answer `/web/<ts>id_/<original>` with: +// ARTICLE a blog post: nav, header, footer, aside around an <article>, +// og:title, article:published_time, a rewritten link and images +// TOOLBAR a page whose body still carries the Wayback toolbar insert, its +// /_static/ + wombat scripts, and /web/<ts>/ rewritten hrefs +// BIG a 3 MB page (over the 2 MB cap) +// PLAIN a text/plain capture +// IMAGE an image/jpeg capture (refused by its mimetype) +// JUMP a capture that recorded a redirect OFF the archive +// A timestamp the fake holds no capture of answers 302 to the nearest capture +// of the same page (the archive's own behaviour); CDX lists every page capture +// and honours `closest=` (nearest first). +export const PAGE_ARTICLE_URL = "https://blog.example/2014/03/a-post.html"; +export const PAGE_ARTICLE_TS = "20140305120000"; +export const PAGE_ARTICLE_LATER_TS = "20150611090000"; +export const PAGE_TOOLBAR_URL = "https://home.example/about"; +export const PAGE_TOOLBAR_TS = "20150101000000"; +export const PAGE_BIG_URL = "https://big.example/dump.html"; +export const PAGE_BIG_TS = "20160101000000"; +export const PAGE_PLAIN_URL = "https://notes.example/readme.txt"; +export const PAGE_PLAIN_TS = "20180101000000"; +export const PAGE_IMAGE_URL = "https://img.example/pic.jpg"; +export const PAGE_IMAGE_TS = "20190101000000"; +export const PAGE_JUMP_URL = "https://jump.example/"; +export const PAGE_JUMP_TS = "20170101000000"; + +const articleHtml = (version) => `<!doctype html> +<html lang="en"><head><meta charset="utf-8"> +<title>A Post About Bread | Example Blog</title> +<meta property="og:title" content="A Post About Bread"> +<meta property="article:published_time" content="2014-03-04T18:30:00Z"> +<meta name="author" content="Pat Example"> +</head><body> +<nav><a href="/">Home</a> <a href="/archive">Archive</a></nav> +<header class="site"><h1>Example Blog</h1></header> +<aside><h3>Blogroll</h3><a href="https://other.example/">Other</a></aside> +<article> +<header><h1>A Post About Bread</h1><time datetime="2014-03-04T18:30:00Z">March 4, 2014</time></header> +<p>The first loaf came out flat, and the second, and the third, which is how it goes when the starter is young.</p> +<p>A starter needs a week of feeding before it rises a loaf; see <a href="/web/20140305120000/https://blog.example/2014/02/starter.html">the starter post</a> for the schedule.</p> +<blockquote><p>Bake it until it sounds hollow.</p></blockquote> +<ul><li>Flour, 500 g</li><li>Water, 350 g</li></ul> +<img src="/images/loaf.jpg" alt="A flat loaf"> +<pre> day 1: feed + day 2: feed</pre> +${version > 1 ? "<p>Update: the fourth loaf rose.</p>" : ""} +</article> +<footer>Copyright 2014 Example Blog. <a href="/about">About</a></footer> +<script>var analytics = 1;</script> +</body></html>`; + +const toolbarHtml = `<!doctype html><html><head> +<script src="//archive.org/includes/athena.js" type="text/javascript"></script> +<script type="text/javascript">window.addEventListener('DOMContentLoaded',function(){var v=archive_analytics.values;});</script> +<script type="text/javascript" src="/_static/js/bundle-playback.js?v=1"></script> +<script type="text/javascript" src="/_static/js/wombat.js?v=1"></script> +<script>if (window._WBWombatInit) { wbinfo = {}; window._WBWombatInit(wbinfo); }</script> +<script>__wm.init("https://web.archive.org/web");</script> +<link rel="stylesheet" type="text/css" href="/_static/css/banner-styles.css?v=1"> +<title>About Us</title> +</head><body> +<!-- BEGIN WAYBACK TOOLBAR INSERT --> +<div id="wm-ipp-base" lang="en" style="display:none;direction:ltr;"><div id="wm-ipp"><p>The Wayback Machine - https://web.archive.org/web/20150101000000/https://home.example/about</p><a href="/web/20150101000000*/https://home.example/about">2 captures</a></div></div> +<!-- END WAYBACK TOOLBAR INSERT --> +<div id="content"><h2>About us</h2> +<p>We are a small group that makes zines about our town, and we have done so since 2009, every season.</p> +<p>Write to us through the <a href="https://web.archive.org/web/20150101000000/https://home.example/contact">contact page</a> or see our <a href="/web/20150101000000/https://home.example/links">links</a>.</p> +</div> +</body></html> +<!-- + FILE ARCHIVED ON 00:00:00 Jan 01, 2015 AND RETRIEVED FROM THE + INTERNET ARCHIVE ON 12:00:00 Oct 20, 2026. +-->`; + +export const PAGE_CAPTURES = [ + { original: PAGE_ARTICLE_URL, timestamp: PAGE_ARTICLE_TS, statuscode: "200", mimetype: "text/html", body: () => articleHtml(1) }, + { original: PAGE_ARTICLE_URL, timestamp: PAGE_ARTICLE_LATER_TS, statuscode: "200", mimetype: "text/html", body: () => articleHtml(2) }, + { original: PAGE_TOOLBAR_URL, timestamp: PAGE_TOOLBAR_TS, statuscode: "200", mimetype: "text/html", body: () => toolbarHtml }, + { + original: PAGE_BIG_URL, + timestamp: PAGE_BIG_TS, + statuscode: "200", + mimetype: "text/html", + body: () => `<html><body><p>${"word ".repeat(600 * 1024)}</p></body></html>`, + }, + { original: PAGE_PLAIN_URL, timestamp: PAGE_PLAIN_TS, statuscode: "200", mimetype: "text/plain", body: () => "README\n\nThe notes of a small project, kept as plain text.\n" }, + { original: PAGE_IMAGE_URL, timestamp: PAGE_IMAGE_TS, statuscode: "200", mimetype: "image/jpeg", body: () => Buffer.alloc(2048, 1) }, + { original: PAGE_JUMP_URL, timestamp: PAGE_JUMP_TS, statuscode: "302", mimetype: "text/html", offsite: "https://elsewhere.example/landing" }, +]; + +// The answer to `/web/<ts>[mod]/<original>` for a page capture, or null when +// the original is not one of PAGE_CAPTURES. +function pageCaptureAnswer(pageCaptures, ts, mod, original, send, res) { + const list = pageCaptures.filter((c) => c.original === original); + if (list.length === 0) return false; + const exact = list.find((c) => c.timestamp === ts); + if (!exact) { + const want = Number(ts.padEnd(14, "0")); + const near = [...list].sort((a, b) => Math.abs(Number(a.timestamp) - want) - Math.abs(Number(b.timestamp) - want))[0]; + res.writeHead(302, { location: `https://web.archive.org/web/${near.timestamp}${mod}/${near.original}`, "content-type": "text/html" }); + res.end(""); + return true; + } + if (exact.offsite) { + res.writeHead(302, { location: exact.offsite, "content-type": "text/html" }); + res.end(""); + return true; + } + const body = exact.body(); + const type = exact.mimetype === "text/html" || exact.mimetype === "text/plain" ? `${exact.mimetype}; charset=utf-8` : exact.mimetype; + send(200, type, body); + return true; +} + // YouTube ids whose video (not only its page) the fake archive holds. export const VIDEOS = ["gone-video-05"]; export async function startFakeWayback(opts = {}) { - const captures = opts.captures ?? CAPTURES; + // Release 37: the page captures are served beside whatever `captures` says, + // and listed by CDX unless a test names its own `captures`. + const pageCaptures = opts.pageCaptures ?? PAGE_CAPTURES; + const captures = opts.captures ?? [...CAPTURES, ...pageCaptures]; const videos = opts.videos ?? VIDEOS; const streams = opts.streams ?? videos; let streamBusy = opts.streamBusyTimes ?? 0; @@ -77,10 +200,13 @@ export async function startFakeWayback(opts = {}) { const prefix = u.searchParams.get("matchType") === "prefix"; const status = /^statuscode:(\d+)$/.exec(u.searchParams.get("filter") ?? "")?.[1]; const limit = Number(u.searchParams.get("limit") ?? 0) || Infinity; + // Release 37: `closest=<ts>` (with sort=closest) lists the nearest first. + const closest = u.searchParams.get("closest"); + const near = (c) => Math.abs(Number(c.timestamp) - Number(String(closest).padEnd(14, "0"))); const rows = captures .filter((c) => (prefix ? c.original.startsWith(want) : c.original === want)) .filter((c) => !status || c.statuscode === status) - .sort((a, b) => a.timestamp.localeCompare(b.timestamp)) + .sort((a, b) => (closest ? near(a) - near(b) : 0) || a.timestamp.localeCompare(b.timestamp)) .slice(0, limit) .map((c) => [urlkey(c.original), c.timestamp, c.original, c.mimetype ?? "text/html", c.statuscode, `DIGEST${c.timestamp}`, "1234"]); if (u.searchParams.get("output") === "json") return send(200, "application/json", JSON.stringify(rows.length ? [HEADER, ...rows] : [])); @@ -108,6 +234,9 @@ export async function startFakeWayback(opts = {}) { const to = Math.min(body.length - 1, range[2] ? Number(range[2]) : body.length - 1); return send(206, "video/mp4", body.subarray(from, to + 1), { "content-range": `bytes ${from}-${to}/${body.length}` }); } + // Release 37: a page capture (PAGE_CAPTURES), raw. + const pc = /^\/web\/(\d{1,14})(id_|if_)?\/(.+)$/.exec(u.pathname + u.search); + if (pc && pageCaptureAnswer(pageCaptures, pc[1], pc[2] ?? "", pc[3], send, res)) return; const m = /^\/web\/(\d{14})(?:id_|if_)?\/(.+)$/.exec(u.pathname + u.search); if (m) { const c = captures.find((x) => x.timestamp === m[1] && x.original === m[2]); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **Wayback Machine captures of pages are records of their own.** A capture of a page that is not a video — an old blog post, a group's site, a channel's About page, a document taken down — goes into a **Wayback pages** channel: on the New channel form, paste a Wayback URL of such a page (`web.archive.org/web/*/example.com/blog*` scopes every capture under that path, `*.example.com` a whole domain, one capture's URL that page) or choose **Wayback pages** as the platform, and edit its targets (a URL, how it matches, optional dates). The channel page's **Import a capture** takes a capture's URL, or the page's own URL and a date for the capture nearest it, and imports it as one job at archive.org's pace: the page as captured is kept, its readable text, title, author, date, links and images become a record — searchable, in the MCP and on a built site like any post — dated by the page's own date when it gives one. A later capture of the same page is kept as a version of the first. **Re-extract** reads every kept capture again with no request. A capture of a video is still Import video's, and is refused here with a sentence saying so. An x.com or twitter.com capture is private exactly as X posts are. From a terminal: `pnpm ops import-page` (`dryRun` says what it would fetch) and `pnpm ops reextract-pages`; `pnpm archilyzer wayback pages import|reextract` run without the editor. Needs a restart of the editor. - **Wayback captures of Tumblr, Twitter, forums, Google Docs and YouTube About pages are read as their posts.** A Tumblr blog's post, index, tagged or archive page becomes one record per post (its date, tags, images and what it reblogged), and the same post seen on an index and on its own page is one record. An old Twitter profile or status page becomes one record per tweet — replies, retweets and quotes pointing at the tweets they answer, and the profile's bio, website and counts as one more — and a capture of X's later JavaScript app says it holds no posts. A captured XenForo thread page gives the same posts, with the same ids, that a forum channel of the thread holds. A Google Doc's mobilebasic or published page gives the document's text with its headings; its edit page says it holds no text and names the mobilebasic address to look for. A YouTube channel's About page gives how the channel described itself at that capture: description, links, joined date and counts. Nothing calls a model. - **Focus the queues on a site, or on some channels, from a terminal.** `pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"<id>"}}'` does what the /channels focus bar's **Focus site** does: that site's channels lead every lane, and the focus follows the site's membership. `{"kind":"channels","slugs":[…]}` focuses a list and `{"kind":"none"}` ends the focus. `focus` goes alone in the body. Needs a restart of the editor. - **The clip editor can ask an assistant to label and rank the clip finder's proposals — optionally.** A **Suggest** button in the clip editor's side column asks the model your generation settings choose (the local model, the Claude API, or a Claude Code session through `/gen`) to name each proposal in at most six words, say in one line what makes it land, and rank them; the labels show on every clip and unused proposal, and **Sort by the assistant's rank** orders both lists by them. Labels made before the clips were proposed again are marked stale, not hidden. Nothing in the cut changes: the labels are suggestions. Without a model, or with no labels, the clip editor works as before. From a shell: `pnpm ops report-draft '{"task":"clips-suggest","project":"<dir>","dryRun":true}'` shows how many proposals and what it would cost first. diff --git a/editor/app/api/ops/import-page/route.ts b/editor/app/api/ops/import-page/route.ts @@ -0,0 +1,34 @@ +import { NextResponse } from "next/server"; +import { importPageAction, importPageDryRunAction } from "../../../channels/[slug]/waybackPagesActions"; +import { jobResponse, ops, optBool, optString, reqSlug, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, url, at?, dryRun? } -> { ok: true, jobId } | (dryRun) { ok: true, dryRun: true, wouldFetch, … } +// +// ONE Wayback Machine capture of a page that is not a video into `slug`, a +// Wayback pages channel (platform "webpage"; release 37 S1): `url` a capture's +// replay URL (https://web.archive.org/web/<ts>[mod]/<page>), or the page's own +// URL with `at` (YYYYMMDD[hhmmss]) for the capture nearest it. An +// `import-page` job on the archive.org queue: the raw body stored under the +// channel's `pages/`, its page records written to the channel's posts; the +// log ends with `@@import-page {ok, captureTs, originalUrl, records, written, +// updated, unchanged, already?, error?}`. `dryRun` answers what it would fetch +// and starts nothing. +// +// Every refusal is the controller's sentence: no such channel, not a Wayback +// pages channel, a URL that names no capture, a video ("use import-video"), +// an X capture outside an X channel while X is private. +export async function POST(request: Request) { + return ops(request, ["slug", "url", "at", "dryRun"], async (body) => { + const slug = reqSlug(body, "slug"); + const url = reqString(body, "url"); + const at = optString(body, "at")?.trim() || undefined; + if (optBool(body, "dryRun") === true) { + const r = await importPageDryRunAction(slug, url, at); + if (!r.ok) return NextResponse.json({ ok: false, error: r.error }, { status: 400 }); + return NextResponse.json(r); + } + return jobResponse(await importPageAction(slug, url, at, "ops")); + }); +} diff --git a/editor/app/api/ops/reextract-pages/route.ts b/editor/app/api/ops/reextract-pages/route.ts @@ -0,0 +1,17 @@ +import { reextractPagesAction } from "../../../channels/[slug]/waybackPagesActions"; +import { jobResponse, ops, optBool, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, dryRun? } -> { ok: true, jobId } +// +// A Wayback pages channel's records re-derived from the raw captures it +// stores (release 37 S1): no request. A `reextract-pages` job on the +// archive.org queue (beside no import into the channel); its log ends with +// `@@reextract-pages {captures, stale, records: {added, changed, removed, +// unchanged, kept}, written}`. `dryRun` counts and writes nothing. +export async function POST(request: Request) { + return ops(request, ["slug", "dryRun"], async (body) => + jobResponse(await reextractPagesAction(reqSlug(body, "slug"), optBool(body, "dryRun") === true)), + ); +} diff --git a/editor/app/channels/[slug]/components/WaybackPagesPanel.tsx b/editor/app/channels/[slug]/components/WaybackPagesPanel.tsx @@ -0,0 +1,160 @@ +"use client"; + +// A WAYBACK PAGES channel's page (release 37 S1): what it holds, the scope its +// targets name, one capture imported by its URL (`import-page`), and the +// records re-derived from the stored captures (`reextract-pages`). No fetch: +// captures are chosen, one job each, at archive.org's pace. + +import { useState } from "react"; +import Link from "next/link"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { cancelJobAction } from "../../../jobs/actions"; +import { importPageAction, reextractPagesAction } from "../waybackPagesActions"; + +export type WaybackPagesRecordRow = { + id: string; + title: string; + kind: string; + captureTs: string; + captureDate: string; + originalUrl: string; + waybackUrl: string; + noContent?: boolean; +}; + +export type WaybackPagesState = { + recordCount: number; + captureCount: number; + targets: { url: string; match: string; from?: string; to?: string }[]; + recent: WaybackPagesRecordRow[]; +}; + +const MATCH_LABEL: Record<string, string> = { + exact: "this page", + prefix: "every URL under", + host: "the host", + domain: "the domain", +}; + +// "2014-03-05" → "20140305"; anything else as typed (the controller refuses +// what is not a date). +function atFromDate(v: string): string { + return /^\d{4}-\d{2}-\d{2}$/.test(v) ? v.replaceAll("-", "") : v.trim(); +} + +export function WaybackPagesPanel({ slug, state }: { slug: string; state: WaybackPagesState }) { + const [url, setUrl] = useState(""); + const [date, setDate] = useState(""); + const [importJob, setImportJob] = useState<string | null>(null); + const [reextractJob, setReextractJob] = useState<string | null>(null); + const input = "rounded border border-border bg-card px-2 py-1 text-sm font-mono"; + return ( + <div className="flex flex-col gap-4"> + <section data-wayback-pages="" aria-label="Wayback pages" className="rounded-lg border border-border bg-card p-4"> + <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1"> + <h2 className="text-sm font-medium">Pages</h2> + <span role="status" aria-label="pages held" className="text-sm text-muted-foreground"> + {state.recordCount} record{state.recordCount === 1 ? "" : "s"} from {state.captureCount} capture + {state.captureCount === 1 ? "" : "s"} + </span> + </div> + {state.targets.length > 0 && ( + <ul aria-label="targets" className="mt-2 flex flex-col gap-1 text-sm"> + {state.targets.map((t, i) => ( + <li key={i} className="font-mono text-xs"> + <span className="text-muted-foreground">{MATCH_LABEL[t.match] ?? t.match}</span> {t.url} + {t.from || t.to ? ( + <span className="text-muted-foreground"> · captured {t.from ?? "…"}–{t.to ?? "…"}</span> + ) : null} + </li> + ))} + </ul> + )} + {state.recent.length > 0 && ( + <table aria-label="page records" className="mt-3 w-full text-sm"> + <thead> + <tr className="text-left text-xs text-muted-foreground"> + <th className="py-1 pr-2 font-medium">Page</th> + <th className="py-1 pr-2 font-medium">Kind</th> + <th className="py-1 font-medium">Captured</th> + </tr> + </thead> + <tbody> + {state.recent.map((r) => ( + <tr key={r.id} data-page-record={r.id} className="border-t border-border align-top"> + <td className="py-1 pr-2"> + <a href={r.originalUrl} target="_blank" rel="noreferrer" className="underline underline-offset-2"> + {r.title} + </a> + {r.noContent && <span className="ml-2 text-xs text-muted-foreground">(no content)</span>} + </td> + <td className="py-1 pr-2 font-mono text-xs">{r.kind}</td> + <td className="py-1"> + <a href={r.waybackUrl} target="_blank" rel="noreferrer" className="font-mono text-xs underline underline-offset-2"> + {r.captureDate} + </a> + </td> + </tr> + ))} + </tbody> + </table> + )} + </section> + <section aria-label="import a capture" className="flex flex-col gap-2 rounded-lg border border-border p-3"> + <h4 className="text-sm font-semibold">Import a capture</h4> + <input + value={url} + onChange={(e) => setUrl(e.target.value)} + aria-label="capture URL" + placeholder="https://web.archive.org/web/20140305120000/https://…" + className={`${input} w-[36rem] max-w-full`} + /> + <label className="flex items-center gap-2 text-sm"> + <span>Nearest to</span> + <input + type="date" + value={date} + onChange={(e) => setDate(e.target.value)} + aria-label="capture date" + className="rounded border border-border bg-card px-2 py-1 text-sm" + /> + <span className="text-xs text-muted-foreground">with the page&apos;s own URL</span> + </label> + <StreamActionLog + trigger={() => importPageAction(slug, url.trim(), date ? atFromDate(date) : undefined)} + cancelAction={cancelJobAction} + buttonLabel="Import capture" + runningLabel="Importing…" + label={`Import a capture into ${slug}`} + disabled={!url.trim()} + onSettled={(started, out) => setImportJob(started ? out.jobId : null)} + /> + {importJob && ( + <Link href={`/jobs/${importJob}`} aria-label="import job" className="text-xs underline underline-offset-2"> + Open the import job + </Link> + )} + </section> + <section aria-label="re-extract" className="flex flex-col gap-2 rounded-lg border border-border p-3"> + <h4 className="text-sm font-semibold">Re-extract</h4> + <span className="text-xs text-muted-foreground"> + Every record read again from the stored captures; nothing is fetched. + </span> + <StreamActionLog + trigger={() => reextractPagesAction(slug)} + cancelAction={cancelJobAction} + buttonLabel="Re-extract" + runningLabel="Re-extracting…" + label={`Re-extract pages of ${slug}`} + disabled={state.captureCount === 0} + onSettled={(started, out) => setReextractJob(started ? out.jobId : null)} + /> + {reextractJob && ( + <Link href={`/jobs/${reextractJob}`} className="text-xs underline underline-offset-2"> + Open the re-extract job + </Link> + )} + </section> + </div> + ); +} diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -6,6 +6,7 @@ import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { countPosts, listPostShards, + readAllPosts, readPostAvailability, readPostFetchState, } from "yt-dlp-transcript-common/lib/posts-server"; @@ -20,6 +21,10 @@ import "yt-dlp-transcript-common/social/xenforoFetcher"; import { readForumSessionStatus } from "yt-dlp-transcript-common/social/forumSession"; import { parseXenforoThreadUrl } from "yt-dlp-transcript-common/social/xenforoParse"; import { SocialChannelPanel } from "./components/SocialChannelPanel"; +import { WaybackPagesPanel } from "./components/WaybackPagesPanel"; +import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; +import { countStoredCaptures } from "yt-dlp-transcript-common/lib/waybackPages/store-server"; +import { waybackCaptureDate } from "yt-dlp-transcript-common/lib/wayback"; import { listPostFetchersFor } from "./socialActions"; import { NoReportYet } from "./components/NoReportYet"; import type { ChannelSnapshot } from "yt-dlp-transcript-common/controller/channelSnapshot"; @@ -179,9 +184,41 @@ export default async function ChannelDetailPage({ const forumSession = forumThread ? await readForumSessionStatus(paths, forumThread.host) : undefined; + // A WAYBACK PAGES channel (release 37): its captures, its scope, Import a + // capture — no fetcher, nothing to fetch. + const wayback = isWaybackPagesChannel(config) + ? { + captureCount: await countStoredCaptures(channelRoot), + recent: (await readAllPosts(channelRoot)) + .filter((p) => p.page) + .sort((a, b) => b.page!.captureTs.padEnd(14, "0").localeCompare(a.page!.captureTs.padEnd(14, "0"))) + .slice(0, 20) + .map((p) => ({ + id: p.id, + title: p.page!.title || p.text.split("\n")[0].slice(0, 120) || p.url, + kind: p.page!.kind, + captureTs: p.page!.captureTs, + captureDate: waybackCaptureDate(p.page!.captureTs), + originalUrl: p.page!.originalUrl, + waybackUrl: p.page!.waybackUrl, + ...(p.page!.noContent ? { noContent: true } : {}), + })), + } + : null; return ( <div className="flex flex-col gap-6"> <RunningJobsList jobs={socialRunningJobs} hideChannelSlug /> + {wayback ? ( + <WaybackPagesPanel + slug={slug} + state={{ + recordCount: postCount, + captureCount: wayback.captureCount, + targets: config.wayback?.targets ?? [], + recent: wayback.recent, + }} + /> + ) : ( <SocialChannelPanel slug={slug} state={{ @@ -208,6 +245,7 @@ export default async function ChannelDetailPage({ ...(forumSession ? { forumSession } : {}), }} /> + )} {/* THE SAME DANGER ZONE A VIDEO CHANNEL HAS, which a social channel used to lack entirely: this branch returns before the stage list, so a misspelled X channel could not be renamed from the editor. The diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -20,6 +20,8 @@ import { readChannelConfig, } from "yt-dlp-transcript-common/controller/channels"; import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; +import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; +import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts"; import { emptyAccountOlderProblem, fetchPosts, @@ -192,6 +194,9 @@ export async function fetchPostsAction( if (!isSocialChannel(config)) { return { ok: false, error: `${slug} is not a social channel.` }; } + // A Wayback pages channel is never fetched: its captures are imported one + // by one (import-page), as chosen — no unattended crawling (release 37). + if (isWaybackPagesChannel(config)) return { ok: false, info: true, error: WAYBACK_PAGES_NOT_FETCHED }; if (older) { await registerBuiltinSocialFetchers(); const problem = olderPostsProblem( diff --git a/editor/app/channels/[slug]/waybackPagesActions.ts b/editor/app/channels/[slug]/waybackPagesActions.ts @@ -0,0 +1,38 @@ +"use server"; + +// WAYBACK PAGES (release 37 S1): one capture imported into a Wayback pages +// channel (`import-page`), and the channel's records re-derived from its stored +// captures (`reextract-pages`) — the controllers' own refusals, before a job +// exists, in their own sentences (common/controller/importPage.ts, +// reextractPages.ts). Both run on the archive.org queue. + +import { safeRevalidate } from "../../lib/safeRevalidate"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; +import { importPage, queueImportPage, type ImportPageResult } from "yt-dlp-transcript-common/controller/importPage"; +import { queueReextractPages } from "yt-dlp-transcript-common/controller/reextractPages"; + +export async function importPageAction( + slug: string, + url: string, + at?: string, + requestedBy?: string, +): Promise<StreamActionResult> { + return queueImportPage({ + paths: getPaths(), + slug, + url: url.trim(), + ...(at?.trim() ? { at: at.trim() } : {}), + ...(requestedBy ? { requestedBy } : {}), + onDone: () => safeRevalidate([`/channels/${slug}`]), + }); +} + +// What an import WOULD fetch, answered now (no job, no request). +export async function importPageDryRunAction(slug: string, url: string, at?: string): Promise<ImportPageResult> { + return importPage({ paths: getPaths(), slug, url: url.trim(), ...(at?.trim() ? { at: at.trim() } : {}), dryRun: true }); +} + +export async function reextractPagesAction(slug: string, dryRun?: boolean): Promise<StreamActionResult> { + return queueReextractPages({ paths: getPaths(), slug, ...(dryRun ? { dryRun: true } : {}) }); +} diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -35,6 +35,9 @@ import { } from "../../scheduler/intervalPresets"; import { DurationField } from "../../components/DurationField"; import { handleFromAccountUrl } from "yt-dlp-transcript-common/social/fetchers"; +import { isWaybackPagesUrl } from "yt-dlp-transcript-common/lib/waybackPages/urls"; +import { waybackTargetFromUrl, waybackTargetHost } from "yt-dlp-transcript-common/lib/waybackPages/config"; +import { WaybackTargetsField } from "./WaybackTargetsField"; import { probeChannelUrlAction } from "../actions"; import { Field, @@ -202,7 +205,14 @@ export function ChannelForm({ const editSourceKind = c?.sourceKind ?? "video"; const isSocial = isEdit ? editSourceKind === "social" - : isSocialPlatform(platform as Platform) || isSocialPlatform(detectPlatform(url)); + : isSocialPlatform(platform as Platform) || isSocialPlatform(detectPlatform(url)) || isWaybackPagesUrl(url); + // A Wayback pages channel (release 37): captures of pages, no fetcher; its + // scope is its targets. + const isWaybackPages = isEdit ? c?.platform === "webpage" : platform === "webpage"; + const waybackHandle = (() => { + const t = waybackTargetFromUrl(url); + return t ? waybackTargetHost(t) : ""; + })(); const [probe, setProbe] = useState<{ state: "idle" | "loading" | "done" | "error"; message?: string; @@ -214,7 +224,7 @@ export function ChannelForm({ // NO network call. Only fills untouched fields, so a hand-set value sticks. useEffect(() => { if (isEdit) return; - const detected = detectPlatform(url); + const detected = detectPlatform(url) ?? (isWaybackPagesUrl(url) ? "webpage" : null); if (!platformTouched) setPlatform(detected ?? ""); if (!handlingTouched && url.trim()) { setHandling(detected === "youtube" ? "youtube" : "transcribe"); @@ -390,6 +400,7 @@ export function ChannelForm({ <option value="twitter">X / Twitter (posts)</option> <option value="bluesky">Bluesky (posts)</option> <option value="xenforo">Forum thread — XenForo (posts)</option> + <option value="webpage">Wayback pages (captures of pages)</option> </SeededSelect> <span className="text-xs text-muted-foreground"> Used as the default job queue, so all channels on the same @@ -512,6 +523,7 @@ export function ChannelForm({ <option value="twitter">X / Twitter (posts)</option> <option value="bluesky">Bluesky (posts)</option> <option value="xenforo">Forum thread — XenForo (posts)</option> + <option value="webpage">Wayback pages (captures of pages)</option> </ControlledSelect> <span className="text-xs text-muted-foreground"> Used as the default job queue, so all channels on the same @@ -523,7 +535,11 @@ export function ChannelForm({ <legend className="px-1 text-xs font-medium uppercase tracking-wide text-muted-foreground"> On create </legend> - {isSocial ? ( + {isWaybackPages ? ( + <span className="text-xs text-muted-foreground"> + Nothing is fetched on create: import captures from the channel page. + </span> + ) : isSocial ? ( <label className="flex items-start gap-2 text-sm"> <input type="checkbox" @@ -585,7 +601,18 @@ export function ChannelForm({ </fieldset> </> )} - {isSocial && ( + {isSocial && isWaybackPages && ( + <> + {/* A Wayback pages channel: no fetcher; its handle is its target's + host, and its scope the targets below. */} + <input type="hidden" name="sourceKind" value="social" /> + <input type="hidden" name="socialHandle" value={isEdit ? (c?.socialHandle ?? "") : waybackHandle} /> + <WaybackTargetsField + {...(isEdit ? { initial: c?.wayback?.targets ?? [] } : { derivedFrom: url })} + /> + </> + )} + {isSocial && !isWaybackPages && ( <> {/* A social source is ingested into the posts corpus, so it carries its fetcher + handle instead of any of the video controls. */} diff --git a/editor/app/channels/components/WaybackTargetsField.tsx b/editor/app/channels/components/WaybackTargetsField.tsx @@ -0,0 +1,126 @@ +"use client"; + +// A Wayback pages channel's targets as editable rows (release 37): a URL, how +// it matches, and optional capture-date bounds. Posted as ONE hidden field, +// `waybackTargets` (a JSON array), which parseChannelForm validates. + +import { useEffect, useState } from "react"; +import { + WAYBACK_TARGET_MATCHES, + waybackTargetFromUrl, + type WaybackTarget, +} from "yt-dlp-transcript-common/lib/waybackPages/config"; + +type Row = { url: string; match: string; from: string; to: string }; + +const LABELS: Record<string, string> = { + exact: "Exact page", + prefix: "Prefix (every URL under it)", + host: "Host", + domain: "Domain (and subdomains)", +}; + +const toRow = (t: WaybackTarget): Row => ({ url: t.url, match: t.match, from: t.from ?? "", to: t.to ?? "" }); + +export function WaybackTargetsField({ + initial, + derivedFrom, +}: { + // The stored targets (edit mode). + initial?: WaybackTarget[]; + // Create mode: the URL typed above, a first row is derived from until a row + // is edited by hand. + derivedFrom?: string; +}) { + const [rows, setRows] = useState<Row[]>(initial?.length ? initial.map(toRow) : []); + const [touched, setTouched] = useState(!!initial?.length); + useEffect(() => { + if (touched || derivedFrom === undefined) return; + const t = waybackTargetFromUrl(derivedFrom); + setRows(t ? [toRow(t)] : []); + }, [derivedFrom, touched]); + const edit = (i: number, patch: Partial<Row>) => { + setTouched(true); + setRows((rs) => rs.map((r, j) => (j === i ? { ...r, ...patch } : r))); + }; + const value = JSON.stringify( + rows + .filter((r) => r.url.trim()) + .map((r) => ({ + url: r.url.trim(), + match: r.match, + ...(r.from.trim() ? { from: r.from.trim() } : {}), + ...(r.to.trim() ? { to: r.to.trim() } : {}), + })), + ); + const input = "rounded border border-border bg-card px-2 py-1 text-sm"; + return ( + <fieldset aria-label="wayback targets" className="flex flex-col gap-2 rounded-md border border-border px-3 py-2"> + <legend className="px-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">Targets</legend> + <input type="hidden" name="waybackTargets" value={value} /> + {rows.map((r, i) => ( + <div key={i} data-wayback-target={i} className="flex flex-wrap items-center gap-2"> + <input + value={r.url} + onChange={(e) => edit(i, { url: e.target.value })} + aria-label={`target ${i + 1} URL`} + placeholder="example.com/blog" + className={`${input} flex-1 font-mono`} + /> + <select + value={r.match} + onChange={(e) => edit(i, { match: e.target.value })} + aria-label={`target ${i + 1} match`} + className={input} + > + {WAYBACK_TARGET_MATCHES.map((m) => ( + <option key={m} value={m}> + {LABELS[m]} + </option> + ))} + </select> + <input + value={r.from} + onChange={(e) => edit(i, { from: e.target.value })} + aria-label={`target ${i + 1} from`} + placeholder="from (2014)" + className={`${input} w-28 font-mono`} + /> + <input + value={r.to} + onChange={(e) => edit(i, { to: e.target.value })} + aria-label={`target ${i + 1} to`} + placeholder="to (2016)" + className={`${input} w-28 font-mono`} + /> + <button + type="button" + onClick={() => { + setTouched(true); + setRows((rs) => rs.filter((_, j) => j !== i)); + }} + aria-label={`remove target ${i + 1}`} + className="rounded-md border border-border px-2 py-1 text-xs hover:bg-muted" + > + Remove + </button> + </div> + ))} + <div> + <button + type="button" + onClick={() => { + setTouched(true); + setRows((rs) => [...rs, { url: "", match: "prefix", from: "", to: "" }]); + }} + className="rounded-md border border-border px-2 py-1 text-xs hover:bg-muted" + > + Add target + </button> + </div> + <span className="text-xs text-muted-foreground"> + Which captures are in scope. Dates are Wayback timestamps or their start (2014, 201403, 20140305). + </span> + </fieldset> + ); +} diff --git a/editor/app/channels/components/channelConfigToForm.ts b/editor/app/channels/components/channelConfigToForm.ts @@ -59,6 +59,9 @@ export const CHANNEL_FORM_VALUES = [ "audioCheckIntervalSeconds", "audioCheckMaxRollbacks", "audioCheckCopyTimeoutSeconds", + // A Wayback pages channel's targets (release 37): a JSON array, or (in a + // patch) the array itself. + "waybackTargets", ] as const; export type ChannelFormFlag = (typeof CHANNEL_FORM_FLAGS)[number]; @@ -124,6 +127,7 @@ export function channelConfigToFormData(config: ChannelConfig): FormData { ); put(fd, "recordedDateTitlePattern", config.recordedDate?.titlePattern); put(fd, "mirrorOf", config.mirror?.of.join(", ")); + if (config.wayback?.targets.length) fd.set("waybackTargets", JSON.stringify(config.wayback.targets)); // Ticked when the check is on: said so, or the platform's default (an // Odysee channel with no `audioCheck`; lib/audioCheckPolicy.ts) — so a patch // that does not name it keeps what the channel has. @@ -169,6 +173,11 @@ export function applyChannelFormPatch( else fd.delete(key); continue; } + if (key === "waybackTargets" && Array.isArray(value)) { + if (value.length > 0) fd.set(key, JSON.stringify(value)); + else fd.delete(key); + continue; + } if (key === "ytdlpExtraArgs" && Array.isArray(value)) { const joined = (value as string[]).join("\n"); if (joined.trim()) fd.set(key, joined); @@ -200,6 +209,7 @@ export function validateChannelFormPatch(patch: ChannelConfigPatch): void { `"${key}" is not a channel config field — accepted: ${CHANNEL_FORM_FIELD_NAMES.join(", ")}`, ); } + if (key === "waybackTargets" && Array.isArray(value)) continue; if (key === "ytdlpExtraArgs" && Array.isArray(value)) { if (value.some((v) => typeof v !== "string")) { throw new Error(`"${key}" must be an array of strings`); diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -152,3 +152,57 @@ test("the form writes browserLookup from its checkbox; unchecked clears it; the applyChannelFormPatch(back, { browserLookup: false }); assert.equal("browserLookup" in parseChannelForm(back).config, false); }); + +// A Wayback pages channel (release 37 S1): a non-video Wayback URL makes one — +// platform "webpage", social, its target derived from the URL and its handle +// the target's host; the form's target rows win over the URL; a row that is +// not a target is refused by number; the ops patch round-trips the targets. +test("a Wayback pages channel from a Wayback URL: platform webpage, one target derived, the host as its handle", () => { + const { config } = parseChannelForm( + form({ name: "Old blog", handling: "transcribe", url: "https://web.archive.org/web/*/blog.example/2014/*" }), + ); + assert.equal(config.platform, "webpage"); + assert.equal(config.sourceKind, "social"); + assert.equal(config.socialHandle, "blog.example"); + assert.deepEqual(config.wayback, { targets: [{ url: "blog.example/2014/", match: "prefix" }] }); + assert.ok((CHANNEL_FORM_FIELDS as readonly string[]).includes("wayback")); + // A capture of a video is not a pages channel. + const video = parseChannelForm( + form({ url: "https://web.archive.org/web/20200101000000/https://www.youtube.com/watch?v=abcdefghijk" }), + ).config; + assert.notEqual(video.platform, "webpage"); +}); + +test("the form's target rows win; a bad row is refused by number; none at all is refused", () => { + const rows = [ + { url: "blog.example/", match: "prefix", from: "2014" }, + { url: "example.net", match: "domain" }, + ]; + const { config } = parseChannelForm( + form({ handling: "transcribe", platform: "webpage", url: "https://blog.example/", waybackTargets: JSON.stringify(rows) }), + ); + assert.deepEqual(config.wayback?.targets, rows); + assert.equal(config.socialHandle, "blog.example"); + assert.throws( + () => parseChannelForm(form({ handling: "transcribe", platform: "webpage", waybackTargets: JSON.stringify([rows[0], { url: "x.example", match: "all" }]) })), + /Wayback target 2 is not a target/, + ); + assert.throws(() => parseChannelForm(form({ handling: "transcribe", platform: "webpage", waybackTargets: "{" })), /JSON list/); + assert.throws(() => parseChannelForm(form({ handling: "transcribe", platform: "webpage" })), /needs a target/); +}); + +test("the ops patch round-trips a pages channel's targets (an array or its JSON)", () => { + const fd = channelConfigToFormData({ + handling: "transcribe", + name: "Old blog", + sourceKind: "social", + platform: "webpage", + socialHandle: "blog.example", + url: "https://web.archive.org/web/*/blog.example/*", + wayback: { targets: [{ url: "blog.example/", match: "prefix" }] }, + }); + assert.deepEqual(parseChannelForm(fd).config.wayback, { targets: [{ url: "blog.example/", match: "prefix" }] }); + validateChannelFormPatch({ waybackTargets: [{ url: "blog.example/", match: "exact" }] }); + applyChannelFormPatch(fd, { waybackTargets: [{ url: "blog.example/about", match: "exact" }] }); + assert.deepEqual(parseChannelForm(fd).config.wayback?.targets, [{ url: "blog.example/about", match: "exact" }]); +}); diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts @@ -20,6 +20,14 @@ import { type Platform, } from "yt-dlp-transcript-common/lib/platform"; import { handleFromAccountUrl } from "yt-dlp-transcript-common/social/fetchers"; +import { + coerceWaybackPagesConfig, + coerceWaybackTarget, + waybackTargetFromUrl, + waybackTargetHost, + type WaybackPagesConfig, +} from "yt-dlp-transcript-common/lib/waybackPages/config"; +import { isWaybackPagesUrl } from "yt-dlp-transcript-common/lib/waybackPages/urls"; import { isCookieMode } from "yt-dlp-transcript-common/lib/cookiePolicy"; import { isDownloadFormatPreset, @@ -66,6 +74,7 @@ export const CHANNEL_FORM_FIELDS = [ "downloadFilter", "recordedDate", "mirror", + "wayback", ] as const satisfies ReadonlyArray<keyof ChannelConfig>; // Maps FormData -> ChannelConfig. Throws on invalid input so the server @@ -87,7 +96,11 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { platformRaw as Platform, ) ? (platformRaw as Platform) - : (detectPlatform(url) ?? undefined); + : (detectPlatform(url) ?? + // A Wayback Machine URL of a page that is not a video (a capture, or a + // listing like web.archive.org/web/*/example.com/blog*): a Wayback + // pages channel (release 37). + (url && isWaybackPagesUrl(url) ? "webpage" : undefined)); // Source kind. A social channel is ingested into the posts corpus instead of // the video pipeline; the form hides every video-only control for it. An // explicit "social" wins, otherwise infer from the platform so a social URL @@ -103,8 +116,12 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { sourceKind === "social" ? stringOrUndef(formData, "postFetcher") : undefined; const socialHandleRaw = sourceKind === "social" ? stringOrUndef(formData, "socialHandle") : undefined; + // A Wayback pages channel's scope: the form's target rows (one hidden JSON + // field), else one target derived from the URL. + const wayback = platform === "webpage" ? parseWaybackTargets(formData, url) : undefined; const socialHandle = socialHandleRaw?.replace(/^@/, "") || + (wayback ? waybackTargetHost(wayback.targets[0]) : undefined) || (sourceKind === "social" && url ? (handleFromAccountUrl(url) ?? undefined) : undefined); @@ -418,10 +435,50 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { config.recordedDate = { titlePattern: recordedDateTitlePattern }; } if (mirrorOf.length > 0) config.mirror = { of: mirrorOf }; + if (wayback) config.wayback = wayback; return { name, slug, config }; } +// `waybackTargets` (a JSON array of {url, match, from?, to?, …}) as the +// channel's Wayback scope; with none given, one target derived from the URL +// (lib/waybackPages/config.ts, waybackTargetFromUrl). A row that is not a +// target is refused here, by number, rather than dropped by the reader. +function parseWaybackTargets(formData: FormData, url: string | undefined): WaybackPagesConfig { + const raw = String(formData.get("waybackTargets") ?? "").trim(); + let rows: unknown[] = []; + if (raw) { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + throw new Error("Wayback targets must be a JSON list of {url, match, from?, to?}"); + } + if (!Array.isArray(parsed)) throw new Error("Wayback targets must be a JSON list of {url, match, from?, to?}"); + rows = parsed; + } + rows.forEach((row, i) => { + if (!coerceWaybackTarget(row)) { + throw new Error( + `Wayback target ${i + 1} is not a target: it needs a URL and a match of exact, prefix, host or domain` + + " (dates as Wayback timestamps, 4–14 digits)", + ); + } + }); + if (rows.length === 0 && url) { + const derived = waybackTargetFromUrl(url); + if (derived) rows = [derived]; + } + const config = coerceWaybackPagesConfig({ targets: rows }); + if (!config) { + throw new Error( + "A Wayback pages channel needs a target: a URL that scopes its captures " + + "(e.g. https://web.archive.org/web/*/example.com/blog*)", + ); + } + return config; +} + function stringOrUndef(fd: FormData, key: string): string | undefined { const v = String(fd.get(key) ?? "").trim(); return v ? v : undefined; diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -52,6 +52,11 @@ export function blueskyOriginFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-bluesky-origin"); } +/** The file naming a slot's fake Wayback Machine (common/lib/waybackClient.ts; wayback-pages.spec). */ +export function waybackOriginFile(transcriptsDir: string): string { + return join(transcriptsDir, ".fake-wayback-origin"); +} + /** The file naming a slot's stub umtool (common/lib/umtoolUrl.ts; find-clips.spec). */ export function umtoolOriginFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-umtool-origin"); @@ -210,6 +215,9 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env) // Where a spec names its fake Bluesky's origin (capture-posts.spec): the // slot's own test data, so two slots never share one. editorEnv.E2E_BLUESKY_ORIGIN_FILE = blueskyOriginFile(paths.transcriptsDir); + // The same for the fake Wayback Machine wayback-pages.spec starts + // (lib/waybackClient.ts: the process's client sends web.archive.org there). + editorEnv.E2E_WAYBACK_ORIGIN_FILE = waybackOriginFile(paths.transcriptsDir); // The same for the stub umtool find-clips.spec starts (lib/umtoolUrl.ts). editorEnv.E2E_UMTOOL_ORIGIN_FILE = umtoolOriginFile(paths.transcriptsDir); // The browser lookup's recorded page reads (browser-lookup.spec): set on diff --git a/editor/e2e/wayback-pages.spec.ts b/editor/e2e/wayback-pages.spec.ts @@ -0,0 +1,145 @@ +// Wayback pages (release 37 S1), end to end over the fake Wayback Machine +// (common/testing/web/fakeWayback.mjs), named to the test server through +// E2E_WAYBACK_ORIGIN_FILE (e2e/servers.ts). The real web.archive.org is never +// contacted. +// +// The New channel form makes a Wayback pages channel of a Wayback listing URL +// (platform "webpage", one target derived), and the channel page's Import a +// capture runs an import-page job: the raw body stored under pages/, the page +// record in the channel's posts and on the page. The ops door answers a dry run +// and imports the capture nearest a date. + +import { test, expect, type APIRequestContext } from "@playwright/test"; +import { readFile, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { + startFakeWayback, + PAGE_ARTICLE_LATER_TS, + PAGE_ARTICLE_TS, + PAGE_ARTICLE_URL, +} from "yt-dlp-transcript-common/testing/web/fakeWayback.mjs"; +import { pageRecordId } from "yt-dlp-transcript-common/lib/waybackPages/types"; +import { baseUrl } from "./baseUrl"; +import { generateReport, pathExists, readJson, resetData, resolvePath, testPaths, writeSettings } from "./helpers"; +import { waybackOriginFile } from "./servers"; + +const AUTH = { authorization: "Bearer test-worker-token" }; +const SLUG = "old-blog"; + +async function waitForJob(request: APIRequestContext, jobId: string): Promise<{ status: string; tail: string[] }> { + let last = { status: "", tail: [] as string[] }; + await expect + .poll( + async () => { + const res = await request.get(`${baseUrl}/api/ops/job/${jobId}?tail=40`, { headers: AUTH }); + const body = (await res.json()) as { job: { status: string }; tail?: string[] }; + last = { status: body.job.status, tail: body.tail ?? [] }; + return last.status; + }, + { timeout: 60_000, intervals: [1_000] }, + ) + .toMatch(/^(done|failed|cancelled)$/); + return last; +} + +test("a Wayback pages channel from the New channel form, then Import a capture on its page", async ({ page, request }) => { + test.setTimeout(150_000); + await resetData("empty"); + await writeSettings({ minFreeDiskGB: 0 }); + await generateReport(page, "new"); + + await page.goto("/channels/new"); + await page.locator('input[name="url"]').fill("https://web.archive.org/web/*/blog.example/2014/*"); + // Offline: a Wayback URL of a page that is not a video is a pages channel. + await expect(page.locator('select[name="platform"]')).toHaveValue("webpage"); + await expect(page.getByLabel("target 1 URL")).toHaveValue("blog.example/2014/"); + await expect(page.getByLabel("target 1 match")).toHaveValue("prefix"); + // Nothing fetched on create, and no video controls. + await expect(page.locator('input[name="fetchPostsNow"]')).toHaveCount(0); + await expect(page.locator('select[name="audioFormat"]')).toHaveCount(0); + // The scope widened by hand: the whole blog. + await page.getByLabel("target 1 URL").fill("blog.example/"); + await page.locator('input[name="name"]').fill("Old blog"); + await page.locator('input[name="slug"]').fill(SLUG); + await page.getByRole("button", { name: /create|add channel|save/i }).first().click(); + + const configFile = `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`; + await expect + .poll(async () => ((await pathExists(configFile)) ? await readJson(configFile) : null), { timeout: 15_000 }) + .toMatchObject({ + sourceKind: "social", + platform: "webpage", + socialHandle: "blog.example", + wayback: { targets: [{ url: "blog.example/", match: "prefix" }] }, + }); + + const wb = await startFakeWayback(); + const originFile = waybackOriginFile(resolvePath(testPaths().transcriptsDir)); + await writeFile(originFile, wb.base); + try { + await page.goto(`/channels/${SLUG}`); + const pages = page.getByRole("region", { name: "Wayback pages" }); + await expect(pages.getByLabel("pages held")).toHaveText("0 records from 0 captures"); + // A video's capture is refused before any job. + await page.getByLabel("capture URL").fill("https://web.archive.org/web/20140101000000/https://www.youtube.com/watch?v=abcdefghijk"); + await page.getByRole("button", { name: "Import capture" }).click(); + await expect(page.getByRole("alert", { name: `Import a capture into ${SLUG} error` })).toContainText("use import-video"); + expect(wb.requests).toEqual([]); + + await page.getByLabel("capture URL").fill(`https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`); + await page.getByRole("button", { name: "Import capture" }).click(); + await expect(page.getByRole("log", { name: `Import a capture into ${SLUG} output` })).toContainText('"ok":true', { + timeout: 60_000, + }); + await expect(page.getByRole("link", { name: "import job" })).toHaveAttribute("href", /^\/jobs\//); + + const id = pageRecordId(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL); + const channelRoot = resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`); + const capture = JSON.parse(await readFile(path.join(channelRoot, "pages", id, "capture.json"), "utf8")) as Record<string, unknown>; + expect(capture).toMatchObject({ originalUrl: PAGE_ARTICLE_URL, captureTs: PAGE_ARTICLE_TS, mimetype: "text/html", extractor: "generic" }); + const shard = await readFile(path.join(channelRoot, "posts", "2014-03.jsonl"), "utf8"); + expect(shard).toContain(`"id":"${id}"`); + expect(shard).toContain('"platform":"webpage"'); + + await page.reload(); + await expect(pages.getByLabel("pages held")).toHaveText("1 record from 1 capture"); + const row = page.locator(`[data-page-record="${id}"]`); + await expect(row.getByRole("link", { name: "A Post About Bread" })).toHaveAttribute("href", PAGE_ARTICLE_URL); + await expect(row.getByRole("link", { name: "2014-03-05" })).toHaveAttribute( + "href", + `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`, + ); + + // The ops door: a dry run fetches nothing; `at` imports the nearest capture. + const before = wb.requests.length; + const dry = await request.post(`${baseUrl}/api/ops/import-page`, { + headers: AUTH, + data: { slug: SLUG, url: PAGE_ARTICLE_URL, at: "20150601", dryRun: true }, + }); + const dryBody = (await dry.json()) as { ok: boolean; dryRun?: boolean; wouldFetch?: string }; + expect(dryBody).toMatchObject({ ok: true, dryRun: true }); + expect(dryBody.wouldFetch).toContain("nearest 20150601"); + expect(wb.requests.length).toBe(before); + + const res = await request.post(`${baseUrl}/api/ops/import-page`, { headers: AUTH, data: { slug: SLUG, url: PAGE_ARTICLE_URL, at: "20150601" } }); + const body = (await res.json()) as { ok?: boolean; jobId?: string; error?: string }; + expect(res.status(), body.error).toBe(200); + const job = await waitForJob(request, body.jobId!); + expect(job.status, job.tail.join("\n")).toBe("done"); + expect(job.tail.join("\n")).toContain(`"captureTs":"${PAGE_ARTICLE_LATER_TS}"`); + + await page.reload(); + await expect(pages.getByLabel("pages held")).toHaveText("2 records from 2 captures"); + + // A refusal over ops is the controller's sentence. + const refused = await request.post(`${baseUrl}/api/ops/import-page`, { + headers: AUTH, + data: { slug: SLUG, url: "https://web.archive.org/web/*/blog.example/*" }, + }); + expect(refused.status()).toBe(400); + expect(((await refused.json()) as { error: string }).error).toContain("not one capture"); + } finally { + await rm(originFile, { force: true }); + await wb.close(); + } +}); diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -34,6 +34,11 @@ import { currentSlot } from "./e2e/testPaths"; // writes its fake Bluesky's loopback origin into, // which the AppView, bsky.app and the image CDN // then are (common/social/blueskyEndpoints.ts) +// E2E_WAYBACK_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec +// writes its fake Wayback Machine's loopback origin +// into, where the editor's Wayback client then sends +// every web.archive.org request +// (common/lib/waybackClient.ts; wayback-pages.spec) // E2E_UMTOOL_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec // writes its stub umtool's loopback origin into, // which Find clips then posts to diff --git a/mcp/src/server.ts b/mcp/src/server.ts @@ -2213,7 +2213,7 @@ function postToMarkdown(post: Post, heading = true, archive: string | null = nul const lines: string[] = []; if (heading) lines.push(`# Post by ${post.authorName || post.author}`); lines.push( - post.platform === "xenforo" + post.platform === "xenforo" || post.platform === "webpage" ? `- author: ${post.author}${post.forum?.authorId ? ` (member ${post.forum.authorId})` : ""}` : `- author: ${post.authorName ? `${post.authorName} (@${post.author})` : `@${post.author}`}`, ); diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -11033,6 +11033,65 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri `validateSlide` inside `validateTransitionStyle`; `slide` is a LOOK_KEY). Grain: `noise=alls=<grain>:allf=t+u` on the D/2 nearest the seam of each plain-join edge (`blurSlideEdges`, the segment's own `t`). +## Release 37 lane A: page records — Wayback pages channels, import-page (verified 2026-10-20, branch `r37/core`) + +- **Platform `"webpage"`** is in `Platform`/`PLATFORM_VALUES`/`SOCIAL_PLATFORM_VALUES`/`isSocialPlatform` + (`common/lib/platform.ts`) and `PostPlatform`/`POST_PLATFORM_VALUES`/`isPostPlatform`/`postPlatformLabel` ("Web + page", `common/lib/posts.ts`). `detectPlatform` never answers it: a web.archive.org URL is a capture of something + else. A **Wayback pages channel** is `sourceKind: "social"` + `platform: "webpage"` (`isWaybackPagesChannel`, + `lib/waybackPages/config.ts`), so the posts index pass, `publishedMemberSlugs`, search, `get_post` and compose read + it with no reader of their own. `fetchPosts` and `fetchPostsAction` refuse it (`WAYBACK_PAGES_NOT_FETCHED`; info + for the scheduler): nothing crawls. +- **`config.wayback`** = `{targets: [{url, match: exact|prefix|host|domain, from?, to?, mime?, include?, exclude?}], + collapse?: "digest"}` (`coerceWaybackPagesConfig`; an invalid target is dropped, none = the key omitted). The form + posts it as ONE hidden JSON field `waybackTargets` (`WaybackTargetsField.tsx`; `parseChannelForm` refuses a bad row + by number; `CHANNEL_FORM_FIELDS` has `wayback`, so a form save rewrites it whole — a key added inside it later must + get a form field). `waybackTargetFromUrl` reads `web.archive.org/web/*/<t>*` (prefix), `*.<host>` (domain), + `/web/2014*/…` (from = to = 2014) and a capture URL (exact). The handle is the first target's host. +- **`Post.page`** is `PagePostInfo` (`lib/waybackPages/types.ts`); `parsePagePostInfo` (`parse.ts`, client-safe) + drops a page missing provenance or extractor, never the post; a kind is any `[a-z][a-z0-9-]*` (not checked against + `PAGE_KINDS`, so a newer extractor's records stay readable). Additive in this lane: `extractorFallback?: {from, + fromVersion, error}` (a site extractor threw or made nothing; the record is generic's). +- **The client:** `WaybackClient.getCapture(ts, url, {maxBytes?})` reads `/web/<ts>id_/<url>` through + `ArchiveOrgClient.getBounded` (new: `redirect: "manual"`, the body streamed to the cap, the gap counted from the + body's end). Cap `WAYBACK_PAGE_MAX_BYTES` 2 MB (a constant; no settings key); mimetypes `PAGE_MIMETYPES` + (text/html, text/plain, application/json); at most `WAYBACK_MAX_REDIRECTS` 5, each inside web.archive.org and + re-formed as `id_`; the answer's `finalTs`/`originalUrl` are the LAST capture's. Refusals are + `WaybackCaptureRefusal` codes `mimetype | too-large | offsite-redirect | redirect-loop | not-archived`. + `closestCapture(url, at)` = one CDX request `closest=<at>&sort=closest&limit=5&filter=statuscode:200`, re-sorted by + distance. The process client honours `E2E_WAYBACK_ORIGIN_FILE` (`waybackTestOrigin`). +- **On disk:** `channels/<slug>/pages/<captureTs>-<urlHash>/raw.html.gz` + `capture.json` (`StoredCapture`: + originalUrl, captureTs, mimetype, contentType, bytes, sha256, fetchedAt, extractor, extractorVersion, + extractorFallback?, requestedTs?/requestedUrl? when redirected, records = the ids it made). The dir name is + `pageRecordId`. Body first, then capture.json (tmp + rename each): a capture.json means a whole body. At the + channel root, not `data/<id>/`: the media tier never moves it. +- **Records:** `draftToPost` (`toPost.ts`): id = itemId else pageRecordId; createdAt = publishedAt else the capture + time (`captureTsIso`); author = draft author else the host; threadId = `pageThreadId(originalUrl)`, a tweet's = + the status it answers else its own. **The split-record merge** (`mergePageRecord`, inside `upsertPosts`): the + later capture's facts win, `firstSeenTs` = the earliest, the stored createdAt (its shard) kept; compared by + `stableRecordJson(asStored(...))` because parsePost and draftToPost order keys differently. `assignPageVersions`: + every later whole-page capture of an original names the earliest as `versionOf`. +- **The generic extractor** (`extractors/generic.ts`, "generic" v1): toolbar insert / `wm-ipp*` / `/_static/` / + wombat / `__wm.` stripped; nav, aside, form, script… and header/footer (a header inside an article kept) pruned; + main = `<main>`/`[role=main]`, else top-level `<article>`s, else the densest block; dates not believed after the + capture (+1 day); links un-rewritten and absolute; images as `/web/<ts>im_/<src>`. `extractPage` (`extract.ts`) + offers HTML only to `SITE_EXTRACTORS`; `decodeCaptureBody` reads the header's, else the document's, charset. +- **import-page** (`controller/importPage.ts`): job kind `import-page` (needsText, not drainable/replayable, an + ingest kind) on `WAYBACK_PAGES_QUEUE` = `queueKeyForUrl("https://web.archive.org/")` = `platform:archive.org`. + `planImportPage` refuses (no job) a non-pages channel, a listing URL, a bare URL with no `at`, a video + (`videoPageOf`: "use import-video"), and — with `social.x.visibility` private — an X capture into a channel that is + not X-scoped (`xCaptureRefusal`). A 14-digit capture already stored is not fetched. The log ends `@@import-page + {…}`. Lane B's door: `startImportPageJob({slug, url, at?, requestedBy?}) → {jobId}` (throws `ImportPageRefusal`). + No reindex at import: the index picks the records up on its next build, as for a post fetch. +- **reextract-pages** (`controller/reextractPages.ts`): recomputes every stored capture's records (oldest first, + merged), re-assigns versions, and replaces the channel's posts WHOLE with `replaceChannelPosts` (posts-server: each + shard tmp + rename, stale shards removed, posts-archive rewritten) when anything differs; a record whose capture is + not stored is kept. Stale = capture.json's extractor/version is not `chooseExtractor`'s now, or it fell back. A job + on the same queue as import-page (the editor's Re-extract, `pnpm ops reextract-pages`); the CLI runs in-process. +- **X:** `isXPostsChannel` (`lib/postsVisibility.ts`) also answers true for a Wayback pages channel whose target (or + url) is on x.com / twitter.com / mobile.twitter.com, so `publishedMemberSlugs` leaves it out of a public site while + X is private. + ## Release 37 lane C: the page extractors (verified 2026-10-20, branch `r37/extractors`) - **Where**: `common/lib/waybackPages/extractors/{gdoc,ytAbout,x,xenforo,tumblr}.ts`, each a `PageExtractor` diff --git a/plans/release-37/core.md b/plans/release-37/core.md @@ -0,0 +1,150 @@ +# Release 37 lane A — `r37/core`: the client, the record, one-page import (as shipped) + +The plan of record is [`wayback-pages.md`](wayback-pages.md) ("What a record is", "What a channel is", S1). This lane +makes a Wayback Machine capture of a page that is not a video a first-class record: a `Post` on platform `"webpage"` +in a **Wayback pages** channel, imported one capture at a time (`import-page`), its raw body kept so its records can be +re-derived offline (`reextract-pages`). Rulings followed: the UI works with no model (nothing here calls one); every +CLI operation has a button (Import a capture, Re-extract); every request to archive.org goes through the polite client +on the `platform:archive.org` queue, one capture per job, no crawling; synthetic fixtures only (the fake Wayback); +commits end with the one Co-Authored-By trailer. + +## What + +1. **Platform `"webpage"`** — in `Platform`, `PLATFORM_VALUES`, `SOCIAL_PLATFORM_VALUES`, `isSocialPlatform`, + `defaultWebpageUrl` (`common/lib/platform.ts`) and `PostPlatform`, `POST_PLATFORM_VALUES`, `isPostPlatform`, + `postPlatformLabel` ("Web page"), `postPermalink` (`common/lib/posts.ts`). `detectPlatform` does not answer it (a + web.archive.org URL is a capture of something else). A Wayback pages channel is `sourceKind: "social"` + + `platform: "webpage"`, so the posts index pass, the per-site posts manifests, compose, search and `get_post` carry + its records with no reader of their own (proved through the real `buildIndex` and `compose-site`). The MCP's post + markdown prints a page's author plain (no "@"); a video manifest leaves a page citation out with a warning, as it + does a forum post. A post fetch refuses a Wayback pages channel (`WAYBACK_PAGES_NOT_FETCHED`, info for the + scheduler's skip): nothing is fetched unattended. +2. **`Post.page`** (`PagePostInfo`), validated by `parsePagePostInfo` (`lib/waybackPages/parse.ts`, client-safe): a + page without its provenance or extractor is dropped, never the post. +3. **`WaybackClient.getCapture(ts, url, {raw, maxBytes?})`** — the `id_` body through `ArchiveOrgClient.getBounded` + (new: a manual-redirect GET whose body is read to the cap and no further, the gap counted from its end). 2 MB cap + (`WAYBACK_PAGE_MAX_BYTES`, a constant — no settings key fits); text/html, text/plain, application/json only; + redirects followed by hand inside web.archive.org only (≤ 5, re-formed as `id_`), the FINAL capture's timestamp + and URL answered; `WaybackCaptureRefusal` (`mimetype`, `too-large`, `offsite-redirect`, `redirect-loop`, + `not-archived`). `closestCapture(url, at)`: one CDX request with `closest`/`sort=closest`, 200s only, re-sorted by + distance (`waybackCdxUrl` gained `closest`). The process client honours `E2E_WAYBACK_ORIGIN_FILE`. +4. **Storage** — `channels/<slug>/pages/<captureTs>-<urlHash>/raw.html.gz` + `capture.json` + (`lib/waybackPages/store-server.ts`): body first, then capture.json, each tmp + rename. At the channel root, + never under `data/<id>/`, so the media tier never moves it. +5. **The generic extractor** (`extractors/generic.ts`, v1) and **`extractPage`** (`extract.ts`): toolbar insert, + `wm-ipp*`, `/_static/`, wombat and `__wm.` stripped; furniture pruned; `<main>`/`[role=main]`, else top-level + `<article>`s, else the densest block; headings, paragraphs, `- ` list items, `> ` blockquotes, `<pre>`, link text, + image alts; title og:title → `<title>` → h1; author/date from JSON-LD, meta and `<time>`, a date after the capture + not believed; links un-rewritten and absolute against the original; images as `/web/<ts>im_/<src>`. Plain text and + JSON as they are. The dispatcher offers HTML to `SITE_EXTRACTORS` in order; a throw or no record falls back to + generic and the record says so (`page.extractorFallback`). `decodeCaptureBody` decodes by the header's, else the + document's, charset. +6. **Draft → Post** (`toPost.ts`) and **the split-record merge** inside `upsertPosts`: the later capture's facts + win, `firstSeenTs` keeps the earliest, the stored createdAt (and shard) is kept; records compared by sorted-key + JSON of what a reader reads back. `assignPageVersions`: later whole-page captures of a page name the first as + `versionOf`. `replaceChannelPosts` (posts-server) rewrites a channel's posts whole for a re-extract. +7. **`import-page`** (`controller/importPage.ts`): job kind on `platform:archive.org` (`needsText`, an ingest kind), + the ops action `{slug, url, at?, dryRun?}`, the CLI `archilyzer wayback pages import`, the channel page's **Import + a capture** (URL + date picker, the job linked). Refused before any job: no channel, not a pages channel, a + listing or a bare URL with no date, a video ("use import-video"), an X capture outside an X-scoped channel while + X is private. A stored capture is not fetched again. `startImportPageJob` is lane B's door. + **`reextract-pages`** (`controller/reextractPages.ts`): every stored capture re-read (no request), stale counted + (extractor/version not what it would go to now, or a fallback), records replaced when anything differs (a record + whose capture is not stored is kept); a job on the same queue (ops + the channel page's **Re-extract**), and the + CLI `archilyzer wayback pages reextract` in-process (editor stopped). +8. **The channel kind** — `config.wayback = {targets: [{url, match, from?, to?, mime?, include?, exclude?}], + collapse?}` (`lib/waybackPages/config.ts`, in `channelConfigSchema.ts`, CHANNEL.md). The New channel form detects + a Wayback URL of a non-video page (`isWaybackPagesUrl`) or takes "Wayback pages" as the platform; targets are rows + (`WaybackTargetsField.tsx`) posted as one JSON field; `waybackTargetFromUrl` derives the first; the handle is its + host; "Fetch posts now" is not offered. `create-channel` over ops takes the same fields (`waybackTargets`). +9. **X** — `isXPostsChannel` answers true for a Wayback pages channel scoped on x.com / twitter.com / + mobile.twitter.com, so a public site leaves it out while `social.x.visibility` is private. +10. **The fake** — `fakeWayback.mjs` serves page captures raw (an article in furniture, two captures; a toolbar + body; 3 MB; text/plain; image/jpeg; an off-archive redirect), 302s a missing timestamp to the nearest, and its + CDX honours `closest`. + +## Interfaces + +- `PostPlatform` + `"webpage"`; `Post.page?: PagePostInfo`; `PagePostInfo.extractorFallback?` (additive, the one + change to the shared contract). +- `WaybackClient.getCapture`, `closestCapture`, `WaybackRawCapture`, `WaybackCaptureRefusal`, + `WAYBACK_PAGE_MAX_BYTES`, `WAYBACK_MAX_REDIRECTS`, `waybackTestOrigin`; `ArchiveOrgClient.getBounded`, + `BoundedResponse`; `waybackCdxUrl(url, {closest})`. +- `lib/waybackPages/`: `config.ts` (`WaybackTarget`, `WaybackPagesConfig`, `coerceWaybackPagesConfig`, + `coerceWaybackTarget`, `isWaybackPagesChannel`, `waybackTargetFromUrl`, `waybackTargetHost`), `urls.ts` + (`PAGE_MIMETYPES`, `parsePageCaptureAsk`, `videoPageOf`, `captureTsIso`, `isXHostUrl`, `isXTargetUrl`, + `isWaybackPagesUrl`), `parse.ts`, `extract.ts` (`extractPage`, `chooseExtractor`, `decodeCaptureBody`), + `extractors/generic.ts` (`genericExtractor`, `stripWaybackChrome`, `unrewriteWaybackUrl`, `absoluteOriginalUrl`, + `waybackImageUrl`), `toPost.ts` (`draftToPost`, `mergePageRecord`, `assignPageVersions`, `isWholePageRecord`, + `stableRecordJson`, `asStored`), `store-server.ts` (`StoredCapture`, `writeStoredCapture`, `listStoredCaptures`, + `readStoredCaptureBody`, `hasStoredCapture`, `countStoredCaptures`, …). +- `controller/importPage.ts`: `planImportPage`, `importPage`, `queueImportPage`, **`startImportPageJob({slug, url, + at?, requestedBy?, paths?}) → {jobId}`** (throws `ImportPageRefusal`), `recordsOfCapture`, `xCaptureRefusal`, + `WAYBACK_PAGES_QUEUE`, `IMPORT_PAGE_JOB_KIND`, `IMPORT_PAGE_RESULT_MARKER`. `controller/reextractPages.ts`: + `reextractPages`, `queueReextractPages`, `REEXTRACT_PAGES_*`. +- `posts-server.ts`: `replaceChannelPosts`. `fetchPosts.ts`: `WAYBACK_PAGES_NOT_FETCHED`. +- Routes: `POST /api/ops/import-page`, `POST /api/ops/reextract-pages`. Actions: + `editor/app/channels/[slug]/waybackPagesActions.ts`. + +## Files + +common: `lib/platform.ts`, `lib/posts.ts`, `lib/posts-server.ts`, `lib/postsVisibility.ts`, `lib/channelConfig.ts`, +`lib/channelConfigSchema.ts` (+ test's key count), `lib/archiveOrgClient.ts`, `lib/waybackClient.ts` +(+ `waybackClient.pages.test.ts`), `lib/waybackPages/{config,urls,parse,extract,toPost,store-server}.ts`, +`lib/waybackPages/types.ts` (one additive field), `lib/waybackPages/extractors/generic.ts`, tests +`lib/waybackPages/{config,toPost}.test.ts`, `extractors/generic.test.ts`, `controller/importPage.ts` (+ test), +`controller/reextractPages.ts`, `controller/fetchPosts.ts`, `jobs/jobKinds.ts`, `bin/wayback-pages.ts`, +`bin/archilyzer.ts`, `bin/compose-site.waybackPages.test.ts`, `lib/envVars.ts`, `lib/citations/schema.ts` (two doc +strings), `lib/report/{convert-server,convertManifest}.ts`, `testing/web/fakeWayback.{mjs,d.mts}`, +`testing/README.md`. mcp: `src/server.ts` (one condition). editor: `app/channels/[slug]/{page.tsx, +waybackPagesActions.ts, socialActions.ts, components/WaybackPagesPanel.tsx}`, +`app/channels/components/{ChannelForm.tsx, WaybackTargetsField.tsx, parseChannelForm.ts (+ test), +channelConfigToForm.ts}`, `app/api/ops/{import-page,reextract-pages}/route.ts`, `e2e/wayback-pages.spec.ts`, +`e2e/servers.ts`, `playwright.config.ts`, `CHANGELOG.md`. scripts: `archilyzer-ops.mjs` (+ test). Docs: OPERATING.md +("Pages from the Wayback Machine"), COMMANDS.md, CHANNEL.md, CITATIONS.md, ENVIRONMENT.md (regenerated), +plans/FACTS.md ("Release 37 lane A: page records"). + +## Commits + +| sha | what | +|---|---| +| `1d2fdf32` | the common half: platform, Post.page, getCapture, pages/ storage, generic extractor, import-page, reextract-pages, ops actions, CLI rows, the fake | +| `76455fa9` | the editor half: New channel form kind + targets, the channel page (Import a capture, Re-extract), ops routes, e2e spec | +| `0861c490` | this record, FACTS, OPERATING | +| `a926ba17` | a nearest import fetches by CDX's own original URL | +| `68f278c4` | merge main (lane C's site extractors) + the dispatcher test over their fixtures, tumblr's PostPlatform cast dropped | +| `e9c97614` | lane C's fixture reader opts out of Turbopack tracing (next-build-trace.test) | + +## Gates + +All through the session's locks, from the worktree root. + +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean before each code commit and on the merged + tree. +- common: start 4695 (4693 pass, 2 skipped); after the lane, before the merge, **4728 / 4726 pass / 0 fail / 2 + skipped** (+33). Merged with lane C: **4765 / 4762 / 1 / 2** — the one is `controller/seeder.test.ts` (torrent + seeding over WebRTC), which hung 19 minutes in that run and was killed; alone it passes (49/49 with the wayback + extractor tests). It passed in the pre-merge full run. +- editor unit: 353 → **356 / 356** (+3, parseChannelForm). +- mcp: **379 / 379** (unchanged). +- test:scripts: 1315 → **1316: 1311 pass, 1 fail, 4 skipped** on the merged tree — the fail was + `next-build-trace.test.mjs`'s cwd-path check on lane C's `__fixtures__/capture.ts`; fixed in `e9c97614`, the file + re-run **9 pass / 0 fail / 1 skipped**. Pre-merge: 1312 pass / 0 fail / 4 skipped. +- Docs: `docs env --check`, `docs files --check`, `docs cli --check`, `settings example --check`: all 0. +- e2e (editor, start mode, stamp `25cf06a2dbf6` at `68f278c4`): `wayback-pages.spec.ts` + `ops-api.spec.ts` **18 / 18 + passed** (1.1 min); `social-channel.spec.ts` **6 / 6 passed** (1.7 min). + +## Rulings followed / decisions + +- No settings key for the 2 MB cap (none fits): a constant plus the `maxBytes` option. +- The record uses the FINAL capture after redirects (timestamp and original URL); `capture.json` keeps what was + asked (`requestedTs`, `requestedUrl`). +- No reindex at import: the index picks the records up on its next build, exactly as after a post fetch (which + reindexes nothing either). +- X visibility is per CHANNEL (the index and compose rule is channel-level): an X-scoped pages channel is an X + channel; while X is private an X capture into any other pages channel is refused, so no X capture can reach a + public site through a non-X channel. +- A page kind is validated as a word, not against `PAGE_KINDS`, so an older reader keeps a newer extractor's + records. +- `reextract-pages` rewrites the channel's posts whole (it may move a record's month); every other writer stays + append-only. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -118,6 +118,9 @@ // pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait // pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait // pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait +// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}' +// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait +// pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait // pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait // pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}' // pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait @@ -439,6 +442,13 @@ const ACTIONS = [ "archive-search", "archive-item", "import-post", + // WAYBACK PAGES (release 37): ONE Wayback Machine capture of a page that is + // not a video into a Wayback pages channel ({slug, url} — a capture's replay + // URL — or {slug, url: <the page>, at: YYYYMMDD}; dryRun?), as an + // import-page job on the archive.org queue; and a channel's records + // re-derived from its stored captures ({slug, dryRun?}), offline, as a job. + "import-page", + "reextract-pages", // EVIDENCE GAPS (release 29 E2): the Wayback Machine's captures of a page // ({url} or a record's {slug, id}), read only and paced; and find-copy — a // copy of every gone recording a report cites (Wayback, then archive.org), @@ -1451,6 +1461,31 @@ export function usage() { " one the platform says is another account's is not written. The log ends", " with @@import-post {ok, slug, url, id, written, already?, post?, error?}.", "", + 'import-page imports ONE Wayback Machine capture of a page that is not a', + ' video into a Wayback pages channel (platform "webpage"): {"slug", "url"}', + " — a capture's replay URL (web.archive.org/web/<timestamp>/<page>) — or", + ' {"slug", "url": <the page>, "at": "YYYYMMDD[hhmmss]"} for the capture', + " nearest that date (one CDX lookup). An import-page job on the archive.org", + " queue, at archive.org's pace: the raw (id_) body, at most 2 MB, html,", + " plain text or JSON only, redirects followed inside the archive only and", + " the FINAL capture recorded; stored under the channel's pages/, read by", + " the first site extractor that claims it (else the generic one), its page", + " records written to the channel's posts. Refused, before any job: no such", + " channel, not a Wayback pages channel, a URL that names no capture, a", + " video (use import-video), an X capture outside an X channel while", + ' social.x.visibility is "private". A capture already stored is not', + ' fetched again. "dryRun" answers what it would fetch and starts nothing.', + " The log ends with @@import-page {ok, slug, url, captureTs, originalUrl,", + " records, written, updated, unchanged, extractor, already?, error?}.", + "", + "reextract-pages re-derives a Wayback pages channel's records from the raw", + ' captures it stores: {"slug", "dryRun"?}. No request. A reextract-pages job', + " on the archive.org queue (never beside an import into the channel): every", + " stored capture read again by the extractor it goes to now, the records", + " replaced when anything differs. The log ends with @@reextract-pages", + " {captures, stale, records: {added, changed, removed, unchanged, kept},", + " written}.", + "", 'report-draft runs a generation over an article\'s iteration as a', ' report-draft job: {"task": "sweep" | "revise-report" | "revise-video" |', ' "research" | a media draft, "article", ...} -> {jobId, iteration,', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -892,3 +892,21 @@ test("report-schedule is registered, posts to its route, and --wait prints a tic assert.match(usage(), /report-schedule keeps a recurring report on a cadence the editor ticks/); assert.match(usage(), /\{"lane": "report-schedule", "held"\}/); }); + +// Release 37 S1: a Wayback page capture's import and a pages channel's +// re-extract are POSTs to their routes, the body passed through untouched. +test("import-page and reextract-pages are POSTs to their routes, named in the usage", () => { + const p = parseArgs([ + "import-page", + "--json", + '{"slug":"old-blog","url":"https://blog.example/a.html","at":"20140301","dryRun":true}', + ]); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/import-page"); + assert.deepEqual(p.body, { slug: "old-blog", url: "https://blog.example/a.html", at: "20140301", dryRun: true }); + const r = parseArgs(["reextract-pages", "--json", '{"slug":"old-blog"}', "--wait"]); + assert.equal(r.path, "/api/ops/reextract-pages"); + assert.equal(r.wait, true); + assert.match(usage(), /Actions:.*import-post, import-page, reextract-pages/); + assert.match(usage(), /import-page imports ONE Wayback Machine capture/); +});