@akilin/api-kit 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 +277 -2
- package/dist/api-error.d.ts +100 -0
- package/dist/api-error.js +30 -0
- package/dist/body.d.ts +2 -0
- package/dist/body.js +20 -0
- package/dist/create-api.d.ts +65 -0
- package/dist/create-api.js +48 -0
- package/dist/deadline.d.ts +16 -0
- package/dist/deadline.js +56 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +2 -0
- package/dist/paged-data.d.ts +4 -0
- package/dist/paged-data.js +1 -0
- package/dist/query.d.ts +5 -0
- package/dist/query.js +22 -0
- package/dist/request.d.ts +80 -0
- package/dist/request.js +179 -0
- package/dist/response.d.ts +17 -0
- package/dist/response.js +79 -0
- package/dist/send.d.ts +50 -0
- package/dist/send.js +68 -0
- package/dist/telemetry.d.ts +15 -0
- package/dist/telemetry.js +67 -0
- package/dist/url.d.ts +10 -0
- package/dist/url.js +39 -0
- package/package.json +41 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 akilin
|
|
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,278 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @akilin/api-kit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> **Personal project — not intended for use by others; no support or stability guarantees.**
|
|
4
|
+
|
|
5
|
+
Library-agnostic TypeScript API client for ASP.NET Core APIs built with `akilin.ApiKit` (RFC 9457 Problem Details
|
|
6
|
+
with stable error codes). ESM-only, zero runtime dependencies; runs in browsers and React Native.
|
|
7
|
+
|
|
8
|
+
## Runtime
|
|
9
|
+
|
|
10
|
+
- ESM-only: there is no CommonJS build. React Native's Jest preset runs CommonJS, so let it transform the package:
|
|
11
|
+
`transformIgnorePatterns: ['node_modules/(?!((jest-)?react-native|@react-native(-community)?|@akilin/api-kit)/)']`.
|
|
12
|
+
- Compiled to ES2022 (class `#private` fields, `Error` `cause`): Safari 15+ and other current browsers, Node 24+ (what
|
|
13
|
+
the tests run on), React Native (Hermes). It needs a global `fetch` (or the `fetch` option) and `AbortController`.
|
|
14
|
+
|
|
15
|
+
## Setup
|
|
16
|
+
|
|
17
|
+
Pass the generated error map: `createApi<AppErrors>(…)`. TypeScript can't infer it from the options, so without it
|
|
18
|
+
the client is typed against an empty map (no codes) and the first `.on(errorCodes.…)` fails to compile with
|
|
19
|
+
"not assignable to parameter of type 'never'". Every type that takes the map defaults to that empty one, so pass it
|
|
20
|
+
there too: `ApiError<AppErrors>`, `ApiResult<T, AppErrors>`, `ApiOptions<AppErrors>`. `e instanceof ApiError` narrows
|
|
21
|
+
to an error of any kind with untyped codes (`ApiError<Record<string, unknown>>`). The option groups are exported as
|
|
22
|
+
`RequestDefaults` (`headers`, `credentials`, `fetch`, `timeout`) and `Policies<AppErrors>`.
|
|
23
|
+
|
|
24
|
+
### One client for the app
|
|
25
|
+
|
|
26
|
+
Create the client once, in a module of its own, and hand out that one instance, here through a `useApi` hook. Calls
|
|
27
|
+
made through it are typed from `AppErrors` without passing the map again: `.on(code, …)` types the error's `payload`
|
|
28
|
+
from the code.
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
// api.ts
|
|
32
|
+
import { createApi } from '@akilin/api-kit';
|
|
33
|
+
import type { AppErrors } from './api-types.g';
|
|
34
|
+
|
|
35
|
+
const api = createApi<AppErrors>({
|
|
36
|
+
baseUrl: '/api',
|
|
37
|
+
onUnauthorized: () => router.navigate('/login'),
|
|
38
|
+
onUnexpected: () => router.navigate('/error'),
|
|
39
|
+
defaultErrorCodeHandler: (e) => toast(t(`errorCodes.${e.code}`, e.payload)),
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
export function useApi() {
|
|
43
|
+
return api;
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
// in a component
|
|
49
|
+
const api = useApi();
|
|
50
|
+
|
|
51
|
+
api.get<User>('/users/1')
|
|
52
|
+
.on(errorCodes.users.planRequired, (e) => {
|
|
53
|
+
e.payload.plan; // Plan
|
|
54
|
+
e.payload.limit; // compile error: limitReached's payload, not planRequired's
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
- Call `createApi` outside the hook, not in its body. Then `useApi()` returns the same object on every render, so it
|
|
59
|
+
is safe in a `useEffect` dependency list, and the telemetry cap (see [Telemetry](#telemetry)) counts the app's
|
|
60
|
+
traces, not one render's.
|
|
61
|
+
- The handler gets the whole error, with its `code`, `status`, `field`, `headers` and `traceId` as well as `payload`.
|
|
62
|
+
- Pass the code from the generated `errorCodes` (or as a string literal). Its literal type selects the payload type; a
|
|
63
|
+
value typed `string` doesn't.
|
|
64
|
+
- Policies are fixed when the client is created, so they can't call React hooks: call a router instance or
|
|
65
|
+
`location` (see [Global error policies](#global-error-policies)).
|
|
66
|
+
- Type annotations you write yourself still take the map: `ApiError<AppErrors>`, `ApiResult<User, AppErrors>`.
|
|
67
|
+
|
|
68
|
+
`baseUrl` and the per-call url are joined with exactly one `/`, whichever side has it: `/api/` + `/users` and `/api` +
|
|
69
|
+
`users` both fetch `/api/users`. A url that is empty or starts with `?`/`#` is appended as it is (`/api/users` +
|
|
70
|
+
`?page=2`). An absolute per-call url (`https://files.example.com/a.pdf`, `//host/…`) is fetched as it is, without
|
|
71
|
+
`baseUrl`; any other `name:` start is a path (`items:batchGet` fetches `/api/items:batchGet`).
|
|
72
|
+
|
|
73
|
+
### Headers, credentials, fetch, timeout
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
export const api = createApi<AppErrors>({
|
|
77
|
+
baseUrl: 'https://api.example.com',
|
|
78
|
+
headers: async () => ({ Authorization: `Bearer ${await auth.token()}` }), // or a plain object; called per request
|
|
79
|
+
credentials: 'include', // cookie auth on another origin (fetch's default, 'same-origin', sends no cookies there)
|
|
80
|
+
fetch: myFetch, // optional; default: the global fetch
|
|
81
|
+
timeout: 10_000, // ms; optional; default: 30 000; 0 or Infinity turns it off
|
|
82
|
+
// …the three policies below
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
await api.put(`/users/${id}`, user, { headers: { 'If-Match': etag } }); // per call, over the client's by name
|
|
86
|
+
await api.post('/files', file, { timeout: 0 }); // per call, over the client's: no timeout for a large upload
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
- `headers`, `credentials`, `fetch` and `timeout` apply to every request, telemetry traces included (`headers` only on
|
|
90
|
+
the API's origin, see below). A call's own `headers` replace the client's of the same name, whatever the case.
|
|
91
|
+
- Every request has a timeout, 30 seconds unless you set another: on the client, or on a call (which wins). It runs
|
|
92
|
+
from the call to the end of the response body, the `headers` function included, so give a large upload or download a
|
|
93
|
+
longer one, or `0` for none. A request over it is cancelled and fails as kind `network`, with an error named
|
|
94
|
+
`TimeoutError` as `cause`, so it goes to `onUnexpected`.
|
|
95
|
+
- `Infinity`, or anything from 2³¹−1 ms (~24.8 days, the most a timer can wait) up, is none too. A negative or `NaN`
|
|
96
|
+
timeout throws a `RangeError`: on the client at `createApi`, on a call at the call (nothing is sent).
|
|
97
|
+
- The client's `headers` (an `Authorization` token, say) go only to the origin of `baseUrl`, or the page's when
|
|
98
|
+
`baseUrl` is relative or empty. An absolute per-call url on another origin (a file link the server returned, a
|
|
99
|
+
third-party URL) gets none of them, and the `headers` function isn't called for it; pass the call's own `headers` to
|
|
100
|
+
send some there. Origins are compared as written, case aside: `https://api.example.com:443` and
|
|
101
|
+
`//api.example.com` are not `https://api.example.com`, so write absolute urls to the API the way `baseUrl` is written,
|
|
102
|
+
or use paths.
|
|
103
|
+
- If the `headers` function throws or rejects, nothing is sent and the call fails as kind `network`, with what it threw
|
|
104
|
+
as `cause` (so it goes to `onUnexpected`).
|
|
105
|
+
|
|
106
|
+
### Cancelling a call
|
|
107
|
+
|
|
108
|
+
Pass an `AbortSignal` as a call's `signal`. If it aborts, before the call or during it (the `headers` function and the
|
|
109
|
+
body included), the request is cancelled and the call fails as kind `aborted`, with the signal's `reason` as `cause`.
|
|
110
|
+
That error goes only to the caller: `await` rejects with it and `.result()` resolves with it, but no per-call handler,
|
|
111
|
+
`.onAnyError` or policy gets it (`.finally` still runs), and no telemetry trace is sent. A signal already aborted sends
|
|
112
|
+
nothing. A timeout is not an abort: it stays kind `network`, whichever comes first wins.
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
// TanStack Query: it aborts the signal when the query is cancelled. `async`, so queryFn returns a Promise of the data.
|
|
116
|
+
useQuery({ queryKey: ['user', id], queryFn: async ({ signal }) => api.get<User>(`/users/${id}`, { signal }) });
|
|
117
|
+
|
|
118
|
+
// React: abort on cleanup. `.result()`, so the abort is no unhandled rejection.
|
|
119
|
+
useEffect(() => {
|
|
120
|
+
const controller = new AbortController();
|
|
121
|
+
void api.get<User>(`/users/${id}`, { signal: controller.signal }).result().then((r) => r.ok && setUser(r.data));
|
|
122
|
+
return () => controller.abort();
|
|
123
|
+
}, [id]);
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### Responses
|
|
127
|
+
|
|
128
|
+
`get`, `post`, `put`, `patch` and `delete` resolve with the body, parsed as JSON (no reviver, so dates stay strings).
|
|
129
|
+
A 204 or an empty (or whitespace-only) body resolves with `undefined`. There is no other way to read a body: a success body that isn't JSON
|
|
130
|
+
fails as kind `unexpected`.
|
|
131
|
+
|
|
132
|
+
`.result()` also gives the response's status and headers on success (`r.ok && r.response.headers.get('ETag')`), and
|
|
133
|
+
`.onSuccess(fn)` gets them as its second argument. Problem and unexpected errors carry `headers` too
|
|
134
|
+
(`error.headers?.get('Retry-After')`).
|
|
135
|
+
|
|
136
|
+
`PagedData<T>` is the body of a paged list, as the server's `PagedData<T>` (package `akilin.ApiKit`) writes it:
|
|
137
|
+
`api.get<PagedData<User>>('/users', { query: { pageNumber: 2 } })` resolves with `{ data, totalPages }`.
|
|
138
|
+
|
|
139
|
+
## Per-call handlers
|
|
140
|
+
|
|
141
|
+
`.on(code)`, `.onFieldError(fn)` and `.onStatus(status, fn)` claim an error: the handler runs instead of a global
|
|
142
|
+
policy, and the error's `handled` is `true`. A network failure has no code, field or status, so no per-call handler
|
|
143
|
+
claims it.
|
|
144
|
+
|
|
145
|
+
`.on(code)` gets only 4xx problems. Every 5xx (a crash, or an app code thrown with a 5xx status) is kind `unexpected`,
|
|
146
|
+
so an `.on` handler for a 5xx code never runs. Use `.onStatus(503, …)` instead: an unexpected error whose body is a
|
|
147
|
+
problem keeps its `code`, untyped (`error.code === errorCodes.ops.maintenance`), and its `payload` when that is an
|
|
148
|
+
object (`{}` when the body has none). A 4xx problem whose `payload` isn't an object is kind `unexpected` too.
|
|
149
|
+
|
|
150
|
+
A problem about one field of the request has a `field`: its camelCase path (`name`, `address.zip`, `items[0].name`).
|
|
151
|
+
`.onFieldError(fn)` claims every such problem, whatever its code, so one handler can put the server's error on the
|
|
152
|
+
form. A response reports one field, the first check that failed:
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
api.post<User>('/users', form)
|
|
156
|
+
.onFieldError((e) => setFieldError(e.field, t(`errorCodes.${e.code}`, e.payload)));
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
A `.on(code)` handler for the problem's code wins over `.onFieldError`; the problem it gets has the `field` too.
|
|
160
|
+
|
|
161
|
+
`.onAnyError(fn)` observes every failed call, whatever the kind (`problem`, `unexpected` or `network`), except an
|
|
162
|
+
aborted one. It runs after
|
|
163
|
+
the per-call handler or the policy that dealt with the error has finished, and before `.finally`. It claims nothing:
|
|
164
|
+
the error's `handled` stays as it was, and the policies run as if it weren't registered.
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
api.post<User>('/users', form)
|
|
168
|
+
.onFieldError(showOnField)
|
|
169
|
+
.onAnyError((e) => log('saving the user failed', e)); // also runs when .onFieldError or a policy got the error
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
If the handler or the policy before it throws, `.onAnyError` doesn't run.
|
|
173
|
+
|
|
174
|
+
A `FormData`, `Blob`, `URLSearchParams`, `ArrayBuffer` or typed array/`DataView` body is sent as it is, with no
|
|
175
|
+
`Content-Type` from the client: fetch sets it (multipart, the Blob's type, `application/x-www-form-urlencoded`), or
|
|
176
|
+
pass one in `headers` for bytes. Any other body goes through `JSON.stringify` and is sent as JSON. A body that can't be
|
|
177
|
+
JSON-serialized (a `BigInt`, a cycle) throws at the call, like an invalid `Date` in `query`; nothing is sent.
|
|
178
|
+
|
|
179
|
+
`.finally` runs whatever the outcome: after `.onSuccess`, or after the error handler (or the policy) and
|
|
180
|
+
`.onAnyError`. It is not `Promise.prototype.finally`: it returns the request, not a new promise, so the chain goes on;
|
|
181
|
+
like every handler, it is registered once and before dispatch (a second `.finally`, or one after an `await`, throws);
|
|
182
|
+
and it runs whether or not anything awaits the call.
|
|
183
|
+
|
|
184
|
+
Handlers, policies, `.onSuccess` and `.finally` may return anything (`(e) => toast(e.code)`): the result is ignored,
|
|
185
|
+
after awaiting it if it is a promise. If one throws, `.finally` still runs, then `await` (and `.result()`) rejects with
|
|
186
|
+
what it threw, not with the `ApiError`: the rejection reason is `unknown`, so check it (`e instanceof ApiError`).
|
|
187
|
+
|
|
188
|
+
## Global error policies
|
|
189
|
+
|
|
190
|
+
`createApi` requires three app-wide policies for errors that no per-call handler (`.on`, `.onFieldError`,
|
|
191
|
+
`.onStatus`) claimed:
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
export const api = createApi<AppErrors>({
|
|
195
|
+
baseUrl: '/api',
|
|
196
|
+
onUnauthorized: (error) => navigate('/login'), // any 401: a problem, or a proxy's 401 without one
|
|
197
|
+
onUnexpected: (error) => navigate('/something-went-wrong'), // a crash, a non-problem response, a network failure
|
|
198
|
+
defaultErrorCodeHandler: (error) => toast(t(`errorCodes.${error.code}`, error.payload)), // any other problem
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
- All three are required, so no unclaimed error is dropped because a policy was forgotten. To ignore a kind on
|
|
203
|
+
purpose, pass `() => {}` (e.g. `onUnauthorized` in an app without auth). A missing one fails to compile.
|
|
204
|
+
- Policies are fixed when the client is created. One that needs a router calls a router instance
|
|
205
|
+
(`router.navigate(...)`) or `location`, not a hook.
|
|
206
|
+
- Each unclaimed error goes to exactly one policy (an `aborted` call, to none). `defaultErrorCodeHandler` gets a problem: an error with a `code`.
|
|
207
|
+
It never gets a 401, which goes only to `onUnauthorized`, nor a 5xx, which is kind `unexpected` even with a code in
|
|
208
|
+
its body and goes to `onUnexpected`.
|
|
209
|
+
- A policy runs where a per-call handler would have: before `.onAnyError` and `.finally`, and before `await` /
|
|
210
|
+
`.result()` settle. Async policies are awaited. `await` still rejects afterwards, so code after the `await` never
|
|
211
|
+
runs on failure.
|
|
212
|
+
- `await` rejects even when a per-call handler claimed the error. In an event handler that nothing awaits (a React
|
|
213
|
+
`onSubmit`, say), that rejection is unhandled: it shows in the console and in error trackers. Use `.result()` there:
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
async function onSubmit(form: Form) {
|
|
217
|
+
const r = await api.post<User>('/users', form).onFieldError(showOnField).result();
|
|
218
|
+
if (!r.ok) return; // a handler or a policy already dealt with it
|
|
219
|
+
navigate(`/users/${r.data.id}`);
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
- **`onUnauthorized` must be idempotent.** Concurrent requests that all get a 401 each call it; there is no
|
|
223
|
+
de-duplication.
|
|
224
|
+
- `.result()` runs the policies exactly like `await`; it only avoids the rejection. Code after `.result()` runs even
|
|
225
|
+
when a policy redirected, so check `r.ok` (e.g. `if (!r.ok) return;`).
|
|
226
|
+
- `.skipDefaultErrorCodeHandler()` keeps one call's problems from `defaultErrorCodeHandler`, for a call that shows
|
|
227
|
+
its errors itself:
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
const r = await api.post<Order>('/orders', cart).skipDefaultErrorCodeHandler().result();
|
|
231
|
+
if (!r.ok) showInlineError(r.error); // a problem went to no policy: no toast, handled === false
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
Only that policy is skipped: a 401 still goes to `onUnauthorized`, and an unexpected response or a network failure
|
|
235
|
+
to `onUnexpected`. Per-call handlers, `.onAnyError` and `.finally` run as usual, and `await` still rejects.
|
|
236
|
+
- To keep a 401 from `onUnauthorized` for one call, claim it with `.onStatus(401, …)`:
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
const r = await api.get<User>('/me').onStatus(401, () => {}).result();
|
|
240
|
+
if (!r.ok) showSignedOut(); // handled === true for the 401; onUnauthorized didn't run
|
|
241
|
+
```
|
|
242
|
+
- Nothing claims every error of a call at once: `.onAnyError` only observes.
|
|
243
|
+
|
|
244
|
+
## Telemetry
|
|
245
|
+
|
|
246
|
+
Every `unexpected` error (a crash, a non-problem response) is posted to the server's client-logs endpoint as a
|
|
247
|
+
trace, even when a per-call handler claimed it, up to the cap below. The server has that endpoint only if the app calls
|
|
248
|
+
`app.MapApiKitClientLogs()`. The client's defaults match that call's, so nothing needs configuring then. If the app
|
|
249
|
+
doesn't call it, turn telemetry off. `telemetry: false` turns it off, and no trace is sent:
|
|
250
|
+
|
|
251
|
+
```ts
|
|
252
|
+
export const api = createApi<AppErrors>({
|
|
253
|
+
baseUrl: '/api',
|
|
254
|
+
// …the three policies above
|
|
255
|
+
telemetry: { url: '/api/client-logs', context: () => ({ appVersion, route: location.pathname }) }, // both optional
|
|
256
|
+
});
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
- The trace is `{ kind, method, url, status?, traceId?, responseBodySnippet, durationMs, timestamp, context? }`: the
|
|
260
|
+
first 2,000 characters of the response body, never request bodies or headers. `url` is the URL that was fetched
|
|
261
|
+
(joined as above) **without its query or fragment**, which may carry tokens or personal data, cut at 2,000
|
|
262
|
+
characters.
|
|
263
|
+
- Keep `context()` small: the server rejects a trace over ~16 KB, and the client doesn't cut `context`.
|
|
264
|
+
- Only `unexpected` errors are reported. Network failures (which often can't reach the server anyway) and JS crashes
|
|
265
|
+
outside API calls are not, in v1.
|
|
266
|
+
- `telemetry.url` is not prefixed with `baseUrl`. A path goes to the origin of `baseUrl` (with
|
|
267
|
+
`baseUrl: 'https://api.example.com/v1'`, the default goes to `https://api.example.com/api/client-logs`); an absolute
|
|
268
|
+
URL is used as it is. Like any request, a trace gets the client's `headers` only on the origin of `baseUrl`.
|
|
269
|
+
- At most 10 traces per 60 seconds are sent per client (`createApi`), so an outage (a proxy answering every call with
|
|
270
|
+
a 502 page) doesn't add a telemetry request to every failed call. Traces beyond the cap are dropped silently: no
|
|
271
|
+
request, no `context()` call. The cap is fixed.
|
|
272
|
+
- The trace is posted with fetch's `keepalive`, so a full-page navigation in `onUnexpected` or `onUnauthorized`
|
|
273
|
+
(`location.href = …`) doesn't cancel it.
|
|
274
|
+
- Telemetry never delays a call and never reports its own failures. A failed telemetry request, a throwing `context()`
|
|
275
|
+
or a `context()` result that can't be serialized drops the trace silently.
|
|
276
|
+
- The endpoint is open to anyone unless the app sets a fallback authorization policy; with one, signed-out users'
|
|
277
|
+
traces get a 401. To also get those, open it to anonymous clients and rate limit it
|
|
278
|
+
(`app.MapApiKitClientLogs().AllowAnonymous().RequireRateLimiting(...)`).
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/** Codes of an error map `E` (the generated `AppErrors`, code → payload). */
|
|
2
|
+
export type CodeOf<E> = keyof E & string;
|
|
3
|
+
interface ApiErrorBase extends Error {
|
|
4
|
+
/** `true` once a per-call handler (`.on`, `.onFieldError`, `.onStatus`) claimed the error. Never for `aborted`. */
|
|
5
|
+
readonly handled: boolean;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The error map as the client reads a body before it is typed as the app's: any string is a code, payloads `unknown`.
|
|
9
|
+
* What `instanceof ApiError` narrows to.
|
|
10
|
+
*/
|
|
11
|
+
export type UntypedErrors = Record<string, unknown>;
|
|
12
|
+
/** A parsed ProblemDetails body. Narrowing on `code` types `payload`. */
|
|
13
|
+
export type ProblemError<E extends object = {}, C extends CodeOf<E> = CodeOf<E>> = {
|
|
14
|
+
[K in C]: ApiErrorBase & {
|
|
15
|
+
readonly kind: 'problem';
|
|
16
|
+
readonly code: K;
|
|
17
|
+
readonly status: number;
|
|
18
|
+
/** The response headers (e.g. `Retry-After`); absent on an error built by hand. */
|
|
19
|
+
readonly headers?: Headers;
|
|
20
|
+
/** The body's `payload` member. `{}` for plain codes, which have none. */
|
|
21
|
+
readonly payload: E[K];
|
|
22
|
+
/**
|
|
23
|
+
* The camelCase path of the request field the error is about: `name`, `address.zip`, `items[0].name`.
|
|
24
|
+
* Absent when the error isn't about one field.
|
|
25
|
+
*/
|
|
26
|
+
readonly field?: string;
|
|
27
|
+
readonly traceId: string | undefined;
|
|
28
|
+
};
|
|
29
|
+
}[C];
|
|
30
|
+
export type FieldError<E extends object = {}> = ProblemError<E> & {
|
|
31
|
+
readonly field: string;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* What a failed request rejects with. `E` is the app's error map (the generated `AppErrors`); pass it, as to
|
|
35
|
+
* `createApi`: without it the map is empty, so there is no code and no kind `problem`.
|
|
36
|
+
*/
|
|
37
|
+
export type ApiError<E extends object = {}> = ProblemError<E> | NetworkError | UnexpectedError | AbortedError;
|
|
38
|
+
/**
|
|
39
|
+
* Kind `network`: `fetch` itself threw (or reading the body failed), or the request timed out: the client's or the
|
|
40
|
+
* call's `timeout` passed. `cause` is what was thrown; for a timeout it is an error named `TimeoutError`.
|
|
41
|
+
*/
|
|
42
|
+
export type NetworkError = ApiErrorBase & NetworkInit;
|
|
43
|
+
/**
|
|
44
|
+
* Kind `unexpected`: a response outside the contract. An error status whose body isn't a parseable
|
|
45
|
+
* `application/problem+json` object with a `code` (and, if it has a `payload`, one that is an object), any 5xx (problem
|
|
46
|
+
* or not), or a success body that isn't the JSON it should be. `cause` is the parse error, when there was one.
|
|
47
|
+
*/
|
|
48
|
+
export type UnexpectedError = ApiErrorBase & UnexpectedInit;
|
|
49
|
+
/**
|
|
50
|
+
* Kind `aborted`: the call's own `signal` aborted, before or during the request. It goes only to the caller (`await`
|
|
51
|
+
* rejects, `.result()` resolves with it): no handler or policy gets it and no telemetry trace is sent. `cause` is the
|
|
52
|
+
* signal's `reason`. A timeout is not this: it is kind `network`.
|
|
53
|
+
*/
|
|
54
|
+
export type AbortedError = ApiErrorBase & AbortedInit;
|
|
55
|
+
interface ProblemInit {
|
|
56
|
+
readonly kind: 'problem';
|
|
57
|
+
readonly code: string;
|
|
58
|
+
readonly status: number;
|
|
59
|
+
readonly headers?: Headers;
|
|
60
|
+
readonly payload: unknown;
|
|
61
|
+
/** Only for a problem about one field of the request. */
|
|
62
|
+
readonly field?: string;
|
|
63
|
+
readonly traceId: string | undefined;
|
|
64
|
+
}
|
|
65
|
+
interface NetworkInit {
|
|
66
|
+
readonly kind: 'network';
|
|
67
|
+
readonly cause: unknown;
|
|
68
|
+
}
|
|
69
|
+
interface UnexpectedInit {
|
|
70
|
+
readonly kind: 'unexpected';
|
|
71
|
+
readonly status: number;
|
|
72
|
+
/** The response headers; absent on an error built by hand. */
|
|
73
|
+
readonly headers?: Headers;
|
|
74
|
+
/** From the body when it is a problem (5xx problems carry one), else `undefined`. */
|
|
75
|
+
readonly traceId: string | undefined;
|
|
76
|
+
/**
|
|
77
|
+
* The body's `code` when it is a problem with one (a 5xx problem: an app code thrown with a 5xx status, or
|
|
78
|
+
* `http.internal-server-error`), else `undefined`. Untyped: 5xx codes never reach `.on`.
|
|
79
|
+
*/
|
|
80
|
+
readonly code?: string;
|
|
81
|
+
/**
|
|
82
|
+
* The `payload` of such a problem body, untyped (`{}` when it has none); `undefined` when `code` is, or when the
|
|
83
|
+
* body's `payload` isn't an object.
|
|
84
|
+
*/
|
|
85
|
+
readonly payload?: Readonly<Record<string, unknown>>;
|
|
86
|
+
readonly responseText: string;
|
|
87
|
+
readonly cause?: unknown;
|
|
88
|
+
}
|
|
89
|
+
interface AbortedInit {
|
|
90
|
+
readonly kind: 'aborted';
|
|
91
|
+
readonly cause: unknown;
|
|
92
|
+
}
|
|
93
|
+
export type ApiErrorInit = ProblemInit | NetworkInit | UnexpectedInit | AbortedInit;
|
|
94
|
+
/**
|
|
95
|
+
* Runtime constructor of {@link ApiError}, for `instanceof` checks. The class knows no error map, so `instanceof`
|
|
96
|
+
* narrows to an error of any kind whose codes are plain strings (`ApiError<Record<string, unknown>>`).
|
|
97
|
+
*/
|
|
98
|
+
export declare const ApiError: new (init: ApiErrorInit) => ApiError<UntypedErrors>;
|
|
99
|
+
export declare function markHandled(error: ApiError<UntypedErrors>): void;
|
|
100
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// One class for every kind, so `instanceof ApiError` covers them all. A class can't be a discriminated union, so it is
|
|
2
|
+
// exported cast to the `ApiError` union.
|
|
3
|
+
class ApiErrorClass extends Error {
|
|
4
|
+
name = 'ApiError';
|
|
5
|
+
handled = false;
|
|
6
|
+
constructor(init) {
|
|
7
|
+
super(message(init), 'cause' in init && init.cause !== undefined ? { cause: init.cause } : undefined);
|
|
8
|
+
Object.assign(this, init);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
function message(init) {
|
|
12
|
+
switch (init.kind) {
|
|
13
|
+
case 'problem':
|
|
14
|
+
return `API error ${init.status} ${init.code}`;
|
|
15
|
+
case 'unexpected':
|
|
16
|
+
return `API request failed: unexpected response (status ${init.status}${init.code ? ` ${init.code}` : ''})`;
|
|
17
|
+
case 'network':
|
|
18
|
+
return 'API request failed: network error';
|
|
19
|
+
case 'aborted':
|
|
20
|
+
return 'API request aborted';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Runtime constructor of {@link ApiError}, for `instanceof` checks. The class knows no error map, so `instanceof`
|
|
25
|
+
* narrows to an error of any kind whose codes are plain strings (`ApiError<Record<string, unknown>>`).
|
|
26
|
+
*/
|
|
27
|
+
export const ApiError = ApiErrorClass;
|
|
28
|
+
export function markHandled(error) {
|
|
29
|
+
error.handled = true;
|
|
30
|
+
}
|
package/dist/body.d.ts
ADDED
package/dist/body.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Read off `globalThis`, not named as a global: URLSearchParams is outside the platform subset (incomplete in React
|
|
2
|
+
// Native). The client only recognizes the caller's own instance, to hand it to fetch; it never builds or reads one.
|
|
3
|
+
const searchParams = () => globalThis.URLSearchParams;
|
|
4
|
+
/** What fetch takes as it is, setting the content type itself (form, multipart boundary, the Blob's type) or none. */
|
|
5
|
+
function isRawBody(body) {
|
|
6
|
+
// The `typeof` guards: a platform may lack any of these globals.
|
|
7
|
+
if (typeof FormData !== 'undefined' && body instanceof FormData)
|
|
8
|
+
return true;
|
|
9
|
+
if (typeof Blob !== 'undefined' && body instanceof Blob)
|
|
10
|
+
return true;
|
|
11
|
+
const SearchParams = searchParams();
|
|
12
|
+
if (SearchParams && body instanceof SearchParams)
|
|
13
|
+
return true;
|
|
14
|
+
return body instanceof ArrayBuffer || ArrayBuffer.isView(body);
|
|
15
|
+
}
|
|
16
|
+
export function jsonBody(body) {
|
|
17
|
+
if (body === undefined || isRawBody(body))
|
|
18
|
+
return body;
|
|
19
|
+
return JSON.stringify(body);
|
|
20
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { ApiRequest, type Policies } from './request.js';
|
|
2
|
+
import { type Query } from './query.js';
|
|
3
|
+
import { type RequestDefaults, type RequestHeaders } from './send.js';
|
|
4
|
+
import { type TelemetryOptions } from './telemetry.js';
|
|
5
|
+
export interface ApiOptions<E extends object = {}> extends RequestDefaults, Policies<E> {
|
|
6
|
+
/**
|
|
7
|
+
* Prefix for every request URL, e.g. `/api` or `https://api.example.com`. Default: `''`. Joined with exactly one `/`
|
|
8
|
+
* whichever side has it (`/api/` + `/users` and `/api` + `users` are both `/api/users`); a url that is empty or
|
|
9
|
+
* starts with `?`/`#` is appended as it is. An absolute per-call url (`https://…`, `//host/…`) is not prefixed.
|
|
10
|
+
*/
|
|
11
|
+
readonly baseUrl?: string;
|
|
12
|
+
/**
|
|
13
|
+
* Where and with what every `unexpected` error is reported. Default: `/api/client-logs`, no context; `false` sends
|
|
14
|
+
* no trace at all. At most 10 traces per 60 s per client are sent; the rest are dropped silently, and so is a trace
|
|
15
|
+
* that fails.
|
|
16
|
+
*/
|
|
17
|
+
readonly telemetry?: TelemetryOptions | false;
|
|
18
|
+
}
|
|
19
|
+
export interface RequestOptions {
|
|
20
|
+
/**
|
|
21
|
+
* Added to the URL's query, before any `#fragment`: arrays as repeated keys, `null`/`undefined` skipped, `Date` as an
|
|
22
|
+
* ISO string.
|
|
23
|
+
*/
|
|
24
|
+
readonly query?: Query;
|
|
25
|
+
/**
|
|
26
|
+
* How long this call may take, in ms, over the client's `timeout` (default 30 000); `0`, `Infinity` or anything from
|
|
27
|
+
* 2³¹−1 up turns the timeout off, for a large upload or download, say. A negative or `NaN` one throws a `RangeError`
|
|
28
|
+
* at the call. A call over it is cancelled and fails as kind `network`, with a `TimeoutError` as `cause`.
|
|
29
|
+
*/
|
|
30
|
+
readonly timeout?: number;
|
|
31
|
+
/** Headers for this call only (`If-Match`, say), over the client's `headers` by name, whatever the case. */
|
|
32
|
+
readonly headers?: RequestHeaders;
|
|
33
|
+
/**
|
|
34
|
+
* Cancels the call when it aborts, before or during the request (the `headers` function included). The call then
|
|
35
|
+
* fails as kind `aborted`, which goes only to the caller: `await` rejects, `.result()` resolves with it; no handler
|
|
36
|
+
* or policy runs (`.finally` does) and no telemetry trace is sent.
|
|
37
|
+
*/
|
|
38
|
+
readonly signal?: AbortSignal;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Every method resolves with the success body parsed as JSON (no reviver, so dates stay strings), or with `undefined`
|
|
42
|
+
* for a 204 or an empty (or whitespace-only) body. A success body that isn't JSON fails as kind `unexpected`.
|
|
43
|
+
*/
|
|
44
|
+
export interface Api<E extends object = {}> {
|
|
45
|
+
get<T>(url: string, opts?: RequestOptions): ApiRequest<T, E>;
|
|
46
|
+
/**
|
|
47
|
+
* `FormData`, `Blob`, `URLSearchParams`, `ArrayBuffer` and typed arrays/`DataView` as `body` go as they are, the
|
|
48
|
+
* content type left to fetch; anything else is JSON-serialized with `Content-Type: application/json`. A body that
|
|
49
|
+
* can't be (a `BigInt`, a cycle) throws at the call; nothing is sent.
|
|
50
|
+
*/
|
|
51
|
+
post<T>(url: string, body?: unknown, opts?: RequestOptions): ApiRequest<T, E>;
|
|
52
|
+
/** Takes `body` like {@link Api.post}. */
|
|
53
|
+
put<T>(url: string, body?: unknown, opts?: RequestOptions): ApiRequest<T, E>;
|
|
54
|
+
/** Takes `body` like {@link Api.post}. */
|
|
55
|
+
patch<T>(url: string, body?: unknown, opts?: RequestOptions): ApiRequest<T, E>;
|
|
56
|
+
delete<T>(url: string, opts?: RequestOptions): ApiRequest<T, E>;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Always pass the generated error map, `createApi<AppErrors>(…)`: nothing in the options lets TypeScript infer it, so
|
|
60
|
+
* without it the client is typed against an empty map (`{}`, no codes) and the first `.on(code)` fails to compile with
|
|
61
|
+
* "not assignable to parameter of type 'never'".
|
|
62
|
+
*
|
|
63
|
+
* The three policies are required, so an unclaimed error never goes unnoticed by accident.
|
|
64
|
+
*/
|
|
65
|
+
export declare function createApi<E extends object = {}>(options: ApiOptions<E>): Api<E>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { jsonBody } from './body.js';
|
|
2
|
+
import { assertTimeout } from './deadline.js';
|
|
3
|
+
import { ApiRequest } from './request.js';
|
|
4
|
+
import { withQuery } from './query.js';
|
|
5
|
+
import { send } from './send.js';
|
|
6
|
+
import { createReporter } from './telemetry.js';
|
|
7
|
+
/**
|
|
8
|
+
* Always pass the generated error map, `createApi<AppErrors>(…)`: nothing in the options lets TypeScript infer it, so
|
|
9
|
+
* without it the client is typed against an empty map (`{}`, no codes) and the first `.on(code)` fails to compile with
|
|
10
|
+
* "not assignable to parameter of type 'never'".
|
|
11
|
+
*
|
|
12
|
+
* The three policies are required, so an unclaimed error never goes unnoticed by accident.
|
|
13
|
+
*/
|
|
14
|
+
export function createApi(options) {
|
|
15
|
+
const { headers, credentials, fetch, timeout } = options;
|
|
16
|
+
assertTimeout(timeout);
|
|
17
|
+
const config = { baseUrl: options.baseUrl ?? '', headers, credentials, fetch, timeout };
|
|
18
|
+
const report = options.telemetry === false ? undefined : createReporter(config, options.telemetry);
|
|
19
|
+
const request = (method, url, body, opts = {}) => {
|
|
20
|
+
// Built here, not in `dispatch`, so a bad query value (an invalid Date), a body that can't be serialized (a
|
|
21
|
+
// BigInt, a cycle) or a negative timeout throws at the call.
|
|
22
|
+
assertTimeout(opts.timeout);
|
|
23
|
+
const req = {
|
|
24
|
+
method,
|
|
25
|
+
url: withQuery(url, opts.query),
|
|
26
|
+
body: jsonBody(body),
|
|
27
|
+
headers: opts.headers,
|
|
28
|
+
timeout: opts.timeout,
|
|
29
|
+
signal: opts.signal,
|
|
30
|
+
};
|
|
31
|
+
const dispatch = async () => {
|
|
32
|
+
const started = Date.now();
|
|
33
|
+
const outcome = await send(config, req);
|
|
34
|
+
// Reported here, before any handler runs: telemetry fires even when a per-call handler claims the error.
|
|
35
|
+
if (!outcome.ok && outcome.error.kind === 'unexpected')
|
|
36
|
+
report?.(req, outcome.error, Date.now() - started);
|
|
37
|
+
return outcome;
|
|
38
|
+
};
|
|
39
|
+
return new ApiRequest(dispatch, options);
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
get: (url, opts) => request('GET', url, undefined, opts),
|
|
43
|
+
post: (url, body, opts) => request('POST', url, body, opts),
|
|
44
|
+
put: (url, body, opts) => request('PUT', url, body, opts),
|
|
45
|
+
patch: (url, body, opts) => request('PATCH', url, body, opts),
|
|
46
|
+
delete: (url, opts) => request('DELETE', url, undefined, opts),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Outcome } from './response.js';
|
|
2
|
+
export declare const defaultTimeoutMs = 30000;
|
|
3
|
+
/** Throws at the call, like a body that can't be serialized: a negative or NaN timeout is a bug, not a no-timeout. */
|
|
4
|
+
export declare function assertTimeout(timeoutMs: number | undefined): void;
|
|
5
|
+
interface Deadline {
|
|
6
|
+
/** For fetch: aborts at the timeout or when the caller's signal does. */
|
|
7
|
+
readonly signal: AbortSignal | undefined;
|
|
8
|
+
/** Resolves with the failure at whichever comes first, the timeout or the caller's abort; else never. */
|
|
9
|
+
readonly expired: Promise<Outcome<never>>;
|
|
10
|
+
/** Stops the timer and removes the listener from the caller's signal, which may outlive the request. */
|
|
11
|
+
readonly clear: () => void;
|
|
12
|
+
}
|
|
13
|
+
/** The end of a request other than its answer: the timeout, or the caller's `signal` aborting. */
|
|
14
|
+
export declare function startDeadline(timeoutMs: number, callerSignal: AbortSignal | undefined): Deadline;
|
|
15
|
+
export declare function aborted(signal: AbortSignal): Outcome<never>;
|
|
16
|
+
export {};
|
package/dist/deadline.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { ApiError } from './api-error.js';
|
|
2
|
+
export const defaultTimeoutMs = 30_000;
|
|
3
|
+
// The longest delay `setTimeout` honours: it clamps a longer one (or a non-finite one) to ~1 ms, which would time the
|
|
4
|
+
// request out at once. Anything from here up, Infinity included, is no timeout at all, like 0.
|
|
5
|
+
const maxTimeoutMs = 2 ** 31 - 1;
|
|
6
|
+
/** Throws at the call, like a body that can't be serialized: a negative or NaN timeout is a bug, not a no-timeout. */
|
|
7
|
+
export function assertTimeout(timeoutMs) {
|
|
8
|
+
if (timeoutMs !== undefined && !(timeoutMs >= 0)) {
|
|
9
|
+
throw new RangeError(`timeout must be a number of ms, 0 or more (0 or Infinity: none), but was ${timeoutMs}.`);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** The end of a request other than its answer: the timeout, or the caller's `signal` aborting. */
|
|
13
|
+
export function startDeadline(timeoutMs, callerSignal) {
|
|
14
|
+
const timed = timeoutMs !== 0 && timeoutMs < maxTimeoutMs;
|
|
15
|
+
if (!timed && !callerSignal)
|
|
16
|
+
return { signal: undefined, expired: new Promise(() => { }), clear: () => { } };
|
|
17
|
+
// One controller for both: `AbortSignal.any` is outside the platform subset, so the caller's signal is forwarded by
|
|
18
|
+
// hand.
|
|
19
|
+
const controller = new AbortController();
|
|
20
|
+
// Typed by the platform's own setTimeout: the id is a number in browsers, an object in Node and React Native.
|
|
21
|
+
let timer;
|
|
22
|
+
let onAbort;
|
|
23
|
+
const expired = new Promise((resolve) => {
|
|
24
|
+
// Each resolves before aborting fetch, so its failure wins the race over what the cancelled fetch rejects with.
|
|
25
|
+
if (timed) {
|
|
26
|
+
timer = setTimeout(() => {
|
|
27
|
+
// A `TimeoutError` like the one `AbortSignal.timeout()` aborts with, built by hand: that method and
|
|
28
|
+
// `DOMException` are missing on some React Native versions.
|
|
29
|
+
const cause = new Error(`The request timed out after ${timeoutMs} ms`);
|
|
30
|
+
cause.name = 'TimeoutError';
|
|
31
|
+
// From the timer itself, not from the signal's `reason`, which an older platform may not carry.
|
|
32
|
+
resolve({ ok: false, error: new ApiError({ kind: 'network', cause }) });
|
|
33
|
+
controller.abort(cause);
|
|
34
|
+
}, timeoutMs);
|
|
35
|
+
}
|
|
36
|
+
if (callerSignal) {
|
|
37
|
+
onAbort = () => {
|
|
38
|
+
resolve(aborted(callerSignal));
|
|
39
|
+
controller.abort(callerSignal.reason);
|
|
40
|
+
};
|
|
41
|
+
callerSignal.addEventListener('abort', onAbort);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
return {
|
|
45
|
+
signal: controller.signal,
|
|
46
|
+
expired,
|
|
47
|
+
clear: () => {
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
if (onAbort)
|
|
50
|
+
callerSignal?.removeEventListener('abort', onAbort);
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
export function aborted(signal) {
|
|
55
|
+
return { ok: false, error: new ApiError({ kind: 'aborted', cause: signal.reason }) };
|
|
56
|
+
}
|