flagtldr / extension /src /lib /tweet-parser.js
botezx's picture
Grok Bot
FlagTLDR 0.5.0 (snapshot of local f98bb37)
043267b
Raw History Blame Contribute Delete
8.72 kB
// Parses X GraphQL timeline / TweetDetail payloads into flat post records.
// Works in the browser (attaches to globalThis.XA) and in Node (module.exports) for tests.
(function (root) {
"use strict";
function unwrap(result) {
if (!result) return null;
if (result.__typename === "TweetWithVisibilityResults" && result.tweet) return result.tweet;
return result;
}
function toPost(t) {
const legacy = t.legacy || {};
const userRes = t.core && t.core.user_results && t.core.user_results.result;
const user = userRes || {};
const uLegacy = user.legacy || {};
const uCore = user.core || {};
const noteText = t.note_tweet && t.note_tweet.note_tweet_results &&
t.note_tweet.note_tweet_results.result && t.note_tweet.note_tweet_results.result.text;
return {
id: t.rest_id || legacy.id_str,
conversationId: legacy.conversation_id_str || null,
inReplyToId: legacy.in_reply_to_status_id_str || null,
author: {
id: user.rest_id || legacy.user_id_str || null,
handle: uCore.screen_name || uLegacy.screen_name || null,
name: uCore.name || uLegacy.name || null,
},
text: noteText || legacy.full_text || "",
lang: legacy.lang || null,
createdAt: legacy.created_at || null,
metrics: {
replies: legacy.reply_count || 0,
reposts: legacy.retweet_count || 0,
likes: legacy.favorite_count || 0,
quotes: legacy.quote_count || 0,
views: (t.views && Number(t.views.count)) || null,
},
quotedId: legacy.quoted_status_id_str || null,
};
}
// Walks any GraphQL payload and collects every Tweet object it finds.
function extractPosts(payload) {
const out = new Map();
const seen = new Set();
(function walk(node) {
if (!node || typeof node !== "object" || seen.has(node)) return;
seen.add(node);
// X conversation module: entryId "conversationthread-<id>", content.items[] in display order (a reply chain)
if (typeof node.entryId === "string" && /^conversationthread-/.test(node.entryId) && Array.isArray(node.content?.items)) {
let prev = null;
for (const it of node.content.items) {
const t = unwrap(it?.item?.itemContent?.tweet_results?.result);
if (!t || !t.legacy) continue;
const p = toPost(t);
if (!p.inReplyToId && prev) p.moduleParent = prev;
p.entryId = it.entryId || null;
if (p.id && !out.has(p.id)) out.set(p.id, p);
prev = p.id;
}
}
if (node.tweet_results && node.tweet_results.result) {
const t = unwrap(node.tweet_results.result);
if (t && (t.__typename === "Tweet" || t.rest_id) && t.legacy) {
const p = toPost(t);
if (p.id && !out.has(p.id)) out.set(p.id, p);
}
}
for (const k in node) walk(node[k]);
})(payload);
return [...out.values()];
}
// v0.4.1 (botex-human 16:21): the summary covers ONLY the subtree rooted at the clicked post – the post itself, its
// direct replies and replies to those replies (recursively). Not the ancestors, not sibling branches.
// v0.4.3 (botex-human 17:05, unrelated-replies bug): a post is a reply ONLY with a verified in_reply_to_status_id_str
// chain up to the focal id. Display order / conversation modules (moduleParent) are NOT edges any more – a
// post without in_reply_to is not a reply. Ancestors come ONLY from the focal's own in_reply_to chain.
// When both sides carry conversation_id_str it must match the focal's (extra guard against stale posts from
// other conversations in the tab's store). opts.context = 0 (none) | 1 (immediate parent, default) | n | "all".
function buildThread(posts, focalId, opts = {}) {
const byId = new Map(posts.map((p) => [p.id, p]));
const focal = byId.get(focalId);
if (!focal) return null;
const conv = focal.conversationId || null;
const sameConv = (p) => !conv || !p.conversationId || p.conversationId === conv;
const parentOf = (p) => (p.inReplyToId && p.inReplyToId !== p.id ? p.inReplyToId : null);
const children = new Map();
for (const p of posts) {
const par = parentOf(p);
if (!par || !sameConv(p)) continue;
if (!children.has(par)) children.set(par, []);
children.get(par).push(p);
}
// descendants, breadth-first; depth 1 = direct reply; every accepted post's in_reply_to points at the focal
// or at an already accepted descendant, i.e. the chain to the focal is verified by construction
const replies = [], seen = new Set([focal.id]);
let level = [focal], depth = 0;
while (level.length && depth < 50) {
depth++;
const next = [];
for (const n of level) for (const c of children.get(n.id) || []) {
if (seen.has(c.id)) continue;
seen.add(c.id);
replies.push({ ...c, depth, parentId: parentOf(c) }); next.push(c);
}
level = next;
}
const chain = ancestorChain(byId, focal);
const want = opts.context === "all" ? chain.length : Math.max(0, Number(opts.context ?? 1) || 0);
const ancestors = want ? chain.slice(-want) : [];
// X's reply_count of the focal + every collected descendant ≈ how many replies X knows in this subtree
const withCount = [focal, ...replies].filter((p) => p.metrics && typeof p.metrics.replies === "number");
const known = withCount.length ? withCount.reduce((n, p) => n + p.metrics.replies, 0) : null;
const direct = replies.filter((r) => r.depth === 1).length;
return { focal, ancestors, replies, known, direct, knownDirect: focal.metrics ? focal.metrics.replies : null,
ancestorsAvailable: chain.length, source: "graphql" };
}
// the focal's own in_reply_to chain, oldest first: [root?, …, parent] – only posts actually present in byId
function ancestorChain(byId, focal) {
const chain = [], guard = new Set([focal.id]);
let cur = focal;
while (cur && cur.inReplyToId && byId.has(cur.inReplyToId) && !guard.has(cur.inReplyToId)) {
cur = byId.get(cur.inReplyToId); guard.add(cur.id); chain.unshift(cur);
}
return chain;
}
// true when post's in_reply_to chain (through byId) reaches focalId
function repliesTo(byId, post, focalId) {
const guard = new Set();
for (let cur = post; cur && cur.inReplyToId && !guard.has(cur.id); cur = byId.get(cur.inReplyToId)) {
if (cur.inReplyToId === focalId) return true;
guard.add(cur.id);
}
return false;
}
// v0.4.3: DOM fallback (no GraphQL reply tree). Pure, so the unrelated-replies regression is unit-testable.
// Allowed ONLY on the focal's own status page (/<handle>/status/<focalId>, no /photo/…, /analytics … overlays)
// and only for posts AFTER the focal article, until X's next section heading ("Odkryj więcej" / "Discover more").
// A DOM post that the GraphQL store knows must have an in_reply_to chain to the focal (and the same
// conversation) – otherwise it is rejected. No DOM context at all: ancestors only via the in_reply_to chain.
// cells: [{id|null, kind: "post"|"heading"|"sep"|"other"}] in display order; byId: Map of stored posts.
const OWN_STATUS = /^\/[A-Za-z0-9_]{1,15}\/status\/(\d{1,25})\/?$/;
function domSubtreeIds(cells, path, focalId, byId = new Map()) {
const m = OWN_STATUS.exec(path || "");
if (!m || m[1] !== focalId) return { replies: [], rejected: [], reason: "not-own-status-page" };
const fi = cells.findIndex((c) => c.kind === "post" && c.id === focalId);
if (fi < 0) return { replies: [], rejected: [], reason: "focal-not-in-view" };
const focal = byId.get(focalId), conv = focal && focal.conversationId;
const replies = [], rejected = [], seen = new Set([focalId]);
for (let k = fi + 1; k < cells.length; k++) {
const c = cells[k];
if (c.kind === "heading") break; // end of the conversation – "Discover more" etc.
if (c.kind !== "post" || !c.id || seen.has(c.id)) continue;
seen.add(c.id);
const p = byId.get(c.id);
// a post scraped from the DOM has no in_reply_to – nothing to verify; a GraphQL post must chain to the focal
if (p && !p.fromDom && (!repliesTo(byId, p, focalId) || (conv && p.conversationId && p.conversationId !== conv))) { rejected.push(c.id); continue; }
replies.push(c.id);
}
return { replies, rejected, reason: null };
}
const api = { extractPosts, buildThread, ancestorChain, repliesTo, domSubtreeIds, toPost };
root.XA = root.XA || {};
root.XA.parser = api;
if (typeof module !== "undefined" && module.exports) module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);