arthron 1.0.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +120 -50
- package/dist/index-C3lylSNd.d.cts +333 -0
- package/dist/index-C3lylSNd.d.mts +333 -0
- package/dist/index.cjs +67 -697
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -240
- package/dist/index.d.mts +16 -240
- package/dist/index.mjs +54 -684
- package/dist/index.mjs.map +1 -1
- package/dist/plugins-CHCMxtAE.mjs +1166 -0
- package/dist/plugins-CHCMxtAE.mjs.map +1 -0
- package/dist/plugins-Cigqz2SS.cjs +1279 -0
- package/dist/plugins-Cigqz2SS.cjs.map +1 -0
- package/dist/plugins.cjs +7 -0
- package/dist/plugins.d.cts +2 -0
- package/dist/plugins.d.mts +2 -0
- package/dist/plugins.mjs +1 -0
- package/llms.txt +15 -15
- package/package.json +12 -1
- package/plugins/package.json +6 -0
package/dist/index.mjs
CHANGED
|
@@ -1,163 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
const ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
3
|
-
const HTTP_URL = /^https?:\/\//i;
|
|
4
|
-
function isAbsoluteUrl(path) {
|
|
5
|
-
return ABSOLUTE_URL.test(path);
|
|
6
|
-
}
|
|
7
|
-
/**
|
|
8
|
-
* Origin + pathname only — the query and userinfo tend to carry secrets.
|
|
9
|
-
* For anything printed: log lines, error messages, `ArthronError.toJSON`.
|
|
10
|
-
*/
|
|
11
|
-
function redactUrl(url) {
|
|
12
|
-
try {
|
|
13
|
-
const parsed = new URL(url);
|
|
14
|
-
return `${parsed.origin}${parsed.pathname}`;
|
|
15
|
-
} catch {
|
|
16
|
-
return url.split(/[?#]/)[0] ?? url;
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* `undefined` when `url` has no origin of its own. A relative baseURL takes
|
|
21
|
-
* the page's origin in a browser and has none elsewhere.
|
|
22
|
-
*/
|
|
23
|
-
function originOf(url) {
|
|
24
|
-
const page = globalThis.location?.href;
|
|
25
|
-
try {
|
|
26
|
-
return new URL(url, page).origin;
|
|
27
|
-
} catch {
|
|
28
|
-
return;
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
/** `path` is absolute and points away from `baseURL`'s origin. */
|
|
32
|
-
function leavesBase(baseURL, path) {
|
|
33
|
-
if (baseURL === void 0 || !isAbsoluteUrl(path)) return false;
|
|
34
|
-
const base = originOf(baseURL);
|
|
35
|
-
return base === void 0 || originOf(path) !== base;
|
|
36
|
-
}
|
|
37
|
-
function toQueryString(params) {
|
|
38
|
-
if (!params) return "";
|
|
39
|
-
if (Object.prototype.toString.call(params) === "[object URLSearchParams]") return params.toString();
|
|
40
|
-
const search = new URLSearchParams();
|
|
41
|
-
for (const [key, value] of Object.entries(params)) for (const item of Array.isArray(value) ? value : [value]) {
|
|
42
|
-
if (item === null || item === void 0) continue;
|
|
43
|
-
if (typeof item === "object" || typeof item === "function") throw new TypeError(`arthron: params.${key} is not a string, number or boolean — pass one of those or an array of them (dates: date.toISOString())`);
|
|
44
|
-
search.append(key, String(item));
|
|
45
|
-
}
|
|
46
|
-
return search.toString();
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* Fill `{name}` placeholders with encoded values, so each one stays inside
|
|
50
|
-
* its segment: "/", "?" and "#" are encoded, and the values WHATWG URL would
|
|
51
|
-
* turn into a different path — "", "." and ".." — are refused. A placeholder
|
|
52
|
-
* without a value, or a value without a placeholder, is a mistake too.
|
|
53
|
-
*/
|
|
54
|
-
function fillPath(template, values) {
|
|
55
|
-
const used = /* @__PURE__ */ new Set();
|
|
56
|
-
const filled = template.replace(/\{([^{}/]+)\}/g, (_, name) => {
|
|
57
|
-
if (!Object.hasOwn(values, name)) throw new TypeError(`arthron: path "${template}" has {${name}} but no value for it — pass path: { ${name}: … }`);
|
|
58
|
-
used.add(name);
|
|
59
|
-
const value = String(values[name]);
|
|
60
|
-
if (value === "" || value === "." || value === "..") throw new TypeError(`arthron: path value ${name}=${JSON.stringify(value)} would change the path, not fill a segment — pass a real id`);
|
|
61
|
-
return encodeURIComponent(value);
|
|
62
|
-
});
|
|
63
|
-
const unused = Object.keys(values).find((name) => !used.has(name));
|
|
64
|
-
if (unused !== void 0) throw new TypeError(`arthron: path "${template}" has no {${unused}} — add the placeholder or drop the value`);
|
|
65
|
-
return filled;
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* Join `baseURL` and `path` by plain string concatenation so a path prefix in
|
|
69
|
-
* the base (`/v1`) survives a leading slash in the path. WHATWG `new URL()`
|
|
70
|
-
* would drop it. An absolute path replaces the base only when it stays on the
|
|
71
|
-
* base's origin, or when `allowAbsoluteUrls` says other origins are fine — a
|
|
72
|
-
* path built from user input or an API response must not carry the client's
|
|
73
|
-
* credentials somewhere else.
|
|
74
|
-
*/
|
|
75
|
-
function resolveUrl(baseURL, path, params, allowAbsoluteUrls = false) {
|
|
76
|
-
let url;
|
|
77
|
-
if (isAbsoluteUrl(path)) {
|
|
78
|
-
if (!HTTP_URL.test(path)) {
|
|
79
|
-
const scheme = path.slice(0, path.indexOf(":") + 1);
|
|
80
|
-
throw new TypeError(`arthron: only http(s) URLs can be requested, got a "${scheme}" URL — use an http:// or https:// URL`);
|
|
81
|
-
}
|
|
82
|
-
if (!allowAbsoluteUrls && leavesBase(baseURL, path)) throw new TypeError(`arthron: ${originOf(path)} is outside baseURL ${(baseURL && originOf(baseURL)) ?? baseURL} — pass a path relative to baseURL, or set arthron({ allowAbsoluteUrls: true }) to allow other origins (config headers are not sent to them)`);
|
|
83
|
-
url = path;
|
|
84
|
-
} else {
|
|
85
|
-
if (baseURL === void 0) throw new TypeError(`arthron: relative path "${redactUrl(path)}" needs a baseURL — pass baseURL in arthron({ baseURL }) or use an absolute URL`);
|
|
86
|
-
url = `${baseURL.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
|
|
87
|
-
}
|
|
88
|
-
const query = toQueryString(params);
|
|
89
|
-
if (!query) return url;
|
|
90
|
-
const hash = url.indexOf("#");
|
|
91
|
-
const [base, fragment] = hash === -1 ? [url, ""] : [url.slice(0, hash), url.slice(hash)];
|
|
92
|
-
return `${base}${base.includes("?") ? "&" : "?"}${query}${fragment}`;
|
|
93
|
-
}
|
|
94
|
-
//#endregion
|
|
95
|
-
//#region src/error/arthron-error.ts
|
|
96
|
-
/**
|
|
97
|
-
* Marks an ArthronError across copies of this package. The ESM and CJS
|
|
98
|
-
* builds can both end up loaded (a CJS dependency creates the client, ESM
|
|
99
|
-
* app code catches), each with its own class — `Symbol.for` is shared.
|
|
100
|
-
*/
|
|
101
|
-
const BRAND = Symbol.for("arthron.ArthronError");
|
|
102
|
-
/**
|
|
103
|
-
* The only error arthron itself produces. Two sources: a response with
|
|
104
|
-
* `ok === false`, or fetch rejecting outright (network failure, `status` 0).
|
|
105
|
-
* Everything else — cancellation, interceptor bugs — is rethrown untouched.
|
|
106
|
-
*/
|
|
107
|
-
var ArthronError = class ArthronError extends Error {
|
|
108
|
-
name = "ArthronError";
|
|
109
|
-
/** HTTP status of the failed response; `0` when fetch itself failed (network). */
|
|
110
|
-
status;
|
|
111
|
-
statusText;
|
|
112
|
-
/** Parsed body: JSON if it parses, else the text, else `undefined`. */
|
|
113
|
-
data;
|
|
114
|
-
/**
|
|
115
|
-
* The server's own explanation, picked out of `data` (by default
|
|
116
|
-
* `message` → `error` → `error.message` → `detail`; see the `errorDetail`
|
|
117
|
-
* config). `undefined` when the body had none. Untrusted server text: show
|
|
118
|
-
* it to users as text, never as HTML. `message`, by contrast, is written by
|
|
119
|
-
* arthron — method, URL without query, status — and is meant for logs.
|
|
120
|
-
*/
|
|
121
|
-
detail;
|
|
122
|
-
/** The underlying error for network failures. */
|
|
123
|
-
cause;
|
|
124
|
-
constructor(init) {
|
|
125
|
-
super(init.message);
|
|
126
|
-
this.status = init.status;
|
|
127
|
-
this.statusText = init.statusText;
|
|
128
|
-
this.data = init.data;
|
|
129
|
-
this.detail = init.detail;
|
|
130
|
-
this.cause = init.cause;
|
|
131
|
-
Object.defineProperties(this, {
|
|
132
|
-
headers: { value: init.headers },
|
|
133
|
-
request: { value: init.request },
|
|
134
|
-
response: { value: init.response },
|
|
135
|
-
[BRAND]: { value: true }
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
/** `instanceof ArthronError` holds for an error from any copy of the package. */
|
|
139
|
-
static [Symbol.hasInstance](value) {
|
|
140
|
-
return this === ArthronError ? isArthronError(value) : Function.prototype[Symbol.hasInstance].call(this, value);
|
|
141
|
-
}
|
|
142
|
-
/** What serializers see: no headers, no body, no query or userinfo. */
|
|
143
|
-
toJSON() {
|
|
144
|
-
return {
|
|
145
|
-
name: this.name,
|
|
146
|
-
message: this.message,
|
|
147
|
-
detail: this.detail,
|
|
148
|
-
status: this.status,
|
|
149
|
-
statusText: this.statusText,
|
|
150
|
-
method: this.request.init.method ?? "GET",
|
|
151
|
-
url: redactUrl(this.request.url),
|
|
152
|
-
data: this.data
|
|
153
|
-
};
|
|
154
|
-
}
|
|
155
|
-
};
|
|
156
|
-
/** `true` for errors arthron produced: a `!ok` response or a network failure. Cancellations and plugin bugs are not ArthronErrors. */
|
|
157
|
-
function isArthronError(error) {
|
|
158
|
-
return typeof error === "object" && error !== null && error[BRAND] === true;
|
|
159
|
-
}
|
|
160
|
-
//#endregion
|
|
1
|
+
import { _ as redactUrl, a as cancellationError, c as responseError, d as runtimeStreamsRequestBody, f as serializeBody, g as leavesBase, h as fillPath, i as logging$1, m as isArthronError, n as timeout$1, o as isCancellation, p as ArthronError, r as retry$1, s as networkError, u as isReadableStream, v as redactUrlIn, y as resolveUrl } from "./plugins-CHCMxtAE.mjs";
|
|
161
2
|
//#region src/request/headers.ts
|
|
162
3
|
const isPlainRecord = (headers) => !Array.isArray(headers) && Object.prototype.toString.call(headers) !== "[object Headers]";
|
|
163
4
|
/**
|
|
@@ -197,17 +38,19 @@ function cloneBody(body) {
|
|
|
197
38
|
* again (retry) must not see the previous attempt's changes, so every attempt
|
|
198
39
|
* starts from a fresh copy of the headers and of a FormData/URLSearchParams body.
|
|
199
40
|
*/
|
|
200
|
-
function cloneContext({ url, init, meta }) {
|
|
41
|
+
function cloneContext({ url, init, meta, fetch }) {
|
|
201
42
|
const copy = {
|
|
202
43
|
...init,
|
|
203
44
|
headers: toHeaderRecord(init.headers)
|
|
204
45
|
};
|
|
205
46
|
if (init.body) copy.body = cloneBody(init.body);
|
|
206
|
-
|
|
47
|
+
const out = {
|
|
207
48
|
url,
|
|
208
49
|
init: copy,
|
|
209
50
|
meta: { ...meta }
|
|
210
51
|
};
|
|
52
|
+
if (fetch) out.fetch = fetch;
|
|
53
|
+
return out;
|
|
211
54
|
}
|
|
212
55
|
/**
|
|
213
56
|
* Put headers back into a plain lowercase record. A plugin written in JS (or
|
|
@@ -215,7 +58,7 @@ function cloneContext({ url, init, meta }) {
|
|
|
215
58
|
* `{ ...ctx.init.headers }` would otherwise drop every header.
|
|
216
59
|
*/
|
|
217
60
|
function normalize(ctx, previous) {
|
|
218
|
-
|
|
61
|
+
const out = {
|
|
219
62
|
...ctx,
|
|
220
63
|
init: {
|
|
221
64
|
...ctx.init,
|
|
@@ -223,6 +66,18 @@ function normalize(ctx, previous) {
|
|
|
223
66
|
},
|
|
224
67
|
meta: ctx.meta ?? previous.meta
|
|
225
68
|
};
|
|
69
|
+
const fetch = ctx.fetch ?? previous.fetch;
|
|
70
|
+
if (fetch) out.fetch = fetch;
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* A plugin written in JS (or with a cast) that forgets to return would hand
|
|
75
|
+
* `undefined` on — and an error interceptor's would be what the caller
|
|
76
|
+
* catches. Name the plugin slot instead.
|
|
77
|
+
*/
|
|
78
|
+
function returned(value, who, what, cause, verb = "returned") {
|
|
79
|
+
if (value != null) return value;
|
|
80
|
+
throw new TypeError(`arthron: ${who} ${verb} ${value} — return ${what}`, cause === void 0 ? void 0 : { cause });
|
|
226
81
|
}
|
|
227
82
|
/**
|
|
228
83
|
* Owns the order of one request.
|
|
@@ -246,267 +101,35 @@ async function runPipeline(plugins, ctx, send) {
|
|
|
246
101
|
}
|
|
247
102
|
const attempt = async (input) => {
|
|
248
103
|
let current = cloneContext(input);
|
|
104
|
+
for (const interceptor of request) current = normalize(returned(await interceptor(current), "a request interceptor", "the context (ctx or a changed copy)"), current);
|
|
105
|
+
let res;
|
|
249
106
|
try {
|
|
250
|
-
|
|
251
|
-
let res = await send(current);
|
|
252
|
-
for (const interceptor of response) res = await interceptor(res, current);
|
|
253
|
-
return res;
|
|
107
|
+
res = await send(current);
|
|
254
108
|
} catch (thrown) {
|
|
255
109
|
if (!isArthronError(thrown)) throw thrown;
|
|
256
110
|
let err = thrown;
|
|
257
|
-
for (const interceptor of error) err = await interceptor(err, current);
|
|
111
|
+
for (const interceptor of error) err = returned(await interceptor(err, current), "an error interceptor", "the error (err or a changed one)", thrown);
|
|
258
112
|
throw err;
|
|
259
113
|
}
|
|
114
|
+
for (const interceptor of response) res = returned(await interceptor(res, current), "a response interceptor", "the Response (res or a new one)");
|
|
115
|
+
return res;
|
|
260
116
|
};
|
|
261
|
-
const dispatch = (index, input) => {
|
|
117
|
+
const dispatch = async (index, input) => {
|
|
262
118
|
const middleware = middlewares[index];
|
|
263
119
|
if (!middleware) return attempt(input);
|
|
264
|
-
return middleware(input, (next) =>
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
120
|
+
return returned(await middleware(input, (next) => {
|
|
121
|
+
const ctx = {
|
|
122
|
+
...next,
|
|
123
|
+
meta: next.meta ?? input.meta
|
|
124
|
+
};
|
|
125
|
+
const fetch = next.fetch ?? input.fetch;
|
|
126
|
+
if (fetch) ctx.fetch = fetch;
|
|
127
|
+
return dispatch(index + 1, ctx);
|
|
128
|
+
}), "a middleware", "the Response, usually `return next(ctx)`", void 0, "resolved with");
|
|
268
129
|
};
|
|
269
130
|
return dispatch(0, ctx);
|
|
270
131
|
}
|
|
271
132
|
//#endregion
|
|
272
|
-
//#region src/request/body.ts
|
|
273
|
-
const RAW_TAGS = /* @__PURE__ */ new Set([
|
|
274
|
-
"FormData",
|
|
275
|
-
"Blob",
|
|
276
|
-
"File",
|
|
277
|
-
"ArrayBuffer",
|
|
278
|
-
"URLSearchParams",
|
|
279
|
-
"ReadableStream"
|
|
280
|
-
]);
|
|
281
|
-
/**
|
|
282
|
-
* `Symbol.toStringTag`, not `instanceof`: a body from another realm or a
|
|
283
|
-
* polyfill (formdata-node, fetch-blob) must not be JSON-encoded into `{}`.
|
|
284
|
-
*/
|
|
285
|
-
const tagOf = (value) => Object.prototype.toString.call(value).slice(8, -1);
|
|
286
|
-
function isReadableStream(value) {
|
|
287
|
-
return tagOf(value) === "ReadableStream";
|
|
288
|
-
}
|
|
289
|
-
/**
|
|
290
|
-
* Whether `RequestCtor` can send a ReadableStream body. Node and Chromium
|
|
291
|
-
* read `duplex` and leave the stream alone; Firefox ignores `duplex` and
|
|
292
|
-
* would send the text "[object ReadableStream]"; older Safari refuses it.
|
|
293
|
-
* The check from
|
|
294
|
-
* https://developer.chrome.com/docs/capabilities/web-apis/fetch-streaming-requests
|
|
295
|
-
*/
|
|
296
|
-
function canStreamRequestBody(RequestCtor) {
|
|
297
|
-
let duplexRead = false;
|
|
298
|
-
try {
|
|
299
|
-
const request = new RequestCtor("https://stream.test", {
|
|
300
|
-
method: "POST",
|
|
301
|
-
body: new ReadableStream(),
|
|
302
|
-
get duplex() {
|
|
303
|
-
duplexRead = true;
|
|
304
|
-
return "half";
|
|
305
|
-
}
|
|
306
|
-
});
|
|
307
|
-
return duplexRead && !request.headers.has("content-type");
|
|
308
|
-
} catch {
|
|
309
|
-
return false;
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
let runtimeStreams;
|
|
313
|
-
/** `canStreamRequestBody` for the global `Request`, checked once. */
|
|
314
|
-
function runtimeStreamsRequestBody() {
|
|
315
|
-
runtimeStreams ??= typeof Request !== "function" || canStreamRequestBody(Request);
|
|
316
|
-
return runtimeStreams;
|
|
317
|
-
}
|
|
318
|
-
/**
|
|
319
|
-
* What JSON.stringify would turn into `{}`, `undefined` or internal state
|
|
320
|
-
* instead of the data — with the fix, so it reads as an error message.
|
|
321
|
-
*/
|
|
322
|
-
function mangledByJson(body) {
|
|
323
|
-
if (typeof body === "function" || typeof body === "symbol") return `a ${typeof body}, which JSON cannot carry — send its data instead`;
|
|
324
|
-
if (typeof body !== "object" || body === null || Array.isArray(body)) return;
|
|
325
|
-
if (Symbol.asyncIterator in body) return "an async iterable (a Node stream?) — pass a ReadableStream (Readable.toWeb(stream)) or collect it first";
|
|
326
|
-
if (Symbol.iterator in body) return "an iterable such as a Map, Set or generator — convert it to an array or plain object first";
|
|
327
|
-
}
|
|
328
|
-
/** Bodies fetch already knows how to send. Content-Type is left to the caller / runtime. */
|
|
329
|
-
function isRawBody(body) {
|
|
330
|
-
if (typeof body === "string") return true;
|
|
331
|
-
if (ArrayBuffer.isView(body)) return true;
|
|
332
|
-
return RAW_TAGS.has(tagOf(body));
|
|
333
|
-
}
|
|
334
|
-
/**
|
|
335
|
-
* Turn a caller-supplied body into something fetch accepts. Raw bodies pass
|
|
336
|
-
* through untouched; anything else is JSON with `content-type` set — unless
|
|
337
|
-
* the caller already set one (headers arrive lowercased, so a plain lookup is
|
|
338
|
-
* enough).
|
|
339
|
-
*/
|
|
340
|
-
function serializeBody(body, headers) {
|
|
341
|
-
if (body === void 0) return {
|
|
342
|
-
body: void 0,
|
|
343
|
-
headers
|
|
344
|
-
};
|
|
345
|
-
if (tagOf(body) === "FormData") {
|
|
346
|
-
const { "content-type": _dropped, ...rest } = headers;
|
|
347
|
-
return {
|
|
348
|
-
body,
|
|
349
|
-
headers: rest
|
|
350
|
-
};
|
|
351
|
-
}
|
|
352
|
-
if (isRawBody(body)) return {
|
|
353
|
-
body,
|
|
354
|
-
headers
|
|
355
|
-
};
|
|
356
|
-
const mangled = mangledByJson(body);
|
|
357
|
-
if (mangled) throw new TypeError(`arthron: the body is ${mangled}`);
|
|
358
|
-
const type = headers["content-type"];
|
|
359
|
-
if (type !== void 0 && !/\bjson\b/i.test(type)) throw new TypeError(`arthron: a ${typeof body} body is sent as JSON, but content-type is "${type}" — pass a string, URLSearchParams or FormData for that content type, or drop the header`);
|
|
360
|
-
const withType = "content-type" in headers ? headers : {
|
|
361
|
-
...headers,
|
|
362
|
-
"content-type": "application/json"
|
|
363
|
-
};
|
|
364
|
-
return {
|
|
365
|
-
body: JSON.stringify(body),
|
|
366
|
-
headers: withType
|
|
367
|
-
};
|
|
368
|
-
}
|
|
369
|
-
//#endregion
|
|
370
|
-
//#region src/response/rebuild-response.ts
|
|
371
|
-
/**
|
|
372
|
-
* A new Response with `body` but everything else taken from `original`. The
|
|
373
|
-
* constructor resets `url`, `redirected` and `type`, so those are copied over
|
|
374
|
-
* as own properties — callers that resolve relative links or detect
|
|
375
|
-
* redirects keep working.
|
|
376
|
-
*/
|
|
377
|
-
function rebuildResponse(original, body) {
|
|
378
|
-
return withFetchedFields(new Response(body, {
|
|
379
|
-
status: original.status,
|
|
380
|
-
statusText: original.statusText,
|
|
381
|
-
headers: original.headers
|
|
382
|
-
}), original);
|
|
383
|
-
}
|
|
384
|
-
/** Copy the fields the constructor resets — onto `clone()`s as well. */
|
|
385
|
-
function withFetchedFields(target, from) {
|
|
386
|
-
const clone = target.clone.bind(target);
|
|
387
|
-
return Object.defineProperties(target, {
|
|
388
|
-
url: { value: from.url },
|
|
389
|
-
redirected: { value: from.redirected },
|
|
390
|
-
type: { value: from.type },
|
|
391
|
-
clone: { value: () => withFetchedFields(clone(), from) }
|
|
392
|
-
});
|
|
393
|
-
}
|
|
394
|
-
//#endregion
|
|
395
|
-
//#region src/error/create-error.ts
|
|
396
|
-
/**
|
|
397
|
-
* Cancellation is not an HTTP failure. Matched by name so it works across
|
|
398
|
-
* realms — or by the request's own `signal`, since `abort(reason)` rejects
|
|
399
|
-
* with whatever reason the caller chose.
|
|
400
|
-
*/
|
|
401
|
-
function isCancellation(error, signal) {
|
|
402
|
-
if (signal?.aborted) return true;
|
|
403
|
-
const name = error?.name;
|
|
404
|
-
return name === "AbortError" || name === "TimeoutError";
|
|
405
|
-
}
|
|
406
|
-
/**
|
|
407
|
-
* What a cancelled call rejects with: its signal's reason. WebKit's fetch
|
|
408
|
-
* rejects, and errors a half-read body, with a generic AbortError instead,
|
|
409
|
-
* dropping a TimeoutError or the caller's own reason.
|
|
410
|
-
*/
|
|
411
|
-
function cancellationError(error, signal) {
|
|
412
|
-
return signal?.aborted ? signal.reason : error;
|
|
413
|
-
}
|
|
414
|
-
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
415
|
-
/** `message` → `error` (string) → `error.message` → `detail`. */
|
|
416
|
-
function defaultErrorDetail(data) {
|
|
417
|
-
if (!isRecord(data)) return void 0;
|
|
418
|
-
if (typeof data.message === "string") return data.message;
|
|
419
|
-
if (typeof data.error === "string") return data.error;
|
|
420
|
-
if (isRecord(data.error) && typeof data.error.message === "string") return data.error.message;
|
|
421
|
-
if (typeof data.detail === "string") return data.detail;
|
|
422
|
-
}
|
|
423
|
-
/** How much of an error body arthron reads. Error bodies are for diagnosis; a hostile or broken server must not be able to fill memory with one. */
|
|
424
|
-
const MAX_ERROR_BODY_BYTES = 65536;
|
|
425
|
-
/** Up to `limit` bytes of the body; the rest is cancelled unread. `undefined` when there is no body or reading it failed. */
|
|
426
|
-
async function readCapped(response, limit) {
|
|
427
|
-
if (!response.body) return void 0;
|
|
428
|
-
let reader;
|
|
429
|
-
const chunks = [];
|
|
430
|
-
let size = 0;
|
|
431
|
-
try {
|
|
432
|
-
reader = response.body.getReader();
|
|
433
|
-
while (size <= limit) {
|
|
434
|
-
const { value, done } = await reader.read();
|
|
435
|
-
if (done) break;
|
|
436
|
-
chunks.push(value);
|
|
437
|
-
size += value.byteLength;
|
|
438
|
-
}
|
|
439
|
-
} catch {
|
|
440
|
-
return;
|
|
441
|
-
} finally {
|
|
442
|
-
await reader?.cancel().catch(() => {});
|
|
443
|
-
reader?.releaseLock();
|
|
444
|
-
}
|
|
445
|
-
const bytes = new Uint8Array(size);
|
|
446
|
-
let offset = 0;
|
|
447
|
-
for (const chunk of chunks) {
|
|
448
|
-
bytes.set(chunk, offset);
|
|
449
|
-
offset += chunk.byteLength;
|
|
450
|
-
}
|
|
451
|
-
return size > limit ? {
|
|
452
|
-
bytes: bytes.subarray(0, limit),
|
|
453
|
-
truncated: true
|
|
454
|
-
} : {
|
|
455
|
-
bytes,
|
|
456
|
-
truncated: false
|
|
457
|
-
};
|
|
458
|
-
}
|
|
459
|
-
/** JSON if the whole body parses, else the text (cut at the limit), else `undefined` when empty. */
|
|
460
|
-
function parseBody(read) {
|
|
461
|
-
const text = new TextDecoder().decode(read.bytes);
|
|
462
|
-
if (text === "") return void 0;
|
|
463
|
-
if (read.truncated) return text;
|
|
464
|
-
try {
|
|
465
|
-
return JSON.parse(text);
|
|
466
|
-
} catch {
|
|
467
|
-
return text;
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
/** The request as error messages name it: method and URL, no query or userinfo. */
|
|
471
|
-
function describeRequest(request) {
|
|
472
|
-
return `${request.init.method ?? "GET"} ${redactUrl(request.url)}`;
|
|
473
|
-
}
|
|
474
|
-
async function responseError(response, request, resolve = defaultErrorDetail) {
|
|
475
|
-
const read = await readCapped(response, MAX_ERROR_BODY_BYTES);
|
|
476
|
-
const data = read && parseBody(read);
|
|
477
|
-
if (read) response = rebuildResponse(response, read.bytes);
|
|
478
|
-
const status = response.statusText ? `${response.status} ${response.statusText}` : String(response.status);
|
|
479
|
-
return new ArthronError({
|
|
480
|
-
message: `${describeRequest(request)} failed with ${status}`,
|
|
481
|
-
detail: resolve(data, response) || void 0,
|
|
482
|
-
status: response.status,
|
|
483
|
-
statusText: response.statusText,
|
|
484
|
-
headers: response.headers,
|
|
485
|
-
data,
|
|
486
|
-
request,
|
|
487
|
-
response
|
|
488
|
-
});
|
|
489
|
-
}
|
|
490
|
-
/**
|
|
491
|
-
* Browsers that stream a request body (Chromium, current WebKit) do it only
|
|
492
|
-
* over HTTP/2, and fail one sent to an HTTP/1.1 server with the same bare
|
|
493
|
-
* "Failed to fetch" / "Load failed" as a dead server, so name the likely cause.
|
|
494
|
-
*/
|
|
495
|
-
const STREAM_BODY_HINT = " — in a browser, a ReadableStream body streams only over HTTP/2; send a Blob or ArrayBuffer to an HTTP/1.1 server";
|
|
496
|
-
function networkError(cause, request) {
|
|
497
|
-
const reason = cause instanceof Error && cause.message ? cause.message : "network error";
|
|
498
|
-
const hint = isReadableStream(request.init.body) ? STREAM_BODY_HINT : "";
|
|
499
|
-
return new ArthronError({
|
|
500
|
-
message: `${describeRequest(request)} failed: ${reason}${hint}`,
|
|
501
|
-
status: 0,
|
|
502
|
-
statusText: "",
|
|
503
|
-
headers: new Headers(),
|
|
504
|
-
data: void 0,
|
|
505
|
-
request,
|
|
506
|
-
cause
|
|
507
|
-
});
|
|
508
|
-
}
|
|
509
|
-
//#endregion
|
|
510
133
|
//#region src/response/schema-validation.ts
|
|
511
134
|
const pathOf = (issue) => (issue.path ?? []).map((part) => String(typeof part === "object" && part !== null ? part.key : part)).join(".");
|
|
512
135
|
/**
|
|
@@ -541,6 +164,10 @@ const DEFAULT_LIMIT = 8388608;
|
|
|
541
164
|
*/
|
|
542
165
|
async function* lines(response, maxLineLength) {
|
|
543
166
|
if (!response.body) return;
|
|
167
|
+
const checked = (line) => {
|
|
168
|
+
if (line.length <= maxLineLength) return line;
|
|
169
|
+
throw new RangeError(`arthron: a stream line is longer than ${maxLineLength} characters — pass a larger maxLineLength to .sse() / .ndjson() if that is expected`);
|
|
170
|
+
};
|
|
544
171
|
const reader = response.body.getReader();
|
|
545
172
|
const decoder = new TextDecoder();
|
|
546
173
|
const breaks = /\r\n|\r|\n/g;
|
|
@@ -558,12 +185,11 @@ async function* lines(response, maxLineLength) {
|
|
|
558
185
|
let start = 0;
|
|
559
186
|
breaks.lastIndex = 0;
|
|
560
187
|
for (let m = breaks.exec(text); m; m = breaks.exec(text)) {
|
|
561
|
-
yield pending + text.slice(start, m.index);
|
|
188
|
+
yield checked(pending + text.slice(start, m.index));
|
|
562
189
|
pending = "";
|
|
563
190
|
start = breaks.lastIndex;
|
|
564
191
|
}
|
|
565
|
-
pending
|
|
566
|
-
if (pending.length > maxLineLength) throw new RangeError(`arthron: a stream line is longer than ${maxLineLength} characters — pass a larger maxLineLength to .sse() / .ndjson() if that is expected`);
|
|
192
|
+
pending = checked(pending + text.slice(start));
|
|
567
193
|
if (done) break;
|
|
568
194
|
}
|
|
569
195
|
if (pending) yield pending;
|
|
@@ -736,9 +362,8 @@ function assertSendable(url, method) {
|
|
|
736
362
|
try {
|
|
737
363
|
new Request(url, { method });
|
|
738
364
|
} catch (cause) {
|
|
739
|
-
const
|
|
740
|
-
|
|
741
|
-
throw new TypeError(`arthron: cannot send ${method} ${shown} (${reason}) — use an absolute URL or a baseURL with a scheme (https://…), and a valid HTTP method`, { cause });
|
|
365
|
+
const reason = redactUrlIn(cause instanceof Error ? cause.message : String(cause), url);
|
|
366
|
+
throw new TypeError(`arthron: cannot send ${method} ${redactUrl(url)} (${reason}) — use an absolute URL or a baseURL with a scheme (https://…), and a valid HTTP method`, { cause });
|
|
742
367
|
}
|
|
743
368
|
}
|
|
744
369
|
/**
|
|
@@ -761,7 +386,7 @@ function failedByDefault(res, init) {
|
|
|
761
386
|
}
|
|
762
387
|
/** The one place a failure becomes an ArthronError. Cancellation passes through. */
|
|
763
388
|
async function send(resolved, ctx, throwOn) {
|
|
764
|
-
const fetchImpl = resolved.fetch ?? globalThis.fetch;
|
|
389
|
+
const fetchImpl = ctx.fetch ?? resolved.fetch ?? globalThis.fetch;
|
|
765
390
|
if (resolved.fetch === void 0) {
|
|
766
391
|
const method = ctx.init.method ?? "GET";
|
|
767
392
|
assertSendable(ctx.url, method);
|
|
@@ -809,7 +434,8 @@ function arthron(config = {}) {
|
|
|
809
434
|
if (rawBody !== void 0 && BODYLESS_METHODS.has(upper)) throw new TypeError(`arthron: ${upper} requests cannot carry a body — send it as params (query) or switch to POST`);
|
|
810
435
|
if (pathValues) path = fillPath(path, pathValues);
|
|
811
436
|
const url = resolveUrl(resolved.baseURL, path, params, resolved.allowAbsoluteUrls);
|
|
812
|
-
const
|
|
437
|
+
const defaults = leavesBase(resolved.baseURL, path) ? void 0 : resolved.headers;
|
|
438
|
+
const { body, headers } = serializeBody(rawBody, mergeHeaders(defaults, callHeaders));
|
|
813
439
|
const requestInit = {
|
|
814
440
|
...initDefaults,
|
|
815
441
|
...init,
|
|
@@ -821,7 +447,8 @@ function arthron(config = {}) {
|
|
|
821
447
|
return toArthronPromise(runPipeline(resolved.use, {
|
|
822
448
|
url,
|
|
823
449
|
init: requestInit,
|
|
824
|
-
meta: { ...meta }
|
|
450
|
+
meta: { ...meta },
|
|
451
|
+
fetch: resolved.fetch ?? globalThis.fetch
|
|
825
452
|
}, (ctx) => send(resolved, ctx, throwOn)), init.signal);
|
|
826
453
|
} catch (thrown) {
|
|
827
454
|
return toArthronPromise(Promise.reject(thrown));
|
|
@@ -869,270 +496,13 @@ const defineInterceptor = {
|
|
|
869
496
|
/** Identity helper: type-checks a plugin object literal without an annotation. */
|
|
870
497
|
const definePlugin = (plugin) => plugin;
|
|
871
498
|
//#endregion
|
|
872
|
-
//#region src/
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
}
|
|
880
|
-
/**
|
|
881
|
-
* One event when a request starts, one when it settles, with status and
|
|
882
|
-
* elapsed time. Wraps the whole call, so retries are included in the time.
|
|
883
|
-
* Default output is a console line per event; pass `onEvent` to get the
|
|
884
|
-
* structured event instead. Cancellations are not reported.
|
|
885
|
-
*/
|
|
886
|
-
function logging(options = {}) {
|
|
887
|
-
const { enabled = true, logger = console, onEvent, now = () => performance.now() } = options;
|
|
888
|
-
const emit = onEvent ?? consoleSink(logger);
|
|
889
|
-
return {
|
|
890
|
-
name: "logging",
|
|
891
|
-
middleware: async (ctx, next) => {
|
|
892
|
-
if (!enabled) return next(ctx);
|
|
893
|
-
const method = ctx.init.method ?? "GET";
|
|
894
|
-
const path = redactUrl(ctx.url);
|
|
895
|
-
const started = now();
|
|
896
|
-
const ms = () => Math.round(now() - started);
|
|
897
|
-
emit({
|
|
898
|
-
phase: "start",
|
|
899
|
-
method,
|
|
900
|
-
path
|
|
901
|
-
});
|
|
902
|
-
let res;
|
|
903
|
-
try {
|
|
904
|
-
res = await next(ctx);
|
|
905
|
-
} catch (error) {
|
|
906
|
-
if (!isCancellation(error, ctx.init.signal)) {
|
|
907
|
-
const status = isArthronError(error) ? error.status : void 0;
|
|
908
|
-
emit({
|
|
909
|
-
phase: "error",
|
|
910
|
-
method,
|
|
911
|
-
path,
|
|
912
|
-
status,
|
|
913
|
-
ms: ms(),
|
|
914
|
-
error
|
|
915
|
-
});
|
|
916
|
-
}
|
|
917
|
-
throw error;
|
|
918
|
-
}
|
|
919
|
-
emit({
|
|
920
|
-
phase: "success",
|
|
921
|
-
method,
|
|
922
|
-
path,
|
|
923
|
-
status: res.status,
|
|
924
|
-
ms: ms()
|
|
925
|
-
});
|
|
926
|
-
return res;
|
|
927
|
-
}
|
|
928
|
-
};
|
|
929
|
-
}
|
|
930
|
-
//#endregion
|
|
931
|
-
//#region src/plugins/retry/retry.ts
|
|
932
|
-
const DEFAULT_RETRY_ON = [
|
|
933
|
-
408,
|
|
934
|
-
429,
|
|
935
|
-
500,
|
|
936
|
-
502,
|
|
937
|
-
503,
|
|
938
|
-
504
|
|
939
|
-
];
|
|
940
|
-
const DEFAULT_METHODS = [
|
|
941
|
-
"GET",
|
|
942
|
-
"HEAD",
|
|
943
|
-
"OPTIONS",
|
|
944
|
-
"QUERY",
|
|
945
|
-
"PUT",
|
|
946
|
-
"DELETE"
|
|
947
|
-
];
|
|
948
|
-
const DEFAULT_MAX_RETRY_AFTER = 6e4;
|
|
949
|
-
/** setTimeout fires at once past this, so every wait is capped to it. */
|
|
950
|
-
const MAX_TIMER_MS$1 = 2 ** 31 - 1;
|
|
951
|
-
function defaultSleep(ms, signal) {
|
|
952
|
-
return new Promise((resolve, reject) => {
|
|
953
|
-
if (signal?.aborted) return reject(signal.reason);
|
|
954
|
-
const onAbort = () => {
|
|
955
|
-
clearTimeout(timer);
|
|
956
|
-
reject(signal?.reason);
|
|
957
|
-
};
|
|
958
|
-
const timer = setTimeout(() => {
|
|
959
|
-
signal?.removeEventListener("abort", onAbort);
|
|
960
|
-
resolve();
|
|
961
|
-
}, ms);
|
|
962
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
963
|
-
});
|
|
964
|
-
}
|
|
965
|
-
/** `Retry-After` as ms — seconds or an HTTP-date. `undefined` when absent or unparsable. */
|
|
966
|
-
function retryAfterMs(error) {
|
|
967
|
-
const value = error.headers.get("retry-after")?.trim();
|
|
968
|
-
if (!value) return void 0;
|
|
969
|
-
const seconds = Number(value);
|
|
970
|
-
if (!Number.isNaN(seconds)) return Math.max(0, seconds * 1e3);
|
|
971
|
-
const at = Date.parse(value);
|
|
972
|
-
if (Number.isNaN(at)) return void 0;
|
|
973
|
-
return Math.max(0, at - Date.now());
|
|
974
|
-
}
|
|
975
|
-
/** The rule without `shouldRetry`: a network error or a `retryOn` status, on a method in `methods`. */
|
|
976
|
-
function byDefault(thrown, method, settings) {
|
|
977
|
-
if (!settings.allowed.has(method) || !isArthronError(thrown)) return false;
|
|
978
|
-
return thrown.status === 0 || settings.retryOn.includes(thrown.status);
|
|
979
|
-
}
|
|
980
|
-
/** Defaults filled in and `retries` checked — `attempt >= NaN` is never true, so an unset env var would retry forever. */
|
|
981
|
-
function settle(options, where) {
|
|
982
|
-
const { retries = 2, retryOn = DEFAULT_RETRY_ON, methods = DEFAULT_METHODS, delay = (retry) => Math.random() * 300 * 2 ** retry, maxRetryAfter = DEFAULT_MAX_RETRY_AFTER, shouldRetry, onRetry } = options;
|
|
983
|
-
if (!Number.isInteger(retries) || retries < 0) throw new TypeError(`arthron: ${where} retries: ${retries} needs a whole number ≥ 0 — e.g. retries: 2`);
|
|
984
|
-
return {
|
|
985
|
-
retries,
|
|
986
|
-
retryOn,
|
|
987
|
-
allowed: new Set(methods.map((m) => m.toUpperCase())),
|
|
988
|
-
delay,
|
|
989
|
-
maxRetryAfter,
|
|
990
|
-
shouldRetry,
|
|
991
|
-
onRetry
|
|
992
|
-
};
|
|
993
|
-
}
|
|
994
|
-
/**
|
|
995
|
-
* Retry on network errors and the configured statuses by calling `next`
|
|
996
|
-
* again — the whole attempt (request interceptors included) is re-run.
|
|
997
|
-
* Only `ArthronError` is considered; cancellation and plugin bugs pass through.
|
|
998
|
-
* A call can turn it off or override its options with `meta.retry`.
|
|
999
|
-
*/
|
|
1000
|
-
function retry(options = {}) {
|
|
1001
|
-
const { sleep = defaultSleep, ...rest } = options;
|
|
1002
|
-
const base = settle(rest, "retry()");
|
|
1003
|
-
return {
|
|
1004
|
-
name: "retry",
|
|
1005
|
-
middleware: async (ctx, next) => {
|
|
1006
|
-
const override = ctx.meta?.retry;
|
|
1007
|
-
if (override === false) return next(ctx);
|
|
1008
|
-
const settings = override ? settle({
|
|
1009
|
-
...rest,
|
|
1010
|
-
...override
|
|
1011
|
-
}, "meta.retry") : base;
|
|
1012
|
-
const method = (ctx.init.method ?? "GET").toUpperCase();
|
|
1013
|
-
const resendable = !isReadableStream(ctx.init.body);
|
|
1014
|
-
for (let attempt = 0;; attempt += 1) try {
|
|
1015
|
-
return await next(ctx);
|
|
1016
|
-
} catch (thrown) {
|
|
1017
|
-
if (!resendable || attempt >= settings.retries) throw thrown;
|
|
1018
|
-
if (ctx.init.signal?.aborted) throw thrown;
|
|
1019
|
-
const verdict = settings.shouldRetry?.(thrown, attempt, ctx);
|
|
1020
|
-
if (verdict === false) throw thrown;
|
|
1021
|
-
if (verdict === void 0 && !byDefault(thrown, method, settings)) throw thrown;
|
|
1022
|
-
const retryAfter = isArthronError(thrown) ? retryAfterMs(thrown) : void 0;
|
|
1023
|
-
if (retryAfter !== void 0 && retryAfter > settings.maxRetryAfter) throw thrown;
|
|
1024
|
-
const wait = Math.min(retryAfter ?? settings.delay(attempt, thrown), MAX_TIMER_MS$1);
|
|
1025
|
-
settings.onRetry?.(thrown, attempt, wait);
|
|
1026
|
-
await sleep(wait, ctx.init.signal);
|
|
1027
|
-
}
|
|
1028
|
-
}
|
|
1029
|
-
};
|
|
1030
|
-
}
|
|
1031
|
-
//#endregion
|
|
1032
|
-
//#region src/plugins/timeout/timeout.ts
|
|
1033
|
-
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
1034
|
-
/**
|
|
1035
|
-
* Wrap `body` so the deadline keeps running until it is fully read, and so an
|
|
1036
|
-
* abort while reading surfaces as a stream error instead of a silent stall.
|
|
1037
|
-
*/
|
|
1038
|
-
function guardBody(body, signal, finish, onChunk) {
|
|
1039
|
-
const reader = body.getReader();
|
|
1040
|
-
return new ReadableStream({
|
|
1041
|
-
start(controller) {
|
|
1042
|
-
signal.addEventListener("abort", () => {
|
|
1043
|
-
controller.error(signal.reason);
|
|
1044
|
-
reader.cancel(signal.reason).catch(() => {});
|
|
1045
|
-
}, { once: true });
|
|
1046
|
-
},
|
|
1047
|
-
async pull(controller) {
|
|
1048
|
-
const { value, done } = await reader.read();
|
|
1049
|
-
if (done) {
|
|
1050
|
-
finish();
|
|
1051
|
-
controller.close();
|
|
1052
|
-
return;
|
|
1053
|
-
}
|
|
1054
|
-
onChunk();
|
|
1055
|
-
controller.enqueue(value);
|
|
1056
|
-
},
|
|
1057
|
-
cancel(reason) {
|
|
1058
|
-
finish();
|
|
1059
|
-
return reader.cancel(reason);
|
|
1060
|
-
}
|
|
1061
|
-
});
|
|
1062
|
-
}
|
|
1063
|
-
/** setTimeout fires at once for NaN, negatives and anything past 2^31-1. */
|
|
1064
|
-
function checkDeadline(ms, where) {
|
|
1065
|
-
if (ms === Number.POSITIVE_INFINITY || ms >= 0 && ms <= MAX_TIMER_MS) return;
|
|
1066
|
-
throw new TypeError(`arthron: ${where} needs 0–${MAX_TIMER_MS} ms — pass Infinity for no deadline`);
|
|
1067
|
-
}
|
|
1068
|
-
/** A timer that aborts `controller` with a TimeoutError and never keeps Node alive on its own. */
|
|
1069
|
-
function deadlineTimer(controller, ms, message) {
|
|
1070
|
-
const timer = setTimeout(() => controller.abort(new DOMException(message, "TimeoutError")), ms);
|
|
1071
|
-
timer.unref?.();
|
|
1072
|
-
return timer;
|
|
1073
|
-
}
|
|
1074
|
-
/**
|
|
1075
|
-
* Abort the request when it takes longer than `ms` — counted from the start
|
|
1076
|
-
* of the attempt until the body has been fully read, so a server that sends
|
|
1077
|
-
* headers and then stalls still trips it. With `idle`, also abort once no
|
|
1078
|
-
* data has arrived for that long. Rejects with a `TimeoutError` (a
|
|
1079
|
-
* `DOMException`, like `AbortSignal.timeout()` would give); it is not an
|
|
1080
|
-
* `ArthronError`, so error interceptors and `retry` leave it alone.
|
|
1081
|
-
*
|
|
1082
|
-
* A call can change the total deadline with `meta.timeout`.
|
|
1083
|
-
*
|
|
1084
|
-
* Deadlines are timers on an AbortController — not `AbortSignal.timeout`,
|
|
1085
|
-
* since the idle one restarts — joined to the caller's signal with
|
|
1086
|
-
* `AbortSignal.any`.
|
|
1087
|
-
*/
|
|
1088
|
-
function timeout(ms, options = {}) {
|
|
1089
|
-
checkDeadline(ms, `timeout(${ms})`);
|
|
1090
|
-
const { idle } = options;
|
|
1091
|
-
if (idle !== void 0) checkDeadline(idle, `timeout(…, { idle: ${idle} })`);
|
|
1092
|
-
return {
|
|
1093
|
-
name: "timeout",
|
|
1094
|
-
middleware: async (ctx, next) => {
|
|
1095
|
-
const deadline = ctx.meta?.timeout ?? ms;
|
|
1096
|
-
if (deadline !== ms) checkDeadline(deadline, `meta.timeout: ${deadline}`);
|
|
1097
|
-
const idleMs = idle === Number.POSITIVE_INFINITY ? void 0 : idle;
|
|
1098
|
-
if (deadline === Number.POSITIVE_INFINITY && idleMs === void 0) return next(ctx);
|
|
1099
|
-
const controller = new AbortController();
|
|
1100
|
-
const outer = ctx.init.signal;
|
|
1101
|
-
const signal = outer ? AbortSignal.any([outer, controller.signal]) : controller.signal;
|
|
1102
|
-
const total = deadline === Number.POSITIVE_INFINITY ? void 0 : deadlineTimer(controller, deadline, `arthron: request timed out after ${deadline}ms`);
|
|
1103
|
-
let quiet;
|
|
1104
|
-
const stillAlive = () => {
|
|
1105
|
-
if (idleMs === void 0) return;
|
|
1106
|
-
clearTimeout(quiet);
|
|
1107
|
-
quiet = deadlineTimer(controller, idleMs, `arthron: no data for ${idleMs}ms`);
|
|
1108
|
-
};
|
|
1109
|
-
const finish = () => {
|
|
1110
|
-
clearTimeout(total);
|
|
1111
|
-
clearTimeout(quiet);
|
|
1112
|
-
};
|
|
1113
|
-
stillAlive();
|
|
1114
|
-
let res;
|
|
1115
|
-
try {
|
|
1116
|
-
res = await next({
|
|
1117
|
-
...ctx,
|
|
1118
|
-
init: {
|
|
1119
|
-
...ctx.init,
|
|
1120
|
-
signal
|
|
1121
|
-
}
|
|
1122
|
-
});
|
|
1123
|
-
} catch (thrown) {
|
|
1124
|
-
finish();
|
|
1125
|
-
throw thrown;
|
|
1126
|
-
}
|
|
1127
|
-
if (!res.body) {
|
|
1128
|
-
finish();
|
|
1129
|
-
return res;
|
|
1130
|
-
}
|
|
1131
|
-
stillAlive();
|
|
1132
|
-
return rebuildResponse(res, guardBody(res.body, signal, finish, stillAlive));
|
|
1133
|
-
}
|
|
1134
|
-
};
|
|
1135
|
-
}
|
|
499
|
+
//#region src/index.ts
|
|
500
|
+
/** @deprecated Import from "arthron/plugins"; this export goes in the next major. */
|
|
501
|
+
const logging = logging$1;
|
|
502
|
+
/** @deprecated Import from "arthron/plugins"; this export goes in the next major. */
|
|
503
|
+
const retry = retry$1;
|
|
504
|
+
/** @deprecated Import from "arthron/plugins"; this export goes in the next major. */
|
|
505
|
+
const timeout = timeout$1;
|
|
1136
506
|
//#endregion
|
|
1137
507
|
export { ArthronError, SchemaError, arthron, defineInterceptor, defineMiddleware, definePlugin, isArthronError, logging, retry, timeout };
|
|
1138
508
|
|