arthron 1.2.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.
@@ -0,0 +1,498 @@
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
+ * `url` as written, without its query, fragment and userinfo — for a value
21
+ * that may not parse, or whose origin would print as "null" (ftp://…).
22
+ */
23
+ function withoutSecrets(url) {
24
+ return (url.split(/[?#]/)[0] ?? url).replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/\\]*@/i, "$1");
25
+ }
26
+ /**
27
+ * `text` with `url` redacted wherever it appears, as given or as the URL
28
+ * parser normalizes it — for a runtime's own message that repeats the URL.
29
+ */
30
+ function redactUrlIn(text, url) {
31
+ const shown = redactUrl(url);
32
+ let href;
33
+ try {
34
+ href = new URL(url).href;
35
+ } catch {}
36
+ let out = text.split(url).join(shown);
37
+ if (href && href !== url) out = out.split(href).join(shown);
38
+ return out;
39
+ }
40
+ /**
41
+ * `undefined` when `url` has no origin of its own. A relative baseURL takes
42
+ * the page's origin in a browser and has none elsewhere.
43
+ */
44
+ function originOf(url) {
45
+ const page = globalThis.location?.href;
46
+ try {
47
+ return new URL(url, page).origin;
48
+ } catch {
49
+ return;
50
+ }
51
+ }
52
+ /** The origin of an absolute http(s) URL; `undefined` for anything else. */
53
+ function httpOrigin(url) {
54
+ try {
55
+ const { protocol, origin } = new URL(url);
56
+ return protocol === "http:" || protocol === "https:" ? origin : void 0;
57
+ } catch {
58
+ return;
59
+ }
60
+ }
61
+ /**
62
+ * The origins of a list of http(s) URLs, for an option that names where
63
+ * requests may go. An empty list or another kind of entry is a TypeError in
64
+ * the option's own words.
65
+ */
66
+ function httpOrigins(urls, errors) {
67
+ if (urls.length === 0) throw new TypeError(errors.empty);
68
+ return new Set(urls.map((url) => {
69
+ const origin = httpOrigin(url);
70
+ if (origin) return origin;
71
+ throw new TypeError(errors.invalid(JSON.stringify(withoutSecrets(url))));
72
+ }));
73
+ }
74
+ /** `allowedOrigins` as origins, checked once when the client is created. */
75
+ function originSet(urls) {
76
+ return httpOrigins(urls, {
77
+ empty: "arthron: allowedOrigins needs at least one URL — leave it out to stay on baseURL's origin",
78
+ invalid: (url) => `arthron: allowedOrigins needs http(s) URLs, got ${url} — e.g. allowedOrigins: ["https://cdn.example.com"]`
79
+ });
80
+ }
81
+ /** `path` is absolute and points away from `baseURL`'s origin. */
82
+ function leavesBase(baseURL, path) {
83
+ if (baseURL === void 0 || !isAbsoluteUrl(path)) return false;
84
+ const base = originOf(baseURL);
85
+ return base === void 0 || originOf(path) !== base;
86
+ }
87
+ function toQueryString(queryParams) {
88
+ if (!queryParams) return "";
89
+ if (Object.prototype.toString.call(queryParams) === "[object URLSearchParams]") return queryParams.toString();
90
+ const search = new URLSearchParams();
91
+ for (const [key, value] of Object.entries(queryParams)) for (const item of Array.isArray(value) ? value : [value]) {
92
+ if (item === null || item === void 0) continue;
93
+ if (typeof item === "object" || typeof item === "function") throw new TypeError(`arthron: queryParams.${key} is not a string, number or boolean — pass one of those or an array of them (dates: date.toISOString())`);
94
+ search.append(key, String(item));
95
+ }
96
+ return search.toString();
97
+ }
98
+ /**
99
+ * Fill `{name}` placeholders with encoded values, so each one stays inside
100
+ * its segment: "/", "?" and "#" are encoded, and the values WHATWG URL would
101
+ * turn into a different path — "", "." and ".." — are refused. A placeholder
102
+ * without a value, or a value without a placeholder, is a mistake too.
103
+ */
104
+ function fillPath(template, values) {
105
+ const used = /* @__PURE__ */ new Set();
106
+ const filled = template.replace(/\{([^{}/]+)\}/g, (_, name) => {
107
+ if (!Object.hasOwn(values, name)) throw new TypeError(`arthron: path "${template}" has {${name}} but no value for it — pass pathParams: { ${name}: … }`);
108
+ used.add(name);
109
+ const value = String(values[name]);
110
+ if (value === "" || value === "." || value === "..") throw new TypeError(`arthron: pathParams.${name}=${JSON.stringify(value)} would change the path, not fill a segment — pass a real id`);
111
+ return encodeURIComponent(value);
112
+ });
113
+ const unused = Object.keys(values).find((name) => !used.has(name));
114
+ if (unused !== void 0) throw new TypeError(`arthron: path "${template}" has no {${unused}} — add the placeholder or drop the value`);
115
+ return filled;
116
+ }
117
+ /**
118
+ * Join `baseURL` and `path` by plain string concatenation so a path prefix in
119
+ * the base (`/v1`) survives a leading slash in the path. WHATWG `new URL()`
120
+ * would drop it. An absolute path replaces the base only when it stays on the
121
+ * base's origin or goes to one in `allowed` (`allowedOrigins`) — a path built
122
+ * from user input or an API response must not carry the client's
123
+ * credentials somewhere else. Without a baseURL, `allowed` alone limits it.
124
+ */
125
+ function resolveUrl(baseURL, path, queryParams, allowed) {
126
+ let url;
127
+ if (isAbsoluteUrl(path)) {
128
+ if (!HTTP_URL.test(path)) {
129
+ const scheme = path.slice(0, path.indexOf(":") + 1);
130
+ throw new TypeError(`arthron: only http(s) URLs can be requested, got a "${scheme}" URL — use an http:// or https:// URL`);
131
+ }
132
+ const target = originOf(path);
133
+ if (target === void 0 && (baseURL !== void 0 || allowed)) throw new TypeError(`arthron: "${withoutSecrets(path)}" is not a valid URL — check it, or pass a path relative to baseURL`);
134
+ const listed = target !== void 0 && allowed?.has(target) === true;
135
+ if (!listed && leavesBase(baseURL, path)) {
136
+ const base = (baseURL && originOf(baseURL)) ?? withoutSecrets(baseURL ?? "");
137
+ throw new TypeError(`arthron: ${target} is outside baseURL ${base} — pass a path relative to baseURL, or add ${target} to arthron({ allowedOrigins }) (config headers are not sent there)`);
138
+ }
139
+ if (!listed && baseURL === void 0 && allowed) throw new TypeError(`arthron: ${target} is not in allowedOrigins — add it to arthron({ allowedOrigins }) or request a listed origin`);
140
+ url = path;
141
+ } else {
142
+ 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`);
143
+ url = `${baseURL.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
144
+ }
145
+ const query = toQueryString(queryParams);
146
+ if (!query) return url;
147
+ const hash = url.indexOf("#");
148
+ const [base, fragment] = hash === -1 ? [url, ""] : [url.slice(0, hash), url.slice(hash)];
149
+ return `${base}${base.includes("?") ? "&" : "?"}${query}${fragment}`;
150
+ }
151
+ //#endregion
152
+ //#region src/error/arthron-error.ts
153
+ /**
154
+ * Marks an ArthronError across copies of this package. The ESM and CJS
155
+ * builds can both end up loaded (a CJS dependency creates the client, ESM
156
+ * app code catches), each with its own class — `Symbol.for` is shared.
157
+ */
158
+ const BRAND = Symbol.for("arthron.ArthronError");
159
+ /**
160
+ * The only error arthron itself produces. Two sources: a response with
161
+ * `ok === false`, or fetch rejecting outright (network failure, `status` 0).
162
+ * Everything else — cancellation, interceptor bugs — is rethrown untouched.
163
+ */
164
+ var ArthronError = class ArthronError extends Error {
165
+ name = "ArthronError";
166
+ /** HTTP status of the failed response; `0` when fetch itself failed (network). */
167
+ status;
168
+ statusText;
169
+ /**
170
+ * The failed response's payload, parsed: JSON if it parses, else the text;
171
+ * `undefined` for a network failure, which has no response. At most 64 KiB
172
+ * is read (text if cut). `response.body`, by contrast, is the stream.
173
+ */
174
+ payload;
175
+ /**
176
+ * For people: the server's description of the failure, extracted from
177
+ * `payload` (by default its `message` → `error` → `error.message` →
178
+ * `detail`; see the `extractDescription` option). `undefined` when there was
179
+ * none, and for a network failure. Untrusted server text: show it as text,
180
+ * never as HTML. `message`, by contrast, is arthron's — method, URL
181
+ * without query, status — for logs, not for people.
182
+ */
183
+ description;
184
+ /** The underlying error for network failures, with the URL's query and userinfo taken out of its message, stack and causes. */
185
+ cause;
186
+ constructor(options) {
187
+ super(options.message);
188
+ this.status = options.status;
189
+ this.statusText = options.statusText;
190
+ this.payload = options.payload;
191
+ this.description = options.description;
192
+ this.cause = options.cause;
193
+ Object.defineProperties(this, {
194
+ headers: { value: options.headers },
195
+ requestContext: { value: options.requestContext },
196
+ response: { value: options.response },
197
+ [BRAND]: { value: true }
198
+ });
199
+ }
200
+ /** `instanceof ArthronError` holds for an error from any copy of the package. */
201
+ static [Symbol.hasInstance](value) {
202
+ return this === ArthronError ? isArthronError(value) : Function.prototype[Symbol.hasInstance].call(this, value);
203
+ }
204
+ /** What serializers see: no headers, no request body, no query or userinfo. */
205
+ toJSON() {
206
+ return {
207
+ name: this.name,
208
+ message: this.message,
209
+ description: this.description,
210
+ status: this.status,
211
+ statusText: this.statusText,
212
+ method: this.requestContext.init.method ?? "GET",
213
+ url: redactUrl(this.requestContext.url),
214
+ payload: this.payload
215
+ };
216
+ }
217
+ };
218
+ /** `true` for errors arthron produced: a `!ok` response or a network failure. Cancellations and plugin bugs are not ArthronErrors. */
219
+ function isArthronError(error) {
220
+ return typeof error === "object" && error !== null && error[BRAND] === true;
221
+ }
222
+ //#endregion
223
+ //#region src/request/body.ts
224
+ const RAW_TAGS = /* @__PURE__ */ new Set([
225
+ "FormData",
226
+ "Blob",
227
+ "File",
228
+ "ArrayBuffer",
229
+ "URLSearchParams",
230
+ "ReadableStream"
231
+ ]);
232
+ /**
233
+ * `Symbol.toStringTag`, not `instanceof`: a body from another realm or a
234
+ * polyfill (formdata-node, fetch-blob) must not be JSON-encoded into `{}`.
235
+ */
236
+ const tagOf = (value) => Object.prototype.toString.call(value).slice(8, -1);
237
+ function isReadableStream(value) {
238
+ return tagOf(value) === "ReadableStream";
239
+ }
240
+ /**
241
+ * Whether `RequestCtor` can send a ReadableStream body. Node and Chromium
242
+ * read `duplex` and leave the stream alone; Firefox ignores `duplex` and
243
+ * would send the text "[object ReadableStream]"; older Safari refuses it.
244
+ * The check from
245
+ * https://developer.chrome.com/docs/capabilities/web-apis/fetch-streaming-requests
246
+ */
247
+ function canStreamRequestBody(RequestCtor) {
248
+ let duplexRead = false;
249
+ try {
250
+ const request = new RequestCtor("https://stream.test", {
251
+ method: "POST",
252
+ body: new ReadableStream(),
253
+ get duplex() {
254
+ duplexRead = true;
255
+ return "half";
256
+ }
257
+ });
258
+ return duplexRead && !request.headers.has("content-type");
259
+ } catch {
260
+ return false;
261
+ }
262
+ }
263
+ let runtimeStreams;
264
+ /** `canStreamRequestBody` for the global `Request`, checked once. */
265
+ function runtimeStreamsRequestBody() {
266
+ runtimeStreams ??= typeof Request !== "function" || canStreamRequestBody(Request);
267
+ return runtimeStreams;
268
+ }
269
+ /**
270
+ * What JSON.stringify would turn into `{}`, `undefined` or internal state
271
+ * instead of the data — with the fix, so it reads as an error message.
272
+ */
273
+ function mangledByJson(body) {
274
+ if (typeof body === "function" || typeof body === "symbol") return `a ${typeof body}, which JSON cannot carry — send its data instead`;
275
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return;
276
+ if (Symbol.asyncIterator in body) return "an async iterable (a Node stream?) — pass a ReadableStream (Readable.toWeb(stream)) or collect it first";
277
+ if (Symbol.iterator in body) return "an iterable such as a Map, Set or generator — convert it to an array or plain object first";
278
+ }
279
+ /** Bodies fetch already knows how to send. Content-Type is left to the caller / runtime. */
280
+ function isRawBody(body) {
281
+ if (typeof body === "string") return true;
282
+ if (ArrayBuffer.isView(body)) return true;
283
+ return RAW_TAGS.has(tagOf(body));
284
+ }
285
+ /**
286
+ * Turn a caller-supplied body into something fetch accepts. Raw bodies pass
287
+ * through untouched; anything else is JSON with `content-type` set — unless
288
+ * the caller already set one (headers arrive lowercased, so a plain lookup is
289
+ * enough).
290
+ */
291
+ function serializeBody(body, headers) {
292
+ if (body === void 0) return {
293
+ body: void 0,
294
+ headers
295
+ };
296
+ if (tagOf(body) === "FormData") {
297
+ const { "content-type": _dropped, ...rest } = headers;
298
+ return {
299
+ body,
300
+ headers: rest
301
+ };
302
+ }
303
+ if (isRawBody(body)) return {
304
+ body,
305
+ headers
306
+ };
307
+ const mangled = mangledByJson(body);
308
+ if (mangled) throw new TypeError(`arthron: the body is ${mangled}`);
309
+ const type = headers["content-type"];
310
+ 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`);
311
+ const withType = "content-type" in headers ? headers : {
312
+ ...headers,
313
+ "content-type": "application/json"
314
+ };
315
+ return {
316
+ body: JSON.stringify(body),
317
+ headers: withType
318
+ };
319
+ }
320
+ //#endregion
321
+ //#region src/response/rebuild-response.ts
322
+ /**
323
+ * A new Response with `body` but everything else taken from `original`. The
324
+ * constructor resets `url`, `redirected` and `type`, so those are copied over
325
+ * as own properties — callers that resolve relative links or detect
326
+ * redirects keep working.
327
+ */
328
+ function rebuildResponse(original, body) {
329
+ const rebuilt = new Response(body, {
330
+ status: original.status,
331
+ statusText: original.statusText,
332
+ headers: original.headers
333
+ });
334
+ const { url, redirected, type } = original;
335
+ return withFields(rebuilt, {
336
+ url,
337
+ redirected,
338
+ type
339
+ });
340
+ }
341
+ /** Set those fields on `target` — and on its `clone()`s as well. */
342
+ function withFields(target, fields) {
343
+ const clone = target.clone.bind(target);
344
+ return Object.defineProperties(target, {
345
+ url: { value: fields.url },
346
+ redirected: { value: fields.redirected },
347
+ type: { value: fields.type },
348
+ clone: { value: () => withFields(clone(), fields) }
349
+ });
350
+ }
351
+ //#endregion
352
+ //#region src/error/create-error.ts
353
+ /**
354
+ * Cancellation is not an HTTP failure. Matched by name so it works across
355
+ * realms — or by the request's own `signal`, since `abort(reason)` rejects
356
+ * with whatever reason the caller chose.
357
+ */
358
+ function isCancellation(error, signal) {
359
+ if (signal?.aborted) return true;
360
+ const name = error?.name;
361
+ return name === "AbortError" || name === "TimeoutError";
362
+ }
363
+ /**
364
+ * What a cancelled call rejects with: its signal's reason. WebKit's fetch
365
+ * rejects, and errors a half-read body, with a generic AbortError instead,
366
+ * dropping a TimeoutError or the caller's own reason.
367
+ */
368
+ function cancellationError(error, signal) {
369
+ return signal?.aborted ? signal.reason : error;
370
+ }
371
+ const isRecord = (value) => typeof value === "object" && value !== null;
372
+ /** `message` → `error` (string) → `error.message` → `detail`. */
373
+ function defaultDescription(payload) {
374
+ if (!isRecord(payload)) return void 0;
375
+ if (typeof payload.message === "string") return payload.message;
376
+ if (typeof payload.error === "string") return payload.error;
377
+ if (isRecord(payload.error) && typeof payload.error.message === "string") return payload.error.message;
378
+ if (typeof payload.detail === "string") return payload.detail;
379
+ }
380
+ /** 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. */
381
+ const MAX_ERROR_BODY_BYTES = 65536;
382
+ /** Up to `limit` bytes of the body; the rest is cancelled unread. `undefined` when there is no body or reading it failed. */
383
+ async function readCapped(response, limit) {
384
+ if (!response.body) return void 0;
385
+ let reader;
386
+ const chunks = [];
387
+ let size = 0;
388
+ try {
389
+ reader = response.body.getReader();
390
+ while (size <= limit) {
391
+ const { value, done } = await reader.read();
392
+ if (done) break;
393
+ chunks.push(value);
394
+ size += value.byteLength;
395
+ }
396
+ } catch {
397
+ return;
398
+ } finally {
399
+ await reader?.cancel().catch(() => {});
400
+ reader?.releaseLock();
401
+ }
402
+ const bytes = new Uint8Array(size);
403
+ let offset = 0;
404
+ for (const chunk of chunks) {
405
+ bytes.set(chunk, offset);
406
+ offset += chunk.byteLength;
407
+ }
408
+ return size > limit ? {
409
+ bytes: bytes.subarray(0, limit),
410
+ truncated: true
411
+ } : {
412
+ bytes,
413
+ truncated: false
414
+ };
415
+ }
416
+ /** JSON if the whole body parses, else the text (cut at the limit), else `undefined` when empty. */
417
+ function parseBody(read) {
418
+ const text = new TextDecoder().decode(read.bytes);
419
+ if (text === "") return void 0;
420
+ if (read.truncated) return text;
421
+ try {
422
+ return JSON.parse(text);
423
+ } catch {
424
+ return text;
425
+ }
426
+ }
427
+ /** The request as error messages name it: method and URL, no query or userinfo. */
428
+ function describeRequest(requestContext) {
429
+ return `${requestContext.init.method ?? "GET"} ${redactUrl(requestContext.url)}`;
430
+ }
431
+ async function responseError(response, requestContext, extractDescription = defaultDescription) {
432
+ const read = await readCapped(response, MAX_ERROR_BODY_BYTES);
433
+ const payload = read && parseBody(read);
434
+ if (read) response = rebuildResponse(response, read.bytes);
435
+ const status = response.statusText ? `${response.status} ${response.statusText}` : String(response.status);
436
+ let description;
437
+ try {
438
+ description = extractDescription(payload, response) || void 0;
439
+ } catch {}
440
+ return new ArthronError({
441
+ message: `${describeRequest(requestContext)} failed with ${status}`,
442
+ description,
443
+ status: response.status,
444
+ statusText: response.statusText,
445
+ headers: response.headers,
446
+ payload,
447
+ requestContext,
448
+ response
449
+ });
450
+ }
451
+ /**
452
+ * Browsers that stream a request body (Chromium, current WebKit) do it only
453
+ * over HTTP/2, and fail one sent to an HTTP/1.1 server with the same bare
454
+ * "Failed to fetch" / "Load failed" as a dead server, so name the likely cause.
455
+ */
456
+ 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";
457
+ /**
458
+ * Take `url`'s query and userinfo out of an error the runtime threw, in
459
+ * place: its message and stack, string fields (Node's `input`), and its
460
+ * causes. `console.error` and error trackers print that chain, not
461
+ * `toJSON()`. It stays the same object, so `cause.code` and `instanceof`
462
+ * still work; a field that cannot be redefined (a frozen error) is left.
463
+ */
464
+ function redactErrorUrl(error, url, seen = /* @__PURE__ */ new Set()) {
465
+ if (typeof error !== "object" || error === null || seen.has(error)) return;
466
+ seen.add(error);
467
+ const fields = error;
468
+ for (const key of /* @__PURE__ */ new Set([
469
+ "message",
470
+ "stack",
471
+ ...Object.keys(error)
472
+ ])) {
473
+ const value = fields[key];
474
+ if (typeof value !== "string") continue;
475
+ const redacted = redactUrlIn(value, url);
476
+ if (redacted === value) continue;
477
+ try {
478
+ Object.defineProperty(error, key, { value: redacted });
479
+ } catch {}
480
+ }
481
+ redactErrorUrl(fields.cause, url, seen);
482
+ }
483
+ function networkError(cause, requestContext) {
484
+ redactErrorUrl(cause, requestContext.url);
485
+ const reason = cause instanceof Error && cause.message ? cause.message : "network error";
486
+ const hint = isReadableStream(requestContext.init.body) ? STREAM_BODY_HINT : "";
487
+ return new ArthronError({
488
+ message: `${describeRequest(requestContext)} failed: ${reason}${hint}`,
489
+ status: 0,
490
+ statusText: "",
491
+ headers: new Headers(),
492
+ payload: void 0,
493
+ requestContext,
494
+ cause
495
+ });
496
+ }
497
+ //#endregion
498
+ export { withoutSecrets as C, resolveUrl as S, leavesBase as _, responseError as a, redactUrl as b, isReadableStream as c, tagOf as d, ArthronError as f, httpOrigins as g, httpOrigin as h, redactErrorUrl as i, runtimeStreamsRequestBody as l, fillPath as m, isCancellation as n, rebuildResponse as o, isArthronError as p, networkError as r, withFields as s, cancellationError as t, serializeBody as u, originOf as v, redactUrlIn as x, originSet as y };