arthron 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +297 -2
- package/dist/index.cjs +665 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +219 -0
- package/dist/index.d.mts +219 -0
- package/dist/index.mjs +656 -0
- package/dist/index.mjs.map +1 -0
- package/llms.txt +99 -0
- package/package.json +59 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 lapidix
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,298 @@
|
|
|
1
|
-
#
|
|
1
|
+
# arthron
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A `fetch` client you assemble from plugins.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { arthron, logging, retry, timeout } from "arthron";
|
|
7
|
+
|
|
8
|
+
const api = arthron({
|
|
9
|
+
baseURL: "https://api.example.com",
|
|
10
|
+
use: [logging(), timeout(10_000), retry()],
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
const user = await api.get("/me").json<User>();
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
- **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 and timeouts are middleware. Headers, logging and error mapping are interceptors.
|
|
18
|
+
- **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
|
+
- Zero dependencies. ESM and CJS. TypeScript types included. Node 18+ and browsers.
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
npm i arthron
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Usage
|
|
28
|
+
|
|
29
|
+
### Create a client
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
const api = arthron({
|
|
33
|
+
baseURL: "https://api.example.com", // prefix for relative paths
|
|
34
|
+
headers: { accept: "application/json" }, // defaults; per-call headers win
|
|
35
|
+
credentials: "include", // only if you need cookies cross-origin
|
|
36
|
+
use: [retry()], // plugins, outermost first
|
|
37
|
+
});
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Every field is optional. Without `baseURL`, only absolute URLs are accepted.
|
|
41
|
+
|
|
42
|
+
### Make requests
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
await api.get("/users", { params: { page: 2 } }); // → Response
|
|
46
|
+
await api.post("/users", { name: "kim" }); // object body → JSON
|
|
47
|
+
await api.post("/upload", formData); // FormData/Blob/string/stream → sent as-is
|
|
48
|
+
await api.put("/users/1", { name: "lee" });
|
|
49
|
+
await api.patch("/users/1", { name: "lee" });
|
|
50
|
+
await api.delete("/users/1");
|
|
51
|
+
await api.head("/users/1");
|
|
52
|
+
await api.request("/users", { method: "OPTIONS" });
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Each call returns `Promise<Response>` with body helpers attached:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
const res = await api.get("/me"); // Response — status, headers, body untouched
|
|
59
|
+
const user = await api.get("/me").json<User>(); // body parsed; T is a cast, not validation
|
|
60
|
+
const text = await api.get("/robots.txt").text();
|
|
61
|
+
const blob = await api.get("/export").blob();
|
|
62
|
+
const stream = (await api.post("/chat", prompt)).body; // ReadableStream
|
|
63
|
+
for await (const e of api.post("/chat", prompt).sse()) {} // see "Stream responses"
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`init` accepts everything `fetch` does (`signal`, `cache`, `headers`, …) plus `params`, a query object whose `null`/`undefined` values are dropped.
|
|
67
|
+
|
|
68
|
+
### Stream responses
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
// Server-sent events — one event per `for await` step
|
|
72
|
+
for await (const { event, data } of api.post("/v1/chat/completions", body).sse()) {
|
|
73
|
+
if (data === "[DONE]") break; // provider sentinel; arthron does not interpret it
|
|
74
|
+
process.stdout.write(JSON.parse(data).choices[0].delta.content ?? "");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Newline-delimited JSON (Ollama, many log endpoints)
|
|
78
|
+
for await (const row of api.get("/logs").ndjson<LogRow>()) console.log(row);
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
`.sse()` follows the EventSource spec (multi-line `data:` joined with `\n`, comments ignored, dispatch on blank line). Both helpers honour `signal` and `timeout` while the body is being read.
|
|
82
|
+
|
|
83
|
+
### Handle errors
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
import { isArthronError } from "arthron";
|
|
87
|
+
|
|
88
|
+
try {
|
|
89
|
+
await api.get("/users/404");
|
|
90
|
+
} catch (e) {
|
|
91
|
+
if (isArthronError(e)) {
|
|
92
|
+
e.status; // 404, or 0 when the network failed
|
|
93
|
+
e.data; // parsed body: JSON, else text, else undefined
|
|
94
|
+
e.message; // from the body (`message` → `error` → `error.message` → `detail`), else "Request failed with status 404"
|
|
95
|
+
e.response; // the original Response, still readable
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
A request that is aborted or times out rejects with the browser's `AbortError` / `TimeoutError`, not an `ArthronError`.
|
|
101
|
+
|
|
102
|
+
### Derive clients
|
|
103
|
+
|
|
104
|
+
Clients are immutable. `use` and `extend` return a new client and leave the original alone.
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
const base = arthron({ baseURL: API, use: [logging(), retry()] });
|
|
108
|
+
const authed = base.use(auth()); // base + auth
|
|
109
|
+
const admin = authed.extend({ headers: { "x-role": "admin" } }); // authed + header
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
`extend` shallow-merges the config, merges headers case-insensitively (child wins), and appends plugins.
|
|
113
|
+
|
|
114
|
+
## Plugins
|
|
115
|
+
|
|
116
|
+
A plugin is an object with any of four slots:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
type Plugin = {
|
|
120
|
+
name?: string;
|
|
121
|
+
middleware?: (ctx: RequestContext, next: (ctx: RequestContext) => Promise<Response>) => Promise<Response>;
|
|
122
|
+
request?: (ctx: RequestContext) => RequestContext | Promise<RequestContext>;
|
|
123
|
+
response?: (res: Response, ctx: RequestContext) => Response | Promise<Response>;
|
|
124
|
+
error?: (err: ArthronError, ctx: RequestContext) => ArthronError | Promise<ArthronError>;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
type RequestContext = { url: string; init: RequestInit };
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
How one request runs:
|
|
131
|
+
|
|
132
|
+
```
|
|
133
|
+
middleware 1
|
|
134
|
+
middleware 2
|
|
135
|
+
attempt ─ request interceptors → fetch → response interceptors
|
|
136
|
+
↘ error interceptors → throw
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
| | Middleware | Interceptor |
|
|
140
|
+
|---|---|---|
|
|
141
|
+
| Runs | Once per call, wrapping everything below | Once per attempt |
|
|
142
|
+
| Gets | `ctx` and `next` | A value: context, `Response`, or `ArthronError` |
|
|
143
|
+
| Can | Call `next` again (retry), skip it, add a deadline | Return a changed value |
|
|
144
|
+
| Cannot | — | Retry, skip, or stop the error from being thrown |
|
|
145
|
+
| Examples | `retry`, `timeout`, auth refresh | auth header, tracing id, error mapping |
|
|
146
|
+
|
|
147
|
+
Every attempt starts from a fresh copy of the context, so a header set by an interceptor on attempt one does not leak into attempt two.
|
|
148
|
+
|
|
149
|
+
### Built in
|
|
150
|
+
|
|
151
|
+
#### `retry(options)`
|
|
152
|
+
|
|
153
|
+
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.
|
|
154
|
+
|
|
155
|
+
| option | default | |
|
|
156
|
+
|---|---|---|
|
|
157
|
+
| `retries` | `2` | retries after the first attempt (3 requests total) |
|
|
158
|
+
| `retryOn` | `[408, 429, 500, 502, 503, 504]` | network failures (`status: 0`) are always retried |
|
|
159
|
+
| `methods` | `GET HEAD OPTIONS PUT DELETE` | case-insensitive |
|
|
160
|
+
| `delay` | `(retry) => 300 * 2 ** retry` | ms; `retry` counts from 0 |
|
|
161
|
+
| `maxRetryAfter` | `60_000` | a `Retry-After` longer than this means "don't retry" |
|
|
162
|
+
|
|
163
|
+
Honours `Retry-After` (seconds or HTTP date). Never retries a `ReadableStream` body or an aborted request.
|
|
164
|
+
|
|
165
|
+
#### `timeout(ms)`
|
|
166
|
+
|
|
167
|
+
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.
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
arthron({ use: [retry(), timeout(5_000)] }); // 5 s per attempt
|
|
171
|
+
arthron({ use: [timeout(5_000), retry()] }); // 5 s for all attempts together
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
#### `logging(options)`
|
|
175
|
+
|
|
176
|
+
```
|
|
177
|
+
[arthron] → GET https://api.example.com/users
|
|
178
|
+
[arthron] ← GET https://api.example.com/users 200 42ms
|
|
179
|
+
[arthron] ✕ GET https://api.example.com/users 503 1203ms
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
| option | default | |
|
|
183
|
+
|---|---|---|
|
|
184
|
+
| `enabled` | `true` | pass `process.env.NODE_ENV !== "production"` or similar — arthron never reads env |
|
|
185
|
+
| `logger` | `console` | anything with `log` and `error` |
|
|
186
|
+
| `onEvent` | — | receive `{ phase, method, path, status, ms, error }` instead of console lines |
|
|
187
|
+
|
|
188
|
+
Query strings and `user:pass@` are never printed. Cancellations are not logged.
|
|
189
|
+
|
|
190
|
+
### Write your own
|
|
191
|
+
|
|
192
|
+
`definePlugin`, `defineMiddleware` and `defineInterceptor.{request,response,error}` are identity functions that give you the parameter types without annotations.
|
|
193
|
+
|
|
194
|
+
**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.
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
import { definePlugin, isArthronError } from "arthron";
|
|
198
|
+
|
|
199
|
+
export const auth = (store: { token: () => string | null; refresh: () => Promise<void> }) =>
|
|
200
|
+
definePlugin({
|
|
201
|
+
name: "auth",
|
|
202
|
+
request: (ctx) => {
|
|
203
|
+
const token = store.token();
|
|
204
|
+
if (!token) return ctx;
|
|
205
|
+
return { ...ctx, init: { ...ctx.init, headers: { ...ctx.init.headers, authorization: `Bearer ${token}` } } };
|
|
206
|
+
},
|
|
207
|
+
middleware: async (ctx, next) => {
|
|
208
|
+
try {
|
|
209
|
+
return await next(ctx);
|
|
210
|
+
} catch (e) {
|
|
211
|
+
if (!isArthronError(e) || e.status !== 401) throw e;
|
|
212
|
+
await store.refresh(); // if this throws, the caller sees it
|
|
213
|
+
return next(ctx);
|
|
214
|
+
}
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
**Send users to an error page.** Error interceptors can look and act, but the error is thrown regardless — which is what you want for a side effect like navigation.
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
import { defineInterceptor } from "arthron";
|
|
223
|
+
|
|
224
|
+
export const errorRedirect = (navigate: (to: string) => void) =>
|
|
225
|
+
defineInterceptor.error((err, ctx) => {
|
|
226
|
+
if ((ctx.init.method ?? "GET") !== "GET") return err;
|
|
227
|
+
if (err.status === 404) navigate("/not-found");
|
|
228
|
+
if (err.status >= 500) navigate("/error");
|
|
229
|
+
return err;
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
api.use({ error: errorRedirect(router.push) });
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
**Attach a trace id.** A one-line request interceptor.
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
api.use({ request: (ctx) => ({ ...ctx, init: { ...ctx.init, headers: { ...ctx.init.headers, "x-trace-id": crypto.randomUUID() } } }) });
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
## Reference
|
|
242
|
+
|
|
243
|
+
### `arthron(config)`
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
type ArthronConfig = {
|
|
247
|
+
baseURL?: string;
|
|
248
|
+
headers?: HeadersInit;
|
|
249
|
+
credentials?: RequestCredentials;
|
|
250
|
+
fetch?: typeof fetch; // inject for tests or a polyfill; resolved per request
|
|
251
|
+
use?: Plugin[];
|
|
252
|
+
errorMessage?: (data: unknown, res: Response) => string | undefined;
|
|
253
|
+
};
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
### Client
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
get(path, init) · delete(path, init) · head(path, init)
|
|
260
|
+
post(path, body, init) · put(path, body, init) · patch(path, body, init)
|
|
261
|
+
request(path, { method, body, ...init })
|
|
262
|
+
use(...plugins) → new client
|
|
263
|
+
extend(config) → new client
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
All arguments after `path` are optional, except `method` in `request`.
|
|
267
|
+
|
|
268
|
+
### `ArthronError`
|
|
269
|
+
|
|
270
|
+
```ts
|
|
271
|
+
class ArthronError extends Error {
|
|
272
|
+
status: number; // 0 for network failures
|
|
273
|
+
statusText: string;
|
|
274
|
+
headers: Headers;
|
|
275
|
+
data: unknown;
|
|
276
|
+
response?: Response; // absent for network failures
|
|
277
|
+
request: RequestContext;
|
|
278
|
+
cause?: unknown; // the underlying error for network failures
|
|
279
|
+
}
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
### Rules worth knowing
|
|
283
|
+
|
|
284
|
+
- **URLs are joined by string concatenation.** `baseURL: "https://a/v1"` + `"/users"` → `https://a/v1/users`. The `/v1` survives, unlike with `new URL()`. Absolute URLs bypass `baseURL`.
|
|
285
|
+
- **Bodies.** `string`, `FormData`, `Blob`, `ArrayBuffer`/views, `URLSearchParams` and `ReadableStream` go through untouched. Anything else — including `null` — becomes JSON with `content-type: application/json` unless you set a content type. `GET`/`HEAD` with a body is rejected with a `TypeError`.
|
|
286
|
+
- **`credentials` is not set unless you set it.** Cross-origin cookies need `credentials: "include"`.
|
|
287
|
+
- **Response bodies are single-use.** A response interceptor that wants to inspect the body must `res.clone()`; one that changes it returns a new `Response`.
|
|
288
|
+
- **Argument errors reject, they don't throw.** No `baseURL` with a relative path, a `BigInt` in a JSON body, a missing `method` in `request` — all surface as a rejected promise.
|
|
289
|
+
|
|
290
|
+
## For tooling and agents
|
|
291
|
+
|
|
292
|
+
- `llms.txt` ships in the package — a compressed API reference meant to be read by LLM-based tools (`node_modules/arthron/llms.txt`).
|
|
293
|
+
- `examples/` holds type-checked, runnable recipes: LLM streaming, auth refresh, upload/download.
|
|
294
|
+
- Error messages state the fix (`… — pass baseURL in arthron({ baseURL }) or use an absolute URL`).
|
|
295
|
+
|
|
296
|
+
## License
|
|
297
|
+
|
|
298
|
+
MIT
|