@spfn/core 0.3.0-beta.24 → 0.3.0-beta.26

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.
@@ -0,0 +1,539 @@
1
+ # @spfn/core/state — server-owned state, declared once
2
+
3
+ A signed-in shell shows a handful of per-person facts: has this person a workspace, agreed to
4
+ the current terms, which role here, is the runtime ready. Each used to be wired by hand three
5
+ times — a read route for the first paint, a domain event the browser re-interprets into a
6
+ value, and a client store that merges the two — and the three drifted.
7
+
8
+ `defineState` declares such a fact once. `defineStateRouter` derives from that one
9
+ declaration the read route, the write route, its entry in a snapshot route and the SSE event.
10
+ The server is the single source of truth: every value a client receives is what `read()`
11
+ returned, read on the server; the browser never computes one.
12
+
13
+ The browser side — `@spfn/core/state/client` and the React hook `@spfn/core/state/react` —
14
+ is described under [Browser](#browser).
15
+
16
+ ## Import paths
17
+
18
+ ```typescript
19
+ // server
20
+ import { defineState, defineStateRouter } from '@spfn/core/state';
21
+ import type { InferStateValue, InferStateKey, InferStateInput } from '@spfn/core/state';
22
+ import { Type } from '@sinclair/typebox'; // for .key() / .value() / .data() / .write() schemas
23
+
24
+ // browser — the router by type only
25
+ import { createStateClient } from '@spfn/core/state/client';
26
+ import { useServerState } from '@spfn/core/state/react';
27
+ import type { states } from '@/server/states';
28
+ ```
29
+
30
+ ---
31
+
32
+ ## Public API (complete)
33
+
34
+ From `@spfn/core/state`:
35
+
36
+ - Builder: `defineState(id)` → `StateBuilder`
37
+ - Router: `defineStateRouter(states, { path?, subject? })` → `StateRouter`
38
+ - Types: `StateBuilder`, `StateRouter`, `StateRouterOptions`, `StateRoutes`, `StateEvents`,
39
+ `StatesSnapshot`, `StatesManifest`, `SubjectResolver`, `InferStateValue`, `InferStateKey`, `InferStateInput`,
40
+ `StateShape`, `StateValue`, `StateKey`, `StateResult`, `StateSnapshot`, `StateFrame`,
41
+ `ReadContext`, `PermissionContext`, `WriteContext`, `ChangedPayload`, `GrantTarget`,
42
+ `RevokeTarget`, `StateContract`, `StateWriteOptions`, `RoutableState`
43
+
44
+ `StateBuilder` methods — immutable, every call returns a new builder, order free, no terminal
45
+ method:
46
+
47
+ | Method | Effect | Refused |
48
+ | --- | --- | --- |
49
+ | `.key(schema, { shared? })` | Key fields: one value per key. `shared: true` — the value does not depend on the subject | a non-object schema; a field that is not a required `Type.String()`; a field named `events` or `token`; a second call |
50
+ | `.value(schema)` | The value. Required | a second call |
51
+ | `.data(schema)` | Data attached to the value. Optional | a second call |
52
+ | `.use(mws)` / `.skip(names)` | Middleware for the two per-state routes, `get<Id>State` / `put<Id>State`; calls add up. **Not authorization** — the snapshot and the SSE stream cannot run it; authorize with `.canRead()` (see [Permissions](#permissions)) | at `defineStateRouter`, when the state declares no `.canRead()` |
53
+ | `.contract({ since, auth?, requiresSession?, deprecatedIn?, removedIn? })` | Publishes the read route, the write route and the event | a second call |
54
+ | `.canRead(fn)` | `({ subject, principal, key? }) => boolean \| Promise<boolean>`. Required on a keyed state | a second call |
55
+ | `.canWrite(fn)` | Same shape. Absent → `canRead` decides | a second call |
56
+ | `.read(fn)` | The only source of a value. Required. Returns `{ value }`, or `{ value, data }` with `.data` — checked against the declaration on every path | a second call |
57
+ | `.write(input, fn, { since?, deprecatedIn?, removedIn? })` | Derives the write route. `fn` gets the read context plus `input` and returns nothing | a second call |
58
+ | `.changedBy(events)` | Domain events whose payload is read like the change signal's (see [The change signal](#the-change-signal)) | a second call; at `defineStateRouter`, an event whose payload schema lacks a required field |
59
+
60
+ `StateBuilder` members: `.changed` (the change signal), `.grant({ subject, key })` (`key` on a
61
+ keyed state only, and required there), `.revoke({ subject, key? })`, `.id`.
62
+
63
+ `StateRouter`: `.router` (a `Router` from `defineRouter`), `.events` (`Record` of the SSE
64
+ events keyed by wire name), `.states` (the declarations as given).
65
+
66
+ The types of `.read()`, `.write()`, `.canRead()` and `.canWrite()` contexts and of `R` are
67
+ computed from the schemas declared *before* the call — runtime order is free, but declare
68
+ `.key()`, `.value()` and `.data()` first to have the functions checked against them.
69
+
70
+ ---
71
+
72
+ ## Quick start
73
+
74
+ ```typescript
75
+ // src/server/state.ts
76
+ import { defineState, defineStateRouter } from '@spfn/core/state';
77
+ import { Type } from '@sinclair/typebox';
78
+
79
+ export const consent = defineState('consent') // keyless: one value per subject
80
+ .value(Type.Union([Type.Literal('pending'), Type.Literal('agreed')]))
81
+ .data(Type.Object({ marketing: Type.Boolean() }))
82
+ .contract({ since: '1.3.0', auth: 'clientProofV1', requiresSession: true })
83
+ .read(({ subject }) => consentService.current(subject))
84
+ .write(Type.Object({ termsVersion: Type.String(), marketing: Type.Boolean() }),
85
+ ({ subject, input }) => consentService.record(subject, input));
86
+
87
+ export const runtime = defineState('runtime') // keyed, shared by every reader of the key
88
+ .key(Type.Object({ workspaceId: Type.String() }), { shared: true })
89
+ .value(Type.Union([Type.Literal('provisioning'), Type.Literal('ready')]))
90
+ .canRead(({ subject, key }) => memberService.isMember(subject, key.workspaceId))
91
+ .canWrite(({ subject, key }) => memberService.isAdmin(subject, key.workspaceId))
92
+ .read(({ key }) => runtimeService.status(key.workspaceId))
93
+ .write(Type.Object({ action: Type.Literal('restart') }), ({ key }) => runtimeService.restart(key.workspaceId));
94
+
95
+ export const member = defineState('member') // keyed, one value per (subject, key)
96
+ .key(Type.Object({ workspaceId: Type.String() }))
97
+ .value(Type.Union([Type.Literal('owner'), Type.Literal('admin'), Type.Literal('member')]))
98
+ .canRead(({ subject, key }) => memberService.isMember(subject, key.workspaceId))
99
+ .read(({ subject, key }) => memberService.roleOf(subject, key.workspaceId));
100
+
101
+ export const states = defineStateRouter({ consent, runtime, member });
102
+ ```
103
+
104
+ ```typescript
105
+ // server.config.ts
106
+ export default defineServerConfig()
107
+ .routes(appRouter.packages([states.router]))
108
+ .events(defineEventRouter({ ...appEvents, ...states.events }), { auth: { enabled: true, resolvePrincipal } })
109
+ .build();
110
+ ```
111
+
112
+ `.packages([states.router])` is the documented mount: the routes reach the generated route map
113
+ like `authRouter`'s, and an app route with the same name is refused by the route-map
114
+ generator's existing duplicate check. Spreading `states.router.routes` into the app router also
115
+ works. `read()` and `write()` are service calls; database access stays in repositories.
116
+
117
+ After a commit that changed a value, the app emits the change signal:
118
+
119
+ ```typescript
120
+ await consent.changed.emit({ subject: userId });
121
+ await member.changed.emit({ workspaceId, subject: userId });
122
+ await runtime.changed.emit({ workspaceId });
123
+ ```
124
+
125
+ ---
126
+
127
+ ## Three kinds of subject
128
+
129
+ | Declaration | `read()` receives | One value per | Frame reaches |
130
+ | --- | --- | --- | --- |
131
+ | no `.key()` | `{ subject, principal }` | subject | that subject's connections |
132
+ | `.key(K)` | `{ subject, principal, key }` | subject and key | that subject's connections that declared the key |
133
+ | `.key(K, { shared: true })` | `{ principal, key }` — no `subject` | key | every connection that declared the key and passed `canRead` |
134
+
135
+ A keyed state must declare `.canRead()`: the key comes from the request, so without it any
136
+ subject could read any key. `defineStateRouter` refuses one that does not.
137
+
138
+ Key fields are required strings. They travel as query parameters (always strings) and the
139
+ SSE frame filter compares them with the connect query as strings, so a `Type.Number()` key
140
+ would never match — `.key()` refuses it rather than coercing on one side. `events` and
141
+ `token` are refused as field names: the SSE stream reads them from the same connect query.
142
+
143
+ ---
144
+
145
+ ## What one declaration derives
146
+
147
+ With the default `path` `/state`:
148
+
149
+ | Derived | Shape |
150
+ | --- | --- |
151
+ | `getConsentState` | `GET /state/consent` → `{ at, value, data }`. Keyed: key fields in the query, validated by the route (missing → 400) |
152
+ | `putConsentState` | `PUT /state/consent`, only when `.write()` exists. Body = the input schema, keyed: key fields in the query. → `{ at, value, data }` |
153
+ | `getStates` | `GET /state` → `{ at, states: { consent: { value, data }, … } }` in declaration order — one for all states of the router |
154
+ | `states.events['state.consent.changed']` | the SSE event, payload `{ at, value, data, key?, subject? }` — `key` on a keyed state, `subject` unless shared |
155
+ | `consent.changed` | the change signal, payload keyless `{ subject }`, keyed `{ ...keyFields, subject }`, shared `{ ...keyFields }` |
156
+
157
+ `data` is present exactly when `.data()` is declared, in every response and frame.
158
+
159
+ Route names are `get<Id>State` / `put<Id>State` with the id's first letter upper-cased, so an
160
+ id must match `^[a-z][a-zA-Z0-9]*$` — `defineState` refuses another.
161
+
162
+ `defineStateRouter` refuses, naming the state: no `.value()` or `.read()`; a keyed state
163
+ without `.canRead()`; a state with `.use()` or `.skip()` but no `.canRead()`; a
164
+ `.changedBy()` event whose payload schema lacks a field the signal needs; two states with one
165
+ id; a `.write(…, { since })` on a state without `.contract()`; a state already grouped by
166
+ another router (each router subscribes the change signal, so every change would be read and
167
+ sent twice). A builder without `.value()` or
168
+ `.read()` is also a type error at the call.
169
+
170
+ ---
171
+
172
+ ## Handler order
173
+
174
+ The subject comes from `options.subject(c)`, default `c.get('auth')?.userId ?? null` — the
175
+ SSE `getSubject` default. No subject → `UnauthorizedError` (401). The principal on HTTP is
176
+ `c.get('auth')` as the app's middleware set it.
177
+
178
+ - **Read** `GET <path>/<id>`: subject → key (query, validated) → `canRead` (false → 403) →
179
+ `at` → `read()` → `{ at, value, data }`.
180
+ - **Write** `PUT <path>/<id>`: subject → key → `canWrite ?? canRead` (false → 403, `write` not
181
+ called) → `write({ …, input })` → `at` → `read()` → one SSE frame → `{ at, value, data }`.
182
+ A `write` that throws propagates; nothing is read and no frame is sent. The input is a
183
+ command, never the value: what the route answers is re-read.
184
+ - **Snapshot** `GET <path>`: subject → one `at` → for each state, in declaration order: a keyed
185
+ state whose key fields are not all in the query is omitted; `canRead` false → omitted;
186
+ otherwise `read()`. A keyed state left out never stops a later keyless one. A `read()` that
187
+ throws fails the whole request — an error is not a permission. The answer is
188
+ `{ at, states, manifest }`: `manifest` is `{ [id]: { key: string[]; write: boolean } }` for
189
+ every state in declaration order — the key fields (`[]` when keyless) and whether it has a
190
+ write — built once when the router is built. It is what the [browser client](#browser)
191
+ knows of the router at runtime.
192
+
193
+ Every `read()` result is checked against `{ value, data }` as declared — `data` exactly when
194
+ `.data()` is, no other field — with a schema built once per state when the router is built.
195
+ A result that does not match fails the read, write and snapshot routes with an `Error` (500)
196
+ naming the state and the first validation message, never the value; on the change signal it
197
+ is logged at warn and sends nothing; `grant` rejects with the same error and sends nothing.
198
+
199
+ A write that committed and then failed to read — `read()` threw or returned an undeclared
200
+ result — answers 500 and sends no frame, although the write ran. There is no value to report;
201
+ the next signal or read brings the client up to date.
202
+
203
+ The derived routes are ordinary `RouteDef`s registered by `registerRoutes`, so `.use()`
204
+ middleware runs inside the route's own chain, after the app's global middleware — it sees the
205
+ `auth` the app set. It runs on the two per-state routes only: the snapshot route and the SSE
206
+ stream carry no state's `.use()`. That is why `.use()` / `.skip()` require `.canRead()` — a
207
+ guard in middleware would hold on `GET <path>/<id>` and leak through `GET <path>` and the
208
+ stream. A state that needs middleware only for, say, rate limiting declares
209
+ `.canRead(() => true)` to say so.
210
+
211
+ ---
212
+
213
+ ## The change signal
214
+
215
+ The app emits `state.changed` **after the commit** that changed the value — from
216
+ `onAfterCommit` (`@spfn/core/db`), not inside the transaction. The module never reads on its
217
+ own: no polling, no database trigger. On each signal it reads and sends one frame:
218
+
219
+ | State | Read | Frame |
220
+ | --- | --- | --- |
221
+ | keyless | `read({ subject })` | `{ at, value, data, subject }` |
222
+ | keyed | `read({ subject, key })` | `{ at, value, data, key, subject }` |
223
+ | keyed shared | `read({ key })` once, however many connections hold the key | `{ at, value, data, key }` |
224
+
225
+ `emit` validates its payload and refuses a missing field — the module reads exactly what the
226
+ payload names. On the signal path `principal` is `undefined`. A `read()` that throws is logged
227
+ at warn with the state id and sends nothing; the next signal works as usual.
228
+
229
+ The signal is in-process: the pod that committed reads and emits, and the SSE event (wired to
230
+ the cache like any event in `.events()`) carries the frame to every pod. Do not attach a cache
231
+ to `state.changed` itself — every pod would read and send the frame again.
232
+
233
+ `changed.emit` on a builder no router grouped throws, naming the state. Every builder call
234
+ returns a new builder and the router subscribes the signal of the instance it was given, so
235
+ export that final instance — an intermediate `base` in `base.write(…)` is never routed.
236
+
237
+ **`.changedBy([event, …])`.** A domain event the app already emits can stand in for the
238
+ signal: the router subscribes each listed `EventDef` and reads its payload like
239
+ `changed.emit`'s — keyless `subject`; keyed the key fields and `subject`; shared the key
240
+ fields. `defineStateRouter` refuses an event whose declared payload schema lacks one of those
241
+ as a required property, naming the event and the field. A payload that fails the same check at
242
+ runtime is logged at warn and skipped (the app emitted it; there is nobody to throw to). The
243
+ module attaches nothing to the event — no `canSubscribe`, no `filter`; it only subscribes.
244
+
245
+ - An event listed by two states re-reads both and sends two frames.
246
+ - An event that is also in the app's SSE router reaches the browser twice by design: as itself,
247
+ and through the state as `state.<id>.changed`.
248
+ - One pod re-reads: the pod that emitted the event. A listed event bound to the cache transport
249
+ (every event in `.events()` is) reaches every pod, so the router subscribes it with
250
+ `{ localOnly: true }`; the derived `state.<id>.changed` frame then fans out to every pod
251
+ through the cache like any event. One emit, one read, one frame.
252
+ - On the emitting pod `await domainEvent.emit()` also awaits the state's `read()` and its frame
253
+ publish, so a slow `read()` delays the caller of `emit`.
254
+ - The payload is checked against the signal's fields only; a field the state does not name is
255
+ ignored, even when the key schema declares `additionalProperties: false`.
256
+
257
+ `read()`'s result is copied into the frame, so neither a handler mutating what it returned nor
258
+ a subscriber mutating the payload changes the other.
259
+
260
+ ---
261
+
262
+ ## Permissions
263
+
264
+ | Predicate | Enforced at | On refusal |
265
+ | --- | --- | --- |
266
+ | `canRead` | `GET <path>/<id>` | 403 |
267
+ | `canRead` | `GET <path>` | that state omitted |
268
+ | `canRead` | SSE connect (`canSubscribe`), with the key from the connect query | that event in `connected.deniedEvents` |
269
+ | `canWrite ?? canRead` | `PUT <path>/<id>` | 403 |
270
+
271
+ On SSE the connection declares its key in the connect query —
272
+ `/events/stream?events=state.runtime.changed&workspaceId=w1&token=…`. The module sets each
273
+ derived event's `.canSubscribe()` and `.filter()` (`@spfn/core/event`):
274
+
275
+ - `canSubscribe`: keyed — any key field missing from the query denies without calling
276
+ `canRead`; otherwise `canRead({ subject, principal, key })`. Keyless — `canRead` when
277
+ declared, else allowed (a subject exists; the handler asks only then). `principal` is what
278
+ the SSE auth config's `resolvePrincipal` returned.
279
+ - `filter`: every key field of the frame equals the query's, and a frame carrying `subject`
280
+ reaches only that subject.
281
+
282
+ `canRead` runs once per connection. A membership that ends while the connection is open is
283
+ the app's `revoke` call — nothing re-evaluates it.
284
+
285
+ **State events require an authenticated stream** (`auth: { enabled: true }` in `.events()`).
286
+ Without auth a connection has no subject, the handler never asks `canSubscribe`, and so
287
+ `canRead` would be skipped; the derived `filter` therefore refuses every connection without a
288
+ subject, and no state frame is delivered on such a stream.
289
+
290
+ ## `grant` / `revoke`
291
+
292
+ ```typescript
293
+ await runtime.revoke({ subject: userId }); // membership ended
294
+ await runtime.grant({ subject: userId, key: { workspaceId } }); // membership began
295
+ ```
296
+
297
+ `grant` opens exactly the granted key and does not consult `canRead` — it is the app's
298
+ statement that the subject may now read it. On a keyed state it calls the derived event's
299
+ `grant(subject, { query: key })`, so only the subject's connections whose connect query
300
+ declared that key are activated; a tab of the same subject on another key — one `canRead`
301
+ refused — stays shut. Then it reads the current value for that subject and key and sends it as
302
+ one frame, so the client has the value at once. `key` is required on a keyed state (a type
303
+ error, and a refusal naming the state at runtime); a keyless state takes `{ subject }`.
304
+
305
+ The key is checked against `.key()`: an empty or partial key (or a non-string field) rejects
306
+ naming the state and the field, since it would match every connection of the subject. A field
307
+ `.key()` does not declare is dropped, never matched on. `revoke({ subject, key })` checks the
308
+ same way.
309
+
310
+ `revoke({ subject, key })` deactivates the event on the subject's connections that declared
311
+ `key`; `revoke({ subject })` without a key reaches every connection of the subject, whatever
312
+ key it declared. Each receives `subscription.revoked`.
313
+
314
+ Both reach every pod through the cache transport, which applies the same key rule. A `read()`
315
+ that throws, or returns an undeclared result, in `grant` rejects the call and sends nothing
316
+ (the grant itself is already applied). Across pods the grant's control message and its frame
317
+ travel on separate channels, so a tab on another pod may still be denied when the frame arrives
318
+ and drop it; the next signal brings it up to date.
319
+
320
+ ---
321
+
322
+ ## `at`
323
+
324
+ `at` is `new Date().toISOString()` taken **before** `read()` starts. Every response and frame
325
+ carries the `at` of the read that produced it, and a snapshot carries one `at` for all its
326
+ states. A client applies a value only when its `at` is not older than the one it holds.
327
+
328
+ `at` is wall-clock: across pods it is as good as their clocks, typically within a few
329
+ milliseconds of each other. Two values with the same `at` are resolved as "same value, no
330
+ change" by the client (implemented in the client half). There is no version counter.
331
+
332
+ ## Contract
333
+
334
+ `.contract({ since, auth?, requiresSession?, deprecatedIn?, removedIn? })` publishes, in
335
+ `contracts/current.json`:
336
+
337
+ - the read operation, response `Type.Object({ at: Type.String(), value, data })` (`data` when declared),
338
+ key fields as the request query;
339
+ - the write operation, request body = the input schema, the same response, and its own
340
+ `since` / `deprecatedIn` / `removedIn` from `.write(…, options)` falling back field by field
341
+ to the state's;
342
+ - the SSE event `state.<id>.changed` with `since` / `deprecatedIn` / `removedIn`.
343
+
344
+ A state without `.contract()` appears nowhere, like a route without one. The snapshot route is
345
+ not contracted, its `manifest` included. A `value` literal removed later is `response.type-changed` on the read
346
+ operation and `event.payload.type-changed` on the event, as any route and event.
347
+
348
+ ---
349
+
350
+ ## Browser
351
+
352
+ `@spfn/core/state/client` is the browser side of a state router: it calls the derived read,
353
+ write and snapshot routes, keeps one SSE stream open for every state, and decides per
354
+ `(id, key)` which of a snapshot, a frame, a read or a write answer is current.
355
+ `@spfn/core/state/react` puts one state into a component. The router is known **by type
356
+ only** — `import type { states }` — so no server code reaches the browser bundle;
357
+ `@spfn/core/state/client` imports nothing from `@spfn/core/state` at runtime.
358
+
359
+ ```typescript
360
+ // src/client/state.ts
361
+ import { createStateClient } from '@spfn/core/state/client';
362
+ import { createAuthSSEClient } from '@spfn/core/event/sse/client';
363
+ import type { states } from '@/server/states'; // type only
364
+
365
+ export const state = createStateClient<typeof states>({
366
+ sse: createAuthSSEClient(), // the state client's own
367
+ api: { baseUrl: '/api/rpc' }, // passed to createApi
368
+ });
369
+ ```
370
+
371
+ ```tsx
372
+ 'use client';
373
+ import { useServerState } from '@spfn/core/state/react';
374
+ import { state } from '@/client/state';
375
+
376
+ function Shell({ workspaceId }: { workspaceId: string })
377
+ {
378
+ const consent = useServerState(state, 'consent'); // keyless
379
+ const runtime = useServerState(state, 'runtime', { workspaceId }); // keyed
380
+
381
+ if (consent.status === 'loading' || runtime.status === 'loading')
382
+ {
383
+ return <Spinner />;
384
+ }
385
+
386
+ return consent.value === 'pending'
387
+ ? <Terms onAgree={marketing => consent.write({ termsVersion: '2026-10', marketing })} />
388
+ : <Workspace runtime={runtime.value} />;
389
+ }
390
+ ```
391
+
392
+ ### The manifest
393
+
394
+ A type cannot be read at runtime, and the client needs three facts the router type carries:
395
+ every state id (the stream requests every state event), each keyed state's key fields (to tell
396
+ which key a snapshot entry belongs to) and which states have a write. The snapshot route
397
+ answers them as `manifest`, so the app declares the router once, on the server.
398
+
399
+ The first `subscribe` — or `get`, `write`, `snapshot` — therefore reads the snapshot **first**:
400
+ the client installs its manifest, then applies its states, then opens the stream with
401
+ `events=` from the manifest, in its order. Until then a `subscribe` waits (it never throws),
402
+ and `current()` is `undefined`; a `subscribe` while that snapshot is in flight is served by it,
403
+ not by a second read. Once the manifest is known, a `subscribe` whose id it does not name, or
404
+ whose key fields differ from the state's, is refused: the error, naming the state and both sets
405
+ of fields, goes to `onError`, and the subscription is dropped without reopening the stream. A
406
+ `write` on a state the manifest marks `write: false` rejects naming the state, before any
407
+ request. A first snapshot that fails goes to `onError` (or rejects the call that needed it).
408
+ While subscriptions wait on it, it is read again every `retryDelay` (default 3000 ms, the SSE
409
+ client's `reconnectDelay`), each failure to `onError`, until it succeeds, `close()` runs, or
410
+ nothing is subscribed; a `get`, `write` or `snapshot` that reads it first serves the waiting
411
+ subscriptions too — whichever call brings the manifest opens the stream. `close()` while it is
412
+ in flight discards its answer, and a `get` or `write` waiting on it rejects: the client was
413
+ closed.
414
+
415
+ ### `createStateClient<typeof states>({ sse, api?, onError?, retryDelay? })`
416
+
417
+ | Member | Behaviour |
418
+ | --- | --- |
419
+ | `get(id, key?)` | `GET` `get<Id>State`, key fields in the query. The answer is applied under the ordering rule and returned |
420
+ | `snapshot(query?)` | `GET getStates`, by default with the stream's query. Each state in the answer is applied, and each subscribed state it omits is marked `'revoked'` (below); the snapshot is returned. A rejected fetch rejects and changes nothing |
421
+ | `subscribe(id, key?, listener)` | Registers the listener for `(id, key)` and returns its unsubscribe (idempotent). The client's first subscriber reads the snapshot, then opens the stream (below) |
422
+ | `write(id, input, key?)` | `put<Id>State` with the input as the body, key fields in the query. The answer is applied at once — before the frame the write also sends — and returned. Typed only for a state with a write, and requires the key on a keyed one |
423
+ | `current(id, key?)` | Synchronous: `{ at, value, data?, status }`, `{ status: 'revoked' }` for a state revoked before any value arrived, or `undefined`. The same frozen object until a change is applied |
424
+ | `close()` | Closes the stream, drops every listener. Idempotent |
425
+
426
+ `onError` receives a failure of something the client ran on its own — the first snapshot, the
427
+ snapshot after the stream opened, the read after a grant — and a refused `subscribe` (default
428
+ `console.error`). Calls the app makes reject.
429
+
430
+ A listener that throws is logged at warn with the state id and does not stop the others.
431
+
432
+ Give the state client an `SSEClient` of its own: an `SSEClient` holds one subscription, and
433
+ the state client's supersedes any other made on it.
434
+
435
+ ### Ordering
436
+
437
+ Per `(id, key)`, every arrival — a snapshot entry, a frame, a read or a write answer — goes
438
+ through one rule. `at` is the time the server's read started, so a larger `at` is a later value.
439
+
440
+ | Arrival | Result |
441
+ | --- | --- |
442
+ | no current entry, or `at` newer than the current | applied, listeners notified |
443
+ | `at` equal to the current | one read stamps one `at`, so this is the same value: applied and notified only when `value` or `data` differ (deep-equal) or the entry is `'revoked'` |
444
+ | `at` older than the current | dropped |
445
+ | a snapshot older than one state's entry | that state keeps its entry; the others take the snapshot |
446
+ | a write answer | applied like a frame — its own frame, arriving later with the same `at` and value, changes nothing |
447
+ | a frame for a key not subscribed here | dropped (the server already filters by the connect query; this is the second guard) |
448
+
449
+ The ordering rule decides the value; the status is decided apart (next section): an arrival
450
+ on a revoked `(id, key)` supplies its value and leaves it `'revoked'`.
451
+
452
+ An applied change replaces the entry with a new frozen object; nothing else does. That is
453
+ what `useSyncExternalStore` needs: `getSnapshot` returns the same reference while nothing
454
+ changed.
455
+
456
+ ### The stream
457
+
458
+ - **One stream per client**, opened when the first subscriber arrives and closed when the last
459
+ leaves. Subscriptions made in the same task (components mounting together, a StrictMode
460
+ unmount-remount) are batched into one change.
461
+ - **Snapshot first**: the first stream opens after the first snapshot, whose manifest it needs.
462
+ - **Every event requested**: `events=` lists `state.<id>.changed` for every state of the
463
+ manifest, in its order, never only the subscribed ones. The server's `grant` activates only an event the
464
+ connection requested, so a state subscribed later would otherwise be ungrantable.
465
+ - **Keys in the query**: the connect query is the union of the subscribed keys' fields (SSE
466
+ `subscribe({ query })`). A new key value, or the last subscriber of one leaving, closes the
467
+ stream and opens it with the new query.
468
+ - **Snapshot on every open** — the first, a reconnect, a reopen on a key change. A frame sent
469
+ while no stream was open is lost, whether its key changed or not; the snapshot read after
470
+ the open covers that gap. (It runs on the stream's `open`, not at `onReconnect`: a snapshot
471
+ read before the new stream is live would leave the same gap.)
472
+ - **One value per key field per connection.** A connect query carries one `workspaceId`; when
473
+ two subscribed keys disagree on a field, the most recently subscribed key is carried. A key
474
+ the stream does not carry is read once (`get`) when the stream opens and receives no frames
475
+ until it is carried again. A screen that must follow two workspaces live uses a second
476
+ state client.
477
+
478
+ ### `'revoked'` — the server does not serve this to you
479
+
480
+ One status says the server stopped serving a `(id, key)` to this subject, however the client
481
+ learned it. The mark is kept per `(id, key)` apart from the value, so it holds even when no
482
+ value has arrived yet.
483
+
484
+ | Arrival | Client |
485
+ | --- | --- |
486
+ | `subscription.revoked` for `state.<id>.changed` | the entry of `id` for **the key the connection carries** (keyless: its one entry) gets `status: 'revoked'`, value kept, listeners notified. The server scopes a revoke by the connect query, so a shadowed key of the same state is untouched |
487
+ | a snapshot that omits a subscribed state — keyless, or keyed with its key in the query | `'revoked'`, value kept if one exists, listeners notified. This is also a state denied at connect (`canRead` false, absent from the snapshot), and a reconnect after access was lost while the stream was down, when no revoke could arrive. A keyed state whose key the query did not carry is not marked |
488
+ | a frame, a read or a snapshot started before the revoke | supplies its value under the ordering rule; the status stays `'revoked'` |
489
+ | `subscription.granted` for it | clears the mark for the carried key and reads it once (`get`); the server also sends a frame, before or after the control frame. Both arrive `'ready'`, and either order ends at the latest value |
490
+ | the snapshot of a connection opened after the revoke, holding the state | clears the mark: that connection's own connect check served it |
491
+ | the read of a shadowed key when a connection opened after the revoke, answered | clears the mark the same way: the read route served it |
492
+ | an answer of such a read older than the entry — a frame or a `write()` answer of the new connection landed first | its value is dropped under the ordering rule, while the mark is still lifted: the lift goes by the connection, not by `at` |
493
+
494
+ Every automatic read is tagged with the connection it was started for, which is how a
495
+ snapshot in flight across a revoke is told from one read after it.
496
+
497
+ ### `useServerState(client, id, key?)`
498
+
499
+ ```typescript
500
+ // → { status: 'loading' | 'ready' | 'revoked'; at?: string; value?: V; data?: D; write?: (input) => Promise<StateFrame> }
501
+ ```
502
+
503
+ - Built on `useSyncExternalStore`: `subscribe` is `client.subscribe(id, key, cb)`,
504
+ `getSnapshot` is `client.current(id, key)`, and the server snapshot is `undefined` — a
505
+ server render is `'loading'` and opens nothing.
506
+ - The key is compared by its fields (stable-stringified), so `{ workspaceId }` written inline
507
+ does not resubscribe on every render; another `workspaceId` unsubscribes and subscribes. A
508
+ key never seen is `'loading'` until it has an entry; a key seen before shows its cached
509
+ entry as `'ready'` until the reopen snapshot lands (entries are not evicted).
510
+ - `write` is typed only for a state with a write, bound to the hook's key. At runtime it is on
511
+ every result — the type decides, so no render waits on the manifest — and on a state
512
+ without a write it rejects naming the state.
513
+ - `react` (`^18 || ^19`) is an **optional peer** of `@spfn/core`: only `@spfn/core/state/react`
514
+ imports it. `@spfn/core/state/client` is framework-neutral.
515
+
516
+ A page's first paint still comes from a server component reading the state's route with the
517
+ app's `api.` client; the hook takes over in the browser.
518
+
519
+ ### Types
520
+
521
+ From `@spfn/core/state/client`: `createStateClient`, `StateClient<TStates>`,
522
+ `StateClientConfig`, `StateFrame<V, D>`, `StateEntry<V, D>` (a frame plus `status`, or
523
+ `{ status: 'revoked' }` alone), `StateListener`, `StateId`, `StateKeyArgs`, `WritableStateId`,
524
+ `StateCatalog`, `StateFrameOf`, `InferStateData`, and — re-exported type-only from the server
525
+ module — `InferStateValue`, `InferStateKey`, `InferStateInput`. From `@spfn/core/state/react`:
526
+ `useServerState`, `ServerState<TStates, Id>`.
527
+
528
+ ---
529
+
530
+ ## Out of scope
531
+
532
+ - Browser-only state (an open panel, a draft), session and network state.
533
+ - Optimistic updates: the client applies what the server read, never a guess.
534
+ - In the browser client: optimistic updates, offline queueing of writes, more than one SSE
535
+ connection per client, WebSocket, and Next.js server components (a server component reads
536
+ the route with the app's `api.` client as any other initial data).
537
+ - De-duplicating `read()` across subscribers of a per-subject keyed state (each subject has
538
+ its own value; a shared key is read once).
539
+ - A route-level "refuse until state X is Y" gate.