// Reading an X post's CONTEXT off the post page capture-posts has ALREADY // loaded: the post it QUOTES (the card inside its own article) and the post it // ANSWERS (the article above it), into capture.json's `context` // (postCapture.ts has the record's shape). // // Why: the archive often names neither. A timeline read keeps no quoted post // unless gallery-dl is asked to (xGalleryDlFetcher.ts now asks), and a reply's // parent is another account's post, never archived with the account's own -- // so a post video drew "you called me a Leftist…" with nothing it answered. // The page shows both, so the capture that loads it reads them. // // NO EXTRA PAGE LOAD. Two evaluates over the page as it stands, before any // shot (the thread shot's blur is a CSS filter; the read sees X's drawing): // 1. the thread snapshot (xThreadShot.ts) and its pick of the IMMEDIATE // parent -- the article whose status link is the archive's in-reply-to // id, else (the archive not saying) the article directly above the post; // an archive id not on the page is no parent at all. Read whether or not // the archive calls the post a reply: X draws only a status's ancestors // above it, and the archive is often what is wrong; // 2. the context read: that parent article's author, check, date, words and // media, and the post's own quote card (a `div[role="link"]` inside its // article holding a User-Name) -- the same fields, and its status id when // a link inside the card names one (a quote card often has none: the // archive's quoted id fills it, when its author agrees). // // The words are kept whole; the people are not judged here. Whose name a card // may show is the card's rule (umtool post-item.mjs authorRedaction), which // blurs every author but the subject unless gold- or grey-checked -- the // badge recorded here is what it decides by. capture.json is editor-only. // // NOT VERIFIED AGAINST LIVE X: the markup is X's as of 2026-11, proved against // a recorded-style fixture page in a real Chromium // (xAvatarCapture.browser.test.ts); the first real run is the check. import type { PageLike } from "./playwrightRuntime"; import type { PostContextPost, PostContextRecord } from "./postCapture"; import { BADGE_OF_JS, pickThreadParent, threadSnapshotScript, type ThreadSnapshot } from "./xThreadShot"; export const CONTEXT_SCRIPT_MARKER = "__archilyzerContext"; // The longest text kept of one context post (a long post's whole body is a // note-tweet's 25,000; a card never draws more than a few lines of context). export const CONTEXT_TEXT_MAX = 10_000; const MEDIA_MAX = 4; // The in-page read: the parent article at `parentIndex` (among // `article[data-testid="tweet"]`, the thread snapshot's order) and the quote // card inside the marked own article. Each as { id, handle, author, verified, // badge, date, text, media }; null where there is none. Null altogether when // the own article is not marked. export const contextScript = (parentIndex: number | null) => `(() => { const ${CONTEXT_SCRIPT_MARKER} = true; const badgeOf = ${BADGE_OF_JS}; const all = Array.from(document.querySelectorAll('article[data-testid="tweet"]')); const own = document.querySelector("[data-archilyzer-capture]"); if (!own) return null; const HANDLE = /^[A-Za-z0-9_]{1,30}$/; // A quote card: a div link inside an article, holding a User-Name. const inCard = (el, root) => { const q = el.closest('div[role="link"]'); return !!q && root.contains(q) && q !== root; }; const cardOf = (a) => Array.from(a.querySelectorAll('div[role="link"]')).find((q) => q.querySelector('[data-testid="User-Name"]')) || null; const read = (root, isCard) => { // An article's own parts, never its quote card's; a card's, all of them. const pick = (sel) => Array.from(root.querySelectorAll(sel)).filter((el) => isCard || !inCard(el, root)); const un = pick('[data-testid="User-Name"]')[0] || null; let handle = null, id = null; const links = pick('a[href*="/status/"]'); const timed = links.filter((l) => l.querySelector("time")); for (const l of [...timed, ...(isCard ? links : [])]) { const m = /^(?:https:\\/\\/(?:x|twitter)\\.com)?\\/([A-Za-z0-9_]{1,30})\\/status\\/(\\d+)/.exec(l.getAttribute("href") || ""); if (m) { handle = m[1]; id = m[2]; break; } } if (!handle) { const c = pick('[data-testid^="UserAvatar-Container-"]')[0]; const t = c ? (c.getAttribute("data-testid") || "").replace(/^UserAvatar-Container-/, "") : ""; if (HANDLE.test(t)) handle = t; } const lines = un ? (un.innerText || "").split("\\n").map((s) => s.trim()).filter((s) => s && s !== "·") : []; if (!handle) { const at = lines.map((s) => /(?:^|\\s)@([A-Za-z0-9_]{1,30})\\b/.exec(s)).find(Boolean); if (at) handle = at[1]; } let author = null; if (un && handle) { for (const l of un.querySelectorAll("a[href]")) { const h = (l.getAttribute("href") || "").split(/[?#]/)[0].toLowerCase(); const t = (l.innerText || "").trim(); if (h === "/" + handle.toLowerCase() && t && !t.startsWith("@")) { author = t; break; } } } if (!author && lines[0] && !lines[0].startsWith("@")) author = lines[0].split(/\\s+@[A-Za-z0-9_]/)[0].trim() || null; const icon = un && un.querySelector('[data-testid="icon-verified"]'); const time = (timed[0] && timed[0].querySelector("time[datetime]")) || pick("time[datetime]")[0] || null; const words = pick('[data-testid="tweetText"]')[0]; const media = []; for (const img of pick('[data-testid="tweetPhoto"] img[src]')) media.push({ kind: "image", url: img.src }); for (const v of pick("video")) { const u = v.poster || v.currentSrc || v.src; if (u) media.push({ kind: "video", url: new URL(u, location.href).href }); } return { id, handle, author, verified: !!icon, badge: icon ? badgeOf(icon) : null, date: time ? time.getAttribute("datetime") : null, text: words ? (words.innerText || "").trim() : "", media, }; }; const card = cardOf(own); const parent = ${parentIndex === null ? "null" : `all[${Math.floor(parentIndex)}] || null`}; return { quoted: card ? read(card, true) : null, parent: parent && parent !== own ? read(parent, false) : null }; })()`; const HANDLE_RE = /^[A-Za-z0-9_]{1,30}$/; const ID_RE = /^\d{1,25}$/; const BADGES = new Set(["blue", "gold", "grey", "other"]); function statusUrl(id: string | undefined, handle: string | undefined): string | undefined { if (!id) return undefined; return handle ? `https://x.com/${handle}/status/${id}` : `https://x.com/i/status/${id}`; } // One post of what the read returned, kept to the shape (null: not a post — // no author and no words is nothing to draw). export function parseContextPost(raw: unknown): PostContextPost | null { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; const r = raw as Record; const s = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim() : undefined); const id = s(r.id) && ID_RE.test(s(r.id)!) ? s(r.id) : undefined; const handle = s(r.handle)?.replace(/^@/, ""); const okHandle = handle && HANDLE_RE.test(handle) ? handle : undefined; const text = typeof r.text === "string" ? r.text.trim().slice(0, CONTEXT_TEXT_MAX) : ""; if (!okHandle && !text) return null; const author = s(r.author)?.slice(0, 200); const dateRaw = s(r.date); const date = dateRaw && Number.isFinite(Date.parse(dateRaw)) ? new Date(Date.parse(dateRaw)).toISOString() : undefined; const badge = typeof r.badge === "string" && BADGES.has(r.badge) ? (r.badge as PostContextPost["badge"]) : undefined; const media: PostContextPost["media"] = []; const seen = new Set(); for (const m of Array.isArray(r.media) ? r.media : []) { if (!m || typeof m !== "object") continue; const { kind, url } = m as Record; if ((kind !== "image" && kind !== "video") || typeof url !== "string" || !/^https?:\/\//.test(url) || seen.has(url)) continue; seen.add(url); media.push({ kind, url }); if (media.length >= MEDIA_MAX) break; } const url = statusUrl(id, okHandle); return { ...(id ? { id } : {}), ...(url ? { url } : {}), ...(okHandle ? { handle: okHandle } : {}), ...(author ? { author } : {}), ...(r.verified === true ? { verified: true } : {}), ...(badge ? { badge } : {}), ...(date ? { date } : {}), text, media, }; } export type XContextReadOptions = { // What the archive says the post answers, when it says (the parent is the // article with this status id; not on the page means no parent). replyTo?: { id?: string; author?: string } | null; // What the archive says it quotes: its id fills a quote card that names // none, when the authors agree. quoted?: { id?: string; author?: string } | null; now?: () => Date; }; const sameHandle = (a?: string, b?: string) => !!a && !!b && a.replace(/^@/, "").toLowerCase() === b.replace(/^@/, "").toLowerCase(); // The whole record from the read's answer and the parent pick. Pure. Null // when the answer is not the read's shape (the page could not be read: a // later run reads it again). export function contextRecordFrom( raw: unknown, pick: { from: "reply-to" | "above" } | null, o: Pick & { readAt: string }, ): PostContextRecord | null { if (!raw || typeof raw !== "object" || Array.isArray(raw) || !("quoted" in raw) || !("parent" in raw)) return null; const r = raw as { quoted: unknown; parent: unknown }; const record: PostContextRecord = { readAt: o.readAt }; const quoted = parseContextPost(r.quoted); if (quoted) { const arch = o.quoted; if (!quoted.id && arch?.id && ID_RE.test(arch.id) && (!arch.author || !quoted.handle || sameHandle(arch.author, quoted.handle))) { quoted.id = arch.id; quoted.url = statusUrl(arch.id, quoted.handle ?? arch.author?.replace(/^@/, "")); } record.quoted = quoted; } const parent = pick ? parseContextPost(r.parent) : null; if (parent && pick) record.parent = { ...parent, from: pick.from }; return record; } // The read, in the page shot — never throws: an unreadable page is null. export async function readXPostContext(page: PageLike, o: XContextReadOptions = {}): Promise { try { const snap = (await page.evaluate(threadSnapshotScript()).catch(() => null)) as ThreadSnapshot | null; let parentIndex: number | null = null; let pick: { from: "reply-to" | "above" } | null = null; if (snap && Array.isArray(snap.articles) && typeof snap.own === "number") { const got = pickThreadParent(snap, o.replyTo ?? null); if ("index" in got) { parentIndex = got.index; pick = { from: got.from }; } } const raw = await page.evaluate(contextScript(parentIndex)); return contextRecordFrom(raw, pick, { quoted: o.quoted, readAt: (o.now ?? (() => new Date()))().toISOString() }); } catch { return null; } } export type XContextRunSummary = { // Posts whose context was read and recorded this run. read: number; // Of them, how many showed a quoted post / a parent. quoted: number; parents: number; // Posts not loaded for it: a context already recorded, or a deleted post. skipped: number; // Post pages loaded for the context alone (contextOnly). pages: number; failed: { id: string; error: string }[]; }; export function emptyContextSummary(): XContextRunSummary { return { read: 0, quoted: 0, parents: 0, skipped: 0, pages: 0, failed: [] }; } export function noteContext(s: XContextRunSummary, c: PostContextRecord): void { s.read++; if (c.quoted) s.quoted++; if (c.parent) s.parents++; } export function describeContextSummary(s: XContextRunSummary): string { return ( `Context: ${s.read} read (${s.quoted} quoting a post, ${s.parents} answering one)` + (s.skipped ? `, ${s.skipped} already read or deleted` : "") + (s.failed.length ? `, ${s.failed.length} failed (${s.failed.map((f) => f.id).join(", ")})` : "") + (s.pages ? `; ${s.pages} page(s) loaded for it` : "") + "." ); } // A one-line account of one post's context, for the run's log. export function describeContext(c: PostContextRecord): string { const who = (p: PostContextPost) => (p.handle ? `@${p.handle}` : p.author ?? "?") + (p.id ? ` ${p.id}` : ""); const parts = [c.parent ? `answers ${who(c.parent)}` : "", c.quoted ? `quotes ${who(c.quoted)}` : ""].filter(Boolean); return parts.length ? `context: ${parts.join(", ")}` : "context: no quote, no parent"; }