Archilyzer · Source

archilyzer

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

commit 88f9d97a67921dc555bc087a4cd4ac9dedea333b
parent 137d0fa55ce5d877f146824bf4368a245bb656bf
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 09:57:48 -0400

editor: Wayback pages channels — the New channel form's kind and targets, Import a capture, Re-extract, the import-page and reextract-pages ops routes

Release 37 lane A (S1), the editor half. A Wayback URL of a page that is not a
video makes a Wayback pages channel on the New channel form (platform
"webpage", one target derived; targets edited as rows, posted as one JSON
field the parser validates), with nothing fetched on create. The channel
page of such a channel shows what it holds, its targets and its recent page
records, an Import a capture field (a replay URL, or the page's URL and a
date) that starts an import-page job and links it, and Re-extract. A post
fetch refuses a Wayback pages channel (the scheduler's skip). The ops door:
import-page {slug, url, at?, dryRun?} and reextract-pages {slug, dryRun?}.
e2e: wayback-pages.spec.ts over the fake Wayback.

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

Diffstat:
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++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Aeditor/e2e/wayback-pages.spec.ts | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13 files changed, 717 insertions(+), 5 deletions(-)

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. - **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. - **Ask the assistant about a clip, and apply what it suggests with one click.** On a comment in the clip editor, **Ask the assistant** has the model read your comment, the clip's words and the clips around it, and reply in the thread (badged "agent"). When it suggests a concrete edit — new edges, a merge with the next clip, or leaving the clip out — the reply shows an **Apply** button; nothing changes until you click it, and Apply does exactly what the clip editor's own buttons do. The editor needs `UMTOOL_URL` set to post the reply. 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/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(); + } +});