arthron 0.1.0 → 1.0.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 -48
- package/dist/index.cjs +679 -261
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +306 -83
- package/dist/index.d.mts +306 -83
- package/dist/index.mjs +679 -262
- package/dist/index.mjs.map +1 -1
- package/llms.txt +46 -30
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,164 +1,228 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
//#region src/
|
|
3
|
-
const
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
2
|
+
//#region src/request/url.ts
|
|
3
|
+
const ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
4
|
+
const HTTP_URL = /^https?:\/\//i;
|
|
5
|
+
function isAbsoluteUrl(path) {
|
|
6
|
+
return ABSOLUTE_URL.test(path);
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Origin + pathname only — the query and userinfo tend to carry secrets.
|
|
10
|
+
* For anything printed: log lines, error messages, `ArthronError.toJSON`.
|
|
11
|
+
*/
|
|
12
|
+
function redactUrl(url) {
|
|
13
|
+
try {
|
|
14
|
+
const parsed = new URL(url);
|
|
15
|
+
return `${parsed.origin}${parsed.pathname}`;
|
|
16
|
+
} catch {
|
|
17
|
+
return url.split(/[?#]/)[0] ?? url;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* `undefined` when `url` has no origin of its own. A relative baseURL takes
|
|
22
|
+
* the page's origin in a browser and has none elsewhere.
|
|
23
|
+
*/
|
|
24
|
+
function originOf(url) {
|
|
25
|
+
const page = globalThis.location?.href;
|
|
26
|
+
try {
|
|
27
|
+
return new URL(url, page).origin;
|
|
28
|
+
} catch {
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** `path` is absolute and points away from `baseURL`'s origin. */
|
|
33
|
+
function leavesBase(baseURL, path) {
|
|
34
|
+
if (baseURL === void 0 || !isAbsoluteUrl(path)) return false;
|
|
35
|
+
const base = originOf(baseURL);
|
|
36
|
+
return base === void 0 || originOf(path) !== base;
|
|
37
|
+
}
|
|
38
|
+
function toQueryString(params) {
|
|
39
|
+
if (!params) return "";
|
|
40
|
+
if (Object.prototype.toString.call(params) === "[object URLSearchParams]") return params.toString();
|
|
41
|
+
const search = new URLSearchParams();
|
|
42
|
+
for (const [key, value] of Object.entries(params)) for (const item of Array.isArray(value) ? value : [value]) {
|
|
43
|
+
if (item === null || item === void 0) continue;
|
|
44
|
+
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())`);
|
|
45
|
+
search.append(key, String(item));
|
|
46
|
+
}
|
|
47
|
+
return search.toString();
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Fill `{name}` placeholders with encoded values, so each one stays inside
|
|
51
|
+
* its segment: "/", "?" and "#" are encoded, and the values WHATWG URL would
|
|
52
|
+
* turn into a different path — "", "." and ".." — are refused. A placeholder
|
|
53
|
+
* without a value, or a value without a placeholder, is a mistake too.
|
|
54
|
+
*/
|
|
55
|
+
function fillPath(template, values) {
|
|
56
|
+
const used = /* @__PURE__ */ new Set();
|
|
57
|
+
const filled = template.replace(/\{([^{}/]+)\}/g, (_, name) => {
|
|
58
|
+
if (!Object.hasOwn(values, name)) throw new TypeError(`arthron: path "${template}" has {${name}} but no value for it — pass path: { ${name}: … }`);
|
|
59
|
+
used.add(name);
|
|
60
|
+
const value = String(values[name]);
|
|
61
|
+
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`);
|
|
62
|
+
return encodeURIComponent(value);
|
|
17
63
|
});
|
|
64
|
+
const unused = Object.keys(values).find((name) => !used.has(name));
|
|
65
|
+
if (unused !== void 0) throw new TypeError(`arthron: path "${template}" has no {${unused}} — add the placeholder or drop the value`);
|
|
66
|
+
return filled;
|
|
18
67
|
}
|
|
19
68
|
/**
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
69
|
+
* Join `baseURL` and `path` by plain string concatenation so a path prefix in
|
|
70
|
+
* the base (`/v1`) survives a leading slash in the path. WHATWG `new URL()`
|
|
71
|
+
* would drop it. An absolute path replaces the base only when it stays on the
|
|
72
|
+
* base's origin, or when `allowAbsoluteUrls` says other origins are fine — a
|
|
73
|
+
* path built from user input or an API response must not carry the client's
|
|
74
|
+
* credentials somewhere else.
|
|
24
75
|
*/
|
|
25
|
-
function
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
headers
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
"
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
76
|
+
function resolveUrl(baseURL, path, params, allowAbsoluteUrls = false) {
|
|
77
|
+
let url;
|
|
78
|
+
if (isAbsoluteUrl(path)) {
|
|
79
|
+
if (!HTTP_URL.test(path)) {
|
|
80
|
+
const scheme = path.slice(0, path.indexOf(":") + 1);
|
|
81
|
+
throw new TypeError(`arthron: only http(s) URLs can be requested, got a "${scheme}" URL — use an http:// or https:// URL`);
|
|
82
|
+
}
|
|
83
|
+
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)`);
|
|
84
|
+
url = path;
|
|
85
|
+
} else {
|
|
86
|
+
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`);
|
|
87
|
+
url = `${baseURL.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
|
|
88
|
+
}
|
|
89
|
+
const query = toQueryString(params);
|
|
90
|
+
if (!query) return url;
|
|
91
|
+
const hash = url.indexOf("#");
|
|
92
|
+
const [base, fragment] = hash === -1 ? [url, ""] : [url.slice(0, hash), url.slice(hash)];
|
|
93
|
+
return `${base}${base.includes("?") ? "&" : "?"}${query}${fragment}`;
|
|
42
94
|
}
|
|
43
95
|
//#endregion
|
|
44
|
-
//#region src/error.ts
|
|
96
|
+
//#region src/error/arthron-error.ts
|
|
97
|
+
/**
|
|
98
|
+
* Marks an ArthronError across copies of this package. The ESM and CJS
|
|
99
|
+
* builds can both end up loaded (a CJS dependency creates the client, ESM
|
|
100
|
+
* app code catches), each with its own class — `Symbol.for` is shared.
|
|
101
|
+
*/
|
|
102
|
+
const BRAND = Symbol.for("arthron.ArthronError");
|
|
45
103
|
/**
|
|
46
104
|
* The only error arthron itself produces. Two sources: a response with
|
|
47
105
|
* `ok === false`, or fetch rejecting outright (network failure, `status` 0).
|
|
48
106
|
* Everything else — cancellation, interceptor bugs — is rethrown untouched.
|
|
49
107
|
*/
|
|
50
|
-
var ArthronError = class extends Error {
|
|
108
|
+
var ArthronError = class ArthronError extends Error {
|
|
51
109
|
name = "ArthronError";
|
|
52
110
|
/** HTTP status of the failed response; `0` when fetch itself failed (network). */
|
|
53
111
|
status;
|
|
54
112
|
statusText;
|
|
55
|
-
/** Response headers; empty for network failures. */
|
|
56
|
-
headers;
|
|
57
113
|
/** Parsed body: JSON if it parses, else the text, else `undefined`. */
|
|
58
114
|
data;
|
|
59
|
-
/**
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
115
|
+
/**
|
|
116
|
+
* The server's own explanation, picked out of `data` (by default
|
|
117
|
+
* `message` → `error` → `error.message` → `detail`; see the `errorDetail`
|
|
118
|
+
* config). `undefined` when the body had none. Untrusted server text: show
|
|
119
|
+
* it to users as text, never as HTML. `message`, by contrast, is written by
|
|
120
|
+
* arthron — method, URL without query, status — and is meant for logs.
|
|
121
|
+
*/
|
|
122
|
+
detail;
|
|
63
123
|
/** The underlying error for network failures. */
|
|
64
124
|
cause;
|
|
65
125
|
constructor(init) {
|
|
66
126
|
super(init.message);
|
|
67
127
|
this.status = init.status;
|
|
68
128
|
this.statusText = init.statusText;
|
|
69
|
-
this.headers = init.headers;
|
|
70
129
|
this.data = init.data;
|
|
71
|
-
this.
|
|
72
|
-
this.response = init.response;
|
|
130
|
+
this.detail = init.detail;
|
|
73
131
|
this.cause = init.cause;
|
|
132
|
+
Object.defineProperties(this, {
|
|
133
|
+
headers: { value: init.headers },
|
|
134
|
+
request: { value: init.request },
|
|
135
|
+
response: { value: init.response },
|
|
136
|
+
[BRAND]: { value: true }
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
/** `instanceof ArthronError` holds for an error from any copy of the package. */
|
|
140
|
+
static [Symbol.hasInstance](value) {
|
|
141
|
+
return this === ArthronError ? isArthronError(value) : Function.prototype[Symbol.hasInstance].call(this, value);
|
|
142
|
+
}
|
|
143
|
+
/** What serializers see: no headers, no body, no query or userinfo. */
|
|
144
|
+
toJSON() {
|
|
145
|
+
return {
|
|
146
|
+
name: this.name,
|
|
147
|
+
message: this.message,
|
|
148
|
+
detail: this.detail,
|
|
149
|
+
status: this.status,
|
|
150
|
+
statusText: this.statusText,
|
|
151
|
+
method: this.request.init.method ?? "GET",
|
|
152
|
+
url: redactUrl(this.request.url),
|
|
153
|
+
data: this.data
|
|
154
|
+
};
|
|
74
155
|
}
|
|
75
156
|
};
|
|
76
157
|
/** `true` for errors arthron produced: a `!ok` response or a network failure. Cancellations and plugin bugs are not ArthronErrors. */
|
|
77
158
|
function isArthronError(error) {
|
|
78
|
-
return error
|
|
79
|
-
}
|
|
80
|
-
/** Cancellation is not an HTTP failure. Matched by name so it works across realms. */
|
|
81
|
-
function isCancellation(error) {
|
|
82
|
-
const name = error?.name;
|
|
83
|
-
return name === "AbortError" || name === "TimeoutError";
|
|
84
|
-
}
|
|
85
|
-
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
86
|
-
/** `message` → `error` (string) → `error.message` → `detail`. */
|
|
87
|
-
function defaultErrorMessage(data) {
|
|
88
|
-
if (!isRecord(data)) return void 0;
|
|
89
|
-
if (typeof data.message === "string") return data.message;
|
|
90
|
-
if (typeof data.error === "string") return data.error;
|
|
91
|
-
if (isRecord(data.error) && typeof data.error.message === "string") return data.error.message;
|
|
92
|
-
if (typeof data.detail === "string") return data.detail;
|
|
93
|
-
}
|
|
94
|
-
/** Body as JSON if it parses, else as text, else `undefined` when empty. */
|
|
95
|
-
async function readBody(response) {
|
|
96
|
-
const text = await response.text().catch(() => "");
|
|
97
|
-
if (text === "") return void 0;
|
|
98
|
-
try {
|
|
99
|
-
return JSON.parse(text);
|
|
100
|
-
} catch {
|
|
101
|
-
return text;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
async function responseError(response, request, resolve = defaultErrorMessage) {
|
|
105
|
-
const data = await readBody(response.clone());
|
|
106
|
-
return new ArthronError({
|
|
107
|
-
message: resolve(data, response) ?? `Request failed with status ${response.status}`,
|
|
108
|
-
status: response.status,
|
|
109
|
-
statusText: response.statusText,
|
|
110
|
-
headers: response.headers,
|
|
111
|
-
data,
|
|
112
|
-
request,
|
|
113
|
-
response
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
function networkError(cause, request) {
|
|
117
|
-
return new ArthronError({
|
|
118
|
-
message: cause instanceof Error ? cause.message : "Network error",
|
|
119
|
-
status: 0,
|
|
120
|
-
statusText: "",
|
|
121
|
-
headers: new Headers(),
|
|
122
|
-
data: void 0,
|
|
123
|
-
request,
|
|
124
|
-
cause
|
|
125
|
-
});
|
|
159
|
+
return typeof error === "object" && error !== null && error[BRAND] === true;
|
|
126
160
|
}
|
|
127
161
|
//#endregion
|
|
128
|
-
//#region src/headers.ts
|
|
162
|
+
//#region src/request/headers.ts
|
|
163
|
+
const isPlainRecord = (headers) => !Array.isArray(headers) && Object.prototype.toString.call(headers) !== "[object Headers]";
|
|
129
164
|
/**
|
|
130
|
-
*
|
|
131
|
-
*
|
|
165
|
+
* Layer header sets left to right into one plain record. Names are compared
|
|
166
|
+
* case-insensitively and come back lowercased; a later layer wins, so a
|
|
167
|
+
* caller's `content-type` replaces a default `Content-Type` instead of fetch
|
|
168
|
+
* sending both values joined. `Headers` validates every value it sets.
|
|
132
169
|
*/
|
|
170
|
+
function mergeHeaders(...layers) {
|
|
171
|
+
const merged = new Headers();
|
|
172
|
+
for (const layer of layers) {
|
|
173
|
+
if (!layer) continue;
|
|
174
|
+
if (isPlainRecord(layer)) for (const [name, value] of Object.entries(layer)) if (value == null) merged.delete(name);
|
|
175
|
+
else merged.set(name, value);
|
|
176
|
+
else for (const [name, value] of new Headers(layer)) merged.set(name, value);
|
|
177
|
+
}
|
|
178
|
+
return Object.fromEntries(merged);
|
|
179
|
+
}
|
|
180
|
+
/** Normalize any header shape into a plain record with lowercased names. */
|
|
133
181
|
function toHeaderRecord(headers) {
|
|
134
|
-
|
|
135
|
-
|
|
182
|
+
return mergeHeaders(headers);
|
|
183
|
+
}
|
|
184
|
+
//#endregion
|
|
185
|
+
//#region src/pipeline/pipeline.ts
|
|
186
|
+
/** The mutable body kinds an interceptor can `append` to; anything else is shared as is. */
|
|
187
|
+
function cloneBody(body) {
|
|
188
|
+
if (typeof FormData !== "undefined" && body instanceof FormData) {
|
|
189
|
+
const copy = new FormData();
|
|
190
|
+
for (const [name, value] of body) copy.append(name, value);
|
|
191
|
+
return copy;
|
|
192
|
+
}
|
|
193
|
+
if (body instanceof URLSearchParams) return new URLSearchParams(body);
|
|
194
|
+
return body;
|
|
136
195
|
}
|
|
137
196
|
/**
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
197
|
+
* Interceptors mutate the context in place. A middleware that calls `next`
|
|
198
|
+
* again (retry) must not see the previous attempt's changes, so every attempt
|
|
199
|
+
* starts from a fresh copy of the headers and of a FormData/URLSearchParams body.
|
|
141
200
|
*/
|
|
142
|
-
function
|
|
201
|
+
function cloneContext({ url, init, meta }) {
|
|
202
|
+
const copy = {
|
|
203
|
+
...init,
|
|
204
|
+
headers: toHeaderRecord(init.headers)
|
|
205
|
+
};
|
|
206
|
+
if (init.body) copy.body = cloneBody(init.body);
|
|
143
207
|
return {
|
|
144
|
-
|
|
145
|
-
|
|
208
|
+
url,
|
|
209
|
+
init: copy,
|
|
210
|
+
meta: { ...meta }
|
|
146
211
|
};
|
|
147
212
|
}
|
|
148
|
-
//#endregion
|
|
149
|
-
//#region src/pipeline.ts
|
|
150
213
|
/**
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
*
|
|
214
|
+
* Put headers back into a plain lowercase record. A plugin written in JS (or
|
|
215
|
+
* with a cast) may hand back a `Headers` object, and the next plugin's
|
|
216
|
+
* `{ ...ctx.init.headers }` would otherwise drop every header.
|
|
154
217
|
*/
|
|
155
|
-
function
|
|
218
|
+
function normalize(ctx, previous) {
|
|
156
219
|
return {
|
|
157
|
-
|
|
220
|
+
...ctx,
|
|
158
221
|
init: {
|
|
159
|
-
...init,
|
|
160
|
-
headers: toHeaderRecord(init.headers)
|
|
161
|
-
}
|
|
222
|
+
...ctx.init,
|
|
223
|
+
headers: toHeaderRecord(ctx.init.headers)
|
|
224
|
+
},
|
|
225
|
+
meta: ctx.meta ?? previous.meta
|
|
162
226
|
};
|
|
163
227
|
}
|
|
164
228
|
/**
|
|
@@ -184,7 +248,7 @@ async function runPipeline(plugins, ctx, send) {
|
|
|
184
248
|
const attempt = async (input) => {
|
|
185
249
|
let current = cloneContext(input);
|
|
186
250
|
try {
|
|
187
|
-
for (const interceptor of request) current = await interceptor(current);
|
|
251
|
+
for (const interceptor of request) current = normalize(await interceptor(current), current);
|
|
188
252
|
let res = await send(current);
|
|
189
253
|
for (const interceptor of response) res = await interceptor(res, current);
|
|
190
254
|
return res;
|
|
@@ -198,29 +262,145 @@ async function runPipeline(plugins, ctx, send) {
|
|
|
198
262
|
const dispatch = (index, input) => {
|
|
199
263
|
const middleware = middlewares[index];
|
|
200
264
|
if (!middleware) return attempt(input);
|
|
201
|
-
return middleware(input, (next) => dispatch(index + 1,
|
|
265
|
+
return middleware(input, (next) => dispatch(index + 1, {
|
|
266
|
+
...next,
|
|
267
|
+
meta: next.meta ?? input.meta
|
|
268
|
+
}));
|
|
202
269
|
};
|
|
203
270
|
return dispatch(0, ctx);
|
|
204
271
|
}
|
|
205
272
|
//#endregion
|
|
206
|
-
//#region src/
|
|
207
|
-
|
|
208
|
-
|
|
273
|
+
//#region src/request/body.ts
|
|
274
|
+
const RAW_TAGS = /* @__PURE__ */ new Set([
|
|
275
|
+
"FormData",
|
|
276
|
+
"Blob",
|
|
277
|
+
"File",
|
|
278
|
+
"ArrayBuffer",
|
|
279
|
+
"URLSearchParams",
|
|
280
|
+
"ReadableStream"
|
|
281
|
+
]);
|
|
282
|
+
/**
|
|
283
|
+
* `Symbol.toStringTag`, not `instanceof`: a body from another realm or a
|
|
284
|
+
* polyfill (formdata-node, fetch-blob) must not be JSON-encoded into `{}`.
|
|
285
|
+
*/
|
|
286
|
+
const tagOf = (value) => Object.prototype.toString.call(value).slice(8, -1);
|
|
287
|
+
function isReadableStream(value) {
|
|
288
|
+
return tagOf(value) === "ReadableStream";
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* What JSON.stringify would turn into `{}`, `undefined` or internal state
|
|
292
|
+
* instead of the data — with the fix, so it reads as an error message.
|
|
293
|
+
*/
|
|
294
|
+
function mangledByJson(body) {
|
|
295
|
+
if (typeof body === "function" || typeof body === "symbol") return `a ${typeof body}, which JSON cannot carry — send its data instead`;
|
|
296
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) return;
|
|
297
|
+
if (Symbol.asyncIterator in body) return "an async iterable (a Node stream?) — pass a ReadableStream (Readable.toWeb(stream)) or collect it first";
|
|
298
|
+
if (Symbol.iterator in body) return "an iterable such as a Map, Set or generator — convert it to an array or plain object first";
|
|
299
|
+
}
|
|
300
|
+
/** Bodies fetch already knows how to send. Content-Type is left to the caller / runtime. */
|
|
301
|
+
function isRawBody(body) {
|
|
302
|
+
if (typeof body === "string") return true;
|
|
303
|
+
if (ArrayBuffer.isView(body)) return true;
|
|
304
|
+
return RAW_TAGS.has(tagOf(body));
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Turn a caller-supplied body into something fetch accepts. Raw bodies pass
|
|
308
|
+
* through untouched; anything else is JSON with `content-type` set — unless
|
|
309
|
+
* the caller already set one (headers arrive lowercased, so a plain lookup is
|
|
310
|
+
* enough).
|
|
311
|
+
*/
|
|
312
|
+
function serializeBody(body, headers) {
|
|
313
|
+
if (body === void 0) return {
|
|
314
|
+
body: void 0,
|
|
315
|
+
headers
|
|
316
|
+
};
|
|
317
|
+
if (tagOf(body) === "FormData") {
|
|
318
|
+
const { "content-type": _dropped, ...rest } = headers;
|
|
319
|
+
return {
|
|
320
|
+
body,
|
|
321
|
+
headers: rest
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
if (isRawBody(body)) return {
|
|
325
|
+
body,
|
|
326
|
+
headers
|
|
327
|
+
};
|
|
328
|
+
const mangled = mangledByJson(body);
|
|
329
|
+
if (mangled) throw new TypeError(`arthron: the body is ${mangled}`);
|
|
330
|
+
const type = headers["content-type"];
|
|
331
|
+
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`);
|
|
332
|
+
const withType = "content-type" in headers ? headers : {
|
|
333
|
+
...headers,
|
|
334
|
+
"content-type": "application/json"
|
|
335
|
+
};
|
|
336
|
+
return {
|
|
337
|
+
body: JSON.stringify(body),
|
|
338
|
+
headers: withType
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
//#endregion
|
|
342
|
+
//#region src/response/schema-validation.ts
|
|
343
|
+
const pathOf = (issue) => (issue.path ?? []).map((part) => String(typeof part === "object" && part !== null ? part.key : part)).join(".");
|
|
344
|
+
/**
|
|
345
|
+
* `.json(schema)` got a body that does not match. Not an ArthronError: the
|
|
346
|
+
* request succeeded — the data is what is wrong.
|
|
347
|
+
*/
|
|
348
|
+
var SchemaError = class extends Error {
|
|
349
|
+
name = "SchemaError";
|
|
350
|
+
/** Every problem the validator reported, with the path to it. */
|
|
351
|
+
issues;
|
|
352
|
+
constructor(issues) {
|
|
353
|
+
const [first] = issues;
|
|
354
|
+
const where = first ? pathOf(first) : "";
|
|
355
|
+
const more = issues.length > 1 ? ` (+${issues.length - 1} more)` : "";
|
|
356
|
+
super(`arthron: the response body does not match the schema — ${where ? `${where}: ` : ""}${first?.message ?? "invalid"}${more}. See error.issues`);
|
|
357
|
+
this.issues = issues;
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
/** Validate `data`; resolve with the schema's output or reject with a SchemaError. */
|
|
361
|
+
async function validate(schema, data) {
|
|
362
|
+
const result = await schema["~standard"].validate(data);
|
|
363
|
+
if (result.issues) throw new SchemaError(result.issues);
|
|
364
|
+
return result.value;
|
|
365
|
+
}
|
|
366
|
+
//#endregion
|
|
367
|
+
//#region src/response/stream-parser.ts
|
|
368
|
+
const DEFAULT_LIMIT = 8388608;
|
|
369
|
+
/**
|
|
370
|
+
* Yield the body line by line, reassembling lines split across chunks. Only
|
|
371
|
+
* the newly arrived text is scanned, so a long line costs linear time; a line
|
|
372
|
+
* past `maxLineLength` stops the stream instead of growing without bound.
|
|
373
|
+
*/
|
|
374
|
+
async function* lines(response, maxLineLength) {
|
|
209
375
|
if (!response.body) return;
|
|
210
376
|
const reader = response.body.getReader();
|
|
211
377
|
const decoder = new TextDecoder();
|
|
212
|
-
|
|
378
|
+
const breaks = /\r\n|\r|\n/g;
|
|
379
|
+
let pending = "";
|
|
380
|
+
let afterCR = false;
|
|
213
381
|
try {
|
|
214
382
|
while (true) {
|
|
215
383
|
const { value, done } = await reader.read();
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
384
|
+
let text = decoder.decode(value, { stream: !done });
|
|
385
|
+
if (afterCR && text.startsWith("\n")) {
|
|
386
|
+
text = text.slice(1);
|
|
387
|
+
afterCR = false;
|
|
388
|
+
}
|
|
389
|
+
if (text) afterCR = text.endsWith("\r");
|
|
390
|
+
let start = 0;
|
|
391
|
+
breaks.lastIndex = 0;
|
|
392
|
+
for (let m = breaks.exec(text); m; m = breaks.exec(text)) {
|
|
393
|
+
yield pending + text.slice(start, m.index);
|
|
394
|
+
pending = "";
|
|
395
|
+
start = breaks.lastIndex;
|
|
396
|
+
}
|
|
397
|
+
pending += text.slice(start);
|
|
398
|
+
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`);
|
|
220
399
|
if (done) break;
|
|
221
400
|
}
|
|
222
|
-
if (
|
|
401
|
+
if (pending) yield pending;
|
|
223
402
|
} finally {
|
|
403
|
+
await reader.cancel().catch(() => {});
|
|
224
404
|
reader.releaseLock();
|
|
225
405
|
}
|
|
226
406
|
}
|
|
@@ -228,28 +408,31 @@ async function* lines(response) {
|
|
|
228
408
|
* Parse a `text/event-stream` body into events. Follows the spec: a blank
|
|
229
409
|
* line dispatches, `data:` lines are joined with `\n`, one leading space
|
|
230
410
|
* after the colon is dropped, lines starting with `:` are comments, and a
|
|
231
|
-
* block without `data` is not dispatched.
|
|
411
|
+
* block without `data` — or one the stream ends inside — is not dispatched.
|
|
412
|
+
* Provider sentinels like
|
|
232
413
|
* `[DONE]` are passed through untouched — they are not part of the spec.
|
|
233
414
|
*/
|
|
234
|
-
async function* parseSse(response) {
|
|
415
|
+
async function* parseSse(response, { maxLineLength = DEFAULT_LIMIT, maxEventSize = DEFAULT_LIMIT } = {}) {
|
|
235
416
|
let data = [];
|
|
417
|
+
let size = 0;
|
|
236
418
|
let event;
|
|
237
419
|
let id;
|
|
420
|
+
let lastEventId = "";
|
|
238
421
|
let retry;
|
|
239
422
|
const flush = () => {
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
if (
|
|
246
|
-
if (
|
|
247
|
-
if (retry !== void 0) out.retry = retry;
|
|
423
|
+
const out = data.length === 0 ? void 0 : {
|
|
424
|
+
data: data.join("\n"),
|
|
425
|
+
lastEventId
|
|
426
|
+
};
|
|
427
|
+
if (out && event !== void 0) out.event = event;
|
|
428
|
+
if (out && id !== void 0) out.id = id;
|
|
429
|
+
if (out && retry !== void 0) out.retry = retry;
|
|
248
430
|
data = [];
|
|
249
|
-
|
|
431
|
+
size = 0;
|
|
432
|
+
event = id = void 0;
|
|
250
433
|
return out;
|
|
251
434
|
};
|
|
252
|
-
for await (const line of lines(response)) {
|
|
435
|
+
for await (const line of lines(response, maxLineLength)) {
|
|
253
436
|
if (line === "") {
|
|
254
437
|
const out = flush();
|
|
255
438
|
if (out) yield out;
|
|
@@ -262,38 +445,35 @@ async function* parseSse(response) {
|
|
|
262
445
|
if (value.startsWith(" ")) value = value.slice(1);
|
|
263
446
|
switch (field) {
|
|
264
447
|
case "data":
|
|
448
|
+
size += value.length + 1;
|
|
449
|
+
if (size > maxEventSize + 1) throw new RangeError(`arthron: an SSE event's data is longer than ${maxEventSize} characters — pass a larger maxEventSize to .sse() if that is expected`);
|
|
265
450
|
data.push(value);
|
|
266
451
|
break;
|
|
267
452
|
case "event":
|
|
268
453
|
event = value;
|
|
269
454
|
break;
|
|
270
455
|
case "id":
|
|
271
|
-
id = value;
|
|
456
|
+
if (!value.includes("\0")) id = lastEventId = value;
|
|
272
457
|
break;
|
|
273
|
-
case "retry":
|
|
274
|
-
const ms = Number(value);
|
|
275
|
-
if (Number.isInteger(ms) && ms >= 0) retry = ms;
|
|
276
|
-
break;
|
|
277
|
-
}
|
|
458
|
+
case "retry": if (/^\d+$/.test(value)) retry = Number(value);
|
|
278
459
|
}
|
|
279
460
|
}
|
|
280
|
-
const out = flush();
|
|
281
|
-
if (out) yield out;
|
|
282
461
|
}
|
|
283
462
|
/**
|
|
284
463
|
* Parse newline-delimited JSON. Blank lines are skipped; a malformed line
|
|
285
464
|
* rejects the iteration with the `SyntaxError` from `JSON.parse`.
|
|
286
465
|
*/
|
|
287
|
-
async function* parseNdjson(response) {
|
|
288
|
-
for await (const line of lines(response)) {
|
|
466
|
+
async function* parseNdjson(response, { maxLineLength = DEFAULT_LIMIT } = {}) {
|
|
467
|
+
for await (const line of lines(response, maxLineLength)) {
|
|
289
468
|
if (line.trim() === "") continue;
|
|
290
469
|
yield JSON.parse(line);
|
|
291
470
|
}
|
|
292
471
|
}
|
|
293
472
|
//#endregion
|
|
294
|
-
//#region src/promise.ts
|
|
473
|
+
//#region src/response/arthron-promise.ts
|
|
295
474
|
/** Defer the Response until iteration starts, so the helper itself never rejects. */
|
|
296
475
|
function iterate(promise, parse) {
|
|
476
|
+
promise.catch(() => {});
|
|
297
477
|
return { async *[Symbol.asyncIterator]() {
|
|
298
478
|
yield* parse(await promise);
|
|
299
479
|
} };
|
|
@@ -304,95 +484,280 @@ function iterate(promise, parse) {
|
|
|
304
484
|
*/
|
|
305
485
|
function toArthronPromise(promise) {
|
|
306
486
|
return Object.assign(promise, {
|
|
307
|
-
json: () => promise.then((res) =>
|
|
487
|
+
json: ((schema) => promise.then(async (res) => {
|
|
488
|
+
const data = await res.json();
|
|
489
|
+
return schema ? validate(schema, data) : data;
|
|
490
|
+
})),
|
|
308
491
|
text: () => promise.then((res) => res.text()),
|
|
309
492
|
blob: () => promise.then((res) => res.blob()),
|
|
310
493
|
arrayBuffer: () => promise.then((res) => res.arrayBuffer()),
|
|
311
494
|
formData: () => promise.then((res) => res.formData()),
|
|
312
|
-
sse: () => iterate(promise, parseSse),
|
|
313
|
-
ndjson: () => iterate(promise, parseNdjson)
|
|
495
|
+
sse: (options) => iterate(promise, (res) => parseSse(res, options)),
|
|
496
|
+
ndjson: (options) => iterate(promise, (res) => parseNdjson(res, options))
|
|
314
497
|
});
|
|
315
498
|
}
|
|
316
499
|
//#endregion
|
|
317
|
-
//#region src/
|
|
318
|
-
const ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
319
|
-
function isAbsoluteUrl(path) {
|
|
320
|
-
return ABSOLUTE_URL.test(path);
|
|
321
|
-
}
|
|
322
|
-
function toQueryString(params) {
|
|
323
|
-
if (!params) return "";
|
|
324
|
-
const search = new URLSearchParams();
|
|
325
|
-
for (const [key, value] of Object.entries(params)) {
|
|
326
|
-
if (value === null || value === void 0) continue;
|
|
327
|
-
search.append(key, String(value));
|
|
328
|
-
}
|
|
329
|
-
return search.toString();
|
|
330
|
-
}
|
|
500
|
+
//#region src/client/resolve-config.ts
|
|
331
501
|
/**
|
|
332
|
-
*
|
|
333
|
-
*
|
|
334
|
-
*
|
|
502
|
+
* Config keys that configure arthron itself; every other key is a fetch
|
|
503
|
+
* default. Typed so that a new config key fails to compile until it is
|
|
504
|
+
* listed here — otherwise it would be sent to fetch.
|
|
335
505
|
*/
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
506
|
+
const OWN_KEYS = {
|
|
507
|
+
baseURL: true,
|
|
508
|
+
allowAbsoluteUrls: true,
|
|
509
|
+
headers: true,
|
|
510
|
+
fetch: true,
|
|
511
|
+
use: true,
|
|
512
|
+
errorDetail: true,
|
|
513
|
+
throwOn: true
|
|
514
|
+
};
|
|
515
|
+
/** Fields that belong to one request, refused as client defaults. */
|
|
516
|
+
const PER_CALL_ONLY = [
|
|
517
|
+
"signal",
|
|
518
|
+
"body",
|
|
519
|
+
"method"
|
|
520
|
+
];
|
|
521
|
+
/**
|
|
522
|
+
* Add plugins to a list. A named plugin takes the place of the one already
|
|
523
|
+
* there with that name — same position, so a replaced `logging()` stays
|
|
524
|
+
* outermost and a second `retry()` does not multiply attempts. Unnamed
|
|
525
|
+
* plugins append.
|
|
526
|
+
*/
|
|
527
|
+
function addPlugins(base, added) {
|
|
528
|
+
const out = [...base];
|
|
529
|
+
for (const plugin of added) {
|
|
530
|
+
const at = plugin.name === void 0 ? -1 : out.findIndex((p) => p.name === plugin.name);
|
|
531
|
+
if (at === -1) out.push(plugin);
|
|
532
|
+
else out[at] = plugin;
|
|
342
533
|
}
|
|
343
|
-
|
|
344
|
-
if (!query) return url;
|
|
345
|
-
const hash = url.indexOf("#");
|
|
346
|
-
const [base, fragment] = hash === -1 ? [url, ""] : [url.slice(0, hash), url.slice(hash)];
|
|
347
|
-
return `${base}${base.includes("?") ? "&" : "?"}${query}${fragment}`;
|
|
534
|
+
return out;
|
|
348
535
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
536
|
+
/** The fetch defaults in a config: every set key that is not arthron's own. */
|
|
537
|
+
function fetchDefaults(config) {
|
|
538
|
+
return Object.fromEntries(Object.entries(config).filter(([key, value]) => value !== void 0 && !(key in OWN_KEYS)));
|
|
539
|
+
}
|
|
540
|
+
/** Normalize once so `extend` can merge headers and add plugins cheaply. */
|
|
353
541
|
function resolveConfig(config) {
|
|
542
|
+
for (const key of PER_CALL_ONLY) if (config[key] !== void 0) throw new TypeError(`arthron: ${key} cannot be a client default, it belongs to one request — pass it per call (api.get(path, { signal }), api.post(path, body), api.request(path, { method }))`);
|
|
354
543
|
const { headers, use, ...rest } = config;
|
|
355
544
|
return {
|
|
356
545
|
...rest,
|
|
357
546
|
headers: toHeaderRecord(headers),
|
|
358
|
-
use: use ?? []
|
|
547
|
+
use: addPlugins([], use ?? [])
|
|
359
548
|
};
|
|
360
549
|
}
|
|
550
|
+
//#endregion
|
|
551
|
+
//#region src/response/rebuild-response.ts
|
|
552
|
+
/**
|
|
553
|
+
* A new Response with `body` but everything else taken from `original`. The
|
|
554
|
+
* constructor resets `url`, `redirected` and `type`, so those are copied over
|
|
555
|
+
* as own properties — callers that resolve relative links or detect
|
|
556
|
+
* redirects keep working.
|
|
557
|
+
*/
|
|
558
|
+
function rebuildResponse(original, body) {
|
|
559
|
+
return withFetchedFields(new Response(body, {
|
|
560
|
+
status: original.status,
|
|
561
|
+
statusText: original.statusText,
|
|
562
|
+
headers: original.headers
|
|
563
|
+
}), original);
|
|
564
|
+
}
|
|
565
|
+
/** Copy the fields the constructor resets — onto `clone()`s as well. */
|
|
566
|
+
function withFetchedFields(target, from) {
|
|
567
|
+
const clone = target.clone.bind(target);
|
|
568
|
+
return Object.defineProperties(target, {
|
|
569
|
+
url: { value: from.url },
|
|
570
|
+
redirected: { value: from.redirected },
|
|
571
|
+
type: { value: from.type },
|
|
572
|
+
clone: { value: () => withFetchedFields(clone(), from) }
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
//#endregion
|
|
576
|
+
//#region src/error/create-error.ts
|
|
577
|
+
/**
|
|
578
|
+
* Cancellation is not an HTTP failure. Matched by name so it works across
|
|
579
|
+
* realms — or by the request's own `signal`, since `abort(reason)` rejects
|
|
580
|
+
* with whatever reason the caller chose.
|
|
581
|
+
*/
|
|
582
|
+
function isCancellation(error, signal) {
|
|
583
|
+
if (signal?.aborted) return true;
|
|
584
|
+
const name = error?.name;
|
|
585
|
+
return name === "AbortError" || name === "TimeoutError";
|
|
586
|
+
}
|
|
587
|
+
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
588
|
+
/** `message` → `error` (string) → `error.message` → `detail`. */
|
|
589
|
+
function defaultErrorDetail(data) {
|
|
590
|
+
if (!isRecord(data)) return void 0;
|
|
591
|
+
if (typeof data.message === "string") return data.message;
|
|
592
|
+
if (typeof data.error === "string") return data.error;
|
|
593
|
+
if (isRecord(data.error) && typeof data.error.message === "string") return data.error.message;
|
|
594
|
+
if (typeof data.detail === "string") return data.detail;
|
|
595
|
+
}
|
|
596
|
+
/** 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. */
|
|
597
|
+
const MAX_ERROR_BODY_BYTES = 65536;
|
|
598
|
+
/** Up to `limit` bytes of the body; the rest is cancelled unread. `undefined` when there is no body or reading it failed. */
|
|
599
|
+
async function readCapped(response, limit) {
|
|
600
|
+
if (!response.body) return void 0;
|
|
601
|
+
let reader;
|
|
602
|
+
const chunks = [];
|
|
603
|
+
let size = 0;
|
|
604
|
+
try {
|
|
605
|
+
reader = response.body.getReader();
|
|
606
|
+
while (size <= limit) {
|
|
607
|
+
const { value, done } = await reader.read();
|
|
608
|
+
if (done) break;
|
|
609
|
+
chunks.push(value);
|
|
610
|
+
size += value.byteLength;
|
|
611
|
+
}
|
|
612
|
+
} catch {
|
|
613
|
+
return;
|
|
614
|
+
} finally {
|
|
615
|
+
await reader?.cancel().catch(() => {});
|
|
616
|
+
reader?.releaseLock();
|
|
617
|
+
}
|
|
618
|
+
const bytes = new Uint8Array(size);
|
|
619
|
+
let offset = 0;
|
|
620
|
+
for (const chunk of chunks) {
|
|
621
|
+
bytes.set(chunk, offset);
|
|
622
|
+
offset += chunk.byteLength;
|
|
623
|
+
}
|
|
624
|
+
return size > limit ? {
|
|
625
|
+
bytes: bytes.subarray(0, limit),
|
|
626
|
+
truncated: true
|
|
627
|
+
} : {
|
|
628
|
+
bytes,
|
|
629
|
+
truncated: false
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
/** JSON if the whole body parses, else the text (cut at the limit), else `undefined` when empty. */
|
|
633
|
+
function parseBody(read) {
|
|
634
|
+
const text = new TextDecoder().decode(read.bytes);
|
|
635
|
+
if (text === "") return void 0;
|
|
636
|
+
if (read.truncated) return text;
|
|
637
|
+
try {
|
|
638
|
+
return JSON.parse(text);
|
|
639
|
+
} catch {
|
|
640
|
+
return text;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
/** The request as error messages name it: method and URL, no query or userinfo. */
|
|
644
|
+
function describeRequest(request) {
|
|
645
|
+
return `${request.init.method ?? "GET"} ${redactUrl(request.url)}`;
|
|
646
|
+
}
|
|
647
|
+
async function responseError(response, request, resolve = defaultErrorDetail) {
|
|
648
|
+
const read = await readCapped(response, MAX_ERROR_BODY_BYTES);
|
|
649
|
+
const data = read && parseBody(read);
|
|
650
|
+
if (read) response = rebuildResponse(response, read.bytes);
|
|
651
|
+
const status = response.statusText ? `${response.status} ${response.statusText}` : String(response.status);
|
|
652
|
+
return new ArthronError({
|
|
653
|
+
message: `${describeRequest(request)} failed with ${status}`,
|
|
654
|
+
detail: resolve(data, response) || void 0,
|
|
655
|
+
status: response.status,
|
|
656
|
+
statusText: response.statusText,
|
|
657
|
+
headers: response.headers,
|
|
658
|
+
data,
|
|
659
|
+
request,
|
|
660
|
+
response
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
function networkError(cause, request) {
|
|
664
|
+
return new ArthronError({
|
|
665
|
+
message: `${describeRequest(request)} failed: ${cause instanceof Error && cause.message ? cause.message : "network error"}`,
|
|
666
|
+
status: 0,
|
|
667
|
+
statusText: "",
|
|
668
|
+
headers: new Headers(),
|
|
669
|
+
data: void 0,
|
|
670
|
+
request,
|
|
671
|
+
cause
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
//#endregion
|
|
675
|
+
//#region src/client/send.ts
|
|
676
|
+
/**
|
|
677
|
+
* The global fetch rejects a malformed URL or method with a TypeError that
|
|
678
|
+
* looks just like a network failure (status 0, retried). A bodiless `Request`
|
|
679
|
+
* runs the same checks first, so those become argument errors instead. Only
|
|
680
|
+
* for the global fetch: an injected one owns its URL rules (SvelteKit's
|
|
681
|
+
* server-side `fetch` accepts relative URLs, for one).
|
|
682
|
+
*/
|
|
683
|
+
function assertSendable(url, method) {
|
|
684
|
+
if (typeof Request !== "function") return;
|
|
685
|
+
try {
|
|
686
|
+
new Request(url, { method });
|
|
687
|
+
} catch (cause) {
|
|
688
|
+
const shown = redactUrl(url);
|
|
689
|
+
const reason = (cause instanceof Error ? cause.message : String(cause)).split(url).join(shown);
|
|
690
|
+
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 });
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* Non-ok responses the caller asked for are not failures: an opaque one
|
|
695
|
+
* (`mode: "no-cors"`) and the 3xx of `redirect: "manual"`.
|
|
696
|
+
*/
|
|
697
|
+
function failedByDefault(res, init) {
|
|
698
|
+
if (res.type === "opaque" || res.type === "opaqueredirect") return false;
|
|
699
|
+
return !(init.redirect === "manual" && res.status >= 300 && res.status < 400);
|
|
700
|
+
}
|
|
701
|
+
/** The one place a failure becomes an ArthronError. Cancellation passes through. */
|
|
702
|
+
async function send(resolved, ctx, throwOn) {
|
|
703
|
+
const fetchImpl = resolved.fetch ?? globalThis.fetch;
|
|
704
|
+
if (resolved.fetch === void 0) assertSendable(ctx.url, ctx.init.method ?? "GET");
|
|
705
|
+
const { signal } = ctx.init;
|
|
706
|
+
let res;
|
|
707
|
+
try {
|
|
708
|
+
res = await fetchImpl(ctx.url, ctx.init);
|
|
709
|
+
} catch (thrown) {
|
|
710
|
+
if (isCancellation(thrown, signal)) throw thrown;
|
|
711
|
+
throw networkError(thrown, ctx);
|
|
712
|
+
}
|
|
713
|
+
if (res.ok) return res;
|
|
714
|
+
if (!(throwOn ? throwOn(res) : failedByDefault(res, ctx.init))) return res;
|
|
715
|
+
const error = await responseError(res, ctx, resolved.errorDetail);
|
|
716
|
+
if (signal?.aborted) throw signal.reason;
|
|
717
|
+
throw error;
|
|
718
|
+
}
|
|
719
|
+
//#endregion
|
|
720
|
+
//#region src/client/client.ts
|
|
721
|
+
const BODYLESS_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
722
|
+
/** Sent uppercased whatever their case; fetch itself only normalizes six. */
|
|
723
|
+
const STANDARD_METHODS = /* @__PURE__ */ new Set([
|
|
724
|
+
"GET",
|
|
725
|
+
"HEAD",
|
|
726
|
+
"POST",
|
|
727
|
+
"PUT",
|
|
728
|
+
"PATCH",
|
|
729
|
+
"DELETE",
|
|
730
|
+
"OPTIONS",
|
|
731
|
+
"QUERY"
|
|
732
|
+
]);
|
|
361
733
|
/**
|
|
362
734
|
* Build a client from config. The result is immutable — `use` and `extend`
|
|
363
735
|
* return new clients and never touch the one they were called on.
|
|
364
736
|
*/
|
|
365
737
|
function arthron(config = {}) {
|
|
366
738
|
const resolved = resolveConfig(config);
|
|
367
|
-
|
|
368
|
-
const
|
|
369
|
-
const fetchImpl = resolved.fetch ?? globalThis.fetch;
|
|
370
|
-
let res;
|
|
739
|
+
const initDefaults = fetchDefaults(resolved);
|
|
740
|
+
const dispatch = (path, method, rawBody, { params, headers: callHeaders, meta, throwOn = resolved.throwOn, path: pathValues, ...init }) => {
|
|
371
741
|
try {
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
if (
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
return res;
|
|
379
|
-
};
|
|
380
|
-
const dispatch = (path, method, rawBody, { params, headers: callHeaders, ...init }) => {
|
|
381
|
-
try {
|
|
382
|
-
if (rawBody !== void 0 && BODYLESS_METHODS.has(method.toUpperCase())) throw new TypeError(`arthron: ${method.toUpperCase()} requests cannot carry a body — send it as params (query) or switch to POST`);
|
|
383
|
-
const url = resolveUrl(resolved.baseURL, path, params);
|
|
384
|
-
const { body, headers } = serializeBody(rawBody, mergeHeaders(resolved.headers, callHeaders));
|
|
742
|
+
const upper = method.toUpperCase();
|
|
743
|
+
const verb = STANDARD_METHODS.has(upper) ? upper : method;
|
|
744
|
+
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`);
|
|
745
|
+
if (pathValues) path = fillPath(path, pathValues);
|
|
746
|
+
const url = resolveUrl(resolved.baseURL, path, params, resolved.allowAbsoluteUrls);
|
|
747
|
+
const { body, headers } = serializeBody(rawBody, mergeHeaders(leavesBase(resolved.baseURL, path) ? void 0 : resolved.headers, callHeaders));
|
|
385
748
|
const requestInit = {
|
|
386
|
-
...
|
|
749
|
+
...initDefaults,
|
|
387
750
|
...init,
|
|
388
|
-
method,
|
|
751
|
+
method: verb,
|
|
389
752
|
headers
|
|
390
753
|
};
|
|
391
754
|
if (body !== void 0) requestInit.body = body;
|
|
755
|
+
if (isReadableStream(body)) Object.assign(requestInit, { duplex: "half" });
|
|
392
756
|
return toArthronPromise(runPipeline(resolved.use, {
|
|
393
757
|
url,
|
|
394
|
-
init: requestInit
|
|
395
|
-
|
|
758
|
+
init: requestInit,
|
|
759
|
+
meta: { ...meta }
|
|
760
|
+
}, (ctx) => send(resolved, ctx, throwOn)));
|
|
396
761
|
} catch (thrown) {
|
|
397
762
|
return toArthronPromise(Promise.reject(thrown));
|
|
398
763
|
}
|
|
@@ -402,7 +767,7 @@ function arthron(config = {}) {
|
|
|
402
767
|
...resolved,
|
|
403
768
|
...next,
|
|
404
769
|
headers: mergeHeaders(resolved.headers, next.headers),
|
|
405
|
-
use:
|
|
770
|
+
use: addPlugins(resolved.use, next.use ?? [])
|
|
406
771
|
});
|
|
407
772
|
};
|
|
408
773
|
return {
|
|
@@ -412,17 +777,22 @@ function arthron(config = {}) {
|
|
|
412
777
|
post: (path, body, init = {}) => dispatch(path, "POST", body, init),
|
|
413
778
|
put: (path, body, init = {}) => dispatch(path, "PUT", body, init),
|
|
414
779
|
patch: (path, body, init = {}) => dispatch(path, "PATCH", body, init),
|
|
780
|
+
query: (path, body, init = {}) => dispatch(path, "QUERY", body, init),
|
|
415
781
|
request: (path, init) => {
|
|
416
782
|
const { method, body, ...rest } = init;
|
|
417
783
|
if (!method) return toArthronPromise(Promise.reject(/* @__PURE__ */ new TypeError("arthron: request() needs init.method — e.g. request(path, { method: \"OPTIONS\" }); use get/post/... for the common verbs")));
|
|
418
784
|
return dispatch(path, method, body, rest);
|
|
419
785
|
},
|
|
420
786
|
use: (...plugins) => derive({ use: plugins }),
|
|
421
|
-
extend: (next) => derive(next)
|
|
787
|
+
extend: (next) => derive(next),
|
|
788
|
+
without: (...names) => arthron({
|
|
789
|
+
...resolved,
|
|
790
|
+
use: resolved.use.filter((p) => p.name === void 0 || !names.includes(p.name))
|
|
791
|
+
})
|
|
422
792
|
};
|
|
423
793
|
}
|
|
424
794
|
//#endregion
|
|
425
|
-
//#region src/define.ts
|
|
795
|
+
//#region src/pipeline/define-plugin.ts
|
|
426
796
|
/** Identity helper: gives a middleware written in its own file the right parameter types. */
|
|
427
797
|
const defineMiddleware = (middleware) => middleware;
|
|
428
798
|
/** Identity helpers for each interceptor kind — `defineInterceptor.request(fn)` etc. */
|
|
@@ -434,16 +804,7 @@ const defineInterceptor = {
|
|
|
434
804
|
/** Identity helper: type-checks a plugin object literal without an annotation. */
|
|
435
805
|
const definePlugin = (plugin) => plugin;
|
|
436
806
|
//#endregion
|
|
437
|
-
//#region src/plugins/logging.ts
|
|
438
|
-
/** Origin + pathname only — the query and userinfo tend to carry secrets. */
|
|
439
|
-
function displayPath(url) {
|
|
440
|
-
try {
|
|
441
|
-
const parsed = new URL(url);
|
|
442
|
-
return `${parsed.origin}${parsed.pathname}`;
|
|
443
|
-
} catch {
|
|
444
|
-
return url.split("?")[0] ?? url;
|
|
445
|
-
}
|
|
446
|
-
}
|
|
807
|
+
//#region src/plugins/logging/logging.ts
|
|
447
808
|
function consoleSink(logger) {
|
|
448
809
|
return (e) => {
|
|
449
810
|
if (e.phase === "start") logger.log(`[arthron] → ${e.method} ${e.path}`);
|
|
@@ -465,7 +826,7 @@ function logging(options = {}) {
|
|
|
465
826
|
middleware: async (ctx, next) => {
|
|
466
827
|
if (!enabled) return next(ctx);
|
|
467
828
|
const method = ctx.init.method ?? "GET";
|
|
468
|
-
const path =
|
|
829
|
+
const path = redactUrl(ctx.url);
|
|
469
830
|
const started = now();
|
|
470
831
|
const ms = () => Math.round(now() - started);
|
|
471
832
|
emit({
|
|
@@ -473,18 +834,11 @@ function logging(options = {}) {
|
|
|
473
834
|
method,
|
|
474
835
|
path
|
|
475
836
|
});
|
|
837
|
+
let res;
|
|
476
838
|
try {
|
|
477
|
-
|
|
478
|
-
emit({
|
|
479
|
-
phase: "success",
|
|
480
|
-
method,
|
|
481
|
-
path,
|
|
482
|
-
status: res.status,
|
|
483
|
-
ms: ms()
|
|
484
|
-
});
|
|
485
|
-
return res;
|
|
839
|
+
res = await next(ctx);
|
|
486
840
|
} catch (error) {
|
|
487
|
-
if (!isCancellation(error)) {
|
|
841
|
+
if (!isCancellation(error, ctx.init.signal)) {
|
|
488
842
|
const status = isArthronError(error) ? error.status : void 0;
|
|
489
843
|
emit({
|
|
490
844
|
phase: "error",
|
|
@@ -497,11 +851,19 @@ function logging(options = {}) {
|
|
|
497
851
|
}
|
|
498
852
|
throw error;
|
|
499
853
|
}
|
|
854
|
+
emit({
|
|
855
|
+
phase: "success",
|
|
856
|
+
method,
|
|
857
|
+
path,
|
|
858
|
+
status: res.status,
|
|
859
|
+
ms: ms()
|
|
860
|
+
});
|
|
861
|
+
return res;
|
|
500
862
|
}
|
|
501
863
|
};
|
|
502
864
|
}
|
|
503
865
|
//#endregion
|
|
504
|
-
//#region src/plugins/retry.ts
|
|
866
|
+
//#region src/plugins/retry/retry.ts
|
|
505
867
|
const DEFAULT_RETRY_ON = [
|
|
506
868
|
408,
|
|
507
869
|
429,
|
|
@@ -514,10 +876,13 @@ const DEFAULT_METHODS = [
|
|
|
514
876
|
"GET",
|
|
515
877
|
"HEAD",
|
|
516
878
|
"OPTIONS",
|
|
879
|
+
"QUERY",
|
|
517
880
|
"PUT",
|
|
518
881
|
"DELETE"
|
|
519
882
|
];
|
|
520
883
|
const DEFAULT_MAX_RETRY_AFTER = 6e4;
|
|
884
|
+
/** setTimeout fires at once past this, so every wait is capped to it. */
|
|
885
|
+
const MAX_TIMER_MS$1 = 2 ** 31 - 1;
|
|
521
886
|
function defaultSleep(ms, signal) {
|
|
522
887
|
return new Promise((resolve, reject) => {
|
|
523
888
|
if (signal?.aborted) return reject(signal.reason);
|
|
@@ -542,43 +907,70 @@ function retryAfterMs(error) {
|
|
|
542
907
|
if (Number.isNaN(at)) return void 0;
|
|
543
908
|
return Math.max(0, at - Date.now());
|
|
544
909
|
}
|
|
545
|
-
|
|
546
|
-
|
|
910
|
+
/** The rule without `shouldRetry`: a network error or a `retryOn` status, on a method in `methods`. */
|
|
911
|
+
function byDefault(thrown, method, settings) {
|
|
912
|
+
if (!settings.allowed.has(method) || !isArthronError(thrown)) return false;
|
|
913
|
+
return thrown.status === 0 || settings.retryOn.includes(thrown.status);
|
|
914
|
+
}
|
|
915
|
+
/** Defaults filled in and `retries` checked — `attempt >= NaN` is never true, so an unset env var would retry forever. */
|
|
916
|
+
function settle(options, where) {
|
|
917
|
+
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;
|
|
918
|
+
if (!Number.isInteger(retries) || retries < 0) throw new TypeError(`arthron: ${where} retries: ${retries} needs a whole number ≥ 0 — e.g. retries: 2`);
|
|
919
|
+
return {
|
|
920
|
+
retries,
|
|
921
|
+
retryOn,
|
|
922
|
+
allowed: new Set(methods.map((m) => m.toUpperCase())),
|
|
923
|
+
delay,
|
|
924
|
+
maxRetryAfter,
|
|
925
|
+
shouldRetry,
|
|
926
|
+
onRetry
|
|
927
|
+
};
|
|
547
928
|
}
|
|
548
929
|
/**
|
|
549
930
|
* Retry on network errors and the configured statuses by calling `next`
|
|
550
931
|
* again — the whole attempt (request interceptors included) is re-run.
|
|
551
932
|
* Only `ArthronError` is considered; cancellation and plugin bugs pass through.
|
|
933
|
+
* A call can turn it off or override its options with `meta.retry`.
|
|
552
934
|
*/
|
|
553
935
|
function retry(options = {}) {
|
|
554
|
-
const {
|
|
555
|
-
const
|
|
936
|
+
const { sleep = defaultSleep, ...rest } = options;
|
|
937
|
+
const base = settle(rest, "retry()");
|
|
556
938
|
return {
|
|
557
939
|
name: "retry",
|
|
558
940
|
middleware: async (ctx, next) => {
|
|
941
|
+
const override = ctx.meta?.retry;
|
|
942
|
+
if (override === false) return next(ctx);
|
|
943
|
+
const settings = override ? settle({
|
|
944
|
+
...rest,
|
|
945
|
+
...override
|
|
946
|
+
}, "meta.retry") : base;
|
|
559
947
|
const method = (ctx.init.method ?? "GET").toUpperCase();
|
|
560
|
-
const
|
|
948
|
+
const resendable = !isReadableStream(ctx.init.body);
|
|
561
949
|
for (let attempt = 0;; attempt += 1) try {
|
|
562
950
|
return await next(ctx);
|
|
563
951
|
} catch (thrown) {
|
|
564
|
-
if (!
|
|
565
|
-
if (!isArthronError(thrown)) throw thrown;
|
|
566
|
-
if (thrown.status !== 0 && !retryOn.includes(thrown.status)) throw thrown;
|
|
952
|
+
if (!resendable || attempt >= settings.retries) throw thrown;
|
|
567
953
|
if (ctx.init.signal?.aborted) throw thrown;
|
|
568
|
-
const
|
|
569
|
-
if (
|
|
570
|
-
|
|
954
|
+
const verdict = settings.shouldRetry?.(thrown, attempt, ctx);
|
|
955
|
+
if (verdict === false) throw thrown;
|
|
956
|
+
if (verdict === void 0 && !byDefault(thrown, method, settings)) throw thrown;
|
|
957
|
+
const retryAfter = isArthronError(thrown) ? retryAfterMs(thrown) : void 0;
|
|
958
|
+
if (retryAfter !== void 0 && retryAfter > settings.maxRetryAfter) throw thrown;
|
|
959
|
+
const wait = Math.min(retryAfter ?? settings.delay(attempt, thrown), MAX_TIMER_MS$1);
|
|
960
|
+
settings.onRetry?.(thrown, attempt, wait);
|
|
961
|
+
await sleep(wait, ctx.init.signal);
|
|
571
962
|
}
|
|
572
963
|
}
|
|
573
964
|
};
|
|
574
965
|
}
|
|
575
966
|
//#endregion
|
|
576
|
-
//#region src/plugins/timeout.ts
|
|
967
|
+
//#region src/plugins/timeout/timeout.ts
|
|
968
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
577
969
|
/**
|
|
578
970
|
* Wrap `body` so the deadline keeps running until it is fully read, and so an
|
|
579
971
|
* abort while reading surfaces as a stream error instead of a silent stall.
|
|
580
972
|
*/
|
|
581
|
-
function guardBody(body, signal, finish) {
|
|
973
|
+
function guardBody(body, signal, finish, onChunk) {
|
|
582
974
|
const reader = body.getReader();
|
|
583
975
|
return new ReadableStream({
|
|
584
976
|
start(controller) {
|
|
@@ -594,6 +986,7 @@ function guardBody(body, signal, finish) {
|
|
|
594
986
|
controller.close();
|
|
595
987
|
return;
|
|
596
988
|
}
|
|
989
|
+
onChunk();
|
|
597
990
|
controller.enqueue(value);
|
|
598
991
|
},
|
|
599
992
|
cancel(reason) {
|
|
@@ -602,37 +995,64 @@ function guardBody(body, signal, finish) {
|
|
|
602
995
|
}
|
|
603
996
|
});
|
|
604
997
|
}
|
|
998
|
+
/** setTimeout fires at once for NaN, negatives and anything past 2^31-1. */
|
|
999
|
+
function checkDeadline(ms, where) {
|
|
1000
|
+
if (ms === Number.POSITIVE_INFINITY || ms >= 0 && ms <= MAX_TIMER_MS) return;
|
|
1001
|
+
throw new TypeError(`arthron: ${where} needs 0–${MAX_TIMER_MS} ms — pass Infinity for no deadline`);
|
|
1002
|
+
}
|
|
1003
|
+
/** A timer that aborts `controller` with a TimeoutError and never keeps Node alive on its own. */
|
|
1004
|
+
function deadlineTimer(controller, ms, message) {
|
|
1005
|
+
const timer = setTimeout(() => controller.abort(new DOMException(message, "TimeoutError")), ms);
|
|
1006
|
+
timer.unref?.();
|
|
1007
|
+
return timer;
|
|
1008
|
+
}
|
|
605
1009
|
/**
|
|
606
1010
|
* Abort the request when it takes longer than `ms` — counted from the start
|
|
607
1011
|
* of the attempt until the body has been fully read, so a server that sends
|
|
608
|
-
* headers and then stalls still trips it.
|
|
1012
|
+
* headers and then stalls still trips it. With `idle`, also abort once no
|
|
1013
|
+
* data has arrived for that long. Rejects with a `TimeoutError` (a
|
|
609
1014
|
* `DOMException`, like `AbortSignal.timeout()` would give); it is not an
|
|
610
1015
|
* `ArthronError`, so error interceptors and `retry` leave it alone.
|
|
611
1016
|
*
|
|
612
|
-
*
|
|
613
|
-
*
|
|
1017
|
+
* A call can change the total deadline with `meta.timeout`.
|
|
1018
|
+
*
|
|
1019
|
+
* Deadlines are timers on an AbortController — not `AbortSignal.timeout`,
|
|
1020
|
+
* since the idle one restarts — joined to the caller's signal with
|
|
1021
|
+
* `AbortSignal.any`.
|
|
614
1022
|
*/
|
|
615
|
-
function timeout(ms) {
|
|
1023
|
+
function timeout(ms, options = {}) {
|
|
1024
|
+
checkDeadline(ms, `timeout(${ms})`);
|
|
1025
|
+
const { idle } = options;
|
|
1026
|
+
if (idle !== void 0) checkDeadline(idle, `timeout(…, { idle: ${idle} })`);
|
|
616
1027
|
return {
|
|
617
1028
|
name: "timeout",
|
|
618
1029
|
middleware: async (ctx, next) => {
|
|
1030
|
+
const deadline = ctx.meta?.timeout ?? ms;
|
|
1031
|
+
if (deadline !== ms) checkDeadline(deadline, `meta.timeout: ${deadline}`);
|
|
1032
|
+
const idleMs = idle === Number.POSITIVE_INFINITY ? void 0 : idle;
|
|
1033
|
+
if (deadline === Number.POSITIVE_INFINITY && idleMs === void 0) return next(ctx);
|
|
619
1034
|
const controller = new AbortController();
|
|
620
1035
|
const outer = ctx.init.signal;
|
|
621
|
-
const
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
const
|
|
1036
|
+
const signal = outer ? AbortSignal.any([outer, controller.signal]) : controller.signal;
|
|
1037
|
+
const total = deadline === Number.POSITIVE_INFINITY ? void 0 : deadlineTimer(controller, deadline, `arthron: request timed out after ${deadline}ms`);
|
|
1038
|
+
let quiet;
|
|
1039
|
+
const stillAlive = () => {
|
|
1040
|
+
if (idleMs === void 0) return;
|
|
1041
|
+
clearTimeout(quiet);
|
|
1042
|
+
quiet = deadlineTimer(controller, idleMs, `arthron: no data for ${idleMs}ms`);
|
|
1043
|
+
};
|
|
625
1044
|
const finish = () => {
|
|
626
|
-
clearTimeout(
|
|
627
|
-
|
|
1045
|
+
clearTimeout(total);
|
|
1046
|
+
clearTimeout(quiet);
|
|
628
1047
|
};
|
|
1048
|
+
stillAlive();
|
|
629
1049
|
let res;
|
|
630
1050
|
try {
|
|
631
1051
|
res = await next({
|
|
632
1052
|
...ctx,
|
|
633
1053
|
init: {
|
|
634
1054
|
...ctx.init,
|
|
635
|
-
signal
|
|
1055
|
+
signal
|
|
636
1056
|
}
|
|
637
1057
|
});
|
|
638
1058
|
} catch (thrown) {
|
|
@@ -643,16 +1063,14 @@ function timeout(ms) {
|
|
|
643
1063
|
finish();
|
|
644
1064
|
return res;
|
|
645
1065
|
}
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
statusText: res.statusText,
|
|
649
|
-
headers: res.headers
|
|
650
|
-
});
|
|
1066
|
+
stillAlive();
|
|
1067
|
+
return rebuildResponse(res, guardBody(res.body, signal, finish, stillAlive));
|
|
651
1068
|
}
|
|
652
1069
|
};
|
|
653
1070
|
}
|
|
654
1071
|
//#endregion
|
|
655
1072
|
exports.ArthronError = ArthronError;
|
|
1073
|
+
exports.SchemaError = SchemaError;
|
|
656
1074
|
exports.arthron = arthron;
|
|
657
1075
|
exports.defineInterceptor = defineInterceptor;
|
|
658
1076
|
exports.defineMiddleware = defineMiddleware;
|