| 1 | import { redactSecrets } from './cookies.js'; |
| 2 | import { QUERY_ID_REGEX } from './runtime-query-ids.js'; |
| 3 | import { TWITTER_API_BASE } from './twitter-client-constants.js'; |
| 4 | import { buildSearchFeatures } from './twitter-client-features.js'; |
| 5 | import { extractCursorFromInstructions, parseTweetsFromInstructions } from './twitter-client-utils.js'; |
| 6 | const RAW_QUERY_MISSING_REGEX = /must be defined/i; |
| 7 | const DEFAULT_UNLIMITED_MAX_PAGES = 20; |
| 8 | const DEFAULT_FINITE_MAX_PAGES_CEILING = 10; |
| 9 | const SKIP_BODY_ON_404 = new Set([404]); |
| 10 | function isQueryIdMismatch(payload) { |
| 11 | try { |
| 12 | const parsed = JSON.parse(payload); |
| 13 | return (parsed.errors?.some((error) => { |
| 14 | if (error?.extensions?.code === 'GRAPHQL_VALIDATION_FAILED') { |
| 15 | return true; |
| 16 | } |
| 17 | if (error?.path?.includes('rawQuery') && RAW_QUERY_MISSING_REGEX.test(error.message ?? '')) { |
| 18 | return true; |
| 19 | } |
| 20 | return false; |
| 21 | }) ?? false); |
| 22 | } |
| 23 | catch { |
| 24 | return false; |
| 25 | } |
| 26 | } |
| 27 | export function withSearch(Base) { |
| 28 | class TwitterClientSearch extends Base { |
| 29 | // biome-ignore lint/complexity/noUselessConstructor lint/suspicious/noExplicitAny: TS mixin constructor requirement. |
| 30 | constructor(...args) { |
| 31 | super(...args); |
| 32 | } |
| 33 | /** |
| 34 | * Search for tweets matching a query |
| 35 | */ |
| 36 | async search(query, count = 20, options = {}) { |
| 37 | return this.searchPaged(query, count, options); |
| 38 | } |
| 39 | /** |
| 40 | * Get all search results (paged) |
| 41 | */ |
| 42 | async getAllSearchResults(query, options) { |
| 43 | return this.searchPaged(query, Number.POSITIVE_INFINITY, options); |
| 44 | } |
| 45 | async searchPaged(query, limit, options = {}) { |
| 46 | if (limit !== Number.POSITIVE_INFINITY && (!Number.isFinite(limit) || limit <= 0)) { |
| 47 | return { success: false, error: 'Invalid search count' }; |
| 48 | } |
| 49 | const features = buildSearchFeatures(); |
| 50 | const pageSize = 20; |
| 51 | const seen = new Set(); |
| 52 | const tweets = []; |
| 53 | let cursor = options.cursor; |
| 54 | let nextCursor; |
| 55 | let pagesFetched = 0; |
| 56 | const { includeRaw = false, maxPages, product = 'Latest', pageDelayMs = 0 } = options; |
| 57 | if (maxPages !== undefined) { |
| 58 | if (typeof maxPages !== 'number' || !Number.isFinite(maxPages)) { |
| 59 | return { success: false, error: 'Invalid maxPages' }; |
| 60 | } |
| 61 | if (maxPages <= 0) { |
| 62 | return { success: true, tweets: [], nextCursor: cursor }; |
| 63 | } |
| 64 | } |
| 65 | const unlimited = limit === Number.POSITIVE_INFINITY; |
| 66 | const effectiveMaxPages = maxPages !== undefined |
| 67 | ? Math.floor(maxPages) |
| 68 | : unlimited |
| 69 | ? DEFAULT_UNLIMITED_MAX_PAGES |
| 70 | : Math.min(DEFAULT_FINITE_MAX_PAGES_CEILING, Math.ceil(limit / pageSize) + 2); |
| 71 | if (effectiveMaxPages <= 0) { |
| 72 | return { success: true, tweets: [], nextCursor: cursor }; |
| 73 | } |
| 74 | const seenCursors = new Set(cursor ? [cursor] : []); |
| 75 | const totalTimeoutMs = |
| 76 | typeof options.timeoutMs === 'number' && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 |
| 77 | ? options.timeoutMs |
| 78 | : typeof this.timeoutMs === 'number' && Number.isFinite(this.timeoutMs) && this.timeoutMs > 0 |
| 79 | ? this.timeoutMs |
| 80 | : undefined; |
| 81 | const deadlineMs = totalTimeoutMs !== undefined ? Date.now() + totalTimeoutMs : undefined; |
| 82 | const remainingBudgetMs = () => (deadlineMs !== undefined ? deadlineMs - Date.now() : undefined); |
| 83 | const timeoutError = () => `Request timed out after ${totalTimeoutMs}ms`; |
| 84 | const redact = (msg) => |
| 85 | typeof this.redactError === 'function' ? this.redactError(msg) : redactSecrets(msg); |
| 86 | const fetchPage = async (pageCount, pageCursor) => { |
| 87 | let lastError; |
| 88 | let had404 = false; |
| 89 | const queryIds = await this.getSearchTimelineQueryIds(); |
| 90 | for (const queryId of queryIds) { |
| 91 | if (typeof queryId !== 'string' || !QUERY_ID_REGEX.test(queryId)) { |
| 92 | continue; |
| 93 | } |
| 94 | const remainingMs = remainingBudgetMs(); |
| 95 | if (remainingMs !== undefined && remainingMs <= 0) { |
| 96 | return { success: false, error: timeoutError(), had404: false }; |
| 97 | } |
| 98 | const variables = { |
| 99 | rawQuery: query, |
| 100 | count: pageCount, |
| 101 | querySource: 'typed_query', |
| 102 | product, |
| 103 | ...(pageCursor ? { cursor: pageCursor } : {}), |
| 104 | }; |
| 105 | const params = new URLSearchParams({ |
| 106 | variables: JSON.stringify(variables), |
| 107 | }); |
| 108 | const url = `${TWITTER_API_BASE}/${queryId}/SearchTimeline?${params.toString()}`; |
| 109 | try { |
| 110 | const response = await this.fetchTextWithTimeout( |
| 111 | url, |
| 112 | { |
| 113 | method: 'POST', |
| 114 | headers: this.getHeaders(), |
| 115 | body: JSON.stringify({ features, queryId }), |
| 116 | }, |
| 117 | { |
| 118 | skipBodyStatuses: SKIP_BODY_ON_404, |
| 119 | ...(remainingMs !== undefined ? { timeoutMs: remainingMs } : {}), |
| 120 | }, |
| 121 | ); |
| 122 | if (response.status === 404) { |
| 123 | had404 = true; |
| 124 | lastError = `HTTP ${response.status}`; |
| 125 | continue; |
| 126 | } |
| 127 | if (!response.ok) { |
| 128 | const text = response.text; |
| 129 | const shouldRefreshQueryIds = (response.status === 400 || response.status === 422) && isQueryIdMismatch(text); |
| 130 | return { |
| 131 | success: false, |
| 132 | error: `HTTP ${response.status}: ${redact(text).slice(0, 200)}`, |
| 133 | had404: had404 || shouldRefreshQueryIds, |
| 134 | }; |
| 135 | } |
| 136 | const data = JSON.parse(response.text); |
| 137 | if (data.errors && data.errors.length > 0) { |
| 138 | const shouldRefreshQueryIds = data.errors.some((error) => error?.extensions?.code === 'GRAPHQL_VALIDATION_FAILED'); |
| 139 | return { |
| 140 | success: false, |
| 141 | error: redact(data.errors.map((e) => e.message).join(', ')), |
| 142 | had404: had404 || shouldRefreshQueryIds, |
| 143 | }; |
| 144 | } |
| 145 | const instructions = data.data?.search_by_raw_query?.search_timeline?.timeline?.instructions; |
| 146 | const pageTweets = parseTweetsFromInstructions(instructions, { quoteDepth: this.quoteDepth, includeRaw }); |
| 147 | const nextCursor = extractCursorFromInstructions(instructions); |
| 148 | return { success: true, tweets: pageTweets, cursor: nextCursor, had404 }; |
| 149 | } |
| 150 | catch (error) { |
| 151 | lastError = redact(error instanceof Error ? error.message : String(error)); |
| 152 | return { success: false, error: lastError, had404: false }; |
| 153 | } |
| 154 | } |
| 155 | return { success: false, error: lastError ?? 'Unknown error fetching search results', had404 }; |
| 156 | }; |
| 157 | const fetchWithRefresh = async (pageCount, pageCursor) => { |
| 158 | const firstAttempt = await fetchPage(pageCount, pageCursor); |
| 159 | if (firstAttempt.success) { |
| 160 | return firstAttempt; |
| 161 | } |
| 162 | if (firstAttempt.had404) { |
| 163 | const refreshRemainingMs = remainingBudgetMs(); |
| 164 | if (refreshRemainingMs !== undefined && refreshRemainingMs <= 0) { |
| 165 | return { success: false, error: timeoutError() }; |
| 166 | } |
| 167 | let refreshBudgetMs; |
| 168 | if (refreshRemainingMs !== undefined) { |
| 169 | const retryReserveMs = refreshRemainingMs > 2000 |
| 170 | ? Math.min(3000, Math.floor(refreshRemainingMs / 3)) |
| 171 | : Math.floor(refreshRemainingMs / 3); |
| 172 | refreshBudgetMs = Math.max(1, refreshRemainingMs - retryReserveMs); |
| 173 | } |
| 174 | await this.refreshQueryIds( |
| 175 | refreshBudgetMs !== undefined ? { timeoutMs: refreshBudgetMs } : {}, |
| 176 | ); |
| 177 | const retryRemainingMs = remainingBudgetMs(); |
| 178 | if (retryRemainingMs !== undefined && retryRemainingMs <= 0) { |
| 179 | return { success: false, error: timeoutError() }; |
| 180 | } |
| 181 | const secondAttempt = await fetchPage(pageCount, pageCursor); |
| 182 | if (secondAttempt.success) { |
| 183 | return secondAttempt; |
| 184 | } |
| 185 | return { success: false, error: secondAttempt.error }; |
| 186 | } |
| 187 | return { success: false, error: firstAttempt.error }; |
| 188 | }; |
| 189 | while (unlimited || tweets.length < limit) { |
| 190 | const remainingBeforePage = remainingBudgetMs(); |
| 191 | if (remainingBeforePage !== undefined && remainingBeforePage <= 0) { |
| 192 | if (tweets.length > 0) { |
| 193 | return { success: false, error: timeoutError(), tweets, nextCursor: cursor }; |
| 194 | } |
| 195 | return { success: false, error: timeoutError() }; |
| 196 | } |
| 197 | if (pagesFetched > 0 && pageDelayMs > 0 && typeof this.sleep === 'function') { |
| 198 | if (remainingBeforePage !== undefined && pageDelayMs >= remainingBeforePage) { |
| 199 | return { success: false, error: timeoutError(), tweets, nextCursor: cursor }; |
| 200 | } |
| 201 | await this.sleep(pageDelayMs); |
| 202 | } |
| 203 | const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length); |
| 204 | const page = await fetchWithRefresh(pageCount, cursor); |
| 205 | if (!page.success) { |
| 206 | if (tweets.length > 0) { |
| 207 | return { success: false, error: page.error, tweets, nextCursor: cursor }; |
| 208 | } |
| 209 | return { success: false, error: page.error }; |
| 210 | } |
| 211 | pagesFetched += 1; |
| 212 | let added = 0; |
| 213 | for (const tweet of page.tweets) { |
| 214 | if (seen.has(tweet.id)) { |
| 215 | continue; |
| 216 | } |
| 217 | seen.add(tweet.id); |
| 218 | tweets.push(tweet); |
| 219 | added += 1; |
| 220 | if (!unlimited && tweets.length >= limit) { |
| 221 | break; |
| 222 | } |
| 223 | } |
| 224 | const pageCursor = page.cursor; |
| 225 | if (!pageCursor || seenCursors.has(pageCursor) || page.tweets.length === 0 || added === 0) { |
| 226 | nextCursor = undefined; |
| 227 | break; |
| 228 | } |
| 229 | seenCursors.add(pageCursor); |
| 230 | if (pagesFetched >= effectiveMaxPages) { |
| 231 | nextCursor = pageCursor; |
| 232 | break; |
| 233 | } |
| 234 | cursor = pageCursor; |
| 235 | nextCursor = pageCursor; |
| 236 | } |
| 237 | return { success: true, tweets, nextCursor }; |
| 238 | } |
| 239 | } |
| 240 | return TwitterClientSearch; |
| 241 | } |
| 242 | //# sourceMappingURL=twitter-client-search.js.map |