import test from "node:test"; import assert from "node:assert/strict"; import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; // Run with: // pnpm -C editor exec tsx --test "app/api/ops/read-x-trending/route.test.ts" // // An X trending library over ops (lane x-trending), against a temp corpus: // every refusal of read-x-trending BEFORE a job exists (so no browser opens // and nothing is asked of X — the corpus has no connected profile, which is // itself the last refusal), the listing (`GET /api/ops/trending`), and the // channel form's refusals: a library on a site, a library with a URL, a // library turned into an ordinary channel. A read itself is driven in // e2e/x-trending.spec.ts over the fake browser. const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-route-")); process.env.WORKER_TOKEN = "test-token"; process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); const READ = "tr-01JA0000000000000000000000"; const TREND = "https://x.com/i/trending/1900000000000000001"; async function channel(slug: string, config: Record): Promise { const dir = path.join(ROOT, "channels", slug); await mkdir(path.join(dir, "trending", "posts"), { recursive: true }); await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config })); return dir; } const lib = await channel("trending", { sourceKind: "social", platform: "twitter", xTrending: {} }); await channel("account-x", { sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: "example", url: "https://x.com/example" }); await writeFile( path.join(lib, "trending", "posts", "2026-11.jsonl"), ["1900000000000001001", "1900000000000001002"] .map((id, i) => JSON.stringify({ id, slug: `trending/${id}`, channelSlug: "trending", author: i ? "saucer_fan" : "teapot_news", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text: i ? "Second." : "The kettle festival opens today.", url: `https://x.com/${i ? "saucer_fan" : "teapot_news"}/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [], }), ) .join("\n") + "\n", ); await writeFile(path.join(lib, "trending", "posts-archive"), "twitter 1900000000000001001\ntwitter 1900000000000001002\n"); await mkdir(path.join(lib, "trending", "reads", READ), { recursive: true }); await writeFile(path.join(lib, "trending", "reads", READ, "responses.jsonl"), JSON.stringify({ n: 1, op: "Op", status: 200, bytes: 9, url: "u", at: "x", body: { secret: "rawcapturemarker" } }) + "\n"); await writeFile( path.join(lib, "trending", "topics.json"), JSON.stringify({ version: 1, topics: [ { id: "kettles", title: "Kettles", createdAt: "2026-11-17T10:00:00.000Z", sources: [{ trendId: "1900000000000000001", url: TREND, reads: [{ id: READ, at: "2026-11-17T10:00:00.000Z", posts: 2, added: 2 }] }], }, ], }), ); await writeFile( path.join(lib, "trending", "membership.json"), JSON.stringify({ version: 1, posts: { "1900000000000001001": { topic: "kettles", seen: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", rank: 1 }], media: { count: 2, kinds: ["image"] } }, "1900000000000001002": { topic: "kettles", seen: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", rank: 2 }] }, }, }), ); await mkdir(path.join(ROOT, "sites", "demo-site"), { recursive: true }); await writeFile(path.join(ROOT, "sites", "demo-site", "site.json"), JSON.stringify({ siteId: "demo-site", siteTitle: "Demo", channels: [] })); const readTrending = (await import("./route")).POST; const listing = (await import("../trending/route")).GET; const create = (await import("../create-channel/route")).POST; const configure = (await import("../channel-config/route")).POST; test.after(() => rm(ROOT, { recursive: true, force: true })); async function call(handler: (r: Request) => Promise, body: Record) { const res = await handler( new Request("http://localhost/api/ops/x", { method: "POST", headers: { authorization: "Bearer test-token", "content-type": "application/json" }, body: JSON.stringify(body), }), ); return { status: res.status, json: (await res.json()) as Record }; } async function get(query: string, token = "test-token") { const res = await listing(new Request(`http://localhost/api/ops/trending${query}`, { headers: { authorization: `Bearer ${token}` } })); return { status: res.status, json: (await res.json()) as Record }; } const exists = (p: string) => access(p).then(() => true, () => false); test("read-x-trending refuses, before any job, with a sentence", async () => { const refused = async (body: Record) => { const r = await call(readTrending, body); assert.equal(r.status, 400, JSON.stringify(r.json)); assert.equal(r.json.ok, false); return String(r.json.error); }; assert.match(await refused({ url: TREND }), /"slug" is required/); assert.equal(await refused({ slug: "nope", url: TREND }), "No such channel: nope"); assert.match(await refused({ slug: "account-x", url: TREND }), /account-x is not an X trending library/); assert.match(await refused({ slug: "trending" }), /Give "url" .* or "reparse"/); assert.match(await refused({ slug: "trending", url: "https://x.com/example/status/1" }), /not a trending page URL/); assert.match(await refused({ slug: "trending", url: TREND, scrolls: 41 }), /"scrolls" is a whole number, 1–40/); assert.match(await refused({ slug: "trending", url: TREND, posts: 0 }), /"posts" must be a whole number above zero/); assert.match(await refused({ slug: "trending", url: TREND, probe: "yes" }), /"probe" must be a boolean/); assert.match(await refused({ slug: "trending", url: TREND, pages: 3 }), /pages/); assert.match(await refused({ slug: "trending", reparse: "tr-01JZ0000000000000000000000" }), /holds no saved read/); // No connected X profile in this corpus: the read is refused, and no browser was asked for. assert.match(await refused({ slug: "trending", url: TREND }), /needs the connected X profile/); assert.equal(await exists(path.join(ROOT, ".jobs")), false, "no job was made"); }); test("get trending lists topics and posts — words, author, media, reads, topic — and never the raw capture", async () => { const all = await get("?slug=trending"); assert.equal(all.status, 200); assert.deepEqual(all.json.topics, [ { id: "kettles", title: "Kettles", posts: 2, sources: [{ trendId: "1900000000000000001", url: TREND, reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z" }] }, ]); const posts = all.json.posts as Array>; assert.deepEqual(posts[0], { id: "1900000000000001001", author: "teapot_news", createdAt: "2026-11-16T12:00:00.000Z", url: "https://x.com/teapot_news/status/1900000000000001001", text: "The kettle festival opens today.", media: { count: 2, kinds: ["image"] }, topic: "kettles", reads: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z" }], thread: "1900000000000001001", }); assert.equal(all.json.total, 2); assert.deepEqual(all.json.reads, [READ]); assert.ok(!JSON.stringify(all.json).includes("rawcapturemarker")); assert.equal(((await get("?slug=trending&limit=1")).json.posts as unknown[]).length, 1); assert.equal(((await get("?slug=trending&topic=kettles")).json.posts as unknown[]).length, 2); // Refusals. assert.match(String((await get("?slug=trending&topic=nope")).json.error), /has no topic "nope" \(its topics: kettles\)/); assert.match(String((await get("?slug=account-x")).json.error), /not an X trending library/); assert.equal((await get("?slug=nope")).status, 404); assert.match(String((await get("?slug=trending&limit=501")).json.error), /1–500/); assert.match(String((await get("?slug=trending&raw=1")).json.error), /unknown parameter "raw"/); assert.match(String((await get("?slug=..%2Fx")).json.error), /not a valid channel slug/); assert.equal((await get("?slug=trending", "wrong")).status, 401); }); test("create-channel refuses a library on a site and a library with a URL; nothing is made", async () => { const fields = { name: "Made trending", handling: "transcribe", platform: "x-trending" }; const onSite = await call(create, { fields, sites: [{ siteId: "demo-site", groupId: "default" }] }); assert.equal(onSite.status, 400); assert.equal(onSite.json.error, "made-trending is an X trending library: it is private, and never put on a site."); const withUrl = await call(create, { fields: { ...fields, url: TREND } }); assert.equal(withUrl.status, 400); assert.match(String(withUrl.json.error), /^An X trending library has no URL/); const badCap = await call(create, { fields: { ...fields, xTrendingMaxPosts: 500 } }); assert.match(String(badCap.json.error), /post cap is a whole number, 1–400/); assert.equal(await exists(path.join(ROOT, "channels", "made-trending")), false); }); test("the marker cannot be switched off: no create or patch changes a library's kind, platform or URL", async () => { const fields = { name: "Video trending", handling: "transcribe", platform: "x-trending" }; const video = await call(create, { fields: { ...fields, sourceKind: "video" } }); assert.equal(video.status, 400); assert.match(String(video.json.error), /An X trending library is a posts channel: its kind cannot be "video"/); assert.equal(await exists(path.join(ROOT, "channels", "video-trending")), false); const before = await readFile(path.join(lib, "config.json"), "utf8"); for (const [patch, sentence] of [ [{ sourceKind: "video" }, /its kind cannot be "video"/], [{ url: "https://x.com/example" }, /An X trending library has no URL/], [{ platform: "youtube" }, /is an X trending library and stays one/], [{ platform: "", url: "https://www.youtube.com/@example/videos", sourceKind: "video" }, /is an X trending library and stays one/], ] as const) { const r = await call(configure, { slug: "trending", patch }); assert.equal(r.status, 400, JSON.stringify(patch)); assert.match(String(r.json.error), sentence, JSON.stringify(patch)); } assert.equal(await readFile(path.join(lib, "config.json"), "utf8"), before, "the config is untouched"); }); test("Configure cannot turn a library into an ordinary channel, an account into a library, or put a library on a site", async () => { const unmade = await call(configure, { slug: "trending", patch: { platform: "twitter", socialHandle: "example" } }); assert.equal(unmade.status, 400); assert.match(String(unmade.json.error), /trending is an X trending library and stays one/); const made = await call(configure, { slug: "account-x", patch: { platform: "x-trending", url: "" } }); assert.equal(made.status, 400); assert.match(String(made.json.error), /Configure cannot make it one/); const onSite = await call(configure, { slug: "trending", sites: [{ siteId: "demo-site", groupId: "default" }] }); assert.equal(onSite.status, 400); assert.equal(onSite.json.error, "trending is an X trending library: it is private, and never put on a site."); });