返回 last30days-skill
twitter-client-utils.js
根目录 / skills / last30days / scripts / lib / vendor / bird-search / lib / twitter-client-utils.js
1 export function normalizeQuoteDepth(value) {
2 if (value === undefined || value === null) {
3 return 1;
4 }
5 if (!Number.isFinite(value)) {
6 return 1;
7 }
8 return Math.max(0, Math.floor(value));
9 }
10 export function firstText(...values) {
11 for (const value of values) {
12 if (typeof value === 'string') {
13 const trimmed = value.trim();
14 if (trimmed) {
15 return trimmed;
16 }
17 }
18 }
19 return undefined;
20 }
21 export function collectTextFields(value, keys, output) {
22 if (!value) {
23 return;
24 }
25 if (typeof value === 'string') {
26 return;
27 }
28 if (Array.isArray(value)) {
29 for (const item of value) {
30 collectTextFields(item, keys, output);
31 }
32 return;
33 }
34 if (typeof value === 'object') {
35 for (const [key, nested] of Object.entries(value)) {
36 if (keys.has(key)) {
37 if (typeof nested === 'string') {
38 const trimmed = nested.trim();
39 if (trimmed) {
40 output.push(trimmed);
41 }
42 continue;
43 }
44 }
45 collectTextFields(nested, keys, output);
46 }
47 }
48 }
49 export function uniqueOrdered(values) {
50 const seen = new Set();
51 const result = [];
52 for (const value of values) {
53 if (seen.has(value)) {
54 continue;
55 }
56 seen.add(value);
57 result.push(value);
58 }
59 return result;
60 }
61 /**
62 * Renders a Draft.js content_state into readable markdown/text format.
63 * Handles blocks (paragraphs, headers, lists) and entities (code blocks, links, tweets, dividers).
64 */
65 export function renderContentState(contentState) {
66 if (!Array.isArray(contentState?.blocks) || contentState.blocks.length === 0) {
67 return undefined;
68 }
69 // Build entity lookup map from array/object formats
70 const entityMap = new Map();
71 const rawEntityMap = contentState.entityMap ?? [];
72 if (Array.isArray(rawEntityMap)) {
73 for (const entry of rawEntityMap) {
74 if (!entry || typeof entry !== 'object') {
75 continue;
76 }
77 const key = Number.parseInt(entry.key, 10);
78 if (!Number.isNaN(key)) {
79 entityMap.set(key, entry.value);
80 }
81 }
82 }
83 else if (rawEntityMap && typeof rawEntityMap === 'object') {
84 for (const [key, value] of Object.entries(rawEntityMap)) {
85 const keyNumber = Number.parseInt(key, 10);
86 if (!Number.isNaN(keyNumber)) {
87 entityMap.set(keyNumber, value);
88 }
89 }
90 }
91 const outputLines = [];
92 let orderedListCounter = 0;
93 let previousBlockType;
94 for (const block of contentState.blocks) {
95 if (!block || typeof block !== 'object') {
96 continue;
97 }
98 // Reset ordered list counter when leaving ordered list context
99 if (block.type !== 'ordered-list-item' && previousBlockType === 'ordered-list-item') {
100 orderedListCounter = 0;
101 }
102 switch (block.type) {
103 case 'unstyled': {
104 // Plain paragraph - just output text with any inline formatting
105 const text = renderBlockText(block, entityMap);
106 if (text) {
107 outputLines.push(text);
108 }
109 break;
110 }
111 case 'header-one': {
112 const text = renderBlockText(block, entityMap);
113 if (text) {
114 outputLines.push(`# ${text}`);
115 }
116 break;
117 }
118 case 'header-two': {
119 const text = renderBlockText(block, entityMap);
120 if (text) {
121 outputLines.push(`## ${text}`);
122 }
123 break;
124 }
125 case 'header-three': {
126 const text = renderBlockText(block, entityMap);
127 if (text) {
128 outputLines.push(`### ${text}`);
129 }
130 break;
131 }
132 case 'unordered-list-item': {
133 const text = renderBlockText(block, entityMap);
134 if (text) {
135 outputLines.push(`- ${text}`);
136 }
137 break;
138 }
139 case 'ordered-list-item': {
140 orderedListCounter++;
141 const text = renderBlockText(block, entityMap);
142 if (text) {
143 outputLines.push(`${orderedListCounter}. ${text}`);
144 }
145 break;
146 }
147 case 'blockquote': {
148 const text = renderBlockText(block, entityMap);
149 if (text) {
150 outputLines.push(`> ${text}`);
151 }
152 break;
153 }
154 case 'atomic': {
155 // Atomic blocks are placeholders for embedded entities
156 const entityContent = renderAtomicBlock(block, entityMap);
157 if (entityContent) {
158 outputLines.push(entityContent);
159 }
160 break;
161 }
162 default: {
163 // Fallback: just output the text
164 const text = renderBlockText(block, entityMap);
165 if (text) {
166 outputLines.push(text);
167 }
168 }
169 }
170 previousBlockType = block.type;
171 }
172 const result = outputLines.join('\n\n');
173 return result.trim() || undefined;
174 }
175 /**
176 * Renders text content of a block, applying inline link entities.
177 */
178 function renderBlockText(block, entityMap) {
179 if (typeof block?.text !== 'string') {
180 return '';
181 }
182 let text = block.text;
183 const rawRanges = Array.isArray(block.entityRanges) ? block.entityRanges : [];
184 // Handle LINK entities by appending URL in markdown format
185 // Process in reverse order to not mess up offsets
186 const linkRanges = rawRanges
187 .filter((range) => {
188 if (!range || typeof range !== 'object') {
189 return false;
190 }
191 if (!Number.isInteger(range.offset) || !Number.isInteger(range.length) || range.offset < 0 || range.length < 0) {
192 return false;
193 }
194 const entity = entityMap.get(range.key);
195 return entity?.type === 'LINK' && typeof entity?.data?.url === 'string' && entity.data.url.length > 0;
196 })
197 .sort((a, b) => b.offset - a.offset);
198 for (const range of linkRanges) {
199 const entity = entityMap.get(range.key);
200 if (typeof entity?.data?.url === 'string' && entity.data.url.length > 0) {
201 const linkText = text.slice(range.offset, range.offset + range.length);
202 const markdownLink = `[${linkText}](${entity.data.url})`;
203 text = text.slice(0, range.offset) + markdownLink + text.slice(range.offset + range.length);
204 }
205 }
206 return text.trim();
207 }
208 /**
209 * Renders an atomic block by looking up its entity and returning appropriate content.
210 */
211 function renderAtomicBlock(block, entityMap) {
212 const entityRanges = Array.isArray(block?.entityRanges) ? block.entityRanges : [];
213 const firstRange = entityRanges[0];
214 if (!firstRange || typeof firstRange !== 'object') {
215 return undefined;
216 }
217 const entityKey = firstRange.key;
218 const entity = entityMap.get(entityKey);
219 if (!entity || typeof entity !== 'object') {
220 return undefined;
221 }
222 switch (entity.type) {
223 case 'MARKDOWN':
224 // Code blocks and other markdown content - output as-is
225 return typeof entity.data?.markdown === 'string'
226 ? entity.data.markdown.trim() || undefined
227 : undefined;
228 case 'DIVIDER':
229 return '---';
230 case 'TWEET':
231 if (entity.data?.tweetId) {
232 return `[Embedded Tweet: https://x.com/i/status/${entity.data.tweetId}]`;
233 }
234 return undefined;
235 case 'LINK':
236 if (typeof entity.data?.url === 'string' && entity.data.url) {
237 return `[Link: ${entity.data.url}]`;
238 }
239 return undefined;
240 case 'IMAGE':
241 // Images in atomic blocks - could extract URL if available
242 return '[Image]';
243 default:
244 return undefined;
245 }
246 }
247 export function extractArticleText(result) {
248 const article = result?.article;
249 if (!article || typeof article !== 'object') {
250 return undefined;
251 }
252 const rawArticleResult = article.article_results?.result;
253 const articleResult = rawArticleResult && typeof rawArticleResult === 'object' ? rawArticleResult : article;
254 if (process.env.BIRD_DEBUG_ARTICLE === '1') {
255 console.error('[bird][debug][article] payload:', JSON.stringify({
256 rest_id: result?.rest_id,
257 article: articleResult,
258 note_tweet: result?.note_tweet?.note_tweet_results?.result ?? null,
259 }, null, 2));
260 }
261 const title = firstText(articleResult.title, article.title);
262 // Try to render from rich content_state first (Draft.js format with blocks + entityMap)
263 // This preserves code blocks, embedded tweets, markdown, etc.
264 const contentState = article.article_results?.result?.content_state;
265 const richBody = renderContentState(contentState);
266 if (richBody) {
267 // Rich content found - prepend title if not already included
268 if (title) {
269 const normalizedTitle = title.trim();
270 const trimmedBody = richBody.trimStart();
271 const headingMatches = [`# ${normalizedTitle}`, `## ${normalizedTitle}`, `### ${normalizedTitle}`];
272 const hasTitle = trimmedBody === normalizedTitle ||
273 trimmedBody.startsWith(`${normalizedTitle}\n`) ||
274 headingMatches.some((heading) => trimmedBody.startsWith(heading));
275 if (!hasTitle) {
276 return `${title}\n\n${richBody}`;
277 }
278 }
279 return richBody;
280 }
281 // Fallback to plain text extraction for articles without rich content_state
282 let body = firstText(articleResult.plain_text, article.plain_text, articleResult.body?.text, articleResult.body?.richtext?.text, articleResult.body?.rich_text?.text, articleResult.content?.text, articleResult.content?.richtext?.text, articleResult.content?.rich_text?.text, articleResult.text, articleResult.richtext?.text, articleResult.rich_text?.text, article.body?.text, article.body?.richtext?.text, article.body?.rich_text?.text, article.content?.text, article.content?.richtext?.text, article.content?.rich_text?.text, article.text, article.richtext?.text, article.rich_text?.text);
283 if (body && title && body.trim() === title.trim()) {
284 body = undefined;
285 }
286 if (!body) {
287 const collected = [];
288 collectTextFields(articleResult, new Set(['text', 'title']), collected);
289 collectTextFields(article, new Set(['text', 'title']), collected);
290 const unique = uniqueOrdered(collected);
291 const filtered = title ? unique.filter((value) => value !== title) : unique;
292 if (filtered.length > 0) {
293 body = filtered.join('\n\n');
294 }
295 }
296 if (title && body && !body.startsWith(title)) {
297 return `${title}\n\n${body}`;
298 }
299 return body ?? title;
300 }
301 export function extractNoteTweetText(result) {
302 const note = result?.note_tweet?.note_tweet_results?.result;
303 if (!note) {
304 return undefined;
305 }
306 return firstText(note.text, note.richtext?.text, note.rich_text?.text, note.content?.text, note.content?.richtext?.text, note.content?.rich_text?.text);
307 }
308 export function extractTweetText(result) {
309 return extractArticleText(result) ?? extractNoteTweetText(result) ?? firstText(result?.legacy?.full_text);
310 }
311 export function extractArticleMetadata(result) {
312 const article = result?.article;
313 if (!article || typeof article !== 'object') {
314 return undefined;
315 }
316 const rawArticleResult = article.article_results?.result;
317 const articleResult = rawArticleResult && typeof rawArticleResult === 'object' ? rawArticleResult : article;
318 const title = firstText(articleResult.title, article.title);
319 if (!title) {
320 return undefined;
321 }
322 // preview_text is available in home timeline responses
323 const previewText = firstText(articleResult.preview_text, article.preview_text);
324 return { title, previewText };
325 }
326 export function extractMedia(result) {
327 // Prefer extended_entities (has video info), fall back to entities
328 const rawMedia = result?.legacy?.extended_entities?.media ?? result?.legacy?.entities?.media;
329 if (!Array.isArray(rawMedia) || rawMedia.length === 0) {
330 return undefined;
331 }
332 const media = [];
333 for (const item of rawMedia) {
334 if (!item || typeof item !== 'object' || !item.type || !item.media_url_https) {
335 continue;
336 }
337 const mediaItem = {
338 type: item.type,
339 url: item.media_url_https,
340 };
341 // Get dimensions from largest available size
342 const sizes = item.sizes;
343 if (sizes?.large) {
344 mediaItem.width = sizes.large.w;
345 mediaItem.height = sizes.large.h;
346 }
347 else if (sizes?.medium) {
348 mediaItem.width = sizes.medium.w;
349 mediaItem.height = sizes.medium.h;
350 }
351 // For thumbnails/previews
352 if (sizes?.small) {
353 mediaItem.previewUrl = `${item.media_url_https}:small`;
354 }
355 // Extract video URL for video/animated_gif
356 if ((item.type === 'video' || item.type === 'animated_gif') && Array.isArray(item.video_info?.variants)) {
357 // Prefer highest bitrate MP4, fall back to first MP4 when bitrate is missing.
358 const mp4Variants = item.video_info.variants.filter((v) => v && typeof v === 'object' && v.content_type === 'video/mp4' && typeof v.url === 'string');
359 const mp4WithBitrate = mp4Variants
360 .filter((v) => typeof v.bitrate === 'number')
361 .sort((a, b) => b.bitrate - a.bitrate);
362 const selectedVariant = mp4WithBitrate[0] ?? mp4Variants[0];
363 if (selectedVariant) {
364 mediaItem.videoUrl = selectedVariant.url;
365 }
366 if (typeof item.video_info.duration_millis === 'number') {
367 mediaItem.durationMs = item.video_info.duration_millis;
368 }
369 }
370 media.push(mediaItem);
371 }
372 return media.length > 0 ? media : undefined;
373 }
374 export function unwrapTweetResult(result) {
375 if (!result || typeof result !== 'object') {
376 return undefined;
377 }
378 if (result.tweet && typeof result.tweet === 'object') {
379 return result.tweet;
380 }
381 return result;
382 }
383 export function mapTweetResult(result, quoteDepthOrOptions) {
384 const options = typeof quoteDepthOrOptions === 'number'
385 ? { quoteDepth: quoteDepthOrOptions }
386 : (quoteDepthOrOptions ?? {});
387 const { quoteDepth = 1, includeRaw = false } = options;
388 const userResult = result?.core?.user_results?.result;
389 const userLegacy = userResult?.legacy;
390 const userCore = userResult?.core;
391 const username = userLegacy?.screen_name ?? userCore?.screen_name;
392 const name = userLegacy?.name ?? userCore?.name ?? username;
393 const userId = userResult?.rest_id;
394 if (!result?.rest_id || !username) {
395 return undefined;
396 }
397 const text = extractTweetText(result);
398 if (!text) {
399 return undefined;
400 }
401 let quotedTweet;
402 if (quoteDepth > 0) {
403 const quotedResult = unwrapTweetResult(result.quoted_status_result?.result);
404 if (quotedResult) {
405 quotedTweet = mapTweetResult(quotedResult, { quoteDepth: quoteDepth - 1, includeRaw });
406 }
407 }
408 const media = extractMedia(result);
409 const article = extractArticleMetadata(result);
410 const tweetData = {
411 id: result.rest_id,
412 text,
413 createdAt: result.legacy?.created_at,
414 replyCount: result.legacy?.reply_count,
415 retweetCount: result.legacy?.retweet_count,
416 likeCount: result.legacy?.favorite_count,
417 conversationId: result.legacy?.conversation_id_str,
418 inReplyToStatusId: result.legacy?.in_reply_to_status_id_str ?? undefined,
419 author: {
420 username,
421 name: name || username,
422 },
423 authorId: userId,
424 quotedTweet,
425 media,
426 article,
427 };
428 if (includeRaw) {
429 tweetData._raw = result;
430 }
431 return tweetData;
432 }
433 export function findTweetInInstructions(instructions, tweetId) {
434 if (!Array.isArray(instructions)) {
435 return undefined;
436 }
437 for (const instruction of instructions) {
438 const entries = Array.isArray(instruction?.entries) ? instruction.entries : [];
439 for (const entry of entries) {
440 const result = unwrapTweetResult(entry?.content?.itemContent?.tweet_results?.result);
441 if (result?.rest_id === tweetId) {
442 return result;
443 }
444 }
445 }
446 return undefined;
447 }
448 export function collectTweetResultsFromEntry(entry) {
449 const results = [];
450 if (!entry || typeof entry !== 'object') {
451 return results;
452 }
453 const pushResult = (result) => {
454 const unwrapped = unwrapTweetResult(result);
455 if (unwrapped?.rest_id) {
456 results.push(unwrapped);
457 }
458 };
459 const content = entry.content;
460 pushResult(content?.itemContent?.tweet_results?.result);
461 pushResult(content?.item?.itemContent?.tweet_results?.result);
462 if (Array.isArray(content?.items)) {
463 for (const item of content.items) {
464 pushResult(item?.item?.itemContent?.tweet_results?.result);
465 pushResult(item?.itemContent?.tweet_results?.result);
466 pushResult(item?.content?.itemContent?.tweet_results?.result);
467 }
468 }
469 return results;
470 }
471 export function parseTweetsFromInstructions(instructions, quoteDepthOrOptions) {
472 const options = typeof quoteDepthOrOptions === 'number'
473 ? { quoteDepth: quoteDepthOrOptions }
474 : (quoteDepthOrOptions ?? {});
475 const { quoteDepth = 1, includeRaw = false } = options;
476 const tweets = [];
477 const seen = new Set();
478 if (!Array.isArray(instructions)) {
479 return tweets;
480 }
481 for (const instruction of instructions) {
482 if (!instruction || typeof instruction !== 'object') {
483 continue;
484 }
485 const entries = [];
486 if (Array.isArray(instruction.entries)) {
487 entries.push(...instruction.entries);
488 }
489 if (instruction.entry && typeof instruction.entry === 'object') {
490 entries.push(instruction.entry);
491 }
492 for (const entry of entries) {
493 const results = collectTweetResultsFromEntry(entry);
494 for (const result of results) {
495 let mapped;
496 try {
497 mapped = mapTweetResult(result, { quoteDepth, includeRaw });
498 }
499 catch {
500 continue;
501 }
502 if (!mapped || seen.has(mapped.id)) {
503 continue;
504 }
505 seen.add(mapped.id);
506 tweets.push(mapped);
507 }
508 }
509 }
510 return tweets;
511 }
512 export function extractCursorFromInstructions(instructions, cursorType = 'Bottom') {
513 if (!Array.isArray(instructions)) {
514 return undefined;
515 }
516 let matchedCursor;
517 let matchedEntryId;
518 const inspectEntry = (entry, isReplacement) => {
519 if (!entry || typeof entry !== 'object') {
520 return;
521 }
522 const content = entry.content;
523 if (content?.cursorType === cursorType && typeof content.value === 'string' && content.value.length > 0) {
524 if (
525 matchedCursor === undefined ||
526 isReplacement ||
527 (typeof entry.entryId === 'string' && entry.entryId === matchedEntryId)
528 ) {
529 matchedCursor = content.value;
530 if (typeof entry.entryId === 'string' && entry.entryId.length > 0) {
531 matchedEntryId = entry.entryId;
532 }
533 }
534 }
535 };
536 for (const instruction of instructions) {
537 if (!instruction || typeof instruction !== 'object') {
538 continue;
539 }
540 if (Array.isArray(instruction.entries)) {
541 for (const entry of instruction.entries) {
542 inspectEntry(entry, false);
543 }
544 }
545 if (instruction.entry && typeof instruction.entry === 'object') {
546 inspectEntry(instruction.entry, true);
547 }
548 }
549 return matchedCursor;
550 }
551 export function parseUsersFromInstructions(instructions) {
552 if (!Array.isArray(instructions)) {
553 return [];
554 }
555 const users = [];
556 for (const instruction of instructions) {
557 if (!Array.isArray(instruction?.entries)) {
558 continue;
559 }
560 for (const entry of instruction.entries) {
561 const content = entry?.content;
562 const rawUserResult = content?.itemContent?.user_results?.result;
563 const userResult = rawUserResult?.__typename === 'UserWithVisibilityResults' && rawUserResult.user
564 ? rawUserResult.user
565 : rawUserResult;
566 if (!userResult || userResult.__typename !== 'User') {
567 continue;
568 }
569 const legacy = userResult.legacy;
570 const core = userResult.core;
571 const username = legacy?.screen_name ?? core?.screen_name;
572 if (!userResult.rest_id || !username) {
573 continue;
574 }
575 users.push({
576 id: userResult.rest_id,
577 username,
578 name: legacy?.name ?? core?.name ?? username,
579 description: legacy?.description,
580 followersCount: legacy?.followers_count,
581 followingCount: legacy?.friends_count,
582 isBlueVerified: userResult.is_blue_verified,
583 profileImageUrl: legacy?.profile_image_url_https ?? userResult.avatar?.image_url,
584 createdAt: legacy?.created_at ?? core?.created_at,
585 });
586 }
587 }
588 return users;
589 }
590 //# sourceMappingURL=twitter-client-utils.js.map
590 lines JAVASCRIPT