// 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-", // "tweet-"), 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 }; // Release 37 lane F: the capture is a copy on another archive source (not // the Wayback Machine): its id and the copy's URL there. The record's // `page.source` / `page.archiveUrl` say so, and its waybackUrl / rawUrl // are that URL (types.ts). source?: { id: string; mementoUrl: 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 other = ctx.source && ctx.source.id !== "wayback" ? ctx.source : null; const page: PagePostInfo = { originalUrl: capture.originalUrl, captureTs: capture.captureTs, waybackUrl: other ? other.mementoUrl : waybackPageUrl(ref), rawUrl: other ? other.mementoUrl : waybackRawUrl(ref), kind: draft.kind, extractor: ctx.extractor.name, extractorVersion: ctx.extractor.version, }; if (other) { page.source = other.id; page.archiveUrl = other.mementoUrl; } 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).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): 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(); 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; }