aboutsummaryrefslogtreecommitdiff
path: root/castle-search/src/x-search.ts
blob: 93e8b56807a7f27432a5140e67de0f2210a0663a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/**
 * Read X (x.com) through the browser's own signed-in session: search posts,
 * read one post with its thread and replies, read a profile, list trends.
 *
 * X serves all of this only to a signed-in session and renders it from
 * JavaScript, so the page is the only interface there is: open the page in a
 * background tab, wait for it to render, read it, scroll for more, close the
 * tab. Free, unlike xAI's x_search ($5 per 1,000 posts returned).
 *
 * A search query is X's own search syntax, passed through untouched:
 * from:handle, to:handle, since:2026-11-01, until:..., min_faves:100,
 * filter:media, -filter:replies, lang:en, "exact phrase", OR.
 *
 * Every read shares one set of limits (x-limits.ts) and, signed out, signs the
 * browser back in once (x-login.ts). Every failure throws, as for the engine
 * searches (errors.ts): signed out, an X error page, or nothing rendering are
 * reported as such, never as an empty answer. X's own "No results" or "doesn't
 * exist" page is reported as an error naming what was asked for.
 */

import type { PageSession } from "./cdp.ts";
import { BrowserUnavailableError, NoResultsError } from "./errors.ts";
import { withPage } from "./search.ts";
import { XLimiter } from "./x-limits.ts";
import { loadCredentials, X_LOGIN_TIMEOUT_MS, xLogin } from "./x-login.ts";

/** Shared by every X read in this process: see x-limits.ts. */
const limiter = new XLimiter();

/**
 * Signed out, a read signs the browser back in (x-login.ts) when
 * CCS_X_LOGIN_FILE names the credentials, then reads again, once. At most one
 * sign-in attempt per LOGIN_COOLDOWN_MS: a sign-in that keeps failing is what
 * gets an account locked, so until the cooldown has passed every read fails
 * with the reason the last attempt gave.
 */
export const LOGIN_COOLDOWN_MS = 30 * 60_000;
let lastLogin: { at: number; error?: string } | undefined;

class SignedOut extends Error {
  readonly at: string;
  constructor(at: string) {
    super(`signed out at ${at}`);
    this.at = at;
  }
}

export type XSort = "latest" | "top";

export type XMedia = { type: "photo" | "video"; url?: string; alt?: string };

export type XPost = {
  url: string;
  author: string;
  handle: string;
  /** ISO 8601, from the post's <time datetime>. */
  time: string;
  text: string;
  /** X cut the text short behind "Show more"; x_post reads it whole. */
  truncated?: true;
  /** "@someone reposted", "Pinned" and the like. */
  context?: string;
  replies?: number;
  reposts?: number;
  likes?: number;
  views?: number;
  /** Photos (with X's image URL and alt text) and videos (with a still). */
  media?: XMedia[];
  /** A link card: the page the post links to. */
  card?: { url: string; title?: string };
  quoted?: { author: string; handle: string; text: string; time?: string; url?: string };
};

export type XSearchRequest = { query: string; count: number; sort?: XSort | undefined };
export type XSearchOutcome = { query: string; sort: XSort; searchUrl: string; posts: XPost[] };

export type XPostRequest = { url: string; replies: number };
export type XPostOutcome = {
  post: XPost;
  /** The posts above it in its thread, oldest first, when it is a reply. */
  thread: XPost[];
  replies: XPost[];
};

export type XUserRequest = { handle: string; count: number };
export type XProfile = {
  name: string;
  handle: string;
  url: string;
  bio?: string;
  location?: string;
  website?: string;
  joined?: string;
  followers?: number;
  following?: number;
  posts?: number;
  avatar?: string;
};
export type XUserOutcome = { profile: XProfile; posts: XPost[] };

export const TREND_TABS = ["trending", "news", "sports", "entertainment", "for_you"] as const;
export type XTrendTab = (typeof TREND_TABS)[number];
export type XTrend = { rank?: number; name: string; context?: string; detail?: string; query: string };
export type XTrendsOutcome = { tab: XTrendTab; trends: XTrend[] };

/** X shows ~5-10 posts per screen; scroll this many times at most for more. */
const MAX_SCROLLS = 6;
/** Wall clock for one read: render, scrolls and all. */
export const X_SEARCH_TIMEOUT_MS = 25_000;
const POLL_MS = 400;

export const buildXSearchUrl = (query: string, sort: XSort): string => {
  const params = new URLSearchParams({ q: query, src: "typed_query" });
  // f=live is the Latest tab. Top is the default tab, no parameter.
  if (sort === "latest") params.set("f", "live");
  return `https://x.com/search?${params.toString()}`;
};

/** The post id in an X or Twitter post link, or a bare id. */
export const postIdOf = (url: string): string | undefined =>
  /^\d{5,25}$/.test(url.trim()) ? url.trim() : /(?:x|twitter)\.com\/(?:[^/]+|i(?:\/web)?)\/status(?:es)?\/(\d+)/i.exec(url)?.[1];

/** A handle as X writes it, from "@nasa", "nasa" or a profile link. */
export const handleOf = (s: string): string | undefined => {
  const m = /^(?:https?:\/\/(?:www\.)?(?:x|twitter)\.com\/)?@?([A-Za-z0-9_]{1,15})\/?$/.exec(s.trim());
  return m?.[1];
};

/** Parses X's action-bar label: "441 replies, 971 reposts, 8852 likes, 1247 bookmarks, 16029782 views". */
export const parseMetrics = (label: string | null | undefined): Partial<Record<"replies" | "reposts" | "likes" | "views", number>> => {
  const out: Partial<Record<"replies" | "reposts" | "likes" | "views", number>> = {};
  for (const m of (label ?? "").matchAll(/(\d+)\s+(repl(?:y|ies)|reposts?|likes?|views?)/g)) {
    const n = Number(m[1]);
    const word = m[2] ?? "";
    if (word.startsWith("repl")) out.replies = n;
    else if (word.startsWith("repost")) out.reposts = n;
    else if (word.startsWith("like")) out.likes = n;
    else if (word.startsWith("view")) out.views = n;
  }
  return out;
};

/** One trend cell's lines: "2", "·", "Gaming · Trending", "GTA 6", "Trending with #GTAVI". */
export const parseTrend = (text: string): XTrend | undefined => {
  const lines = text.split("\n").map((l) => l.trim()).filter((l) => l && l !== "·");
  let rank: number | undefined;
  if (lines[0] && /^\d+$/.test(lines[0])) rank = Number(lines.shift());
  const context = lines.shift();
  const name = lines.shift();
  if (!name) return undefined;
  const trend: XTrend = { name, query: name };
  if (rank !== undefined) trend.rank = rank;
  if (context) trend.context = context;
  if (lines.length) trend.detail = lines.join("; ");
  return trend;
};

type RawPost = Omit<XPost, "replies" | "reposts" | "likes" | "views"> & { metrics: string | null };

type XProbe = {
  url: string;
  state: "signed-out" | "posts" | "empty" | "error" | "loading";
  posts: RawPost[];
  note: string;
  /** The profile's JSON-LD, on a profile page. */
  profile: string | null;
};

/**
 * Reads the page as it stands. Runs in the page; must stay self-contained.
 * Ads are skipped by having no <time>: every real post has one.
 */
export const PROBE = `(() => {
  const url = location.href;
  if (/^\\/(login|i\\/flow\\/login|i\\/jf\\/onboarding|account\\/access)/.test(location.pathname)) {
    return { url, state: "signed-out", posts: [], note: location.pathname, profile: null };
  }
  const txt = (el) => (el ? el.innerText.trim() : "");
  const nameOf = (scope) => {
    const lines = txt(scope.querySelector('[data-testid="User-Name"]')).split("\\n");
    return { author: lines[0] || "", handle: lines.find((l) => l.startsWith("@")) || "" };
  };
  const clean = (href) => href.split("?")[0].replace(/\\/(analytics|photo\\/\\d+|video\\/\\d+)$/, "");
  const posts = [];
  for (const a of document.querySelectorAll('article[data-testid="tweet"]')) {
    // The quoted post: the clickable box holding post text. Not simply the
    // first div[role=link], which can be something else in the post.
    const quote = [...a.querySelectorAll('div[role="link"]')].find((d) => d.querySelector('[data-testid="tweetText"], [data-testid="User-Name"]')) || null;
    const mine = (el) => !(quote && quote.contains(el));
    // The post's own time, a link to it. On a post's own page that sits below
    // the text, after the quoted post's unlinked one.
    const time = [...a.querySelectorAll("time")].find((t) => mine(t) && t.closest("a"));
    const link = time && time.closest("a");
    if (!time || !link) continue;
    const own = [...a.querySelectorAll('[data-testid="tweetText"]')].filter(mine);
    const byline = [...a.querySelectorAll('[data-testid="User-Name"]')].find(mine);
    const post = {
      url: clean(link.href),
      ...nameOf(byline ? byline.parentElement : a),
      time: time.getAttribute("datetime") || "",
      text: own.map(txt).join("\\n"),
      metrics: null,
    };
    const bar = a.querySelector('[role="group"][aria-label]');
    if (bar) post.metrics = bar.getAttribute("aria-label");
    if (a.querySelector('[data-testid="tweet-text-show-more-link"]')) post.truncated = true;
    const ctx = txt(a.querySelector('[data-testid="socialContext"]'));
    if (ctx) post.context = ctx;
    const media = [];
    // A video's still is an <img> in the same box: listed with the video, not as a photo.
    for (const img of [...a.querySelectorAll('[data-testid="tweetPhoto"] img')].filter((i) => mine(i) && !i.closest('[data-testid="tweetPhoto"]').querySelector("video"))) {
      const m = { type: "photo", url: img.src.replace(/name=\\w+/, "name=large") };
      if (img.alt && img.alt !== "Image") m.alt = img.alt;
      media.push(m);
    }
    for (const v of [...a.querySelectorAll("video")].filter(mine)) {
      const m = { type: "video" };
      if (v.poster) m.url = v.poster;
      const label = v.getAttribute("aria-label");
      if (label && label !== "Embedded video") m.alt = label;
      media.push(m);
    }
    if (media.length) post.media = media;
    const card = [...a.querySelectorAll('[data-testid="card.wrapper"] a[href]')].find(mine);
    if (card) {
      post.card = { url: card.href };
      const title = txt(card).split("\\n").filter(Boolean).pop();
      if (title) post.card.title = title.slice(0, 200);
    }
    if (quote) {
      const qt = txt(quote.querySelector('[data-testid="tweetText"]'));
      if (qt) {
        post.quoted = { ...nameOf(quote), text: qt };
        const qtime = quote.querySelector("time");
        if (qtime) post.quoted.time = qtime.getAttribute("datetime") || "";
        const qlink = quote.querySelector('a[href*="/status/"]');
        if (qlink) post.quoted.url = clean(qlink.href);
      }
    }
    posts.push(post);
  }
  const schema = document.querySelector('[data-testid="UserProfileSchema-test"]');
  const profile = schema ? schema.textContent : null;
  if (posts.length) return { url, state: "posts", posts, note: "", profile };
  const empty = document.querySelector('[data-testid="emptyState"]');
  if (empty) return { url, state: "empty", posts, note: txt(empty).slice(0, 300), profile };
  const col = document.querySelector('[data-testid="primaryColumn"]');
  const said = txt(col);
  if (/doesn.t exist|was deleted|account is suspended|these posts are protected|you.re unable to view this post/i.test(said)) {
    return { url, state: "empty", posts, note: said.slice(0, 300), profile };
  }
  const retry = [...document.querySelectorAll('button, [role="button"]')].find((b) => /^Retry$/.test(txt(b)));
  if (retry) return { url, state: "error", posts, note: said.slice(0, 300), profile };
  return { url, state: "loading", posts, note: "", profile };
})()`;

const TRENDS = `(() => {
  if (/^\\/(login|i\\/flow\\/login|i\\/jf\\/onboarding|account\\/access)/.test(location.pathname)) return null;
  return [...document.querySelectorAll('[data-testid="trend"]')].map((t) => t.innerText);
})()`;

const SCROLL = `window.scrollBy(0, window.innerHeight * 2), true`;

const sleep = (ms: number, signal: AbortSignal): Promise<void> =>
  new Promise((resolve, reject) => {
    if (signal.aborted) return reject(signal.reason);
    const t = setTimeout(resolve, ms);
    signal.addEventListener("abort", () => {
      clearTimeout(t);
      reject(signal.reason);
    }, { once: true });
  });

const finish = (raw: RawPost): XPost => {
  const { metrics, ...rest } = raw;
  return { ...rest, ...parseMetrics(metrics) };
};

type Saw = (state: string) => void;

// --- Shared: limits, sign-in, deadline -----------------------------------

/**
 * Runs one X read: in turn with every other (the limits), within its own
 * deadline, signing in and reading again once if X has signed the browser out.
 */
const xRead = <T>(outer: AbortSignal, what: string, read: (page: PageSession, signal: AbortSignal, saw: Saw) => Promise<T>): Promise<T> =>
  // The deadline starts once the limiter lets the read through, so waiting
  // its turn does not eat into it.
  limiter.run(outer, async () => {
    try {
      return await attempt(outer, what, read);
    } catch (e) {
      if (!(e instanceof SignedOut)) throw e;
      // The sign-in has its own deadline, and the read after it a fresh one.
      await signIn(e.at, outer);
      return await attempt(outer, what, read);
    }
  });

const attempt = async <T>(
  outer: AbortSignal,
  what: string,
  read: (page: PageSession, signal: AbortSignal, saw: Saw) => Promise<T>,
): Promise<T> => {
  const signal = AbortSignal.any([outer, AbortSignal.timeout(X_SEARCH_TIMEOUT_MS)]);
  let last = "nothing yet";
  try {
    return await withPage(signal, (page) => read(page, signal, (state) => (last = state)));
  } catch (e) {
    if (signal.aborted && !outer.aborted) {
      throw new BrowserUnavailableError(
        `X did not finish ${what} within ${X_SEARCH_TIMEOUT_MS / 1000} s (last seen: ${last}). ` +
          `X may be slow or stuck on a page this tool does not recognise.`,
      );
    }
    throw e;
  }
};

const signedOutError = (at: string, why: string): BrowserUnavailableError =>
  new BrowserUnavailableError(
    `X needs a signed-in X session in castle Chrome, and it is signed out (X sent it to ${at}). ` +
      `${why} Tell the user: someone has to sign in to X in that browser again.`,
  );

/** Signs the browser in, within its own deadline, or throws saying why not. */
const signIn = async (at: string, outer: AbortSignal): Promise<void> => {
  const creds = loadCredentials(process.env["CCS_X_LOGIN_FILE"]);
  if (!creds) throw signedOutError(at, "No sign-in details are configured (CCS_X_LOGIN_FILE).");
  if (lastLogin && Date.now() - lastLogin.at < LOGIN_COOLDOWN_MS) {
    const next = new Date(lastLogin.at + LOGIN_COOLDOWN_MS).toISOString().slice(11, 16);
    throw signedOutError(
      at,
      `Signing in again was tried at ${new Date(lastLogin.at).toISOString().slice(11, 16)} UTC` +
        (lastLogin.error ? ` and failed: ${lastLogin.error}` : ", yet it is signed out again.") +
        ` The next try is after ${next} UTC.`,
    );
  }
  lastLogin = { at: Date.now() };
  const signal = AbortSignal.any([outer, AbortSignal.timeout(X_LOGIN_TIMEOUT_MS)]);
  try {
    await withPage(signal, (page) => xLogin(page, creds, signal, (line) => console.log(line)));
  } catch (e) {
    const why = signal.aborted && !outer.aborted ? `it took over ${X_LOGIN_TIMEOUT_MS / 1000} s` : (e as Error).message;
    lastLogin.error = why;
    console.log(`x-login failed: ${why}`);
    throw signedOutError(at, `Signing in again failed: ${why}`);
  }
};

/**
 * Opens `url` and waits for X to render: posts, an empty or error page, or a
 * sign-in redirect. `ready` can ask for more before posts count, such as a
 * profile's header.
 */
const open = async (
  page: PageSession,
  url: string,
  signal: AbortSignal,
  saw: Saw,
  ready: (p: XProbe) => boolean = (p) => p.state !== "loading",
): Promise<XProbe> => {
  await page.navigate(url, signal);
  for (;;) {
    const probe = await page.evaluate<XProbe>(PROBE, signal);
    saw(`${probe.state} at ${probe.url}`);
    if (probe.state === "signed-out") throw new SignedOut(probe.url);
    if (probe.state === "error") {
      throw new BrowserUnavailableError(
        `X answered with an error page (${probe.url}): "${probe.note}". This is usually X rate-limiting ` +
          `the account; wait a few minutes rather than retrying in a loop.`,
      );
    }
    if (probe.state === "empty" || ready(probe)) return probe;
    await sleep(POLL_MS, signal);
  }
};

/**
 * X keeps only the posts near the viewport in the page, so collect by URL
 * while scrolling rather than reading once at the end. Stops at `enough`, or
 * when scrolling brings nothing new.
 */
const collect = async (page: PageSession, first: XProbe, enough: (seen: Map<string, RawPost>) => boolean, signal: AbortSignal): Promise<RawPost[]> => {
  // The newest reading of a post wins: photos and cards render after the
  // text, so the first reading of a post can lack them. A Map keeps the order
  // posts were first seen in.
  const seen = new Map<string, RawPost>();
  const take = (p: XProbe) => p.posts.forEach((post) => seen.set(post.url, post));
  take(first);
  // Let the first screen settle: photos, cards and a post's replies arrive
  // after the post itself. Settled means two readings in a row agree, and
  // there are enough posts or ~3 s have passed.
  const shape = (p: XProbe) => p.posts.map((x) => `${x.url}:${x.media?.length ?? 0}:${x.card ? 1 : 0}`).join(" ");
  let previous = shape(first);
  for (let w = 0; w < 8; w++) {
    await sleep(POLL_MS, signal);
    const now = await page.evaluate<XProbe>(PROBE, signal);
    take(now);
    const current = shape(now);
    if (current === previous && (enough(seen) || w >= 3)) break;
    previous = current;
  }
  for (let i = 0; i < MAX_SCROLLS && !enough(seen); i++) {
    const before = seen.size;
    await page.evaluate(SCROLL, signal);
    // New posts arrive over the next second or so.
    for (let w = 0; w < 4 && seen.size === before; w++) {
      await sleep(POLL_MS, signal);
      take(await page.evaluate<XProbe>(PROBE, signal));
    }
    if (seen.size === before) break; // the end of the page
  }
  return [...seen.values()];
};

// --- The reads ---------------------------------------------------------------

export const xSearch = (request: XSearchRequest, outer: AbortSignal): Promise<XSearchOutcome> => {
  const sort: XSort = request.sort ?? "latest";
  const searchUrl = buildXSearchUrl(request.query, sort);
  return xRead(outer, `the search ${searchUrl}`, async (page, signal, saw) => {
    const probe = await open(page, searchUrl, signal, saw);
    if (probe.state === "empty") {
      throw new NoResultsError(
        `X found no posts for ${JSON.stringify(request.query)} (${sort}). X said: "${probe.note}". ` +
          `The page loaded normally, so the query is the cause: check the handle, loosen the terms, ` +
          `or try sort "top" or a wider date range.`,
      );
    }
    const posts = await collect(page, probe, (s) => s.size >= request.count, signal);
    return { query: request.query, sort, searchUrl, posts: posts.slice(0, request.count).map(finish) };
  });
};

export const xPost = (request: XPostRequest, outer: AbortSignal): Promise<XPostOutcome> => {
  const id = postIdOf(request.url);
  if (!id) return Promise.reject(new BrowserUnavailableError(`not an X post link: ${request.url}`));
  // /i/status/<id> redirects to the post under its author's handle.
  const url = `https://x.com/i/status/${id}`;
  const isMain = (p: RawPost) => p.url.endsWith(`/status/${id}`);
  return xRead(outer, `reading ${url}`, async (page, signal, saw) => {
    const probe = await open(page, url, signal, saw, (p) => p.posts.some(isMain));
    if (probe.state === "empty") {
      throw new NoResultsError(`X shows no post at ${url}: "${probe.note}". It may be deleted, or its account protected or suspended.`);
    }
    const posts = await collect(page, probe, (s) => s.size >= request.replies + 1 + [...s.values()].findIndex(isMain), signal);
    const at = posts.findIndex(isMain);
    if (at < 0) throw new BrowserUnavailableError(`X's page for ${url} did not show the post itself (${probe.url})`);
    return {
      post: finish(posts[at]!),
      thread: posts.slice(0, at).map(finish),
      replies: posts.slice(at + 1, at + 1 + request.replies).map(finish),
    };
  });
};

type ProfileSchema = {
  dateCreated?: string;
  relatedLink?: string[];
  mainEntity?: {
    additionalName?: string;
    name?: string;
    description?: string;
    homeLocation?: { name?: string };
    image?: { contentUrl?: string };
    url?: string;
    interactionStatistic?: { name?: string; userInteractionCount?: number }[];
  };
};

/** The profile from X's JSON-LD block: exact counts, where the page shows "92.2M". */
export const parseProfile = (json: string, handle: string): XProfile => {
  const s = JSON.parse(json) as ProfileSchema;
  const e = s.mainEntity ?? {};
  const count = (name: string) => e.interactionStatistic?.find((i) => i.name === name)?.userInteractionCount;
  const profile: XProfile = { name: e.name ?? handle, handle: `@${e.additionalName ?? handle}`, url: e.url ?? `https://x.com/${handle}` };
  if (e.description) profile.bio = e.description;
  if (e.homeLocation?.name) profile.location = e.homeLocation.name;
  const site = s.relatedLink?.find((l) => !/^https?:\/\/t\.co\//.test(l));
  if (site) profile.website = site;
  if (s.dateCreated) profile.joined = s.dateCreated;
  const followers = count("Follows");
  const following = count("Friends");
  const posts = count("Tweets");
  if (followers !== undefined) profile.followers = followers;
  if (following !== undefined) profile.following = following;
  if (posts !== undefined) profile.posts = posts;
  if (e.image?.contentUrl) profile.avatar = e.image.contentUrl;
  return profile;
};

export const xUser = (request: XUserRequest, outer: AbortSignal): Promise<XUserOutcome> => {
  const handle = handleOf(request.handle);
  if (!handle) return Promise.reject(new BrowserUnavailableError(`not an X handle: ${request.handle}`));
  const url = `https://x.com/${handle}`;
  return xRead(outer, `reading ${url}`, async (page, signal, saw) => {
    // The header renders before the posts; wait for both, or for X to say
    // the account has none to show.
    const probe = await open(page, url, signal, saw, (p) => p.profile !== null && p.state !== "loading");
    if (!probe.profile) {
      throw new NoResultsError(`X shows no account @${handle}: "${probe.note}". Check the handle.`);
    }
    const profile = parseProfile(probe.profile, handle);
    const posts = probe.state === "posts" && request.count > 0 ? await collect(page, probe, (s) => s.size >= request.count, signal) : [];
    return { profile, posts: posts.slice(0, request.count).map(finish) };
  });
};

export const xTrends = (tab: XTrendTab, outer: AbortSignal): Promise<XTrendsOutcome> => {
  const url = `https://x.com/explore/tabs/${tab}`;
  return xRead(outer, `reading ${url}`, async (page, signal, saw) => {
    await page.navigate(url, signal);
    for (;;) {
      const cells = await page.evaluate<string[] | null>(TRENDS, signal);
      if (cells === null) throw new SignedOut(url);
      saw(`${cells.length} trends at ${url}`);
      if (cells.length) {
        // The list renders in one go; a moment more lets the last cells fill.
        await sleep(POLL_MS, signal);
        const all = (await page.evaluate<string[] | null>(TRENDS, signal)) ?? cells;
        return { tab, trends: all.map(parseTrend).filter((t): t is XTrend => t !== undefined) };
      }
      const probe = await page.evaluate<XProbe>(PROBE, signal);
      if (probe.state === "error") {
        throw new BrowserUnavailableError(`X answered with an error page (${url}): "${probe.note}".`);
      }
      await sleep(POLL_MS, signal);
    }
  });
};