| 1 | const TWEET_HOSTS = new Set([ |
| 2 | 'mobile.twitter.com', |
| 3 | 'mobile.x.com', |
| 4 | 'twitter.com', |
| 5 | 'www.twitter.com', |
| 6 | 'www.x.com', |
| 7 | 'x.com', |
| 8 | ]) |
| 9 | |
| 10 | export function resolveTweetId( |
| 11 | id: string | number | undefined, |
| 12 | sourceUrl: string | undefined, |
| 13 | ): string | undefined { |
| 14 | if (typeof id === 'number') |
| 15 | return id.toString() |
| 16 | |
| 17 | if (id?.trim()) |
| 18 | return id.trim() |
| 19 | |
| 20 | if (!sourceUrl) |
| 21 | return |
| 22 | |
| 23 | try { |
| 24 | const url = new URL(sourceUrl) |
| 25 | if (!['http:', 'https:'].includes(url.protocol) || !TWEET_HOSTS.has(url.hostname)) |
| 26 | return |
| 27 | |
| 28 | const segments = url.pathname.split('/').filter(Boolean) |
| 29 | const statusIndex = segments.lastIndexOf('status') |
| 30 | const tweetId = segments[statusIndex + 1] |
| 31 | if (statusIndex < 1 || !tweetId || !/^\d+$/.test(tweetId)) |
| 32 | return |
| 33 | |
| 34 | return tweetId |
| 35 | } |
| 36 | catch {} |
| 37 | } |
| 38 |