@zerosumstudio/conduit 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +785 -2
- package/dist/core-DXSbz15-.d.ts +142 -0
- package/dist/dev-CNYwEGcY.js +14 -0
- package/dist/devtools.d.ts +61 -0
- package/dist/devtools.js +152 -0
- package/dist/errors-DT0d6Qhy.js +85 -0
- package/dist/index.d.ts +177 -0
- package/dist/index.js +2412 -0
- package/dist/observable-LsEew2iL.d.ts +30 -0
- package/dist/query-state-BlmK3fBM.js +37 -0
- package/dist/react.d.ts +75 -0
- package/dist/react.js +331 -0
- package/dist/shared-2HssxK9p.d.ts +53 -0
- package/dist/shared-BsSjKC7q.js +118 -0
- package/dist/stores-DGXWZXXg.js +195 -0
- package/dist/testing.d.ts +88 -0
- package/dist/testing.js +224 -0
- package/dist/types-B9nuOKel.d.ts +689 -0
- package/dist/upload.d.ts +27 -0
- package/dist/upload.js +94 -0
- package/docs/migration-1.0.md +423 -0
- package/docs/threat-model.md +69 -0
- package/package.json +151 -3
package/README.md
CHANGED
|
@@ -1,3 +1,786 @@
|
|
|
1
|
-
#
|
|
1
|
+
# <picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/zerosumstudio/conduit/main/.github/assets/zerosum-on-dark.png"><img src="https://raw.githubusercontent.com/zerosumstudio/conduit/main/.github/assets/zerosum-on-light.png" alt="" height="32"></picture> Conduit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://badge.fury.io/js/@zerosumstudio%2Fconduit)
|
|
4
|
+
[](https://github.com/zerosumstudio/conduit/actions/workflows/release.yml)
|
|
5
|
+
[](https://codecov.io/gh/zerosumstudio/conduit)
|
|
6
|
+
[](https://opensource.org/licenses/MIT)
|
|
7
|
+
|
|
8
|
+
A data-fetching client for micro frontends. One client is shared by every bundle on the page, so four remotes asking for the same thing make one request, read one cache and share one session. Sharing goes through a global registry rather than a framework provider, so it works whichever framework each bundle is built with. Caching, request sharing, retry, queueing, timeouts and a session are plugins you add with `.with()`, and each one adds its methods to the client's type.
|
|
9
|
+
|
|
10
|
+
Coming from `@bkincz/conduit` 2.0? See the [migration guide](./docs/migration-1.0.md).
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pnpm add @zerosumstudio/conduit
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Requires Node 26 or newer, and the package is ESM-only. It has no dependencies. React 18 or newer is an optional peer, needed only for `@zerosumstudio/conduit/react`.
|
|
19
|
+
|
|
20
|
+
Up to 2.0.0 this was published as `@bkincz/conduit`.
|
|
21
|
+
|
|
22
|
+
## Quick start
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { createClient, defaults } from '@zerosumstudio/conduit'
|
|
26
|
+
|
|
27
|
+
interface User {
|
|
28
|
+
id: number
|
|
29
|
+
name: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const api = defaults(createClient({ baseUrl: '/api' }), {
|
|
33
|
+
cache: { ttlMs: 30_000, staleMs: Infinity },
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
const user = await api.get<User>('/users/:id', { params: { id: 7 } })
|
|
37
|
+
|
|
38
|
+
await api.post('/users', { name: 'Ada' })
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`defaults()` installs the standard stack in the order the layers need to be in. Reach for `.with()` only for something it can't express. `session` is installed only when you pass it, and `retry: false` or `timeout: false` leaves those two out.
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
observable → cache → dedupe → session → retry → queue → timeout → transport
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The entries are `@zerosumstudio/conduit`, `/react`, `/devtools`, `/testing` and `/upload`.
|
|
48
|
+
|
|
49
|
+
## Requests
|
|
50
|
+
|
|
51
|
+
`get`, `head`, `delete`, `post`, `put`, `patch` and `request` for anything else. `post`, `put` and `patch` take the body as the second argument. A string or a `BodyInit` is sent as it is, and anything else is JSON-encoded with a matching `content-type`. A body on `GET` or `HEAD` rejects with `INVALID_ARGUMENT`.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
const users = await api.get<User[]>('/users', { query: { role: ['admin', 'staff'], page: 2 } })
|
|
55
|
+
const { status, headers, from } = await api.get<User[]>('/users').response()
|
|
56
|
+
const { data, error } = await api.get<User[]>('/users').safe() // never throws
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`.response()` resolves the whole record: `status`, `headers`, `data`, `from` (`'network' | 'cache' | 'stale' | 'dedupe'`), `attempt`, `raw` and `request`. `.safe()` resolves `{ data, error: null }` or `{ data: null, error }`, so `error === null` narrows `data`. A bare request that nobody awaits and that fails is an unhandled rejection. `.safe()` and `.response()` stay silent.
|
|
60
|
+
|
|
61
|
+
| Option | Description |
|
|
62
|
+
| ------------- | ------------------------------------------------------------------------------ |
|
|
63
|
+
| `params` | Fills `:name` placeholders in the path |
|
|
64
|
+
| `query` | Query values. Arrays repeat the key, and `null` and `undefined` are skipped |
|
|
65
|
+
| `headers` | Per request headers, merged over the client's |
|
|
66
|
+
| `signal` | Your own `AbortSignal` |
|
|
67
|
+
| `key` | Override the derived cache and dedupe key |
|
|
68
|
+
| `lane` | `critical`, `default`, `prefetch`, or your own. See [queue](#queue) |
|
|
69
|
+
| `owner` | Who issued it, surfaced in devtools and on errors |
|
|
70
|
+
| `tags` | Labels for `invalidateTag`. They never switch caching on |
|
|
71
|
+
| `cacheable` | Whether cache and dedupe may serve it. Defaults to `true` for `GET` and `HEAD` |
|
|
72
|
+
| `parse` | How to decode the body, see below |
|
|
73
|
+
| `credentials` | Fetch credential mode |
|
|
74
|
+
| `meta` | Per request switches for plugins, such as `{ timeoutMs: 60_000 }` |
|
|
75
|
+
|
|
76
|
+
`mode`, `redirect`, `cache`, `keepalive`, `priority`, `referrerPolicy` and `integrity` pass straight through to `fetch`, per request or as a client default. See [Redirects](#redirects) before setting `redirect`.
|
|
77
|
+
|
|
78
|
+
On the client:
|
|
79
|
+
|
|
80
|
+
| Option | Description |
|
|
81
|
+
| ------------- | -------------------------------------------------------------------------------- |
|
|
82
|
+
| `baseUrl` | Prefixed to relative paths. A relative one needs a page, see [Origins](#origins) |
|
|
83
|
+
| `headers` | An object, or a function read fresh on every request |
|
|
84
|
+
| `vary` | Which headers count toward request identity. Defaults to `'*'` |
|
|
85
|
+
| `credentials` | Default credential mode |
|
|
86
|
+
| `owner` | Default owner for this bundle |
|
|
87
|
+
| `lane` | Default lane |
|
|
88
|
+
| `parse` | Default decode mode |
|
|
89
|
+
| `fetch` | Swap the network implementation, for tests or instrumentation |
|
|
90
|
+
| `origins` | Extra origins this client may call, see [Origins](#origins) |
|
|
91
|
+
| `redact` | What events and `.response()` hide, see [Redaction](#redaction) |
|
|
92
|
+
| `logger` | Where conduit's own diagnostics go. Defaults to `console`, see [Logger](#logger) |
|
|
93
|
+
|
|
94
|
+
### Path params
|
|
95
|
+
|
|
96
|
+
`:name` placeholders take a string or a number, URL-encoded. When the path is a literal, `params` is required and checked against it.
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
api.get('/users/:id', { params: { id: 7 } })
|
|
100
|
+
api.post('/orgs/:org/users', { name: 'Ada' }, { params: { org: 'acme' } })
|
|
101
|
+
api.get('/users/:id') // compile error: params is required
|
|
102
|
+
api.get('/users/:id', { params: { userId: 7 } }) // compile error: no such param
|
|
103
|
+
api.get('/users', { params: { id: 7 } }) // compile error: the path has no placeholders
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
A missing, empty, `null` or non-primitive param rejects with `INVALID_ARGUMENT` instead of producing `/users//invoices`, as do `.` and `..`. A colon that doesn't start a segment is literal (`/models/gemini:generate`), and `::name` is a literal segment that begins with a colon. Params are read as own properties only.
|
|
107
|
+
|
|
108
|
+
When you give the result type, as in `get<User>('/users/:id')`, TypeScript can't infer the path from the same call, so `params` stays optional and unchecked there and a missing one fails at run time. Use [`defineEndpoint`](#typed-endpoints) when you want the types to hold.
|
|
109
|
+
|
|
110
|
+
### Parse modes
|
|
111
|
+
|
|
112
|
+
`parse` is `auto` by default. Set it on the client, or per request, when the server's `content-type` can't be trusted.
|
|
113
|
+
|
|
114
|
+
| Mode | Result |
|
|
115
|
+
| ------------- | -------------------------------------------------------------------------------- |
|
|
116
|
+
| `auto` | `none` for 204, 205 and 304. Else `json`, `text` or `blob` from the content type |
|
|
117
|
+
| `json` | Parsed JSON. An empty body is `null` |
|
|
118
|
+
| `text` | A string |
|
|
119
|
+
| `blob` | A `Blob` |
|
|
120
|
+
| `arrayBuffer` | An `ArrayBuffer` |
|
|
121
|
+
| `formData` | A `FormData` |
|
|
122
|
+
| `none` | `null`, without reading the body |
|
|
123
|
+
|
|
124
|
+
`auto` reads `json` when the content type contains `json`, `text` for `text/*`, XML and a missing content type, and `blob` for everything else. A body that doesn't decode as declared rejects with `PARSE_FAILED`. An error response never does: a 503 carrying an HTML page under a JSON content type keeps its status, and the text is its `body`.
|
|
125
|
+
|
|
126
|
+
## Typed endpoints
|
|
127
|
+
|
|
128
|
+
`defineEndpoint` names a request once, with its path params, query, body, tags and response schema, so it can be called and keyed without repeating any of that. `response` takes any [Standard Schema](https://standardschema.dev) validator, such as zod or valibot, or a plain function.
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
import { z } from 'zod'
|
|
132
|
+
import { defineEndpoint } from '@zerosumstudio/conduit'
|
|
133
|
+
|
|
134
|
+
const userSchema = z.object({ id: z.number(), name: z.string() })
|
|
135
|
+
|
|
136
|
+
export const getUser = defineEndpoint({
|
|
137
|
+
method: 'GET',
|
|
138
|
+
path: '/users/:id',
|
|
139
|
+
response: userSchema,
|
|
140
|
+
tags: vars => [`user:${vars.id}`],
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
const user = await api.call(getUser, { id: '7' }) // { id: number, name: string }
|
|
144
|
+
api.invalidate(api.getKey(getUser, { id: '7' }))
|
|
145
|
+
api.call(getUser, { userId: '7' }) // compile error: the path asks for { id }
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Without type arguments, `vars` is read from the path literal: `{ id }` for `/users/:id`, and `void` for a path with none. Give `Vars` and `Result` yourself when the variables carry more than path params, and then `query` and `body` build the request from them.
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
export const searchUsers = defineEndpoint<{ term: string }, User[]>({
|
|
152
|
+
method: 'POST',
|
|
153
|
+
path: '/users/search',
|
|
154
|
+
body: vars => vars,
|
|
155
|
+
cacheable: true, // a POST that only reads
|
|
156
|
+
tags: ['users'],
|
|
157
|
+
})
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
A failing schema or `response` function rejects with `VALIDATION_FAILED`, carrying the schema's issues as `body`, and the original as `cause` when a function threw. `invalidates` names the tags to invalidate after a mutation through [`useMutation`](#react).
|
|
161
|
+
|
|
162
|
+
## Cancelling
|
|
163
|
+
|
|
164
|
+
A scope is a cancellation boundary with the full request surface. Hand one to a remote on mount, and nothing it started outlives it.
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
const scope = api.scope('remote:profile')
|
|
168
|
+
|
|
169
|
+
scope.get('/settings')
|
|
170
|
+
scope.abort() // everything in flight through it stops, and the scope stays usable
|
|
171
|
+
scope.dispose() // the same, and the scope ends for good
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Requests made through a scope carry its name as their `owner`. `api.abortAll()` aborts every scope and every request, and the client stays usable. A sign-out cancels only the session's own credentialed requests, never a scope.
|
|
175
|
+
|
|
176
|
+
## Request identity
|
|
177
|
+
|
|
178
|
+
Entries are keyed on method, url, body, decode mode, credentials mode, and the headers `vary` selects. Headers count by default, because two remotes calling `/me` under different tokens must not share an entry. Headers a session attaches never count, since an identity change already clears everything.
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
createClient({ vary: '*' }) // default, every header
|
|
182
|
+
createClient({ vary: ['x-tenant'] }) // only what changes the response
|
|
183
|
+
createClient({ vary: [] }) // url alone
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Narrow it if you send a header that is unique per request, like a trace id. Under `'*'` that gives every request its own key, so nothing hits the cache or shares a flight. `api.getKey(path, options)` returns the key a request would get.
|
|
187
|
+
|
|
188
|
+
## Plugins
|
|
189
|
+
|
|
190
|
+
Each plugin is middleware that can also extend the client, and the extension shows up in the type. `api.invalidate()` doesn't compile until `cache()` is installed.
|
|
191
|
+
|
|
192
|
+
| Plugin | Adds to the client | What it does |
|
|
193
|
+
| ------------ | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
|
|
194
|
+
| `observable` | `observe`, `getObservedCount` | Per key state for framework bindings |
|
|
195
|
+
| `cache` | `invalidate`, `invalidateTag`, `clearCache`, `getCacheSize`, `setData` | LRU with a freshness window and optional stale serving, tag invalidation |
|
|
196
|
+
| `dedupe` | `getInFlightCount` | One request per key. Unmounting cancels your wait, not everyone else's |
|
|
197
|
+
| `session` | `session` | One session for the page, single-flight recovery, behind an adapter |
|
|
198
|
+
| `retry` | | Backoff with jitter, honours `Retry-After`, idempotent requests only by default |
|
|
199
|
+
| `queue` | `getQueueDepth`, `getActiveCount` | Bounded concurrency with priority lanes |
|
|
200
|
+
| `timeout` | | A deadline per attempt, failing with `TIMEOUT` |
|
|
201
|
+
| `apiVersion` | | Reports once when this bundle and the API disagree on version. Not in `defaults()` |
|
|
202
|
+
| `requestId` | | Sends an id with every attempt and puts it on errors. Not in `defaults()` |
|
|
203
|
+
|
|
204
|
+
A request can step around a layer through `meta`:
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
api.get('/live', { meta: { cache: 'bypass', dedupe: 'bypass' } })
|
|
208
|
+
api.get('/fresh', { meta: { cache: 'refresh' } }) // skip the read, keep the result
|
|
209
|
+
api.get('/slow', { meta: { timeoutMs: 60_000 } }) // 0 turns the timeout off
|
|
210
|
+
api.get('/urgent', { meta: { queue: 'bypass' } })
|
|
211
|
+
api.post('/auth/sign-in', { email: 'ada@example.com' }, { meta: { session: 'bypass' } })
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### cache
|
|
215
|
+
|
|
216
|
+
| Option | Description |
|
|
217
|
+
| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
218
|
+
| `ttlMs` | How long a response is fresh. Defaults to `30_000` |
|
|
219
|
+
| `staleMs` | How long past `ttlMs` a response is still served, as `from: 'stale'`, while one refresh runs behind it. Defaults to `0`, and `Infinity` means always |
|
|
220
|
+
| `max` | Entry cap. Defaults to `200`, and the least recently read entry goes first |
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
const previous = api.setData(api.getKey('/users/:id', { params: { id: 7 } }), (user?: User) => ({
|
|
224
|
+
id: 7,
|
|
225
|
+
name: 'Ada',
|
|
226
|
+
...user,
|
|
227
|
+
}))
|
|
228
|
+
|
|
229
|
+
api.invalidate(api.getKey('/users/:id', { params: { id: 7 } })) // one entry
|
|
230
|
+
api.invalidateTag('users') // every entry carrying the tag, returns how many
|
|
231
|
+
api.clearCache()
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
The cache stores what `cacheable` allows, which is `GET` and `HEAD` unless a request or endpoint says otherwise. Set `cacheable: true` on a `POST` that only reads, such as a search, and `false` to keep a `GET` out. `tags` are labels for `invalidateTag` and nothing else, so a tagged `POST` that writes is never cached or shared. A response with `cache-control: no-store` or `no-cache` is not stored.
|
|
235
|
+
|
|
236
|
+
Invalidating an entry or a tag reaches every mounted hook that shows it, and they refetch. `setData` writes the entry and those hooks directly, and hands back the previous value for a rollback. Cached and shared bodies are deeply frozen, since every reader holds the same object.
|
|
237
|
+
|
|
238
|
+
### dedupe
|
|
239
|
+
|
|
240
|
+
One request per key, however many callers ask for it, for every `cacheable` request. It takes no options. The shared request is cancelled only when its last participant leaves, so one remote unmounting cancels its own wait and nobody else's. `getInFlightCount()` reports the distinct requests in flight.
|
|
241
|
+
|
|
242
|
+
### retry
|
|
243
|
+
|
|
244
|
+
Replays a failed request with exponential backoff. It retries `NETWORK` and `TIMEOUT` failures, and `HTTP_STATUS` failures with a status in `statuses`.
|
|
245
|
+
|
|
246
|
+
| Option | Description |
|
|
247
|
+
| ----------------- | --------------------------------------------------------------------------------------------------------- |
|
|
248
|
+
| `attempts` | Total attempts including the first. Defaults to `3` |
|
|
249
|
+
| `baseDelayMs` | First backoff step. Defaults to `300`, and doubles each attempt |
|
|
250
|
+
| `maxDelayMs` | Ceiling for one step. Defaults to `5000` |
|
|
251
|
+
| `maxRetryAfterMs` | The longest `Retry-After` honoured. A server asking for more gets no retry. Defaults to `30_000` |
|
|
252
|
+
| `jitter` | Spread each wait across its window. Defaults to `true` |
|
|
253
|
+
| `idempotentOnly` | Replay only `GET`, `HEAD`, `PUT`, `DELETE`, `OPTIONS` and `cacheable` requests. Defaults to `true` |
|
|
254
|
+
| `statuses` | Statuses worth another attempt. Defaults to `408`, `425`, `429`, `500`, `502`, `503` and `504` |
|
|
255
|
+
| `shouldRetry` | `(error, request, attempt) => boolean`. Replaces the built-in decision, except for a consumed stream body |
|
|
256
|
+
| `onRetry` | Called with `{ request, error, attempt, delayMs }` before each wait |
|
|
257
|
+
|
|
258
|
+
`Retry-After` seconds or a date is read into `error.retryAfterMs`. A `ReadableStream` body that was already consumed is never replayed.
|
|
259
|
+
|
|
260
|
+
### queue
|
|
261
|
+
|
|
262
|
+
Bounded concurrency with priority lanes, so a remote's speculative prefetching can't queue ahead of the host's boot path.
|
|
263
|
+
|
|
264
|
+
| Option | Description |
|
|
265
|
+
| ------------- | -------------------------------------------------------------------------------- |
|
|
266
|
+
| `concurrency` | Requests in flight at once. Defaults to `6` |
|
|
267
|
+
| `lanes` | Lane names, most urgent first. Defaults to `['critical', 'default', 'prefetch']` |
|
|
268
|
+
| `limits` | Per lane ceilings, so one lane can't take the whole pool. Each at least `1` |
|
|
269
|
+
|
|
270
|
+
Pick a lane per request or as a client default, and read `getQueueDepth(lane?)` and `getActiveCount()` for what is waiting and running. A `concurrency` or limit that isn't a whole number of at least `1` throws `INVALID_ARGUMENT`.
|
|
271
|
+
|
|
272
|
+
### timeout
|
|
273
|
+
|
|
274
|
+
`timeout({ ms })` cancels a request that takes longer than `ms` (`15_000` by default) with `TIMEOUT` instead of a generic abort. It sits innermost, so each retry attempt gets its own clock. Override it with `meta: { timeoutMs }`, and `0` turns it off. `api.upload()` has no timeout by default, since a slow connection is not a hung one.
|
|
275
|
+
|
|
276
|
+
### session
|
|
277
|
+
|
|
278
|
+
conduit owns the hard parts, and the adapter owns whatever is specific to your backend. A cookie backend implements `load` and `identify`. A token backend adds `authorize` and `renew`.
|
|
279
|
+
|
|
280
|
+
```ts
|
|
281
|
+
import { createClient, defaults, withRequest, type SessionAdapter } from '@zerosumstudio/conduit'
|
|
282
|
+
|
|
283
|
+
interface Session {
|
|
284
|
+
id: string
|
|
285
|
+
token: string
|
|
286
|
+
exp: number
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const adapter: SessionAdapter<Session> = {
|
|
290
|
+
load: async ctx => (await ctx.request<{ session: Session | null }>('/auth/session')).session,
|
|
291
|
+
identify: session => session.id, // a different id resets everything held for the last one
|
|
292
|
+
authorize: (request, session) => {
|
|
293
|
+
const headers = new Headers(request.headers)
|
|
294
|
+
|
|
295
|
+
headers.set('authorization', `Bearer ${session.token}`)
|
|
296
|
+
|
|
297
|
+
return withRequest(request, { headers })
|
|
298
|
+
},
|
|
299
|
+
renew: async ctx =>
|
|
300
|
+
(await ctx.request('/auth/refresh', { method: 'POST' }).safe()).error === null,
|
|
301
|
+
expiresAt: session => session.exp * 1000,
|
|
302
|
+
onClear: () => tokens.clear(), // whatever you hold outside conduit
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const api = defaults(createClient({ baseUrl: '/api' }), {
|
|
306
|
+
session: { adapter, channel: 'app.session' },
|
|
307
|
+
})
|
|
308
|
+
|
|
309
|
+
api.session.getState() // { status, session, error, updatedAt }
|
|
310
|
+
api.session.subscribe(state => render(state))
|
|
311
|
+
await api.session.load()
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
| Adapter method | Called |
|
|
315
|
+
| ------------------- | ------------------------------------------------------------------------------------------------------------- |
|
|
316
|
+
| `load` | To read the session. `null` means signed out, which is not an error |
|
|
317
|
+
| `identify` | After every read. Required, and a changed value resets cache, dedupe and observed state |
|
|
318
|
+
| `authorize` | On every request to the API origin or `session({ origins })`, and never elsewhere. Only called with a session |
|
|
319
|
+
| `renew` | Once per 401 on a credentialed request, however many hit it together. `false` gives up |
|
|
320
|
+
| `expiresAt` | Epoch milliseconds, to schedule a read `refreshLeewayMs` before the session lapses |
|
|
321
|
+
| `isUnauthenticated` | Optional. Whether a failure means the session is at fault. Defaults to HTTP 401 |
|
|
322
|
+
| `onClear` | After `session.clear()` and after a session is lost, once local state is gone |
|
|
323
|
+
|
|
324
|
+
`session()` throws `INVALID_ARGUMENT` at install when the adapter has no `identify`. The adapter's `ctx.request` skips the session, the cache and dedupe, and runs in the `critical` lane.
|
|
325
|
+
|
|
326
|
+
| Option | Description |
|
|
327
|
+
| ------------------- | ----------------------------------------------------------------------------------------------------------- |
|
|
328
|
+
| `adapter` | The adapter above |
|
|
329
|
+
| `autoLoad` | Read the session when the plugin installs. Defaults to `false` |
|
|
330
|
+
| `refreshLeewayMs` | Read again this long before `expiresAt`. Defaults to `60_000` |
|
|
331
|
+
| `origins` | Extra origins that receive credentials. They must be in the client's `origins` too |
|
|
332
|
+
| `channel` | A `BroadcastChannel` name that makes other tabs and bundles re-read when this one signs out or changes user |
|
|
333
|
+
| `onUnauthenticated` | Called once per lost session |
|
|
334
|
+
|
|
335
|
+
The state is a union on `status`:
|
|
336
|
+
|
|
337
|
+
| `status` | `session` | Meaning |
|
|
338
|
+
| --------------- | ----------- | ---------------------------------------------------------------------------------------- |
|
|
339
|
+
| `unknown` | `null` | Never read, or `clear()` ran |
|
|
340
|
+
| `loading` | kept | A read is in flight. The previous session and error stay visible |
|
|
341
|
+
| `authenticated` | the session | A read found one |
|
|
342
|
+
| `anonymous` | `null` | A read found nobody, or the session was lost, and then `error.code` is `UNAUTHENTICATED` |
|
|
343
|
+
| `error` | kept | A read failed. A previous session keeps being used |
|
|
344
|
+
|
|
345
|
+
Nothing about the session is sticky. A 401 on a credentialed request triggers one renewal, however many requests hit it together, and then a replay. When renewal fails, the session is `anonymous` with `UNAUTHENTICATED`, the session's in-flight credentialed requests are cancelled and reject `UNAUTHENTICATED`, cached data is dropped, and `onUnauthenticated` fires once. Later requests go out without credentials until a read finds a session. A 401 on a request that carried none, such as a failed sign-in, is an ordinary `HTTP_STATUS`.
|
|
346
|
+
|
|
347
|
+
`load()` returns a known session, signed in or not, without a request, and otherwise joins the read in flight. `reload()` always starts a new read, the latest wins, and older results are dropped. Call `reload()` after signing in. `clear()` drops local state without telling the server and cancels the session's credentialed requests with `ABORTED`, as does a change of user. A token adapter waits for its first read, and a request rejects with the load error if that fails with no previous session. A cookie adapter has no `authorize`, so it doesn't wait. Call `load()` at boot, or pass `autoLoad: true`, before a 401 can mean a lost session. A failed read is `UNKNOWN` with the original as `cause`.
|
|
348
|
+
|
|
349
|
+
Pass `meta: { session: 'bypass' }` on sign-in, sign-up and refresh calls so they skip `authorize` and 401 handling. With a `channel`, a sign-out, a lost session or a change of user in one tab makes every other tab re-read. Without it each tab learns on its next rejected request. A message carries no session or identity, so a forged one only causes a read.
|
|
350
|
+
|
|
351
|
+
### observable
|
|
352
|
+
|
|
353
|
+
`observe(key)` returns the live [store](#any-other-framework) of one key, created on first call and shared by every watcher, so two remotes rendering the same query watch one object. `max` (default `200`) caps the keys held, and a watched key is never evicted.
|
|
354
|
+
|
|
355
|
+
```ts
|
|
356
|
+
const store = api.observe<User>(api.getKey('/users/:id', { params: { id: 1 } }))
|
|
357
|
+
|
|
358
|
+
store.getState() // { status, data, error, from, isFetching, updatedAt, invalidatedAt }
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
`status` is `idle`, `loading`, `success` or `error`. `from` is where the last answer came from, and `stale` means it was served past its ttl while a refresh ran.
|
|
362
|
+
|
|
363
|
+
### apiVersion
|
|
364
|
+
|
|
365
|
+
`apiVersion({ expected })` reports once per server version when a response's `x-api-version` header isn't `expected`, including on error responses, since a deployment that moved on often fails first. Pass `header` to read another header, and `onMismatch` to route the report. The default report goes through `config.logger`, and the `api-version:mismatch` event carries it as well.
|
|
366
|
+
|
|
367
|
+
```ts
|
|
368
|
+
import { apiVersion } from '@zerosumstudio/conduit'
|
|
369
|
+
|
|
370
|
+
export const api = defaults(createClient({ baseUrl: '/api' })).with(apiVersion({ expected: 'v2' }))
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
This is separate from the `apiVersion` option of [`sharedClient`](#one-client-across-bundles), which compares what two bundles were built against.
|
|
374
|
+
|
|
375
|
+
### requestId
|
|
376
|
+
|
|
377
|
+
`requestId()` sends an id with every attempt and records it, so a failure on screen leads to the server's log line. Install it after `defaults()`, so it sits innermost: the id never reaches a cache key, and each retry goes out with its own. A header the caller already set is kept.
|
|
378
|
+
|
|
379
|
+
```ts
|
|
380
|
+
import { requestId } from '@zerosumstudio/conduit'
|
|
381
|
+
|
|
382
|
+
const traced = api.with(requestId({ header: 'x-request-id' }))
|
|
383
|
+
|
|
384
|
+
const { error } = await traced.get('/users').safe()
|
|
385
|
+
|
|
386
|
+
error?.requestId // the id the failing attempt went out with
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
`header` defaults to `x-request-id` and `generate` to `crypto.randomUUID()`. The id is on `ConduitError.requestId`, `request.meta.requestId` and each devtools entry.
|
|
390
|
+
|
|
391
|
+
## One client across bundles
|
|
392
|
+
|
|
393
|
+
Each federated bundle gets its own module instance, so a client built in the host is invisible to a remote. A registry on `globalThis` fixes that.
|
|
394
|
+
|
|
395
|
+
```ts
|
|
396
|
+
import { createClient, defaults, sharedClient } from '@zerosumstudio/conduit'
|
|
397
|
+
|
|
398
|
+
export const api = sharedClient('app.api', () => defaults(createClient({ baseUrl: '/api' })), {
|
|
399
|
+
apiVersion: 'v1',
|
|
400
|
+
clientVersion: 1,
|
|
401
|
+
})
|
|
402
|
+
```
|
|
403
|
+
|
|
404
|
+
The first caller builds the client, and everyone else gets that instance. A later caller's factory never runs, which is what `apiVersion` and `clientVersion` warn you about: they report a bundle built against another API version, another client shape, or another conduit version, through `onMismatch` or the logger. With Module Federation, share `@zerosumstudio/conduit` as a singleton so only one copy loads.
|
|
405
|
+
|
|
406
|
+
The registry key includes the major version, so a 1.0 bundle never receives a client built by 2.0. A page that mixes the two runs two clients, each with its own cache and session.
|
|
407
|
+
|
|
408
|
+
Tearing one down means deregistering it too, or the next bundle to ask gets a replacement and a warning:
|
|
409
|
+
|
|
410
|
+
```ts
|
|
411
|
+
api.destroy()
|
|
412
|
+
releaseSharedClient('app.api')
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
`getSharedClient(key)` reads one without creating it. Under Vite, pass `hot` so a reload during development gets a fresh client:
|
|
416
|
+
|
|
417
|
+
```ts
|
|
418
|
+
export const api = sharedClient('app.api', () => defaults(createClient({ baseUrl: '/api' })), {
|
|
419
|
+
hot: import.meta.hot,
|
|
420
|
+
})
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
`hot.dispose` runs `destroy()` and `releaseSharedClient()` for you. A shared client lets every bundle on the page use it, with its session. See [Security](#security).
|
|
424
|
+
|
|
425
|
+
## React
|
|
426
|
+
|
|
427
|
+
```ts
|
|
428
|
+
// api.ts
|
|
429
|
+
import { createHooks } from '@zerosumstudio/conduit/react'
|
|
430
|
+
|
|
431
|
+
export const { useRequest, useMutation, usePrefetch, useSession } = createHooks(api)
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
```tsx
|
|
435
|
+
function Profile({ id }: { id: string }) {
|
|
436
|
+
const { data, error, isLoading } = useRequest<User>('/users/:id', { params: { id } })
|
|
437
|
+
|
|
438
|
+
if (isLoading) return <Spinner />
|
|
439
|
+
if (error) return <ErrorCard code={error.code} />
|
|
440
|
+
|
|
441
|
+
return <Card user={data!} />
|
|
442
|
+
}
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
`createHooks` takes a client with `observable()` installed, which `defaults()` does. There is no provider: the hooks bind to a client at module scope, so every remote importing them shares it.
|
|
446
|
+
|
|
447
|
+
| Field | Description |
|
|
448
|
+
| --------------- | --------------------------------------------------------------------- |
|
|
449
|
+
| `data`, `error` | The current answer, and a `ConduitError` when it failed |
|
|
450
|
+
| `status` | `idle`, `loading`, `success` or `error` |
|
|
451
|
+
| `isLoading` | Nothing on screen yet and a request is in the air |
|
|
452
|
+
| `isFetching` | A request is in the air, with or without data showing |
|
|
453
|
+
| `isStale` | The data on screen was served stale, and a refresh is running |
|
|
454
|
+
| `updatedAt` | When the data arrived, in epoch milliseconds. `0` before anything has |
|
|
455
|
+
| `refetch()` | Fetch again, past the cache, and store the answer |
|
|
456
|
+
|
|
457
|
+
Options are the request's own, plus these:
|
|
458
|
+
|
|
459
|
+
| Option | Description |
|
|
460
|
+
| -------------------- | ----------------------------------------------------------------------- |
|
|
461
|
+
| `enabled` | Hold off until a dependency is ready. Defaults to `true` |
|
|
462
|
+
| `keepPreviousData` | Keep showing the last answer while a new key loads. Defaults to `false` |
|
|
463
|
+
| `refetchOnFocus` | Refetch when the tab becomes visible. Defaults to `false` |
|
|
464
|
+
| `refetchOnReconnect` | Refetch when the browser comes back online. Defaults to `false` |
|
|
465
|
+
|
|
466
|
+
The hooks never abort. A request that was superseded by a new key, or that outlived its component, finishes and fills the cache, so unmounting is cheap and StrictMode's second effect joins the first run instead of putting a duplicate on the wire. To cancel, pass your own `signal` or make the request through a [scope](#cancelling).
|
|
467
|
+
|
|
468
|
+
Two components rendering the same query share one store and one request, and the second to mount renders what the first already fetched. When an entry is invalidated, every hook showing it refetches. The hook re-subscribes when the key changes, not when the options object does, so a fresh `params` object every render costs nothing. `refetchOnFocus` and `refetchOnReconnect` read from the cache when its entry is fresh, and only `refetch()` goes past it.
|
|
469
|
+
|
|
470
|
+
`enabled` is how one query waits on another, and a missing param leaves the hook idle:
|
|
471
|
+
|
|
472
|
+
```tsx
|
|
473
|
+
function Invoices() {
|
|
474
|
+
const { data: user } = useRequest<User>('/me')
|
|
475
|
+
|
|
476
|
+
const { data: invoices, isFetching } = useRequest<Invoice[]>('/users/:id/invoices', {
|
|
477
|
+
params: user ? { id: user.id } : undefined,
|
|
478
|
+
enabled: user !== undefined,
|
|
479
|
+
})
|
|
480
|
+
|
|
481
|
+
return <List rows={invoices ?? []} busy={isFetching} />
|
|
482
|
+
}
|
|
483
|
+
```
|
|
484
|
+
|
|
485
|
+
Endpoints work everywhere a path does: `useRequest(getUser, { id })` and `useMutation(updateUser)`, with the endpoint's `tags` and `invalidates` applied. Give `useRequest` an endpoint that isn't `cacheable` and development warns.
|
|
486
|
+
|
|
487
|
+
`useMutation` takes the request to run rather than a path, so a scope, a lane or two calls in one mutation are all fair game. `mutate` never rejects. It resolves the same `SafeResult` as `.safe()`, after the tags in `invalidates` are invalidated, and the latest call owns the hook's state.
|
|
488
|
+
|
|
489
|
+
```tsx
|
|
490
|
+
function NewUser() {
|
|
491
|
+
const { mutate, isPending, error } = useMutation(
|
|
492
|
+
(variables: { name: string }) => api.post<User>('/users', variables),
|
|
493
|
+
{ invalidates: ['users'] },
|
|
494
|
+
)
|
|
495
|
+
|
|
496
|
+
async function handleSubmit(name: string) {
|
|
497
|
+
const { data, error } = await mutate({ name })
|
|
498
|
+
|
|
499
|
+
if (error === null) navigate(`/users/${data.id}`)
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
return <Form onSubmit={handleSubmit} busy={isPending} error={error?.message} />
|
|
503
|
+
}
|
|
504
|
+
```
|
|
505
|
+
|
|
506
|
+
It returns `mutate`, `status` (`idle`, `pending`, `success` or `error`), `data`, `error`, `isPending` and `reset`.
|
|
507
|
+
|
|
508
|
+
`usePrefetch` returns a function that warms the cache in the `prefetch` lane, so the queue serves it behind anything on screen:
|
|
509
|
+
|
|
510
|
+
```tsx
|
|
511
|
+
function UserRow({ id }: { id: string }) {
|
|
512
|
+
const prefetch = usePrefetch()
|
|
513
|
+
|
|
514
|
+
return <Row onMouseEnter={() => prefetch('/users/:id', { params: { id } })} />
|
|
515
|
+
}
|
|
516
|
+
```
|
|
517
|
+
|
|
518
|
+
`useSession` returns the page's one session state, typed as your session. Every remote calling it follows the same state, so a lost session signs the whole page out at once. It throws `INVALID_ARGUMENT` when the client has no `session` plugin.
|
|
519
|
+
|
|
520
|
+
```tsx
|
|
521
|
+
function Nav() {
|
|
522
|
+
const { status, session } = useSession()
|
|
523
|
+
|
|
524
|
+
if (status === 'unknown' || status === 'loading') return <Spinner />
|
|
525
|
+
if (status === 'anonymous') return <SignIn />
|
|
526
|
+
if (status === 'error') return <Retry onClick={() => void api.session.reload()} />
|
|
527
|
+
|
|
528
|
+
return <Avatar name={session.id} />
|
|
529
|
+
}
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
## Any other framework
|
|
533
|
+
|
|
534
|
+
Everything observable is a store with two methods, `getState()` and `subscribe(listener)`. `subscribe` returns an unsubscribe function and does not call the listener on subscribe, so read `getState()` first. That is `useSyncExternalStore`'s contract, and not Svelte's, which expects the current value on subscribe. In Svelte, wrap the store:
|
|
535
|
+
|
|
536
|
+
```ts
|
|
537
|
+
import { readable } from 'svelte/store'
|
|
538
|
+
|
|
539
|
+
const store = api.observe<User>(api.getKey('/users/:id', { params: { id: 1 } }))
|
|
540
|
+
|
|
541
|
+
export const user = readable(store.getState(), set => store.subscribe(set))
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
`api.session`, `api.observe(key)` and `devtools.store` are all this shape.
|
|
545
|
+
|
|
546
|
+
## Uploads
|
|
547
|
+
|
|
548
|
+
`api.upload(path, body, options)` posts a `FormData` or `Blob` with no default timeout, through the same middleware stack and `config.fetch` as any request, mock servers included.
|
|
549
|
+
|
|
550
|
+
```ts
|
|
551
|
+
await api.upload('/avatars', file)
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
For progress events, use `uploadWithProgress` from `@zerosumstudio/conduit/upload`. `fetch` has no event for upload progress, so this one request goes through `XMLHttpRequest`, and session, retry, the queue and the origin check still apply.
|
|
555
|
+
|
|
556
|
+
```ts
|
|
557
|
+
import { uploadWithProgress } from '@zerosumstudio/conduit/upload'
|
|
558
|
+
|
|
559
|
+
await uploadWithProgress(api, '/avatars', file, {
|
|
560
|
+
onProgress: ({ loaded, total, percent }) => setProgress(percent ?? 0),
|
|
561
|
+
})
|
|
562
|
+
```
|
|
563
|
+
|
|
564
|
+
`total` and `percent` are `undefined` when the server doesn't report a length. `XMLHttpRequest` can't refuse a redirect and can't leave out same-origin cookies, so a progress upload rejects with `INVALID_ARGUMENT` when it carries a custom credential header and `redirect` isn't `'follow'`, and when `credentials` is `'omit'`. `Authorization` and cookies are fine. See [Redirects](#redirects).
|
|
565
|
+
|
|
566
|
+
## Events and devtools
|
|
567
|
+
|
|
568
|
+
One shared client sees traffic from every remote on the page, which is what makes "who issued this" answerable. Request, cache, dedupe, retry, queue, session and API version events publish on `api.events`, and nothing is built while nothing is listening. A remote can listen and nothing else: it can't clear another bundle's listeners or publish events.
|
|
569
|
+
|
|
570
|
+
```ts
|
|
571
|
+
api.events.on('request:error', ({ request, error }) => {
|
|
572
|
+
reportToTelemetry(`${request.owner} ${error.code} ${error.requestId}`)
|
|
573
|
+
})
|
|
574
|
+
```
|
|
575
|
+
|
|
576
|
+
`on(type, listener)` and `onAny(listener)` return an unsubscribe function. A listener that throws is reported through the logger and never fails a request.
|
|
577
|
+
|
|
578
|
+
```ts
|
|
579
|
+
import { attachDevtools } from '@zerosumstudio/conduit/devtools'
|
|
580
|
+
|
|
581
|
+
const devtools = attachDevtools(api)
|
|
582
|
+
|
|
583
|
+
devtools.store.subscribe(state => render(state)) // entries, inFlight, counters, session, isSessionLost
|
|
584
|
+
devtools.detach()
|
|
585
|
+
```
|
|
586
|
+
|
|
587
|
+
Devtools read the event stream and nothing else. Entries carry the owner, lane, status, `durationMs` and `requestId`, and query strings are stripped from urls and keys. In a development build the handle also lands on `globalThis.__CONDUIT_DEVTOOLS__` for console poking, and `getDevtools()` reads it. Pass `expose: false` to opt out, or `expose: true` to keep it in production. `max` (default `100`) caps the finished entries kept.
|
|
588
|
+
|
|
589
|
+
## Errors
|
|
590
|
+
|
|
591
|
+
Everything rejects with a `ConduitError` carrying a `code`, plus `status`, `url`, `method`, `owner`, `requestId`, `retryAfterMs` and `cause` where they apply. Errors are not subclassed, so check `error.code`.
|
|
592
|
+
|
|
593
|
+
```ts
|
|
594
|
+
import { isConduitError, isErrorCode } from '@zerosumstudio/conduit'
|
|
595
|
+
|
|
596
|
+
const { error } = await api.get<User[]>('/users').safe()
|
|
597
|
+
|
|
598
|
+
if (isErrorCode(error, 'TIMEOUT')) retryLater()
|
|
599
|
+
if (isErrorCode(error, 'HTTP_STATUS') && error.status === 404) showEmptyState()
|
|
600
|
+
```
|
|
601
|
+
|
|
602
|
+
Use `isConduitError(value)` and not `instanceof ConduitError`. Two bundles that each carry a copy of conduit have two `ConduitError` classes, and `instanceof` is false across them. `isConduitError` checks a brand that holds across copies.
|
|
603
|
+
|
|
604
|
+
| Code | Raised when |
|
|
605
|
+
| --------------------- | -------------------------------------------------------------------------------------------------------------- |
|
|
606
|
+
| `HTTP_STATUS` | The server answered with a failing status. `status`, `headers` and the decoded `body` are set |
|
|
607
|
+
| `NETWORK` | The request never reached a server: DNS, offline, CORS or TLS |
|
|
608
|
+
| `TIMEOUT` | The request exceeded its deadline |
|
|
609
|
+
| `ABORTED` | A caller, a scope, `abortAll`, a change of user or a destroyed client cancelled it |
|
|
610
|
+
| `PARSE_FAILED` | A body arrived that doesn't decode as the parse mode says |
|
|
611
|
+
| `VALIDATION_FAILED` | An endpoint's `response` schema or function rejected the body. The issues are the error's `body` |
|
|
612
|
+
| `UNAUTHENTICATED` | The session was lost and could not be recovered |
|
|
613
|
+
| `REDIRECT_BLOCKED` | A request carrying a credential was answered with a redirect, see [Redirects](#redirects) |
|
|
614
|
+
| `ORIGIN_REJECTED` | A url resolved outside the origins this client may call, see [Origins](#origins) |
|
|
615
|
+
| `INVALID_ARGUMENT` | conduit was used wrong: a bad param, a body on `GET`, a bad `origins` entry, a relative `baseUrl` with no page |
|
|
616
|
+
| `DESTROYED` | The client was destroyed |
|
|
617
|
+
| `DUPLICATE_PLUGIN` | A plugin was installed twice |
|
|
618
|
+
| `EXTENSION_COLLISION` | A plugin tried to add a name the client already has |
|
|
619
|
+
| `UNKNOWN` | Something threw that conduit can't classify |
|
|
620
|
+
|
|
621
|
+
`body` and `headers` are readable but not enumerable, so a logger that walks properties doesn't print them. `toJSON()` omits them as well, and messages carry the url without its query string. `toConduitError(value, code?, message?)` coerces anything thrown. A conduit error passes through, and a recode keeps the original as `cause`. `ConduitErrorCode` is the type of `code`.
|
|
622
|
+
|
|
623
|
+
### Logger
|
|
624
|
+
|
|
625
|
+
`logger` is where conduit reports what nobody is awaiting: a listener that threw, a background cache refresh that failed, a failed renewal, a background session read, and development warnings. Every message is prefixed `[conduit]`.
|
|
626
|
+
|
|
627
|
+
```ts
|
|
628
|
+
createClient({
|
|
629
|
+
baseUrl: '/api',
|
|
630
|
+
logger: {
|
|
631
|
+
warn: message => telemetry.warn(message),
|
|
632
|
+
error: message => telemetry.error(message),
|
|
633
|
+
},
|
|
634
|
+
})
|
|
635
|
+
```
|
|
636
|
+
|
|
637
|
+
## Testing
|
|
638
|
+
|
|
639
|
+
`@zerosumstudio/conduit/testing` mocks at the transport, so cache, dedupe, retry, the queue and session recovery all run for real, and the request's `signal` is honoured the way `fetch` honours it.
|
|
640
|
+
|
|
641
|
+
```ts
|
|
642
|
+
import {
|
|
643
|
+
clearSharedClients,
|
|
644
|
+
createMockServer,
|
|
645
|
+
delay,
|
|
646
|
+
networkError,
|
|
647
|
+
status,
|
|
648
|
+
} from '@zerosumstudio/conduit/testing'
|
|
649
|
+
|
|
650
|
+
const server = createMockServer({ baseUrl: 'https://api.example.com' })
|
|
651
|
+
|
|
652
|
+
server.get('/users/:id', request => ({ id: request.params.id }))
|
|
653
|
+
server.post('/users', status(201, { id: 2 }))
|
|
654
|
+
server.get('/flaky', status(503), { times: 1 }) // fails once, then falls through
|
|
655
|
+
server.get('/slow', delay(500, { ok: true }))
|
|
656
|
+
server.get('/down', networkError())
|
|
657
|
+
|
|
658
|
+
const api = defaults(createClient({ baseUrl: 'https://api.example.com', fetch: server.fetch }))
|
|
659
|
+
|
|
660
|
+
afterEach(() => {
|
|
661
|
+
server.reset()
|
|
662
|
+
clearSharedClients()
|
|
663
|
+
})
|
|
664
|
+
```
|
|
665
|
+
|
|
666
|
+
A responder is a function or a value: a `Response` as it is, an `Error` as a network failure, `undefined` as a 204, a string, `Blob`, `FormData` or stream as the body, and anything else as JSON. One that throws answers 500 with `{ message }`. Routes match the request's pathname, the last route registered wins, and a route used up by `times` falls through to the earlier ones.
|
|
667
|
+
|
|
668
|
+
Unmatched requests fail where they were made and name what is registered, unless you pass `onUnmatched: 'notFound'` to `createMockServer`. `server.calls` has everything that arrived, with an absolute `url`. A custom `fetch` you write yourself also receives an absolute url, so match on `new URL(input).pathname`, not on `input.startsWith('/api')`.
|
|
669
|
+
|
|
670
|
+
A relative `baseUrl` needs a page. In a node test environment, pass an absolute one as above, or use jsdom. Testing the hooks while conduit is linked from a sibling checkout (`link:` or `pnpm link`) needs `resolve.dedupe: ['react', 'react-dom']` in the consumer's vite or vitest config, or React resolves twice and every hook call fails.
|
|
671
|
+
|
|
672
|
+
## Security
|
|
673
|
+
|
|
674
|
+
What conduit enforces and what it leaves to the app is in [docs/threat-model.md](./docs/threat-model.md). The short version is below.
|
|
675
|
+
|
|
676
|
+
### Origins
|
|
677
|
+
|
|
678
|
+
Every url is resolved with `new URL` and compared as an origin, and what is sent is the url that was checked. A request may go to `baseUrl`'s origin, or the page's when `baseUrl` is relative, or an origin listed in `origins`. Anything else rejects with `ORIGIN_REJECTED` before a plugin runs, and the transport checks again, so a middleware that rewrites `url` can't leave the list either.
|
|
679
|
+
|
|
680
|
+
```ts
|
|
681
|
+
const api = createClient({ baseUrl: '/api', origins: ['https://cdn.example.com'] })
|
|
682
|
+
|
|
683
|
+
api.get('https://cdn.example.com/assets/logo.png') // fine, listed
|
|
684
|
+
api.get('https://evil.example.com/x') // rejected: ORIGIN_REJECTED
|
|
685
|
+
api.get('data:text/plain,hi') // rejected: ORIGIN_REJECTED, only http and https are sent
|
|
686
|
+
api.get('/../other') // rejected: ORIGIN_REJECTED, outside baseUrl's path
|
|
687
|
+
```
|
|
688
|
+
|
|
689
|
+
A relative path is always joined under `baseUrl`, so `//host/x` is a path on the API origin and never a host. Only an absolute url can name another origin, and it must be listed. A relative path has to stay inside `baseUrl`'s path prefix, a url with credentials in it is refused, and a path that reads as a scheme (`users:list`) is rejected with a hint to write `/users:list`. `origins` takes bare origins such as `https://host:8443`. A path, a query or a non-http scheme is `INVALID_ARGUMENT`, and a trailing slash is dropped.
|
|
690
|
+
|
|
691
|
+
A relative `baseUrl` (`'/api'`) means the page's own origin and needs a page. Without one, the first request fails with `INVALID_ARGUMENT`, so on a server pass an absolute `baseUrl`.
|
|
692
|
+
|
|
693
|
+
Static `headers` on the client go on every request, including those to a listed third-party origin. Only the session's `authorize` is scoped to the API origin, or to `session({ origins })`. Put a static credential in `headers` only when every origin in `origins` may see it, and attach it with `authorize` otherwise.
|
|
694
|
+
|
|
695
|
+
With a relative `baseUrl`, the API origin comes from the page's base url, so a `<base href>` that points at another origin moves it, and the session's credentials go with it. Plain `fetch` resolves the same way. Block it with a `base-uri 'self'` or `base-uri 'none'` directive in your content security policy.
|
|
696
|
+
|
|
697
|
+
### Redirects
|
|
698
|
+
|
|
699
|
+
A request that carries a credential the platform won't strip itself is sent with `redirect: 'manual'`, and a redirect answer rejects with `REDIRECT_BLOCKED`. Browsers and Node strip `Authorization` and `cookie` when a redirect crosses origins, and send every other header on, so a download endpoint that answers 302 to a CDN, or an open redirect, would receive an `x-api-key`.
|
|
700
|
+
|
|
701
|
+
A credential here is a header in the guard list: `DEFAULT_REDACT.headers`, anything in `redact.headers`, and every header the session's `authorize` adds or changes. Plain Bearer and cookie setups don't match, because the platform handles them, and keep following redirects.
|
|
702
|
+
|
|
703
|
+
```ts
|
|
704
|
+
api.get('/export', { headers: { 'x-api-key': key } }) // REDIRECT_BLOCKED on a 301, 302, 303, 307 or 308
|
|
705
|
+
api.get('/download', { headers: { 'x-api-key': key }, redirect: 'follow' }) // follows, on purpose
|
|
706
|
+
```
|
|
707
|
+
|
|
708
|
+
The rule covers same-origin redirects too, so a custom credential on an endpoint that really redirects needs `redirect: 'follow'`. The error carries `status` and `headers`, and the status is `0` in a browser, where a manual redirect is an opaque response. Retry never replays it. An explicit `redirect` on the request or the client always wins, and with `'manual'` a 3xx is an `HTTP_STATUS`. conduit never follows a redirect itself. A progress upload can't be blocked and fails closed, see [Uploads](#uploads).
|
|
709
|
+
|
|
710
|
+
### Redaction
|
|
711
|
+
|
|
712
|
+
Credentials are visible to the plugin chain that attaches them and to nothing else. `.response()`, every event, devtools and error urls show a credential header as `[redacted]` and the value of a secret query parameter as `[redacted]`. A header the session's `authorize` sets is hidden too, whatever the list says.
|
|
713
|
+
|
|
714
|
+
```ts
|
|
715
|
+
import { DEFAULT_REDACT } from '@zerosumstudio/conduit'
|
|
716
|
+
|
|
717
|
+
const api = createClient({
|
|
718
|
+
baseUrl: '/api',
|
|
719
|
+
redact: { headers: [...DEFAULT_REDACT.headers, 'x-tenant-token'], query: ['ticket'] },
|
|
720
|
+
})
|
|
721
|
+
|
|
722
|
+
const response = await api
|
|
723
|
+
.get('/me?ticket=abc', { headers: { 'x-tenant-token': 'secret' } })
|
|
724
|
+
.response()
|
|
725
|
+
|
|
726
|
+
response.request.headers.get('x-tenant-token') // '[redacted]'
|
|
727
|
+
response.request.url // '…/api/me?ticket=[redacted]'
|
|
728
|
+
```
|
|
729
|
+
|
|
730
|
+
`redact.headers` and `redact.query` each replace the defaults for what is displayed, and `[]` turns display redaction off for that list. The redirect and upload guards are not affected: their list is always `DEFAULT_REDACT.headers` plus `redact.headers` plus what `authorize` adds, so narrowing `redact` can't turn them off. Query names are matched case-insensitively, and a trailing `*` matches a prefix.
|
|
731
|
+
|
|
732
|
+
| List | Defaults |
|
|
733
|
+
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
734
|
+
| `DEFAULT_REDACT.headers` | `authorization`, `cookie`, `proxy-authorization`, `x-api-key`, `x-auth-token`, `x-csrf-token`, `x-xsrf-token`, `x-session-token`, `x-access-token`, `x-amz-security-token` |
|
|
735
|
+
| `DEFAULT_REDACT.query` | `token`, `access_token`, `refresh_token`, `id_token`, `code`, `key`, `api_key`, `apikey`, `password`, `secret`, `signature`, `sig`, `client_secret`, `access-token`, `jwt`, `private_token`, `sessionid`, `x-amz-*`, `x-goog-*` |
|
|
736
|
+
|
|
737
|
+
`response.raw` is the platform's `Response`, with its real url. Don't log it. Secrets in a query string still travel in the url, into history, referrers and server logs, so put them in a header.
|
|
738
|
+
|
|
739
|
+
## Size
|
|
740
|
+
|
|
741
|
+
Minified and brotli compressed, including dependencies, from `pnpm size`. Plugins you don't import are tree-shaken away.
|
|
742
|
+
|
|
743
|
+
| Import | Size |
|
|
744
|
+
| ----------------------------------------------------------------- | -------- |
|
|
745
|
+
| `{ createClient }` only | 6.81 KB |
|
|
746
|
+
| Core with `sharedClient`, cache, dedupe, retry, timeout and queue | 9.85 KB |
|
|
747
|
+
| Everything from the main entry | 12.62 KB |
|
|
748
|
+
| Errors only (`ConduitError`, `isConduitError`) | 291 B |
|
|
749
|
+
| React bindings (`/react`) | 2.18 KB |
|
|
750
|
+
| Devtools (`/devtools`) | 1.12 KB |
|
|
751
|
+
| Testing (`/testing`) | 1.63 KB |
|
|
752
|
+
| Progress uploads (`/upload`) | 651 B |
|
|
753
|
+
|
|
754
|
+
## TypeScript
|
|
755
|
+
|
|
756
|
+
Types are inferred from the plugins you install, and each `.with()` widens the client's type with the plugin's API. `defaults()` returns the standard stack, and `DefaultClient & SessionApi<Session>` names it when a function takes the client.
|
|
757
|
+
|
|
758
|
+
```ts
|
|
759
|
+
import type { CacheApi, Client, SessionApi } from '@zerosumstudio/conduit'
|
|
760
|
+
|
|
761
|
+
function refresh(client: Client & CacheApi) {
|
|
762
|
+
client.invalidateTag('users')
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
type AppClient = typeof api // Client & ObservableApi & CacheApi & DedupeApi & QueueApi & SessionApi<Session>
|
|
766
|
+
```
|
|
767
|
+
|
|
768
|
+
`ConduitMeta` takes your own `meta` keys through declaration merging, and `ConduitEventMap` takes your own events:
|
|
769
|
+
|
|
770
|
+
```ts
|
|
771
|
+
declare module '@zerosumstudio/conduit' {
|
|
772
|
+
interface ConduitMeta {
|
|
773
|
+
'my-plugin.skip'?: boolean
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
```
|
|
777
|
+
|
|
778
|
+
`Client` is exported as a type. Create one with `createClient`. Also exported: `Plugin`, `PluginContext`, `Middleware`, `ConduitRequest`, `ConduitResponse`, `SafeResult`, `RequestOptions`, `PathParamsOf`, `PathVars`, `Endpoint`, `StandardSchemaV1`, `SessionAdapter`, `SessionState`, `QueryState`, `ConduitErrorCode`, `ConduitLogger`, `ClientEvents` and every event type.
|
|
779
|
+
|
|
780
|
+
## Upgrading to 1.0
|
|
781
|
+
|
|
782
|
+
1.0 is the first release under `@zerosumstudio`. Coming from `@bkincz/conduit` 2.0, the package is ESM-only on Node 26, error codes are renamed and split, a tagged `POST` is no longer cached on its own, the session has no sticky terminal state, and many options and methods are renamed. The [migration guide](./docs/migration-1.0.md) opens with a checklist and covers every change with a before and after. The full list is in the [changelog](./CHANGELOG.md).
|
|
783
|
+
|
|
784
|
+
## License
|
|
785
|
+
|
|
786
|
+
MIT © zerosum studio
|