arthron 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,18 +3,19 @@
3
3
  A `fetch` client you assemble from plugins.
4
4
 
5
5
  ```ts
6
- import { arthron, logging, retry, timeout } from "arthron";
6
+ import { arthron } from "arthron";
7
+ import { logging, retry, timeout } from "arthron/plugins";
7
8
 
8
9
  const api = arthron({
9
10
  baseURL: "https://api.example.com",
10
- use: [logging(), timeout(10_000), retry()],
11
+ use: [logging(), timeout(10_000), retry()], // 10 s for the whole call, retries included
11
12
  });
12
13
 
13
14
  const user = await api.get("/me").json<User>();
14
15
  ```
15
16
 
16
17
  - **Plain `Response` in, plain `Response` out.** No wrapper type to learn. `.json<T>()` and friends are there when you want the body.
17
- - **Two kinds of plugin, kept apart by the types.** Middleware wraps the request and controls the flow — it can call `next` again to retry. Interceptors transform one value and return it; they cannot retry, skip, or swallow. Auth refresh, retry, timeouts, logging, and anything that reacts to how a call ended (error pages, domain errors) are middleware. Headers, trace ids and per-attempt error details are interceptors.
18
+ - **A plugin holds middleware and interceptors, kept apart by the types.** Middleware wraps the call and controls the flow — it can call `next` again to retry, or not at all. Interceptors transform one value and return it; they cannot retry, skip, or swallow. Retry, timeouts, logging, auth refresh, and anything that reacts to how a call ended (error pages, domain errors) are middleware. Headers, trace ids and per-attempt error details are interceptors. One plugin can use both: `bearerAuth` sets the header in an interceptor and refreshes in middleware.
18
19
  - **One error type, two causes.** `ArthronError` means the server said no (`!response.ok`) or the network failed (`status: 0`). Everything else — cancellation, a bug in a plugin — is rethrown as-is.
19
20
  - Zero dependencies. ESM and CJS. TypeScript types included, for TypeScript 5.0+. Node 22+ and browsers.
20
21
 
@@ -118,15 +119,15 @@ A request that is aborted or times out rejects with the abort reason — `AbortE
118
119
 
119
120
  ### Derive clients
120
121
 
121
- Clients are immutable. `use` and `extend` return a new client and leave the original alone.
122
+ Clients are immutable. `use`, `extend` and `without` return a new client and leave the original alone — so keep what they return. `api.use(plugin)` on its own line does nothing.
122
123
 
123
124
  ```ts
124
125
  const base = arthron({ baseURL: API, use: [logging(), retry()] });
125
- const authed = base.use(auth()); // base + auth
126
+ const authed = base.use(bearerAuth({ origin: API, token })); // base + auth
126
127
  const admin = authed.extend({ headers: { "x-role": "admin" } }); // authed + header
127
128
  ```
128
129
 
129
- `extend` shallow-merges the config, merges headers case-insensitively (child wins), and adds plugins the way `use` does: a plugin whose `name` is already there replaces it in place — so `streaming = base.use(timeout(120_000))` loosens the inherited `timeout`, and a second `retry()` does not multiply attempts — while unnamed plugins append. `without("retry")` returns a client without that plugin. The built-ins are named `retry`, `timeout` and `logging`.
130
+ `extend` shallow-merges the config, merges headers case-insensitively (child wins), and adds plugins the way `use` does: a plugin whose `name` is already there replaces it in place — so `streaming = base.use(timeout(120_000))` loosens the inherited `timeout`, and a second `retry()` does not multiply attempts — while unnamed plugins append. `without("retry")` returns a client without that plugin. The built-ins are named `bearerAuth`, `logging`, `retry`, `timeout` and `uploadProgress`.
130
131
 
131
132
  ## Plugins
132
133
 
@@ -145,18 +146,22 @@ type RequestContext = {
145
146
  url: string;
146
147
  init: Omit<RequestInit, "headers"> & { headers: Record<string, string> }; // lowercase names
147
148
  meta: ArthronMeta; // per-call plugin settings, never sent
149
+ fetch?: typeof fetch; // the fetch this attempt is sent with — replace it to change the transport, wrap it to observe
148
150
  };
149
151
  ```
150
152
 
151
- How one request runs:
153
+ How one request runs, with `use: [m1, m2]`:
152
154
 
153
155
  ```
154
- middleware 1
155
- middleware 2
156
- attempt ─ request interceptors → fetch → response interceptors
157
- ↘ error interceptors → throw
156
+ call → m1 (before next) → m2 (before next) ─┐
157
+ │ attempt — runs again each time a middleware calls next again
158
+ │ request interceptors → fetch → response interceptors
159
+ │ ↘ error interceptors → throw
160
+ call ← m1 (after next) ← m2 (after next) ←─┘
158
161
  ```
159
162
 
163
+ A middleware is called once. `await next(ctx)` runs everything inside it and resumes the same call with the result — or the error, to `catch`. Request interceptors are not the outermost layer, as axios users may expect: they run inside every middleware, on every attempt. That is why a retry sends a refreshed token or a new trace id without extra code, and why a `timeout` also bounds a slow interceptor.
164
+
160
165
  | | Middleware | Interceptor |
161
166
  |---|---|---|
162
167
  | Runs | Once per call, wrapping everything below | Once per attempt |
@@ -169,6 +174,30 @@ Every attempt starts from a fresh copy of the context, so a header set by an int
169
174
 
170
175
  ### Built in
171
176
 
177
+ The built-in plugins come from `arthron/plugins`: `import { bearerAuth, logging, retry, timeout, uploadProgress } from "arthron/plugins"`. They are plain plugins — anything they do, yours can. `logging`, `retry` and `timeout` are also exported from `arthron` itself, as they were in 1.0; those exports are deprecated and go in the next major.
178
+
179
+ | plugin | slots | per call |
180
+ |---|---|---|
181
+ | `bearerAuth` | request interceptor (the header) + middleware (refresh on 401) | `meta: { bearerAuth: false }` |
182
+ | `retry` | middleware | `meta: { retry: false \| options }` |
183
+ | `timeout` | middleware | `meta: { timeout: ms }` |
184
+ | `logging` | middleware | — |
185
+ | `uploadProgress` | request interceptor (picks the transport) | `meta: { onUploadProgress }` — only calls that pass it |
186
+
187
+ Order is meaning: the first plugin is outermost. A good default:
188
+
189
+ ```ts
190
+ use: [logging(), bearerAuth(…), timeout(10_000), retry()]
191
+ ```
192
+
193
+ `logging` first logs each call once — its start, and its end with the total time, retries included. A `timeout` before `retry` bounds the whole call; after it, each attempt — and a timed-out attempt is not retried. `bearerAuth` sets its header on every attempt wherever it sits. Anything that should see only the final outcome — an error page, mapping to domain errors — goes before `retry`.
194
+
195
+ Plugins with the same name replace each other, so a second `timeout()` takes the first one's place instead of adding a deadline. For both a total and a per-attempt deadline, rename one:
196
+
197
+ ```ts
198
+ use: [{ ...timeout(30_000), name: "callTimeout" }, retry(), timeout(10_000)] // 30 s in all, 10 s per attempt
199
+ ```
200
+
172
201
  #### `retry(options)`
173
202
 
174
203
  Re-runs the attempt on network failure or a retryable status. Because it re-runs the whole attempt, request interceptors run again — a refreshed token or a new trace id is picked up automatically.
@@ -187,11 +216,13 @@ Honours `Retry-After` (seconds or HTTP date). Never retries a `ReadableStream` b
187
216
 
188
217
  Opting a non-idempotent method in (`methods: ["POST"]`) means a network failure is retried too, and a dropped connection may already have reached the server. Where a duplicate would hurt — a payment, an LLM completion you pay for — keep retries to statuses: `shouldRetry: (e) => (isArthronError(e) && e.status === 0 ? false : undefined)`. Per call, `meta: { retry: false }` turns it off and `meta: { retry: { retries: 5 } }` overrides any option but `sleep`.
189
218
 
190
- #### `timeout(ms, { idle? })`
219
+ #### `timeout(ms)` / `timeout({ total?, idle? })`
191
220
 
192
221
  Aborts the attempt after `ms`, counted until the body has been fully read — a server that sends headers and then stalls still trips it. Rejects with a `TimeoutError`, which `retry` and error interceptors ignore. Combines with a `signal` you pass yourself. `Infinity` means no deadline. The timer never keeps a Node process alive on its own. Per call, `meta: { timeout: 120_000 }` replaces the deadline (`Infinity` lifts it).
193
222
 
194
- A total deadline also cuts off a stream that is still flowing. For streams, bound the silence instead: `timeout(Infinity, { idle: 30_000 })` aborts only after 30 s without data — waiting for headers or between chunks — however long the stream runs. Both can be combined: `timeout(600_000, { idle: 30_000 })`.
223
+ A total deadline also cuts off a stream that is still flowing. For streams, bound the silence instead: `timeout({ idle: 30_000 })` aborts only after 30 s without data — waiting for headers or between chunks — however long the stream runs. Both can be combined: `timeout({ total: 600_000, idle: 30_000 })`; `timeout(ms)` is `timeout({ total: ms })`. Options with neither are a `TypeError`.
224
+
225
+ `timeout(ms, { idle })` still works but is deprecated; it goes in the next major.
195
226
 
196
227
  ```ts
197
228
  arthron({ use: [retry(), timeout(5_000)] }); // 5 s per attempt — a timed-out attempt is not retried
@@ -214,54 +245,93 @@ arthron({ use: [timeout(5_000), retry()] }); // 5 s for all attempts together
214
245
 
215
246
  Query strings and `user:pass@` are never printed. Cancellations are not logged.
216
247
 
248
+ #### `bearerAuth(options)`
249
+
250
+ Bearer tokens, with a refresh on 401.
251
+
252
+ ```ts
253
+ const api = arthron({
254
+ baseURL: API,
255
+ use: [
256
+ bearerAuth({
257
+ origin: API,
258
+ token: () => session.accessToken,
259
+ refresh: async () => {
260
+ const res = await api.post("/token/refresh", undefined, { meta: { bearerAuth: false } }).json<{ access_token: string }>();
261
+ session.accessToken = res.access_token;
262
+ },
263
+ }),
264
+ ],
265
+ });
266
+ ```
267
+
268
+ | option | default | |
269
+ |---|---|---|
270
+ | `origin` | required | a URL or several; only their origins count, so `baseURL` works as is. Anything that is not an http(s) URL is a `TypeError` |
271
+ | `token` | required | `() => string \| null \| undefined`, or a promise of one; read on every attempt. No token, no header |
272
+ | `refresh` | — | `() => Promise<void>`, called after a 401; then the call is redone once. Without it, a 401 is thrown as is |
273
+
274
+ The token goes to `origin` only — never to a CDN or a URL taken from a response body. Concurrent 401s share one refresh: with refresh-token rotation, parallel refreshes would revoke each other and log the user out. A call whose token was already replaced by another call's refresh retries without refreshing again. A second 401 is thrown, and so is a failed refresh — every call waiting on it rejects with the error `refresh` threw, so that is the place to send the user to a login page. The 401 of a `ReadableStream` body is thrown without a refresh: the first try has read the stream, so there is nothing to resend.
275
+
276
+ Per call, `meta: { bearerAuth: false }` sends no token and never refreshes. Use it for the login and refresh endpoints: a refresh request that went through `bearerAuth()` would, on its own 401, wait for itself.
277
+
278
+ The token is treated as opaque: to refresh a JWT ahead of its `exp`, do it inside `token()`. It is not for cookie sessions: it tells whether another call already refreshed by comparing the `authorization` header a call sent with the current one, and an httpOnly cookie cannot be read to compare.
279
+
280
+ #### `uploadProgress()`
281
+
282
+ Does nothing by itself — only a call that passes `meta.onUploadProgress` reports progress. Every other call, on the same client too, goes out exactly as before.
283
+
284
+ ```ts
285
+ const api = arthron({ baseURL: API, use: [retry(), uploadProgress()] }); // last in use
286
+
287
+ await api.get("/me"); // as usual
288
+ await api.post("/files", file, {
289
+ meta: { onUploadProgress: ({ loaded, total, progress }) => setBar(progress) }, // this call only
290
+ });
291
+ ```
292
+
293
+ The event: `loaded` (bytes sent), `total` (bytes in the body, `undefined` when unknown — a stream without `content-length`), `progress` (`loaded / total` from 0 to 1, `undefined` with `total`). Progress counts what was handed to the network, so it reaches 1 a moment before the server has it all; the response arriving is the end. Each attempt counts from 0 again, so a retried upload starts the bar over.
294
+
295
+ How that call is sent depends on where it runs:
296
+
297
+ - **Browser:** over `XMLHttpRequest`, the only browser API that reports upload progress. On another origin, the upload listener makes every such call send a CORS preflight — an S3 bucket's CORS rules must allow the method and headers. The response arrives whole: `.sse()` / `.ndjson()` are not live on that call. What XHR cannot honour and would change the call is refused with a `TypeError` before sending: `redirect: "manual" | "error"`, `mode: "no-cors"`, and `credentials: "omit"` to the page's own origin (XHR always sends its cookies there). What only tunes fetch — `cache`, `priority`, `referrerPolicy`, `integrity`, `keepalive` — is ignored on that call. A `ReadableStream` body is sent as usual, without progress.
298
+ - **Node:** with `fetch` as usual, the body counted as it is read, in steps of at most 64 KiB. `content-length` and the content type a `Blob` would set are kept, so an S3 presigned `PUT` accepts it. A `FormData` body is encoded with its length known up front, its files streamed rather than read into memory. jsdom on Node counts the same way.
299
+ - **Anywhere else** — Deno, Bun, Cloudflare Workers, an Electron main process, a service worker — and on a client with an injected `fetch` or another plugin's transport: sent as usual, without progress.
300
+
301
+ A callback that throws fails the call with its own error, untouched: not an `ArthronError`, not retried. Put `uploadProgress()` last in `use`: a request interceptor after it that replaces `init.signal` would cut that path, and the error would come back as a network failure.
302
+
217
303
  ### Write your own
218
304
 
219
305
  `definePlugin`, `defineMiddleware` and `defineInterceptor.{request,response,error}` are identity functions that give you the parameter types without annotations.
220
306
 
307
+ **`return await next(ctx)` inside `try`.** Without `await`, the promise is returned before it settles, and the `catch` never sees its error.
308
+
309
+ **Per attempt or per call.** A request interceptor runs on every attempt, so it fits a value that must be fresh each time: a token, a signature with a timestamp, a span id. A value that must be the same on every attempt — an idempotency key, so the server can tell a retry from a second payment — is set once, by a middleware placed before `retry()`:
310
+
311
+ ```ts
312
+ const idempotent = defineMiddleware((ctx, next) =>
313
+ next({ ...ctx, init: { ...ctx.init, headers: { ...ctx.init.headers, "idempotency-key": crypto.randomUUID() } } }),
314
+ );
315
+ // A client of its own, so the order is exactly this: the key first, then retry.
316
+ const payments = arthron({ baseURL: API, use: [{ name: "idempotency", middleware: idempotent }, retry({ methods: ["POST"] })] });
317
+ ```
318
+
319
+ (`api.use(…)` would not do here if `api` already has a `retry()`: the new one takes the old one's place, which may be before the key.)
320
+
221
321
  **Per-call settings.** `api.get(path, { meta })` hands `meta` to every plugin as `ctx.meta` and never sends it. Declare your own keys once and they are typed everywhere:
222
322
 
223
323
  ```ts
224
324
  declare module "arthron" {
225
325
  interface ArthronMeta {
226
- skipAuth?: boolean;
326
+ skipTrace?: boolean;
227
327
  }
228
328
  }
229
329
 
230
- api.use({ request: (ctx) => (ctx.meta.skipAuth ? ctx : withToken(ctx)) });
231
- api.get("/health", { meta: { skipAuth: true } });
330
+ const traced = api.use({ request: (ctx) => (ctx.meta.skipTrace ? ctx : withTraceId(ctx)) });
331
+ traced.get("/health", { meta: { skipTrace: true } });
232
332
  ```
233
333
 
234
- **Refresh a session on 401, then redo the request.** The refresh is flow, so it is middleware. The header is a value, so it is a request interceptor — and because `next` re-runs the interceptors, the retried request carries the new token without extra code. Two details matter in production: concurrent 401s must share one refresh (with refresh-token rotation, parallel refreshes revoke each other), and the token must only go to your API's origin. Tested in [`examples/auth-refresh.ts`](examples/auth-refresh.ts).
235
-
236
- ```ts
237
- import { definePlugin, isArthronError } from "arthron";
238
-
239
- export const auth = (store: { token: () => string | null; refresh: () => Promise<void> }, origin: string) => {
240
- let refreshing: Promise<void> | undefined;
241
- const bearer = () => (store.token() ? `Bearer ${store.token()}` : undefined);
242
- return definePlugin({
243
- name: "auth",
244
- request: (ctx) => {
245
- const value = bearer();
246
- if (!value || new URL(ctx.url).origin !== origin) return ctx;
247
- return { ...ctx, init: { ...ctx.init, headers: { ...ctx.init.headers, authorization: value } } };
248
- },
249
- middleware: async (ctx, next) => {
250
- try {
251
- return await next(ctx);
252
- } catch (e) {
253
- if (!isArthronError(e) || e.status !== 401) throw e;
254
- // Refresh only if the failed token is still current — else another call already did.
255
- if (e.request.init.headers.authorization === bearer()) {
256
- refreshing ??= store.refresh().finally(() => (refreshing = undefined));
257
- await refreshing; // a failed refresh rejects here: the caller sees it
258
- }
259
- return next(ctx);
260
- }
261
- },
262
- });
263
- };
264
- ```
334
+ **Refresh a session on 401, then redo the request.** That is the built-in [`bearerAuth()`](#bearerauthoptions), and a model for your own: the refresh is flow, so it is middleware; the header is a value, so it is a request interceptor — and because `next` re-runs the interceptors, the redone request carries the new token without extra code. Read [`src/plugins/bearer-auth/bearer-auth.ts`](src/plugins/bearer-auth/bearer-auth.ts) before writing a variant for another scheme.
265
335
 
266
336
  **Send users to an error page.** This reacts to how the *call* ended, so it is middleware placed before `retry()`: it sees only the final result. An error interceptor would run on every failed attempt and navigate away even when the next retry succeeds. Error interceptors are for enriching the error of one attempt. Tested in [`examples/error-page.ts`](examples/error-page.ts).
267
337
 
@@ -292,7 +362,7 @@ The same shape maps errors to your own types: `catch (e) { throw toDomainError(e
292
362
  **Attach a trace id.** A one-line request interceptor.
293
363
 
294
364
  ```ts
295
- api.use({ request: (ctx) => ({ ...ctx, init: { ...ctx.init, headers: { ...ctx.init.headers, "x-trace-id": crypto.randomUUID() } } }) });
365
+ const traced = api.use({ request: (ctx) => ({ ...ctx, init: { ...ctx.init, headers: { ...ctx.init.headers, "x-trace-id": crypto.randomUUID() } } }) });
296
366
  ```
297
367
 
298
368
  ## Reference
@@ -303,7 +373,7 @@ api.use({ request: (ctx) => ({ ...ctx, init: { ...ctx.init, headers: { ...ctx.in
303
373
  type ArthronConfig = {
304
374
  baseURL?: string;
305
375
  allowAbsoluteUrls?: boolean; // let absolute URLs leave baseURL's origin (without config headers)
306
- headers?: HeadersInit | Record<string, string | null>; // null drops a header (in extend)
376
+ headers?: HeadersOption; // anything fetch's headers take, or a record whose null drops a header (in extend)
307
377
  fetch?: typeof fetch; // inject for tests or a polyfill; resolved per request
308
378
  use?: Plugin[];
309
379
  errorDetail?: (data: unknown, res: Response) => string | undefined; // picks ArthronError.detail out of the body
@@ -363,7 +433,7 @@ class ArthronError extends Error {
363
433
 
364
434
  - `CHANGELOG.md` lists every release and the semver rules arthron follows since 1.0.
365
435
  - `llms.txt` ships in the package — a compressed API reference meant to be read by LLM-based tools (`node_modules/arthron/llms.txt`).
366
- - `examples/` holds type-checked, runnable recipes: LLM streaming, auth refresh, an error page, upload/download. `examples/recipes.test.ts` keeps the auth and error-page recipes honest.
436
+ - `examples/` holds type-checked, runnable recipes: LLM streaming, auth refresh, an error page, upload/download. `examples/recipes.test.ts` keeps the error-page recipe honest.
367
437
  - Error messages state the fix (`… — pass baseURL in arthron({ baseURL }) or use an absolute URL`).
368
438
 
369
439
  ## Security
@@ -0,0 +1,333 @@
1
+ //#region src/types/request.types.d.ts
2
+ /**
3
+ * What plugins see and return. `init.headers` is always a plain record with
4
+ * lowercased names — spread it, read it, add to it — and the pipeline puts
5
+ * it back into that shape after every request interceptor.
6
+ */
7
+ interface RequestContext {
8
+ url: string;
9
+ init: Omit<RequestInit, "headers"> & {
10
+ headers: Record<string, string>;
11
+ };
12
+ /** Per-call settings for plugins (`RequestOptions.meta`); never sent. */
13
+ meta: ArthronMeta;
14
+ /**
15
+ * The fetch this attempt is sent with — the client's `fetch`, else the
16
+ * global one. Always set on contexts arthron creates; replace it to change
17
+ * the transport for this attempt, wrap it to observe. Optional so a
18
+ * context you build yourself stays valid.
19
+ */
20
+ fetch?: typeof fetch;
21
+ }
22
+ /**
23
+ * Per-call settings for plugins, passed as `api.get(path, { meta })` and
24
+ * carried next to `init` — never sent to fetch. The built-in plugins read
25
+ * `bearerAuth`, `onUploadProgress`, `retry` and `timeout`; your own add keys
26
+ * by augmentation:
27
+ *
28
+ * ```ts
29
+ * declare module "arthron" {
30
+ * interface ArthronMeta { skipTrace?: boolean }
31
+ * }
32
+ * ```
33
+ */
34
+ interface ArthronMeta {
35
+ /**
36
+ * `false` sends this call without the `bearerAuth()` token and never refreshes
37
+ * on its 401 — for the login and token-refresh endpoints.
38
+ */
39
+ bearerAuth?: false;
40
+ /**
41
+ * Upload progress for this call, with `uploadProgress()` on the client.
42
+ * Never called without that plugin or without a body, nor where progress
43
+ * cannot be had: a client with an injected `fetch`, another plugin's
44
+ * transport, Deno, Bun, Cloudflare Workers, a service worker, or a
45
+ * `ReadableStream` body in a browser — those calls are sent as usual.
46
+ */
47
+ onUploadProgress?: (event: UploadProgressEvent) => void;
48
+ /** `false` turns `retry()` off for this call; an object overrides its options. */
49
+ retry?: false | Omit<RetryOptions, "sleep">;
50
+ /** Deadline for this call in ms, overriding `timeout(ms)`. `Infinity` lifts it. */
51
+ timeout?: number;
52
+ }
53
+ /** One step of an upload, as `meta.onUploadProgress` receives it. */
54
+ type UploadProgressEvent = {
55
+ /** Bytes sent so far. */
56
+ loaded: number;
57
+ /** Bytes in the whole body; `undefined` when it cannot be known (a stream without content-length). */
58
+ total: number | undefined;
59
+ /** `loaded / total`, from 0 to 1; `undefined` when `total` is. */
60
+ progress: number | undefined;
61
+ };
62
+ type RetryOptions = {
63
+ /** Number of retries after the first attempt. Default 2 (3 requests total). */
64
+ retries?: number;
65
+ /** Statuses worth retrying. Network errors (status 0) always are. */
66
+ retryOn?: readonly number[];
67
+ /** Methods safe to repeat (QUERY is, per RFC 10008). Compared case-insensitively. */
68
+ methods?: readonly string[];
69
+ /**
70
+ * Backoff in ms for retry number `retry` (0-based). Default "full jitter":
71
+ * a random share of 300 · 2^retry, so clients that failed together do not
72
+ * retry together.
73
+ */
74
+ delay?: (retry: number, error: unknown) => number;
75
+ /**
76
+ * Your own verdict on one failure: `true` retries, `false` stops,
77
+ * `undefined` leaves it to `retryOn`/`methods`. It sees every error — a
78
+ * TimeoutError from a `timeout()` placed after `retry()` included — but
79
+ * cannot exceed `retries`, resend a `ReadableStream` body, or retry a call
80
+ * the caller aborted.
81
+ */
82
+ shouldRetry?: (error: unknown, attempt: number, ctx: RequestContext) => boolean | undefined;
83
+ /** Called before each wait, for logs and metrics. */
84
+ onRetry?: (error: unknown, attempt: number, waitMs: number) => void;
85
+ /** Injectable for tests. Default `setTimeout`; rejects with the abort reason. */
86
+ sleep?: (ms: number, signal?: AbortSignal | null) => Promise<void>;
87
+ /**
88
+ * Longest `Retry-After` (ms) worth honouring. Beyond it the request is not
89
+ * retried at all. Default 60 000.
90
+ */
91
+ maxRetryAfter?: number;
92
+ };
93
+ type QueryValue = string | number | boolean | null | undefined;
94
+ /**
95
+ * Query parameters. `null`/`undefined` values are skipped, an array becomes
96
+ * repeated keys (`ids=1&ids=2`), and a `URLSearchParams` is used as is.
97
+ */
98
+ type QueryParams = Record<string, QueryValue | readonly QueryValue[]> | URLSearchParams;
99
+ /**
100
+ * Headers as config and per-call options accept them: anything fetch's
101
+ * `headers` takes, or a plain object whose `null`/`undefined` values delete
102
+ * that header from the layer underneath (a client default, an inherited
103
+ * header). Not spelled `HeadersInit`: that name exists only in the DOM lib,
104
+ * and a Node project typed with `@types/node` alone does not have it.
105
+ */
106
+ type HeadersOption = NonNullable<RequestInit["headers"]> | Record<string, string | null | undefined>;
107
+ //#endregion
108
+ //#region src/error/arthron-error.d.ts
109
+ type ArthronErrorInit = {
110
+ message: string;
111
+ status: number;
112
+ statusText: string;
113
+ headers: Headers;
114
+ data: unknown;
115
+ detail?: string | undefined;
116
+ request: RequestContext;
117
+ response?: Response;
118
+ cause?: unknown;
119
+ };
120
+ /**
121
+ * The only error arthron itself produces. Two sources: a response with
122
+ * `ok === false`, or fetch rejecting outright (network failure, `status` 0).
123
+ * Everything else — cancellation, interceptor bugs — is rethrown untouched.
124
+ */
125
+ declare class ArthronError extends Error {
126
+ readonly name = "ArthronError";
127
+ /** HTTP status of the failed response; `0` when fetch itself failed (network). */
128
+ readonly status: number;
129
+ readonly statusText: string;
130
+ /** Response headers; empty for network failures. Not enumerable — kept out of logs. */
131
+ readonly headers: Headers;
132
+ /** Parsed body: JSON if it parses, else the text, else `undefined`. */
133
+ readonly data: unknown;
134
+ /**
135
+ * The server's own explanation, picked out of `data` (by default
136
+ * `message` → `error` → `error.message` → `detail`; see the `errorDetail`
137
+ * config). `undefined` when the body had none. Untrusted server text: show
138
+ * it to users as text, never as HTML. `message`, by contrast, is written by
139
+ * arthron — method, URL without query, status — and is meant for logs.
140
+ */
141
+ readonly detail: string | undefined;
142
+ /**
143
+ * The context that was sent — url and init after request interceptors.
144
+ * Not enumerable: it holds credentials, so `JSON.stringify`, `console.error`
145
+ * and error trackers leave it out. Read it directly when you need it.
146
+ */
147
+ readonly request: RequestContext;
148
+ /** The failed Response, still readable — its body holds what arthron read (at most 64 KiB). Absent for network failures. Not enumerable. */
149
+ readonly response: Response | undefined;
150
+ /** The underlying error for network failures. */
151
+ readonly cause: unknown;
152
+ constructor(init: ArthronErrorInit);
153
+ /** `instanceof ArthronError` holds for an error from any copy of the package. */
154
+ static [Symbol.hasInstance](value: unknown): boolean;
155
+ /** What serializers see: no headers, no body, no query or userinfo. */
156
+ toJSON(): {
157
+ name: string;
158
+ message: string;
159
+ detail: string | undefined;
160
+ status: number;
161
+ statusText: string;
162
+ method: string;
163
+ url: string;
164
+ data: unknown;
165
+ };
166
+ }
167
+ /** `true` for errors arthron produced: a `!ok` response or a network failure. Cancellations and plugin bugs are not ArthronErrors. */
168
+ declare function isArthronError(error: unknown): error is ArthronError;
169
+ //#endregion
170
+ //#region src/types/plugin.types.d.ts
171
+ /** Runs before each attempt. Returns the context to send (may be a new object). */
172
+ type RequestInterceptor = (ctx: RequestContext) => RequestContext | Promise<RequestContext>;
173
+ /** Runs after a successful attempt. The body is single-use — `clone()` to peek. */
174
+ type ResponseInterceptor = (res: Response, ctx: RequestContext) => Response | Promise<Response>;
175
+ /** Runs after a failed attempt. Returns the error to throw; it is always thrown. */
176
+ type ErrorInterceptor = (err: ArthronError, ctx: RequestContext) => ArthronError | Promise<ArthronError>;
177
+ /**
178
+ * Wraps the whole call. `next` runs everything below it (request interceptors →
179
+ * fetch → response/error interceptors) and may be called again to retry.
180
+ * `next` rejects with an `ArthronError`, or with the untouched original when the
181
+ * failure was a cancellation or a bug in a plugin.
182
+ */
183
+ type Middleware = (ctx: RequestContext, next: (ctx: RequestContext) => Promise<Response>) => Promise<Response>;
184
+ interface Plugin {
185
+ /**
186
+ * Identity within a client: `use`/`extend` replace the plugin of the same
187
+ * name in place, `without(name)` removes it. The built-ins are named
188
+ * "bearerAuth", "logging", "retry", "timeout" and "uploadProgress". Leave it out to always
189
+ * append.
190
+ */
191
+ name?: string;
192
+ middleware?: Middleware;
193
+ request?: RequestInterceptor;
194
+ response?: ResponseInterceptor;
195
+ error?: ErrorInterceptor;
196
+ }
197
+ //#endregion
198
+ //#region src/plugins/bearer-auth/bearer-auth.types.d.ts
199
+ type BearerAuthOptions = {
200
+ /**
201
+ * Where the token may go: a URL, or several. Only their origins count, so
202
+ * your `baseURL` works as is. A request anywhere else — a CDN, a URL taken
203
+ * from a response body — is sent without the token.
204
+ */
205
+ origin: string | readonly string[];
206
+ /**
207
+ * The current access token, read on every attempt. `null`, `undefined` or
208
+ * `""` sends no `authorization` header.
209
+ */
210
+ token: () => string | null | undefined | Promise<string | null | undefined>;
211
+ /**
212
+ * Get a new token after a 401; the call is then redone once. Concurrent
213
+ * 401s share one refresh, and a call whose token was already replaced
214
+ * retries without one. Throw when the refresh fails — every waiting call
215
+ * rejects with that error. Requests the refresh makes through the same
216
+ * client need `meta: { bearerAuth: false }`. Without `refresh`, or for a
217
+ * `ReadableStream` body (already read, so it cannot be resent), a 401 is
218
+ * thrown as is.
219
+ */
220
+ refresh?: () => Promise<void>;
221
+ };
222
+ //#endregion
223
+ //#region src/plugins/bearer-auth/bearer-auth.d.ts
224
+ /**
225
+ * Bearer-token auth. A request interceptor sets `authorization: Bearer
226
+ * <token>` on every attempt to `origin`; with `refresh`, a middleware turns a
227
+ * 401 into one refresh and one more try. Concurrent 401s share the refresh
228
+ * (with refresh-token rotation, parallel refreshes revoke each other), and a
229
+ * call whose token was replaced meanwhile just retries. A call opts out with
230
+ * `meta: { bearerAuth: false }`.
231
+ */
232
+ declare function bearerAuth(options: BearerAuthOptions): Plugin;
233
+ //#endregion
234
+ //#region src/plugins/logging/logging.types.d.ts
235
+ type LogEventBase = {
236
+ method: string;
237
+ path: string;
238
+ };
239
+ type LogEvent = ({
240
+ phase: "start";
241
+ } & LogEventBase) | ({
242
+ phase: "success";
243
+ status: number;
244
+ ms: number;
245
+ } & LogEventBase) | ({
246
+ phase: "error";
247
+ /** HTTP status for an ArthronError (0 = network); undefined for anything else. */
248
+ status: number | undefined;
249
+ ms: number;
250
+ error: unknown;
251
+ } & LogEventBase);
252
+ type LoggingOptions = {
253
+ /** Default `true`. The library never reads `NODE_ENV` — pass `isDev` yourself. */
254
+ enabled?: boolean;
255
+ logger?: Pick<Console, "log" | "error">;
256
+ /** Receive structured events instead of the default console lines. */
257
+ onEvent?: (event: LogEvent) => void;
258
+ /** Clock in ms. Injectable for tests. */
259
+ now?: () => number;
260
+ };
261
+ //#endregion
262
+ //#region src/plugins/logging/logging.d.ts
263
+ /**
264
+ * One event when a request starts, one when it settles, with status and
265
+ * elapsed time. Wraps the whole call, so retries are included in the time.
266
+ * Default output is a console line per event; pass `onEvent` to get the
267
+ * structured event instead. Cancellations are not reported.
268
+ */
269
+ declare function logging(options?: LoggingOptions): Plugin;
270
+ //#endregion
271
+ //#region src/plugins/retry/retry.d.ts
272
+ /**
273
+ * Retry on network errors and the configured statuses by calling `next`
274
+ * again — the whole attempt (request interceptors included) is re-run.
275
+ * Only `ArthronError` is considered; cancellation and plugin bugs pass through.
276
+ * A call can turn it off or override its options with `meta.retry`.
277
+ */
278
+ declare function retry(options?: RetryOptions): Plugin;
279
+ //#endregion
280
+ //#region src/plugins/timeout/timeout.types.d.ts
281
+ type TimeoutOptions = {
282
+ /**
283
+ * Abort after this many ms in all, counted until the body has been fully
284
+ * read — the same deadline as `timeout(ms)`. Default: none.
285
+ */
286
+ total?: number;
287
+ /**
288
+ * Abort when no data has arrived for this many ms — while waiting for the
289
+ * headers and between body chunks. Unlike `total`, a stream that keeps
290
+ * flowing is never cut off: `timeout({ idle: 30_000 })`.
291
+ */
292
+ idle?: number;
293
+ };
294
+ //#endregion
295
+ //#region src/plugins/timeout/timeout.d.ts
296
+ /**
297
+ * Abort the request when it takes longer than `ms` — counted from the start
298
+ * of the attempt until the body has been fully read, so a server that sends
299
+ * headers and then stalls still trips it. `timeout({ idle })` instead aborts
300
+ * once no data has arrived for that long, and never cuts off a stream that
301
+ * keeps flowing; `timeout({ total, idle })` does both. Rejects with a
302
+ * `TimeoutError` (a `DOMException`, like `AbortSignal.timeout()` would give);
303
+ * it is not an `ArthronError`, so error interceptors and `retry` leave it
304
+ * alone.
305
+ *
306
+ * A call can change the total deadline with `meta.timeout`.
307
+ *
308
+ * Deadlines are timers on an AbortController — not `AbortSignal.timeout`,
309
+ * since the idle one restarts — joined to the caller's signal with
310
+ * `AbortSignal.any`.
311
+ */
312
+ declare function timeout(ms: number): Plugin;
313
+ declare function timeout(options: TimeoutOptions): Plugin;
314
+ /** @deprecated Use `timeout({ total: ms, idle })`; this form goes in the next major. */
315
+ declare function timeout(ms: number, options: Pick<TimeoutOptions, "idle">): Plugin;
316
+ //#endregion
317
+ //#region src/plugins/upload-progress/upload-progress.d.ts
318
+ /**
319
+ * Does nothing by itself — only a call that passes `meta.onUploadProgress`
320
+ * reports upload progress. On such a call it changes how that one attempt
321
+ * is sent: over XMLHttpRequest in a browser, with a counted body in Node.
322
+ * Every other call, on this client too, goes out exactly as before.
323
+ *
324
+ * Progress needs the runtime's own fetch: with an injected `fetch`, another
325
+ * plugin's transport, or a runtime that is neither (Deno, Bun, Cloudflare
326
+ * Workers, a service worker), the call is sent as usual without progress.
327
+ * Put it last in `use`: the call's signal carries a throwing callback's
328
+ * error, and an interceptor after it that replaces the signal would cut it.
329
+ */
330
+ declare function uploadProgress(): Plugin;
331
+ //#endregion
332
+ export { UploadProgressEvent as S, ArthronMeta as _, logging as a, RequestContext as b, bearerAuth as c, Middleware as d, Plugin as f, isArthronError as g, ArthronError as h, retry as i, BearerAuthOptions as l, ResponseInterceptor as m, timeout as n, LogEvent as o, RequestInterceptor as p, TimeoutOptions as r, LoggingOptions as s, uploadProgress as t, ErrorInterceptor as u, HeadersOption as v, RetryOptions as x, QueryParams as y };
333
+ //# sourceMappingURL=index-C3lylSNd.d.cts.map