internetdata-web 0.0.0-stage → 1.1.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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +282 -2
  3. package/dist/bogon.d.ts +31 -0
  4. package/dist/bogon.js +214 -0
  5. package/dist/bogons.gen.d.ts +2 -0
  6. package/dist/bogons.gen.js +87 -0
  7. package/dist/client.d.ts +183 -0
  8. package/dist/client.js +446 -0
  9. package/dist/errors.d.ts +66 -0
  10. package/dist/errors.js +185 -0
  11. package/dist/generated/client/client.gen.d.ts +2 -0
  12. package/dist/generated/client/client.gen.js +216 -0
  13. package/dist/generated/client/index.d.ts +10 -0
  14. package/dist/generated/client/index.js +6 -0
  15. package/dist/generated/client/types.gen.d.ts +120 -0
  16. package/dist/generated/client/types.gen.js +2 -0
  17. package/dist/generated/client/utils.gen.d.ts +37 -0
  18. package/dist/generated/client/utils.gen.js +228 -0
  19. package/dist/generated/client.gen.d.ts +12 -0
  20. package/dist/generated/client.gen.js +3 -0
  21. package/dist/generated/core/auth.gen.d.ts +25 -0
  22. package/dist/generated/core/auth.gen.js +14 -0
  23. package/dist/generated/core/bodySerializer.gen.d.ts +25 -0
  24. package/dist/generated/core/bodySerializer.gen.js +57 -0
  25. package/dist/generated/core/params.gen.d.ts +43 -0
  26. package/dist/generated/core/params.gen.js +109 -0
  27. package/dist/generated/core/pathSerializer.gen.d.ts +33 -0
  28. package/dist/generated/core/pathSerializer.gen.js +106 -0
  29. package/dist/generated/core/queryKeySerializer.gen.d.ts +18 -0
  30. package/dist/generated/core/queryKeySerializer.gen.js +92 -0
  31. package/dist/generated/core/serverSentEvents.gen.d.ts +71 -0
  32. package/dist/generated/core/serverSentEvents.gen.js +132 -0
  33. package/dist/generated/core/types.gen.d.ts +83 -0
  34. package/dist/generated/core/types.gen.js +2 -0
  35. package/dist/generated/core/utils.gen.d.ts +19 -0
  36. package/dist/generated/core/utils.gen.js +87 -0
  37. package/dist/generated/index.d.ts +2 -0
  38. package/dist/generated/index.js +2 -0
  39. package/dist/generated/sdk.gen.d.ts +117 -0
  40. package/dist/generated/sdk.gen.js +251 -0
  41. package/dist/generated/types.gen.d.ts +1527 -0
  42. package/dist/generated/types.gen.js +2 -0
  43. package/dist/index.d.ts +9 -0
  44. package/dist/index.js +4 -0
  45. package/dist/oauth.d.ts +119 -0
  46. package/dist/oauth.js +247 -0
  47. package/dist/shapes.d.ts +68 -0
  48. package/dist/shapes.js +284 -0
  49. package/dist/store.d.ts +39 -0
  50. package/dist/store.js +64 -0
  51. package/dist/transport.d.ts +51 -0
  52. package/dist/transport.js +147 -0
  53. package/dist/types.d.ts +115 -0
  54. package/dist/types.js +46 -0
  55. package/package.json +65 -3
package/dist/shapes.js ADDED
@@ -0,0 +1,284 @@
1
+ // The members each answer must carry before the client hands it back: every one
2
+ // the spec requires and never sends as null. The tests read them against the
3
+ // generated types, so a member the spec adds fails the suite until it is here.
4
+ import { hasMembers } from './transport.js';
5
+ export const LOOKUP_MEMBERS = [
6
+ 'ip', 'is_bogon', 'is_tor', 'is_relay', 'is_anycast', 'is_carrier', 'is_satellite', 'is_ssh', 'is_smtp',
7
+ 'is_web', 'is_dns_resolver', 'is_bittorrent', 'tor', 'relay', 'location', 'asn', 'company', 'hostname',
8
+ 'abuse',
9
+ ];
10
+ export const WEB_DETAIL_MEMBERS = [
11
+ 'port', 'tls_ok', 'session_ok', 'status_code', 'server', 'location', 'title', 'cert_subject_cn',
12
+ 'cert_subject_o', 'cert_issuer_dn', 'cert_browser_trusted', 'tls_version', 'first_seen', 'last_seen',
13
+ ];
14
+ export const LOCATION_MEMBERS = [
15
+ 'continent', 'continent_name', 'country', 'country_name', 'timezone', 'currency_code', 'currency_name',
16
+ 'currency_symbol', 'flag_emoji', 'flag_unicode',
17
+ ];
18
+ export const ASN_MEMBERS = ['asn', 'name', 'domain', 'type', 'prefix'];
19
+ export const COMPANY_MEMBERS = ['name', 'domain'];
20
+ export const ABUSE_CONTACT_MEMBERS = ['email'];
21
+ export const WHOIS_MEMBERS = [
22
+ 'id', 'name', 'org', 'country', 'status', 'source', 'domain', 'abuse_email', 'asn',
23
+ ];
24
+ export const RWHOIS_MEMBERS = ['id', 'name', 'country', 'source', 'domain', 'abuse_email'];
25
+ export const HOSTED_DOMAINS_MEMBERS = ['total'];
26
+ export const ASN_LOOKUP_MEMBERS = ['asn', 'name', 'country', 'registry', 'allocated', 'domain'];
27
+ export const ASN_PREFIX_MEMBERS = [
28
+ 'prefix', 'peer_count', 'rpki_status', 'first_seen', 'country', 'size', 'other_origins',
29
+ ];
30
+ export const DOMAIN_LOOKUP_MEMBERS = [
31
+ 'domain', 'is_registered', 'has_a', 'has_aaaa', 'has_mx', 'has_ns', 'has_cname',
32
+ ];
33
+ export const DOMAIN_DNS_MEMBERS = ['a', 'aaaa', 'mx', 'ns', 'cname'];
34
+ export const DNS_ADDRESS_RECORD_MEMBERS = ['ip', 'last_seen'];
35
+ export const DNS_MX_RECORD_MEMBERS = ['priority', 'host', 'last_seen'];
36
+ export const DNS_NS_RECORD_MEMBERS = ['host', 'last_seen'];
37
+ export const DNS_CNAME_RECORD_MEMBERS = ['target', 'last_seen'];
38
+ export const DOMAIN_IP_RANGES_MEMBERS = ['domain', 'redirects_to', 'total', 'ipv4', 'ranges'];
39
+ export const DOMAIN_IP_RANGE_MEMBERS = ['range', 'name', 'country'];
40
+ export const BATCH_MEMBERS = ['results', 'errors'];
41
+ export const BATCH_ERROR_MEMBERS = ['status', 'error'];
42
+ export const ENTITLEMENT_MEMBERS = ['org_id', 'apikey', 'plan', 'usage'];
43
+ export const ENTITLEMENT_APIKEY_MEMBERS = ['id', 'allowed_cidrs'];
44
+ export const ENTITLEMENT_PLAN_MEMBERS = ['key', 'tier'];
45
+ export const ENTITLEMENT_USAGE_MEMBERS = ['requests', 'quota', 'window_start', 'window_end'];
46
+ const FLAG = 'boolean';
47
+ export const LOOKUP_TYPES = {
48
+ ip: 'string', is_bogon: FLAG, is_vpn: FLAG, is_tor: FLAG, is_relay: FLAG, is_resproxy: FLAG, is_dcproxy: FLAG,
49
+ is_mobproxy: FLAG, is_pubproxy: FLAG, is_hosting: FLAG, is_cdn: FLAG, is_anycast: FLAG, is_carrier: FLAG,
50
+ is_satellite: FLAG, is_ssh: FLAG, is_smtp: FLAG, is_web: FLAG, is_dns_resolver: FLAG, is_bittorrent: FLAG,
51
+ vpn: 'object', tor: 'object', relay: 'object', resproxy: 'object', dcproxy: 'object', mobproxy: 'object',
52
+ pubproxy: 'object', hosting: 'object', cdn: 'object', carrier: 'object', satellite: 'object', ssh: 'object',
53
+ smtp: 'object', web: 'array', dns_resolver: 'object', bittorrent: 'object', location: 'object', asn: 'object',
54
+ company: 'object', hostname: 'string', abuse: 'object', whois: 'object', rwhois: 'object',
55
+ hosted_domains: 'object', trial_expired: FLAG,
56
+ };
57
+ export const CLASS_DETAIL_TYPES = {
58
+ provider: 'string', provider_name: 'string', confidence: 'string', last_seen: 'string',
59
+ };
60
+ export const PROXY_DETAIL_TYPES = {
61
+ provider: 'string', provider_name: 'string', first_seen: 'string', last_seen: 'string', hits: 'integer',
62
+ hits_days_pct: 'integer', providers_num: 'integer',
63
+ };
64
+ export const PUBPROXY_DETAIL_TYPES = {
65
+ entry: 'boolean', exit: 'boolean', protocols: 'array', num_ports: 'integer', num_proxies: 'integer',
66
+ last_seen: 'string', last_usable: 'string',
67
+ };
68
+ export const CARRIER_DETAIL_TYPES = {
69
+ name: 'string', mcc: 'string', mnc: 'string', country: 'string', confidence: 'string',
70
+ };
71
+ export const SATELLITE_DETAIL_TYPES = {
72
+ provider: 'string', provider_name: 'string', orbit: 'string', segment: 'string', country: 'string',
73
+ asn: 'integer', confidence: 'string',
74
+ };
75
+ export const SSH_DETAIL_TYPES = {
76
+ port: 'integer', banner: 'string', host_key_fp: 'string', session_ok: 'boolean', first_seen: 'string',
77
+ last_seen: 'string',
78
+ };
79
+ export const SMTP_DETAIL_TYPES = {
80
+ port: 'integer', banner: 'string', session_ok: 'boolean', first_seen: 'string', last_seen: 'string',
81
+ };
82
+ export const WEB_DETAIL_TYPES = {
83
+ port: 'integer', tls_ok: 'boolean', session_ok: 'boolean', status_code: 'integer', server: 'string',
84
+ location: 'string', title: 'string', cert_subject_cn: 'string', cert_subject_o: 'string',
85
+ cert_issuer_dn: 'string', cert_browser_trusted: 'boolean', tls_version: 'string', first_seen: 'string',
86
+ last_seen: 'string',
87
+ };
88
+ export const DNS_RESOLVER_DETAIL_TYPES = {
89
+ port: 'integer', recursion_available: 'boolean', rcode: 'integer', answer_correct: 'boolean',
90
+ first_seen: 'string', last_seen: 'string',
91
+ };
92
+ export const BITTORRENT_DETAIL_TYPES = {
93
+ verified: 'boolean', id_matches_ip: 'boolean', first_seen: 'string', last_seen: 'string',
94
+ last_reachable: 'string', days_seen: 'integer', num_ports: 'integer', peak_num_ports: 'integer',
95
+ indexer: 'boolean', clients: 'array',
96
+ };
97
+ export const LOCATION_TYPES = {
98
+ ...Object.fromEntries(LOCATION_MEMBERS.map((m) => [m, 'string'])),
99
+ region: 'string', region_code: 'string', city: 'string', postal_code: 'string', latitude: 'number',
100
+ longitude: 'number', accuracy_radius: 'integer', geoname_id: 'string', dma_code: 'string',
101
+ last_changed: 'string',
102
+ };
103
+ export const ASN_TYPES = {
104
+ asn: 'integer', name: 'string', domain: 'string', type: 'string', prefix: 'string', country: 'string',
105
+ rpki_status: 'string',
106
+ };
107
+ export const COMPANY_TYPES = {
108
+ name: 'string', domain: 'string', type: 'string', country: 'string',
109
+ };
110
+ export const ABUSE_CONTACT_TYPES = {
111
+ email: 'string', name: 'string', phone: 'string', address: 'string', country: 'string', network: 'string',
112
+ validated: 'boolean', unvalidated_since: 'string',
113
+ };
114
+ export const WHOIS_TYPES = {
115
+ id: 'string', name: 'string', org: 'string', country: 'string', status: 'string', source: 'string',
116
+ domain: 'string', abuse_email: 'string', asn: 'integer',
117
+ };
118
+ export const RWHOIS_TYPES = {
119
+ id: 'string', name: 'string', country: 'string', source: 'string', domain: 'string', abuse_email: 'string',
120
+ };
121
+ export const HOSTED_DOMAINS_TYPES = { total: 'integer', domains: 'array' };
122
+ export const ASN_LOOKUP_TYPES = {
123
+ asn: 'integer', name: 'string', country: 'string', registry: 'string', allocated: 'string', domain: 'string',
124
+ type: 'string', num_ips: 'integer', num_prefixes4: 'integer', num_prefixes6: 'integer', rpki_valid: 'integer',
125
+ rpki_invalid: 'integer', rpki_not_found: 'integer', whois: 'object', prefixes: 'array', trial_expired: FLAG,
126
+ };
127
+ export const ASN_PREFIX_TYPES = {
128
+ prefix: 'string', peer_count: 'integer', rpki_status: 'string', first_seen: 'string', country: 'string',
129
+ size: 'integer', other_origins: 'array',
130
+ };
131
+ export const DOMAIN_LOOKUP_TYPES = {
132
+ domain: 'string', is_registered: FLAG, is_disposable: FLAG, has_a: FLAG, has_aaaa: FLAG, has_mx: FLAG,
133
+ has_ns: FLAG, has_cname: FLAG, dns: 'object', ip_ranges: 'object', disposable: 'object', trial_expired: FLAG,
134
+ };
135
+ export const DOMAIN_DNS_TYPES = {
136
+ a: 'array', aaaa: 'array', mx: 'array', ns: 'array', cname: 'array',
137
+ };
138
+ export const DNS_ADDRESS_RECORD_TYPES = { ip: 'string', last_seen: 'string' };
139
+ export const DNS_MX_RECORD_TYPES = {
140
+ priority: 'integer', host: 'string', last_seen: 'string',
141
+ };
142
+ export const DNS_NS_RECORD_TYPES = { host: 'string', last_seen: 'string' };
143
+ export const DNS_CNAME_RECORD_TYPES = { target: 'string', last_seen: 'string' };
144
+ export const DOMAIN_IP_RANGES_TYPES = {
145
+ domain: 'string', redirects_to: 'string', total: 'integer', ipv4: 'integer', ranges: 'array',
146
+ };
147
+ export const DOMAIN_IP_RANGE_TYPES = {
148
+ range: 'string', name: 'string', country: 'string',
149
+ };
150
+ export const DISPOSABLE_DETAIL_TYPES = {
151
+ confidence: 'string', providers: 'array', first_seen: 'string', last_seen: 'string',
152
+ };
153
+ export const BATCH_ERROR_TYPES = { status: 'integer', error: 'string' };
154
+ export const ENTITLEMENT_TYPES = {
155
+ org_id: 'string', apikey: 'object', plan: 'object', usage: 'object',
156
+ };
157
+ export const ENTITLEMENT_APIKEY_TYPES = {
158
+ id: 'string', expires: 'date-time', allowed_cidrs: 'array',
159
+ };
160
+ export const ENTITLEMENT_PLAN_TYPES = { key: 'string', tier: 'string' };
161
+ export const ENTITLEMENT_USAGE_TYPES = {
162
+ requests: 'integer', quota: 'integer', hard_limit: 'integer', window_start: 'date-time',
163
+ window_end: 'date-time',
164
+ };
165
+ function isObject(value) {
166
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
167
+ }
168
+ function isKind(value, kind) {
169
+ switch (kind) {
170
+ case 'string': return typeof value === 'string';
171
+ case 'integer': return Number.isInteger(value);
172
+ case 'number': return typeof value === 'number' && Number.isFinite(value);
173
+ case 'boolean': return typeof value === 'boolean';
174
+ case 'object': return isObject(value);
175
+ case 'array': return Array.isArray(value);
176
+ case 'date': return typeof value === 'string' && isFullDate(value);
177
+ case 'date-time': return typeof value === 'string' && isDateTime(value);
178
+ }
179
+ }
180
+ const FULL_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
181
+ const DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))$/;
182
+ /** RFC 3339's `full-date`, naming a day its month has. */
183
+ function isFullDate(value) {
184
+ const m = FULL_DATE.exec(value);
185
+ return m !== null && isDay(m[1], m[2], m[3]);
186
+ }
187
+ /**
188
+ * RFC 3339's `date-time`, its lowercase `t` and `z` included, with an hour below 24,
189
+ * a minute and a second below 60 and an offset of at most 23:59.
190
+ */
191
+ function isDateTime(value) {
192
+ const m = DATE_TIME.exec(value);
193
+ return m !== null && isDay(m[1], m[2], m[3])
194
+ && Number(m[4]) < 24 && Number(m[5]) < 60 && Number(m[6]) < 60
195
+ && (m[7] === undefined || (Number(m[7]) < 24 && Number(m[8]) < 60));
196
+ }
197
+ // setUTCFullYear rather than Date.UTC, which reads a year below 100 as 19xx.
198
+ function isDay(year, month, day) {
199
+ const date = new Date(0);
200
+ date.setUTCFullYear(Number(year), Number(month) - 1, Number(day));
201
+ return date.getUTCFullYear() === Number(year) && date.getUTCMonth() === Number(month) - 1
202
+ && date.getUTCDate() === Number(day);
203
+ }
204
+ function typed(value, required, types) {
205
+ return hasMembers(value, required) && Object.entries(types).every(([member, kind]) => {
206
+ const v = value[member];
207
+ return v === undefined || v === null ? !required.includes(member) : isKind(v, kind);
208
+ });
209
+ }
210
+ function every(value, valid) {
211
+ return Array.isArray(value) && value.every(valid);
212
+ }
213
+ function isString(value) {
214
+ return typeof value === 'string';
215
+ }
216
+ function values(value, valid) {
217
+ return isObject(value) && Object.values(value).every(valid);
218
+ }
219
+ /** An optional member: absent or null, or valid. */
220
+ function optional(value, valid) {
221
+ return value === undefined || value === null || valid(value);
222
+ }
223
+ function lists(value, member, valid) {
224
+ return optional(value[member], (list) => every(list, valid));
225
+ }
226
+ const DETAILS = [
227
+ ['vpn', CLASS_DETAIL_TYPES], ['tor', CLASS_DETAIL_TYPES], ['relay', CLASS_DETAIL_TYPES],
228
+ ['resproxy', PROXY_DETAIL_TYPES], ['dcproxy', PROXY_DETAIL_TYPES], ['mobproxy', PROXY_DETAIL_TYPES],
229
+ ['pubproxy', PUBPROXY_DETAIL_TYPES], ['hosting', CLASS_DETAIL_TYPES], ['cdn', CLASS_DETAIL_TYPES],
230
+ ['carrier', CARRIER_DETAIL_TYPES], ['satellite', SATELLITE_DETAIL_TYPES], ['ssh', SSH_DETAIL_TYPES],
231
+ ['smtp', SMTP_DETAIL_TYPES], ['dns_resolver', DNS_RESOLVER_DETAIL_TYPES],
232
+ ['bittorrent', BITTORRENT_DETAIL_TYPES],
233
+ ];
234
+ // Required where the lookup itself requires them, and optional otherwise.
235
+ const SHARED = [
236
+ ['location', LOCATION_MEMBERS, LOCATION_TYPES],
237
+ ['asn', ASN_MEMBERS, ASN_TYPES],
238
+ ['company', COMPANY_MEMBERS, COMPANY_TYPES],
239
+ ['abuse', ABUSE_CONTACT_MEMBERS, ABUSE_CONTACT_TYPES],
240
+ ['whois', WHOIS_MEMBERS, WHOIS_TYPES],
241
+ ['rwhois', RWHOIS_MEMBERS, RWHOIS_TYPES],
242
+ ['hosted_domains', HOSTED_DOMAINS_MEMBERS, HOSTED_DOMAINS_TYPES],
243
+ ];
244
+ export function isLookup(data) {
245
+ return typed(data, LOOKUP_MEMBERS, LOOKUP_TYPES)
246
+ && DETAILS.every(([member, types]) => optional(data[member], (detail) => typed(detail, [], types)))
247
+ && optional(data['pubproxy'], (pubproxy) => lists(pubproxy, 'protocols', isString))
248
+ && optional(data['bittorrent'], (bittorrent) => lists(bittorrent, 'clients', isString))
249
+ && optional(data['web'], (web) => every(web, (row) => typed(row, WEB_DETAIL_MEMBERS, WEB_DETAIL_TYPES)))
250
+ && optional(data['hosted_domains'], (hosted) => lists(hosted, 'domains', isString))
251
+ && SHARED.every(([member, required, types]) => optional(data[member], (object) => typed(object, required, types)));
252
+ }
253
+ export function isAsnLookup(data) {
254
+ return typed(data, ASN_LOOKUP_MEMBERS, ASN_LOOKUP_TYPES)
255
+ && optional(data['whois'], (whois) => values(whois, isString))
256
+ && lists(data, 'prefixes', (prefix) => typed(prefix, ASN_PREFIX_MEMBERS, ASN_PREFIX_TYPES)
257
+ && every(prefix['other_origins'], Number.isInteger));
258
+ }
259
+ export function isDomainLookup(data) {
260
+ return typed(data, DOMAIN_LOOKUP_MEMBERS, DOMAIN_LOOKUP_TYPES)
261
+ && optional(data['dns'], (dns) => typed(dns, DOMAIN_DNS_MEMBERS, DOMAIN_DNS_TYPES)
262
+ && every(dns['a'], (r) => typed(r, DNS_ADDRESS_RECORD_MEMBERS, DNS_ADDRESS_RECORD_TYPES))
263
+ && every(dns['aaaa'], (r) => typed(r, DNS_ADDRESS_RECORD_MEMBERS, DNS_ADDRESS_RECORD_TYPES))
264
+ && every(dns['mx'], (r) => typed(r, DNS_MX_RECORD_MEMBERS, DNS_MX_RECORD_TYPES))
265
+ && every(dns['ns'], (r) => typed(r, DNS_NS_RECORD_MEMBERS, DNS_NS_RECORD_TYPES))
266
+ && every(dns['cname'], (r) => typed(r, DNS_CNAME_RECORD_MEMBERS, DNS_CNAME_RECORD_TYPES)))
267
+ && optional(data['ip_ranges'], (ranges) => typed(ranges, DOMAIN_IP_RANGES_MEMBERS, DOMAIN_IP_RANGES_TYPES) && every(ranges['ranges'], (r) => typed(r, DOMAIN_IP_RANGE_MEMBERS, DOMAIN_IP_RANGE_TYPES)))
268
+ && optional(data['disposable'], (d) => typed(d, [], DISPOSABLE_DETAIL_TYPES)
269
+ && lists(d, 'providers', isString));
270
+ }
271
+ /** Both maps present. An entry in either is judged on its own, as that address's answer. */
272
+ export function isBatch(data) {
273
+ return hasMembers(data, BATCH_MEMBERS) && isObject(data['results']) && isObject(data['errors']);
274
+ }
275
+ export function isBatchError(entry) {
276
+ return typed(entry, BATCH_ERROR_MEMBERS, BATCH_ERROR_TYPES);
277
+ }
278
+ export function isEntitlement(data) {
279
+ return typed(data, ENTITLEMENT_MEMBERS, ENTITLEMENT_TYPES)
280
+ && typed(data['apikey'], ENTITLEMENT_APIKEY_MEMBERS, ENTITLEMENT_APIKEY_TYPES)
281
+ && every(data['apikey']['allowed_cidrs'], isString)
282
+ && typed(data['plan'], ENTITLEMENT_PLAN_MEMBERS, ENTITLEMENT_PLAN_TYPES)
283
+ && typed(data['usage'], ENTITLEMENT_USAGE_MEMBERS, ENTITLEMENT_USAGE_TYPES);
284
+ }
@@ -0,0 +1,39 @@
1
+ import { type Result } from './types.js';
2
+ /**
3
+ * A persistent tier behind the client's in-memory cache, for answers that should
4
+ * outlive the client: a page reload, or an extension's service worker, which the
5
+ * browser stops once it sits idle and starts again on the next event.
6
+ *
7
+ * `key` is the address with a hash of the client's API key and base URL in front of
8
+ * it, so clients holding different keys, and so entitled to different fields, can
9
+ * share one store without ever reading each other's answers. `set` is handed how long
10
+ * the answer stays fresh; dropping it once that has passed is the store's job.
11
+ */
12
+ export interface CacheStore {
13
+ get(key: string): Promise<Result | undefined> | Result | undefined;
14
+ set(key: string, result: Result, ttlMs: number): Promise<void> | void;
15
+ }
16
+ /**
17
+ * The client's side of a `CacheStore`. A store is a cache, never a source of
18
+ * errors: one that throws or rejects reads as a miss and a write that fails is
19
+ * dropped, so either costs a request and never an answer. An entry it hands back
20
+ * is read the way an answer off the wire is, so one that is not a lookup answer
21
+ * is a miss too.
22
+ */
23
+ export declare class StoreTier {
24
+ private readonly store;
25
+ private readonly scope;
26
+ private readonly ttlMs;
27
+ constructor(store: CacheStore, scope: string, ttlMs: number);
28
+ get(ip: string): Promise<Result | undefined>;
29
+ set(ip: string, result: Result): Promise<void>;
30
+ private keyFor;
31
+ }
32
+ /**
33
+ * What tells one client's entries from another's: FNV-1a over the base URL and the
34
+ * key, as 16 hex digits. It tells keys apart and keeps the key itself out of the
35
+ * store; it is not a way to keep a key secret.
36
+ */
37
+ export declare function storeScope(baseUrl: string, apiKey: string | undefined): string;
38
+ /** A store is two functions; anything else is refused where the client is built. */
39
+ export declare function isCacheStore(store: unknown): store is CacheStore;
package/dist/store.js ADDED
@@ -0,0 +1,64 @@
1
+ import { isLookup } from './shapes.js';
2
+ import { toResult } from './types.js';
3
+ /**
4
+ * The client's side of a `CacheStore`. A store is a cache, never a source of
5
+ * errors: one that throws or rejects reads as a miss and a write that fails is
6
+ * dropped, so either costs a request and never an answer. An entry it hands back
7
+ * is read the way an answer off the wire is, so one that is not a lookup answer
8
+ * is a miss too.
9
+ */
10
+ export class StoreTier {
11
+ store;
12
+ scope;
13
+ ttlMs;
14
+ constructor(store, scope, ttlMs) {
15
+ this.store = store;
16
+ this.scope = scope;
17
+ this.ttlMs = ttlMs;
18
+ }
19
+ async get(ip) {
20
+ let stored;
21
+ try {
22
+ stored = await this.store.get(this.keyFor(ip));
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ if (typeof stored !== 'object' || stored === null) {
28
+ return undefined;
29
+ }
30
+ const raw = stored.raw;
31
+ return isLookup(raw) ? toResult(raw) : undefined;
32
+ }
33
+ async set(ip, result) {
34
+ try {
35
+ await this.store.set(this.keyFor(ip), result, this.ttlMs);
36
+ }
37
+ catch {
38
+ // Costs a request on the next miss, nothing more.
39
+ }
40
+ }
41
+ keyFor(ip) {
42
+ return `${this.scope}:${ip}`;
43
+ }
44
+ }
45
+ const FNV_OFFSET = 0xcbf29ce484222325n;
46
+ const FNV_PRIME = 0x100000001b3n;
47
+ const MASK_64 = (1n << 64n) - 1n;
48
+ /**
49
+ * What tells one client's entries from another's: FNV-1a over the base URL and the
50
+ * key, as 16 hex digits. It tells keys apart and keeps the key itself out of the
51
+ * store; it is not a way to keep a key secret.
52
+ */
53
+ export function storeScope(baseUrl, apiKey) {
54
+ let hash = FNV_OFFSET;
55
+ for (const byte of new TextEncoder().encode(`${baseUrl}\n${apiKey ?? ''}`)) {
56
+ hash = ((hash ^ BigInt(byte)) * FNV_PRIME) & MASK_64;
57
+ }
58
+ return hash.toString(16).padStart(16, '0');
59
+ }
60
+ /** A store is two functions; anything else is refused where the client is built. */
61
+ export function isCacheStore(store) {
62
+ return typeof store === 'object' && store !== null
63
+ && typeof store.get === 'function' && typeof store.set === 'function';
64
+ }
@@ -0,0 +1,51 @@
1
+ import { InternetDataError } from './errors.js';
2
+ export interface Res {
3
+ data?: unknown;
4
+ error?: unknown;
5
+ response?: Response;
6
+ }
7
+ export declare function unwrap<T>(res: Res): T;
8
+ /**
9
+ * The request never got an answer: offline, refused by the browser (a CORS
10
+ * failure, an extension blocking it, a page's Content-Security-Policy), or cut
11
+ * off. Browsers say little about which, and what they say is kept.
12
+ */
13
+ export declare function noResponse(cause: unknown): InternetDataError;
14
+ /**
15
+ * A 2xx the call cannot read as its answer: a proxy's HTML page, a cut-off,
16
+ * empty or non-object body, or an object without what the call returns. The
17
+ * server's fault, so a retried `server_error` carrying the status.
18
+ */
19
+ export declare function readable<T>(res: Res, valid: (data: unknown) => boolean): T;
20
+ /** An object holding every member named, none of them missing. */
21
+ export declare function hasMembers(value: unknown, members: readonly string[]): value is Record<string, unknown>;
22
+ export declare const MAX_TIMEOUT_MS: number;
23
+ /**
24
+ * Refuses a timeout no attempt can meet where it is set, on the client or the
25
+ * call, rather than failing every call as a timeout 1 ms in.
26
+ */
27
+ export declare function checkTimeout(timeoutMs: number | undefined): number | undefined;
28
+ /**
29
+ * A retry count p-retry can run, refused where it is set, on the client or the
30
+ * call: p-retry checks one only inside the call, so a negative, NaN or
31
+ * non-number would fail every call with its own TypeError, and a fraction would
32
+ * end a failing call as one. `Infinity` is p-retry's own unbounded count, and
33
+ * `null` reads as unset.
34
+ */
35
+ export declare function checkRetries(retries: number | null | undefined): number | undefined;
36
+ /**
37
+ * How many batch requests may be in flight, refused where it is set, on the
38
+ * client or the call, where p-limit would throw its own bare TypeError.
39
+ * `Infinity` is p-limit's own unbounded count, and `null` reads as unset.
40
+ */
41
+ export declare function checkConcurrency(concurrency: number | null | undefined): number | undefined;
42
+ /**
43
+ * Bound one attempt, and report an expiry as our own error rather than the
44
+ * runtime's `TimeoutError`, whose message says nothing about which call gave up.
45
+ *
46
+ * The signal is built per call, so a retried request gets a fresh budget: the
47
+ * bound is per attempt.
48
+ */
49
+ export declare function deadline<T>(timeoutMs: number, fn: (signal: AbortSignal) => Promise<T>): Promise<T>;
50
+ export declare function withRetry<T>(retries: number, fn: () => Promise<T>): Promise<T>;
51
+ export declare function asError(err: unknown): InternetDataError;
@@ -0,0 +1,147 @@
1
+ import pRetry from 'p-retry';
2
+ import { errorFromResponse, InternetDataError, messageFromBody } from './errors.js';
3
+ export function unwrap(res) {
4
+ if (res.response === undefined) {
5
+ throw noResponse(res.error);
6
+ }
7
+ if (!res.response.ok) {
8
+ throw errorFromResponse(res.response.status, res.response.headers, messageFromBody(res.error ?? res.data));
9
+ }
10
+ return res.data;
11
+ }
12
+ /**
13
+ * The request never got an answer: offline, refused by the browser (a CORS
14
+ * failure, an extension blocking it, a page's Content-Security-Policy), or cut
15
+ * off. Browsers say little about which, and what they say is kept.
16
+ */
17
+ export function noResponse(cause) {
18
+ const detail = cause instanceof Error && cause.message !== '' ? `: ${cause.message}` : '';
19
+ return new InternetDataError('network', `no response from the API${detail}`);
20
+ }
21
+ /**
22
+ * A 2xx the call cannot read as its answer: a proxy's HTML page, a cut-off,
23
+ * empty or non-object body, or an object without what the call returns. The
24
+ * server's fault, so a retried `server_error` carrying the status.
25
+ */
26
+ export function readable(res, valid) {
27
+ const data = unwrap(res);
28
+ if (!valid(data)) {
29
+ const status = res.response.status;
30
+ throw new InternetDataError('server_error', `unreadable answer from the API, status ${status}`, status);
31
+ }
32
+ return data;
33
+ }
34
+ /** An object holding every member named, none of them missing. */
35
+ export function hasMembers(value, members) {
36
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
37
+ && members.every((member) => value[member] !== undefined);
38
+ }
39
+ // The longest delay setTimeout runs as asked, in every browser as in Node. It runs
40
+ // anything longer, and anything that is not a positive number, as at once.
41
+ export const MAX_TIMEOUT_MS = 2 ** 31 - 1;
42
+ /**
43
+ * Refuses a timeout no attempt can meet where it is set, on the client or the
44
+ * call, rather than failing every call as a timeout 1 ms in.
45
+ */
46
+ export function checkTimeout(timeoutMs) {
47
+ if (timeoutMs !== undefined
48
+ && !(typeof timeoutMs === 'number' && timeoutMs >= 1 && timeoutMs <= MAX_TIMEOUT_MS)) {
49
+ throw new InternetDataError('bad_request', `timeoutMs must be from 1 to ${MAX_TIMEOUT_MS} milliseconds, got ${String(timeoutMs)}`);
50
+ }
51
+ return timeoutMs;
52
+ }
53
+ /**
54
+ * A retry count p-retry can run, refused where it is set, on the client or the
55
+ * call: p-retry checks one only inside the call, so a negative, NaN or
56
+ * non-number would fail every call with its own TypeError, and a fraction would
57
+ * end a failing call as one. `Infinity` is p-retry's own unbounded count, and
58
+ * `null` reads as unset.
59
+ */
60
+ export function checkRetries(retries) {
61
+ if (retries === undefined || retries === null) {
62
+ return undefined;
63
+ }
64
+ if (!(typeof retries === 'number' && retries >= 0
65
+ && (Number.isInteger(retries) || retries === Infinity))) {
66
+ throw new InternetDataError('bad_request', `retries must be a whole number from 0, got ${String(retries)}`);
67
+ }
68
+ return retries;
69
+ }
70
+ /**
71
+ * How many batch requests may be in flight, refused where it is set, on the
72
+ * client or the call, where p-limit would throw its own bare TypeError.
73
+ * `Infinity` is p-limit's own unbounded count, and `null` reads as unset.
74
+ */
75
+ export function checkConcurrency(concurrency) {
76
+ if (concurrency === undefined || concurrency === null) {
77
+ return undefined;
78
+ }
79
+ if (!(typeof concurrency === 'number' && concurrency >= 1
80
+ && (Number.isInteger(concurrency) || concurrency === Infinity))) {
81
+ throw new InternetDataError('bad_request', `concurrency must be a whole number of at least 1, got ${String(concurrency)}`);
82
+ }
83
+ return concurrency;
84
+ }
85
+ /**
86
+ * Bound one attempt, and report an expiry as our own error rather than the
87
+ * runtime's `TimeoutError`, whose message says nothing about which call gave up.
88
+ *
89
+ * The signal is built per call, so a retried request gets a fresh budget: the
90
+ * bound is per attempt.
91
+ */
92
+ export async function deadline(timeoutMs, fn) {
93
+ const controller = new AbortController();
94
+ let timer;
95
+ // Raced, not left to the signal alone: aborting releases the connection, but
96
+ // only a transport that HONORS the signal then settles, and a substituted
97
+ // `fetch` need not. Clearing the timer stops the losing side rejecting into nothing.
98
+ const expiry = new Promise((_, reject) => {
99
+ timer = setTimeout(() => {
100
+ controller.abort();
101
+ reject(new InternetDataError('network', `request timed out after ${timeoutMs}ms`));
102
+ }, timeoutMs);
103
+ });
104
+ try {
105
+ return await Promise.race([fn(controller.signal), expiry]);
106
+ }
107
+ finally {
108
+ clearTimeout(timer);
109
+ }
110
+ }
111
+ // p-retry owns the backoff schedule; the extra sleep here is what honors a
112
+ // server-supplied Retry-After, which p-retry has no way to know about. A 429
113
+ // carrying that header is the only 429 worth retrying, which is why the wait
114
+ // and the retry decision both key off the same field. One past what setTimeout
115
+ // runs as asked is waited out on the backoff alone, still a throttle.
116
+ export async function withRetry(retries, fn) {
117
+ try {
118
+ return await pRetry(fn, {
119
+ retries: retries,
120
+ shouldRetry: ({ error }) => !(error instanceof InternetDataError) || error.retryable,
121
+ onFailedAttempt: async ({ error, retriesLeft }) => {
122
+ // p-retry runs this hook before it checks retriesLeft, so with no
123
+ // retry left a wait here would only delay the failure.
124
+ if (retriesLeft <= 0) {
125
+ return;
126
+ }
127
+ const seconds = error instanceof InternetDataError ? error.retryAfterSeconds : undefined;
128
+ if (seconds !== undefined && seconds > 0 && seconds * 1000 <= MAX_TIMEOUT_MS) {
129
+ await new Promise((r) => setTimeout(r, seconds * 1000));
130
+ }
131
+ },
132
+ });
133
+ }
134
+ catch (err) {
135
+ throw asError(err);
136
+ }
137
+ }
138
+ export function asError(err) {
139
+ if (err instanceof InternetDataError) {
140
+ return err;
141
+ }
142
+ const cause = err?.cause;
143
+ if (cause instanceof InternetDataError) {
144
+ return cause;
145
+ }
146
+ return new InternetDataError('network', err instanceof Error ? err.message : String(err));
147
+ }