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