// The avatar half of the X capture, against fakes only: a page that answers // the capture's evaluates (the post's snapshot, the avatar read) and serves // the picture through a fake request context. No browser, no network — the // in-page read itself is proved in a real Chromium by // xAvatarCapture.browser.test.ts. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xAvatarCapture.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readdir, readFile } 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 { AVATARS_SCRIPT_MARKER, avatarsScript, parseAvatarCandidates, type XAvatarCandidate } from "./xAvatarCapture"; import { AVATARS_DIRNAME, readXAvatarIndex, writeXAvatar } from "./xAvatars"; import { VIEW_SCRIPT_MARKER } from "./viewportShot"; import type { PostCaptureInput } from "./fetchers"; const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 9, 9]); const JPG = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 7]); const RECT = { x: 10, y: 120, width: 598, height: 300 }; const snap = (id: string): XPostSnapshot => ({ path: `/someone/status/${id}`, text: "the post", article: { rect: RECT, sensitive: false } }); const pic = (n: string) => `https://pbs.twimg.com/profile_images/${n}/face_normal.jpg`; type Fake = PageLike & { gotos: string[]; gets: string[]; reads: string[]; shots: number }; // Each status page answers with its snapshot and the avatars `byId` names. function fakePage(byId: Record): Fake { let current = ""; const gotos: string[] = []; const gets: string[] = []; const reads: string[] = []; const page: Fake = { gotos, gets, reads, 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(AVATARS_SCRIPT_MARKER)) { reads.push(script); return byId[current] ?? []; } if (script.includes(VIEW_SCRIPT_MARKER)) return null; if (script.includes("imgs.length")) return 0; return snap(current); }, screenshot: async () => { page.shots++; return PNG; }, request: { get: async (url: string) => { gets.push(url); return { ok: () => true, status: () => 200, headers: () => ({ "content-type": "image/jpeg" }), body: async () => JPG, }; }, }, }; return page; } function deps(page: Fake, over: Partial = {}): XCaptureDeps & { pauses: number[]; opened: number } { const d = { pauses: [] as number[], opened: 0, openPage: async () => { d.opened++; return { page, close: async () => {} }; }, downloadMedia: async () => ({ ok: true as const, files: [] }), pauseMs: () => 4000, pause: async (ms: number) => { d.pauses.push(ms); }, now: () => new Date("2026-11-02T20:00:00.000Z"), ...over, }; return d; } async function outDir(): Promise { return path.join(await mkdtemp(path.join(os.tmpdir(), "xavatar-run-")), "posts-media"); } const input = (out: string, ids: string[], over: Partial = {}): PostCaptureInput => ({ ids, handle: "ObviousRises", outDir: out, signal: new AbortController().signal, media: false, articles: false, ...over, }); test("read: the script carries its marker and the archive's parent id; its answer is kept to the shape", () => { const s = avatarsScript({ parent: true, quotes: true, parentId: "500" }); assert.ok(s.includes(AVATARS_SCRIPT_MARKER)); assert.ok(s.includes('"500"')); assert.deepEqual(parseAvatarCandidates({ path: "/x" }), []); assert.deepEqual( parseAvatarCandidates([ { role: "author", handle: "ObviousRises", src: pic("1") }, { role: "author", handle: "../x", src: pic("1") }, { role: "fan", handle: "a", src: pic("1") }, { role: "parent", handle: "b", src: "" }, null, ]), [{ role: "author", handle: "ObviousRises", src: pic("1") }], ); }); test("run: a normal capture stores the author's avatar from the page it shot — one load, one fetch at 400×400", async () => { const out = await outDir(); const page = fakePage({ "11": [{ role: "author", handle: "ObviousRises", src: pic("9") }] }); const d = deps(page); const res = await captureXPosts(input(out, ["11"]), d); assert.equal(res.outcomes[0].state, "captured"); assert.equal(page.gotos.length, 1); assert.equal(page.shots, 1); assert.deepEqual(page.gets, ["https://pbs.twimg.com/profile_images/9/face_400x400.jpg"]); assert.deepEqual(res.avatars?.stored, ["ObviousRises"]); const index = await readXAvatarIndex(path.join(out, AVATARS_DIRNAME)); assert.deepEqual(index, { ObviousRises: { file: "ObviousRises.jpg", url: "https://pbs.twimg.com/profile_images/9/face_400x400.jpg", capturedAt: "2026-11-02T20:00:00.000Z", postId: "11", }, }); assert.deepEqual(new Uint8Array(await readFile(path.join(out, AVATARS_DIRNAME, "ObviousRises.jpg"))), JPG); // Without the thread, only the author is looked for. assert.ok(page.reads[0].includes("const wantParent = false")); }); test("run: two posts of one author fetch the picture once; an author already stored is not fetched again", async () => { const out = await outDir(); const a = [{ role: "author" as const, handle: "ObviousRises", src: pic("9") }]; const page = fakePage({ "11": a, "12": a }); await captureXPosts(input(out, ["11", "12"]), deps(page)); assert.equal(page.gets.length, 1); // A later run: stored (under another case, even) — read, not fetched. const page2 = fakePage({ "13": [{ role: "author", handle: "obviousrises", src: pic("9") }] }); const res = await captureXPosts(input(out, ["13"]), deps(page2)); assert.equal(page2.gets.length, 0); assert.deepEqual(res.avatars?.skipped, ["obviousrises"]); // force fetches again, and the entry takes the case X prints now. const page3 = fakePage({ "14": [{ role: "author", handle: "obviousrises", src: pic("10") }] }); await captureXPosts(input(out, ["14"], { force: true }), deps(page3)); assert.equal(page3.gets.length, 1); const index = await readXAvatarIndex(path.join(out, AVATARS_DIRNAME)); assert.deepEqual(Object.keys(index), ["obviousrises"]); assert.equal(index.obviousrises.postId, "14"); }); test("run: avatars: false reads none; X's default picture is not stored", async () => { const out = await outDir(); const page = fakePage({ "11": [{ role: "author", handle: "ObviousRises", src: pic("9") }] }); const res = await captureXPosts(input(out, ["11"], { avatars: false }), deps(page)); assert.equal(page.reads.length, 0); assert.equal(page.gets.length, 0); assert.equal(res.avatars, undefined); const egg = fakePage({ "12": [{ role: "author", handle: "eggy", src: "https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png" }], }); const res2 = await captureXPosts(input(out, ["12"]), deps(egg)); assert.equal(egg.gets.length, 0); assert.deepEqual(res2.avatars?.skipped, ["eggy"]); assert.deepEqual(await readXAvatarIndex(path.join(out, AVATARS_DIRNAME)), {}); }); test("run: with the thread on, the parent's and the quoted post's authors' too, by the archive's parent id", async () => { const out = await outDir(); const page = fakePage({ "21": [ { role: "author", handle: "ObviousRises", src: pic("1") }, { role: "quoted", handle: "quoted_one", src: pic("2") }, { role: "parent", handle: "parent_one", src: pic("3") }, ], }); const archived = new Map([["21", { text: "", author: "ObviousRises", isReply: true, replyTo: { id: "20" } }]]); const res = await captureXPosts(input(out, ["21"], { thread: true, shots: false, archived }), deps(page)); assert.ok(page.reads[0].includes("const wantParent = true")); assert.ok(page.reads[0].includes('const parentId = "20"')); assert.deepEqual(res.avatars?.stored, ["ObviousRises", "quoted_one", "parent_one"]); assert.deepEqual(Object.keys(await readXAvatarIndex(path.join(out, AVATARS_DIRNAME))), ["ObviousRises", "parent_one", "quoted_one"]); }); test("avatarsOnly: one page per distinct archived author, paced, no shot, no media, no capture record", async () => { const out = await outDir(); const page = fakePage({ "31": [{ role: "author", handle: "ObviousRises", src: pic("1") }], "33": [{ role: "author", handle: "someone_else", src: pic("2") }], }); let downloads = 0; const d = deps(page, { downloadMedia: async () => { downloads++; return { ok: true, files: [] }; }, }); const archived = new Map([ ["31", { text: "", author: "ObviousRises" }], ["32", { text: "", author: "obviousrises" }], ["33", { text: "", author: "someone_else" }], ]); const res = await captureXPosts(input(out, ["31", "32", "33"], { avatarsOnly: true, media: true, archived }), d); assert.deepEqual(page.gotos, ["https://x.com/i/status/31", "https://x.com/i/status/33"]); assert.deepEqual(d.pauses, [4000], "the gap before every contact after the first"); assert.equal(page.shots, 0); assert.equal(downloads, 0); assert.deepEqual(res.outcomes, []); assert.equal(res.avatars?.pages, 2); assert.deepEqual(res.avatars?.stored, ["ObviousRises", "someone_else"]); // Nothing but the store under posts-media/: no post directory, no capture.json. assert.deepEqual(await readdir(out), [AVATARS_DIRNAME]); }); test("avatarsOnly: an author already stored costs no page load unless force", async () => { const out = await outDir(); await writeXAvatar(path.join(out, AVATARS_DIRNAME), { handle: "ObviousRises", bytes: JPG, url: "https://pbs.twimg.com/profile_images/1/face_400x400.jpg", postId: "1", }); const page = fakePage({ "31": [{ role: "author", handle: "ObviousRises", src: pic("1") }] }); const archived = new Map([["31", { text: "", author: "obviousrises" }]]); const d = deps(page); const res = await captureXPosts(input(out, ["31"], { avatarsOnly: true, archived }), d); assert.equal(d.opened, 0); assert.deepEqual(page.gotos, []); assert.deepEqual(res.avatars?.skipped, ["obviousrises"]); const res2 = await captureXPosts(input(out, ["31"], { avatarsOnly: true, archived, force: true }), deps(page)); assert.deepEqual(page.gotos, ["https://x.com/i/status/31"]); assert.deepEqual(page.gets, ["https://pbs.twimg.com/profile_images/1/face_400x400.jpg"]); assert.deepEqual(res2.avatars?.stored, ["ObviousRises"]); }); test("avatarsOnly: a login wall stops the run with needsCookies, the rest left", async () => { const out = await outDir(); const page = fakePage({}); page.evaluate = async (script: string) => script.includes(AVATARS_SCRIPT_MARKER) ? [] : { path: "/i/flow/login", text: "", article: null }; const archived = new Map([ ["41", { text: "", author: "a" }], ["42", { text: "", author: "b" }], ]); const res = await captureXPosts(input(out, ["41", "42"], { avatarsOnly: true, archived }), deps(page)); assert.equal(res.needsCookies, true); assert.match(res.stoppedEarly ?? "", /Stopped at 41/); assert.equal(page.gotos.length, 1); assert.deepEqual(res.outcomes, []); });