@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,144 @@
1
+ import { TSchema, Static } from '@sinclair/typebox';
2
+ import { SSEClient } from '@spfn/core/event/sse/client';
3
+ import { ApiConfig } from '@spfn/core/nextjs';
4
+ import { StateRouter, StatesSnapshot } from '@spfn/core/state';
5
+ export { InferStateInput, InferStateKey, InferStateValue } from '@spfn/core/state';
6
+
7
+ /**
8
+ * State Client Types
9
+ *
10
+ * Everything the browser side knows about a state router is its type,
11
+ * `typeof states`, imported type-only. These types turn it into the ids, keys,
12
+ * values and write inputs the client and the hook accept. Nothing here is
13
+ * runtime: the client bundle never contains server code.
14
+ */
15
+
16
+ /** Any state router, as `typeof states`. */
17
+ type AnyStateRouter = StateRouter<any>;
18
+ type StateOf<TStates extends AnyStateRouter> = TStates['states'][keyof TStates['states']];
19
+ type Schema<T> = T extends TSchema ? Static<T> : undefined;
20
+ /**
21
+ * What the client needs of each state, computed once per router: key, value,
22
+ * data and write input by id. Every signature below indexes it, rather than
23
+ * re-deriving a state's shape per argument.
24
+ */
25
+ type StateCatalog<TStates extends AnyStateRouter> = {
26
+ [S in StateOf<TStates> as S['id']]: {
27
+ key: Schema<S['_types']['key']>;
28
+ value: Schema<S['_types']['value']>;
29
+ data: Schema<S['_types']['data']>;
30
+ input: S['_types']['input'] extends TSchema ? Static<S['_types']['input']> : never;
31
+ };
32
+ };
33
+ /** The ids of a router's states. */
34
+ type StateId<TStates extends AnyStateRouter> = keyof StateCatalog<TStates> & string;
35
+ /** The data type of state `Id`, `undefined` when it declares no `.data()`. */
36
+ type InferStateData<TStates extends AnyStateRouter, Id extends StateId<TStates>> = StateCatalog<TStates>[Id]['data'];
37
+ /** The ids of the states that declare a `.write()`. */
38
+ type WritableStateId<TStates extends AnyStateRouter> = {
39
+ [Id in StateId<TStates>]: [StateCatalog<TStates>[Id]['input']] extends [never] ? never : Id;
40
+ }[StateId<TStates>];
41
+ /** The key argument of state `Id`: one key object when keyed, none when keyless. */
42
+ type StateKeyArgs<TStates extends AnyStateRouter, Id extends StateId<TStates>> = [
43
+ StateCatalog<TStates>[Id]['key']
44
+ ] extends [undefined] ? [] : [key: StateCatalog<TStates>[Id]['key']];
45
+ /** The frame type of state `Id`. */
46
+ type StateFrameOf<TStates extends AnyStateRouter, Id extends StateId<TStates>> = StateFrame<StateCatalog<TStates>[Id]['value'], StateCatalog<TStates>[Id]['data']>;
47
+ /** A value as a read, a write or the SSE event answers it, stamped with the `at` of its read. */
48
+ interface StateFrame<V = unknown, D = unknown> {
49
+ at: string;
50
+ value: V;
51
+ data?: D;
52
+ }
53
+ /**
54
+ * What the client holds for one `(id, key)`: the latest frame and whether the
55
+ * server still serves it. A state the server stopped serving before any value
56
+ * arrived is `{ status: 'revoked' }` alone.
57
+ */
58
+ type StateEntry<V = unknown, D = unknown> = Readonly<StateFrame<V, D> & {
59
+ status: 'ready' | 'revoked';
60
+ }> | Readonly<{
61
+ at?: undefined;
62
+ value?: undefined;
63
+ data?: undefined;
64
+ status: 'revoked';
65
+ }>;
66
+ /** Called after the entry of a subscribed `(id, key)` changed. */
67
+ type StateListener = () => void;
68
+ interface StateClientConfig {
69
+ /**
70
+ * The SSE client the stream is opened on — `createAuthSSEClient()` for an
71
+ * authenticated app. Give the state client its own: an `SSEClient` holds
72
+ * one subscription, and the state client's supersedes any other on it.
73
+ */
74
+ sse: SSEClient<any>;
75
+ /** Passed to `createApi` for the read, write and snapshot routes. */
76
+ api?: ApiConfig;
77
+ /**
78
+ * Something the client ran on its own failed: a snapshot (the first, or the
79
+ * one after a stream opened), the read after a grant, or a `subscribe` the
80
+ * manifest refuses. Calls the app makes reject instead.
81
+ * @default console.error
82
+ */
83
+ onError?: (error: unknown) => void;
84
+ /**
85
+ * Milliseconds before a failed first snapshot is read again, while
86
+ * subscriptions wait on it — the SSE client's `reconnectDelay` for a
87
+ * stream that does not exist yet.
88
+ * @default 3000
89
+ */
90
+ retryDelay?: number;
91
+ }
92
+ /**
93
+ * The browser side of a state router: one store per `(id, key)`, one SSE
94
+ * stream for the whole client.
95
+ */
96
+ interface StateClient<TStates extends AnyStateRouter> {
97
+ /** Read one state; the answer is applied to the store and returned. */
98
+ get<Id extends StateId<TStates>>(id: Id, ...key: StateKeyArgs<TStates, Id>): Promise<StateFrameOf<TStates, Id>>;
99
+ /** Read every state the query names a key for, and the manifest; each entry is applied and the snapshot returned. */
100
+ snapshot(query?: Record<string, string>): Promise<StatesSnapshot<TStates['states']>>;
101
+ /**
102
+ * Watch one `(id, key)`. The first subscriber reads the snapshot, then opens
103
+ * the stream. A key whose fields are not the state's goes to `onError` once
104
+ * the manifest is known. Returns the unsubscribe.
105
+ */
106
+ subscribe<Id extends StateId<TStates>>(id: Id, ...args: [...key: StateKeyArgs<TStates, Id>, listener: StateListener]): () => void;
107
+ /** Write a state through its write route; the answer is applied at once and returned. */
108
+ write<Id extends WritableStateId<TStates>>(id: Id, input: StateCatalog<TStates>[Id]['input'], ...key: StateKeyArgs<TStates, Id>): Promise<StateFrameOf<TStates, Id>>;
109
+ /** The entry held for `(id, key)`, the same object until it changes. */
110
+ current<Id extends StateId<TStates>>(id: Id, ...key: StateKeyArgs<TStates, Id>): StateEntry<StateCatalog<TStates>[Id]['value'], StateCatalog<TStates>[Id]['data']> | undefined;
111
+ /** Close the stream and drop every listener. */
112
+ close(): void;
113
+ }
114
+
115
+ /**
116
+ * State Client
117
+ *
118
+ * The browser side of a state router (`@spfn/core/state`): it calls the derived
119
+ * read, write and snapshot routes, keeps one SSE stream open for every state of
120
+ * the router, and orders snapshots against frames per `(id, key)`. It knows the
121
+ * router by type — `typeof states` — and at runtime by the manifest every
122
+ * snapshot carries; it imports no server code.
123
+ *
124
+ * @example
125
+ * ```typescript
126
+ * import { createStateClient } from '@spfn/core/state/client';
127
+ * import { createAuthSSEClient } from '@spfn/core/event/sse/client';
128
+ * import type { states } from '@/server/states';
129
+ *
130
+ * export const state = createStateClient<typeof states>({ sse: createAuthSSEClient() });
131
+ *
132
+ * const stop = state.subscribe('runtime', { workspaceId }, () => render(state.current('runtime', { workspaceId })));
133
+ * ```
134
+ */
135
+
136
+ /**
137
+ * Build the client for `typeof states`. The first subscription (or call)
138
+ * reads the snapshot, whose manifest names every state; the stream then
139
+ * requests every state event — the server's `grant` can only activate an
140
+ * event the connection requested.
141
+ */
142
+ declare function createStateClient<TStates extends AnyStateRouter>(config: StateClientConfig): StateClient<TStates>;
143
+
144
+ export { type AnyStateRouter, type InferStateData, type StateCatalog, type StateClient, type StateClientConfig, type StateEntry, type StateFrame, type StateFrameOf, type StateId, type StateKeyArgs, type StateListener, type WritableStateId, createStateClient };
@@ -0,0 +1,478 @@
1
+ import { createApi } from '@spfn/core/nextjs';
2
+
3
+ // src/state/client.ts
4
+
5
+ // src/state/client-store.ts
6
+ function stableKey(key) {
7
+ if (!key) {
8
+ return "";
9
+ }
10
+ return JSON.stringify(Object.keys(key).sort().map((field) => [field, key[field]]));
11
+ }
12
+ function sameJson(a, b) {
13
+ if (a === b) {
14
+ return true;
15
+ }
16
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null || Array.isArray(a) !== Array.isArray(b)) {
17
+ return false;
18
+ }
19
+ const aKeys = Object.keys(a);
20
+ const bRecord = b;
21
+ return aKeys.length === Object.keys(b).length && aKeys.every((field) => field in bRecord && sameJson(a[field], bRecord[field]));
22
+ }
23
+ function supersedes(current, arrival) {
24
+ if (current?.at === void 0 || arrival.at > current.at) {
25
+ return true;
26
+ }
27
+ if (arrival.at < current.at) {
28
+ return false;
29
+ }
30
+ return !sameJson(current.value, arrival.value) || !sameJson(current.data, arrival.data);
31
+ }
32
+ function entryOf(frame, status) {
33
+ const { at, value, data } = frame;
34
+ return Object.freeze(data === void 0 ? { at, value, status } : { at, value, data, status });
35
+ }
36
+ var StateStore = class {
37
+ entries = /* @__PURE__ */ new Map();
38
+ listeners = /* @__PURE__ */ new Map();
39
+ /**
40
+ * The slots the server stopped serving, with the generation of the
41
+ * connection that said so. Kept apart from the entries: a revoke can
42
+ * arrive before the slot has a value, and an arrival afterwards supplies
43
+ * the value without clearing the mark.
44
+ */
45
+ revoked = /* @__PURE__ */ new Map();
46
+ /** The store slot of `(id, key)`. */
47
+ static slot(id, keyText) {
48
+ return `${id}\0${keyText}`;
49
+ }
50
+ current(slot) {
51
+ return this.entries.get(slot);
52
+ }
53
+ /**
54
+ * Apply an arrival: the value under the ordering rule, the status from the
55
+ * revoked mark. Listeners hear only an applied change.
56
+ */
57
+ apply(slot, frame) {
58
+ const current = this.entries.get(slot);
59
+ const status = this.revoked.has(slot) ? "revoked" : "ready";
60
+ if (supersedes(current, frame)) {
61
+ this.replace(slot, entryOf(frame, status));
62
+ } else if (current.status !== status) {
63
+ this.replace(slot, entryOf(current, status));
64
+ }
65
+ }
66
+ /** Mark `slot` revoked by the connection of `generation`; its value, if any, is kept. */
67
+ revoke(slot, generation) {
68
+ this.revoked.set(slot, generation);
69
+ const entry = this.entries.get(slot);
70
+ if (entry?.status !== "revoked") {
71
+ this.replace(slot, Object.freeze(entry ? { ...entry, status: "revoked" } : { status: "revoked" }));
72
+ }
73
+ }
74
+ /** The generation of the connection that revoked `slot`, or `undefined` while it is served. */
75
+ revokedBy(slot) {
76
+ return this.revoked.get(slot);
77
+ }
78
+ /** Clear the revoked mark; the next arrival for `slot` is `'ready'`. */
79
+ allow(slot) {
80
+ this.revoked.delete(slot);
81
+ }
82
+ listen(slot, listener) {
83
+ const set = this.listeners.get(slot) ?? /* @__PURE__ */ new Set();
84
+ set.add(listener);
85
+ this.listeners.set(slot, set);
86
+ }
87
+ unlisten(slot, listener) {
88
+ const set = this.listeners.get(slot);
89
+ if (listener) {
90
+ set?.delete(listener);
91
+ }
92
+ if (!listener || set?.size === 0) {
93
+ this.listeners.delete(slot);
94
+ }
95
+ }
96
+ clearListeners() {
97
+ this.listeners.clear();
98
+ }
99
+ /** Replace the entry and notify; a throwing listener is logged and does not stop the others. */
100
+ replace(slot, entry) {
101
+ this.entries.set(slot, entry);
102
+ for (const listener of [...this.listeners.get(slot) ?? []]) {
103
+ notify(slot, listener);
104
+ }
105
+ }
106
+ };
107
+ function notify(slot, listener) {
108
+ try {
109
+ listener();
110
+ } catch (error) {
111
+ console.warn(`[state] A listener of state "${slot.split("\0")[0]}" threw:`, error);
112
+ }
113
+ }
114
+
115
+ // src/state/client.ts
116
+ function routeName(method, id) {
117
+ return `${method}${id[0].toUpperCase()}${id.slice(1)}State`;
118
+ }
119
+ function carries(query, key) {
120
+ return Object.entries(key).every(([field, value]) => query[field] === value);
121
+ }
122
+ function sortedFields(fields) {
123
+ return [...fields].sort().join(", ");
124
+ }
125
+ function createStateClient(config) {
126
+ return new BrowserStateClient(config);
127
+ }
128
+ var BrowserStateClient = class {
129
+ constructor(config) {
130
+ this.config = config;
131
+ this.api = createApi(config.api);
132
+ this.reportError = config.onError ?? ((error) => console.error("[state] A refresh failed:", error));
133
+ }
134
+ store = new StateStore();
135
+ api;
136
+ watched = /* @__PURE__ */ new Map();
137
+ reportError;
138
+ manifest;
139
+ manifestRead;
140
+ stream;
141
+ syncQueued = false;
142
+ /** The lifetime whose subscriptions wait on the first snapshot — its read in flight, or its retry timer set. */
143
+ waitingLifetime;
144
+ retryTimer;
145
+ /** Bumped by `close()`: a snapshot started before it is discarded. */
146
+ lifetime = 0;
147
+ /** Bumped on every connection open; tags the snapshot read for it. */
148
+ generation = 0;
149
+ /** Bumped on every automatic read and every grant, to tell which came first. */
150
+ clock = 0;
151
+ /** The clock at the latest grant of each slot. */
152
+ grants = /* @__PURE__ */ new Map();
153
+ async get(id, key) {
154
+ await this.requireManifest();
155
+ const frame = await this.api[routeName("get", id)].call(key ? { query: key } : {});
156
+ this.store.apply(this.slot(id, key), frame);
157
+ return frame;
158
+ }
159
+ async write(id, input, key) {
160
+ if (!(await this.requireManifest())[id]?.write) {
161
+ throw new Error(`State client: state "${id}" declares no .write(), so it has no write route.`);
162
+ }
163
+ const frame = await this.api[routeName("put", id)].call({ body: input, ...key ? { query: key } : {} });
164
+ this.store.apply(this.slot(id, key), frame);
165
+ return frame;
166
+ }
167
+ snapshot(query = this.streamQuery()) {
168
+ return this.readSnapshot(query, this.tag());
169
+ }
170
+ subscribe(id, ...args) {
171
+ const listener = args[args.length - 1];
172
+ const key = args.length === 2 ? args[0] : void 0;
173
+ const refusal = this.manifest && this.refusal(id, key);
174
+ if (refusal) {
175
+ this.reportError(refusal);
176
+ return () => void 0;
177
+ }
178
+ const notify2 = () => listener();
179
+ const slot = this.slot(id, key);
180
+ this.store.listen(slot, notify2);
181
+ this.watch(slot, id, key, 1);
182
+ let live = true;
183
+ return () => {
184
+ if (live) {
185
+ live = false;
186
+ this.store.unlisten(slot, notify2);
187
+ this.watch(slot, id, key, -1);
188
+ }
189
+ };
190
+ }
191
+ current(id, key) {
192
+ return this.store.current(this.slot(id, key));
193
+ }
194
+ close() {
195
+ this.lifetime++;
196
+ clearTimeout(this.retryTimer);
197
+ this.retryTimer = void 0;
198
+ this.closeStream();
199
+ this.watched.clear();
200
+ this.store.clearListeners();
201
+ }
202
+ slot(id, key) {
203
+ return StateStore.slot(id, stableKey(key));
204
+ }
205
+ tag() {
206
+ return { generation: this.generation, tick: ++this.clock };
207
+ }
208
+ /** The key of state `id` the query names; `undefined` for a keyless state. */
209
+ keyIn(id, query) {
210
+ const fields = this.manifest[id].key;
211
+ return fields.length ? Object.fromEntries(fields.map((field) => [field, query[field]])) : void 0;
212
+ }
213
+ /** Why the manifest refuses `subscribe(id, key)` — an unknown id, or key fields not the state's. */
214
+ refusal(id, key) {
215
+ const state = this.manifest[id];
216
+ if (!state) {
217
+ return new Error(`State client: the server's manifest has no state "${id}".`);
218
+ }
219
+ const expected = sortedFields(state.key);
220
+ const given = sortedFields(Object.keys(key ?? {}));
221
+ return expected === given ? void 0 : new Error(`State client: state "${id}" takes the key fields [${expected}], given [${given}].`);
222
+ }
223
+ /** The first snapshot, read once however many callers wait for it. */
224
+ ensureManifest() {
225
+ if (this.manifest) {
226
+ return Promise.resolve();
227
+ }
228
+ this.manifestRead ??= this.snapshot().then(() => void 0).finally(() => {
229
+ this.manifestRead = void 0;
230
+ });
231
+ return this.manifestRead;
232
+ }
233
+ /** The manifest for a call the app made; one whose wait outlived `close()` is refused. */
234
+ async requireManifest() {
235
+ await this.ensureManifest();
236
+ if (!this.manifest) {
237
+ throw new Error("State client: the client was closed while the first snapshot was in flight.");
238
+ }
239
+ return this.manifest;
240
+ }
241
+ /**
242
+ * Read the snapshot and apply it: the manifest first — `keyIn` and the
243
+ * key checks need it — then each state present, then each watched state
244
+ * it omits. A snapshot that resolves after `close()` is discarded.
245
+ */
246
+ async readSnapshot(query, tag) {
247
+ const lifetime = this.lifetime;
248
+ const snapshot = await this.api.getStates.call({ query });
249
+ if (lifetime === this.lifetime) {
250
+ this.installManifest(snapshot.manifest);
251
+ this.applyPresent(snapshot, query, tag);
252
+ this.applyOmitted(snapshot, query, tag);
253
+ }
254
+ return snapshot;
255
+ }
256
+ /**
257
+ * The manifest is static; the first one stays. Subscriptions made before
258
+ * it are checked now, and the stream opens for those it accepts —
259
+ * whichever call (`subscribe`, `get`, `write`, `snapshot`) brought it.
260
+ */
261
+ installManifest(manifest) {
262
+ if (this.manifest) {
263
+ return;
264
+ }
265
+ this.manifest = manifest;
266
+ for (const [slot, watch] of this.watched) {
267
+ const refusal = this.refusal(watch.id, watch.key);
268
+ if (refusal) {
269
+ this.watched.delete(slot);
270
+ this.store.unlisten(slot);
271
+ this.reportError(refusal);
272
+ }
273
+ }
274
+ if (this.watched.size > 0) {
275
+ this.queueSync();
276
+ }
277
+ }
278
+ /**
279
+ * An arrival from a read started for the connection of `tag`: a
280
+ * connection newer than the one that revoked the slot lifts the mark, an
281
+ * older or the same connection leaves `'revoked'`. The lift is by
282
+ * generation alone — a frame or a write answer of the new connection may
283
+ * land first with a newer `at` — and the ordering rule decides only the value.
284
+ */
285
+ serve(slot, frame, tag) {
286
+ if ((this.store.revokedBy(slot) ?? Infinity) < tag.generation) {
287
+ this.store.allow(slot);
288
+ }
289
+ this.store.apply(slot, frame);
290
+ }
291
+ /** A state present is served, under the generation rule of `serve`. */
292
+ applyPresent(snapshot, query, tag) {
293
+ for (const [id, result] of Object.entries(snapshot.states)) {
294
+ this.serve(this.slot(id, this.keyIn(id, query)), { at: snapshot.at, ...result }, tag);
295
+ }
296
+ }
297
+ /**
298
+ * A watched state whose key the query carried (or a keyless one) and that
299
+ * the snapshot omits is not served to this subject: `'revoked'`. Not when
300
+ * a newer connection exists, nor when a grant came after the read started.
301
+ */
302
+ applyOmitted(snapshot, query, tag) {
303
+ if (tag.generation !== this.generation) {
304
+ return;
305
+ }
306
+ for (const [slot, watch] of this.watched) {
307
+ const asked = !watch.key || carries(query, watch.key);
308
+ const grantedSince = (this.grants.get(slot) ?? 0) > tag.tick;
309
+ if (asked && !(watch.id in snapshot.states) && !grantedSince) {
310
+ this.store.revoke(slot, tag.generation);
311
+ }
312
+ }
313
+ }
314
+ watch(slot, id, key, delta) {
315
+ const count = (this.watched.get(slot)?.count ?? 0) + delta;
316
+ if (count > 0) {
317
+ this.watched.set(slot, { id, key, count });
318
+ } else {
319
+ this.watched.delete(slot);
320
+ }
321
+ this.queueSync();
322
+ }
323
+ /**
324
+ * One stream for the client, its query the union of the subscribed keys.
325
+ * Batched to the end of the task, so components mounting together (or a
326
+ * StrictMode unmount-remount) open the stream once.
327
+ */
328
+ queueSync() {
329
+ if (!this.syncQueued) {
330
+ this.syncQueued = true;
331
+ queueMicrotask(() => {
332
+ this.syncQueued = false;
333
+ this.sync();
334
+ });
335
+ }
336
+ }
337
+ /**
338
+ * Until the manifest is known, subscriptions wait for the first snapshot;
339
+ * the stream opens after it, never before — its `events=` comes from it.
340
+ */
341
+ sync() {
342
+ if (this.watched.size === 0) {
343
+ this.closeStream();
344
+ return;
345
+ }
346
+ if (!this.manifest) {
347
+ this.awaitManifest();
348
+ return;
349
+ }
350
+ const query = this.streamQuery();
351
+ if (this.stream?.text !== stableKey(query)) {
352
+ this.openStream(query);
353
+ }
354
+ }
355
+ /**
356
+ * One waiter per lifetime on the first snapshot. A failure goes to
357
+ * `onError`, and the read is retried after `retryDelay` — the stream that
358
+ * would reconnect on its own does not exist yet. A retry stops on
359
+ * `close()` or when nothing is watched (`sync` closes instead).
360
+ */
361
+ awaitManifest() {
362
+ const lifetime = this.lifetime;
363
+ if (this.waitingLifetime === lifetime) {
364
+ return;
365
+ }
366
+ this.waitingLifetime = lifetime;
367
+ this.ensureManifest().then(
368
+ () => lifetime === this.lifetime && this.resync(),
369
+ (error) => {
370
+ this.reportError(error);
371
+ if (lifetime === this.lifetime) {
372
+ this.retryLater();
373
+ }
374
+ }
375
+ );
376
+ }
377
+ /** The wait is over; `sync` opens the stream, or waits again when a closed lifetime's read was discarded. */
378
+ resync() {
379
+ this.waitingLifetime = void 0;
380
+ this.sync();
381
+ }
382
+ /** Read the first snapshot again after `retryDelay`, as the SSE client reconnects a dropped stream. */
383
+ retryLater() {
384
+ this.retryTimer = setTimeout(() => {
385
+ this.retryTimer = void 0;
386
+ this.resync();
387
+ }, this.config.retryDelay ?? 3e3);
388
+ this.retryTimer.unref?.();
389
+ }
390
+ /**
391
+ * Every subscribed key's fields; one connection carries one value per
392
+ * field, so on a conflict the latest subscribed key wins. The keys it
393
+ * shadows are read once when the stream opens and get no frames.
394
+ */
395
+ streamQuery() {
396
+ return Object.assign({}, ...[...this.watched.values()].map((watch) => watch.key ?? {}));
397
+ }
398
+ /**
399
+ * Open (or reopen) the stream. `events` is every state of the manifest, in
400
+ * its order, never only the subscribed ones: a state subscribed later would
401
+ * otherwise be unrequested, and the server's `grant` cannot activate it.
402
+ */
403
+ openStream(query) {
404
+ this.closeStream();
405
+ const ids = Object.keys(this.manifest);
406
+ const stream = { query, text: stableKey(query), generation: 0, close: () => void 0 };
407
+ stream.close = this.config.sse.subscribe({
408
+ events: ids.map((id) => `state.${id}.changed`),
409
+ handlers: Object.fromEntries(ids.map((id) => [`state.${id}.changed`, (frame) => this.onFrame(id, frame)])),
410
+ query,
411
+ // Every open — the first, a reconnect, a reopen on a key change — re-reads the
412
+ // snapshot. A frame sent while no stream was open is lost, whether its key
413
+ // changed or not; the snapshot read after the open covers that gap.
414
+ onOpen: () => {
415
+ stream.generation = ++this.generation;
416
+ this.refresh(query);
417
+ },
418
+ onSubscriptionChange: (change) => this.onSubscriptionChange(change, stream)
419
+ });
420
+ this.stream = stream;
421
+ }
422
+ closeStream() {
423
+ this.stream?.close();
424
+ this.stream = void 0;
425
+ }
426
+ /** The snapshot for the stream's query, and one read for each subscribed key the query shadows. */
427
+ refresh(query) {
428
+ this.readSnapshot(query, this.tag()).catch(this.reportError);
429
+ for (const watch of this.watched.values()) {
430
+ if (watch.key && !carries(query, watch.key)) {
431
+ this.readShadowed(watch.id, watch.key, this.tag()).catch(this.reportError);
432
+ }
433
+ }
434
+ }
435
+ /**
436
+ * A shadowed key gets no frames, no grant and no snapshot entry; the
437
+ * server answering its own read is the evidence of access instead.
438
+ */
439
+ async readShadowed(id, key, tag) {
440
+ const frame = await this.api[routeName("get", id)].call({ query: key });
441
+ this.serve(this.slot(id, key), frame, tag);
442
+ }
443
+ /** A frame for a key nobody here subscribed is dropped — the server's filter is the first guard, this the second. */
444
+ onFrame(id, frame) {
445
+ const slot = this.slot(id, frame.key);
446
+ if (this.watched.has(slot)) {
447
+ this.store.apply(slot, frame);
448
+ }
449
+ }
450
+ /**
451
+ * A revoke or a grant concerns the key the connection carries — the
452
+ * server scopes both by the connect query — and so does the read after a
453
+ * grant. Revoked: the entry keeps its value, marked `'revoked'`, until a
454
+ * grant. Granted: the mark is cleared and the key read once; the server
455
+ * sends a frame too, in either order, and both arrive `'ready'`.
456
+ */
457
+ onSubscriptionChange(change, stream) {
458
+ const id = /^state\.(.+)\.changed$/.exec(change.event)?.[1];
459
+ if (id === void 0 || !this.manifest[id]) {
460
+ return;
461
+ }
462
+ const key = this.keyIn(id, stream.query);
463
+ const slot = this.slot(id, key);
464
+ if (change.status === "revoked") {
465
+ this.store.revoke(slot, stream.generation);
466
+ return;
467
+ }
468
+ this.grants.set(slot, ++this.clock);
469
+ this.store.allow(slot);
470
+ if (this.watched.has(slot)) {
471
+ this.get(id, key).catch(this.reportError);
472
+ }
473
+ }
474
+ };
475
+
476
+ export { createStateClient };
477
+ //# sourceMappingURL=client.js.map
478
+ //# sourceMappingURL=client.js.map