@intellectual-frontiers/net 0.0.0-stage → 0.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.
package/dist/dns.js ADDED
@@ -0,0 +1,381 @@
1
+ // Spec: 0001-net FR-007
2
+ /**
3
+ * Names on the network (commons 0001-net FR-007). `resolveDns` asks for `A`, `AAAA`, `CNAME`, `MX`, `NS`, `TXT` and `SRV`
4
+ * records, with the records in these shapes (`MX` as `{ preference, exchange }`, `TXT` as each record's
5
+ * strings, `SRV` as `{ priority, weight, port, target }`), and answers with a `Result` whose error says whether the name does not exist,
6
+ * has no such record, or could not be asked: a name that does not resolve is an expected outcome, not an exception.
7
+ *
8
+ * The question is asked here, over `node:dgram` (and `node:net` where the answer is too long for UDP), not through `node:dns`: the two
9
+ * runtimes' `node:dns` can disagree on exactly what this must tell apart (Bun reports a name without the record as one that does not exist),
10
+ * so one small stub resolver (RFC 1035, with EDNS0
11
+ * for answers up to 1232 bytes over UDP) gives the same answer everywhere. The servers asked are the system's (`node:dns`'s `getServers`,
12
+ * which reads `/etc/resolv.conf` or Windows's settings) or the one given; each is tried twice, for two seconds each time.
13
+ *
14
+ * Names in records come without the trailing dot (`mail.example.com`, as Node gives them). The
15
+ * DNS is asked directly, so the hosts file (`localhost`) is not read.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import { resolveDns } from "./dns.ts";
20
+ * const r = await resolveDns("example.com", "MX");
21
+ * if (r.kind === "ok") for (const mx of r.value) console.log(mx.preference, mx.exchange);
22
+ * else if (r.error.kind === "not-found") console.log("no such domain");
23
+ * ```
24
+ *
25
+ * @module
26
+ */
27
+ import { getServers } from "node:dns";
28
+ import * as dgram from "node:dgram";
29
+ import * as net from "node:net";
30
+ import { absurd, err, ok } from "@intellectual-frontiers/core";
31
+ const TYPE_CODE = { A: 1, NS: 2, CNAME: 5, MX: 15, TXT: 16, AAAA: 28, SRV: 33 };
32
+ const CLASS_IN = 1;
33
+ const OPT = 41;
34
+ const UDP_SIZE = 1232;
35
+ const TRY_MS = 2000;
36
+ const TRIES = 2;
37
+ const RCODE = { 1: "EFORMERR", 2: "ESERVFAIL", 4: "ENOTIMP", 5: "EREFUSED" };
38
+ /** A failure that ends the whole query (the caller gave up), as opposed to one where the next try or server may help. */
39
+ class Stop extends Error {
40
+ code;
41
+ constructor(code, message) {
42
+ super(message);
43
+ this.code = code;
44
+ }
45
+ }
46
+ function u16(n) {
47
+ return [(n >> 8) & 0xff, n & 0xff];
48
+ }
49
+ function encodeName(name) {
50
+ const trimmed = name.endsWith(".") ? name.slice(0, -1) : name;
51
+ if (trimmed === "")
52
+ return [0];
53
+ const out = [];
54
+ for (const label of trimmed.split(".")) {
55
+ const bytes = new TextEncoder().encode(label);
56
+ if (bytes.length === 0 || bytes.length > 63)
57
+ return undefined;
58
+ out.push(bytes.length, ...bytes);
59
+ }
60
+ out.push(0);
61
+ return out.length > 255 ? undefined : out;
62
+ }
63
+ function query(id, qname, qtype) {
64
+ return Uint8Array.from([
65
+ ...u16(id),
66
+ 0x01,
67
+ 0x00, // a standard query, recursion desired
68
+ ...u16(1),
69
+ ...u16(0),
70
+ ...u16(0),
71
+ ...u16(1), // one question, and one additional record: EDNS0's OPT
72
+ ...qname,
73
+ ...u16(qtype),
74
+ ...u16(CLASS_IN),
75
+ 0, // the root
76
+ ...u16(OPT),
77
+ ...u16(UDP_SIZE),
78
+ 0,
79
+ 0,
80
+ 0,
81
+ 0,
82
+ ...u16(0),
83
+ ]);
84
+ }
85
+ /** A reader of a DNS message that throws `RangeError` past its end. */
86
+ class Message {
87
+ bytes;
88
+ pos = 0;
89
+ constructor(bytes) {
90
+ this.bytes = bytes;
91
+ }
92
+ byte(at = this.pos++) {
93
+ const b = this.bytes[at];
94
+ if (b === undefined)
95
+ throw new RangeError("the answer ends early");
96
+ return b;
97
+ }
98
+ u16() {
99
+ return (this.byte() << 8) | this.byte();
100
+ }
101
+ u32() {
102
+ return ((this.u16() << 16) >>> 0) + this.u16();
103
+ }
104
+ slice(length) {
105
+ if (this.pos + length > this.bytes.length)
106
+ throw new RangeError("the answer ends early");
107
+ const out = this.bytes.subarray(this.pos, this.pos + length);
108
+ this.pos += length;
109
+ return out;
110
+ }
111
+ /** A name, following compression pointers (at most 64 of them, so a loop ends). */
112
+ name() {
113
+ const labels = [];
114
+ let at = this.pos;
115
+ let jumped = false;
116
+ for (let hops = 0; hops < 64;) {
117
+ const len = this.byte(at);
118
+ if (len === 0) {
119
+ if (!jumped)
120
+ this.pos = at + 1;
121
+ return labels.join(".");
122
+ }
123
+ if ((len & 0xc0) === 0xc0) {
124
+ const target = ((len & 0x3f) << 8) | this.byte(at + 1);
125
+ if (!jumped)
126
+ this.pos = at + 2;
127
+ jumped = true;
128
+ at = target;
129
+ hops++;
130
+ continue;
131
+ }
132
+ if ((len & 0xc0) !== 0)
133
+ throw new RangeError("a label type that is not known");
134
+ if (at + 1 + len > this.bytes.length)
135
+ throw new RangeError("the answer ends early");
136
+ labels.push(new TextDecoder().decode(this.bytes.subarray(at + 1, at + 1 + len)));
137
+ at += 1 + len;
138
+ }
139
+ throw new RangeError("a loop of compressed names");
140
+ }
141
+ }
142
+ function ipv6(bytes) {
143
+ const groups = [];
144
+ for (let i = 0; i < 16; i += 2)
145
+ groups.push(((bytes[i] ?? 0) << 8) | (bytes[i + 1] ?? 0));
146
+ // RFC 5952: the longest run of two or more zero groups (the first, on a tie) becomes `::`.
147
+ let best = -1;
148
+ let bestLen = 1;
149
+ for (let i = 0; i < 8;) {
150
+ let j = i;
151
+ while (j < 8 && groups[j] === 0)
152
+ j++;
153
+ if (j - i > bestLen) {
154
+ best = i;
155
+ bestLen = j - i;
156
+ }
157
+ i = j === i ? i + 1 : j;
158
+ }
159
+ const hex = groups.map((g) => g.toString(16));
160
+ if (best < 0)
161
+ return hex.join(":");
162
+ return `${hex.slice(0, best).join(":")}::${hex.slice(best + bestLen).join(":")}`;
163
+ }
164
+ function characterStrings(data) {
165
+ const out = [];
166
+ for (let i = 0; i < data.length;) {
167
+ const len = data[i] ?? 0;
168
+ if (i + 1 + len > data.length)
169
+ throw new RangeError("a TXT string ends early");
170
+ out.push(new TextDecoder().decode(data.subarray(i + 1, i + 1 + len)));
171
+ i += 1 + len;
172
+ }
173
+ return out;
174
+ }
175
+ const PARSE = {
176
+ A: (m, length) => {
177
+ if (length !== 4)
178
+ throw new RangeError("an A record that is not 4 bytes");
179
+ return Array.from(m.slice(4)).join(".");
180
+ },
181
+ AAAA: (m, length) => {
182
+ if (length !== 16)
183
+ throw new RangeError("an AAAA record that is not 16 bytes");
184
+ return ipv6(m.slice(16));
185
+ },
186
+ CNAME: (m) => m.name(),
187
+ NS: (m) => m.name(),
188
+ MX: (m) => ({ preference: m.u16(), exchange: m.name() }),
189
+ TXT: (m, length) => characterStrings(m.slice(length)),
190
+ SRV: (m) => ({ priority: m.u16(), weight: m.u16(), port: m.u16(), target: m.name() }),
191
+ };
192
+ function parseAnswer(bytes, id, qname, type) {
193
+ const m = new Message(bytes);
194
+ if (m.u16() !== id)
195
+ return { kind: "not-ours" };
196
+ const flags = m.u16();
197
+ if ((flags & 0x8000) === 0)
198
+ return { kind: "not-ours" };
199
+ const qd = m.u16();
200
+ const an = m.u16();
201
+ m.u16();
202
+ m.u16();
203
+ for (let i = 0; i < qd; i++) {
204
+ const name = m.name();
205
+ const qtype = m.u16();
206
+ m.u16();
207
+ if (name.toLowerCase() !== qname.toLowerCase() || qtype !== TYPE_CODE[type])
208
+ return { kind: "not-ours" };
209
+ }
210
+ if ((flags & 0x0200) !== 0)
211
+ return { kind: "truncated" };
212
+ const rcode = flags & 0x0f;
213
+ if (rcode === 3)
214
+ return { kind: "nxdomain" };
215
+ if (rcode !== 0)
216
+ return { kind: "rcode", rcode };
217
+ const parse = PARSE[type];
218
+ const records = [];
219
+ for (let i = 0; i < an; i++) {
220
+ m.name();
221
+ const rtype = m.u16();
222
+ const rclass = m.u16();
223
+ m.u32();
224
+ const length = m.u16();
225
+ const end = m.pos + length;
226
+ if (end > bytes.length)
227
+ throw new RangeError("the answer ends early");
228
+ if (rtype === TYPE_CODE[type] && rclass === CLASS_IN)
229
+ records.push(parse(m, length));
230
+ m.pos = end;
231
+ }
232
+ return { kind: "records", records };
233
+ }
234
+ function systemServers() {
235
+ const seen = new Set();
236
+ const out = [];
237
+ for (const s of getServers()) {
238
+ let server;
239
+ const v6 = /^\[(.+)\]:(\d+)$/.exec(s);
240
+ const v4 = /^([\d.]+):(\d+)$/.exec(s);
241
+ if (v6?.[1] !== undefined && v6[2] !== undefined)
242
+ server = { host: v6[1], port: Number(v6[2]) };
243
+ else if (v4?.[1] !== undefined && v4[2] !== undefined)
244
+ server = { host: v4[1], port: Number(v4[2]) };
245
+ else
246
+ server = { host: s, port: 53 };
247
+ const key = `${server.host} ${server.port}`;
248
+ if (seen.has(key) || net.isIP(server.host) === 0)
249
+ continue;
250
+ seen.add(key);
251
+ out.push(server);
252
+ }
253
+ return out;
254
+ }
255
+ function randomId() {
256
+ const b = new Uint16Array(1);
257
+ crypto.getRandomValues(b);
258
+ return b[0] ?? 0;
259
+ }
260
+ /** Wait for `start` to settle, or for the try's time, or for the signal; `cleanup` runs once whatever happens. */
261
+ function attempt(signal, start) {
262
+ return new Promise((resolve, reject) => {
263
+ let cleanup = () => undefined;
264
+ let done = false;
265
+ const finish = (f) => {
266
+ if (done)
267
+ return;
268
+ done = true;
269
+ clearTimeout(timer);
270
+ signal?.removeEventListener("abort", onAbort);
271
+ cleanup();
272
+ f();
273
+ };
274
+ const onAbort = () => finish(() => reject(new Stop("ECANCELLED", "the query was aborted")));
275
+ const timer = setTimeout(() => finish(() => reject(Object.assign(new Error("the server did not answer in time"), { code: "ETIMEOUT" }))), TRY_MS);
276
+ signal?.addEventListener("abort", onAbort, { once: true });
277
+ cleanup = start((a) => finish(() => resolve(a)), (e) => finish(() => reject(e)));
278
+ });
279
+ }
280
+ function askUdp(server, qname, type, signal) {
281
+ const id = randomId();
282
+ const encoded = encodeName(qname) ?? [0];
283
+ return attempt(signal, (settle, fail) => {
284
+ const socket = dgram.createSocket(net.isIPv6(server.host) ? "udp6" : "udp4");
285
+ socket.on("error", fail);
286
+ socket.on("message", (msg, from) => {
287
+ if (from.port !== server.port)
288
+ return;
289
+ try {
290
+ const answer = parseAnswer(msg, id, qname, type);
291
+ if (answer.kind !== "not-ours")
292
+ settle(answer);
293
+ }
294
+ catch (e) {
295
+ fail(Object.assign(new Error(`the answer cannot be read: ${e instanceof Error ? e.message : String(e)}`), { code: "EBADRESP" }));
296
+ }
297
+ });
298
+ socket.send(query(id, encoded, TYPE_CODE[type]), server.port, server.host);
299
+ return () => socket.close();
300
+ });
301
+ }
302
+ function askTcp(server, qname, type, signal) {
303
+ const id = randomId();
304
+ const q = query(id, encodeName(qname) ?? [0], TYPE_CODE[type]);
305
+ return attempt(signal, (settle, fail) => {
306
+ const socket = net.connect({ host: server.host, port: server.port });
307
+ let buffered = new Uint8Array(0);
308
+ socket.on("error", fail);
309
+ socket.on("connect", () => socket.write(Uint8Array.from([...u16(q.length), ...q])));
310
+ socket.on("data", (chunk) => {
311
+ const next = new Uint8Array(buffered.length + chunk.length);
312
+ next.set(buffered);
313
+ next.set(chunk, buffered.length);
314
+ buffered = next;
315
+ if (buffered.length < 2)
316
+ return;
317
+ const length = ((buffered[0] ?? 0) << 8) | (buffered[1] ?? 0);
318
+ if (buffered.length < 2 + length)
319
+ return;
320
+ try {
321
+ const answer = parseAnswer(buffered.subarray(2, 2 + length), id, qname, type);
322
+ if (answer.kind === "not-ours" || answer.kind === "truncated")
323
+ fail(Object.assign(new Error("an answer that is not ours"), { code: "EBADRESP" }));
324
+ else
325
+ settle(answer);
326
+ }
327
+ catch (e) {
328
+ fail(Object.assign(new Error(`the answer cannot be read: ${e instanceof Error ? e.message : String(e)}`), { code: "EBADRESP" }));
329
+ }
330
+ });
331
+ return () => socket.destroy();
332
+ });
333
+ }
334
+ function failure(name, e) {
335
+ const code = typeof e === "object" && e !== null ? Reflect.get(e, "code") : undefined;
336
+ return { kind: "failed", name, code: typeof code === "string" ? code : "", message: e instanceof Error ? e.message : String(e) };
337
+ }
338
+ /** The records of a type for a name, or why there are none. */
339
+ export async function resolveDns(name, type, options = {}) {
340
+ const { signal, nameServer } = options;
341
+ const qname = name.endsWith(".") ? name.slice(0, -1) : name;
342
+ if (signal?.aborted === true)
343
+ return err({ kind: "failed", name, code: "ECANCELLED", message: "the query was aborted" });
344
+ if (encodeName(qname) === undefined)
345
+ return err({ kind: "failed", name, code: "EBADNAME", message: `not a domain name: ${name}` });
346
+ const servers = nameServer === undefined ? systemServers() : [{ host: nameServer.ipAddr, port: nameServer.port ?? 53 }];
347
+ let last = { kind: "failed", name, code: "ENOSERVERS", message: "no DNS server is configured" };
348
+ for (const server of servers) {
349
+ for (let t = 0; t < TRIES; t++) {
350
+ try {
351
+ let answer = await askUdp(server, qname, type, signal);
352
+ if (answer.kind === "truncated")
353
+ answer = await askTcp(server, qname, type, signal);
354
+ switch (answer.kind) {
355
+ case "records":
356
+ return answer.records.length === 0 ? err({ kind: "no-data", name, type }) : ok(answer.records);
357
+ case "nxdomain":
358
+ return err({ kind: "not-found", name });
359
+ case "rcode": {
360
+ const code = RCODE[answer.rcode] ?? `ERCODE${answer.rcode}`;
361
+ last = { kind: "failed", name, code, message: `the server at ${server.host} answered ${code}` };
362
+ t = TRIES; // the next server, not the same one again
363
+ break;
364
+ }
365
+ case "truncated":
366
+ case "not-ours":
367
+ last = { kind: "failed", name, code: "EBADRESP", message: "the server's answer could not be used" };
368
+ break;
369
+ default:
370
+ return absurd(answer);
371
+ }
372
+ }
373
+ catch (e) {
374
+ if (e instanceof Stop)
375
+ return err({ kind: "failed", name, code: e.code, message: e.message });
376
+ last = failure(name, e);
377
+ }
378
+ }
379
+ }
380
+ return err(last);
381
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * How a typed client reaches a system over HTTP (commons 0001-net FR-003): a transport, live (`fetch`) or recorded (the
3
+ * exchanges a test keeps, so it reaches no host), and over it the guards and helpers every client otherwise rewrites: a read-only guard
4
+ * (safe methods only, POST to the token endpoints named, and the POSTs a predicate says only read, FR-066), AWS Signature Version 4 on each
5
+ * request (FR-069), backoff on 429 and 503 that honours `Retry-After`, a JSON read decoded at the boundary with typed failures (a denied
6
+ * call is told apart, so a caller can record a gap instead of failing), and every item of a list that pages by `Link: rel="next"` or by a
7
+ * cursor in the body. A request that carries a credential is refused before it is sent unless the transport is made to allow it, so a
8
+ * harness whose proxy injects credentials never sends one by mistake. Taken from erga's `lib/ts/http-client` and Stolos's connector SDK
9
+ * (`src/archon/connect/sdk.ts`, `connector.ts`).
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { array, object, string } from "@intellectual-frontiers/core";
14
+ * import { getJson, liveTransport, withBackoff } from "./http-client.js";
15
+ * const http = withBackoff(liveTransport());
16
+ * const repo = await getJson(http, "https://api.github.com/repos/oven-sh/bun", object({ full_name: string }));
17
+ * ```
18
+ *
19
+ * @module
20
+ */
21
+ import { type Decoder, type Result } from "@intellectual-frontiers/core";
22
+ import { type AwsCredentials } from "@intellectual-frontiers/crypto/sigv4";
23
+ /** A request a client makes. */
24
+ export type OutRequest = {
25
+ readonly method: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
26
+ readonly url: string;
27
+ readonly headers: Readonly<Record<string, string>>;
28
+ readonly body?: string;
29
+ /** Read the answer as bytes (`Exchange.bytes`), for an artifact that is not text (a tarball, a zip); the text `body` of the answer is then empty. */
30
+ readonly binary?: boolean;
31
+ };
32
+ /** One exchange: a request and what answered it. */
33
+ export type Exchange = {
34
+ readonly method: OutRequest["method"];
35
+ readonly url: string;
36
+ readonly status: number;
37
+ /** The headers kept: the content type, paging, rate limits and `Retry-After`. */
38
+ readonly headers: Readonly<Record<string, string>>;
39
+ readonly body: string;
40
+ /** The answer's bytes: present where the request asked for `binary` (a recorded exchange of an artifact holds them). */
41
+ readonly bytes?: Uint8Array;
42
+ };
43
+ /** Why a request got no answer at all (a refusal before it was sent, or the network). */
44
+ export type TransportError = {
45
+ readonly kind: "refused";
46
+ readonly message: string;
47
+ } | {
48
+ readonly kind: "network";
49
+ readonly message: string;
50
+ };
51
+ /** A way to reach a system. */
52
+ export type Transport = {
53
+ readonly kind: "live" | "recorded";
54
+ readonly send: (r: OutRequest) => Promise<Result<Exchange, TransportError>>;
55
+ };
56
+ /** The headers a credential travels in. */
57
+ export declare const CREDENTIAL_HEADERS: readonly string[];
58
+ /** Why a request may not be sent where credentials are refused: it carries one in a header or in its query. Undefined where it carries none. */
59
+ export declare function carriesCredential(r: OutRequest): string | undefined;
60
+ /** How the live transport sends. */
61
+ export type LiveOptions = {
62
+ /** The `fetch` to use (the platform's by default). */
63
+ readonly fetch?: typeof fetch;
64
+ /** Refuse a request that carries a credential (the default), or send it. */
65
+ readonly credentials?: "refuse" | "allow";
66
+ /** The `User-Agent` said to every system: a generic name, never a person's. */
67
+ readonly userAgent?: string;
68
+ /** No answer within this many seconds fails the request (30 by default). */
69
+ readonly timeoutSeconds?: number;
70
+ };
71
+ /** The live transport, over `fetch`. */
72
+ export declare function liveTransport(options?: LiveOptions): Transport;
73
+ /** A transport that answers from recorded exchanges, by method and URL, and refuses a request it has none for, naming it. */
74
+ export declare function recordedTransport(exchanges: readonly Exchange[]): Transport;
75
+ /**
76
+ * Whether a `POST` only reads (FR-066): a GraphQL query, a search, a JSON API's `Describe` and `Get` actions. It is given the whole
77
+ * request (method, URL, headers and body), as an action may be named in a header (`x-amz-target`) or the body.
78
+ */
79
+ export type ReadPost = (r: OutRequest) => boolean;
80
+ /**
81
+ * A transport that sends only safe methods (GET, HEAD, ...), POST to URLs that start with one of `tokenEndpoints`, and the POSTs that
82
+ * `readPost` says only read (FR-066). Every other request (PUT, PATCH, DELETE, any other POST) is refused without being sent.
83
+ */
84
+ export declare function readOnly(t: Transport, tokenEndpoints?: readonly string[], readPost?: ReadPost): Transport;
85
+ /** How {@link withSigV4} signs. */
86
+ export type SigV4TransportOptions = {
87
+ readonly credentials: AwsCredentials;
88
+ readonly region: string;
89
+ readonly service: string;
90
+ /** The clock read as each request is sent (`new Date()` by default; a test gives its own). */
91
+ readonly now?: () => Date;
92
+ /** Sign `UNSIGNED-PAYLOAD` instead of the body's hash (S3 allows it). */
93
+ readonly unsignedPayload?: boolean;
94
+ };
95
+ /**
96
+ * A transport that signs each request by AWS Signature Version 4 (FR-069, by the kernel's `sigv4`, FR-068) when it is sent. A signed
97
+ * request carries a credential, so the live transport under it must be made with `credentials: "allow"`, or it refuses the request.
98
+ */
99
+ export declare function withSigV4(t: Transport, options: SigV4TransportOptions): Transport;
100
+ /** How long to back off. */
101
+ export type BackoffOptions = {
102
+ /** Tries after the first (3 by default). */
103
+ readonly retries?: number;
104
+ /** How a wait is spent (a timer by default; a test passes one that returns at once). */
105
+ readonly pause?: (ms: number) => Promise<void>;
106
+ /** The longest wait, whatever `Retry-After` asks (60 s by default). */
107
+ readonly capMs?: number;
108
+ };
109
+ /** A transport that waits and tries again on 429 and 503: as long as `Retry-After` asks (up to the cap), else 1, 2, 4 seconds. */
110
+ export declare function withBackoff(t: Transport, options?: BackoffOptions): Transport;
111
+ /** Why a JSON read failed. */
112
+ export type ReadError = TransportError | {
113
+ readonly kind: "denied";
114
+ readonly status: 401 | 403;
115
+ readonly url: string;
116
+ } | {
117
+ readonly kind: "status";
118
+ readonly status: number;
119
+ readonly url: string;
120
+ } | {
121
+ readonly kind: "decode";
122
+ readonly url: string;
123
+ readonly message: string;
124
+ };
125
+ /** A read error as one sentence; never a header or a body, so no credential or personal datum is said. */
126
+ export declare function formatReadError(e: ReadError): string;
127
+ /** A GET whose JSON body is decoded, with the exchange; 401 and 403 are `denied`, any other status from 400 up is `status`. */
128
+ export declare function getExchange<T>(t: Transport, url: string, decoder: Decoder<T>, headers?: Readonly<Record<string, string>>): Promise<Result<{
129
+ readonly value: T;
130
+ readonly exchange: Exchange;
131
+ }, ReadError>>;
132
+ /** A GET whose JSON body is decoded. */
133
+ export declare function getJson<T>(t: Transport, url: string, decoder: Decoder<T>, headers?: Readonly<Record<string, string>>): Promise<Result<T, ReadError>>;
134
+ /** Every page of a list that pages by `Link: <...>; rel="next"`, at most `maxPages` (200 by default); the first failure ends it, as an error. */
135
+ export declare function linkPages<T>(t: Transport, url: string, item: Decoder<T>, options?: {
136
+ readonly headers?: Readonly<Record<string, string>>;
137
+ readonly maxPages?: number;
138
+ }): AsyncGenerator<T, Result<number, ReadError>>;
139
+ /** Every item of a list that pages by a cursor in its body: `items` takes a page's items, `next` the next page's URL or undefined. */
140
+ export declare function cursorPages<B, T>(t: Transport, first: string, page: Decoder<B>, items: (body: B) => readonly T[], next: (body: B, url: string) => string | undefined, options?: {
141
+ readonly headers?: Readonly<Record<string, string>>;
142
+ readonly maxPages?: number;
143
+ }): AsyncGenerator<T, Result<number, ReadError>>;
144
+ /** A recorded exchange read from the JSON5 text `recordedText` writes, or why it is not one. */
145
+ export declare function decodeRecorded(text: string): Result<Exchange, string>;
146
+ /** The text a recorded exchange is kept in: a comment that says where and when it was recorded, then the exchange as JSON5. */
147
+ export declare function recordedText(x: Exchange, note: string): string;
148
+ /** Headers that give a bearer token (for a transport made to allow credentials). */
149
+ export declare function bearer(token: string, scheme?: string): Readonly<Record<string, string>>;