// The context half of the X capture (the quoted post, the parent), against // fakes only: the parse of the in-page read's answer, the record built from // it, and the run (a normal capture and contextOnly) over a page that answers // the capture's evaluates. The in-page read itself is proved in a real // Chromium by xAvatarCapture.browser.test.ts, against the recorded-style page. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xPostContext.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readdir } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import type { PageLike } from "./playwrightRuntime"; import { captureXPosts, type XCaptureDeps, type XPostSnapshot } from "./xPostCapture"; import { CONTEXT_SCRIPT_MARKER, CONTEXT_TEXT_MAX, contextRecordFrom, contextScript, parseContextPost, readXPostContext, } from "./xPostContext"; import { THREAD_SNAPSHOT_MARKER, type ThreadSnapshot } from "./xThreadShot"; import { AVATARS_SCRIPT_MARKER } from "./xAvatarCapture"; import { VIEW_SCRIPT_MARKER } from "./viewportShot"; import { readPostCapture, writePostCapture } from "./postCapture"; import type { PostCaptureInput } from "./fetchers"; const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 9, 9]); const RECT = { x: 10, y: 120, width: 598, height: 300 }; const snap = (id: string): XPostSnapshot => ({ path: `/ObviousRises/status/${id}`, text: "the post", article: { rect: RECT, sensitive: false } }); // What the read returns for the operator's case: a reply to Kirsche, quoting // a third post. const KIRSCHE = { id: "1983000000000000001", handle: "Kirsche", author: "Kirsche", verified: true, badge: "blue", date: "2026-10-29T13:00:00.000Z", text: "Your whole channel is grift.", media: [], }; const QUOTED = { id: null, handle: "quoted_person", author: "Quoted Person", verified: false, badge: null, date: "2026-10-28T09:00:00.000Z", text: "The receipt itself.", media: [{ kind: "image", url: "https://pbs.twimg.com/media/QQ1.jpg?format=jpg&name=small" }], }; const THREAD: ThreadSnapshot = { own: 1, articles: [ { id: KIRSCHE.id, handle: "Kirsche", verified: true, badge: "blue", top: 0, bottom: 200 }, { id: "1983000000000000002", handle: "ObviousRises", verified: false, top: 200, bottom: 500 }, ], }; test("parse: the read's post kept to the shape — ids are digits, the date ISO, the media http(s) and at most four, the text capped", () => { const p = parseContextPost({ ...KIRSCHE, handle: "@Kirsche", date: "2026-10-29T13:00:00Z", badge: "platinum", media: [ { kind: "image", url: "https://pbs.twimg.com/media/a.jpg" }, { kind: "image", url: "https://pbs.twimg.com/media/a.jpg" }, { kind: "gif", url: "https://pbs.twimg.com/media/b.jpg" }, { kind: "video", url: "javascript:alert(1)" }, { kind: "video", url: "https://pbs.twimg.com/ext_tw_video_thumb/1/pu/img/c.jpg" }, ], }); assert.deepEqual(p, { id: KIRSCHE.id, url: `https://x.com/Kirsche/status/${KIRSCHE.id}`, handle: "Kirsche", author: "Kirsche", verified: true, date: "2026-10-29T13:00:00.000Z", text: "Your whole channel is grift.", media: [ { kind: "image", url: "https://pbs.twimg.com/media/a.jpg" }, { kind: "video", url: "https://pbs.twimg.com/ext_tw_video_thumb/1/pu/img/c.jpg" }, ], }); assert.equal(parseContextPost({ ...KIRSCHE, id: "../etc", handle: "not a handle!" })?.id, undefined); assert.equal(parseContextPost({ ...KIRSCHE, text: "x".repeat(CONTEXT_TEXT_MAX + 50) })?.text.length, CONTEXT_TEXT_MAX); // Nobody and nothing said is no post. assert.equal(parseContextPost({ handle: null, text: " " }), null); assert.equal(parseContextPost("a string"), null); assert.equal(parseContextPost(null), null); }); test("record: the quote and the parent with how the parent was told; the archive's quoted id fills a card that names none, only when the authors agree", () => { const rec = contextRecordFrom({ quoted: QUOTED, parent: KIRSCHE }, { from: "above" }, { quoted: { id: "1982000000000000009", author: "quoted_person" }, readAt: "2026-11-02T20:00:00.000Z", }); assert.equal(rec?.readAt, "2026-11-02T20:00:00.000Z"); assert.equal(rec?.parent?.from, "above"); assert.equal(rec?.parent?.handle, "Kirsche"); assert.equal(rec?.parent?.badge, "blue"); assert.equal(rec?.quoted?.id, "1982000000000000009"); assert.equal(rec?.quoted?.url, "https://x.com/quoted_person/status/1982000000000000009"); assert.equal(rec?.quoted?.media.length, 1); const other = contextRecordFrom({ quoted: QUOTED, parent: null }, null, { quoted: { id: "1982000000000000009", author: "someone_else" }, readAt: "t" }); assert.equal(other?.quoted?.id, undefined, "another author's id is not this card's"); // No pick: no parent, whatever the page answered. assert.equal(contextRecordFrom({ quoted: null, parent: KIRSCHE }, null, { readAt: "t" })?.parent, undefined); // Neither: still a read. assert.deepEqual(contextRecordFrom({ quoted: null, parent: null }, null, { readAt: "t" }), { readAt: "t" }); // Not the read's shape: not read. assert.equal(contextRecordFrom(snap("1"), null, { readAt: "t" }), null); assert.equal(contextRecordFrom(null, null, { readAt: "t" }), null); }); test("script: carries its marker; reads the parent at the picked index, or none", () => { assert.ok(contextScript(0).includes(CONTEXT_SCRIPT_MARKER)); assert.match(contextScript(3), /all\[3\] \|\| null/); assert.match(contextScript(null), /const parent = null;/); assert.ok(contextScript(null).includes("badgeOf"), "the badge is told as the thread snapshot tells it"); }); function contextPage(answer: { quoted: unknown; parent: unknown }, thread: ThreadSnapshot = THREAD) { const reads: string[] = []; const gotos: string[] = []; let current = ""; const page: PageLike & { reads: string[]; gotos: string[]; shots: number } = { reads, gotos, shots: 0, goto: async (url: string) => { gotos.push(url); current = /status\/(\d+)/.exec(url)?.[1] ?? ""; }, waitForSelector: async () => undefined, waitForTimeout: async () => undefined, on: () => {}, evaluate: async (script: string) => { if (script.includes(THREAD_SNAPSHOT_MARKER)) { reads.push("thread"); return thread; } if (script.includes(CONTEXT_SCRIPT_MARKER)) { reads.push(`context ${/all\[(\d+)\]/.exec(script)?.[1] ?? "none"}`); return answer; } if (script.includes(AVATARS_SCRIPT_MARKER)) return []; if (script.includes(VIEW_SCRIPT_MARKER)) return null; if (script.includes("imgs.length")) return 0; return snap(current); }, screenshot: async () => { page.shots++; return PNG; }, }; return page; } test("read: the parent is the archive's in-reply-to id when it says, else the article above; an id not on the page is no parent", async () => { const page = contextPage({ quoted: null, parent: KIRSCHE }); const told = await readXPostContext(page, { replyTo: { id: KIRSCHE.id }, now: () => new Date("2026-11-02T00:00:00Z") }); assert.equal(told?.parent?.from, "reply-to"); assert.deepEqual(page.reads, ["thread", "context 0"]); // The archive says nothing (the operator's case): the article above. assert.equal((await readXPostContext(page, { replyTo: null }))?.parent?.from, "above"); // An id not on the page: the article above is not taken for it. page.reads.length = 0; const wrong = await readXPostContext(page, { replyTo: { id: "1" } }); assert.equal(wrong?.parent, undefined); assert.deepEqual(page.reads, ["thread", "context none"]); }); const deps = (page: PageLike, pauses: number[] = []): XCaptureDeps => ({ openPage: async () => ({ page, close: async () => {} }), downloadMedia: async () => ({ ok: true, files: [] }), pauseMs: () => 5000, pause: async (ms) => void pauses.push(ms), now: () => new Date("2026-11-02T20:00:00.000Z"), }); const input = async (over: Partial = {}): Promise => ({ ids: ["1983000000000000002"], handle: "ObviousRises", outDir: path.join(await mkdtemp(path.join(os.tmpdir(), "xcontext-")), "posts-media"), signal: new AbortController().signal, media: false, articles: false, avatars: false, ...over, }); test("run: a normal capture writes the context it read into capture.json, from the page it shot — one load", async () => { const page = contextPage({ quoted: QUOTED, parent: KIRSCHE }); const inp = await input(); const res = await captureXPosts(inp, deps(page)); assert.equal(res.outcomes[0]?.state, "captured"); assert.equal(page.gotos.length, 1); assert.equal(page.shots, 1); const rec = await readPostCapture(path.join(inp.outDir, "1983000000000000002")); assert.equal(rec?.context?.readAt, "2026-11-02T20:00:00.000Z"); assert.equal(rec?.context?.parent?.handle, "Kirsche"); assert.equal(rec?.context?.quoted?.text, "The receipt itself."); assert.deepEqual(res.context, { read: 1, quoted: 1, parents: 1, skipped: 0, pages: 0, failed: [] }); // context: false reads none, and keeps the one on disk. const again = contextPage({ quoted: null, parent: null }); const res2 = await captureXPosts({ ...inp, force: true, context: false }, deps(again)); assert.equal(res2.context, undefined); assert.ok(!again.reads.includes("thread")); assert.equal((await readPostCapture(path.join(inp.outDir, "1983000000000000002")))?.context?.parent?.handle, "Kirsche"); }); test("contextOnly: one page per post, paced, no shot, the context merged into the record — or a record of its own; read ones and deleted ones not loaded", async () => { const page = contextPage({ quoted: QUOTED, parent: KIRSCHE }); const inp = await input({ ids: ["11", "22", "33", "44"], contextOnly: true, shots: false }); // 22 was shot before; 33's context is already read; 44 was found deleted. const shot = { name: "shot.png", bytes: 6, sha256: "ab" }; await writePostCapture(path.join(inp.outDir, "22"), { version: 1, id: "22", url: "https://x.com/i/status/22", capturedAt: "2026-10-01T00:00:00.000Z", state: "captured", shot, mediaState: "ok", media: [shot], }); await writePostCapture(path.join(inp.outDir, "33"), { version: 1, id: "33", url: "https://x.com/i/status/33", capturedAt: "x", state: "captured", mediaState: "none", media: [], context: { readAt: "2026-10-30T00:00:00.000Z" }, }); await writePostCapture(path.join(inp.outDir, "44"), { version: 1, id: "44", url: "https://x.com/i/status/44", capturedAt: "x", state: "deleted", mediaState: "skipped", media: [], }); const pauses: number[] = []; const res = await captureXPosts(inp, deps(page, pauses)); assert.deepEqual(res.outcomes, []); assert.deepEqual(page.gotos, ["https://x.com/i/status/11", "https://x.com/i/status/22"]); assert.deepEqual(pauses, [5000], "paced before every page after the first"); assert.equal(page.shots, 0); assert.deepEqual(res.context, { read: 2, quoted: 2, parents: 2, skipped: 2, pages: 2, failed: [] }); const fresh = (await readPostCapture(path.join(inp.outDir, "11")))!; assert.equal(fresh.state, "captured"); assert.equal(fresh.shot, undefined); assert.equal(fresh.mediaState, "skipped", "the media is still owed"); assert.equal(fresh.context?.parent?.id, KIRSCHE.id); assert.deepEqual(await readdir(path.join(inp.outDir, "11")), ["capture.json"]); const merged = (await readPostCapture(path.join(inp.outDir, "22")))!; assert.deepEqual(merged.shot, shot); assert.equal(merged.capturedAt, "2026-10-01T00:00:00.000Z"); assert.equal(merged.context?.quoted?.handle, "quoted_person"); assert.equal((await readPostCapture(path.join(inp.outDir, "33")))?.context?.readAt, "2026-10-30T00:00:00.000Z"); // force reads again. const page2 = contextPage({ quoted: null, parent: null }); await captureXPosts({ ...inp, ids: ["33"], force: true }, deps(page2)); assert.deepEqual((await readPostCapture(path.join(inp.outDir, "33")))?.context, { readAt: "2026-11-02T20:00:00.000Z" }); }); test("contextOnly: a login wall stops the run with needsCookies, the rest left; a page that is not the post writes nothing", async () => { let n = 0; const page = contextPage({ quoted: null, parent: null }); const inner = page.evaluate; page.evaluate = async (s: string) => { if (!s.includes(CONTEXT_SCRIPT_MARKER) && !s.includes(THREAD_SNAPSHOT_MARKER) && !s.includes("imgs.length")) { n++; if (n === 1) return { path: "/i/status/11", text: "This post was deleted", article: null }; return { path: "/i/flow/login", text: "", article: null }; } return inner(s); }; const inp = await input({ ids: ["11", "22", "33"], contextOnly: true }); const res = await captureXPosts(inp, deps(page)); assert.equal(res.needsCookies, true); assert.match(res.stoppedEarly ?? "", /Stopped at 22/); assert.deepEqual(page.gotos, ["https://x.com/i/status/11", "https://x.com/i/status/22"]); assert.deepEqual(await readdir(inp.outDir).catch(() => []), []); assert.equal(res.context?.failed.length, 2); });