Files
RSSHub/lib/routes/twitter/api/web-api/gql-id-resolver.ts
T
dependabot[bot]andTony 873618e99d chore(deps-dev): bump eslint-plugin-unicorn from 65.0.1 to 66.0.0 (#22274)
* chore(deps-dev): bump eslint-plugin-unicorn from 65.0.1 to 66.0.0

Bumps [eslint-plugin-unicorn](https://github.com/sindresorhus/eslint-plugin-unicorn) from 65.0.1 to 66.0.0.
- [Release notes](https://github.com/sindresorhus/eslint-plugin-unicorn/releases)
- [Commits](https://github.com/sindresorhus/eslint-plugin-unicorn/compare/v65.0.1...v66.0.0)

---
updated-dependencies:
- dependency-name: eslint-plugin-unicorn
  dependency-version: 66.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* style: fix unicorn-js/prefer-url-href

* style: oxlint disable

* style: fix unicorn-js/no-useless-else

* style: no-unsafe-string-replacement

* style: fix no-duplicate-loops

* style: fix prefer-number-is-safe-integer

* style: fix prefer-single-array-predicate

* style: fix no-object-methods-with-collections

* style: fix no-useless-boolean-cast

* style: fix no-useless-template-literals

* style: fix no-negated-array-predicate

* style: fix prefer-direct-iteration

* style: fix consistent-optional-chaining

* style: fix prefer-simple-sort-comparator

* style: fix prefer-global-number-constants

* style: fix prefer-type-literal-last

* style: fix require-array-sort-compare.

* style: fix prefer-early-return

* style: fix prefer-short-arrow-method

* style: fix prefer-array-from-map

* style: fix prefer-scoped-selector

* style: fix no-global-object-property-assignment

* style: fix no-unnecessary-global-this

* style: fix no-unreadable-object-destructuring

* style: fix no-invalid-argument-count

* style: fix prefer-smaller-scope

* style: fix prefer-iterator-to-array.

* style: fix prefer-object-iterable-methods

* style: fix typo

* style: fix max-nested-calls

* style: fix no-incorrect-template-string-interpolation

* style: fix no-break-in-nested-loop

* style: fix prefer-await

* style: fix no-computed-property-existence-check

* style: fix prefer-number-coercion

* style: fix no-empty-file

* style: update eslint unicorn v66 recommended preset

* style: add unicorn/prefer-spread to oxlint-disable comments

* style: fix no-array-reduce

* style: delete github/no-then as it's covered by unicorn/prefer-await

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Tony <TonyRL@users.noreply.github.com>
2026-06-16 14:43:42 +08:00

117 lines
4.3 KiB
TypeScript

import { config } from '@/config';
import cache from '@/utils/cache';
import logger from '@/utils/logger';
import ofetch from '@/utils/ofetch';
const CACHE_KEY = 'twitter:gql-query-ids';
// Hardcoded fallback IDs (last known working values)
export const fallbackIds: Record<string, string> = {
UserTweets: 'E3opETHurmVJflFsUBVuUQ',
UserByScreenName: 'Yka-W8dz7RaEuQNkroPkYw',
HomeTimeline: 'xhYBF94fPSp8ey64FfYXiA',
HomeLatestTimeline: '0vp2Au9doTKsbn2vIk48Dg',
UserTweetsAndReplies: 'bt4TKuFz4T7Ckk-VvQVSow',
UserMedia: 'dexO_2tohK86JDudXXG3Yw',
UserByRestId: 'Qw77dDjp9xCpUY-AXwt-yQ',
SearchTimeline: 'UN1i3zUiCWa-6r-Uaho4fw',
ListLatestTweetsTimeline: 'Pa45JvqZuKcW1plybfgBlQ',
TweetDetail: 'QuBlQ6SxNAQCt6-kBiCXCQ',
};
const operationNames = Object.keys(fallbackIds);
async function fetchTwitterPage(): Promise<string> {
const response = await ofetch('https://x.com', {
parseResponse: (txt) => txt,
});
return response as unknown as string;
}
function extractQueryIds(scriptContent: string): Record<string, string> {
const ids: Record<string, string> = {};
const matches = scriptContent.matchAll(/queryId:"([^"]+)".+?operationName:"([^"]+)"/g);
for (const match of matches) {
const [, queryId, operationName] = match;
if (operationNames.includes(operationName)) {
ids[operationName] = queryId;
}
}
return ids;
}
async function fetchAndExtractIds(): Promise<Record<string, string>> {
const html = await fetchTwitterPage();
// Extract main.hash.js URL — it contains all the GraphQL query IDs we need
const mainMatch = html.match(/\/client-web\/main\.([a-z0-9]+)\./);
if (!mainMatch) {
logger.warn('twitter gql-id-resolver: main.js URL not found in Twitter page');
return {};
}
const mainUrl = `https://abs.twimg.com/responsive-web/client-web/main.${mainMatch[1]}.js`;
logger.debug(`twitter gql-id-resolver: fetching ${mainUrl}`);
const content = await ofetch(mainUrl, {
parseResponse: (txt) => txt,
});
return extractQueryIds(content as unknown as string);
}
let resolvePromise: Promise<Record<string, string>> | null = null;
export async function resolveQueryIds(): Promise<Record<string, string>> {
// Check cache first
const cached = await cache.get(CACHE_KEY);
if (cached) {
try {
const parsed = typeof cached === 'string' ? JSON.parse(cached) : cached;
if (parsed && typeof parsed === 'object' && Object.keys(parsed).length > 0) {
logger.debug('twitter gql-id-resolver: using cached query IDs');
return { ...fallbackIds, ...parsed };
}
} catch {
// ignore parse error
}
}
// Deduplicate concurrent requests
if (!resolvePromise) {
resolvePromise = (async () => {
try {
logger.info('twitter gql-id-resolver: fetching fresh query IDs from Twitter JS bundles');
const ids = await fetchAndExtractIds();
if (Object.keys(ids).length > 0) {
await cache.set(CACHE_KEY, JSON.stringify(ids), config.cache.contentExpire);
const found = operationNames.filter((name) => ids[name]);
const missing = operationNames.filter((name) => !Object.hasOwn(ids, name));
logger.debug(`twitter gql-id-resolver: resolved ${found.length}/${operationNames.length} query IDs. Missing: ${missing.join(', ') || 'none'}`);
} else {
logger.warn('twitter gql-id-resolver: failed to extract any query IDs, using fallback');
}
return ids;
} catch (error) {
logger.warn(`twitter gql-id-resolver: error fetching query IDs: ${error}. Using fallback.`);
return {};
} finally {
resolvePromise = null;
}
})();
}
const ids = await resolvePromise;
return { ...fallbackIds, ...ids };
}
export function buildGqlMap(queryIds: Record<string, string>): Record<string, string> {
const map: Record<string, string> = {};
for (const name of operationNames) {
const id = queryIds[name] || fallbackIds[name];
map[name] = `/graphql/${id}/${name}`;
}
return map;
}