From 1a610c366a98926637296265be3c8a6592090738 Mon Sep 17 00:00:00 2001 From: Peter Steinberger Date: Thu, 1 Jan 2026 16:53:19 +0100 Subject: [PATCH] fix(followers): fallback to legacy API --- src/lib/twitter-client-users.ts | 81 ++++++++++++++++++++ tests/twitter-client.following-likes.test.ts | 40 ++++++++++ 2 files changed, 121 insertions(+) diff --git a/src/lib/twitter-client-users.ts b/src/lib/twitter-client-users.ts index 8b5da4d..16ebb10 100644 --- a/src/lib/twitter-client-users.ts +++ b/src/lib/twitter-client-users.ts @@ -34,6 +34,79 @@ export function withUsers>( return Array.from(new Set([primary, 'kuFUYP9eV1FPoEy4N-pi7w'])); } + private async getFollowersViaRest(userId: string, count: number): Promise { + const params = new URLSearchParams({ + user_id: userId, + count: String(count), + skip_status: 'true', + include_user_entities: 'false', + }); + + const urls = [ + `https://x.com/i/api/1.1/followers/list.json?${params.toString()}`, + `https://api.twitter.com/1.1/followers/list.json?${params.toString()}`, + ]; + + let lastError: string | undefined; + + for (const url of urls) { + try { + const response = await this.fetchWithTimeout(url, { + method: 'GET', + headers: this.getHeaders(), + }); + + if (!response.ok) { + const text = await response.text(); + lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`; + continue; + } + + const data = (await response.json()) as { + users?: Array<{ + id_str?: string; + id?: string | number; + screen_name?: string; + name?: string; + description?: string; + followers_count?: number; + friends_count?: number; + verified?: boolean; + profile_image_url_https?: string; + created_at?: string; + }>; + }; + + const users = (data.users ?? []) + .map((u) => { + const id = typeof u.id_str === 'string' ? u.id_str : typeof u.id === 'number' ? String(u.id) : null; + const username = typeof u.screen_name === 'string' ? u.screen_name : null; + if (!id || !username) { + return null; + } + return { + id, + username, + name: typeof u.name === 'string' && u.name.length > 0 ? u.name : username, + description: typeof u.description === 'string' ? u.description : undefined, + followersCount: typeof u.followers_count === 'number' ? u.followers_count : undefined, + followingCount: typeof u.friends_count === 'number' ? u.friends_count : undefined, + isBlueVerified: typeof u.verified === 'boolean' ? u.verified : undefined, + profileImageUrl: typeof u.profile_image_url_https === 'string' ? u.profile_image_url_https : undefined, + createdAt: typeof u.created_at === 'string' ? u.created_at : undefined, + }; + }) + .filter((u) => u !== null); + + return { success: true, users }; + } catch (error) { + lastError = error instanceof Error ? error.message : String(error); + } + } + + return { success: false, error: lastError ?? 'Unknown error fetching followers' }; + } + /** * Fetch the account associated with the current cookies */ @@ -334,6 +407,14 @@ export function withUsers>( if (secondAttempt.success) { return { success: true, users: secondAttempt.users }; } + + // GraphQL Followers regularly returns 404 (queryId churn / endpoint flakiness). + // Fallback to the legacy 1.1 endpoint so the CLI stays useful. + const restAttempt = await this.getFollowersViaRest(userId, count); + if (restAttempt.success) { + return restAttempt; + } + return { success: false, error: secondAttempt.error }; } diff --git a/tests/twitter-client.following-likes.test.ts b/tests/twitter-client.following-likes.test.ts index 48b743a..120da65 100644 --- a/tests/twitter-client.following-likes.test.ts +++ b/tests/twitter-client.following-likes.test.ts @@ -200,6 +200,46 @@ describe('TwitterClient following/followers', () => { expect(result.success).toBe(true); expect(mockFetch).toHaveBeenCalledTimes(2); }); + + it('falls back to REST followers list after repeated 404s', async () => { + mockFetch + .mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'nope' }) + .mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'still nope' }) + .mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => ({ + users: [ + { + id_str: '1', + screen_name: 'alpha', + name: 'Alpha', + description: 'bio-1', + followers_count: 10, + friends_count: 5, + verified: true, + profile_image_url_https: 'https://example.com/1.jpg', + created_at: '2024-01-01T00:00:00Z', + }, + ], + }), + }); + + const client = new TwitterClient({ cookies: validCookies }); + const clientPrivate = client as unknown as TwitterClient & { getFollowersQueryIds: () => Promise }; + clientPrivate.getFollowersQueryIds = async () => ['test']; + + const result = await client.getFollowers('123', 1); + + expect(result.success).toBe(true); + expect(result.users?.[0].username).toBe('alpha'); + expect(mockFetch).toHaveBeenCalledTimes(3); + + const urls = mockFetch.mock.calls.map((call) => String(call[0])); + expect(urls[0]).toContain('/Followers?'); + expect(urls[1]).toContain('/Followers?'); + expect(urls[2]).toContain('/followers/list.json?'); + }); }); describe('TwitterClient likes', () => {