@internetdata/internetdata 2.8.1 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -1,13 +1,21 @@
1
1
  import type { Writable } from 'node:stream';
2
2
  import type { Client } from './generated/client/index.js';
3
+ import type { Entitlement } from './generated/types.gen.js';
4
+ import { InternetDataError } from './errors.js';
3
5
  import { OauthApi } from './oauth.js';
4
- import type { Database, DatabaseFormat, DatabaseMetadata, DbChecksums, Download } from './types.js';
6
+ import type { AsnResult, Database, DatabaseFormat, DatabaseMetadata, DbChecksums, DomainResult, Download, Result } from './types.js';
5
7
  /**
6
8
  * Where `download` puts the bytes: a path to write, or a stream you opened
7
9
  * yourself and will close yourself.
8
10
  */
9
11
  export type DownloadDestination = string | Writable;
10
- export declare const DEFAULT_BASE_URL = "https://internetdata.io";
12
+ export declare const DEFAULT_BASE_URL = "https://api.internetdata.io";
13
+ export interface CacheOptions {
14
+ /** Maximum number of addresses held. Default 10000. */
15
+ max?: number;
16
+ /** How long an answer stays fresh, in milliseconds. Default 1 hour. */
17
+ ttlMs?: number;
18
+ }
11
19
  export interface DownloadsOptions {
12
20
  /** How many attempts to return, newest first. The API clamps this to 200. */
13
21
  limit?: number;
@@ -42,12 +50,24 @@ export interface DownloadOptions {
42
50
  }
43
51
  export interface Options {
44
52
  /**
45
- * Your API key, carrying the `db.download` scope. Omit it to send no
46
- * `Authorization` header at all, which is what a dataset offered without a
47
- * license would be read with.
53
+ * Your API key. Without one a lookup is on Unlimited, the free plan, limited
54
+ * per address per minute, and no `Authorization` header is sent at all. The
55
+ * database calls need a key carrying the `db.download` scope. A batch needs
56
+ * a key on a paid plan.
48
57
  */
49
58
  apiKey?: string;
59
+ /**
60
+ * Default `https://api.internetdata.io`. The `oauth` calls go to the apex
61
+ * this names: `api.` dropped, and `api-<env>.` read as `<env>.`.
62
+ */
50
63
  baseUrl?: string;
64
+ /** Pass `false` to disable caching. */
65
+ cache?: CacheOptions | false;
66
+ /**
67
+ * Concurrent batch requests - chunks of up to 1000 addresses - during a
68
+ * batch, a whole number from 1. Default 8.
69
+ */
70
+ concurrency?: number;
51
71
  /** Retry attempts for a transient failure, a whole number from 0. Default 2. */
52
72
  retries?: number;
53
73
  /**
@@ -62,20 +82,36 @@ export interface Options {
62
82
  /** Override the HTTP implementation, mostly for tests. */
63
83
  fetch?: typeof globalThis.fetch;
64
84
  }
85
+ /** Per-call overrides for a single lookup. Anything omitted falls back to the client's setting. */
86
+ export interface LookupOptions {
87
+ /** Retry attempts for a transient failure, a whole number from 0. */
88
+ retries?: number;
89
+ /** How long one attempt may take before it is abandoned, in milliseconds. */
90
+ timeoutMs?: number;
91
+ }
92
+ /** Per-call overrides for one batch. Anything omitted falls back to the client's setting. */
93
+ export interface BatchOptions extends LookupOptions {
94
+ /** Concurrent batch requests for THIS batch only. */
95
+ concurrency?: number;
96
+ }
65
97
  /**
66
98
  * A client for the InternetData API.
67
99
  *
68
- * Everything the API answers is scoped to the organization the key belongs to,
69
- * including which databases are listed at all, so one client speaks for exactly
70
- * one organization and nothing it learns may be reused for another key.
100
+ * The cache is per instance, so an answer is never shared between two clients
101
+ * holding different API keys and therefore entitled to different fields.
71
102
  *
72
- * The key is optional, and an absent one sends no `Authorization` header rather
73
- * than an empty one. `oauth` needs none. Every database published today is
74
- * licensed, so a keyless `database` call is answered `401` for now; it exists
75
- * because what the API serves without a license is a product decision, not the
76
- * client's to refuse.
103
+ * Everything the database calls answer is scoped to the organization the key
104
+ * belongs to, including which databases are listed at all, so one client speaks
105
+ * for exactly one organization and nothing it learns may be reused for another
106
+ * key. The key is optional, and an absent one sends no `Authorization` header
107
+ * rather than an empty one. `oauth` needs none.
77
108
  */
78
109
  export declare class InternetData {
110
+ private readonly client;
111
+ private readonly cache;
112
+ private readonly limit;
113
+ private readonly retries;
114
+ private readonly timeoutMs;
79
115
  /** The database catalog, downloads and their history. */
80
116
  readonly database: DatabaseApi;
81
117
  /**
@@ -84,6 +120,105 @@ export declare class InternetData {
84
120
  */
85
121
  readonly oauth: OauthApi;
86
122
  constructor(options?: Options);
123
+ /**
124
+ * Whether an address is private, loopback, link-local, documentation,
125
+ * multicast or otherwise not routable, including the IPv6 equivalents and
126
+ * the 6to4 and Teredo ranges.
127
+ *
128
+ * These are the addresses `lookup` answers locally. Exposed here so the
129
+ * check is reachable from the client you already hold; the same function is
130
+ * also importable on its own.
131
+ */
132
+ isBogon(ip: string): boolean;
133
+ /**
134
+ * What every database says about one address.
135
+ *
136
+ * A bogon is answered locally and never reaches the network. Everything
137
+ * else is served, then cached for this instance. Calls that miss the cache
138
+ * while a request for their address is in flight, a batch's included, await
139
+ * that request rather than sending their own, and take its answer, sent
140
+ * under the options of the call that led it. An IPv4-mapped address
141
+ * (`::ffff:8.8.8.8`) is the IPv4 address it carries: judged, sent and cached
142
+ * as that, so the answer names `8.8.8.8`.
143
+ */
144
+ lookup(ip: string, options?: LookupOptions): Promise<Result>;
145
+ private serve;
146
+ /**
147
+ * What the databases say about the address this client is calling from.
148
+ *
149
+ * The same answer `lookup` would give for that address, at the same cost
150
+ * against your allowance. The address is the one our edge observed, so a
151
+ * call made through a proxy or a VPN reports the exit it left through -
152
+ * usually the point of asking.
153
+ *
154
+ * Deliberately NOT cached. The cache is keyed by address, and which
155
+ * address this is IS the question: a machine that moves between networks
156
+ * would otherwise be told where it used to be.
157
+ */
158
+ myIp(options?: LookupOptions): Promise<Result>;
159
+ /**
160
+ * What InternetData knows about one autonomous system, by its number: its
161
+ * registration on every plan, and on a paid one its ASN Whois record and
162
+ * every prefix it announces.
163
+ *
164
+ * Sent as given and not cached. The API refuses a number it cannot read as
165
+ * `bad_request`.
166
+ */
167
+ lookupAsn(asn: number, options?: LookupOptions): Promise<AsnResult>;
168
+ /**
169
+ * What InternetData knows about one domain: on every plan whether it is
170
+ * registered and which DNS record types it has, and on a paid one the
171
+ * records themselves, its organization's IP ranges and whether it is a
172
+ * disposable email domain.
173
+ *
174
+ * Sent as given and not cached. The API refuses a name it cannot read as
175
+ * `bad_request`.
176
+ */
177
+ lookupDomain(domain: string, options?: LookupOptions): Promise<DomainResult>;
178
+ /**
179
+ * What this client's key is entitled to, and how much of it has been used.
180
+ *
181
+ * Named for what it answers rather than `me`, which sits one letter from
182
+ * `myIp` and means something quite different: one is which address you are
183
+ * calling FROM, the other is what the key you are calling WITH may spend.
184
+ *
185
+ * Unlike a lookup there is no useful unauthenticated answer, so a client
186
+ * built without a key gets an unauthorized error rather than a partial one.
187
+ *
188
+ * Usage counts against the ALLOWANCE WINDOW - on a paid plan the
189
+ * anniversary of the subscription, not the calendar month and not the
190
+ * billing period, and on the free plan the UTC day - and it is the same
191
+ * number a lookup is gated on. It can lag by a few seconds, because
192
+ * requests are counted in memory and flushed in aggregate.
193
+ *
194
+ * Deliberately NOT cached: the whole point is what has been spent, and a
195
+ * cached answer is a wrong one within seconds of the next request.
196
+ */
197
+ myEntitlement(options?: LookupOptions): Promise<Entitlement>;
198
+ /**
199
+ * Look many addresses up in as few requests as possible.
200
+ *
201
+ * Bogons are answered locally and cached answers are reused, and an address
202
+ * with a request already in flight, a lookup's or another batch's, awaits
203
+ * that request; everything else goes to the batch endpoint in chunks of up
204
+ * to 1000 addresses, with at most `concurrency` chunks in flight, and a
205
+ * lookup arriving meanwhile awaits this batch's answer for its address.
206
+ * Keyed by address rather than positional, so duplicates in the input
207
+ * collapse to a single entry and the caller never has to line two lists up.
208
+ * An address that fails carries its error as its value, so one bad entry
209
+ * cannot lose the rest of the answers: the API reports a per-entry failure
210
+ * with the status the single lookup would have answered, and a chunk that
211
+ * fails as a whole marks every address in it. A per-call `concurrency` that
212
+ * is not a whole number from 1 is refused as `bad_request` before anything
213
+ * is sent. An IPv4-mapped address is looked up as the IPv4 address it
214
+ * carries, and its answer keyed as you passed it. The batch endpoint needs
215
+ * a paid plan: without a key every address in a request of two or more
216
+ * carries an `unauthorized` error, and a free-plan key's request of two or
217
+ * more a `bad_request` (HTTP 402). A request of one address is answered as
218
+ * its lookup would be.
219
+ */
220
+ lookupBatch(ips: Iterable<string>, options?: BatchOptions): Promise<Map<string, Result | InternetDataError>>;
221
+ private lookupChunk;
87
222
  }
88
223
  /** The licensed database downloads. Access is granted by contract, not self-serve. */
89
224
  export declare class DatabaseApi {
package/dist/client.js CHANGED
@@ -1,29 +1,42 @@
1
+ import { LRUCache } from 'lru-cache';
2
+ import pLimit from 'p-limit';
1
3
  import { createClient, createConfig } from './generated/client/index.js';
2
- import { databaseChecksumV2, databaseMetadataV2, downloadDatabaseV2 as downloadRedirect, listDatabases, listDownloads, } from './generated/sdk.gen.js';
3
- import { errorFromResponse, InternetDataError } from './errors.js';
4
+ import { databaseChecksumV2, databaseMetadataV2, downloadDatabaseV2 as downloadRedirect, listDatabases, listDownloads, lookupAsn, lookupBatch, lookupDomain, lookupIp, lookupMyIp, myEntitlement, } from './generated/sdk.gen.js';
5
+ import { bogonResult, isBogon, unmapped } from './bogon.js';
6
+ import { errorFromEntry, errorFromResponse, InternetDataError } from './errors.js';
4
7
  import { OauthApi } from './oauth.js';
5
- import { isChecksumsResponse, isDatabaseList, isDatabaseMetadata, isDownloadList, } from './shapes.js';
6
- import { checkTimeout, deadline, readable, unwrap, withRetry } from './transport.js';
7
- import { DATABASE_FORMATS } from './types.js';
8
- export const DEFAULT_BASE_URL = 'https://internetdata.io';
8
+ import { isAsnLookup, isBatch, isBatchError, isChecksumsResponse, isDatabaseList, isDatabaseMetadata, isDomainLookup, isDownloadList, isEntitlement, isLookup, } from './shapes.js';
9
+ import { asError, checkConcurrency, checkRetries, checkTimeout, deadline, readable, unwrap, withRetry, } from './transport.js';
10
+ import { DATABASE_FORMATS, toAsnResult, toDomainResult, toResult } from './types.js';
11
+ export const DEFAULT_BASE_URL = 'https://api.internetdata.io';
9
12
  // Matches the other SDKs, whose HTTP clients default to 30s. Node's global
10
13
  // fetch has no whole-request limit of its own, so without this a hung API holds
11
14
  // a caller until undici's 300s headers timeout.
12
15
  const DEFAULT_TIMEOUT_MS = 30_000;
16
+ // The most addresses POST /batch takes in one call; a larger batch is sent in
17
+ // chunks of this size.
18
+ const BATCH_MAX = 1000;
13
19
  /**
14
20
  * A client for the InternetData API.
15
21
  *
16
- * Everything the API answers is scoped to the organization the key belongs to,
17
- * including which databases are listed at all, so one client speaks for exactly
18
- * one organization and nothing it learns may be reused for another key.
22
+ * The cache is per instance, so an answer is never shared between two clients
23
+ * holding different API keys and therefore entitled to different fields.
19
24
  *
20
- * The key is optional, and an absent one sends no `Authorization` header rather
21
- * than an empty one. `oauth` needs none. Every database published today is
22
- * licensed, so a keyless `database` call is answered `401` for now; it exists
23
- * because what the API serves without a license is a product decision, not the
24
- * client's to refuse.
25
+ * Everything the database calls answer is scoped to the organization the key
26
+ * belongs to, including which databases are listed at all, so one client speaks
27
+ * for exactly one organization and nothing it learns may be reused for another
28
+ * key. The key is optional, and an absent one sends no `Authorization` header
29
+ * rather than an empty one. `oauth` needs none.
25
30
  */
26
31
  export class InternetData {
32
+ client;
33
+ // Keyed by address. The context is how a call sends the request when the
34
+ // address has none in flight: `fetch()` runs it synchronously, so a batch
35
+ // knows which addresses it leads before it builds a chunk.
36
+ cache;
37
+ limit;
38
+ retries;
39
+ timeoutMs;
27
40
  /** The database catalog, downloads and their history. */
28
41
  database;
29
42
  /**
@@ -37,18 +50,312 @@ export class InternetData {
37
50
  // the same implementation a test substituted.
38
51
  const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
39
52
  const apiKey = checkApiKey(options.apiKey);
40
- const client = createClient(createConfig({
41
- // Every path appended starts with a slash, and a second one is another
42
- // path, which the API answers with a redirect.
43
- baseUrl: (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, ''),
53
+ // Every path appended starts with a slash, and a second one is another
54
+ // path, which the API answers with a redirect.
55
+ const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
56
+ this.client = createClient(createConfig({
57
+ baseUrl: baseUrl,
44
58
  ...(apiKey === undefined ? {} : { auth: bearerOnly(apiKey) }),
45
59
  fetch: fetchImpl,
46
60
  }));
47
- const retries = checkRetries(options.retries ?? 2);
48
- const timeoutMs = checkTimeout(options.timeoutMs) ?? DEFAULT_TIMEOUT_MS;
49
- this.database = new DatabaseApi(client, retries, timeoutMs, fetchImpl);
50
- this.oauth = new OauthApi(client, retries, timeoutMs);
61
+ this.cache = options.cache === false ? null : new LRUCache({
62
+ max: options.cache?.max ?? 10_000,
63
+ ttl: options.cache?.ttlMs ?? 60 * 60 * 1000,
64
+ // Concurrent misses for one address share one request: every
65
+ // `fetch()` while it is in flight gets the same promise, and a
66
+ // failure rejects them all and is cached for none.
67
+ fetchMethod: (_ip, _stale, { context }) => context(),
68
+ // An eviction must not fail the callers awaiting a request.
69
+ ignoreFetchAbort: true,
70
+ });
71
+ this.limit = pLimit(checkConcurrency(options.concurrency) ?? 8);
72
+ this.retries = checkRetries(options.retries) ?? 2;
73
+ this.timeoutMs = checkTimeout(options.timeoutMs) ?? DEFAULT_TIMEOUT_MS;
74
+ this.database = new DatabaseApi(this.client, this.retries, this.timeoutMs, fetchImpl);
75
+ // The authorization server is the apex, not the API host, and its
76
+ // requests carry no credential at all.
77
+ const authServer = createClient(createConfig({ baseUrl: apexOf(baseUrl), fetch: fetchImpl }));
78
+ this.oauth = new OauthApi(authServer, this.retries, this.timeoutMs);
79
+ }
80
+ /**
81
+ * Whether an address is private, loopback, link-local, documentation,
82
+ * multicast or otherwise not routable, including the IPv6 equivalents and
83
+ * the 6to4 and Teredo ranges.
84
+ *
85
+ * These are the addresses `lookup` answers locally. Exposed here so the
86
+ * check is reachable from the client you already hold; the same function is
87
+ * also importable on its own.
88
+ */
89
+ isBogon(ip) {
90
+ return isBogon(ip);
91
+ }
92
+ /**
93
+ * What every database says about one address.
94
+ *
95
+ * A bogon is answered locally and never reaches the network. Everything
96
+ * else is served, then cached for this instance. Calls that miss the cache
97
+ * while a request for their address is in flight, a batch's included, await
98
+ * that request rather than sending their own, and take its answer, sent
99
+ * under the options of the call that led it. An IPv4-mapped address
100
+ * (`::ffff:8.8.8.8`) is the IPv4 address it carries: judged, sent and cached
101
+ * as that, so the answer names `8.8.8.8`.
102
+ */
103
+ async lookup(ip, options = {}) {
104
+ // First, or a bogon and a cached address would answer any value.
105
+ checkTimeout(options.timeoutMs);
106
+ checkRetries(options.retries);
107
+ const addr = unmapped(ip);
108
+ if (isBogon(addr)) {
109
+ return bogonResult(addr);
110
+ }
111
+ if (this.cache === null) {
112
+ return this.serve(addr, options);
113
+ }
114
+ return (await this.cache.fetch(addr, { context: () => this.serve(addr, options) }));
115
+ }
116
+ async serve(ip, options) {
117
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
118
+ return withRetry(options.retries ?? this.retries, async () => {
119
+ const res = await deadline(timeoutMs, (signal) => lookupIp({
120
+ client: this.client, path: { ip: ip }, signal: signal,
121
+ }));
122
+ return toResult(readable(res, isLookup));
123
+ });
51
124
  }
125
+ /**
126
+ * What the databases say about the address this client is calling from.
127
+ *
128
+ * The same answer `lookup` would give for that address, at the same cost
129
+ * against your allowance. The address is the one our edge observed, so a
130
+ * call made through a proxy or a VPN reports the exit it left through -
131
+ * usually the point of asking.
132
+ *
133
+ * Deliberately NOT cached. The cache is keyed by address, and which
134
+ * address this is IS the question: a machine that moves between networks
135
+ * would otherwise be told where it used to be.
136
+ */
137
+ async myIp(options = {}) {
138
+ const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
139
+ return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
140
+ const res = await deadline(timeoutMs, (signal) => lookupMyIp({
141
+ client: this.client, signal: signal,
142
+ }));
143
+ return toResult(readable(res, isLookup));
144
+ });
145
+ }
146
+ /**
147
+ * What InternetData knows about one autonomous system, by its number: its
148
+ * registration on every plan, and on a paid one its ASN Whois record and
149
+ * every prefix it announces.
150
+ *
151
+ * Sent as given and not cached. The API refuses a number it cannot read as
152
+ * `bad_request`.
153
+ */
154
+ async lookupAsn(asn, options = {}) {
155
+ const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
156
+ return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
157
+ const res = await deadline(timeoutMs, (signal) => lookupAsn({
158
+ client: this.client, path: { asn: String(asn) }, signal: signal,
159
+ }));
160
+ return toAsnResult(readable(res, isAsnLookup));
161
+ });
162
+ }
163
+ /**
164
+ * What InternetData knows about one domain: on every plan whether it is
165
+ * registered and which DNS record types it has, and on a paid one the
166
+ * records themselves, its organization's IP ranges and whether it is a
167
+ * disposable email domain.
168
+ *
169
+ * Sent as given and not cached. The API refuses a name it cannot read as
170
+ * `bad_request`.
171
+ */
172
+ async lookupDomain(domain, options = {}) {
173
+ const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
174
+ return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
175
+ const res = await deadline(timeoutMs, (signal) => lookupDomain({
176
+ client: this.client, path: { domain: domain }, signal: signal,
177
+ }));
178
+ return toDomainResult(readable(res, isDomainLookup));
179
+ });
180
+ }
181
+ /**
182
+ * What this client's key is entitled to, and how much of it has been used.
183
+ *
184
+ * Named for what it answers rather than `me`, which sits one letter from
185
+ * `myIp` and means something quite different: one is which address you are
186
+ * calling FROM, the other is what the key you are calling WITH may spend.
187
+ *
188
+ * Unlike a lookup there is no useful unauthenticated answer, so a client
189
+ * built without a key gets an unauthorized error rather than a partial one.
190
+ *
191
+ * Usage counts against the ALLOWANCE WINDOW - on a paid plan the
192
+ * anniversary of the subscription, not the calendar month and not the
193
+ * billing period, and on the free plan the UTC day - and it is the same
194
+ * number a lookup is gated on. It can lag by a few seconds, because
195
+ * requests are counted in memory and flushed in aggregate.
196
+ *
197
+ * Deliberately NOT cached: the whole point is what has been spent, and a
198
+ * cached answer is a wrong one within seconds of the next request.
199
+ */
200
+ async myEntitlement(options = {}) {
201
+ const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
202
+ return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
203
+ const res = await deadline(timeoutMs, (signal) => myEntitlement({
204
+ client: this.client, signal: signal,
205
+ }));
206
+ return readable(res, isEntitlement);
207
+ });
208
+ }
209
+ /**
210
+ * Look many addresses up in as few requests as possible.
211
+ *
212
+ * Bogons are answered locally and cached answers are reused, and an address
213
+ * with a request already in flight, a lookup's or another batch's, awaits
214
+ * that request; everything else goes to the batch endpoint in chunks of up
215
+ * to 1000 addresses, with at most `concurrency` chunks in flight, and a
216
+ * lookup arriving meanwhile awaits this batch's answer for its address.
217
+ * Keyed by address rather than positional, so duplicates in the input
218
+ * collapse to a single entry and the caller never has to line two lists up.
219
+ * An address that fails carries its error as its value, so one bad entry
220
+ * cannot lose the rest of the answers: the API reports a per-entry failure
221
+ * with the status the single lookup would have answered, and a chunk that
222
+ * fails as a whole marks every address in it. A per-call `concurrency` that
223
+ * is not a whole number from 1 is refused as `bad_request` before anything
224
+ * is sent. An IPv4-mapped address is looked up as the IPv4 address it
225
+ * carries, and its answer keyed as you passed it. The batch endpoint needs
226
+ * a paid plan: without a key every address in a request of two or more
227
+ * carries an `unauthorized` error, and a free-plan key's request of two or
228
+ * more a `bad_request` (HTTP 402). A request of one address is answered as
229
+ * its lookup would be.
230
+ */
231
+ async lookupBatch(ips, options = {}) {
232
+ const concurrency = checkConcurrency(options.concurrency);
233
+ checkTimeout(options.timeoutMs);
234
+ checkRetries(options.retries);
235
+ const asked = [...new Set(ips)];
236
+ const unique = [...new Set(asked.map(unmapped))];
237
+ const out = new Map();
238
+ const pending = [];
239
+ // Every address that is neither a bogon nor cached goes through
240
+ // `fetch()` in one synchronous pass: one with a request in flight joins
241
+ // it, and for the rest `fetchMethod` runs at once, which is how this
242
+ // batch learns the addresses it leads before building any chunk.
243
+ const shared = [];
244
+ const led = new Map();
245
+ for (const ip of unique) {
246
+ if (isBogon(ip)) {
247
+ out.set(ip, bogonResult(ip));
248
+ continue;
249
+ }
250
+ const hit = this.cache?.get(ip);
251
+ if (hit !== undefined) {
252
+ out.set(ip, hit);
253
+ continue;
254
+ }
255
+ if (this.cache === null) {
256
+ pending.push(ip);
257
+ continue;
258
+ }
259
+ shared.push([ip, this.cache.fetch(ip, {
260
+ context: () => {
261
+ const landing = Promise.withResolvers();
262
+ led.set(ip, landing);
263
+ pending.push(ip);
264
+ return landing.promise;
265
+ },
266
+ })]);
267
+ }
268
+ // A per-call concurrency gets its own limiter; without one the call
269
+ // would share the instance's budget and silently ignore the override.
270
+ const limit = concurrency === undefined ? this.limit : pLimit(concurrency);
271
+ const chunks = [];
272
+ for (let i = 0; i < pending.length; i += BATCH_MAX) {
273
+ chunks.push(pending.slice(i, i + BATCH_MAX));
274
+ }
275
+ await Promise.all([
276
+ ...chunks.map((chunk) => limit(async () => {
277
+ for (const [ip, answer] of await this.lookupChunk(chunk, options)) {
278
+ const landing = led.get(ip);
279
+ if (landing === undefined) {
280
+ out.set(ip, answer);
281
+ }
282
+ else if (answer instanceof InternetDataError) {
283
+ landing.reject(answer);
284
+ }
285
+ else {
286
+ landing.resolve(answer);
287
+ }
288
+ }
289
+ })),
290
+ ...shared.map(async ([ip, answer]) => {
291
+ try {
292
+ out.set(ip, (await answer));
293
+ }
294
+ catch (err) {
295
+ out.set(ip, asError(err));
296
+ }
297
+ }),
298
+ ]);
299
+ // Reinstated in input order, under the addresses as passed: chunks
300
+ // settle in completion order, and a caller iterating the map should see
301
+ // what they passed in.
302
+ return new Map(asked.map((ip) => [ip, out.get(unmapped(ip))]));
303
+ }
304
+ // One POST /batch, mapped back onto the addresses it was asked about. A
305
+ // chunk-level failure - the call refused, the transport failing, the
306
+ // retries exhausted - becomes every address's error, exactly as it would
307
+ // have been had each been looked up alone.
308
+ async lookupChunk(chunk, options) {
309
+ const out = new Map();
310
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
311
+ let body;
312
+ try {
313
+ body = await withRetry(options.retries ?? this.retries, async () => {
314
+ const res = await deadline(timeoutMs, (signal) => lookupBatch({
315
+ client: this.client, body: { ips: chunk }, signal: signal,
316
+ }));
317
+ return readable(res, isBatch);
318
+ });
319
+ }
320
+ catch (err) {
321
+ const failure = asError(err);
322
+ for (const ip of chunk) {
323
+ out.set(ip, failure);
324
+ }
325
+ return out;
326
+ }
327
+ // An entry is judged alone: one the client cannot read is that address's
328
+ // error, and the rest of the chunk keeps its answers. Each map is read by
329
+ // its own keys alone, so `__proto__`, `constructor` and `toString` never
330
+ // read the object's prototype as a served answer.
331
+ for (const ip of chunk) {
332
+ const served = Object.hasOwn(body.results, ip) ? body.results[ip] : undefined;
333
+ if (served !== undefined) {
334
+ // Cached by the `fetch()` this batch leads it through.
335
+ out.set(ip, isLookup(served) ? toResult(served) : unreadableEntry(ip));
336
+ continue;
337
+ }
338
+ const failed = Object.hasOwn(body.errors, ip) ? body.errors[ip] : undefined;
339
+ if (failed !== undefined) {
340
+ out.set(ip, isBatchError(failed) ? errorFromEntry(failed) : unreadableEntry(ip));
341
+ continue;
342
+ }
343
+ out.set(ip, new InternetDataError('server_error', `the batch answer did not include ${ip}`, 200));
344
+ }
345
+ return out;
346
+ }
347
+ }
348
+ /**
349
+ * The host the `oauth` calls go to: the apex, since the authorization server is
350
+ * mounted there and not on the API host. `https://api.internetdata.io` is
351
+ * `https://internetdata.io` and `https://api-<env>.internetdata.io` is
352
+ * `https://<env>.internetdata.io`; any other base URL is used as given.
353
+ */
354
+ function apexOf(baseUrl) {
355
+ return baseUrl.replace(/^(https?:\/\/)api(?:-([^./:@]+))?\./i, (_, scheme, env) => (env === undefined ? scheme : `${scheme}${env}.`));
356
+ }
357
+ function unreadableEntry(ip) {
358
+ return new InternetDataError('server_error', `unreadable batch answer for ${ip}, status 200`, 200);
52
359
  }
53
360
  /** The licensed database downloads. Access is granted by contract, not self-serve. */
54
361
  export class DatabaseApi {
@@ -258,10 +565,11 @@ function checkBuild(build) {
258
565
  * The key without the blanks around it, and no key at all for blanks alone,
259
566
  * which went out as `Authorization: Bearer` (2.5.1, measured 2026-10-10). A
260
567
  * control character inside it is refused here: fetch refuses such a header, so
261
- * every call failed as a retried `network` error with nothing sent.
568
+ * every call failed as a retried `network` error with nothing sent. `null` is no
569
+ * key.
262
570
  */
263
571
  function checkApiKey(apiKey) {
264
- if (apiKey === undefined) {
572
+ if (apiKey === undefined || apiKey === null) {
265
573
  return undefined;
266
574
  }
267
575
  if (typeof apiKey !== 'string') {
@@ -278,18 +586,6 @@ function checkApiKey(apiKey) {
278
586
  }
279
587
  return key === '' ? undefined : key;
280
588
  }
281
- /**
282
- * A retry count p-retry can run, refused where it is set: through 2.7.3 a negative,
283
- * NaN or non-number failed every call with p-retry's own TypeError as a `network`
284
- * error, and a fraction ended a failing call as one too (measured 2026-10-23).
285
- * `Infinity` is p-retry's own unbounded count.
286
- */
287
- function checkRetries(retries) {
288
- if (typeof retries === 'number' && (Number.isInteger(retries) || retries === Infinity) && retries >= 0) {
289
- return retries;
290
- }
291
- throw new InternetDataError('bad_request', `retries must be a whole number from 0, got ${String(retries)}`);
292
- }
293
589
  /**
294
590
  * Sends the key in the `Authorization` header and nowhere else.
295
591
  *