@openstage/monadyssey-fetch 3.0.0-rc.2 → 3.0.0-rc.3

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.
@@ -1,364 +1,1196 @@
1
- import { IO as e, List as t, Option as n, Stream as r } from "@openstage/monadyssey-core";
1
+ import { IO, List, Option, Stream } from "@openstage/monadyssey-core";
2
2
  // src/http-error.ts
3
- var i = (e) => {
4
- try {
5
- return Object.fromEntries(Array.from(e.headers.entries()).filter(([e]) => e !== "set-cookie" && e !== "set-cookie2"));
6
- } catch {
7
- return {};
8
- }
9
- }, a = {
10
- describe: (e) => e instanceof Error ? e.message : typeof e == "string" ? e : typeof e == "object" && e && "message" in e ? String(e.message) : "An unknown error occurred.",
11
- format: (e, t, n, r, i) => {
12
- switch (e) {
13
- case "response": return `Request to '${t}' failed with status ${n} and message: ${r}.`;
14
- case "decode": return `Response from '${t}' (status ${n}) could not be decoded: ${r}.`;
15
- case "request": return `Request to '${t}' could not be sent: ${r}.`;
16
- case "timeout": return `Request to '${t}' timed out after ${i} ms.`;
17
- case "aborted": return `Request to '${t}' was aborted before a response arrived: ${r}.`;
18
- default: return `Request to '${t}' failed before a response arrived: ${r}.`;
3
+ /** @internal What an `HttpError` holds besides its message, and how the client fills it in. */
4
+ var HttpErrorFields = {
5
+ /**
6
+ * The response headers an `HttpError` carries. `Set-Cookie` is left out: browsers never expose it,
7
+ * Node and Electron do, and an error that ends up in a log must not carry a session.
8
+ */
9
+ responseHeaders: (response) => {
10
+ try {
11
+ return Object.fromEntries(Array.from(response.headers.entries()).filter(([name]) => name !== "set-cookie" && name !== "set-cookie2"));
12
+ } catch {
13
+ return {};
19
14
  }
15
+ },
16
+ /** A read-only property that enumeration and `JSON.stringify` skip. */
17
+ hidden: (value) => ({
18
+ value,
19
+ enumerable: false,
20
+ writable: false,
21
+ configurable: true
22
+ }),
23
+ /**
24
+ * Records the request method on an error the client returns, unless it already has one (an
25
+ * `HttpError` an interceptor built with its own).
26
+ */
27
+ withMethod: (error, method) => {
28
+ if (error.method === void 0) error.method = method;
29
+ return error;
20
30
  }
21
- }, o = class e extends Error {
31
+ };
32
+ /** @internal */
33
+ var HttpErrorMessage = {
34
+ /** Ends `text` with exactly one period, so a cause that has its own does not give "..". */
35
+ sentence: (text) => text.endsWith(".") ? text : `${text}.`,
36
+ /**
37
+ * `text` with every character that is not plain visible text written as an escape, `\uXXXX` or
38
+ * `\u{XXXXX}` by code point: controls, format characters (bidirectional marks and overrides,
39
+ * zero-width characters, the BOM, tag characters), line and paragraph separators, lone
40
+ * surrogates and variation selectors. A backslash is written `\\`, so text that spells an escape
41
+ * cannot pass for one. A status text, a URL or a parser's message can come from the server;
42
+ * written raw to a log or a terminal it could forge lines, move the cursor, or change what is
43
+ * shown.
44
+ */
45
+ printable: (text) => text.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}\u{FE00}-\u{FE0F}\u{E0100}-\u{E01EF}\\]/gu, (c) => {
46
+ if (c === "\\") return "\\\\";
47
+ const code = c.codePointAt(0);
48
+ return code > 65535 ? `\\u{${code.toString(16)}}` : `\\u${code.toString(16).padStart(4, "0")}`;
49
+ }),
50
+ describe: (cause) => cause instanceof Error ? cause.message : typeof cause === "string" ? cause : typeof cause === "object" && cause !== null && "message" in cause ? String(cause.message) : "An unknown error occurred.",
51
+ /** Response errors keep the pre-3.0 wording; the other kinds carry no status. */
52
+ format: (kind, rawUrl, status, rawText, timeoutMs) => {
53
+ const url = HttpErrorMessage.printable(rawUrl);
54
+ const rawMessage = HttpErrorMessage.printable(rawText);
55
+ switch (kind) {
56
+ case "response": return `Request to '${url}' failed with status ${status} and message: ${HttpErrorMessage.sentence(rawMessage)}`;
57
+ case "decode": return `Response from '${url}' (status ${status}) could not be decoded: ${HttpErrorMessage.sentence(rawMessage)}`;
58
+ case "request": return `Request to '${url}' could not be sent: ${HttpErrorMessage.sentence(rawMessage)}`;
59
+ case "timeout": return `Request to '${url}' timed out after ${timeoutMs} ms.`;
60
+ case "aborted": return `Request to '${url}' was aborted before a response arrived: ${HttpErrorMessage.sentence(rawMessage)}`;
61
+ case "redirect": return `Request to '${url}' was redirected (status ${status}), and redirects are refused.`;
62
+ case "tooLarge": return `Response from '${url}' (status ${status}) is too large: ${HttpErrorMessage.sentence(rawMessage)}`;
63
+ default: return `Request to '${url}' failed before a response arrived: ${HttpErrorMessage.sentence(rawMessage)}`;
64
+ }
65
+ }
66
+ };
67
+ /**
68
+ * Represents an HTTP error encountered during a request.
69
+ *
70
+ * Extends the native `Error` class with additional context: the transport outcome (`kind`), HTTP
71
+ * status code, raw error message, response body, request URL, response headers, and the
72
+ * underlying cause.
73
+ *
74
+ * `kind` tells the two facts apart that `status` alone cannot: "the server said 500" is
75
+ * `kind: "response", status: 500`, while "nothing answered" is `kind: "network", status: 0`.
76
+ * For every kind other than `"response"`, `"decode"`, `"redirect"` and `"tooLarge"`, `status` is `0`;
77
+ * `body` is `null` except for `"response"`.
78
+ *
79
+ * `message`, `rawMessage`, `body`, `headers`, `url` and `cause` hold what the server and the request
80
+ * contained, which may be sensitive (a token in a query string, an error page echoing input, part of
81
+ * a body in a parse error, a request header value the platform rejected); log {@link HttpError.summary} instead outside a trusted sink.
82
+ * `Set-Cookie` is never carried.
83
+ *
84
+ * @example
85
+ * client.post("/payments", payment).mapErr((error) =>
86
+ * error.kind === "response"
87
+ * ? { kind: "rejected", status: error.status }
88
+ * : { kind: "outcomeUnknown" } // the request may or may not have reached the server
89
+ * );
90
+ */
91
+ var HttpError = class HttpError extends Error {
92
+ /** The transport outcome. See {@link HttpErrorKind}. */
22
93
  kind;
94
+ /** The HTTP status code (`"response"` and `"decode"`), or `0` when no response arrived. */
23
95
  status;
24
- rawMessage;
25
- body;
26
- url;
27
- headers;
28
- cause;
96
+ /** The request method. Set by `HttpClient` on every error it returns. */
97
+ method;
98
+ /** The timeout that fired, in milliseconds. Set only when `kind === "timeout"`. */
29
99
  timeoutMs;
30
- constructor(e, t, n, r, i, o = "response", s, c) {
31
- super(a.format(o, r, e, t, c)), this.name = "HttpError", this.kind = o, this.status = e, this.rawMessage = t, this.body = n, this.url = r, this.headers = i, this.cause = s, this.timeoutMs = c;
32
- }
33
- static network(t, n) {
34
- return new e(0, a.describe(n), null, t, void 0, "network", n);
35
- }
36
- static timeout(t, n) {
37
- return new e(0, `Request timed out after ${n} ms`, null, t, void 0, "timeout", void 0, n);
38
- }
39
- static decode(t, n, r) {
40
- return new e(n.status, a.describe(r), null, t, i(n), "decode", r);
41
- }
42
- static request(t, n) {
43
- return new e(0, a.describe(n), null, t, void 0, "request", n);
44
- }
45
- static aborted(t, n) {
46
- return new e(0, a.describe(n), null, t, void 0, "aborted", n);
47
- }
48
- bodyAs(e) {
49
- return e(this.body) ? n.ofNullable(this.body) : n.empty();
50
- }
51
- }, s = (e) => typeof e != "object" || !e || e instanceof FormData || e instanceof Blob || e instanceof ArrayBuffer || e instanceof URLSearchParams || typeof ReadableStream < "u" && e instanceof ReadableStream || ArrayBuffer.isView(e), c = (e) => Object.fromEntries(Object.entries(e).filter((e) => e[1] !== void 0).map(([e, t]) => [e.toLowerCase(), t])), l = (e, t) => {
52
- if (t instanceof FormData) {
53
- let { "content-type": t, ...n } = e;
54
- return n;
55
- }
56
- return typeof t == "object" && t && !s(t) && !("content-type" in e) ? {
57
- ...e,
58
- "content-type": "application/json"
59
- } : e;
60
- }, u = (e) => {
61
- let t = e.split(";")[0].trim().toLowerCase();
62
- return t === "application/json" || t.endsWith("+json");
63
- }, d = (e, t, n) => e === "GET" || e === "HEAD" || t == null ? void 0 : s(t) ? t : u(n["content-type"]) ? JSON.stringify(t) : t, f = {
64
- isNativeBody: s,
65
- normalizeHeaders: c,
66
- prepare: (e, t, n) => {
67
- let r = l(c({
68
- ...n.headers,
69
- ...t.headers ?? {}
70
- }), t.body);
100
+ constructor(status, rawMessage, body, url, headers, kind = "response", cause, timeoutMs) {
101
+ super(HttpErrorMessage.format(kind, url, status, rawMessage, timeoutMs));
102
+ this.name = "HttpError";
103
+ this.kind = kind;
104
+ this.status = status;
105
+ this.timeoutMs = timeoutMs;
106
+ Object.defineProperties(this, {
107
+ rawMessage: HttpErrorFields.hidden(rawMessage),
108
+ body: HttpErrorFields.hidden(body),
109
+ url: HttpErrorFields.hidden(url),
110
+ headers: HttpErrorFields.hidden(headers),
111
+ cause: HttpErrorFields.hidden(cause)
112
+ });
113
+ }
114
+ /**
115
+ * An error for a request that received no response: DNS failure, offline, CORS block, or a
116
+ * rejected interceptor. `status` is `0` and `body` is `null`.
117
+ *
118
+ * @param {string} url The request URL.
119
+ * @param {unknown} cause The underlying exception (typically the `TypeError` thrown by `fetch`).
120
+ */
121
+ static network(url, cause) {
122
+ return new HttpError(0, HttpErrorMessage.describe(cause), null, url, void 0, "network", cause);
123
+ }
124
+ /**
125
+ * An error for a request whose `timeout` option fired before the response, or its body, completed.
126
+ * `status` is `0`, `body` is `null`, and `timeoutMs` records the timeout.
127
+ *
128
+ * @param {string} url The request URL.
129
+ * @param {number} after The timeout in milliseconds.
130
+ */
131
+ static timeout(url, after) {
132
+ return new HttpError(0, `Request timed out after ${after} ms`, null, url, void 0, "timeout", void 0, after);
133
+ }
134
+ /**
135
+ * An error for a 2xx response whose body could not be used: it failed to parse, a `transform`
136
+ * threw, or there was no body where one was expected. `status` is the real status, `body` is
137
+ * `null`, and `cause` carries the underlying error.
138
+ *
139
+ * @param {string} url The request URL.
140
+ * @param {Response} response The response that could not be decoded.
141
+ * @param {unknown} cause The parse error, the value a `transform` threw, or a description.
142
+ */
143
+ static decode(url, response, cause) {
144
+ return new HttpError(response.status, HttpErrorMessage.describe(cause), null, url, HttpErrorFields.responseHeaders(response), "decode", cause);
145
+ }
146
+ /**
147
+ * An error for a request that could not be built, so nothing was sent — typically a body that
148
+ * could not be serialized. `status` is `0` and `body` is `null`.
149
+ *
150
+ * @param {string} url The request URL.
151
+ * @param {unknown} cause The underlying exception (typically a `TypeError` from `JSON.stringify`).
152
+ */
153
+ static request(url, cause) {
154
+ return new HttpError(0, HttpErrorMessage.describe(cause), null, url, void 0, "request", cause);
155
+ }
156
+ /**
157
+ * An error for a request aborted by something other than IO cancellation, such as an
158
+ * interceptor aborting the signal. `status` is `0` and `body` is `null`.
159
+ *
160
+ * @param {string} url The request URL.
161
+ * @param {unknown} [cause] The abort reason, if any.
162
+ */
163
+ static aborted(url, cause) {
164
+ return new HttpError(0, HttpErrorMessage.describe(cause), null, url, void 0, "aborted", cause);
165
+ }
166
+ /**
167
+ * An error for a redirect that the request's `redirect: "error"` setting refused. The redirect
168
+ * was not followed. `status` is the redirect status (`0` in a browser, which hides it), `body` is
169
+ * `null`, and `headers` are the redirect's own (its `Location`, where the platform exposes it).
170
+ *
171
+ * @param {string} url The request URL.
172
+ * @param {Response} response The redirect response.
173
+ */
174
+ static redirect(url, response) {
175
+ return new HttpError(response.status, "Redirects are refused", null, url, HttpErrorFields.responseHeaders(response), "redirect");
176
+ }
177
+ /**
178
+ * An error for a 2xx response whose body is larger than the request's `maxBodyBytes`. Reading
179
+ * stopped at the limit. `status` is the real status and `body` is `null`.
180
+ *
181
+ * @param {string} url The request URL.
182
+ * @param {Response} response The response whose body was too large.
183
+ * @param {number} maxBodyBytes The limit, in bytes.
184
+ */
185
+ static tooLarge(url, response, maxBodyBytes) {
186
+ return new HttpError(response.status, `the body is larger than ${maxBodyBytes} bytes`, null, url, HttpErrorFields.responseHeaders(response), "tooLarge");
187
+ }
188
+ /**
189
+ * Narrows the `unknown` error body to a concrete type using a runtime type guard.
190
+ * Returns `Some(body)` if the guard passes, `None` otherwise — so the narrow is *checked*,
191
+ * not asserted. This keeps the unsafe cast out of consumer code: the body stays `unknown`
192
+ * by default (forcing a conscious narrow), and this is the safe way to perform it.
193
+ *
194
+ * @template T The expected body shape.
195
+ * @param {(x: unknown) => x is T} guard A type guard validating the body's shape.
196
+ * @returns {Option<T>} `Some(body)` if the guard matches, `None` otherwise.
197
+ *
198
+ * @example
199
+ * interface ApiError { code: string; message: string }
200
+ * const isApiError = (x: unknown): x is ApiError =>
201
+ * typeof x === "object" && x !== null && "code" in x && "message" in x;
202
+ *
203
+ * httpError.bodyAs(isApiError).fold(
204
+ * () => "unrecognized error shape",
205
+ * (e) => `${e.code}: ${e.message}`
206
+ * );
207
+ */
208
+ bodyAs(guard) {
209
+ return guard(this.body) ? Option.ofNullable(this.body) : Option.empty();
210
+ }
211
+ /**
212
+ * The parts of this error that are safe to log: the kind, the status, the method, the host (with
213
+ * its port, without credentials) and, for a timeout, `timeoutMs`. It never holds the URL's path or
214
+ * query, the body, the headers, the message or the cause.
215
+ *
216
+ * @returns {HttpErrorSummary} The summary.
217
+ *
218
+ * @example
219
+ * client.get("/users/42?token=…").tapErr((error) => logger.warn("user lookup failed", error.summary()));
220
+ * // { kind: "response", status: 404, method: "GET", host: "api.example.com" }
221
+ */
222
+ summary() {
223
+ let host;
224
+ try {
225
+ host = new URL(this.url).host || void 0;
226
+ } catch {
227
+ host = void 0;
228
+ }
229
+ return {
230
+ kind: this.kind,
231
+ status: this.status,
232
+ ...this.method !== void 0 ? { method: this.method } : {},
233
+ ...host !== void 0 ? { host } : {},
234
+ ...this.timeoutMs !== void 0 ? { timeoutMs: this.timeoutMs } : {}
235
+ };
236
+ }
237
+ };
238
+ // src/http-request.ts
239
+ /** @internal */
240
+ var HttpRequest = {
241
+ /** Bodies `fetch` sends as-is: never JSON-encoded, never given an automatic content type. */
242
+ isNativeBody: (body) => typeof body !== "object" || body === null || body instanceof FormData || body instanceof Blob || body instanceof ArrayBuffer || body instanceof URLSearchParams || typeof ReadableStream !== "undefined" && body instanceof ReadableStream || ArrayBuffer.isView(body),
243
+ normalizeHeaders: (headers) => Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== void 0).map(([key, value]) => [key.toLowerCase(), value])),
244
+ /** `FormData` must carry no content type so the browser can set the multipart boundary. */
245
+ withContentType: (headers, body) => {
246
+ if (body instanceof FormData) {
247
+ const { "content-type": _dropped, ...rest } = headers;
248
+ return rest;
249
+ }
250
+ return body != null && typeof body === "object" && !HttpRequest.isNativeBody(body) && !("content-type" in headers) ? {
251
+ ...headers,
252
+ "content-type": "application/json"
253
+ } : headers;
254
+ },
255
+ /**
256
+ * `application/json`, with or without parameters (`; charset=utf-8`), or any `+json` suffix type
257
+ * (`application/merge-patch+json`, `application/vnd.api+json`). Matching the exact string alone
258
+ * would send an object declared as one of the others as `"[object Object]"`.
259
+ */
260
+ isJsonContentType: (contentType) => {
261
+ const media = contentType.split(";")[0].trim().toLowerCase();
262
+ return media === "application/json" || media.endsWith("+json");
263
+ },
264
+ serializeBody: (method, body, headers) => method === "GET" || method === "HEAD" || body == null ? void 0 : HttpRequest.isNativeBody(body) ? body : HttpRequest.isJsonContentType(headers["content-type"]) ? JSON.stringify(body) : body,
265
+ /** Per-request headers win over defaults; names are lowercased; the body follows the content type. */
266
+ prepare: (method, options, defaults) => {
267
+ const headers = HttpRequest.withContentType(HttpRequest.normalizeHeaders({
268
+ ...defaults.headers,
269
+ ...options.headers ?? {}
270
+ }), options.body);
71
271
  return {
72
- method: e,
73
- headers: r,
74
- credentials: t.credentials ?? n.credentials,
75
- body: d(e, t.body, r)
272
+ method,
273
+ headers,
274
+ credentials: options.credentials ?? defaults.credentials,
275
+ body: HttpRequest.serializeBody(method, options.body, headers)
76
276
  };
77
277
  }
78
- }, p = {
79
- json: (e) => e.json(),
80
- text: (e) => e.text(),
81
- blob: (e) => e.blob(),
82
- arrayBuffer: (e) => e.arrayBuffer(),
83
- formData: (e) => e.formData()
84
- }, m = (e) => Object.prototype.hasOwnProperty.call(p, e) ? n.of(p[e]) : n.empty(), h = i, g = (e, t, n) => o.decode(t, n, e), _ = Symbol("HttpResponse.noBody"), v = (e, t, n) => new o(e.status, e.statusText, t, n, h(e)), y = async (e) => {
85
- if (typeof e.text != "function") return e.json();
86
- let t = await e.text();
87
- return t.trim() === "" ? _ : JSON.parse(t);
88
- }, b = {
89
- headers: h,
90
- error: g,
91
- failure: v,
92
- read: (t, n, r, i) => e.from(m(n), () => g(`Unsupported response type: ${n}`, r, t)).flatMap((a) => e.lift(async () => t.status === 204 || t.status === 205 || i === "HEAD" ? _ : n === "json" ? y(t) : a(t), (e) => g(e, r, t))),
93
- readFailure: (t, n, r) => e.promise(async () => {
278
+ };
279
+ // src/http-response.ts
280
+ var bodyReaders = {
281
+ json: (response) => response.json(),
282
+ text: (response) => response.text(),
283
+ blob: (response) => response.blob(),
284
+ arrayBuffer: (response) => response.arrayBuffer(),
285
+ formData: (response) => response.formData()
286
+ };
287
+ /**
288
+ * What {@link HttpResponse.read} yields when there is no body at all — distinct from a JSON body
289
+ * that is literally `null`.
290
+ *
291
+ * @internal
292
+ */
293
+ var NO_BODY = Symbol("HttpResponse.noBody");
294
+ /** What {@link HttpResponse.readBytes} yields for a body larger than the limit. */
295
+ var TOO_LARGE = Symbol("HttpResponse.tooLarge");
296
+ /**
297
+ * How much of an error (non-2xx) body is read when the request sets no `maxBodyBytes`. An error
298
+ * body is a diagnostic, so a server that sends an endless one must not hold the request or grow
299
+ * memory without bound.
300
+ */
301
+ var DEFAULT_ERROR_BODY_BYTES = 65536;
302
+ /** Decodes bytes read under a limit as the platform's own body readers would. */
303
+ var fromBytes = {
304
+ json: (bytes) => {
305
+ const text = HttpResponse.utf8(bytes);
306
+ return text.trim() === "" ? NO_BODY : JSON.parse(text);
307
+ },
308
+ text: (bytes) => HttpResponse.utf8(bytes),
309
+ blob: (bytes, response) => new Blob([bytes], { type: response.headers.get("content-type") ?? "" }),
310
+ arrayBuffer: (bytes) => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
311
+ formData: (bytes, response) => new Response(bytes, { headers: { "content-type": response.headers.get("content-type") ?? "" } }).formData()
312
+ };
313
+ /** @internal */
314
+ var HttpResponse = {
315
+ headers: HttpErrorFields.responseHeaders,
316
+ /** The server answered 2xx but the body could not be used (`kind: "decode"`). */
317
+ error: (cause, url, response) => HttpError.decode(url, response, cause),
318
+ /** The server answered with a non-2xx status; the parsed body travels with the error. */
319
+ failure: (response, body, url) => new HttpError(response.status, response.statusText, body, url, HttpResponse.headers(response)),
320
+ /** An own-property lookup, so an untyped `responseType` such as `"toString"` is rejected. */
321
+ readerFor: (responseType) => Object.prototype.hasOwnProperty.call(bodyReaders, responseType) ? Option.of(bodyReaders[responseType]) : Option.empty(),
322
+ /**
323
+ * Reads a JSON body, yielding `NO_BODY` for an empty one. Responses that implement only `json()` —
324
+ * hand-rolled mocks in consumers' tests — are read with it.
325
+ */
326
+ readJson: async (response) => {
327
+ if (typeof response.text !== "function") return response.json();
328
+ const text = await response.text();
329
+ return text.trim() === "" ? NO_BODY : JSON.parse(text);
330
+ },
331
+ utf8: (bytes) => new TextDecoder().decode(bytes),
332
+ /**
333
+ * Whether a body chunk is bytes. Read from the type tag, not with `instanceof`: a body created in
334
+ * another realm (a test DOM, an iframe, a `vm` context) carries that realm's `Uint8Array`. A Node
335
+ * `Buffer` is a `Uint8Array` too.
336
+ */
337
+ isBytes: (value) => Object.prototype.toString.call(value) === "[object Uint8Array]",
338
+ /** The pieces of a body that can be read one at a time: a `ReadableStream`, or an async iterable (a Node `Readable`). */
339
+ chunksOf: (body) => {
340
+ if (typeof body?.getReader === "function") {
341
+ const reader = body.getReader();
342
+ return {
343
+ next: () => reader.read(),
344
+ stop: () => void reader.cancel().catch(() => {})
345
+ };
346
+ }
347
+ if (typeof body?.[Symbol.asyncIterator] === "function") {
348
+ const iterator = body[Symbol.asyncIterator]();
349
+ return {
350
+ next: () => iterator.next(),
351
+ stop: () => {
352
+ try {
353
+ Promise.resolve(iterator.return?.()).catch(() => {});
354
+ } catch {}
355
+ }
356
+ };
357
+ }
358
+ },
359
+ /**
360
+ * Reads the body as bytes, and stops once it passes `limit`: reading is cancelled and `TOO_LARGE`
361
+ * is returned. A `Content-Length` already above the limit returns `TOO_LARGE` without reading. A
362
+ * piece that is not bytes cannot be counted, so it fails the read rather than slipping past the
363
+ * limit.
364
+ */
365
+ readBytes: async (response, limit) => {
366
+ const chunks = response.body === null ? void 0 : HttpResponse.chunksOf(response.body);
367
+ if (Number(response.headers?.get("content-length") ?? void 0) > limit) {
368
+ chunks?.stop();
369
+ return TOO_LARGE;
370
+ }
371
+ if (chunks === void 0) return /* @__PURE__ */ new Uint8Array(0);
372
+ const pieces = [];
373
+ let size = 0;
374
+ for (;;) {
375
+ const { done, value } = await chunks.next();
376
+ if (done === true) break;
377
+ if (!HttpResponse.isBytes(value)) {
378
+ chunks.stop();
379
+ throw new TypeError("a response body chunk is not bytes");
380
+ }
381
+ size += value.byteLength;
382
+ if (size > limit) {
383
+ chunks.stop();
384
+ return TOO_LARGE;
385
+ }
386
+ pieces.push(value);
387
+ }
388
+ const bytes = new Uint8Array(size);
389
+ let offset = 0;
390
+ for (const piece of pieces) {
391
+ bytes.set(piece, offset);
392
+ offset += piece.byteLength;
393
+ }
394
+ return bytes;
395
+ },
396
+ /** A finite limit: one that bytes are counted against. */
397
+ finite: (limit) => limit !== void 0 && limit !== Infinity,
398
+ /**
399
+ * Whether the body can be counted as it is read: no body at all, a `ReadableStream`, or an async
400
+ * iterable. Checking does not touch the body.
401
+ */
402
+ countable: (response) => {
403
+ const body = response.body;
404
+ return body === null || typeof body?.getReader === "function" || typeof body?.[Symbol.asyncIterator] === "function";
405
+ },
406
+ /**
407
+ * Reads a successful body. Yields `NO_BODY` when there is none to read: `204`/`205`, a `HEAD`
408
+ * request, or an empty body under `"json"` (e.g. `201 Created` / `202 Accepted` with nothing
409
+ * attached). A body that cannot be parsed fails with `kind: "decode"`.
410
+ */
411
+ read: (response, responseType, url, method, maxBodyBytes) => IO.from(HttpResponse.readerFor(responseType), () => HttpResponse.error(`Unsupported response type: ${responseType}`, url, response)).flatMap((read) => IO.lift(async () => {
412
+ if (response.status === 204 || response.status === 205 || method === "HEAD") return NO_BODY;
413
+ if (HttpResponse.finite(maxBodyBytes)) {
414
+ if (!HttpResponse.countable(response)) throw new TypeError("maxBodyBytes needs a response whose body is a ReadableStream");
415
+ const bytes = await HttpResponse.readBytes(response, maxBodyBytes);
416
+ if (bytes === TOO_LARGE) throw TOO_LARGE;
417
+ return fromBytes[responseType](bytes, response);
418
+ }
419
+ if (responseType !== "json") return read(response);
420
+ return HttpResponse.readJson(response);
421
+ }, (cause) => cause === TOO_LARGE ? HttpError.tooLarge(url, response, maxBodyBytes) : HttpResponse.error(cause, url, response))),
422
+ /**
423
+ * Fails with the error for a non-2xx response. The body is read leniently, so an error page
424
+ * that is not JSON (an HTML 502 from a proxy, say) still travels with the error and the message
425
+ * stays the status text: under `"json"` the text is parsed when it is JSON and kept as a string
426
+ * otherwise; an unreadable or empty body is `null`. At most `maxBodyBytes` of it is read, or
427
+ * 64 KiB when the request sets none; a longer body is dropped (`null`).
428
+ */
429
+ readFailure: (response, responseType, url, maxBodyBytes) => IO.promise(async () => {
430
+ const limit = maxBodyBytes ?? DEFAULT_ERROR_BODY_BYTES;
94
431
  try {
95
- if (n !== "json") return await m(n).fold(async () => null, (e) => e(t));
96
- if (typeof t.text != "function") return await t.json();
97
- let e = await t.text();
98
- if (e.trim() === "") return null;
432
+ if (HttpResponse.finite(limit) && !HttpResponse.countable(response)) {
433
+ if (response.body !== void 0 || HttpResponse.finite(maxBodyBytes)) return null;
434
+ } else if (HttpResponse.finite(limit)) {
435
+ const bytes = await HttpResponse.readBytes(response, limit);
436
+ if (bytes === TOO_LARGE) return null;
437
+ if (responseType !== "json") return await fromBytes[responseType](bytes, response);
438
+ const text = HttpResponse.utf8(bytes);
439
+ if (text.trim() === "") return null;
440
+ try {
441
+ return JSON.parse(text);
442
+ } catch {
443
+ return text;
444
+ }
445
+ }
446
+ if (responseType !== "json") return await HttpResponse.readerFor(responseType).fold(async () => null, (read) => read(response));
447
+ if (typeof response.text !== "function") return await response.json();
448
+ const text = await response.text();
449
+ if (text.trim() === "") return null;
99
450
  try {
100
- return JSON.parse(e);
451
+ return JSON.parse(text);
101
452
  } catch {
102
- return e;
453
+ return text;
103
454
  }
104
455
  } catch {
105
456
  return null;
106
457
  }
107
- }).flatMap((n) => e.fail(v(t, n, r)))
108
- }, x = (e) => typeof e == "object" && !!e && "name" in e && e.name === "AbortError", S = {
109
- error: (e, t) => e instanceof o ? e : x(e) ? o.aborted(t, e) : o.network(t, e),
110
- isRetryable: (e) => e.kind === "network" || e.kind === "response" && e.status >= 500
111
- }, C = {
112
- run: (e, t, n) => e.reduceRight((e, t) => (n) => t.intercept(n, e), n)(t),
113
- request: (e, t) => {
114
- let n;
458
+ }).flatMap((body) => IO.fail(HttpResponse.failure(response, body, url)))
459
+ };
460
+ // src/url.ts
461
+ /** @internal How the client reads and checks request URLs before sending them. */
462
+ var HttpUrl = {
463
+ /**
464
+ * The base URL a browser's `fetch` reads every URL against: the document's base URL (which a
465
+ * `<base href>` changes), else the page's address. None outside a browser.
466
+ */
467
+ pageBase: () => {
468
+ const scope = globalThis;
469
+ try {
470
+ const base = scope.document?.baseURI;
471
+ if (typeof base === "string") return base;
472
+ const href = scope.location?.href;
473
+ return typeof href === "string" ? href : void 0;
474
+ } catch {
475
+ return;
476
+ }
477
+ },
478
+ /** `url` read by the WHATWG parser, against `base` when given; `undefined` when it cannot be read. */
479
+ parse: (url, base) => {
480
+ try {
481
+ return new URL(url, base);
482
+ } catch {
483
+ return;
484
+ }
485
+ },
486
+ /**
487
+ * `url` read as `fetch` will: against the page's base URL in a browser, on its own elsewhere. A
488
+ * browser reads `https:host/x` against the page too, as a path on the page's own origin.
489
+ */
490
+ parseForFetch: (url) => {
491
+ const base = HttpUrl.pageBase();
492
+ return base === void 0 ? HttpUrl.parse(url) : HttpUrl.parse(url, base);
493
+ },
494
+ /**
495
+ * The `kind: "request"` error for a URL that carries credentials, or `undefined`. The URL is read
496
+ * by the WHATWG parser that `fetch` uses, so every form it accepts is caught (leading whitespace,
497
+ * tabs, missing slashes, backslashes, protocol-relative). The error's URL leaves the credentials
498
+ * out.
499
+ */
500
+ refuseCredentials: (url) => {
501
+ for (const parsed of [HttpUrl.parse(url), HttpUrl.parse(url, HttpUrl.pageBase() ?? "http://localhost/")]) {
502
+ if (parsed === void 0 || parsed.username === "" && parsed.password === "") continue;
503
+ parsed.username = "";
504
+ parsed.password = "";
505
+ return HttpError.request(parsed.href, /* @__PURE__ */ new TypeError("the URL carries credentials; send them in a header instead"));
506
+ }
507
+ },
508
+ /**
509
+ * The origins of an `allowedOrigins` list. An entry must be exactly an origin
510
+ * (`https://api.example.com`, a port allowed); a path, query, fragment or credentials throws
511
+ * `RangeError`.
512
+ */
513
+ originsOf: (entries) => {
514
+ const origins = /* @__PURE__ */ new Set();
515
+ for (const entry of entries) {
516
+ const parsed = HttpUrl.parse(entry);
517
+ if (!(parsed !== void 0 && parsed.origin !== "null" && parsed.pathname === "/" && parsed.search === "" && parsed.hash === "" && parsed.username === "" && parsed.password === "" && !/\/[^/]/.test(entry.replace(/^[a-z][a-z\d+.-]*:\/\//i, "")))) throw new RangeError(`HttpClient: allowedOrigins entries must be origins such as "https://api.example.com", got ${entry}`);
518
+ origins.add(parsed.origin);
519
+ }
520
+ return origins;
521
+ },
522
+ /** Whether `url` is read by `fetch` as one of `allowed`'s origins. */
523
+ allowedOrigin: (url, allowed) => {
524
+ const parsed = HttpUrl.parseForFetch(url);
525
+ return parsed !== void 0 && allowed.has(parsed.origin);
526
+ },
527
+ /** The `kind: "request"` error for a URL whose origin is not in `allowed`, or `undefined`. */
528
+ refuseOrigin: (url, allowed) => {
529
+ if (allowed === void 0 || HttpUrl.allowedOrigin(url, allowed)) return void 0;
530
+ const parsed = HttpUrl.parseForFetch(url);
531
+ const origin = parsed === void 0 ? "an unreadable URL" : `the origin ${parsed.origin}`;
532
+ return HttpError.request(url, /* @__PURE__ */ new TypeError(`${origin} is not in allowedOrigins`));
533
+ },
534
+ /** The first reason to refuse `url` before sending it: credentials, then its origin. */
535
+ refuseUrl: (url, allowed) => HttpUrl.refuseCredentials(url) ?? HttpUrl.refuseOrigin(url, allowed)
536
+ };
537
+ // src/http-transport.ts
538
+ /** The statuses `fetch` follows as redirects; a `304` (or `300`) is not one. */
539
+ var REDIRECT_STATUSES = /* @__PURE__ */ new Set([
540
+ 301,
541
+ 302,
542
+ 303,
543
+ 307,
544
+ 308
545
+ ]);
546
+ /** @internal */
547
+ var HttpTransport = {
548
+ /** Whether `e` is the platform's abort error. */
549
+ isAbort: (e) => typeof e === "object" && e !== null && "name" in e && e.name === "AbortError",
550
+ /** An interceptor may reject with a ready-made `HttpError`; it is passed through untouched. */
551
+ error: (e, url) => e instanceof HttpError ? e : HttpTransport.isAbort(e) ? HttpError.aborted(url, e) : HttpError.network(url, e),
552
+ /**
553
+ * The `redirect` init for a setting: `"error"` sends `"manual"`, so the client sees the redirect
554
+ * and fails it as `kind: "redirect"` (the platform's own `"error"` rejects with a `TypeError` that
555
+ * looks like a network failure). No setting leaves the platform default.
556
+ */
557
+ redirectInit: (redirect) => redirect === void 0 ? {} : { redirect: redirect === "error" ? "manual" : "follow" },
558
+ /**
559
+ * The end of the chain checks the URL `fetch` will actually get, so an interceptor cannot add
560
+ * credentials to it, or send it to an origin outside `allowed`, either. Under `allowed`, `fetch`
561
+ * gets the absolute URL that was checked, so it has nothing left to read differently.
562
+ */
563
+ guardUrl: (send, allowed) => (request) => {
564
+ const url = request.url;
565
+ if (typeof url !== "string") return Promise.reject(HttpError.request("[not a string]", /* @__PURE__ */ new TypeError("the request URL is not a string")));
566
+ const refused = HttpUrl.refuseUrl(url, allowed);
567
+ if (refused !== void 0) return Promise.reject(refused);
568
+ return send(allowed === void 0 ? request : {
569
+ ...request,
570
+ url: HttpUrl.parseForFetch(url).href
571
+ });
572
+ },
573
+ /**
574
+ * The end of the chain under a setting: `"error"` sends `redirect: "manual"` whatever the
575
+ * interceptors left in `init`, so an interceptor that rebuilds or changes it cannot turn the
576
+ * refusal off.
577
+ */
578
+ enforceRedirect: (redirect, send) => redirect === "error" ? (request) => send({
579
+ ...request,
580
+ init: {
581
+ ...request.init,
582
+ redirect: "manual"
583
+ }
584
+ }) : send,
585
+ /**
586
+ * The error for a response that is a redirect the setting refuses, or `undefined`. Under
587
+ * `"manual"`, Node returns the redirect itself and a browser returns an `opaqueredirect` response.
588
+ * A response that was already followed (`redirected`, from a `fetch` that ignores
589
+ * `init.redirect`) is refused too.
590
+ */
591
+ refusedRedirect: (redirect, response, url) => {
592
+ if (redirect !== "error") return void 0;
593
+ if (response.type !== "opaqueredirect" && !REDIRECT_STATUSES.has(response.status) && response.redirected !== true) return;
594
+ response.body?.cancel().catch(() => {});
595
+ return HttpError.redirect(url, response);
596
+ },
597
+ /** A timeout means the caller stopped waiting and an abort means someone wanted it stopped: neither is retried. */
598
+ isRetryable: (error) => error.kind === "network" || error.kind === "response" && error.status >= 500
599
+ };
600
+ // src/interceptors.ts
601
+ /** @internal */
602
+ var Interceptors = {
603
+ /** A right fold, so the first registered interceptor is outermost. */
604
+ run: (interceptors, request, send) => interceptors.reduceRight((next, interceptor) => (r) => interceptor.intercept(r, next), send)(request),
605
+ /**
606
+ * Builds the request interceptors see: headers normalised to a `Headers` instance. A header the
607
+ * platform rejects (a CR, LF or NUL in a value, say) is a `kind: "request"` error: the request could
608
+ * not be built and nothing was sent, so it is not retried as a network failure. So is an absolute
609
+ * URL that carries credentials (`https://user:password@host/`), which `fetch` refuses; the error's
610
+ * URL leaves the credentials out.
611
+ */
612
+ request: (url, init) => {
613
+ let headers;
115
614
  try {
116
- n = new Headers(t.headers);
117
- } catch (t) {
118
- throw o.request(e, t);
615
+ headers = new Headers(init.headers);
616
+ } catch (e) {
617
+ throw HttpError.request(url, e);
119
618
  }
120
619
  return {
121
- url: e,
620
+ url,
122
621
  init: {
123
- ...t,
124
- headers: n
622
+ ...init,
623
+ headers
125
624
  }
126
625
  };
127
626
  },
128
- fetch: (e) => fetch(e.url, e.init)
129
- }, w = (e) => {
130
- let t = "", n, r, i = [];
131
- for (let a of e.split("\n")) {
132
- if (a === "" || a.startsWith(":")) continue;
133
- let e = a.indexOf(":"), o = e === -1 ? a : a.slice(0, e), s = e === -1 ? "" : a.slice(e + 1);
134
- switch (s.startsWith(" ") && (s = s.slice(1)), o) {
135
- case "event":
136
- t = s;
137
- break;
138
- case "data":
139
- i.push(s);
140
- break;
141
- case "id":
142
- s.includes("\0") || (n = s);
143
- break;
144
- case "retry": /^\d+$/.test(s) && (r = Number.parseInt(s, 10));
627
+ /**
628
+ * The end of the chain: `custom`, or the global `fetch` as it is when the request is sent. Called
629
+ * without a receiver, as the platform `fetch` requires.
630
+ */
631
+ transport: (custom) => (request) => (custom ?? fetch)(request.url, request.init)
632
+ };
633
+ // src/sse.ts
634
+ /** @internal How a block of event-stream text becomes a frame and an event. */
635
+ var SseEvents = {
636
+ /** One block (the text between two blank lines) as a frame. */
637
+ parseBlock: (block) => {
638
+ let event = "";
639
+ let id;
640
+ let retry;
641
+ const data = [];
642
+ for (const line of block.split("\n")) {
643
+ if (line === "" || line.startsWith(":")) continue;
644
+ const colon = line.indexOf(":");
645
+ const field = colon === -1 ? line : line.slice(0, colon);
646
+ let value = colon === -1 ? "" : line.slice(colon + 1);
647
+ if (value.startsWith(" ")) value = value.slice(1);
648
+ switch (field) {
649
+ case "event":
650
+ event = value;
651
+ break;
652
+ case "data":
653
+ data.push(value);
654
+ break;
655
+ case "id":
656
+ if (!value.includes("\0")) id = value;
657
+ break;
658
+ case "retry": if (/^\d+$/.test(value)) retry = Number.parseInt(value, 10);
659
+ }
145
660
  }
661
+ return {
662
+ event: data.length === 0 ? null : {
663
+ event: event || "message",
664
+ data: data.join("\n"),
665
+ ...id !== void 0 ? { id } : {},
666
+ ...retry !== void 0 ? { retry } : {}
667
+ },
668
+ ...id !== void 0 ? { id } : {},
669
+ ...retry !== void 0 ? { retry } : {}
670
+ };
671
+ },
672
+ /**
673
+ * `event` with `id` set to the last event id in effect (the spec's `lastEventId`), which persists
674
+ * across events until the server changes it.
675
+ */
676
+ withLastEventId: (event, lastEventId) => {
677
+ const { id: _blockId, ...rest } = event;
678
+ return lastEventId === void 0 ? rest : {
679
+ ...rest,
680
+ id: lastEventId
681
+ };
146
682
  }
147
- return {
148
- event: i.length === 0 ? null : {
149
- event: t || "message",
150
- data: i.join("\n"),
151
- ...n === void 0 ? {} : { id: n },
152
- ...r === void 0 ? {} : { retry: r }
153
- },
154
- ...n === void 0 ? {} : { id: n },
155
- ...r === void 0 ? {} : { retry: r }
156
- };
157
- }, T = (e, t) => {
158
- let { id: n, ...r } = e;
159
- return t === void 0 ? r : {
160
- ...r,
161
- id: t
162
- };
163
- }, E = class {
683
+ };
684
+ /**
685
+ * Reassembles a byte stream into complete blocks; partial input and split multi-byte characters
686
+ * are buffered. Call `reset` when a new connection begins. With a `limit`, an unterminated block
687
+ * longer than that many characters throws `RangeError` (a hostile or broken server must not make the
688
+ * buffer grow without bound); by default there is no limit.
689
+ *
690
+ * @internal
691
+ */
692
+ var FrameBuffer = class {
164
693
  limit;
165
694
  decoder = new TextDecoder("utf-8");
166
- buffered = "";
167
- constructor(e = Infinity) {
168
- this.limit = e;
169
- }
170
- skipLeadingLF = !1;
171
- push(e) {
172
- let t = this.decoder.decode(e, { stream: !0 });
173
- if (t.length === 0) return [];
174
- this.skipLeadingLF && t.startsWith("\n") && (t = t.slice(1)), this.skipLeadingLF = t.endsWith("\r");
175
- let n = Math.max(0, this.buffered.length - 1);
176
- if (t = this.buffered + t.replace(/\r\n/g, "\n").replace(/\r/g, "\n"), t.indexOf("\n\n", n) === -1) return this.buffered = t, this.checkLimit(), [];
177
- let r = t.split("\n\n");
178
- return this.buffered = r.pop() ?? "", this.checkLimit(), r.map(w);
695
+ /**
696
+ * The unfinished block, in the pieces it arrived in. Joining them only once a block ends keeps a
697
+ * long block that arrives in tiny chunks linear: appending to one string and searching it would
698
+ * copy everything buffered so far on every chunk.
699
+ */
700
+ pieces = [];
701
+ size = 0;
702
+ /** The last character buffered, so a `\n\n` split across two chunks is found. */
703
+ lastChar = "";
704
+ constructor(limit = Infinity) {
705
+ this.limit = limit;
706
+ }
707
+ /** The previous chunk ended in CR: a LF opening the next chunk belongs to that CRLF. */
708
+ skipLeadingLF = false;
709
+ push(chunk) {
710
+ let text = this.decoder.decode(chunk, { stream: true });
711
+ if (text.length === 0) return [];
712
+ if (this.skipLeadingLF && text.startsWith("\n")) text = text.slice(1);
713
+ this.skipLeadingLF = text.endsWith("\r");
714
+ if (text.length === 0) return [];
715
+ text = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
716
+ if (!(text.indexOf("\n\n") !== -1 || this.lastChar === "\n" && text.startsWith("\n"))) {
717
+ this.pieces.push(text);
718
+ this.size += text.length;
719
+ this.lastChar = text[text.length - 1];
720
+ this.checkLimit();
721
+ return [];
722
+ }
723
+ this.pieces.push(text);
724
+ const blocks = this.pieces.join("").split("\n\n");
725
+ const rest = blocks.pop() ?? "";
726
+ this.pieces = rest === "" ? [] : [rest];
727
+ this.size = rest.length;
728
+ this.lastChar = rest === "" ? "" : rest[rest.length - 1];
729
+ this.checkLimit();
730
+ return blocks.map(SseEvents.parseBlock);
179
731
  }
180
732
  reset() {
181
- this.decoder = new TextDecoder("utf-8"), this.buffered = "", this.skipLeadingLF = !1;
733
+ this.decoder = new TextDecoder("utf-8");
734
+ this.pieces = [];
735
+ this.size = 0;
736
+ this.lastChar = "";
737
+ this.skipLeadingLF = false;
182
738
  }
183
739
  checkLimit() {
184
- if (this.buffered.length > this.limit) throw RangeError(`An event block exceeds the ${this.limit}-character limit without ending`);
185
- }
186
- }, D = () => {
187
- let e = new E();
188
- return (n) => n.mapAccumulate(void 0, (n, r) => {
189
- let i = [], a = n;
190
- for (let t of e.push(r)) t.id !== void 0 && (a = t.id), t.event !== null && i.push(T(t.event, a));
191
- return [a, t.from(i)];
740
+ if (this.size > this.limit) throw new RangeError(`An event block exceeds the ${this.limit}-character limit without ending`);
741
+ }
742
+ };
743
+ /**
744
+ * @internal The longest event block (in UTF-16 code units, about 1 MiB of ASCII) buffered while
745
+ * waiting for its terminating blank line. A source that never sends one would otherwise grow the
746
+ * buffer without bound.
747
+ */
748
+ var MAX_BLOCK_CHARS = 1048576;
749
+ /**
750
+ * A stream transformation that decodes raw response bytes into {@link ServerSentEvent}s, buffering
751
+ * partial input across chunks. Single-use: each application maintains its own decoding state.
752
+ *
753
+ * A block that passes `maxBlockChars` without ending fails the stream with a `RangeError` defect:
754
+ * the input is not an event stream this decoder can read, and the surrounding error type `E` has no
755
+ * case for it.
756
+ *
757
+ * @typeParam E - The error type carried by the surrounding stream.
758
+ * @param options - `maxBlockChars`: the longest block buffered (default 1,048,576).
759
+ * @returns A pipe from a byte stream to a stream of parsed events.
760
+ * @throws {RangeError} If `maxBlockChars` is not a positive integer or `Infinity`.
761
+ */
762
+ var decodeEvents = (options = {}) => {
763
+ const limit = options.maxBlockChars ?? 1048576;
764
+ if (limit !== Infinity && !(Number.isInteger(limit) && limit > 0)) throw new RangeError(`decodeEvents: maxBlockChars must be a positive integer or Infinity, got ${limit}`);
765
+ const frames = new FrameBuffer(limit);
766
+ return (bytes) => bytes.mapAccumulate(void 0, (lastEventId, chunk) => {
767
+ const events = [];
768
+ let current = lastEventId;
769
+ for (const frame of frames.push(chunk)) {
770
+ if (frame.id !== void 0) current = frame.id;
771
+ if (frame.event !== null) events.push(SseEvents.withLastEventId(frame.event, current));
772
+ }
773
+ return [current, List.from(events)];
192
774
  });
193
- }, O = 100, k = 2147483647, A = 1048576, j = (e) => Array.from(new TextEncoder().encode(e), (e) => String.fromCharCode(e)).join(""), M = (t) => e.promise((e) => new Promise((n) => {
194
- let r = () => {
195
- clearTimeout(i), n();
196
- }, i = setTimeout(() => {
197
- e.removeEventListener("abort", r), n();
198
- }, Math.min(t, k));
199
- e.addEventListener("abort", r, { once: !0 });
200
- })), N = class {
775
+ };
776
+ // src/sse-client.ts
777
+ /** A server-sent `retry:` below this is raised to it, so a misbehaving server cannot force a tight loop. */
778
+ var MIN_SERVER_RETRY_MS = 100;
779
+ /** Largest delay `setTimeout` honours; anything above it (or Infinity) fires after ~1ms. */
780
+ var MAX_DELAY_MS = 2147483647;
781
+ /**
782
+ * Carried across reconnections within one run. Owns the one `AbortController` every connection
783
+ * of the run is opened with, linked once to the run's signal; a connection registers a single
784
+ * listener on it and removes it when closed, so listeners stay bounded however long the run lasts.
785
+ */
786
+ var SseSession = class {
201
787
  controller = new AbortController();
202
- frames = new E(A);
788
+ /** Reaching the block limit fails the stream with `kind: "decode"`, which is not retried. */
789
+ frames = new FrameBuffer(MAX_BLOCK_CHARS);
790
+ /**
791
+ * Frames parsed but not yet handled, read from `next` on: a chunk can hold hundreds of thousands
792
+ * of frames, and `Array.shift()` on each would cost time quadratic in the chunk size.
793
+ */
203
794
  pending = [];
795
+ next = 0;
204
796
  lastEventId = void 0;
205
797
  retryMs;
798
+ /** The server's `retry:` value, once received: the delay, or with a `Schedule` a lower bound of it. */
206
799
  serverRetryMs = void 0;
800
+ /** Consecutive reconnects since the last delivered event. */
207
801
  reconnects = 0;
802
+ /** The status of the current connection, for an error raised while reading it. */
208
803
  status = 200;
209
804
  connection = null;
210
805
  unlinkParent;
211
- constructor(e, t) {
212
- this.retryMs = e;
213
- let n = () => this.controller.abort(t.reason);
214
- t.addEventListener("abort", n, { once: !0 }), this.unlinkParent = () => t.removeEventListener("abort", n);
806
+ constructor(retryMs, parent) {
807
+ this.retryMs = retryMs;
808
+ const onAbort = () => this.controller.abort(parent.reason);
809
+ parent.addEventListener("abort", onAbort, { once: true });
810
+ this.unlinkParent = () => parent.removeEventListener("abort", onAbort);
215
811
  }
216
812
  get reader() {
217
813
  return this.connection?.reader ?? null;
218
814
  }
219
- attach(e, t) {
220
- this.status = t;
221
- let n = () => e.cancel().catch(() => {});
222
- this.controller.signal.addEventListener("abort", n, { once: !0 }), this.connection = {
223
- reader: e,
224
- unlink: () => this.controller.signal.removeEventListener("abort", n)
225
- }, this.frames.reset();
815
+ attach(reader, status) {
816
+ this.status = status;
817
+ const onAbort = () => reader.cancel().catch(() => {});
818
+ this.controller.signal.addEventListener("abort", onAbort, { once: true });
819
+ this.connection = {
820
+ reader,
821
+ unlink: () => this.controller.signal.removeEventListener("abort", onAbort)
822
+ };
823
+ this.frames.reset();
226
824
  }
227
825
  closeConnection() {
228
- this.connection &&= (this.connection.unlink(), this.connection.reader.cancel().catch(() => {}), null);
826
+ if (this.connection) {
827
+ this.connection.unlink();
828
+ this.connection.reader.cancel().catch(() => {});
829
+ this.connection = null;
830
+ }
229
831
  }
230
832
  close() {
231
- this.closeConnection(), this.unlinkParent(), this.controller.abort();
232
- }
233
- }, P = (e) => e.split(";")[0].trim().toLowerCase(), F = { stream: (t) => {
234
- let { url: i, headers: a, defaultHeaders: s, credentials: c, interceptors: l, reconnect: u, retry: d } = t, p = (t) => {
235
- let n = f.prepare("GET", {
236
- headers: {
237
- ...a,
238
- accept: "text/event-stream",
239
- ...t.lastEventId ? { "last-event-id": j(t.lastEventId) } : {}
240
- },
241
- credentials: c
242
- }, {
243
- headers: s,
244
- credentials: c
245
- });
246
- return e.lift(() => C.run(l, C.request(i, {
247
- ...n,
248
- cache: "no-store",
249
- signal: t.controller.signal
250
- }), C.fetch), (e) => S.error(e, i)).flatMap((t) => t.ok ? e.of(t) : b.readFailure(t, "text", i)).flatMap((t) => {
251
- if (t.status === 204) return t.body?.cancel().catch(() => {}), e.of(null);
252
- let n = t.headers.get("content-type");
253
- return n !== null && P(n) !== "text/event-stream" ? (t.body?.cancel().catch(() => {}), e.fail(b.error(`Expected text/event-stream, got ${n}`, i, t))) : t.body === null ? e.fail(b.error("Response has no body", i, t)) : e.of({
254
- reader: t.body.getReader(),
255
- status: t.status
833
+ this.closeConnection();
834
+ this.unlinkParent();
835
+ this.controller.abort();
836
+ }
837
+ };
838
+ /** @internal */
839
+ var SseClient = {
840
+ /** The `Last-Event-ID` value is the id UTF-8 encoded, byte for byte, as the EventSource spec sends it. */
841
+ utf8ByteString: (id) => Array.from(new TextEncoder().encode(id), (b) => String.fromCharCode(b)).join(""),
842
+ /** A cancellable sleep. The abort listener is removed when the timer fires, so waits do not accumulate listeners. */
843
+ delay: (ms) => IO.promise((signal) => new Promise((resolve) => {
844
+ const onAbort = () => {
845
+ clearTimeout(timer);
846
+ resolve();
847
+ };
848
+ const timer = setTimeout(() => {
849
+ signal.removeEventListener("abort", onAbort);
850
+ resolve();
851
+ }, Math.min(ms, MAX_DELAY_MS));
852
+ signal.addEventListener("abort", onAbort, { once: true });
853
+ })),
854
+ /** The media type of a `Content-Type` value, without its parameters. */
855
+ mediaType: (contentType) => contentType.split(";")[0].trim().toLowerCase(),
856
+ /** The events of a server-sent-events stream, reconnecting as `config` says. */
857
+ stream: (config) => {
858
+ const { url, headers, defaultHeaders, credentials, interceptors, transport, redirect, maxBodyBytes, reconnect, retry } = config;
859
+ /** The reader for a new connection, or `null` when the server answered 204 ("stop reconnecting"). */
860
+ const open = (session) => {
861
+ const prepared = HttpRequest.prepare("GET", {
862
+ headers: {
863
+ ...headers,
864
+ accept: "text/event-stream",
865
+ ...session.lastEventId ? { "last-event-id": SseClient.utf8ByteString(session.lastEventId) } : {}
866
+ },
867
+ credentials
868
+ }, {
869
+ headers: defaultHeaders,
870
+ credentials
256
871
  });
257
- });
258
- }, m = (t) => e.lift(() => t.read(), (e) => S.error(e, i)), h = e.of(n.empty()), g = (e, t) => {
259
- if (u === !1) return t;
260
- let n = e.reconnects + 1;
261
- if (u !== !0 && !u.allowsAttempt(n)) return t;
262
- let r = e.serverRetryMs ?? (u === !0 ? e.retryMs : u.delayAfter(n));
263
- return e.reconnects = n, M(r).flatMap(() => _(e));
264
- }, _ = (t) => {
265
- for (; t.pending.length > 0;) {
266
- let r = t.pending.shift();
267
- if (r.id !== void 0 && (t.lastEventId = r.id), r.retry !== void 0 && (t.serverRetryMs = Math.max(r.retry, O)), r.event !== null) return t.reconnects = 0, e.of(n.of([T(r.event, t.lastEventId), t]));
268
- }
269
- let r = t.reader;
270
- return r === null ? p(t).foldM((n) => S.isRetryable(n) ? g(t, e.fail(n)) : e.fail(n), (e) => e === null ? h : (t.attach(e.reader, e.status), _(t))) : m(r).foldM((n) => (t.closeConnection(), S.isRetryable(n) ? g(t, e.fail(n)) : e.fail(n)), (n) => {
271
- if (n.done) return t.closeConnection(), g(t, h);
272
- let r;
273
- try {
274
- r = t.frames.push(n.value);
275
- } catch (n) {
276
- return t.closeConnection(), e.fail(new o(t.status, String(n.message), null, i, void 0, "decode", n));
872
+ return IO.lift(() => Interceptors.run(interceptors, Interceptors.request(url, {
873
+ ...prepared,
874
+ ...HttpTransport.redirectInit(redirect),
875
+ cache: "no-store",
876
+ signal: session.controller.signal
877
+ }), HttpTransport.enforceRedirect(redirect, transport)), (e) => HttpTransport.error(e, url)).flatMap((response) => {
878
+ const refused = HttpTransport.refusedRedirect(redirect, response, url);
879
+ if (refused !== void 0) return IO.fail(refused);
880
+ return response.ok ? IO.of(response) : HttpResponse.readFailure(response, "text", url, maxBodyBytes);
881
+ }).flatMap((response) => {
882
+ if (response.status === 204) {
883
+ response.body?.cancel().catch(() => {});
884
+ return IO.of(null);
885
+ }
886
+ const contentType = response.headers.get("content-type");
887
+ if (contentType !== null && SseClient.mediaType(contentType) !== "text/event-stream") {
888
+ response.body?.cancel().catch(() => {});
889
+ return IO.fail(HttpResponse.error(`Expected text/event-stream, got ${contentType}`, url, response));
890
+ }
891
+ return response.body === null ? IO.fail(HttpResponse.error("Response has no body", url, response)) : IO.of({
892
+ reader: response.body.getReader(),
893
+ status: response.status
894
+ });
895
+ });
896
+ };
897
+ const readChunk = (reader) => IO.lift(() => reader.read(), (e) => HttpTransport.error(e, url));
898
+ const done = IO.of(Option.empty());
899
+ /**
900
+ * Reconnects after the scheduled delay, or gives up (`giveUp`) when reconnection is off or the
901
+ * `Schedule` allows no further attempt. A server `retry:` value, once received, is the delay.
902
+ */
903
+ const reconnectOr = (session, giveUp) => {
904
+ if (reconnect === false) return giveUp;
905
+ const made = session.reconnects + 1;
906
+ if (reconnect !== true && !reconnect.allowsAttempt(made)) return giveUp;
907
+ const ms = reconnect === true ? session.serverRetryMs ?? session.retryMs : Math.max(session.serverRetryMs ?? 0, reconnect.delayAfter(made));
908
+ session.reconnects = made;
909
+ return SseClient.delay(ms).flatMap(() => step(session));
910
+ };
911
+ const step = (session) => {
912
+ while (session.next < session.pending.length) {
913
+ const frame = session.pending[session.next++];
914
+ if (frame.id !== void 0) session.lastEventId = frame.id;
915
+ if (frame.retry !== void 0) session.serverRetryMs = Math.max(frame.retry, MIN_SERVER_RETRY_MS);
916
+ if (frame.event !== null) {
917
+ session.reconnects = 0;
918
+ return IO.of(Option.of([SseEvents.withLastEventId(frame.event, session.lastEventId), session]));
919
+ }
277
920
  }
278
- for (let e of r) t.pending.push(e);
279
- return _(t);
280
- });
281
- };
282
- return r.bracket(e.promise(async (e) => new N(d, e)), (e) => r.unfoldEval(e, _), (t) => e.sync(() => t.close()));
283
- } }, I = class {
921
+ session.pending = [];
922
+ session.next = 0;
923
+ const reader = session.reader;
924
+ if (reader === null) return open(session).foldM((error) => HttpTransport.isRetryable(error) ? reconnectOr(session, IO.fail(error)) : IO.fail(error), (opened) => {
925
+ if (opened === null) return done;
926
+ session.attach(opened.reader, opened.status);
927
+ return step(session);
928
+ });
929
+ return readChunk(reader).foldM((error) => {
930
+ session.closeConnection();
931
+ return HttpTransport.isRetryable(error) ? reconnectOr(session, IO.fail(error)) : IO.fail(error);
932
+ }, (result) => {
933
+ if (result.done) {
934
+ session.closeConnection();
935
+ return reconnectOr(session, done);
936
+ }
937
+ let frames;
938
+ try {
939
+ frames = session.frames.push(result.value);
940
+ } catch (e) {
941
+ session.closeConnection();
942
+ return IO.fail(new HttpError(session.status, String(e.message), null, url, void 0, "decode", e));
943
+ }
944
+ for (const frame of frames) if (frame.event !== null || frame.id !== void 0 || frame.retry !== void 0) session.pending.push(frame);
945
+ return step(session);
946
+ });
947
+ };
948
+ return Stream.bracket(IO.promise(async (signal) => new SseSession(retry, signal)), (session) => Stream.unfoldEval(session, step), (session) => IO.sync(() => session.close()));
949
+ }
950
+ };
951
+ // src/http-client.ts
952
+ /**
953
+ * A composable HTTP client that wraps the native `fetch` API, returning `IO` instances instead of
954
+ * Promises. Each instance carries its own configuration (base URL, interceptors, default headers,
955
+ * timeout, credentials), so different parts of an application can use independently configured
956
+ * clients.
957
+ *
958
+ * Three kinds of call, by what you want back:
959
+ * - **the decoded body** — `get`, `post`, `put`, `patch`, `delete`, `fetch` return
960
+ * `IO<HttpError, A>`. A response with no body (`204`, an empty `200`) fails with
961
+ * `kind: "decode"`, since a value was expected; pass `{ empty: "option" }` when absence is
962
+ * legitimate, to get `IO<HttpError, Option<A>>`.
963
+ * - **nothing** — `send(method, uri, { body })` returns `IO<HttpError, void>` for actions whose
964
+ * response body you do not read (publish, archive, leave …); any body, or none, is fine.
965
+ * - **the `Response`** — `raw(method, uri, options?)` returns `IO<HttpError, Response>` for
966
+ * status codes, headers or streaming.
967
+ *
968
+ * Every non-2xx response fails with `kind: "response"`, whichever you use. Cancellation is
969
+ * supported: when the IO is cancelled (via a fiber or `timeout`), the underlying `fetch` is
970
+ * aborted through its `AbortSignal`.
971
+ *
972
+ * `A` is what you claim the body is; the JSON is not checked unless you pass a `transform` that
973
+ * validates it (a schema's `parse`, say) — a throw there fails with `kind: "decode"`.
974
+ *
975
+ * **Default credentials:** `same-origin`, matching the platform `fetch` default. Set
976
+ * `credentials: "include"` explicitly per-client or per-request if you need cookies to flow
977
+ * cross-origin.
978
+ *
979
+ * @example
980
+ * const api = new HttpClient({
981
+ * baseUrl: "https://api.example.com",
982
+ * interceptors: [authInterceptor],
983
+ * timeout: 5000,
984
+ * });
985
+ *
986
+ * const users = api.get<User[]>("/users"); // IO<HttpError, User[]>
987
+ * const avatar = api.get<Avatar>("/me/avatar", { empty: "option" }); // IO<HttpError, Option<Avatar>>
988
+ * const leave = api.send("POST", `/communities/${slug}/leave`); // IO<HttpError, void>
989
+ */
990
+ var HttpClient = class HttpClient {
284
991
  interceptors;
285
992
  baseUrl;
286
993
  defaultHeaders;
287
994
  defaultTimeout;
288
995
  defaultCredentials;
289
- constructor(e = {}) {
290
- this.interceptors = Object.freeze([...e.interceptors ?? []]), this.baseUrl = e.baseUrl, this.defaultHeaders = e.defaultHeaders ?? {}, this.defaultTimeout = e.timeout, this.defaultCredentials = e.credentials ?? "same-origin";
996
+ defaultRedirect;
997
+ defaultMaxBodyBytes;
998
+ allowedOrigins;
999
+ transport;
1000
+ /**
1001
+ * Creates a new HttpClient with the given configuration.
1002
+ *
1003
+ * @param {HttpClientConfig} config - Configuration for the client.
1004
+ */
1005
+ constructor(config = {}) {
1006
+ this.interceptors = Object.freeze([...config.interceptors ?? []]);
1007
+ this.baseUrl = config.baseUrl;
1008
+ this.defaultHeaders = config.defaultHeaders ?? {};
1009
+ this.defaultTimeout = config.timeout;
1010
+ this.defaultCredentials = config.credentials ?? "same-origin";
1011
+ this.allowedOrigins = config.allowedOrigins === void 0 ? void 0 : HttpUrl.originsOf(config.allowedOrigins);
1012
+ if (this.allowedOrigins !== void 0 && this.baseUrl !== void 0) {
1013
+ if (!HttpUrl.allowedOrigin(this.baseUrl, this.allowedOrigins)) throw new RangeError(`HttpClient: the baseUrl's origin must be in allowedOrigins, got ${this.baseUrl}`);
1014
+ }
1015
+ this.defaultRedirect = this.redirectOf(config.redirect);
1016
+ this.defaultMaxBodyBytes = HttpClient.checkMaxBodyBytes(config.maxBodyBytes);
1017
+ this.transport = HttpTransport.guardUrl(Interceptors.transport(config.fetch), this.allowedOrigins);
291
1018
  }
292
- get(e, t = {}) {
293
- return this.request(e, "GET", t);
1019
+ get(uri, options = {}) {
1020
+ return this.request(uri, "GET", options);
294
1021
  }
295
- post(e, t, n = {}) {
296
- return this.request(e, "POST", {
297
- ...n,
298
- body: t
1022
+ post(uri, body, options = {}) {
1023
+ return this.request(uri, "POST", {
1024
+ ...options,
1025
+ body
299
1026
  });
300
1027
  }
301
- put(e, t, n = {}) {
302
- return this.request(e, "PUT", {
303
- ...n,
304
- body: t
1028
+ put(uri, body, options = {}) {
1029
+ return this.request(uri, "PUT", {
1030
+ ...options,
1031
+ body
305
1032
  });
306
1033
  }
307
- patch(e, t, n = {}) {
308
- return this.request(e, "PATCH", {
309
- ...n,
310
- body: t
1034
+ patch(uri, body, options = {}) {
1035
+ return this.request(uri, "PATCH", {
1036
+ ...options,
1037
+ body
311
1038
  });
312
1039
  }
313
- delete(e, t = {}) {
314
- return this.request(e, "DELETE", t);
1040
+ delete(uri, options = {}) {
1041
+ return this.request(uri, "DELETE", options);
315
1042
  }
316
- fetch(e, t, n = {}) {
317
- return this.request(e, t, n);
1043
+ fetch(uri, method, options = {}) {
1044
+ return this.request(uri, method, options);
318
1045
  }
319
- send(t, n, r) {
320
- let i = this.resolveUrl(n), a = r ?? {};
321
- return this.withTimeout(i, a.timeout, this.exchange(i, t, a).flatMap((t) => t.ok ? e.sync(() => void t.body?.cancel().catch(() => {})) : b.readFailure(t, "json", i)));
1046
+ /**
1047
+ * Performs a request whose response body you do not need — an action such as publish,
1048
+ * archive or leave. Succeeds with `void` for any 2xx, with or without a body (which is
1049
+ * discarded); a non-2xx response fails with `kind: "response"` and its body.
1050
+ *
1051
+ * @param {Method} method - The HTTP method.
1052
+ * @param {string} uri - The URL or path to request.
1053
+ * @param {SendOptions} [options] - Headers, credentials, timeout and body. Every key must be one of
1054
+ * `SendOptions`: a payload passed here by mistake (`send("POST", url, article)`) is rejected at
1055
+ * compile time; it belongs in `{ body: article }`. A `GET` or `HEAD` request with a body throws
1056
+ * `TypeError` where it is built.
1057
+ * @returns {IO<HttpError, void>}
1058
+ *
1059
+ * @example
1060
+ * client.send("POST", `/api/v1/communities/${slug}/leave`);
1061
+ * client.send("PUT", `/api/v1/articles/${id}`, { body: article });
1062
+ * client.send("DELETE", `/api/v1/passkeys/${id}`, { headers: { "X-Step-Up": token } });
1063
+ */
1064
+ send(method, uri, options) {
1065
+ const url = this.resolveUrl(uri);
1066
+ const refused = HttpUrl.refuseUrl(url, this.allowedOrigins);
1067
+ if (refused !== void 0) return IO.fail(HttpErrorFields.withMethod(refused, method));
1068
+ const opts = options ?? {};
1069
+ const maxBodyBytes = this.maxBodyBytes(opts);
1070
+ return this.withTimeout(url, opts.timeout, this.exchange(url, method, opts).flatMap((response) => response.ok ? IO.sync(() => void response.body?.cancel().catch(() => {})) : HttpResponse.readFailure(response, "json", url, maxBodyBytes))).mapErr((e) => HttpErrorFields.withMethod(e, method));
322
1071
  }
323
- raw(t, n, r) {
324
- let i = this.resolveUrl(n), a = r ?? {};
325
- return this.withTimeout(i, a.timeout, this.exchange(i, t, a).flatMap((t) => t.ok ? e.of(t) : b.readFailure(t, "json", i)));
1072
+ /**
1073
+ * Performs a request and yields the `Response` itself, for status codes, headers or streaming.
1074
+ * A non-2xx response still fails with `kind: "response"` (its body read into the error); a 2xx
1075
+ * `Response` is returned unread. When you only need the status or headers, cancel the body
1076
+ * (`response.body?.cancel()`) so the connection is released; `send` does this for you.
1077
+ *
1078
+ * @param {Method} method - The HTTP method.
1079
+ * @param {string} uri - The URL or path to request.
1080
+ * @param {SendOptions} [options] - Headers, credentials, timeout and body; every key must be one of
1081
+ * `SendOptions`, as for `send`.
1082
+ * @returns {IO<HttpError, Response>}
1083
+ *
1084
+ * @example
1085
+ * client.raw("POST", "/api/v1/communities", { body: input }).map((r) => r.headers.get("Location"));
1086
+ */
1087
+ raw(method, uri, options) {
1088
+ const url = this.resolveUrl(uri);
1089
+ const refused = HttpUrl.refuseUrl(url, this.allowedOrigins);
1090
+ if (refused !== void 0) return IO.fail(HttpErrorFields.withMethod(refused, method));
1091
+ const opts = options ?? {};
1092
+ const maxBodyBytes = this.maxBodyBytes(opts);
1093
+ return this.withTimeout(url, opts.timeout, this.exchange(url, method, opts).flatMap((response) => response.ok ? IO.of(response) : HttpResponse.readFailure(response, "json", url, maxBodyBytes))).mapErr((e) => HttpErrorFields.withMethod(e, method));
326
1094
  }
327
- sse(e, t = {}) {
328
- if (t.retry !== void 0 && !(t.retry >= 0)) throw RangeError(`HttpClient.sse: retry must be a non-negative number of milliseconds, got ${t.retry}`);
329
- return F.stream({
330
- url: this.resolveUrl(e),
331
- headers: t.headers ?? {},
1095
+ /**
1096
+ * Opens a server-sent-events stream and emits each {@link ServerSentEvent} as it arrives.
1097
+ *
1098
+ * The request goes through the same pipeline as every other method, so headers (including
1099
+ * `Authorization`), credentials, interceptors, and the base URL all apply. No request timeout is
1100
+ * used — the connection is long-lived. Cancelling the terminal `IO` (via `fork`/`timeout`) aborts
1101
+ * the connection and releases resources.
1102
+ *
1103
+ * By default the stream reconnects automatically when the connection ends or fails with a
1104
+ * retryable error (network error or `5xx`), resuming with `Last-Event-ID` and re-applying headers
1105
+ * and credentials on each attempt; terminal `4xx` responses (including auth failures) end the
1106
+ * stream. See {@link SseOptions} to configure or disable this.
1107
+ *
1108
+ * @param {string} uri - The URL or path to connect to.
1109
+ * @param {SseOptions} [options] - Headers, credentials, and reconnection settings.
1110
+ * @returns {Stream<HttpError, ServerSentEvent>} A stream of parsed events.
1111
+ * @throws {RangeError} If `options.retry` is negative or `NaN`.
1112
+ *
1113
+ * @example
1114
+ * const events = client.sse("/events", { headers: { Authorization: `Bearer ${token}` } });
1115
+ * await events.runForEach((event) => IO.sync(() => handle(event))).unsafeRun();
1116
+ */
1117
+ sse(uri, options = {}) {
1118
+ if (options.retry !== void 0 && !(options.retry >= 0)) throw new RangeError(`HttpClient.sse: retry must be a non-negative number of milliseconds, got ${options.retry}`);
1119
+ const url = this.resolveUrl(uri);
1120
+ const refused = HttpUrl.refuseUrl(url, this.allowedOrigins);
1121
+ if (refused !== void 0) return Stream.eval(IO.fail(HttpErrorFields.withMethod(refused, "GET")));
1122
+ return SseClient.stream({
1123
+ url,
1124
+ headers: options.headers ?? {},
332
1125
  defaultHeaders: this.defaultHeaders,
333
- credentials: t.credentials ?? this.defaultCredentials,
1126
+ credentials: options.credentials ?? this.defaultCredentials,
334
1127
  interceptors: this.interceptors,
335
- reconnect: t.reconnect ?? !0,
336
- retry: t.retry ?? 3e3
337
- });
1128
+ transport: this.transport,
1129
+ redirect: this.redirectOf(options.redirect ?? this.defaultRedirect),
1130
+ maxBodyBytes: this.defaultMaxBodyBytes,
1131
+ reconnect: options.reconnect ?? true,
1132
+ retry: options.retry ?? 3e3
1133
+ }).mapErr((e) => HttpErrorFields.withMethod(e, "GET"));
1134
+ }
1135
+ /** A `maxBodyBytes` setting, or a `RangeError` when it is not a positive integer or `Infinity`. */
1136
+ static checkMaxBodyBytes(limit) {
1137
+ if (limit !== void 0 && limit !== Infinity && !(Number.isInteger(limit) && limit > 0)) throw new RangeError(`HttpClient: maxBodyBytes must be a positive integer or Infinity, got ${limit}`);
1138
+ return limit;
1139
+ }
1140
+ /**
1141
+ * The `redirect` setting a request runs under: `"error"` under `allowedOrigins`, where `"follow"`
1142
+ * throws `RangeError`, since `fetch` would send the request, its headers and its body to every
1143
+ * origin on the way before the client could see where it ended.
1144
+ */
1145
+ redirectOf(redirect) {
1146
+ if (this.allowedOrigins === void 0) return redirect;
1147
+ if (redirect === "follow") throw new RangeError("HttpClient: redirect \"follow\" cannot be used with allowedOrigins");
1148
+ return "error";
1149
+ }
1150
+ /** The request's limit, else the client's; checked where the request is built. */
1151
+ maxBodyBytes(options) {
1152
+ return HttpClient.checkMaxBodyBytes(options.maxBodyBytes) ?? this.defaultMaxBodyBytes;
338
1153
  }
339
- resolveUrl(e) {
340
- return !this.baseUrl || /^[a-z][a-z\d+.-]*:\/\//i.test(e) || /^(data|blob):/i.test(e) ? e : `${this.baseUrl.endsWith("/") ? this.baseUrl.slice(0, -1) : this.baseUrl}${e.startsWith("/") ? e : `/${e}`}`;
1154
+ resolveUrl(uri) {
1155
+ if (!this.baseUrl || /^[a-z][a-z\d+.-]*:\/\//i.test(uri) || /^(data|blob):/i.test(uri)) return uri;
1156
+ const base = this.baseUrl.endsWith("/") ? this.baseUrl.slice(0, -1) : this.baseUrl;
1157
+ const path = uri.startsWith("/") ? uri : `/${uri}`;
1158
+ return base === "" ? path.replace(/^[/\\\t\n\r]+/, "/") : `${base}${path}`;
341
1159
  }
342
- exchange(t, n, r) {
343
- if ((n === "GET" || n === "HEAD") && r.body != null) throw TypeError(`A ${n} request cannot have a body (${t})`);
344
- let i = {
1160
+ /** Prepares the request, runs it through the interceptors and `fetch`, and yields the `Response`. */
1161
+ exchange(url, method, options) {
1162
+ if ((method === "GET" || method === "HEAD") && options.body != null) throw new TypeError(`A ${method} request cannot have a body (${url})`);
1163
+ const defaults = {
345
1164
  headers: this.defaultHeaders,
346
1165
  credentials: this.defaultCredentials
347
1166
  };
348
- return e.lift(() => f.prepare(n, r, i), (e) => o.request(t, e)).flatMap((n) => e.cancellable((e) => C.run(this.interceptors, C.request(t, {
349
- ...n,
350
- signal: e
351
- }), C.fetch), (e) => S.error(e, t)));
1167
+ const redirect = this.redirectOf(options.redirect ?? this.defaultRedirect);
1168
+ return IO.lift(() => HttpRequest.prepare(method, options, defaults), (e) => HttpError.request(url, e)).flatMap((prepared) => IO.cancellable((signal) => Interceptors.run(this.interceptors, Interceptors.request(url, {
1169
+ ...prepared,
1170
+ ...HttpTransport.redirectInit(redirect),
1171
+ signal
1172
+ }), HttpTransport.enforceRedirect(redirect, this.transport)), (e) => HttpTransport.error(e, url)).flatMap((response) => {
1173
+ const refused = HttpTransport.refusedRedirect(redirect, response, url);
1174
+ return refused === void 0 ? IO.of(response) : IO.fail(refused);
1175
+ }));
352
1176
  }
353
- withTimeout(e, t, n) {
354
- let r = t ?? this.defaultTimeout;
355
- return r == null ? n : n.timeout(r, () => o.timeout(e, r));
1177
+ withTimeout(url, timeout, io) {
1178
+ const ms = timeout ?? this.defaultTimeout;
1179
+ return ms == null ? io : io.timeout(ms, () => HttpError.timeout(url, ms));
356
1180
  }
357
- request(t, r, i) {
358
- let a = this.resolveUrl(t), { responseType: s = "json", transform: c = (e) => e, empty: l = "error" } = i;
359
- return this.withTimeout(a, i.timeout, this.exchange(a, r, i).flatMap((t) => t.ok ? b.read(t, s, a, r).flatMap((r) => r === _ ? l === "option" ? e.of(n.empty()) : e.fail(o.decode(a, t, `expected a response body, got none (status ${t.status}); use send() or { empty: "option" }`)) : e.lift(() => c(r), (e) => o.decode(a, t, e)).map((e) => l === "option" ? n.ofNullable(e) : e)) : b.readFailure(t, s, a)));
1181
+ request(uri, method, options) {
1182
+ const url = this.resolveUrl(uri);
1183
+ const refused = HttpUrl.refuseUrl(url, this.allowedOrigins);
1184
+ if (refused !== void 0) return IO.fail(HttpErrorFields.withMethod(refused, method));
1185
+ const { responseType = "json", transform = (data) => data, empty = "error" } = options;
1186
+ const maxBodyBytes = this.maxBodyBytes(options);
1187
+ const decode = (response) => response.ok ? HttpResponse.read(response, responseType, url, method, maxBodyBytes).flatMap((parsed) => {
1188
+ if (parsed === NO_BODY) return empty === "option" ? IO.of(Option.empty()) : IO.fail(HttpError.decode(url, response, `expected a response body, got none (status ${response.status}); use send() or { empty: "option" }`));
1189
+ return IO.lift(() => transform(parsed), (e) => HttpError.decode(url, response, e)).map((value) => empty === "option" ? Option.ofNullable(value) : value);
1190
+ }) : HttpResponse.readFailure(response, responseType, url, maxBodyBytes);
1191
+ return this.withTimeout(url, options.timeout, this.exchange(url, method, options).flatMap(decode)).mapErr((e) => HttpErrorFields.withMethod(e, method));
360
1192
  }
361
1193
  };
362
- export { I as HttpClient, o as HttpError, D as decodeEvents };
1194
+ export { HttpClient, HttpError, decodeEvents };
363
1195
 
364
1196
  //# sourceMappingURL=monadyssey-fetch.mjs.map