/** * The entity leg: `wbgetentities` on the Wikidata API, in batches of * {@linkcode DEFAULT_ENTITY_BATCH} ids, for the ranked candidates. * * The API answers an id list where the query service times out on a world-scale * class query (measured 2026-11-03: 5,171 items with no timeout against 27 of 29 * per-class `GROUP BY` counts failing after about 135 s each). * Each entity's classes, country, coordinate, population, sitelink count * and the requested languages' labels and aliases are kept. * The class verdict is a later phase's. * * Records are appended to a JSONL file as each request answers, and a rerun reads * the ids already on disk before it asks for the rest. * Entity answers therefore skip the HTTP cache: the JSONL file is the resume record, * and a cached answer averaged about 100 KB per entity (1.85 GB for 18,600 entities). * * The requests follow Wikimedia's published limits: * * - https://wikitech.wikimedia.org/wiki/Robot_policy, "Action API rules": "If unauthenticated, * keep the concurrency of your requests to 1 at a time, and below 5 requests per second overall." * "If authenticated, you can raise the concurrency to 3 overall, * and the number of requests per second to 10." * "Avoid using expensive API endpoints: if your request takes more than 1 second to serve, * please wait 5 seconds before making another request." * - https://www.mediawiki.org/wiki/API:Etiquette: "If your task isn't interactive, * i.e. a user isn't waiting for the result, you should use the `maxlag` parameter." * "Use GZip compression when making API calls by setting `Accept-Encoding: gzip` * to reduce bandwidth usage." * - https://www.mediawiki.org/wiki/Wikimedia_APIs/Rate_limits: "limit the number of * concurrent requests to 3 or fewer"; unauthenticated bot requests with a compliant * User-Agent, and accounts with few edits, get 200 requests per minute. * - https://www.mediawiki.org/wiki/Manual:Maxlag_parameter: a lagged replica answers * `maxlag` requests with status 200, an `error.code` of `maxlag`, the `lag` in seconds * and a `Retry-After` header; "pause your script for at least 5 seconds before trying again". * * {@linkcode ACTION_API_LIMITS} holds the concurrency and spacing of each mode, a request that takes * more than {@linkcode SLOW_REQUEST_MS} to serve holds its worker for {@linkcode SLOW_REQUEST_WAIT_MS}, * every entity request sets `maxlag=5`, and the client sends `Accept-Encoding: gzip`. */ import { APIClient, type APIClientConfig } from "@mailwoman/core/api"; import type { LatLon } from "@mailwoman/spatial/position"; import type { PathBuilderLike } from "path-ts"; import { type WikidataBotCredentials, WikimediaRequestMode } from "#tools/fetch/wikidata/session"; import { type CreateWikidataClientOptions } from "#tools/fetch/wikidata/subvenue"; import { type ProgressReporter } from "#tools/fetch/wikidata/vital-places/progress"; import type { QRankRow } from "#tools/fetch/wikidata/vital-places/qrank"; /** * The MediaWiki API endpoint of Wikidata. */ export declare const WIKIDATA_API_ENDPOINT = "https://www.wikidata.org/w/api.php"; /** * The most ids one `wbgetentities` request accepts without a bot flag. */ export declare const WBGETENTITIES_BATCH = 50; /** * The ids one entity request asks for when a caller sets no batch size. * * Measured 2026-11-04 from the lab host, serially, with this module's `props` and ten languages: * 10 ids answered in 607 and 849 ms, 20 in 883 and 961 ms, and 50 in 1,455 and 1,596 ms. * Twenty sits within 12% of the 1 s threshold, and a request over it costs a 5 s wait. * * Twenty ids beat ten only while fewer than about one request in nine runs slow. */ export declare const DEFAULT_ENTITY_BATCH = 10; /** * A request that takes longer than this to serve is an expensive one under the robot policy. */ export declare const SLOW_REQUEST_MS = 1000; /** * How long a worker waits after an expensive request before its next one. */ export declare const SLOW_REQUEST_WAIT_MS = 5000; /** * The replica lag, in seconds, past which the API refuses an entity request. */ export declare const MAXLAG_SECONDS = 5; /** * The languages whose labels and aliases are kept when a caller passes none. * * Covers every language declared in `SUPPORT_PROMISES` (`en`, `fr`, `es`, `de`, `it`, * `nl`, `pl`, `pt`, `sv`, `ja`) alongside `ru`, `zh`, `ar`, and `he`. */ export declare const DEFAULT_LANGUAGES: readonly string[]; /** * The item for Earth, the globe a kept coordinate must sit on. */ export declare const EARTH_QID = "Q2"; /** * One ranked entity as kept from `wbgetentities`. */ export interface VitalEntity { qid: string; qrank: number; /** * The `P31` class ids. */ classes: string[]; /** * The `P17` country item ids. */ countries: string[]; /** * The best-ranked `P625` coordinate on Earth, or `null` when the item has none. */ coordinate: LatLon | null; /** * The best-ranked `P1082` population, or `null` when the item has none. */ population: number | null; /** * The number of sitelinks, every project counted. */ sitelinks: number; labels: Record; aliases: Record; } /** * A ranked id the API reports as missing, such as a deleted item. */ export interface MissingEntity { qid: string; qrank: number; missing: true; } /** * One line of the entities file. */ export type VitalEntityRecord = VitalEntity | MissingEntity; /** * Whether a record is a kept entity rather than a missing one. */ export declare function isVitalEntity(record: VitalEntityRecord): record is VitalEntity; /** * The parts of a `wbgetentities` entity this module reads. */ export interface WikidataEntityBody { id?: string; missing?: string; redirects?: { from?: string; to?: string; }; labels?: Record; aliases?: Record>; claims?: Record; sitelinks?: Record; } /** * One statement as the API serializes it. */ export interface WikidataClaim { rank?: "preferred" | "normal" | "deprecated"; mainsnak?: { snaktype?: string; datavalue?: { type?: string; value?: unknown; }; }; } /** * The `wbgetentities` response envelope. */ export interface WikidataEntitiesResponse { entities?: Record; /** * An Action API error; `lag` is the replica lag in seconds on a `maxlag` error. */ error?: { code?: string; info?: string; lag?: number; }; warnings?: { result?: { "*"?: string; }; }; } /** * Options for {@linkcode buildEntitiesURL}. */ export interface EntitiesURLOptions { /** * Adds `assert=user`, so a request whose session lapsed is refused rather than served anonymously. */ assertUser?: boolean; } /** * The `wbgetentities` request for a batch of ids, with `maxlag` set. */ export declare function buildEntitiesURL(ids: readonly string[], languages: readonly string[], options?: EntitiesURLOptions): string; /** * Options for {@linkcode WikidataAPIClient.getEntities}. */ export interface GetEntitiesOptions { /** * Whether the answer may come from and go to the HTTP cache. * * Off for the ranked entities, since the entities file already keeps them. * On for the few country lookups. * * @defaultValue `false` */ cache?: boolean; } /** * The configuration of a {@linkcode WikidataAPIClient}. * * The shared client's, with the bot credentials it logs in with. */ export interface WikidataAPIClientConfig extends APIClientConfig { credentials?: WikidataBotCredentials | null; } /** * A paced and retrying client for the Wikidata API, logged in when it holds bot credentials. * * Session cookies a response sets are kept and sent on every later request. * Each request's serve time runs from its start, after pacing, to its answer. */ export declare class WikidataAPIClient extends APIClient { #private; /** * The client spaces its own requests by `minRequestIntervalMs` before each one starts. * * The base client's adapter would pace inside the request instead. * A request paced before it starts takes its serve time, with no pacing wait inside it. */ constructor(config: WikidataAPIClientConfig); /** * The requests this client started, each counted once with its retries. */ get requestsDispatched(): number; /** * The account the client is logged in as, or `null`. */ get loggedInAs(): string | null; /** * Whether requests go out logged in. */ get mode(): WikimediaRequestMode; /** * Log in with the bot credentials and confirm the session through `meta=userinfo`. * * The steps are those of https://www.mediawiki.org/wiki/API:Login: a login token from * `meta=tokens`, then `action=login` with `lgname`, `lgpassword` and `lgtoken` in a POST body. * Concurrent callers share one login. * * @returns The account the API reports. * @throws With the credential values redacted, when a step fails or the session reads as anonymous. */ logIn(): Promise; /** * Fetch a batch of entities, keyed by the id each was requested under. * * The API files a redirected item under its target id with a `redirects.from` field, * so the answer is re-keyed by the requested id. * An id the answer files in neither way is an error in the answer and is refused * rather than read as missing. */ getEntities(ids: readonly string[], languages?: readonly string[], options?: GetEntitiesOptions): Promise>; } /** * The wait before asking again after a `maxlag` answer, in milliseconds. */ export declare function maxlagWaitMs(retryAfter: unknown, lagSeconds: unknown): number; /** * Whether a body has the `wbgetentities` envelope. */ export declare function isEntitiesResponse(value: unknown): value is WikidataEntitiesResponse; /** * Options for {@linkcode createWikidataAPIClient}. */ export interface CreateWikidataAPIClientOptions extends CreateWikidataClientOptions { /** * The bot credentials to log in with; `null` or absent sends every request anonymously. */ credentials?: WikidataBotCredentials | null; } /** * Creates a Wikidata API client with the shared retry, cache and header defaults, spaced for its mode. * * A client given credentials is spaced for the logged-in mode. * It logs in when {@linkcode WikidataAPIClient.logIn} is called. */ export declare function createWikidataAPIClient(options: CreateWikidataAPIClientOptions): WikidataAPIClient; /** * The statements of one property that state a value, best rank first and deprecated ones left out. */ export declare function rankedClaims(entity: WikidataEntityBody, property: string): WikidataClaim[]; /** * The item ids a property's statements point at. */ export declare function claimItemIDs(entity: WikidataEntityBody, property: string): string[]; /** * The best-ranked coordinate on Earth, or `null`. * * A coordinate on another globe, such as a Martian crater's, isn't a place an address refers to. */ export declare function readEarthCoordinate(entity: WikidataEntityBody): LatLon | null; /** * The best-ranked population, or `null`. */ export declare function readPopulation(entity: WikidataEntityBody): number | null; /** * The best-ranked ISO 3166-1 alpha-2 code, or `null` for an item that has none. */ export declare function readISOAlpha2(entity: WikidataEntityBody): string | null; /** * The record kept for one ranked id from the API's entity. */ export declare function readVitalEntity(row: QRankRow, entity: WikidataEntityBody, languages: readonly string[]): VitalEntityRecord; /** * Every record already in the entities file, in file order. */ export declare function readEntityRecords(path: PathBuilderLike): Promise; export interface FetchVitalEntitiesOptions { /** * The JSONL file records are appended to. */ entitiesPath: PathBuilderLike; languages?: readonly string[]; /** * The ids one request asks for, from 1 to {@linkcode WBGETENTITIES_BATCH}. * * @defaultValue {@linkcode DEFAULT_ENTITY_BATCH} */ batchSize?: number; /** * The requests in flight at once, capped by the client's mode in {@linkcode ACTION_API_LIMITS}. * * @defaultValue the mode's cap */ concurrency?: number; /** * The number of requests between progress lines. */ reportEvery?: number; report?: ProgressReporter; } /** * The concurrency a run uses: the one asked for, capped by the mode. * * @throws When the request isn't a positive integer. */ export declare function resolveConcurrency(mode: WikimediaRequestMode, requested?: number | null): number; export interface FetchVitalEntitiesResult { /** * Ranked ids whose record was already on disk. */ skipped: number; /** * Records appended by this run. */ fetched: number; /** * Requests that failed after the client's retries, with the first id of each. */ failedBatches: string[]; } /** * Append a record for every ranked id the entities file lacks, one batch per request, * with up to the mode's concurrency of workers taking the remaining batches in turn. * * An id already on disk isn't requested again. * Each worker's records are appended through one write queue, a batch's lines together, * so the file holds whole lines in the order the batches finished. * * A request that fails after the client's retries is reported and skipped, * so a rerun asks for its ids again. */ export declare function fetchVitalEntities(client: Pick, rows: readonly QRankRow[], options: FetchVitalEntitiesOptions): Promise; /** * The ISO 3166-1 alpha-2 code of each country item, `null` where the item states none. * * Codes already known are not requested again. */ export declare function readCountryCodes(client: Pick, countryIDs: readonly string[], known?: Readonly>, report?: ProgressReporter): Promise>; //# sourceMappingURL=entities.d.ts.map