arthron 1.1.0 → 2.0.1
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 +325 -176
- package/dist/index.cjs +270 -152
- package/dist/index.d.cts +158 -115
- package/dist/index.d.mts +158 -115
- package/dist/index.mjs +251 -132
- package/dist/plugins.cjs +846 -5
- package/dist/plugins.d.cts +129 -2
- package/dist/plugins.d.mts +129 -2
- package/dist/plugins.mjs +842 -1
- package/dist/shared.cjs +635 -0
- package/dist/shared.d.cts +239 -0
- package/dist/shared.d.mts +239 -0
- package/dist/shared.mjs +498 -0
- package/llms.txt +45 -41
- package/package.json +5 -3
- package/dist/index-Bz1P80JN.d.cts +0 -293
- package/dist/index-Bz1P80JN.d.mts +0 -293
- package/dist/index.cjs.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/plugins-CVrzb8x6.cjs +0 -864
- package/dist/plugins-CVrzb8x6.cjs.map +0 -1
- package/dist/plugins-ChNZ2Q8t.mjs +0 -757
- package/dist/plugins-ChNZ2Q8t.mjs.map +0 -1
|
@@ -1,757 +0,0 @@
|
|
|
1
|
-
//#region src/request/url.ts
|
|
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
|
-
* `text` with `url` redacted wherever it appears, as given or as the URL
|
|
21
|
-
* parser normalizes it — for a runtime's own message that repeats the URL.
|
|
22
|
-
*/
|
|
23
|
-
function redactUrlIn(text, url) {
|
|
24
|
-
const shown = redactUrl(url);
|
|
25
|
-
let href;
|
|
26
|
-
try {
|
|
27
|
-
href = new URL(url).href;
|
|
28
|
-
} catch {}
|
|
29
|
-
let out = text.split(url).join(shown);
|
|
30
|
-
if (href && href !== url) out = out.split(href).join(shown);
|
|
31
|
-
return out;
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* `undefined` when `url` has no origin of its own. A relative baseURL takes
|
|
35
|
-
* the page's origin in a browser and has none elsewhere.
|
|
36
|
-
*/
|
|
37
|
-
function originOf$1(url) {
|
|
38
|
-
const page = globalThis.location?.href;
|
|
39
|
-
try {
|
|
40
|
-
return new URL(url, page).origin;
|
|
41
|
-
} catch {
|
|
42
|
-
return;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
/** `path` is absolute and points away from `baseURL`'s origin. */
|
|
46
|
-
function leavesBase(baseURL, path) {
|
|
47
|
-
if (baseURL === void 0 || !isAbsoluteUrl(path)) return false;
|
|
48
|
-
const base = originOf$1(baseURL);
|
|
49
|
-
return base === void 0 || originOf$1(path) !== base;
|
|
50
|
-
}
|
|
51
|
-
function toQueryString(params) {
|
|
52
|
-
if (!params) return "";
|
|
53
|
-
if (Object.prototype.toString.call(params) === "[object URLSearchParams]") return params.toString();
|
|
54
|
-
const search = new URLSearchParams();
|
|
55
|
-
for (const [key, value] of Object.entries(params)) for (const item of Array.isArray(value) ? value : [value]) {
|
|
56
|
-
if (item === null || item === void 0) continue;
|
|
57
|
-
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())`);
|
|
58
|
-
search.append(key, String(item));
|
|
59
|
-
}
|
|
60
|
-
return search.toString();
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* Fill `{name}` placeholders with encoded values, so each one stays inside
|
|
64
|
-
* its segment: "/", "?" and "#" are encoded, and the values WHATWG URL would
|
|
65
|
-
* turn into a different path — "", "." and ".." — are refused. A placeholder
|
|
66
|
-
* without a value, or a value without a placeholder, is a mistake too.
|
|
67
|
-
*/
|
|
68
|
-
function fillPath(template, values) {
|
|
69
|
-
const used = /* @__PURE__ */ new Set();
|
|
70
|
-
const filled = template.replace(/\{([^{}/]+)\}/g, (_, name) => {
|
|
71
|
-
if (!Object.hasOwn(values, name)) throw new TypeError(`arthron: path "${template}" has {${name}} but no value for it — pass path: { ${name}: … }`);
|
|
72
|
-
used.add(name);
|
|
73
|
-
const value = String(values[name]);
|
|
74
|
-
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`);
|
|
75
|
-
return encodeURIComponent(value);
|
|
76
|
-
});
|
|
77
|
-
const unused = Object.keys(values).find((name) => !used.has(name));
|
|
78
|
-
if (unused !== void 0) throw new TypeError(`arthron: path "${template}" has no {${unused}} — add the placeholder or drop the value`);
|
|
79
|
-
return filled;
|
|
80
|
-
}
|
|
81
|
-
/**
|
|
82
|
-
* Join `baseURL` and `path` by plain string concatenation so a path prefix in
|
|
83
|
-
* the base (`/v1`) survives a leading slash in the path. WHATWG `new URL()`
|
|
84
|
-
* would drop it. An absolute path replaces the base only when it stays on the
|
|
85
|
-
* base's origin, or when `allowAbsoluteUrls` says other origins are fine — a
|
|
86
|
-
* path built from user input or an API response must not carry the client's
|
|
87
|
-
* credentials somewhere else.
|
|
88
|
-
*/
|
|
89
|
-
function resolveUrl(baseURL, path, params, allowAbsoluteUrls = false) {
|
|
90
|
-
let url;
|
|
91
|
-
if (isAbsoluteUrl(path)) {
|
|
92
|
-
if (!HTTP_URL.test(path)) {
|
|
93
|
-
const scheme = path.slice(0, path.indexOf(":") + 1);
|
|
94
|
-
throw new TypeError(`arthron: only http(s) URLs can be requested, got a "${scheme}" URL — use an http:// or https:// URL`);
|
|
95
|
-
}
|
|
96
|
-
if (!allowAbsoluteUrls && leavesBase(baseURL, path)) throw new TypeError(`arthron: ${originOf$1(path)} is outside baseURL ${(baseURL && originOf$1(baseURL)) ?? baseURL} — pass a path relative to baseURL, or set arthron({ allowAbsoluteUrls: true }) to allow other origins (config headers are not sent to them)`);
|
|
97
|
-
url = path;
|
|
98
|
-
} else {
|
|
99
|
-
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`);
|
|
100
|
-
url = `${baseURL.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
|
|
101
|
-
}
|
|
102
|
-
const query = toQueryString(params);
|
|
103
|
-
if (!query) return url;
|
|
104
|
-
const hash = url.indexOf("#");
|
|
105
|
-
const [base, fragment] = hash === -1 ? [url, ""] : [url.slice(0, hash), url.slice(hash)];
|
|
106
|
-
return `${base}${base.includes("?") ? "&" : "?"}${query}${fragment}`;
|
|
107
|
-
}
|
|
108
|
-
//#endregion
|
|
109
|
-
//#region src/error/arthron-error.ts
|
|
110
|
-
/**
|
|
111
|
-
* Marks an ArthronError across copies of this package. The ESM and CJS
|
|
112
|
-
* builds can both end up loaded (a CJS dependency creates the client, ESM
|
|
113
|
-
* app code catches), each with its own class — `Symbol.for` is shared.
|
|
114
|
-
*/
|
|
115
|
-
const BRAND = Symbol.for("arthron.ArthronError");
|
|
116
|
-
/**
|
|
117
|
-
* The only error arthron itself produces. Two sources: a response with
|
|
118
|
-
* `ok === false`, or fetch rejecting outright (network failure, `status` 0).
|
|
119
|
-
* Everything else — cancellation, interceptor bugs — is rethrown untouched.
|
|
120
|
-
*/
|
|
121
|
-
var ArthronError = class ArthronError extends Error {
|
|
122
|
-
name = "ArthronError";
|
|
123
|
-
/** HTTP status of the failed response; `0` when fetch itself failed (network). */
|
|
124
|
-
status;
|
|
125
|
-
statusText;
|
|
126
|
-
/** Parsed body: JSON if it parses, else the text, else `undefined`. */
|
|
127
|
-
data;
|
|
128
|
-
/**
|
|
129
|
-
* The server's own explanation, picked out of `data` (by default
|
|
130
|
-
* `message` → `error` → `error.message` → `detail`; see the `errorDetail`
|
|
131
|
-
* config). `undefined` when the body had none. Untrusted server text: show
|
|
132
|
-
* it to users as text, never as HTML. `message`, by contrast, is written by
|
|
133
|
-
* arthron — method, URL without query, status — and is meant for logs.
|
|
134
|
-
*/
|
|
135
|
-
detail;
|
|
136
|
-
/** The underlying error for network failures. */
|
|
137
|
-
cause;
|
|
138
|
-
constructor(init) {
|
|
139
|
-
super(init.message);
|
|
140
|
-
this.status = init.status;
|
|
141
|
-
this.statusText = init.statusText;
|
|
142
|
-
this.data = init.data;
|
|
143
|
-
this.detail = init.detail;
|
|
144
|
-
this.cause = init.cause;
|
|
145
|
-
Object.defineProperties(this, {
|
|
146
|
-
headers: { value: init.headers },
|
|
147
|
-
request: { value: init.request },
|
|
148
|
-
response: { value: init.response },
|
|
149
|
-
[BRAND]: { value: true }
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
/** `instanceof ArthronError` holds for an error from any copy of the package. */
|
|
153
|
-
static [Symbol.hasInstance](value) {
|
|
154
|
-
return this === ArthronError ? isArthronError(value) : Function.prototype[Symbol.hasInstance].call(this, value);
|
|
155
|
-
}
|
|
156
|
-
/** What serializers see: no headers, no body, no query or userinfo. */
|
|
157
|
-
toJSON() {
|
|
158
|
-
return {
|
|
159
|
-
name: this.name,
|
|
160
|
-
message: this.message,
|
|
161
|
-
detail: this.detail,
|
|
162
|
-
status: this.status,
|
|
163
|
-
statusText: this.statusText,
|
|
164
|
-
method: this.request.init.method ?? "GET",
|
|
165
|
-
url: redactUrl(this.request.url),
|
|
166
|
-
data: this.data
|
|
167
|
-
};
|
|
168
|
-
}
|
|
169
|
-
};
|
|
170
|
-
/** `true` for errors arthron produced: a `!ok` response or a network failure. Cancellations and plugin bugs are not ArthronErrors. */
|
|
171
|
-
function isArthronError(error) {
|
|
172
|
-
return typeof error === "object" && error !== null && error[BRAND] === true;
|
|
173
|
-
}
|
|
174
|
-
//#endregion
|
|
175
|
-
//#region src/request/body.ts
|
|
176
|
-
const RAW_TAGS = /* @__PURE__ */ new Set([
|
|
177
|
-
"FormData",
|
|
178
|
-
"Blob",
|
|
179
|
-
"File",
|
|
180
|
-
"ArrayBuffer",
|
|
181
|
-
"URLSearchParams",
|
|
182
|
-
"ReadableStream"
|
|
183
|
-
]);
|
|
184
|
-
/**
|
|
185
|
-
* `Symbol.toStringTag`, not `instanceof`: a body from another realm or a
|
|
186
|
-
* polyfill (formdata-node, fetch-blob) must not be JSON-encoded into `{}`.
|
|
187
|
-
*/
|
|
188
|
-
const tagOf = (value) => Object.prototype.toString.call(value).slice(8, -1);
|
|
189
|
-
function isReadableStream(value) {
|
|
190
|
-
return tagOf(value) === "ReadableStream";
|
|
191
|
-
}
|
|
192
|
-
/**
|
|
193
|
-
* Whether `RequestCtor` can send a ReadableStream body. Node and Chromium
|
|
194
|
-
* read `duplex` and leave the stream alone; Firefox ignores `duplex` and
|
|
195
|
-
* would send the text "[object ReadableStream]"; older Safari refuses it.
|
|
196
|
-
* The check from
|
|
197
|
-
* https://developer.chrome.com/docs/capabilities/web-apis/fetch-streaming-requests
|
|
198
|
-
*/
|
|
199
|
-
function canStreamRequestBody(RequestCtor) {
|
|
200
|
-
let duplexRead = false;
|
|
201
|
-
try {
|
|
202
|
-
const request = new RequestCtor("https://stream.test", {
|
|
203
|
-
method: "POST",
|
|
204
|
-
body: new ReadableStream(),
|
|
205
|
-
get duplex() {
|
|
206
|
-
duplexRead = true;
|
|
207
|
-
return "half";
|
|
208
|
-
}
|
|
209
|
-
});
|
|
210
|
-
return duplexRead && !request.headers.has("content-type");
|
|
211
|
-
} catch {
|
|
212
|
-
return false;
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
let runtimeStreams;
|
|
216
|
-
/** `canStreamRequestBody` for the global `Request`, checked once. */
|
|
217
|
-
function runtimeStreamsRequestBody() {
|
|
218
|
-
runtimeStreams ??= typeof Request !== "function" || canStreamRequestBody(Request);
|
|
219
|
-
return runtimeStreams;
|
|
220
|
-
}
|
|
221
|
-
/**
|
|
222
|
-
* What JSON.stringify would turn into `{}`, `undefined` or internal state
|
|
223
|
-
* instead of the data — with the fix, so it reads as an error message.
|
|
224
|
-
*/
|
|
225
|
-
function mangledByJson(body) {
|
|
226
|
-
if (typeof body === "function" || typeof body === "symbol") return `a ${typeof body}, which JSON cannot carry — send its data instead`;
|
|
227
|
-
if (typeof body !== "object" || body === null || Array.isArray(body)) return;
|
|
228
|
-
if (Symbol.asyncIterator in body) return "an async iterable (a Node stream?) — pass a ReadableStream (Readable.toWeb(stream)) or collect it first";
|
|
229
|
-
if (Symbol.iterator in body) return "an iterable such as a Map, Set or generator — convert it to an array or plain object first";
|
|
230
|
-
}
|
|
231
|
-
/** Bodies fetch already knows how to send. Content-Type is left to the caller / runtime. */
|
|
232
|
-
function isRawBody(body) {
|
|
233
|
-
if (typeof body === "string") return true;
|
|
234
|
-
if (ArrayBuffer.isView(body)) return true;
|
|
235
|
-
return RAW_TAGS.has(tagOf(body));
|
|
236
|
-
}
|
|
237
|
-
/**
|
|
238
|
-
* Turn a caller-supplied body into something fetch accepts. Raw bodies pass
|
|
239
|
-
* through untouched; anything else is JSON with `content-type` set — unless
|
|
240
|
-
* the caller already set one (headers arrive lowercased, so a plain lookup is
|
|
241
|
-
* enough).
|
|
242
|
-
*/
|
|
243
|
-
function serializeBody(body, headers) {
|
|
244
|
-
if (body === void 0) return {
|
|
245
|
-
body: void 0,
|
|
246
|
-
headers
|
|
247
|
-
};
|
|
248
|
-
if (tagOf(body) === "FormData") {
|
|
249
|
-
const { "content-type": _dropped, ...rest } = headers;
|
|
250
|
-
return {
|
|
251
|
-
body,
|
|
252
|
-
headers: rest
|
|
253
|
-
};
|
|
254
|
-
}
|
|
255
|
-
if (isRawBody(body)) return {
|
|
256
|
-
body,
|
|
257
|
-
headers
|
|
258
|
-
};
|
|
259
|
-
const mangled = mangledByJson(body);
|
|
260
|
-
if (mangled) throw new TypeError(`arthron: the body is ${mangled}`);
|
|
261
|
-
const type = headers["content-type"];
|
|
262
|
-
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`);
|
|
263
|
-
const withType = "content-type" in headers ? headers : {
|
|
264
|
-
...headers,
|
|
265
|
-
"content-type": "application/json"
|
|
266
|
-
};
|
|
267
|
-
return {
|
|
268
|
-
body: JSON.stringify(body),
|
|
269
|
-
headers: withType
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
//#endregion
|
|
273
|
-
//#region src/plugins/bearer-auth/bearer-auth.ts
|
|
274
|
-
/** The origin of an absolute http(s) URL; `undefined` for anything else. */
|
|
275
|
-
function originOf(url) {
|
|
276
|
-
try {
|
|
277
|
-
const { protocol, origin } = new URL(url);
|
|
278
|
-
return protocol === "http:" || protocol === "https:" ? origin : void 0;
|
|
279
|
-
} catch {
|
|
280
|
-
return;
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
function allowedOrigins(origin) {
|
|
284
|
-
const urls = typeof origin === "string" ? [origin] : origin;
|
|
285
|
-
if (urls.length === 0) throw new TypeError("arthron: bearerAuth({ origin }) needs at least one URL — e.g. origin: \"https://api.example.com\"");
|
|
286
|
-
return new Set(urls.map((url) => {
|
|
287
|
-
const found = originOf(url);
|
|
288
|
-
if (found) return found;
|
|
289
|
-
throw new TypeError(`arthron: bearerAuth({ origin }) needs an http(s) URL, got ${JSON.stringify(url)} — e.g. origin: "https://api.example.com"`);
|
|
290
|
-
}));
|
|
291
|
-
}
|
|
292
|
-
/**
|
|
293
|
-
* Bearer-token auth. A request interceptor sets `authorization: Bearer
|
|
294
|
-
* <token>` on every attempt to `origin`; with `refresh`, a middleware turns a
|
|
295
|
-
* 401 into one refresh and one more try. Concurrent 401s share the refresh
|
|
296
|
-
* (with refresh-token rotation, parallel refreshes revoke each other), and a
|
|
297
|
-
* call whose token was replaced meanwhile just retries. A call opts out with
|
|
298
|
-
* `meta: { bearerAuth: false }`.
|
|
299
|
-
*/
|
|
300
|
-
function bearerAuth(options) {
|
|
301
|
-
const { token, refresh } = options;
|
|
302
|
-
const allowed = allowedOrigins(options.origin);
|
|
303
|
-
const ours = (url) => allowed.has(originOf(url) ?? "");
|
|
304
|
-
const bearer = async () => {
|
|
305
|
-
const value = await token();
|
|
306
|
-
return value ? `Bearer ${value}` : void 0;
|
|
307
|
-
};
|
|
308
|
-
let refreshing;
|
|
309
|
-
return {
|
|
310
|
-
name: "bearerAuth",
|
|
311
|
-
request: async (ctx) => {
|
|
312
|
-
if (ctx.meta?.bearerAuth === false || !ours(ctx.url)) return ctx;
|
|
313
|
-
const value = await bearer();
|
|
314
|
-
if (!value) return ctx;
|
|
315
|
-
return {
|
|
316
|
-
...ctx,
|
|
317
|
-
init: {
|
|
318
|
-
...ctx.init,
|
|
319
|
-
headers: {
|
|
320
|
-
...ctx.init.headers,
|
|
321
|
-
authorization: value
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
};
|
|
325
|
-
},
|
|
326
|
-
middleware: async (ctx, next) => {
|
|
327
|
-
if (!refresh || ctx.meta?.bearerAuth === false) return next(ctx);
|
|
328
|
-
if (isReadableStream(ctx.init.body)) return next(ctx);
|
|
329
|
-
try {
|
|
330
|
-
return await next(ctx);
|
|
331
|
-
} catch (error) {
|
|
332
|
-
if (!isArthronError(error) || error.status !== 401) throw error;
|
|
333
|
-
if (!ours(error.request.url)) throw error;
|
|
334
|
-
if (error.request.init.headers.authorization === await bearer()) {
|
|
335
|
-
refreshing ??= refresh().finally(() => {
|
|
336
|
-
refreshing = void 0;
|
|
337
|
-
});
|
|
338
|
-
await refreshing;
|
|
339
|
-
}
|
|
340
|
-
return next(ctx);
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
//#endregion
|
|
346
|
-
//#region src/response/rebuild-response.ts
|
|
347
|
-
/**
|
|
348
|
-
* A new Response with `body` but everything else taken from `original`. The
|
|
349
|
-
* constructor resets `url`, `redirected` and `type`, so those are copied over
|
|
350
|
-
* as own properties — callers that resolve relative links or detect
|
|
351
|
-
* redirects keep working.
|
|
352
|
-
*/
|
|
353
|
-
function rebuildResponse(original, body) {
|
|
354
|
-
return withFetchedFields(new Response(body, {
|
|
355
|
-
status: original.status,
|
|
356
|
-
statusText: original.statusText,
|
|
357
|
-
headers: original.headers
|
|
358
|
-
}), original);
|
|
359
|
-
}
|
|
360
|
-
/** Copy the fields the constructor resets — onto `clone()`s as well. */
|
|
361
|
-
function withFetchedFields(target, from) {
|
|
362
|
-
const clone = target.clone.bind(target);
|
|
363
|
-
return Object.defineProperties(target, {
|
|
364
|
-
url: { value: from.url },
|
|
365
|
-
redirected: { value: from.redirected },
|
|
366
|
-
type: { value: from.type },
|
|
367
|
-
clone: { value: () => withFetchedFields(clone(), from) }
|
|
368
|
-
});
|
|
369
|
-
}
|
|
370
|
-
//#endregion
|
|
371
|
-
//#region src/error/create-error.ts
|
|
372
|
-
/**
|
|
373
|
-
* Cancellation is not an HTTP failure. Matched by name so it works across
|
|
374
|
-
* realms — or by the request's own `signal`, since `abort(reason)` rejects
|
|
375
|
-
* with whatever reason the caller chose.
|
|
376
|
-
*/
|
|
377
|
-
function isCancellation(error, signal) {
|
|
378
|
-
if (signal?.aborted) return true;
|
|
379
|
-
const name = error?.name;
|
|
380
|
-
return name === "AbortError" || name === "TimeoutError";
|
|
381
|
-
}
|
|
382
|
-
/**
|
|
383
|
-
* What a cancelled call rejects with: its signal's reason. WebKit's fetch
|
|
384
|
-
* rejects, and errors a half-read body, with a generic AbortError instead,
|
|
385
|
-
* dropping a TimeoutError or the caller's own reason.
|
|
386
|
-
*/
|
|
387
|
-
function cancellationError(error, signal) {
|
|
388
|
-
return signal?.aborted ? signal.reason : error;
|
|
389
|
-
}
|
|
390
|
-
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
391
|
-
/** `message` → `error` (string) → `error.message` → `detail`. */
|
|
392
|
-
function defaultErrorDetail(data) {
|
|
393
|
-
if (!isRecord(data)) return void 0;
|
|
394
|
-
if (typeof data.message === "string") return data.message;
|
|
395
|
-
if (typeof data.error === "string") return data.error;
|
|
396
|
-
if (isRecord(data.error) && typeof data.error.message === "string") return data.error.message;
|
|
397
|
-
if (typeof data.detail === "string") return data.detail;
|
|
398
|
-
}
|
|
399
|
-
/** 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. */
|
|
400
|
-
const MAX_ERROR_BODY_BYTES = 65536;
|
|
401
|
-
/** Up to `limit` bytes of the body; the rest is cancelled unread. `undefined` when there is no body or reading it failed. */
|
|
402
|
-
async function readCapped(response, limit) {
|
|
403
|
-
if (!response.body) return void 0;
|
|
404
|
-
let reader;
|
|
405
|
-
const chunks = [];
|
|
406
|
-
let size = 0;
|
|
407
|
-
try {
|
|
408
|
-
reader = response.body.getReader();
|
|
409
|
-
while (size <= limit) {
|
|
410
|
-
const { value, done } = await reader.read();
|
|
411
|
-
if (done) break;
|
|
412
|
-
chunks.push(value);
|
|
413
|
-
size += value.byteLength;
|
|
414
|
-
}
|
|
415
|
-
} catch {
|
|
416
|
-
return;
|
|
417
|
-
} finally {
|
|
418
|
-
await reader?.cancel().catch(() => {});
|
|
419
|
-
reader?.releaseLock();
|
|
420
|
-
}
|
|
421
|
-
const bytes = new Uint8Array(size);
|
|
422
|
-
let offset = 0;
|
|
423
|
-
for (const chunk of chunks) {
|
|
424
|
-
bytes.set(chunk, offset);
|
|
425
|
-
offset += chunk.byteLength;
|
|
426
|
-
}
|
|
427
|
-
return size > limit ? {
|
|
428
|
-
bytes: bytes.subarray(0, limit),
|
|
429
|
-
truncated: true
|
|
430
|
-
} : {
|
|
431
|
-
bytes,
|
|
432
|
-
truncated: false
|
|
433
|
-
};
|
|
434
|
-
}
|
|
435
|
-
/** JSON if the whole body parses, else the text (cut at the limit), else `undefined` when empty. */
|
|
436
|
-
function parseBody(read) {
|
|
437
|
-
const text = new TextDecoder().decode(read.bytes);
|
|
438
|
-
if (text === "") return void 0;
|
|
439
|
-
if (read.truncated) return text;
|
|
440
|
-
try {
|
|
441
|
-
return JSON.parse(text);
|
|
442
|
-
} catch {
|
|
443
|
-
return text;
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
/** The request as error messages name it: method and URL, no query or userinfo. */
|
|
447
|
-
function describeRequest(request) {
|
|
448
|
-
return `${request.init.method ?? "GET"} ${redactUrl(request.url)}`;
|
|
449
|
-
}
|
|
450
|
-
async function responseError(response, request, resolve = defaultErrorDetail) {
|
|
451
|
-
const read = await readCapped(response, MAX_ERROR_BODY_BYTES);
|
|
452
|
-
const data = read && parseBody(read);
|
|
453
|
-
if (read) response = rebuildResponse(response, read.bytes);
|
|
454
|
-
const status = response.statusText ? `${response.status} ${response.statusText}` : String(response.status);
|
|
455
|
-
return new ArthronError({
|
|
456
|
-
message: `${describeRequest(request)} failed with ${status}`,
|
|
457
|
-
detail: resolve(data, response) || void 0,
|
|
458
|
-
status: response.status,
|
|
459
|
-
statusText: response.statusText,
|
|
460
|
-
headers: response.headers,
|
|
461
|
-
data,
|
|
462
|
-
request,
|
|
463
|
-
response
|
|
464
|
-
});
|
|
465
|
-
}
|
|
466
|
-
/**
|
|
467
|
-
* Browsers that stream a request body (Chromium, current WebKit) do it only
|
|
468
|
-
* over HTTP/2, and fail one sent to an HTTP/1.1 server with the same bare
|
|
469
|
-
* "Failed to fetch" / "Load failed" as a dead server, so name the likely cause.
|
|
470
|
-
*/
|
|
471
|
-
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";
|
|
472
|
-
function networkError(cause, request) {
|
|
473
|
-
const reason = cause instanceof Error && cause.message ? redactUrlIn(cause.message, request.url) : "network error";
|
|
474
|
-
const hint = isReadableStream(request.init.body) ? STREAM_BODY_HINT : "";
|
|
475
|
-
return new ArthronError({
|
|
476
|
-
message: `${describeRequest(request)} failed: ${reason}${hint}`,
|
|
477
|
-
status: 0,
|
|
478
|
-
statusText: "",
|
|
479
|
-
headers: new Headers(),
|
|
480
|
-
data: void 0,
|
|
481
|
-
request,
|
|
482
|
-
cause
|
|
483
|
-
});
|
|
484
|
-
}
|
|
485
|
-
//#endregion
|
|
486
|
-
//#region src/plugins/logging/logging.ts
|
|
487
|
-
function consoleSink(logger) {
|
|
488
|
-
return (e) => {
|
|
489
|
-
if (e.phase === "start") logger.log(`[arthron] → ${e.method} ${e.path}`);
|
|
490
|
-
else if (e.phase === "success") logger.log(`[arthron] ← ${e.method} ${e.path} ${e.status} ${e.ms}ms`);
|
|
491
|
-
else logger.error(`[arthron] ✕ ${e.method} ${e.path} ${e.status ?? "-"} ${e.ms}ms`);
|
|
492
|
-
};
|
|
493
|
-
}
|
|
494
|
-
/**
|
|
495
|
-
* One event when a request starts, one when it settles, with status and
|
|
496
|
-
* elapsed time. Wraps the whole call, so retries are included in the time.
|
|
497
|
-
* Default output is a console line per event; pass `onEvent` to get the
|
|
498
|
-
* structured event instead. Cancellations are not reported.
|
|
499
|
-
*/
|
|
500
|
-
function logging(options = {}) {
|
|
501
|
-
const { enabled = true, logger = console, onEvent, now = () => performance.now() } = options;
|
|
502
|
-
const emit = onEvent ?? consoleSink(logger);
|
|
503
|
-
return {
|
|
504
|
-
name: "logging",
|
|
505
|
-
middleware: async (ctx, next) => {
|
|
506
|
-
if (!enabled) return next(ctx);
|
|
507
|
-
const method = ctx.init.method ?? "GET";
|
|
508
|
-
const path = redactUrl(ctx.url);
|
|
509
|
-
const started = now();
|
|
510
|
-
const ms = () => Math.round(now() - started);
|
|
511
|
-
emit({
|
|
512
|
-
phase: "start",
|
|
513
|
-
method,
|
|
514
|
-
path
|
|
515
|
-
});
|
|
516
|
-
let res;
|
|
517
|
-
try {
|
|
518
|
-
res = await next(ctx);
|
|
519
|
-
} catch (error) {
|
|
520
|
-
if (!isCancellation(error, ctx.init.signal)) {
|
|
521
|
-
const status = isArthronError(error) ? error.status : void 0;
|
|
522
|
-
emit({
|
|
523
|
-
phase: "error",
|
|
524
|
-
method,
|
|
525
|
-
path,
|
|
526
|
-
status,
|
|
527
|
-
ms: ms(),
|
|
528
|
-
error
|
|
529
|
-
});
|
|
530
|
-
}
|
|
531
|
-
throw error;
|
|
532
|
-
}
|
|
533
|
-
emit({
|
|
534
|
-
phase: "success",
|
|
535
|
-
method,
|
|
536
|
-
path,
|
|
537
|
-
status: res.status,
|
|
538
|
-
ms: ms()
|
|
539
|
-
});
|
|
540
|
-
return res;
|
|
541
|
-
}
|
|
542
|
-
};
|
|
543
|
-
}
|
|
544
|
-
//#endregion
|
|
545
|
-
//#region src/plugins/retry/retry.ts
|
|
546
|
-
const DEFAULT_RETRY_ON = [
|
|
547
|
-
408,
|
|
548
|
-
429,
|
|
549
|
-
500,
|
|
550
|
-
502,
|
|
551
|
-
503,
|
|
552
|
-
504
|
|
553
|
-
];
|
|
554
|
-
const DEFAULT_METHODS = [
|
|
555
|
-
"GET",
|
|
556
|
-
"HEAD",
|
|
557
|
-
"OPTIONS",
|
|
558
|
-
"QUERY",
|
|
559
|
-
"PUT",
|
|
560
|
-
"DELETE"
|
|
561
|
-
];
|
|
562
|
-
const DEFAULT_MAX_RETRY_AFTER = 6e4;
|
|
563
|
-
/** setTimeout fires at once past this, so every wait is capped to it. */
|
|
564
|
-
const MAX_TIMER_MS$1 = 2 ** 31 - 1;
|
|
565
|
-
function defaultSleep(ms, signal) {
|
|
566
|
-
return new Promise((resolve, reject) => {
|
|
567
|
-
if (signal?.aborted) return reject(signal.reason);
|
|
568
|
-
const onAbort = () => {
|
|
569
|
-
clearTimeout(timer);
|
|
570
|
-
reject(signal?.reason);
|
|
571
|
-
};
|
|
572
|
-
const timer = setTimeout(() => {
|
|
573
|
-
signal?.removeEventListener("abort", onAbort);
|
|
574
|
-
resolve();
|
|
575
|
-
}, ms);
|
|
576
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
577
|
-
});
|
|
578
|
-
}
|
|
579
|
-
/** `Retry-After` as ms — seconds or an HTTP-date. `undefined` when absent or unparsable. */
|
|
580
|
-
function retryAfterMs(error) {
|
|
581
|
-
const value = error.headers.get("retry-after")?.trim();
|
|
582
|
-
if (!value) return void 0;
|
|
583
|
-
const seconds = Number(value);
|
|
584
|
-
if (!Number.isNaN(seconds)) return Math.max(0, seconds * 1e3);
|
|
585
|
-
const at = Date.parse(value);
|
|
586
|
-
if (Number.isNaN(at)) return void 0;
|
|
587
|
-
return Math.max(0, at - Date.now());
|
|
588
|
-
}
|
|
589
|
-
/** The rule without `shouldRetry`: a network error or a `retryOn` status, on a method in `methods`. */
|
|
590
|
-
function byDefault(thrown, method, settings) {
|
|
591
|
-
if (!settings.allowed.has(method) || !isArthronError(thrown)) return false;
|
|
592
|
-
return thrown.status === 0 || settings.retryOn.includes(thrown.status);
|
|
593
|
-
}
|
|
594
|
-
/** Defaults filled in and `retries` checked — `attempt >= NaN` is never true, so an unset env var would retry forever. */
|
|
595
|
-
function settle$1(options, where) {
|
|
596
|
-
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;
|
|
597
|
-
if (!Number.isInteger(retries) || retries < 0) throw new TypeError(`arthron: ${where} retries: ${retries} needs a whole number ≥ 0 — e.g. retries: 2`);
|
|
598
|
-
return {
|
|
599
|
-
retries,
|
|
600
|
-
retryOn,
|
|
601
|
-
allowed: new Set(methods.map((m) => m.toUpperCase())),
|
|
602
|
-
delay,
|
|
603
|
-
maxRetryAfter,
|
|
604
|
-
shouldRetry,
|
|
605
|
-
onRetry
|
|
606
|
-
};
|
|
607
|
-
}
|
|
608
|
-
/**
|
|
609
|
-
* Retry on network errors and the configured statuses by calling `next`
|
|
610
|
-
* again — the whole attempt (request interceptors included) is re-run.
|
|
611
|
-
* Only `ArthronError` is considered; cancellation and plugin bugs pass through.
|
|
612
|
-
* A call can turn it off or override its options with `meta.retry`.
|
|
613
|
-
*/
|
|
614
|
-
function retry(options = {}) {
|
|
615
|
-
const { sleep = defaultSleep, ...rest } = options;
|
|
616
|
-
const base = settle$1(rest, "retry()");
|
|
617
|
-
return {
|
|
618
|
-
name: "retry",
|
|
619
|
-
middleware: async (ctx, next) => {
|
|
620
|
-
const override = ctx.meta?.retry;
|
|
621
|
-
if (override === false) return next(ctx);
|
|
622
|
-
const settings = override ? settle$1({
|
|
623
|
-
...rest,
|
|
624
|
-
...override
|
|
625
|
-
}, "meta.retry") : base;
|
|
626
|
-
const method = (ctx.init.method ?? "GET").toUpperCase();
|
|
627
|
-
const resendable = !isReadableStream(ctx.init.body);
|
|
628
|
-
for (let attempt = 0;; attempt += 1) try {
|
|
629
|
-
return await next(ctx);
|
|
630
|
-
} catch (thrown) {
|
|
631
|
-
if (!resendable || attempt >= settings.retries) throw thrown;
|
|
632
|
-
if (ctx.init.signal?.aborted) throw thrown;
|
|
633
|
-
const verdict = settings.shouldRetry?.(thrown, attempt, ctx);
|
|
634
|
-
if (verdict === false) throw thrown;
|
|
635
|
-
if (verdict === void 0 && !byDefault(thrown, method, settings)) throw thrown;
|
|
636
|
-
const retryAfter = isArthronError(thrown) ? retryAfterMs(thrown) : void 0;
|
|
637
|
-
if (retryAfter !== void 0 && retryAfter > settings.maxRetryAfter) throw thrown;
|
|
638
|
-
const wait = Math.min(retryAfter ?? settings.delay(attempt, thrown), MAX_TIMER_MS$1);
|
|
639
|
-
settings.onRetry?.(thrown, attempt, wait);
|
|
640
|
-
await sleep(wait, ctx.init.signal);
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
};
|
|
644
|
-
}
|
|
645
|
-
//#endregion
|
|
646
|
-
//#region src/plugins/timeout/timeout.ts
|
|
647
|
-
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
648
|
-
/**
|
|
649
|
-
* Wrap `body` so the deadline keeps running until it is fully read, and so an
|
|
650
|
-
* abort while reading surfaces as a stream error instead of a silent stall.
|
|
651
|
-
*/
|
|
652
|
-
function guardBody(body, signal, finish, onChunk) {
|
|
653
|
-
const reader = body.getReader();
|
|
654
|
-
return new ReadableStream({
|
|
655
|
-
start(controller) {
|
|
656
|
-
signal.addEventListener("abort", () => {
|
|
657
|
-
controller.error(signal.reason);
|
|
658
|
-
reader.cancel(signal.reason).catch(() => {});
|
|
659
|
-
}, { once: true });
|
|
660
|
-
},
|
|
661
|
-
async pull(controller) {
|
|
662
|
-
const { value, done } = await reader.read();
|
|
663
|
-
if (done) {
|
|
664
|
-
finish();
|
|
665
|
-
controller.close();
|
|
666
|
-
return;
|
|
667
|
-
}
|
|
668
|
-
onChunk();
|
|
669
|
-
controller.enqueue(value);
|
|
670
|
-
},
|
|
671
|
-
cancel(reason) {
|
|
672
|
-
finish();
|
|
673
|
-
return reader.cancel(reason);
|
|
674
|
-
}
|
|
675
|
-
});
|
|
676
|
-
}
|
|
677
|
-
/** setTimeout fires at once for NaN, negatives and anything past 2^31-1. */
|
|
678
|
-
function checkDeadline(ms, where) {
|
|
679
|
-
if (ms === Number.POSITIVE_INFINITY || ms >= 0 && ms <= MAX_TIMER_MS) return;
|
|
680
|
-
throw new TypeError(`arthron: ${where} needs 0–${MAX_TIMER_MS} ms — pass Infinity for no deadline`);
|
|
681
|
-
}
|
|
682
|
-
/** A timer that aborts `controller` with a TimeoutError and never keeps Node alive on its own. */
|
|
683
|
-
function deadlineTimer(controller, ms, message) {
|
|
684
|
-
const timer = setTimeout(() => controller.abort(new DOMException(message, "TimeoutError")), ms);
|
|
685
|
-
timer.unref?.();
|
|
686
|
-
return timer;
|
|
687
|
-
}
|
|
688
|
-
/** `timeout(ms)`, `timeout({ total, idle })` or the deprecated `timeout(ms, { idle })`, checked. */
|
|
689
|
-
function settle(first, second) {
|
|
690
|
-
if (typeof first === "number") {
|
|
691
|
-
checkDeadline(first, `timeout(${first})`);
|
|
692
|
-
const { idle } = second;
|
|
693
|
-
if (idle !== void 0) checkDeadline(idle, `timeout(…, { idle: ${idle} })`);
|
|
694
|
-
return {
|
|
695
|
-
ms: first,
|
|
696
|
-
idle
|
|
697
|
-
};
|
|
698
|
-
}
|
|
699
|
-
const { total, idle } = first;
|
|
700
|
-
if (total === void 0 && idle === void 0) throw new TypeError("arthron: timeout({}) needs total or idle — e.g. timeout({ total: 10_000 }) or timeout({ idle: 30_000 })");
|
|
701
|
-
if (total !== void 0) checkDeadline(total, `timeout({ total: ${total} })`);
|
|
702
|
-
if (idle !== void 0) checkDeadline(idle, `timeout({ idle: ${idle} })`);
|
|
703
|
-
return {
|
|
704
|
-
ms: total ?? Number.POSITIVE_INFINITY,
|
|
705
|
-
idle
|
|
706
|
-
};
|
|
707
|
-
}
|
|
708
|
-
function timeout(first, second = {}) {
|
|
709
|
-
const { ms, idle } = settle(first, second);
|
|
710
|
-
return {
|
|
711
|
-
name: "timeout",
|
|
712
|
-
middleware: async (ctx, next) => {
|
|
713
|
-
const deadline = ctx.meta?.timeout ?? ms;
|
|
714
|
-
if (deadline !== ms) checkDeadline(deadline, `meta.timeout: ${deadline}`);
|
|
715
|
-
const idleMs = idle === Number.POSITIVE_INFINITY ? void 0 : idle;
|
|
716
|
-
if (deadline === Number.POSITIVE_INFINITY && idleMs === void 0) return next(ctx);
|
|
717
|
-
const controller = new AbortController();
|
|
718
|
-
const outer = ctx.init.signal;
|
|
719
|
-
const signal = outer ? AbortSignal.any([outer, controller.signal]) : controller.signal;
|
|
720
|
-
const total = deadline === Number.POSITIVE_INFINITY ? void 0 : deadlineTimer(controller, deadline, `arthron: request timed out after ${deadline}ms`);
|
|
721
|
-
let quiet;
|
|
722
|
-
const stillAlive = () => {
|
|
723
|
-
if (idleMs === void 0) return;
|
|
724
|
-
clearTimeout(quiet);
|
|
725
|
-
quiet = deadlineTimer(controller, idleMs, `arthron: no data for ${idleMs}ms`);
|
|
726
|
-
};
|
|
727
|
-
const finish = () => {
|
|
728
|
-
clearTimeout(total);
|
|
729
|
-
clearTimeout(quiet);
|
|
730
|
-
};
|
|
731
|
-
stillAlive();
|
|
732
|
-
let res;
|
|
733
|
-
try {
|
|
734
|
-
res = await next({
|
|
735
|
-
...ctx,
|
|
736
|
-
init: {
|
|
737
|
-
...ctx.init,
|
|
738
|
-
signal
|
|
739
|
-
}
|
|
740
|
-
});
|
|
741
|
-
} catch (thrown) {
|
|
742
|
-
finish();
|
|
743
|
-
throw thrown;
|
|
744
|
-
}
|
|
745
|
-
if (!res.body) {
|
|
746
|
-
finish();
|
|
747
|
-
return res;
|
|
748
|
-
}
|
|
749
|
-
stillAlive();
|
|
750
|
-
return rebuildResponse(res, guardBody(res.body, signal, finish, stillAlive));
|
|
751
|
-
}
|
|
752
|
-
};
|
|
753
|
-
}
|
|
754
|
-
//#endregion
|
|
755
|
-
export { redactUrlIn as _, isCancellation as a, bearerAuth as c, serializeBody as d, ArthronError as f, redactUrl as g, leavesBase as h, cancellationError as i, isReadableStream as l, fillPath as m, retry as n, networkError as o, isArthronError as p, logging as r, responseError as s, timeout as t, runtimeStreamsRequestBody as u, resolveUrl as v };
|
|
756
|
-
|
|
757
|
-
//# sourceMappingURL=plugins-ChNZ2Q8t.mjs.map
|