@openstage/monadyssey-fetch 3.0.0-rc.1 → 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.
@@ -16,10 +16,35 @@ export declare type Credentials = "omit" | "same-origin" | "include";
16
16
  * A stream transformation that decodes raw response bytes into {@link ServerSentEvent}s, buffering
17
17
  * partial input across chunks. Single-use: each application maintains its own decoding state.
18
18
  *
19
+ * A block that passes `maxBlockChars` without ending fails the stream with a `RangeError` defect:
20
+ * the input is not an event stream this decoder can read, and the surrounding error type `E` has no
21
+ * case for it.
22
+ *
19
23
  * @typeParam E - The error type carried by the surrounding stream.
24
+ * @param options - `maxBlockChars`: the longest block buffered (default 1,048,576).
20
25
  * @returns A pipe from a byte stream to a stream of parsed events.
26
+ * @throws {RangeError} If `maxBlockChars` is not a positive integer or `Infinity`.
27
+ */
28
+ export declare const decodeEvents: <E>(options?: DecodeEventsOptions) => Pipe<E, Uint8Array, ServerSentEvent>;
29
+
30
+ /** Options for {@link decodeEvents}. */
31
+ export declare interface DecodeEventsOptions {
32
+ /**
33
+ * The longest event block, in characters, buffered while waiting for its end. A positive
34
+ * integer or `Infinity`; defaults to 1,048,576, the limit `sse()` uses.
35
+ */
36
+ readonly maxBlockChars?: number;
37
+ }
38
+
39
+ /**
40
+ * `T` restricted to the keys of `Shape`: every other key is typed `never`, so an object with an extra
41
+ * key is rejected even when it is a variable rather than a literal. `send` / `raw` take their options
42
+ * this way, so a payload passed positionally (`send("POST", url, article)`, where `article` happens to
43
+ * have a `body` key) does not type-check as the options.
21
44
  */
22
- export declare const decodeEvents: <E>() => Pipe<E, Uint8Array, ServerSentEvent>;
45
+ declare type Exact<T, Shape> = T & {
46
+ [K in Exclude<keyof T, keyof Shape>]: never;
47
+ };
23
48
 
24
49
  /**
25
50
  * A composable HTTP client that wraps the native `fetch` API, returning `IO` instances instead of
@@ -65,6 +90,10 @@ export declare class HttpClient {
65
90
  private readonly defaultHeaders;
66
91
  private readonly defaultTimeout;
67
92
  private readonly defaultCredentials;
93
+ private readonly defaultRedirect;
94
+ private readonly defaultMaxBodyBytes;
95
+ private readonly allowedOrigins;
96
+ private readonly transport;
68
97
  /**
69
98
  * Creates a new HttpClient with the given configuration.
70
99
  *
@@ -143,8 +172,10 @@ export declare class HttpClient {
143
172
  *
144
173
  * @param {Method} method - The HTTP method.
145
174
  * @param {string} uri - The URL or path to request.
146
- * @param {SendOptions} [options] - Headers, credentials, timeout and body. A `GET` or `HEAD`
147
- * request with a body throws `TypeError` where it is built.
175
+ * @param {SendOptions} [options] - Headers, credentials, timeout and body. Every key must be one of
176
+ * `SendOptions`: a payload passed here by mistake (`send("POST", url, article)`) is rejected at
177
+ * compile time; it belongs in `{ body: article }`. A `GET` or `HEAD` request with a body throws
178
+ * `TypeError` where it is built.
148
179
  * @returns {IO<HttpError, void>}
149
180
  *
150
181
  * @example
@@ -152,7 +183,7 @@ export declare class HttpClient {
152
183
  * client.send("PUT", `/api/v1/articles/${id}`, { body: article });
153
184
  * client.send("DELETE", `/api/v1/passkeys/${id}`, { headers: { "X-Step-Up": token } });
154
185
  */
155
- send(method: Method, uri: string, options?: SendOptions): IO<HttpError, void>;
186
+ send<O extends SendOptions>(method: Method, uri: string, options?: Exact<O, SendOptions>): IO<HttpError, void>;
156
187
  /**
157
188
  * Performs a request and yields the `Response` itself, for status codes, headers or streaming.
158
189
  * A non-2xx response still fails with `kind: "response"` (its body read into the error); a 2xx
@@ -161,13 +192,14 @@ export declare class HttpClient {
161
192
  *
162
193
  * @param {Method} method - The HTTP method.
163
194
  * @param {string} uri - The URL or path to request.
164
- * @param {SendOptions} [options] - Headers, credentials, timeout and body.
195
+ * @param {SendOptions} [options] - Headers, credentials, timeout and body; every key must be one of
196
+ * `SendOptions`, as for `send`.
165
197
  * @returns {IO<HttpError, Response>}
166
198
  *
167
199
  * @example
168
200
  * client.raw("POST", "/api/v1/communities", { body: input }).map((r) => r.headers.get("Location"));
169
201
  */
170
- raw(method: Method, uri: string, options?: SendOptions): IO<HttpError, Response>;
202
+ raw<O extends SendOptions>(method: Method, uri: string, options?: Exact<O, SendOptions>): IO<HttpError, Response>;
171
203
  /**
172
204
  * Opens a server-sent-events stream and emits each {@link ServerSentEvent} as it arrives.
173
205
  *
@@ -191,6 +223,16 @@ export declare class HttpClient {
191
223
  * await events.runForEach((event) => IO.sync(() => handle(event))).unsafeRun();
192
224
  */
193
225
  sse(uri: string, options?: SseOptions): Stream<HttpError, ServerSentEvent>;
226
+ /** A `maxBodyBytes` setting, or a `RangeError` when it is not a positive integer or `Infinity`. */
227
+ private static checkMaxBodyBytes;
228
+ /**
229
+ * The `redirect` setting a request runs under: `"error"` under `allowedOrigins`, where `"follow"`
230
+ * throws `RangeError`, since `fetch` would send the request, its headers and its body to every
231
+ * origin on the way before the client could see where it ended.
232
+ */
233
+ private redirectOf;
234
+ /** The request's limit, else the client's; checked where the request is built. */
235
+ private maxBodyBytes;
194
236
  private resolveUrl;
195
237
  /** Prepares the request, runs it through the interceptors and `fetch`, and yields the `Response`. */
196
238
  private exchange;
@@ -202,16 +244,55 @@ export declare class HttpClient {
202
244
  * Configuration for creating an HttpClient instance.
203
245
  */
204
246
  export declare type HttpClientConfig = {
205
- /** Base URL prepended to relative paths. */
247
+ /**
248
+ * Prepended to relative paths by string concatenation with exactly one `/` between them, so the
249
+ * base's own path is kept: `baseUrl: "https://h/api"` and `"/v1/x"` give `https://h/api/v1/x`
250
+ * (`new URL("/v1/x", base)` would drop `/api`). A `uri` with a scheme (`https://…`, `data:`,
251
+ * `blob:`) is used as is.
252
+ */
206
253
  baseUrl?: string;
207
254
  /** Interceptors applied in registration order (first registered = outermost). Immutable after construction. */
208
255
  interceptors?: HttpInterceptor[];
209
256
  /** Default headers merged into every request. Per-request headers take precedence. */
210
257
  defaultHeaders?: Record<string, string>;
211
- /** Default timeout in milliseconds for all requests. Can be overridden per-request. */
258
+ /** Default timeout in milliseconds for all requests; none by default. Can be overridden per-request. */
212
259
  timeout?: number;
213
260
  /** Default credentials policy. Defaults to `"same-origin"` (matches the platform `fetch` default). */
214
261
  credentials?: Credentials;
262
+ /**
263
+ * Whether requests follow a redirect: `"follow"`, as `fetch` does, or `"error"`, which fails the
264
+ * request with `kind: "redirect"` instead. Can be overridden per request. When neither the client
265
+ * nor the request sets it, the `fetch` default (follow) applies and nothing is set on the request.
266
+ * With `allowedOrigins`, it is `"error"`, and `"follow"` throws `RangeError` in the constructor.
267
+ */
268
+ redirect?: Redirect;
269
+ /**
270
+ * The largest response body, in bytes, a request reads; none by default. Reading stops at the
271
+ * limit: a 2xx body past it fails with `kind: "tooLarge"`, and a non-2xx body past it is dropped
272
+ * (`body: null`). A `Content-Length` above the limit fails before reading. `raw()` hands the body
273
+ * to you unread, and server-sent events are not limited, except for an error response's body.
274
+ * A positive integer or `Infinity`; anything else throws `RangeError` in the constructor. Can be
275
+ * overridden per request.
276
+ */
277
+ maxBodyBytes?: number;
278
+ /**
279
+ * The only origins requests may go to, such as `["https://api.example.com"]`; any origin by
280
+ * default. A request to another origin — an absolute URL, a `data:` or `blob:` URL, or a URL an
281
+ * interceptor rewrote — fails with `kind: "request"` before anything is sent, so the client's
282
+ * default headers and interceptors' credentials never leave for it. In a browser, a URL is read
283
+ * against the page's base URL (a `<base href>` included), as `fetch` reads it, and `fetch` gets
284
+ * the absolute URL that was checked. With this set, redirects are refused (`kind: "redirect"`):
285
+ * `redirect: "follow"`, on the client or on a request, throws `RangeError`, since `fetch` would
286
+ * send the request to every origin on the way. Each entry must be exactly an origin, and the
287
+ * `baseUrl`'s origin must be listed; otherwise the constructor throws `RangeError`.
288
+ */
289
+ allowedOrigins?: readonly string[];
290
+ /**
291
+ * The `fetch` that sends every request: the end of the interceptor chain, for HTTP requests and
292
+ * server-sent events alike. Defaults to the global `fetch`, looked up when each request is sent.
293
+ * It is called without a receiver, so the platform `fetch` can be passed as is.
294
+ */
295
+ fetch?: typeof globalThis.fetch;
215
296
  };
216
297
 
217
298
  /**
@@ -223,8 +304,13 @@ export declare type HttpClientConfig = {
223
304
  *
224
305
  * `kind` tells the two facts apart that `status` alone cannot: "the server said 500" is
225
306
  * `kind: "response", status: 500`, while "nothing answered" is `kind: "network", status: 0`.
226
- * For every kind other than `"response"` and `"decode"`, `status` is `0`; `body` is `null` except
227
- * for `"response"`.
307
+ * For every kind other than `"response"`, `"decode"`, `"redirect"` and `"tooLarge"`, `status` is `0`;
308
+ * `body` is `null` except for `"response"`.
309
+ *
310
+ * `message`, `rawMessage`, `body`, `headers`, `url` and `cause` hold what the server and the request
311
+ * contained, which may be sensitive (a token in a query string, an error page echoing input, part of
312
+ * a body in a parse error, a request header value the platform rejected); log {@link HttpError.summary} instead outside a trusted sink.
313
+ * `Set-Cookie` is never carried.
228
314
  *
229
315
  * @example
230
316
  * client.post("/payments", payment).mapErr((error) =>
@@ -236,12 +322,14 @@ export declare type HttpClientConfig = {
236
322
  export declare class HttpError extends Error {
237
323
  /** The transport outcome. See {@link HttpErrorKind}. */
238
324
  readonly kind: HttpErrorKind;
239
- /** The HTTP status code, or `0` when no response arrived (`kind !== "response"`). */
325
+ /** The HTTP status code (`"response"` and `"decode"`), or `0` when no response arrived. */
240
326
  readonly status: number;
241
327
  readonly rawMessage: string;
242
328
  /** The parsed response body, or `null` when none was parsed. */
243
329
  readonly body: unknown;
244
330
  readonly url: string;
331
+ /** The request method. Set by `HttpClient` on every error it returns. */
332
+ readonly method?: Method;
245
333
  readonly headers?: Record<string, string>;
246
334
  /** The underlying exception, when there was one (a `TypeError` from `fetch`, a parse error, an abort reason). */
247
335
  readonly cause?: unknown;
@@ -290,6 +378,24 @@ export declare class HttpError extends Error {
290
378
  * @param {unknown} [cause] The abort reason, if any.
291
379
  */
292
380
  static aborted(url: string, cause?: unknown): HttpError;
381
+ /**
382
+ * An error for a redirect that the request's `redirect: "error"` setting refused. The redirect
383
+ * was not followed. `status` is the redirect status (`0` in a browser, which hides it), `body` is
384
+ * `null`, and `headers` are the redirect's own (its `Location`, where the platform exposes it).
385
+ *
386
+ * @param {string} url The request URL.
387
+ * @param {Response} response The redirect response.
388
+ */
389
+ static redirect(url: string, response: Response): HttpError;
390
+ /**
391
+ * An error for a 2xx response whose body is larger than the request's `maxBodyBytes`. Reading
392
+ * stopped at the limit. `status` is the real status and `body` is `null`.
393
+ *
394
+ * @param {string} url The request URL.
395
+ * @param {Response} response The response whose body was too large.
396
+ * @param {number} maxBodyBytes The limit, in bytes.
397
+ */
398
+ static tooLarge(url: string, response: Response, maxBodyBytes: number): HttpError;
293
399
  /**
294
400
  * Narrows the `unknown` error body to a concrete type using a runtime type guard.
295
401
  * Returns `Some(body)` if the guard passes, `None` otherwise — so the narrow is *checked*,
@@ -311,6 +417,18 @@ export declare class HttpError extends Error {
311
417
  * );
312
418
  */
313
419
  bodyAs<T>(guard: (x: unknown) => x is T): Option_2<NonNullable<T>>;
420
+ /**
421
+ * The parts of this error that are safe to log: the kind, the status, the method, the host (with
422
+ * its port, without credentials) and, for a timeout, `timeoutMs`. It never holds the URL's path or
423
+ * query, the body, the headers, the message or the cause.
424
+ *
425
+ * @returns {HttpErrorSummary} The summary.
426
+ *
427
+ * @example
428
+ * client.get("/users/42?token=…").tapErr((error) => logger.warn("user lookup failed", error.summary()));
429
+ * // { kind: "response", status: 404, method: "GET", host: "api.example.com" }
430
+ */
431
+ summary(): HttpErrorSummary;
314
432
  }
315
433
 
316
434
  /**
@@ -327,10 +445,30 @@ export declare class HttpError extends Error {
327
445
  * - `"aborted"`: the request was aborted by something other than IO cancellation, such as an
328
446
  * interceptor's own signal (an IO cancelled via `fiber.cancel()` or `IO.timeout` ends as
329
447
  * `Cancelled`, not as an `HttpError`).
448
+ * - `"redirect"`: the server answered with a redirect and the request's `redirect` setting is
449
+ * `"error"`. The redirect was not followed. `status` is the redirect status, or `0` in a browser,
450
+ * which hides it.
451
+ * - `"tooLarge"`: the server answered 2xx with a body larger than the request's `maxBodyBytes`.
452
+ * Reading stopped at the limit. `status` is the real status and `body` is `null`.
330
453
  *
331
454
  * New kinds may be added in a minor release, so give an exhaustive `switch` a `default` branch.
332
455
  */
333
- export declare type HttpErrorKind = "request" | "response" | "decode" | "network" | "timeout" | "aborted";
456
+ export declare type HttpErrorKind = "request" | "response" | "decode" | "network" | "timeout" | "aborted" | "redirect" | "tooLarge";
457
+
458
+ /**
459
+ * What {@link HttpError.summary} returns: the parts of an error that are safe to log. It never holds
460
+ * the URL's path or query, the body, the headers, the message or the cause.
461
+ */
462
+ export declare type HttpErrorSummary = {
463
+ readonly kind: HttpErrorKind;
464
+ readonly status: number;
465
+ /** The request method, when the error came from an `HttpClient`. */
466
+ readonly method?: Method;
467
+ /** The host and port of the URL, without credentials. Absent for a relative URL. */
468
+ readonly host?: string;
469
+ /** The timeout that fired. Present only for `kind: "timeout"`. */
470
+ readonly timeoutMs?: number;
471
+ };
334
472
 
335
473
  /**
336
474
  * An HTTP interceptor that can modify or handle a request before, and its response after, the
@@ -344,6 +482,10 @@ export declare interface HttpInterceptor {
344
482
  * `next({ url: request.url, init: { ...request.init, headers } })`. Return a
345
483
  * `Promise<Response>` without calling `next` to short-circuit the request.
346
484
  *
485
+ * Keep `request.init.signal` when building the request you pass on: it is how a timeout or a
486
+ * cancelled fiber aborts the `fetch`. A request forwarded without it runs to completion in the
487
+ * background after the IO has already failed or been cancelled.
488
+ *
347
489
  * @param request - The resolved URL and `fetch` options of the pending request.
348
490
  * @param next - Forwards the request to the next interceptor or to `fetch`.
349
491
  * @returns A Promise of the resulting `Response`.
@@ -364,7 +506,8 @@ export declare type InterceptedRequest = {
364
506
  };
365
507
 
366
508
  /**
367
- * Represents the HTTP method for the request.
509
+ * Represents the HTTP method for the request. Methods may be added in a minor release, so give an
510
+ * exhaustive `switch` or a `Record<Method, …>` a fallback.
368
511
  */
369
512
  export declare type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS" | "HEAD";
370
513
 
@@ -390,7 +533,8 @@ export declare type Options<A = unknown> = RequestOptions & {
390
533
  */
391
534
  transform?: (data: unknown) => A;
392
535
  /**
393
- * What a response without a body (`204`, `205`, an empty `200`) means:
536
+ * What a response without a body means (`204`, `205`, a `HEAD` response, or an empty 2xx under
537
+ * `responseType: "json"`; under `"text"` an empty body is `""`, not absence):
394
538
  * - `"error"` (default): a value was expected, so it fails with `kind: "decode"`;
395
539
  * - `"option"`: absence is expected, so the request yields `Option<A>` — `None` for no body.
396
540
  *
@@ -399,6 +543,13 @@ export declare type Options<A = unknown> = RequestOptions & {
399
543
  empty?: "error" | "option";
400
544
  };
401
545
 
546
+ /**
547
+ * What to do when the server answers with a redirect (`301`, `302`, `303`, `307` or `308`):
548
+ * - `"follow"`: follow it, as `fetch` does by default;
549
+ * - `"error"`: do not follow it, and fail the request with `kind: "redirect"`.
550
+ */
551
+ export declare type Redirect = "follow" | "error";
552
+
402
553
  /**
403
554
  * Options shared by every request: headers, credentials and timeout.
404
555
  */
@@ -407,8 +558,22 @@ export declare type RequestOptions = {
407
558
  headers?: Record<string, string>;
408
559
  /** The credential policy for the request. Defaults to the client-level setting. */
409
560
  credentials?: Credentials;
410
- /** Per-request timeout in milliseconds. Overrides the client-level timeout. */
561
+ /**
562
+ * Per-request timeout in milliseconds. Overrides the client-level timeout. Values above
563
+ * 2,147,483,647 ms (the `setTimeout` limit), including `Infinity`, are lowered to it; a negative
564
+ * or `NaN` value throws `RangeError` where the request is built.
565
+ */
411
566
  timeout?: number;
567
+ /**
568
+ * Whether the request follows a redirect. Overrides the client-level setting. `"follow"` on a
569
+ * client with `allowedOrigins` throws `RangeError` where the request is built.
570
+ */
571
+ redirect?: Redirect;
572
+ /**
573
+ * The largest response body, in bytes, this request reads. Overrides the client-level setting.
574
+ * A positive integer or `Infinity`; anything else throws `RangeError` where the request is built.
575
+ */
576
+ maxBodyBytes?: number;
412
577
  };
413
578
 
414
579
  /** Options for a request whose body is required (the default). */
@@ -423,6 +588,9 @@ declare type RequiredBody<A> = Options<A> & {
423
588
  * - `"blob"`: Parse the response as a Blob.
424
589
  * - `"arrayBuffer"`: Parse the response as an ArrayBuffer.
425
590
  * - `"formData"`: Parse the response as FormData.
591
+ *
592
+ * Response types may be added in a minor release, so give an exhaustive `switch` or a
593
+ * `Record<ResponseType, …>` a fallback.
426
594
  */
427
595
  declare type ResponseType_2 = "json" | "text" | "blob" | "arrayBuffer" | "formData";
428
596
  export { ResponseType_2 as ResponseType }
@@ -460,6 +628,12 @@ export declare type SseOptions = {
460
628
  headers?: Record<string, string>;
461
629
  /** The credential policy — set `"include"` to send cookies. Defaults to the client-level setting. */
462
630
  credentials?: Credentials;
631
+ /**
632
+ * Whether the connection follows a redirect. Defaults to the client-level setting. A refused
633
+ * redirect ends the stream with `kind: "redirect"`, which is not retried. `"follow"` on a client
634
+ * with `allowedOrigins` throws `RangeError` where the stream is built.
635
+ */
636
+ redirect?: Redirect;
463
637
  /**
464
638
  * Whether to automatically reconnect when the connection ends or fails with a retryable error
465
639
  * (network error or a `5xx` status). Terminal `4xx` responses (including auth failures) are not
@@ -468,8 +642,8 @@ export declare type SseOptions = {
468
642
  *
469
643
  * `true` waits `retry` ms (or the server's `retry:` value) before each reconnect, forever. Pass a
470
644
  * `Schedule` for backoff, jitter or a limit on consecutive failed reconnects, e.g.
471
- * `Schedule.exponential(1000).maxDelay(30_000).jittered()`; a server `retry:` value still
472
- * takes precedence as the delay once received. `maxAttempts` counts connection attempts since the
645
+ * `Schedule.exponential(1000).maxDelay(30_000).jittered()`; a server `retry:` value, once
646
+ * received, can lengthen the schedule's delay but not shorten it. `maxAttempts` counts connection attempts since the
473
647
  * last delivered event, the connection that delivered it included — `maxAttempts(3)` allows two
474
648
  * reconnects in a row that deliver nothing — and the count resets with every delivered event.
475
649
  */