@lunora/client 1.0.0-alpha.26 → 1.0.0-alpha.261

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.
Files changed (106) hide show
  1. package/README.md +19 -4
  2. package/dist/admin/index.d.mts +609 -0
  3. package/dist/admin/index.d.ts +609 -0
  4. package/dist/admin/index.mjs +1 -0
  5. package/dist/auth/index.d.mts +138 -5
  6. package/dist/auth/index.d.ts +138 -5
  7. package/dist/auth/index.mjs +1 -60
  8. package/dist/index.d.mts +752 -186
  9. package/dist/index.d.ts +752 -186
  10. package/dist/index.mjs +1 -21
  11. package/dist/packem_shared/ADMIN_AUTH_DEFAULT_PAGE_SIZE-V9c3bHU1.mjs +1 -0
  12. package/dist/packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs +1 -0
  13. package/dist/packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs +1 -0
  14. package/dist/packem_shared/LunoraAdminClient-DMK1sZpm.mjs +1 -0
  15. package/dist/packem_shared/LunoraClient-CeaiXMQN.mjs +1 -0
  16. package/dist/packem_shared/OfflineQueue-Ba2qgZK1.mjs +1 -0
  17. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
  18. package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
  19. package/dist/packem_shared/SubscriptionRegistry-BKgQtuh9.mjs +1 -0
  20. package/dist/packem_shared/TabCoordinator-DBuR7Dwv.mjs +1 -0
  21. package/dist/packem_shared/applyDelta-CaudNj2C.mjs +1 -0
  22. package/dist/packem_shared/base64-849R7V-V.mjs +1 -0
  23. package/dist/packem_shared/client-tuning-C10B2KCO.mjs +1 -0
  24. package/dist/packem_shared/client-urls-BHLUjjcG.mjs +1 -0
  25. package/dist/packem_shared/connectLiveStream-BdjsWP1-.mjs +1 -0
  26. package/dist/packem_shared/createAsyncStoragePersistence-6FCvqc6C.mjs +1 -0
  27. package/dist/packem_shared/createAsyncStorageQueryCache-D8NJXPJa.mjs +1 -0
  28. package/dist/packem_shared/createCallRunner-Bwcrfh76.mjs +1 -0
  29. package/dist/packem_shared/createClientQuery-B8Nfj-7o.mjs +1 -0
  30. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  31. package/dist/packem_shared/createInMemoryPersistence-C-IzNVbg.mjs +1 -0
  32. package/dist/packem_shared/createInMemoryQueryCache-DR6AorA2.mjs +1 -0
  33. package/dist/packem_shared/createLocalStore-CsKA0HPB.mjs +1 -0
  34. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  35. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  36. package/dist/packem_shared/createServerClient-CCCSB2eL.mjs +1 -0
  37. package/dist/packem_shared/createSnapshotPrecondition-BXP1NPBW.mjs +1 -0
  38. package/dist/packem_shared/delta-merge-C6OqMEPH.mjs +1 -0
  39. package/dist/packem_shared/deserializePreloaded-CyFK_cv6.mjs +1 -0
  40. package/dist/packem_shared/frame-hint-D-NK691z.mjs +1 -0
  41. package/dist/packem_shared/function-reference.d-Br_hsKje.d.mts +45 -0
  42. package/dist/packem_shared/function-reference.d-Br_hsKje.d.ts +45 -0
  43. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  44. package/dist/packem_shared/httpStream-ChJxN9M1.mjs +7 -0
  45. package/dist/packem_shared/idb-utility-BS7xvou1.mjs +1 -0
  46. package/dist/packem_shared/live-stream-DBKgZlnb.mjs +10 -0
  47. package/dist/packem_shared/liveTopicSubscription-DQtKMFKw.mjs +1 -0
  48. package/dist/packem_shared/local-store-C3bw2MPY.mjs +1 -0
  49. package/dist/packem_shared/lunora-client-Csrg4U0l.mjs +1 -0
  50. package/dist/packem_shared/lunora-client.d-D3G_fsa6.d.mts +4752 -0
  51. package/dist/packem_shared/lunora-client.d-eugqse6z.d.ts +4752 -0
  52. package/dist/packem_shared/lunoraQueryKey-CucWmxnx.mjs +1 -0
  53. package/dist/packem_shared/offline-queue-BEqCPDmw.mjs +1 -0
  54. package/dist/packem_shared/{preload.d-Cqb4Kh2I.d.ts → preload.d-C3esb5ZQ.d.mts} +2 -1
  55. package/dist/packem_shared/{preload.d-CLwoXl3R.d.mts → preload.d-N9jMP9ai.d.ts} +2 -1
  56. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  57. package/dist/packem_shared/setAuthTokenProvider-DhBppDiZ.mjs +1 -0
  58. package/dist/packem_shared/single-blob-store-DpqSxsgi.mjs +1 -0
  59. package/dist/packem_shared/snapshot-precondition-BEtcSbWr.mjs +1 -0
  60. package/dist/packem_shared/stream-idle-C7CsIT_m.mjs +1 -0
  61. package/dist/packem_shared/wire-errors-BDckSTKZ.mjs +1 -0
  62. package/dist/pagination/index.mjs +1 -61
  63. package/dist/query/index.d.mts +143 -4
  64. package/dist/query/index.d.ts +143 -4
  65. package/dist/query/index.mjs +1 -1
  66. package/dist/service.d.mts +49 -0
  67. package/dist/service.d.ts +49 -0
  68. package/dist/service.mjs +1 -0
  69. package/dist/ssr/index.d.mts +45 -16
  70. package/dist/ssr/index.d.ts +45 -16
  71. package/dist/ssr/index.mjs +1 -4
  72. package/dist/upload.d.mts +49 -0
  73. package/dist/upload.d.ts +49 -0
  74. package/dist/upload.mjs +1 -0
  75. package/package.json +19 -2
  76. package/dist/packem_shared/CONFLICT_ERROR_CODE-B8gQ8tyU.mjs +0 -33
  77. package/dist/packem_shared/ClientServiceWorker-C3PAFwy0.mjs +0 -100
  78. package/dist/packem_shared/DEFAULT_MAX_BUFFER-7hFnzNk9.mjs +0 -110
  79. package/dist/packem_shared/LunoraClient-DKATLGHY.mjs +0 -3631
  80. package/dist/packem_shared/OfflineQueue-BgarnAub.mjs +0 -1
  81. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  82. package/dist/packem_shared/SubscriptionRegistry-CxS_Inha.mjs +0 -31
  83. package/dist/packem_shared/TabCoordinator-D_5oNTTt.mjs +0 -258
  84. package/dist/packem_shared/applyDelta-CRKZ1PBt.mjs +0 -81
  85. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  86. package/dist/packem_shared/createClientQuery-dJZg1ohm.mjs +0 -80
  87. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  88. package/dist/packem_shared/createInMemoryPersistence-DZ2VHWgm.mjs +0 -79
  89. package/dist/packem_shared/createInMemoryQueryCache-DiaGZkA2.mjs +0 -112
  90. package/dist/packem_shared/createLocalStore-BtqUmOQA.mjs +0 -2
  91. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  92. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  93. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  94. package/dist/packem_shared/createReply-lI4tVS2w.mjs +0 -36
  95. package/dist/packem_shared/createServerClient-Bp2r9tcB.mjs +0 -11
  96. package/dist/packem_shared/createSnapshotPrecondition-CxQ1T4ZP.mjs +0 -18
  97. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  98. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  99. package/dist/packem_shared/httpStream-DIdL8NEw.mjs +0 -168
  100. package/dist/packem_shared/idb-utility-DrSVX43Q.mjs +0 -48
  101. package/dist/packem_shared/local-store-DIq-UWfD.mjs +0 -106
  102. package/dist/packem_shared/lunora-client.d-B1iZb2Ph.d.mts +0 -2845
  103. package/dist/packem_shared/lunora-client.d-B1iZb2Ph.d.ts +0 -2845
  104. package/dist/packem_shared/offline-queue-N-1JvYb4.mjs +0 -211
  105. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  106. package/dist/packem_shared/wire-key-Djie6aaR.mjs +0 -266
@@ -0,0 +1,4752 @@
1
+ import { LunoraErrorCodeInput, LunoraErrorCode, LunoraError } from '@lunora/errors';
2
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./function-reference.d-Br_hsKje.js";
3
+ /**
4
+ * The two client operations an admin call needs. The client supplies them as late-bound calls.
5
+ *
6
+ * The module signatures take their types from `LunoraAdminClient` via `Parameters` and `ReturnType`.
7
+ * Every class method those types read must keep an explicit return annotation: without one the
8
+ * derived type is circular, and it silently widens if the method is overloaded later.
9
+ */
10
+ interface AdminHost {
11
+ adminFetch: (path: string, method: "DELETE" | "GET" | "POST" | "PUT", payload?: ArrayBuffer | Blob | Record<string, unknown>, contentType?: string) => Promise<unknown>;
12
+ assertOpen: () => void;
13
+ }
14
+ /**
15
+ * The `onlineOnly` option a call to the function reference `F` may take. A
16
+ * function with a `v.sensitive` argument is emitted as `… & { readonly sensitive:
17
+ * true }`, and is always online-only: its arguments never reach the offline queue,
18
+ * the outbox or a persistence adapter. For it the option may be omitted or `true`;
19
+ * `false` is a type error. Every other reference is unchanged.
20
+ */
21
+ type OnlineOnlyOption<F> = F extends {
22
+ readonly sensitive: true;
23
+ } ? {
24
+ onlineOnly?: true;
25
+ } : unknown;
26
+ /**
27
+ * Typed reference to an HTTP-SSE stream route (`httpRoute.<verb>(path).stream()`)
28
+ * emitted by `@lunora/codegen` as `httpStreams.<namespace>.<name>`.
29
+ *
30
+ * Distinct from {@link FunctionReference}: this is the **HTTP-SSE route stream**
31
+ * (opened with `fetch` + `ReadableStream` against the route's own URL), not the
32
+ * WS procedure stream (`kind: "stream"`). At runtime it carries the HTTP verb
33
+ * and the route path; the phantom marker carries the chunk / searchParams /
34
+ * params types so `httpStream` (and the framework hooks over it) infer the
35
+ * chunk type end-to-end.
36
+ */
37
+ /**
38
+ * A typed reference to a `defineRoom` room, as the generated `rooms` object carries
39
+ * it. At runtime it is the room's name; the phantom marker carries its message type,
40
+ * so `connectRoom(rooms.chat, …)` types `onMessage` and `send` from the room itself.
41
+ */
42
+ interface RoomRef<Message = unknown> {
43
+ /**
44
+ * Phantom marker carrying the room's message type for inference. Never present
45
+ * at runtime.
46
+ */
47
+ readonly __lunoraRoomMessage?: Message;
48
+ /** The room's name, which the shard routes on (`room:<name>`). */
49
+ readonly name: string;
50
+ }
51
+ interface HttpStreamRef<Chunk = unknown, SearchParams = unknown, Params = unknown> {
52
+ /**
53
+ * Phantom marker carrying the `Chunk`/`SearchParams`/`Params` type
54
+ * parameters for inference. Never present at runtime; declared in a
55
+ * covariant (output) position so a concrete reference stays assignable to
56
+ * a widened one.
57
+ */
58
+ readonly __lunoraHttpStream?: {
59
+ chunk: Chunk;
60
+ params: Params;
61
+ searchParams: SearchParams;
62
+ };
63
+ /** HTTP verb the route binds to (uppercased), e.g. `"GET"`. */
64
+ readonly method: string;
65
+ /** The route path as declared, e.g. `/api/tokens/:id` — `:name` segments are filled from `params`. */
66
+ readonly path: string;
67
+ }
68
+ /**
69
+ * The call-side args of an HTTP-SSE stream route: `:name` path params plus URL query params.
70
+ */
71
+ interface HttpStreamCallArgs<SearchParams = unknown, Params = unknown> {
72
+ /** Values for the route path's `:name` segments. */
73
+ params?: Params;
74
+ /** URL query params, appended to the request URL (undefined entries are skipped). */
75
+ searchParams?: SearchParams;
76
+ }
77
+ /**
78
+ * Extract the chunk type from a {@link HttpStreamRef}.
79
+ */
80
+ type HttpStreamChunkOf<R> = R extends HttpStreamRef<infer Chunk, infer _S, infer _P> ? Chunk : never;
81
+ /**
82
+ * Extract the call-side args type from a {@link HttpStreamRef}.
83
+ */
84
+ type HttpStreamArgsOf<R> = R extends HttpStreamRef<infer _C, infer S, infer P> ? HttpStreamCallArgs<S, P> : never;
85
+ type Unsubscribe = () => void;
86
+ /**
87
+ * Serializable result of `preloadQuery`. Produced on the server during SSR,
88
+ * embedded in the rendered HTML, then handed to `usePreloadedQuery` on the
89
+ * client so the first render shows the server value with no loading flash
90
+ * before a live subscription attaches. Every field survives `JSON.stringify`.
91
+ */
92
+ interface Preloaded<T = unknown> {
93
+ readonly __lunoraPreloaded: true;
94
+ readonly args: Record<string, unknown>;
95
+ readonly functionPath: string;
96
+ readonly shardKey?: string;
97
+ readonly value: T;
98
+ }
99
+ /**
100
+ * Pluggable storage for the `x-d1-bookmark` value used to provide
101
+ * read-your-writes between a mutation and subsequent queries.
102
+ */
103
+ interface BookmarkStorage {
104
+ get: () => string | null;
105
+ set: (value: string | null) => void;
106
+ }
107
+ interface ReconnectOptions {
108
+ initialDelayMs?: number;
109
+ jitter?: boolean;
110
+ maxDelayMs?: number;
111
+ }
112
+ /** Which durable-storage operation failed, passed to {@link OfflineQueueOptions.onPersistenceError}. */
113
+ type PersistenceOperation = "append" | "clear" | "load" | "remove" | "replace";
114
+ /** Context handed to a persistence-error handler. */
115
+ interface PersistenceErrorContext {
116
+ readonly error: unknown;
117
+ /** The mutation id involved, when the failing op was scoped to one (`append`/`remove`). */
118
+ readonly mutationId?: string;
119
+ readonly operation: PersistenceOperation;
120
+ }
121
+ interface OfflineQueueOptions {
122
+ maxItems?: number;
123
+ /**
124
+ * Invoked when a {@link PersistenceAdapter} call rejects (e.g. IndexedDB quota
125
+ * exceeded). Without a handler, failures are logged via `console.warn` so they
126
+ * are never fully silent. Note: a failed `append` means the write is queued in
127
+ * memory but NOT durable — it will not survive a reload.
128
+ */
129
+ onPersistenceError?: (context: PersistenceErrorContext) => void;
130
+ /**
131
+ * Queue mutations issued before a shard's first successful WebSocket
132
+ * connect (defaults to `false`). The standard behaviour (`LunoraClient`'s
133
+ * `mutation()`) queues only when the targeted shard has been connected at
134
+ * least once (`wasEverConnected`), so the registry / resubscribe handshake
135
+ * has run. Set this to `true` for offline-first apps that want to enqueue
136
+ * writes on the very first session before the WS is up.
137
+ */
138
+ queueBeforeFirstConnect?: boolean;
139
+ }
140
+ /**
141
+ * Serializable shape of an offline mutation, durably stored by a
142
+ * {@link PersistenceAdapter} so queued writes survive a reload/crash. The live
143
+ * `resolve`/`reject` callbacks of an in-flight `QueuedMutation` are *not*
144
+ * persisted — a restored mutation is replayed with no original awaiter.
145
+ */
146
+ interface PersistedMutation {
147
+ args: Record<string, unknown>;
148
+ /**
149
+ * The CDC cursor this write was composed against, persisted so a replay —
150
+ * including one after a reload, days later — is still judged against what its
151
+ * author could actually see. Consumed only by `.dropStalePatches()` tables.
152
+ *
153
+ * Persisting it is the entire point of the feature. Re-deriving a baseline at
154
+ * replay time would read the cursor the client has ADVANCED to while the write
155
+ * sat in the queue, which is the newer state the write must be compared
156
+ * against — so the stale write would always look fresh and always clobber.
157
+ *
158
+ * Absent on records written by older client versions, and on a client with no
159
+ * live subscription to take a cursor from; both replay with no baseline, which
160
+ * applies the write unchanged.
161
+ */
162
+ baselineSeq?: number;
163
+ /**
164
+ * The client id that queued this write, persisted so a replay after a reload
165
+ * lands in the SAME server-side dedup namespace it was issued under. The
166
+ * standalone client's own `clientId` is minted per session, so replaying under
167
+ * the live one would miss the `__idempotency` row for an anonymous caller and
168
+ * re-run a write the server already committed. Absent on records written by
169
+ * older client versions, which replay under the live id.
170
+ */
171
+ clientId?: string;
172
+ functionPath: string;
173
+ id: string;
174
+ /**
175
+ * Issuing identity fingerprint, persisted so a hydrated write replays only
176
+ * under the identity that queued it (`null` = queued while signed out).
177
+ * Absent on records written by older client versions, which replay under
178
+ * the ambient identity for back-compat.
179
+ */
180
+ identity?: string | null;
181
+ shardKey?: string;
182
+ /**
183
+ * App/schema version stamped at enqueue (from `LunoraClientOptions.persistenceVersion`).
184
+ * On hydrate, a record whose `version` doesn't match the current one is dropped
185
+ * and purged rather than replayed — so a write persisted by an older deploy
186
+ * (with a now-changed function signature) can't replay against the new schema.
187
+ * Absent when no `persistenceVersion` is configured (no version gating).
188
+ */
189
+ version?: string;
190
+ }
191
+ /**
192
+ * Durable store for the offline mutation queue. The default client keeps the
193
+ * queue in memory; supplying an adapter (e.g. `createIndexedDbPersistence`)
194
+ * makes queued writes survive a page reload. Implementations must preserve FIFO
195
+ * (enqueue) order in `PersistenceAdapter.load`.
196
+ *
197
+ * Replay semantics are at-least-once: a mutation is removed only after the
198
+ * server confirms (or rejects) it, so a crash between commit and `remove` can
199
+ * replay it again on the next load.
200
+ */
201
+ interface PersistenceAdapter {
202
+ /** Append a mutation to durable storage (called on enqueue). */
203
+ append: (mutation: PersistedMutation) => Promise<void>;
204
+ /** Drop every persisted mutation (e.g. on logout). */
205
+ clear: () => Promise<void>;
206
+ /** Load all persisted mutations in FIFO order — called once at startup. */
207
+ load: () => Promise<PersistedMutation[]>;
208
+ /** Remove a mutation by id once it has been replayed (resolved or rejected). */
209
+ remove: (id: string) => Promise<void>;
210
+ /**
211
+ * Overwrite an already-persisted mutation IN PLACE, keeping its position in
212
+ * FIFO order. Used when a queued write's identity stamp is rewritten after a
213
+ * sign-in / sign-out.
214
+ *
215
+ * Must be atomic: a `remove` + `append` pair has a window where a process
216
+ * stop leaves the mutation in no durable store at all, and the in-memory
217
+ * entry has already advanced, so a reload loses the write outright. It also
218
+ * moved the record to the BACK of the queue, replaying it out of the order
219
+ * it was issued in. Implementations do the whole swap under one transaction
220
+ * (or one serialized blob write).
221
+ *
222
+ * A mutation whose id is not present is left alone — the record was drained
223
+ * concurrently and re-inserting it would replay a settled write.
224
+ */
225
+ replace: (mutation: PersistedMutation) => Promise<void>;
226
+ }
227
+ /**
228
+ * One write handed to an {@link OutboxSink}. Mirrors {@link PersistedMutation}
229
+ * plus the custom-mutator identity (`clientId`/`mutationId`/`idempotencyKey`)
230
+ * the durable outbox needs to dedupe and watermark replays.
231
+ */
232
+ interface OutboxMutation {
233
+ args: Record<string, unknown>;
234
+ /**
235
+ * The CDC cursor this write was composed against — see
236
+ * {@link PersistedMutation.baselineSeq}, whose contract this mirrors.
237
+ *
238
+ * A sink MUST persist it and hand it back unchanged on replay. This is the
239
+ * canonical statement of that rule for the durable path; every other site
240
+ * that carries the field points here. Re-deriving one at replay time reads
241
+ * the cursor the client has since advanced to — the newer state the write is
242
+ * supposed to be judged against — so a stale write always looks fresh and
243
+ * always clobbers.
244
+ *
245
+ * `undefined` when the client has no live subscription to take a cursor from,
246
+ * which replays the write unchanged.
247
+ */
248
+ baselineSeq?: number;
249
+ /** Stable per-client id; pairs with {@link OutboxMutation.mutationId} as `idempotencyKey`. */
250
+ clientId: string;
251
+ functionPath: string;
252
+ /**
253
+ * `${clientId}:${mutationId}`, or the caller's own `mutationId` when it passed
254
+ * one (an `importRows` chunk) — sent as `x-lunora-mutation-id` so a replay is
255
+ * server-idempotent.
256
+ */
257
+ idempotencyKey: string;
258
+ /** Issuing identity fingerprint (`null` = signed out); drives the sink's identity guard. */
259
+ identity: string | null;
260
+ /** Monotonic per-client mutation id, backing the server `__client_watermark`. */
261
+ mutationId: number;
262
+ /**
263
+ * Roll this write's optimistic patch back. The sink's owner invokes it when
264
+ * the replay reaches a PERMANENT verdict (a coded rejection, an identity
265
+ * drop) — never on a transient failure it will retry, and never on success.
266
+ *
267
+ * Without it a rejected replay leaves its predicted value on screen until an
268
+ * unrelated frame or a reload: the client drops the layer when it hands the
269
+ * write over (it cannot cursor-confirm through this path) and has no other
270
+ * signal that the write died. Absent when the write carried no optimistic
271
+ * update, and safe to ignore — a sink that never calls it behaves as before.
272
+ */
273
+ onRejected?: () => void;
274
+ shardKey?: string;
275
+ }
276
+ /**
277
+ * Pluggable durable outbox seam. When set on {@link LunoraClientOptions.outbox},
278
+ * the client delegates offline write durability + at-least-once replay to this
279
+ * sink instead of its built-in {@link PersistenceAdapter}-backed `OfflineQueue`.
280
+ * `@lunora/db` supplies the blessed implementation (`createExecutorOutboxSink`,
281
+ * backed by the TanStack `OfflineExecutor`); the interface itself is
282
+ * dependency-free so `@lunora/client` stays TanStack-free.
283
+ */
284
+ interface OutboxSink {
285
+ /**
286
+ * Persist and schedule a write for replay. Rejects with an
287
+ * `OFFLINE_QUEUE_OVERFLOW`-coded error when the sink's cap is exceeded, so
288
+ * the caller can surface back-pressure to the issuing mutation.
289
+ */
290
+ enqueue: (mutation: OutboxMutation) => Promise<void>;
291
+ /**
292
+ * Whether the sink still holds writes that have not replayed. The client
293
+ * consults this before sending a fresh mutation live, so a new write can
294
+ * never overtake an older one the sink is still holding (a write deferred
295
+ * because its identity isn't re-confirmed yet is held indefinitely, with
296
+ * nothing for the client's flush barrier to wait on).
297
+ *
298
+ * Optional: a sink that cannot answer never engages the ordering gate, so
299
+ * such a sink behaves exactly as before.
300
+ */
301
+ pending?: () => boolean;
302
+ }
303
+ /**
304
+ * One persisted query result in the durable read cache (Pillar 2). Keyed in the
305
+ * store by `shardKey + functionPath + argsKey`; the record carries everything
306
+ * needed to render offline on reload and to resume the live subscription.
307
+ */
308
+ interface CachedQuery {
309
+ /**
310
+ * Token-hash fingerprint of the bearer the value was cached under, when the
311
+ * entry was written by the identity the client currently advertises.
312
+ *
313
+ * The second half of the identity gate, and the half that makes the cache
314
+ * usable at all for a bearer-token app. `identity` settles on the resolved
315
+ * subject (`subj:<id>`) once the session resolves, but on the NEXT reload
316
+ * every adapter can only offer the stored token first — the subject arrives
317
+ * a round trip later, and offline it never arrives at all. Matching the
318
+ * credential the entry was written under is what lets the seed happen before
319
+ * (or without) that round trip. Absent when signed out, or when the value
320
+ * arrived over a socket authenticated as someone else.
321
+ */
322
+ credential?: string;
323
+ /**
324
+ * Issuing identity fingerprint (same shape the offline queue stamps). A
325
+ * cached value only hydrates when it matches the current identity, so a
326
+ * signed-out cache never leaks into a new session.
327
+ *
328
+ * `null` = cached by a client that had no subject to name — an app with no
329
+ * auth at all, or one the server answered "no session" to. It is never
330
+ * written while a session resolve is in flight, because a `null` written
331
+ * there belongs to a user the client was about to name, and every
332
+ * unidentified session would match it.
333
+ */
334
+ identity: string | null;
335
+ /**
336
+ * The `cursor` high-watermark this value reflects, replayed as `sinceSeq`
337
+ * on reconnect so the server can resume instead of re-snapshotting. Absent
338
+ * when the value predates CDC / no cursor was advertised.
339
+ */
340
+ serverCursor?: number;
341
+ /**
342
+ * The CDC `epoch` the `serverCursor` belongs to, replayed as `sinceEpoch`
343
+ * on reconnect so the server only resumes when the client is still on the
344
+ * same changelog timeline. Absent when no epoch was advertised.
345
+ */
346
+ serverEpoch?: string;
347
+ /** Wall-clock millis the value was written — drives LRU eviction. */
348
+ ts: number;
349
+ /** The full query result last seen from the server. */
350
+ value: unknown;
351
+ /**
352
+ * App/schema version stamped when persisted (from `LunoraClientOptions.persistenceVersion`).
353
+ * A cached value whose `version` doesn't match the current one is not hydrated —
354
+ * so a result of a now-changed shape from an older deploy can't render. Absent
355
+ * when no `persistenceVersion` is configured (no version gating).
356
+ */
357
+ version?: string;
358
+ }
359
+ /** A stored read-cache row: the {@link CachedQuery} plus the key it is stored under. */
360
+ interface StoredQuery extends CachedQuery {
361
+ key: string;
362
+ }
363
+ /**
364
+ * Durable store for the client read cache (Pillar 2): query results survive a
365
+ * reload so reads hydrate from disk and render immediately while the socket
366
+ * reconnects. Opt-in via {@link LunoraClientOptions.queryCache}; omit to keep
367
+ * reads in memory only (today's behaviour). Mirrors {@link PersistenceAdapter}'s
368
+ * shape over the same IndexedDB plumbing.
369
+ */
370
+ interface QueryCacheAdapter {
371
+ /** Drop every cached query (e.g. on logout / identity change). */
372
+ clear: () => Promise<void>;
373
+ /** Load every cached query — called once at startup to hydrate reads. */
374
+ load: () => Promise<StoredQuery[]>;
375
+ /** Upsert one cached query by key (called when a subscription value advances). */
376
+ put: (key: string, entry: CachedQuery) => Promise<void>;
377
+ /** Remove one cached query by key. */
378
+ remove: (key: string) => Promise<void>;
379
+ }
380
+ /**
381
+ * Resolves a WebSocket credential (`wsToken` or `wsTicket`) fresh at every
382
+ * (re)connect, so a short-lived credential is re-minted rather than held.
383
+ * May return the value synchronously or as a Promise; returning `undefined`
384
+ * connects without one. A thrown error / rejected Promise fails that connect
385
+ * attempt, and the client retries with its normal reconnect backoff.
386
+ */
387
+ type WsTokenProvider = () => Promise<string | undefined> | string | undefined;
388
+ interface LunoraClientOptions {
389
+ /**
390
+ * Base path the worker mounts better-auth at, used by the client's
391
+ * `getCurrentUser()` to reach the `get-session` route. Defaults to
392
+ * `/api/auth` (matching `@lunora/auth`'s `DEFAULT_AUTH_BASE_PATH`).
393
+ */
394
+ authBasePath?: string;
395
+ /**
396
+ * Whether sockets present the `setAuthToken` bearer on the upgrade. Turn it on
397
+ * when the session is a bearer and not a cookie on the API's origin — an
398
+ * external identity provider's JWT (Clerk, WorkOS, …) or a cross-origin API.
399
+ *
400
+ * A browser cannot set `Authorization` on a WebSocket, so the bearer is
401
+ * offered as a `Sec-WebSocket-Protocol` entry (`lunora.bearer.<base64url>`),
402
+ * never in the URL; the worker reads it for `resolveIdentity` only.
403
+ * `@lunora/react-native` turns this on by default on native, where the bearer
404
+ * also rides an `Authorization` header (the header wins).
405
+ *
406
+ * A sign-in from signed-out then reconnects the shard sockets cold, and a
407
+ * refreshed bearer bounces them warm, so the server sees the current token.
408
+ * The default `false` keeps cookie-session sockets (and their live values)
409
+ * alone.
410
+ */
411
+ authTokenOnUpgrade?: boolean;
412
+ bookmarkStorage?: BookmarkStorage;
413
+ /**
414
+ * Stable per-client id backing the custom-mutator watermark. Sent on the
415
+ * `connect` envelope (so the server can scope this client's
416
+ * `__client_watermark`) and stamped onto every {@link OutboxMutation} the
417
+ * {@link LunoraClientOptions.outbox} sink persists, where it pairs with the
418
+ * monotonic mutation id to form the idempotency key. The `@lunora/db` path
419
+ * persists a stable id alongside the outbox and passes it here; omit for the
420
+ * standalone client, which generates an ephemeral per-session id.
421
+ */
422
+ clientId?: string;
423
+ /**
424
+ * Default app context sent in the `connect` envelope right after each socket
425
+ * opens, forwarded to the server's `onConnect`/`onDisconnect` lifecycle hooks
426
+ * as `event.context`. A per-shard context registered via
427
+ * `setConnectionContext` overrides this for that shard. Omit when no lifecycle
428
+ * hook needs connection context.
429
+ */
430
+ connectionContext?: Record<string, unknown>;
431
+ /**
432
+ * Fail-fast timeout (ms) for opening a subscription WebSocket. If the
433
+ * handshake doesn't complete within this window — a hung dev proxy or a cold
434
+ * worker that never upgrades — the client force-closes the socket and routes
435
+ * through its normal reconnect/backoff (surfacing `offline` status) instead
436
+ * of leaving the live channel silently stuck on the browser's much longer
437
+ * default. Does not affect HTTP queries/mutations (those never ride the WS).
438
+ * Defaults to 10000 (10s); set to `0` (or negative) to disable.
439
+ */
440
+ connectTimeoutMs?: number;
441
+ /**
442
+ * When `true`, tabs sharing the same origin (and the same signed-in identity)
443
+ * coordinate via BroadcastChannel so only one tab — the "leader" — opens
444
+ * WebSocket connections to the server. Reduces simultaneous WS connections,
445
+ * bandwidth, and cross-tab state drift. Requires `BroadcastChannel`
446
+ * (browser-only); silently ignored otherwise. Defaults to `false`.
447
+ *
448
+ * **The channel is one-directional: leader → follower.** The leader
449
+ * broadcasts the values, errors, checkpoints and connection status of the
450
+ * subscriptions *it* holds; there is no frame with which a follower can ask
451
+ * the leader for anything.
452
+ *
453
+ * `subscribe` works on a follower and is how the relay delivers: the
454
+ * registration is what the leader's broadcast key is matched against, so a
455
+ * follower sees a value while the leader independently holds the same
456
+ * `(fn, args, shardKey)`.
457
+ *
458
+ * Nothing else is served, because the leader broadcasts nothing for it and a
459
+ * follower cannot ask. `subscribeShape` and `acquireConnectionContext` are
460
+ * inert on a follower — framework code (`@lunora/db`'s shape sync, every
461
+ * `usePresence` adapter) calls them from an effect the app cannot opt out
462
+ * of, so throwing would unwind the tab rather than degrade one feature.
463
+ * `whisper`, `whisperSubscribe`, `setConnectionContext` and `stream` are
464
+ * only ever called by app code, which can handle a failure, so those throw
465
+ * `NOT_IMPLEMENTED` rather than returning a handle that never fires. (The
466
+ * brief window every tab spends claiming leadership at startup is not a
467
+ * follower state: a lone tab self-promotes and its registered subscriptions
468
+ * are sent then.) HTTP surfaces — `query`, `mutation`, `action`, the offline
469
+ * queue's replay — are unaffected on every tab.
470
+ *
471
+ * So: enable this when your tabs run the SAME app views over plain
472
+ * `subscribe`, and leave it off if tabs can sit on different routes or you
473
+ * use shapes, whispers, streams, or connection context.
474
+ */
475
+ crossTabSync?: boolean;
476
+ fetch?: typeof fetch;
477
+ /**
478
+ * Interval (ms) between keepalive pings sent on each open subscription
479
+ * socket. The server answers them via the Durable Object's hibernation
480
+ * auto-response WITHOUT waking the DO, so an idle socket stays alive across
481
+ * hibernation without a billable wakeup. Defaults to 30000 (30s); set to
482
+ * `0` (or a negative value) to disable the heartbeat entirely.
483
+ */
484
+ heartbeatIntervalMs?: number;
485
+ /**
486
+ * When `true` and a `queryCache` is active, React's `useQuery` holds its
487
+ * TanStack query disabled until the durable cache has finished loading
488
+ * (`whenReady()`), so its first enabled render can seed the cached value
489
+ * instead of issuing an HTTP read that the cache would immediately
490
+ * overwrite. Defaults to `false`.
491
+ *
492
+ * It is ONLY React's `useQuery` that defers — the Vue, Svelte, Solid and
493
+ * Angular hooks subscribe at mount regardless of this flag, and so does
494
+ * React's own subscription registry. They do not need the gate: a
495
+ * subscription opened before the load completes is seeded by the load
496
+ * itself, so a cached value reaches the first subscriber either way.
497
+ *
498
+ * Requires `queryCache` to be set (not `false`); silently ignored otherwise.
499
+ */
500
+ hydrateOnStart?: boolean;
501
+ offlineQueue?: OfflineQueueOptions;
502
+ /**
503
+ * Durable outbox seam for offline writes. When supplied (the `@lunora/db`
504
+ * path wires `createExecutorOutboxSink`), offline mutations are delegated to
505
+ * the sink and the built-in {@link PersistenceAdapter}-backed `OfflineQueue`
506
+ * is bypassed, so a db app has exactly one durable write path. Omit for the
507
+ * standalone client, which keeps using {@link LunoraClientOptions.persistence}.
508
+ */
509
+ outbox?: OutboxSink;
510
+ /**
511
+ * Durable store for the offline mutation queue. Tri-state — an explicit
512
+ * {@link PersistenceAdapter} is used as-is; `false` opts out (the queue stays
513
+ * in memory, lost on reload); omitted (the default) auto-probes a durable
514
+ * IndexedDB store when the `indexedDB` global is present (browsers), otherwise
515
+ * in-memory, so SSR/Node/React-Native keep the in-memory behaviour and only
516
+ * environments that can persist do. Pass `createAsyncStoragePersistence()` on
517
+ * React Native.
518
+ */
519
+ persistence?: false | PersistenceAdapter;
520
+ /**
521
+ * App/schema version stamped onto every persisted queued write and cached
522
+ * read. Bump it on a breaking change to a function signature or query shape:
523
+ * on the next boot, persisted writes / cached reads stamped with a different
524
+ * version are dropped (and purged) rather than replayed / hydrated against the
525
+ * new schema. Omit to disable version gating (records are never invalidated by
526
+ * version).
527
+ *
528
+ * **Adoption is itself an invalidation event:** records written before you set
529
+ * `persistenceVersion` carry no version, so the first boot after enabling it
530
+ * purges all currently-queued offline writes (and cached reads) as stale. Adopt
531
+ * it on a build where that clean slate is acceptable — typically the same
532
+ * breaking deploy you're protecting against — not purely speculatively.
533
+ */
534
+ persistenceVersion?: string;
535
+ /**
536
+ * HTTP polling fallback for live queries on a network that refuses WebSocket
537
+ * upgrades (a corporate proxy, a captive portal).
538
+ *
539
+ * One-shot `query`/`mutation`/`action` calls already ride HTTP POST, so such a
540
+ * network does not break them — it breaks reactivity, and only that. After a
541
+ * run of connect attempts that never reach `open`, the client re-runs each
542
+ * subscribed query over the batch-RPC endpoint on an interval and reports
543
+ * `"polling"` from the client's `connectionStatus()`.
544
+ *
545
+ * It is a degradation, not a second transport: shapes (`@lunora/db`
546
+ * collections), durable streams and whispers have no request/response form to
547
+ * re-run and stay unavailable until a socket opens. Freshness is bounded by
548
+ * the interval, and each tick costs a full re-run of every subscribed query.
549
+ *
550
+ * Defaults to polling every 5s after 3 consecutive failed opens. Set
551
+ * `intervalMs: 0` to disable it and keep the historical behaviour (live
552
+ * queries simply stop moving).
553
+ */
554
+ pollingFallback?: {
555
+ /** Consecutive connect attempts that must fail to reach `open` first. Default 3; `0` disables. */
556
+ afterFailedAttempts?: number;
557
+ /** Poll cadence in ms. Default 5000; `0` disables. */
558
+ intervalMs?: number;
559
+ };
560
+ /**
561
+ * Durable store for the read cache (Pillar 2). When active, query results
562
+ * are persisted as their subscriptions advance and hydrated on construction
563
+ * so a reload renders cached data before the socket reconnects, then resumes
564
+ * the live subscription from the persisted cursor. Tri-state — an explicit
565
+ * {@link QueryCacheAdapter} is used as-is; `false` opts out (reads stay in
566
+ * memory only); omitted (the default) auto-probes IndexedDB exactly like
567
+ * {@link LunoraClientOptions.persistence}.
568
+ */
569
+ queryCache?: QueryCacheAdapter | false;
570
+ reconnect?: ReconnectOptions;
571
+ /**
572
+ * Deadline (ms) for one HTTP RPC round trip (`query`, `mutation`, a replayed
573
+ * write), covering the response body as well as the connection. A request
574
+ * that stalls past it fails with a retryable `TransportError` — and a durable
575
+ * write is re-queued under the same `mutationId` — instead of freezing every
576
+ * write queued behind it on the shard. `action` is exempt: it may legitimately
577
+ * run for longer. Defaults to 30000 (30s); set to `0` (or negative) to disable.
578
+ */
579
+ rpcTimeoutMs?: number;
580
+ url: string;
581
+ WebSocket?: typeof WebSocket;
582
+ /**
583
+ * The short-lived ticket appended to the WebSocket URL as `?token=…`. Only
584
+ * an ephemeral admin sub-token belongs here, minted by
585
+ * `POST /_lunora/admin/ws-token`; the server authorizes `__lunora_admin__:*`
586
+ * subscriptions from it. A ticket lapses after its TTL, so a static master
587
+ * token must never be used here: the server refuses it in the URL.
588
+ *
589
+ * Pass a {@link WsTokenProvider} to re-mint on every (re)connect, including
590
+ * the one that follows a lapsed ticket.
591
+ */
592
+ wsTicket?: string | WsTokenProvider;
593
+ /**
594
+ * The session credential. It is sent in the `connect` frame of every shard
595
+ * socket and never in the WebSocket URL, because a URL is logged by every
596
+ * proxy and edge on the way (protocol §6). The server matches it against
597
+ * `LUNORA_WS_BEARER`; a socket that does not present a match is closed.
598
+ *
599
+ * Pass a {@link WsTokenProvider} to resolve it fresh at every (re)connect, so
600
+ * a rotated session is picked up on the next connect.
601
+ */
602
+ wsToken?: string | WsTokenProvider;
603
+ wsUrl?: string;
604
+ }
605
+ /** Wire envelope sent on `POST /_lunora/rpc`. */
606
+ interface RpcEnvelope {
607
+ args?: Record<string, unknown>;
608
+ /**
609
+ * Stable per-client identifier (custom-mutator push path). Pairs with
610
+ * {@link RpcEnvelope.mutationId} to form `idempotencyKey` and scope the
611
+ * server `__client_watermark`. Absent on plain `client.mutation` calls.
612
+ */
613
+ clientId?: string;
614
+ functionPath: string;
615
+ /**
616
+ * Idempotency key (`${clientId}:${mutationId}`) for the custom-mutator push
617
+ * path, mirrored into the `x-lunora-mutation-id` header. Absent on plain
618
+ * `client.mutation` calls.
619
+ */
620
+ idempotencyKey?: string;
621
+ /**
622
+ * Monotonic per-client mutation id (custom-mutator push path), backing the
623
+ * server-side per-client watermark: `id <= watermark` is a replay (skipped),
624
+ * `id == watermark + 1` runs authoritatively, `id > watermark + 1` halts the
625
+ * batch so the client resends from `watermark + 1`. Absent on plain
626
+ * `client.mutation` calls.
627
+ */
628
+ mutationId?: number;
629
+ shardKey?: string;
630
+ }
631
+ /**
632
+ * Wire response from the shard's `/rpc` endpoint (forwarded by the runtime). A
633
+ * watermarked custom-mutator push additionally carries `lastMutationId` — the
634
+ * highest per-client sequence the DO has applied — which the client uses to keep
635
+ * its `clientSeq` generator monotonic across reloads (see `LunoraClient.callMutator`).
636
+ * A plain mutation on a CDC shard carries `commitCursor` — the cursor the write
637
+ * committed at — which gates the drop of a per-call optimistic layer.
638
+ */
639
+ type RpcResponseBody = {
640
+ error: {
641
+ code: string;
642
+ data?: unknown;
643
+ message: string;
644
+ };
645
+ } | {
646
+ commitCursor?: number;
647
+ lastMutationId?: number;
648
+ result: unknown;
649
+ };
650
+ /** Subscription protocol — client → server. */
651
+ interface ClientSubscribeMessage {
652
+ id: string;
653
+ /**
654
+ * `sinceSeq` is the persisted `cursor` high-watermark the client last saw
655
+ * for this shard (Pillar 1b resume). Present only when a durable
656
+ * {@link QueryCacheAdapter} restored a cached value with a cursor; the
657
+ * server replies with a lightweight `resume` frame instead of a full
658
+ * snapshot when nothing the query reads changed since it. Absent on a
659
+ * first-time subscribe.
660
+ */
661
+ query: {
662
+ args?: Record<string, unknown>;
663
+ functionPath?: string;
664
+ sinceEpoch?: string;
665
+ sinceSeq?: number;
666
+ table?: string;
667
+ };
668
+ type: "subscribe";
669
+ }
670
+ interface ClientUnsubscribeMessage {
671
+ id: string;
672
+ type: "unsubscribe";
673
+ }
674
+ /**
675
+ * One-shot control frame sent right after the socket opens. Registers the
676
+ * connection's app `context` (e.g. `{ roomId, sessionId }`) with the server and
677
+ * fires the `onConnect` lifecycle hooks; the same context is replayed to
678
+ * `onDisconnect` when the socket drops.
679
+ */
680
+ interface ClientConnectMessage {
681
+ /**
682
+ * Wire behaviours this client can handle that an older one cannot, so the
683
+ * server can use them without breaking clients that can't. Currently just
684
+ * `"pageDelta"`; see `shared/page-result.ts` for what it promises and why it
685
+ * must be announced rather than assumed. Omitting it is always safe.
686
+ */
687
+ caps?: ReadonlyArray<string>;
688
+ /**
689
+ * Stable per-client id (persisted alongside the outbox). Lets the server
690
+ * scope this connection's `__client_watermark` so custom-mutator pokes can
691
+ * echo the right per-client `lastMutationId`. Omitted by clients that don't
692
+ * use custom mutators.
693
+ */
694
+ clientId?: string;
695
+ context?: Record<string, unknown>;
696
+ id: string;
697
+ /**
698
+ * The session credential (protocol §6). A gated server checks it against
699
+ * `LUNORA_WS_BEARER`. Set from the client's `wsToken` and never placed in the
700
+ * socket URL.
701
+ */
702
+ token?: string;
703
+ type: "connect";
704
+ }
705
+ /**
706
+ * Subscribe to a declarative **shape** — server-side partial replication scoped
707
+ * by `shardBy` + the shape's predicate + RLS. The client sends the shape *name*
708
+ * + validated `args`; the server resolves the trusted `where` (identity/RLS
709
+ * `baseWhere` the client can't forge) and streams the matching rowset, then live
710
+ * {@link ServerPokePartMessage} diffs. `id` namespaces the subscription and is
711
+ * echoed as `shapeId` on every poke part.
712
+ */
713
+ interface ClientShapeSubscribeMessage {
714
+ id: string;
715
+ shape: {
716
+ args?: Record<string, unknown>;
717
+ name: string;
718
+ };
719
+ /**
720
+ * Resume from this checkpoint (the `__cdc_log` cursor the client last
721
+ * applied for this shape). When absent or below the server's retained floor
722
+ * (`minCdcSeq`), the server re-seeds with a full insert-poke instead of a
723
+ * delta.
724
+ */
725
+ sinceCheckpoint?: number;
726
+ /**
727
+ * The CDC epoch {@link ClientShapeSubscribeMessage.sinceCheckpoint} belongs
728
+ * to. A mismatch (forked changelog timeline) forces a full re-seed even when
729
+ * the cursor is numerically in range.
730
+ */
731
+ sinceEpoch?: string;
732
+ type: "shape_subscribe";
733
+ }
734
+ /** Cancel a shape subscription started with the same `id`. */
735
+ interface ClientShapeUnsubscribeMessage {
736
+ id: string;
737
+ type: "shape_unsubscribe";
738
+ }
739
+ interface ClientAckMessage {
740
+ id: string;
741
+ type: "ack";
742
+ }
743
+ /**
744
+ * Start a streaming query. The id namespaces a fresh stream and is echoed on
745
+ * every {@link ServerChunkMessage} the server pushes back. Cancel a running
746
+ * stream by sending a {@link ClientUnsubscribeMessage} with the same id —
747
+ * subscription and stream id-spaces share the cancel channel; the prefix
748
+ * (`sub_*` vs `stream_*`) keeps the local registries searchable.
749
+ */
750
+ interface ClientStreamMessage {
751
+ /**
752
+ * Run generation the {@link ClientStreamMessage.sinceChunk} watermark
753
+ * belongs to: the `generation` stamp carried by the chunk frames this
754
+ * client already received, echoed back on a resume. The server refuses to
755
+ * splice a different run's tail onto the held prefix — a mismatch fails
756
+ * with `STREAM_INTERRUPTED` instead. Omitted on a first attach.
757
+ */
758
+ generation?: number;
759
+ id: string;
760
+ query: {
761
+ args?: Record<string, unknown>;
762
+ functionPath: string;
763
+ shardKey?: string;
764
+ };
765
+ /**
766
+ * Resume watermark: the highest chunk `seq` this client already received.
767
+ * Only meaningful for a stream the server declared `durable` — the run
768
+ * replays everything after it and then continues live, which is what turns
769
+ * a reconnect into a resume instead of a lost generation. Omitted on a
770
+ * first attach.
771
+ *
772
+ * Named `sinceChunk`, not `sinceSeq`, because a subscribe envelope already
773
+ * carries a `query.sinceSeq` meaning the CDC cursor.
774
+ */
775
+ sinceChunk?: number;
776
+ type: "stream";
777
+ }
778
+ /**
779
+ * Join or leave a whisper `topic` — an app-chosen ephemeral channel scoped to a
780
+ * shard. While joined, the client receives every {@link ServerWhisperMessage}
781
+ * other members broadcast to the topic.
782
+ */
783
+ interface ClientWhisperSubscribeMessage {
784
+ topic: string;
785
+ type: "whisper_subscribe" | "whisper_unsubscribe";
786
+ }
787
+ /**
788
+ * Broadcast ephemeral `data` to the topic's other members on the shard. The
789
+ * payload is relayed verbatim with no server-side persistence (no SQLite/CDC
790
+ * write) — for typing indicators, live cursors, presence pings. The sender does
791
+ * not receive its own whisper.
792
+ */
793
+ interface ClientWhisperMessage {
794
+ data?: unknown;
795
+ topic: string;
796
+ type: "whisper";
797
+ }
798
+ type ClientMessage = ClientAckMessage | ClientConnectMessage | ClientShapeSubscribeMessage | ClientShapeUnsubscribeMessage | ClientStreamMessage | ClientSubscribeMessage | ClientUnsubscribeMessage | ClientWhisperMessage | ClientWhisperSubscribeMessage;
799
+ /** Subscription protocol — server → client. */
800
+ interface ServerDataMessage {
801
+ /**
802
+ * The `__cdc_log` high-watermark covered by this frame (Pillar 1b). The
803
+ * client persists it as the query's `serverCursor` and replays it as
804
+ * `sinceSeq` on the next reconnect. Absent on shards that never enabled CDC.
805
+ */
806
+ cursor?: number;
807
+ data?: unknown;
808
+ delta?: unknown;
809
+ /** The CDC epoch this frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
810
+ epoch?: string;
811
+ id: string;
812
+ /**
813
+ * The highest custom-mutator `mutationId` from this client the server has
814
+ * now applied (the per-client `__client_watermark`). Echoed so the client's
815
+ * outbox can drop confirmed pending mutations and let TanStack DB collapse
816
+ * the matching optimistic overlay. Absent on shards without custom mutators.
817
+ */
818
+ lastMutationId?: number;
819
+ /** Set on every frame of a delta run except its last; the client holds those until the run ends. */
820
+ more?: boolean;
821
+ type: "data" | "delta";
822
+ }
823
+ /**
824
+ * Lightweight resume acknowledgement (Pillar 1b): the server determined that
825
+ * nothing the subscription reads changed since the client's `sinceSeq`, so it
826
+ * skips re-sending the snapshot. The client keeps its cached value and only
827
+ * advances `serverCursor` to `cursor`.
828
+ */
829
+ interface ServerResumeMessage {
830
+ cursor?: number;
831
+ /** The CDC epoch this resume's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
832
+ epoch?: string;
833
+ id: string;
834
+ /** Per-client custom-mutator watermark (see {@link ServerDataMessage.lastMutationId}). */
835
+ lastMutationId?: number;
836
+ type: "resume";
837
+ }
838
+ /**
839
+ * Settled acknowledgement for a **list** subscription: a write touched one of
840
+ * the subscription's read tables but produced a byte-identical result, so the
841
+ * server suppressed the data frame. Sent ONLY to a `@lunora/db` custom-mutator
842
+ * client (one that announced a `clientId`, hence has a server-side
843
+ * `__client_watermark`) so its optimistic list overlay drops even when no data
844
+ * frame arrives. Plain `useQuery` subscribers never receive it, and an older
845
+ * client safely ignores the unknown frame.
846
+ */
847
+ interface ServerSettledMessage {
848
+ cursor?: number;
849
+ /** The CDC epoch this settled frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
850
+ epoch?: string;
851
+ id: string;
852
+ /**
853
+ * The highest custom-mutator `mutationId` from this client the server has
854
+ * now applied (the per-client `__client_watermark`). Forwarded to a
855
+ * collection's `onCheckpoint` so it can drop the overlay for the confirmed
856
+ * write whose result didn't change this list.
857
+ */
858
+ lastMutationId?: number;
859
+ type: "settled";
860
+ }
861
+ interface ServerErrorMessage {
862
+ error?: unknown;
863
+ id?: string;
864
+ message?: string;
865
+ type: "error";
866
+ }
867
+ interface ServerAckMessage {
868
+ id: string;
869
+ type: "ack";
870
+ }
871
+ interface ServerCompleteMessage {
872
+ id: string;
873
+ type: "complete";
874
+ }
875
+ /** One frame of a streaming query — `data` carries the user-yielded chunk. */
876
+ interface ServerChunkMessage {
877
+ data: unknown;
878
+ /**
879
+ * Generation stamp of the **durable** run this chunk belongs to. The client
880
+ * stores it beside {@link ServerChunkMessage.seq} and echoes it as
881
+ * {@link ClientStreamMessage.generation} on a resume, so the server can
882
+ * tell a genuine resume from an attempt to splice onto a different run
883
+ * under the same key. Absent on an ephemeral stream.
884
+ */
885
+ generation?: number;
886
+ id: string;
887
+ /**
888
+ * Monotonic position of this chunk within a **durable** run, starting at 1.
889
+ * The client stores the last one it saw and replays it as
890
+ * {@link ClientStreamMessage.sinceChunk} when the socket comes back. Absent
891
+ * on an ephemeral stream, which has nothing to resume from.
892
+ */
893
+ seq?: number;
894
+ type: "chunk";
895
+ }
896
+ /**
897
+ * An ephemeral whisper relayed from another member of `topic` on the same shard
898
+ * (AnyCable-style whispering). `data` is the sender's payload verbatim; `from`
899
+ * is the sender's verified user id when known (absent for an anonymous sender).
900
+ * Never persisted server-side.
901
+ */
902
+ interface ServerWhisperMessage {
903
+ data: unknown;
904
+ from?: string;
905
+ topic: string;
906
+ type: "whisper";
907
+ }
908
+ /**
909
+ * The shard processed a `whisper_subscribe` for a live (non-room) `topic` on this socket. It is sent
910
+ * whether or not the join was admitted, so it carries no authorization signal. A client that must
911
+ * publish or receive only once its membership took effect waits for it. A room join gets no ack.
912
+ */
913
+ interface ServerWhisperSubscribedMessage {
914
+ topic: string;
915
+ type: "whisper_subscribed";
916
+ }
917
+ /**
918
+ * A server live publish to a WebSocket member granted `stream` on `topic`. Server-only:
919
+ * a peer's whisper never carries this type, so a `live` frame is always the server's.
920
+ * `data` is the published payload, the same as the SSE `live` event.
921
+ */
922
+ interface ServerLiveMessage {
923
+ data: unknown;
924
+ stream: string;
925
+ topic: string;
926
+ type: "live";
927
+ }
928
+ /**
929
+ * The user the shard authenticated this socket as, sent in reply to every
930
+ * `connect` frame. `subject` is the resolved user id, or `null` when the socket
931
+ * is anonymous. A cookie-session client reads it to learn who it is — a
932
+ * sign-out or another user's sign-in changes nothing else it can see.
933
+ *
934
+ * `connectionId` names this socket to the live-stream control route, which grants
935
+ * it live topics (see `LunoraClient.subscribeLiveTopic`). `whisperAck` is `true` when the
936
+ * shard answers every live join with `whisper_subscribed`; a client waits for that answer
937
+ * before it posts a grant, and posts at once when the flag is absent.
938
+ */
939
+ interface ServerIdentityMessage {
940
+ connectionId?: string;
941
+ subject: null | string;
942
+ type: "identity";
943
+ whisperAck?: boolean;
944
+ }
945
+ /**
946
+ * One row-level change in a shape's replication stream — the wire form of the
947
+ * DO's `__cdc_log` `CdcChange`. `insert`/`update` carry the post-image in
948
+ * `value` (projected to the shape's `columns`); `delete` omits it, identifying
949
+ * the removed row by `key` alone. The client applies these to its local
950
+ * collection; an unknown `key` on a `delete` is a safe no-op (a row the client
951
+ * never had in this shape).
952
+ */
953
+ interface RowOp {
954
+ /** Row primary key (`_id`). */
955
+ key: string;
956
+ op: "delete" | "insert" | "update";
957
+ /** Logical table the row belongs to. */
958
+ table: string;
959
+ /** Post-image document for insert/update; absent on delete. */
960
+ value?: Record<string, unknown>;
961
+ }
962
+ /**
963
+ * Opens a **poke** — an atomically-applied batch of shape diffs (Zero's poke
964
+ * protocol). A `pokeStart` is followed by zero or more {@link ServerPokePartMessage}
965
+ * frames and closed by exactly one {@link ServerPokeEndMessage}; the client
966
+ * buffers every part and applies them in a single transaction at `pokeEnd`, so a
967
+ * socket that drops mid-poke simply re-seeds on reconnect (no torn view).
968
+ */
969
+ interface ServerPokeStartMessage {
970
+ /**
971
+ * Poke-level fallback base, stamped by single-part senders. Per-shape
972
+ * {@link ServerPokePartMessage.baseCheckpoint} takes precedence; this is what
973
+ * a part without its own base falls back to.
974
+ */
975
+ baseCheckpoint?: number;
976
+ /** CDC epoch this poke belongs to; a mismatch forces the client to re-seed rather than apply. */
977
+ epoch?: string;
978
+ /** Correlates this poke's `pokeStart`/`pokePart`/`pokeEnd` frames. */
979
+ pokeId: string;
980
+ type: "pokeStart";
981
+ }
982
+ /** One shape's slice of an in-flight poke: the row-ops to apply for `shapeId`. */
983
+ interface ServerPokePartMessage {
984
+ /**
985
+ * The checkpoint this shape's view must be at for `rowsPatch` to splice on
986
+ * cleanly. Per shape, because every shape on a socket has its own
987
+ * delivered-through cursor. Absent when the server cannot name a base — the
988
+ * gap check is then disarmed for this part, never guessed at.
989
+ */
990
+ baseCheckpoint?: number;
991
+ /** Per-client custom-mutator watermark carried with this slice (see {@link ServerSettledMessage.lastMutationId}). */
992
+ lastMutationId?: number;
993
+ pokeId: string;
994
+ /**
995
+ * `true` when `rowsPatch` is the shape's COMPLETE membership, not a diff (a
996
+ * full seed or re-seed). The client MUST drop its current view for this shape
997
+ * before applying: a seed is inserts-only, so merging it leaves any row that
998
+ * left the shape while the client was disconnected on screen forever.
999
+ *
1000
+ * Never inferred from an absent {@link ServerPokePartMessage.baseCheckpoint} —
1001
+ * most live poke paths legitimately carry no base.
1002
+ */
1003
+ reset?: boolean;
1004
+ /** Ordered row-level changes for this shape, applied in sequence at `pokeEnd`. */
1005
+ rowsPatch: RowOp[];
1006
+ /** The {@link ClientShapeSubscribeMessage.id} these row-ops belong to. */
1007
+ shapeId: string;
1008
+ type: "pokePart";
1009
+ }
1010
+ /**
1011
+ * Closes a poke: the client commits the buffered parts atomically and advances
1012
+ * its checkpoint to {@link ServerPokeEndMessage.checkpoint} (the `__cdc_log`
1013
+ * cursor high-watermark the view now reflects), replayed as `sinceCheckpoint` on
1014
+ * the next reconnect.
1015
+ */
1016
+ interface ServerPokeEndMessage {
1017
+ /** The `__cdc_log` cursor the view is at after applying this poke. */
1018
+ checkpoint?: number;
1019
+ /** CDC epoch the {@link ServerPokeEndMessage.checkpoint} belongs to. */
1020
+ epoch?: string;
1021
+ pokeId: string;
1022
+ type: "pokeEnd";
1023
+ }
1024
+ type ServerMessage = ServerAckMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerIdentityMessage | ServerLiveMessage | ServerPokeEndMessage | ServerPokePartMessage | ServerPokeStartMessage | ServerResumeMessage | ServerSettledMessage | ServerWhisperMessage | ServerWhisperSubscribedMessage;
1025
+ /**
1026
+ * The authenticated user as exposed client-side, mirroring better-auth's
1027
+ * `user` row (the `user` field of the `get-session` response). Kept minimal
1028
+ * and structural — only `id` is guaranteed; the rest are the common better-auth
1029
+ * fields, and the index signature carries any plugin-contributed extras.
1030
+ */
1031
+ interface User {
1032
+ readonly createdAt?: NullableTimestamp;
1033
+ readonly email?: null | string;
1034
+ readonly emailVerified?: boolean | null;
1035
+ readonly id: string;
1036
+ readonly image?: null | string;
1037
+ readonly name?: null | string;
1038
+ readonly [key: string]: unknown;
1039
+ readonly updatedAt?: NullableTimestamp;
1040
+ }
1041
+ /**
1042
+ * Per-job retry policy carried on a {@link ScheduleRecord}. Mirrors
1043
+ * `@lunora/scheduler`'s `RetryPolicy`; absent means the scheduler's defaults.
1044
+ */
1045
+ interface ScheduleRetryPolicy {
1046
+ /** Backoff growth across attempts. Default `"exponential"`. */
1047
+ backoff?: "exponential" | "linear";
1048
+ /** Base delay in milliseconds for the first retry. Default `30_000`. */
1049
+ baseMs?: number;
1050
+ /** Maximum number of dispatch attempts before dead-lettering. Default `5`. */
1051
+ maxAttempts?: number;
1052
+ /** Optional ceiling clamping the computed backoff delay. */
1053
+ maxMs?: number;
1054
+ }
1055
+ /**
1056
+ * One pending scheduled function, as returned by the worker's
1057
+ * `GET /_lunora/admin/scheduled` endpoint. The route is a byte-for-byte proxy of
1058
+ * the SchedulerDO's own `/list`, so this mirrors `@lunora/scheduler`'s
1059
+ * `ScheduleRecord` field-for-field — structurally, so the client carries no
1060
+ * dependency on it. `packages/client/__tests__/structural-mirrors.test.ts` fails
1061
+ * when the two drift.
1062
+ */
1063
+ interface ScheduleRecord {
1064
+ args: Record<string, unknown>;
1065
+ /**
1066
+ * Dispatch attempts already made. Absent (treated as 0) until the first
1067
+ * failure; on a dead-letter record it is the exhausted count (> the retry
1068
+ * budget). Surfaced so the studio can show how hard a job tried before it
1069
+ * was parked.
1070
+ */
1071
+ attempts?: number;
1072
+ enqueuedAt: number;
1073
+ /**
1074
+ * The `ns:fn` path dispatched on fire. Absent when the job targets a durable
1075
+ * workflow/agent instead — exactly one of `functionPath` /
1076
+ * {@link ScheduleRecord.workflow} is set, so a view rendering a job's target
1077
+ * must fall back to `workflow` rather than assuming a path.
1078
+ */
1079
+ functionPath?: string;
1080
+ id: string;
1081
+ /** Scheduler/workpool instance the job was enqueued through. Absent for the default instance. */
1082
+ instanceName?: string;
1083
+ /** Logical workpool the job is routed to (concurrency-gated), when any. */
1084
+ pool?: string;
1085
+ /** Per-job retry policy; absent means the scheduler's built-in defaults. */
1086
+ retry?: ScheduleRetryPolicy;
1087
+ scheduledFor: number;
1088
+ shardKey?: string;
1089
+ /**
1090
+ * The workflow/agent class name (its `ctx.exports` key) a fresh durable instance is started from
1091
+ * on fire (the {@link ScheduleRecord.args} become its `params`). Set instead
1092
+ * of {@link ScheduleRecord.functionPath}.
1093
+ */
1094
+ workflow?: string;
1095
+ }
1096
+ /**
1097
+ * One workpool's live backlog, as returned by the worker's
1098
+ * `GET /_lunora/admin/scheduled/status` endpoint. Mirrors `@lunora/scheduler`'s
1099
+ * `SchedulerPoolStatus` structurally so the client carries no dependency on it.
1100
+ */
1101
+ interface SchedulerPoolStatus {
1102
+ /** Jobs currently dispatched-but-not-yet-completed (the held concurrency slots). */
1103
+ inFlight: number;
1104
+ /** The pool's concurrency cap. */
1105
+ maxConcurrency: number;
1106
+ /** The logical workpool name. */
1107
+ name: string;
1108
+ /** Pending jobs routed to this pool but not yet dispatched. */
1109
+ queued: number;
1110
+ }
1111
+ /**
1112
+ * The app-level scheduler backlog, as returned by the worker's
1113
+ * `GET /_lunora/admin/scheduled/status` endpoint. `pools` is the per-pool
1114
+ * breakdown; `backlog` and `inFlight` are the app-wide sums of `queued` and
1115
+ * `inFlight` across every pool — the headline numbers for the studio SLO
1116
+ * view. Mirrors `@lunora/scheduler`'s `SchedulerStatus` structurally.
1117
+ */
1118
+ interface SchedulerStatus {
1119
+ /** Sum of every pool's `queued` count — the total pending backlog. */
1120
+ backlog: number;
1121
+ /** Sum of every pool's `inFlight` count — the total held concurrency slots. */
1122
+ inFlight: number;
1123
+ /** Per-pool backlog breakdown. */
1124
+ pools: SchedulerPoolStatus[];
1125
+ }
1126
+ /**
1127
+ * One shard's request volume, as returned by the worker's
1128
+ * `POST /_lunora/admin/shard-traffic` endpoint. The cross-shard traffic feed
1129
+ * the studio's `hot_shard` advisor lint consumes: `requests` is the shard's
1130
+ * lifetime dispatch total, `shardKey` the DO id name (`""` for the root shard).
1131
+ */
1132
+ interface ShardTrafficEntry {
1133
+ requests: number;
1134
+ shardKey: string;
1135
+ }
1136
+ /**
1137
+ * The whole-shard-set traffic distribution returned by the worker's
1138
+ * `POST /_lunora/admin/shard-traffic` endpoint. `shards` is one entry per live
1139
+ * shard (a failed shard surfaces with `requests: 0`); `ok`/`failed` count the
1140
+ * shards that returned vs. errored. Shaped to feed the advisor's `hot_shard`
1141
+ * lint after the studio tags each entry with its sharded function `group`.
1142
+ */
1143
+ interface ShardTrafficResult {
1144
+ failed: number;
1145
+ ok: number;
1146
+ shards: ShardTrafficEntry[];
1147
+ }
1148
+ /**
1149
+ * One object in the storage bucket, as returned by the worker's
1150
+ * `GET /_lunora/admin/storage` endpoint. Mirrors `@lunora/storage`'s
1151
+ * `R2ObjectLike` structurally.
1152
+ */
1153
+ interface StorageObject {
1154
+ customMetadata?: Record<string, string>;
1155
+ etag: string;
1156
+ httpMetadata?: {
1157
+ contentType?: string;
1158
+ };
1159
+ key: string;
1160
+ size: number;
1161
+ /**
1162
+ * When the object was stored. R2 emits a `Date`, which JSON-serializes to an
1163
+ * ISO string over the wire; a mock may supply epoch ms — so consumers should
1164
+ * normalise via `new Date(uploaded)`. Absent if the backend didn't report it.
1165
+ */
1166
+ uploaded?: number | string;
1167
+ }
1168
+ /** One page of {@link StorageObject}s plus the cursor to fetch the next, if any. */
1169
+ interface StorageListPage {
1170
+ cursor?: string;
1171
+ objects: StorageObject[];
1172
+ }
1173
+ /**
1174
+ * One argument of a registered function, derived from its `v.*` validator by the
1175
+ * worker. A compact signature shape — enough to render a function's API without
1176
+ * the build-time codegen types.
1177
+ */
1178
+ interface FunctionArgumentDescriptor {
1179
+ /** Element validator kind for an `array` arg (one level), e.g. `string`. */
1180
+ element?: string;
1181
+ /** The (optional-unwrapped) validator kind, e.g. `string`, `id`, `object`. */
1182
+ kind: string;
1183
+ /** The argument name. */
1184
+ name: string;
1185
+ /** True when the arg is wrapped in `v.optional(...)`. */
1186
+ optional: boolean;
1187
+ /** True when the arg is marked `v.sensitive` — a secret the caller supplies, never queued offline. */
1188
+ sensitive?: true;
1189
+ /** Target table for an `id` arg (`v.id("table")`). */
1190
+ table?: string;
1191
+ }
1192
+ /**
1193
+ * One registered function, as returned by the worker's
1194
+ * `GET /_lunora/admin/functions` endpoint: its `<file>:<function>` path, which
1195
+ * client method (`query` / `mutation` / `action`) invokes it, and its argument
1196
+ * signature. `args` is absent on responses from an older worker.
1197
+ */
1198
+ interface FunctionDescriptor {
1199
+ args?: FunctionArgumentDescriptor[];
1200
+ kind: "action" | "mutation" | "query";
1201
+ path: string;
1202
+ }
1203
+ /** A `.global()` (D1-backed) table plus its row count, from `/_lunora/admin/global/tables`. */
1204
+ interface GlobalTableInfo {
1205
+ name: string;
1206
+ rowCount: number;
1207
+ }
1208
+ /** A window of rows from one global table, from `/_lunora/admin/global/table`. */
1209
+ interface GlobalTablePage {
1210
+ columns: string[];
1211
+ /** FK columns (local column → referenced table) for external tables with real `REFERENCES` constraints, from `PRAGMA foreign_key_list`. */
1212
+ refs?: Record<string, string>;
1213
+ rows: Record<string, unknown>[];
1214
+ total: number;
1215
+ }
1216
+ /**
1217
+ * One equality constraint a facet-value click adds to the global browser's view
1218
+ * (`column = value`). `value` is the raw stored scalar the facet returned, sent
1219
+ * as-is and bound server-side, so it never injects SQL. The server accepts only
1220
+ * `eq` on a top-level column and rejects `operator` or `path` values it cannot
1221
+ * compile, so the browser never silently gets an equality it did not ask for.
1222
+ */
1223
+ interface GlobalFilterClause {
1224
+ column: string;
1225
+ /** Must be absent or `"eq"`; the server rejects any other operator. */
1226
+ operator?: string;
1227
+ /** Must be absent or empty; the server rejects a nested path. */
1228
+ path?: string[];
1229
+ value: unknown;
1230
+ }
1231
+ /** One distinct value of a faceted global column with its row count, from `/_lunora/admin/global/facet`. */
1232
+ interface GlobalFacetValue {
1233
+ count: number;
1234
+ value: unknown;
1235
+ }
1236
+ /** Per-column distinct-value summary for the global browser, from `/_lunora/admin/global/facet`. */
1237
+ interface GlobalFacetResult {
1238
+ truncated: boolean;
1239
+ values: GlobalFacetValue[];
1240
+ }
1241
+ /** A nullable timestamp field as better-auth serializes it: epoch-ms, ISO string, or null. */
1242
+ type NullableTimestamp = null | number | string;
1243
+ /** A workflow instance's lifecycle status. Mirrors Cloudflare's `InstanceStatus`. */
1244
+ type WorkflowInstanceStatus = "complete" | "errored" | "paused" | "queued" | "rollingBack" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
1245
+ /** The lifecycle mutations the status endpoint accepts. */
1246
+ type WorkflowInstanceAction = "pause" | "restart" | "resume" | "terminate";
1247
+ /** One row of the workflow-instances list. */
1248
+ interface WorkflowInstanceSummary {
1249
+ createdOn?: string;
1250
+ endedOn?: string;
1251
+ id: string;
1252
+ startedOn?: string;
1253
+ status: WorkflowInstanceStatus;
1254
+ }
1255
+ /** One durable step of an instance's execution timeline. */
1256
+ interface WorkflowStepDetail {
1257
+ /** 1-based attempt count (`> 1` means the step retried). */
1258
+ attempts?: number;
1259
+ end?: string;
1260
+ error?: unknown;
1261
+ name: string;
1262
+ output?: unknown;
1263
+ start?: string;
1264
+ success?: boolean;
1265
+ /** `step` / `sleep` / `waitForEvent` / … (Cloudflare's step `type`). */
1266
+ type?: string;
1267
+ }
1268
+ /** A workflow instance's full detail: summary plus params/output/error and the step timeline. */
1269
+ interface WorkflowInstanceDetail extends WorkflowInstanceSummary {
1270
+ error?: unknown;
1271
+ output?: unknown;
1272
+ params?: unknown;
1273
+ steps: WorkflowStepDetail[];
1274
+ }
1275
+ /** A page of workflow instances. */
1276
+ interface WorkflowInstancePage {
1277
+ /**
1278
+ * Whether workflow inspection is configured on the worker (a Cloudflare
1279
+ * account id + API token). `false` when the admin proxy reports it can't
1280
+ * inspect instances; omitted (treated as configured) otherwise. Lets a
1281
+ * caller render a "set credentials" state without a failed request.
1282
+ */
1283
+ configured?: boolean;
1284
+ instances: WorkflowInstanceSummary[];
1285
+ page: number;
1286
+ perPage: number;
1287
+ totalCount?: number;
1288
+ }
1289
+ type SubscriptionCallback = (data: unknown) => void;
1290
+ /**
1291
+ * The high-water marks a shape poke has now synced to the client: `checkpoint`
1292
+ * is the op-log cursor and `mutationId` the highest custom-mutator id the server
1293
+ * echoed for this client. A `@lunora/db` collection feeds these into its
1294
+ * checkpoint registry to drop optimistic overlays once the server's authoritative
1295
+ * rows have landed.
1296
+ */
1297
+ interface SyncWatermark {
1298
+ checkpoint?: number;
1299
+ mutationId?: number;
1300
+ /**
1301
+ * `true` only on the checkpoint a `data`/`delta` frame fires immediately
1302
+ * before that same frame's rowset callback — i.e. the one checkpoint whose
1303
+ * `mutationId` describes rows that are about to arrive.
1304
+ *
1305
+ * A `settled` frame (and a cross-tab `subscription-settled` relay) fires a
1306
+ * checkpoint with NO matching rowset, because the server suppressed a data
1307
+ * frame whose value didn't change. A consumer that stashes `mutationId` for
1308
+ * the next rowset to consume — `@lunora/db`'s `pendingFrameWatermark` — must
1309
+ * not stash those, or the value sits until some later unstamped frame eats
1310
+ * it and the checkpoint gate resolves at a stale watermark instead of
1311
+ * falling back to the RPC-ack compensator.
1312
+ */
1313
+ rowsFollow?: boolean;
1314
+ }
1315
+ /** A subscription-scoped error the server pushed for this subscription id. */
1316
+ interface SubscriptionError {
1317
+ /**
1318
+ * The coded reason, when the frame carried one. `LunoraErrorCodeInput`, not
1319
+ * `LunoraErrorCode`: the catalog codes autocomplete for a consumer branching
1320
+ * on this (the shard sends `BAD_SUBSCRIPTION_ARGS`, `TOO_MANY_SUBSCRIPTIONS`,
1321
+ * `SUBSCRIPTION_PERSIST_FAILED`, …; the client itself adds
1322
+ * `WIRE_DECODE_FAILED` for a frame `decodeWire` refuses), but this value is
1323
+ * read verbatim off the wire and nothing validates it against the catalog,
1324
+ * so narrowing it to `LunoraErrorCode` would be a lie a newer server tells.
1325
+ */
1326
+ code?: LunoraErrorCodeInput;
1327
+ /** The actionable fix text (Markdown), when the frame carried one. */
1328
+ hint?: string | string[];
1329
+ message: string;
1330
+ /** The client-visible explanation of the cause, when the frame carried one. */
1331
+ why?: string;
1332
+ }
1333
+ type SubscriptionErrorCallback = (error: SubscriptionError) => void;
1334
+ /**
1335
+ * One active per-call optimistic transform layered onto a subscription. The
1336
+ * displayed value is the authoritative {@link SubscriptionState.serverBase}
1337
+ * folded through every layer's `transform`, in order — so an incoming server
1338
+ * frame re-folds the still-pending layers onto the new base (rebasing) instead
1339
+ * of clobbering them. A layer is dropped — gaplessly — once a `data`/`delta`
1340
+ * frame whose `cursor >= commitCursor` arrives (its write is now reflected in
1341
+ * `serverBase`); `commitCursor` is the CDC cursor the server echoed on the
1342
+ * mutation's response, and stays `undefined` while the write is still queued/
1343
+ * in-flight (so the overlay survives unrelated deltas until confirmed).
1344
+ */
1345
+ interface OptimisticLayer {
1346
+ /**
1347
+ * Where this write's RPC resolved in the process-wide acknowledgement order
1348
+ * (see `acknowledgementMark`); `undefined` until confirmed. A polled snapshot
1349
+ * carries no cursor, so this is what lets it drop the layer instead.
1350
+ */
1351
+ acknowledgedAt?: number;
1352
+ /** The committed CDC cursor (from the mutation response); `undefined` until confirmed. */
1353
+ commitCursor?: number;
1354
+ readonly id: symbol;
1355
+ readonly transform: (current: unknown) => unknown;
1356
+ }
1357
+ interface SubscriptionState {
1358
+ /**
1359
+ * Where this subscription's `subscribe` frame stands on the current socket:
1360
+ * none outstanding (`"idle"`), sent and not yet answered (`"inflight"`, so a
1361
+ * second subscriber joins it instead of sending another), or acknowledged by
1362
+ * the server (`"acked"`). Written only through {@link setSubscriptionAck}.
1363
+ */
1364
+ ack: "acked" | "idle" | "inflight";
1365
+ readonly args: Record<string, unknown>;
1366
+ /**
1367
+ * Stable wire-key of `args` (`stableWireKey`), computed once at subscribe
1368
+ * time. Cached so the optimistic-update fan-out can compare against a
1369
+ * mutation's args key without re-serializing every subscription's args on
1370
+ * every mutation.
1371
+ */
1372
+ readonly argsKey: string;
1373
+ readonly callbacks: Set<SubscriptionCallback>;
1374
+ /**
1375
+ * Notified when a `settled` frame advances this subscription's watermark — a
1376
+ * write touched the subscription's tables but the result was byte-identical,
1377
+ * so the server suppressed the data frame. A `@lunora/db` list collection
1378
+ * uses this to drop the optimistic overlay for the confirmed write.
1379
+ *
1380
+ * A SET (not a single slot) because `SubscriptionState` is SHARED across
1381
+ * every subscriber to the same `(fn, args, shardKey)`: a `@lunora/db`
1382
+ * collection may subscribe to a query a plain `useQuery` already opened, so
1383
+ * each subscriber registers its own callback (mirroring `callbacks` /
1384
+ * `errorCallbacks`) and a `settled` frame fans out to all of them. Plain
1385
+ * `useQuery` consumers register nothing, leaving the set empty.
1386
+ */
1387
+ readonly checkpointCallbacks: Set<(watermark: SyncWatermark) => void>;
1388
+ /** Notified when the server rejects this subscription (e.g. admin auth). */
1389
+ readonly errorCallbacks: Set<SubscriptionErrorCallback>;
1390
+ readonly fn: FunctionReference;
1391
+ readonly id: string;
1392
+ /**
1393
+ * The highest custom-mutator `mutationId` from this client the server has
1394
+ * applied, captured from the last `settled` frame (the suppressed-list-frame
1395
+ * watermark). Forwarded to {@link SubscriptionState.checkpointCallbacks}.
1396
+ * Absent until a `settled` frame arrives.
1397
+ */
1398
+ lastMutationId?: number;
1399
+ /** Last known value, used to short-circuit `useQuery`-style consumers. */
1400
+ lastValue: unknown;
1401
+ /**
1402
+ * Active per-call optimistic layers, in application order (see
1403
+ * {@link OptimisticLayer}). Empty for subscriptions with no pending per-call
1404
+ * optimistic write — the common case, where `lastValue` tracks `serverBase`
1405
+ * exactly and behaviour is identical to a plain server-value assignment.
1406
+ */
1407
+ optimisticLayers: OptimisticLayer[];
1408
+ /**
1409
+ * The merged value of a delta run whose final, cursor-carrying frame has not
1410
+ * arrived yet. Held aside so a run of k frames commits, notifies and
1411
+ * broadcasts once. Dropped when a snapshot, a `resume`, or a new socket
1412
+ * supersedes the run.
1413
+ */
1414
+ pendingDeltaRun?: {
1415
+ payload: unknown;
1416
+ };
1417
+ /**
1418
+ * The authoritative server value the optimistic layers fold onto — the value
1419
+ * with NO optimistic overlay. Tracks `lastValue` exactly whenever no layers
1420
+ * are active; diverges only while a per-call optimistic write is pending. A
1421
+ * server frame updates this (and re-folds the layers); the durable read cache
1422
+ * persists this, never the optimistic overlay.
1423
+ */
1424
+ serverBase: unknown;
1425
+ /**
1426
+ * The `__cdc_log` high-watermark (`cursor`) the `lastValue` reflects,
1427
+ * captured from the last `data`/`delta`/`resume` frame. Persisted to the
1428
+ * durable read cache and replayed as `sinceSeq` on reconnect so the server
1429
+ * can resume instead of re-snapshotting (Pillar 1b/2). Absent until the
1430
+ * first cursor-stamped frame arrives.
1431
+ */
1432
+ serverCursor?: number;
1433
+ /**
1434
+ * The CDC `epoch` token the `serverCursor` belongs to, captured from the
1435
+ * same frame. Replayed as `sinceEpoch` on reconnect so the server resumes
1436
+ * only when the client is still on the same changelog timeline — a reset or
1437
+ * recycled shard advertises a new epoch, forcing a fresh snapshot. Absent
1438
+ * until the first epoch-stamped frame arrives.
1439
+ */
1440
+ serverEpoch?: string;
1441
+ readonly shardKey?: string;
1442
+ /**
1443
+ * Whether a poll or the leader tab has delivered a value for this subscription on the
1444
+ * CURRENT connection. A polling connection and a follower tab see no server `ack`, so this
1445
+ * is their only evidence of an answer, and `serverBase` cannot stand in for it: a hydrated
1446
+ * cache sets that before anything has arrived. A WebSocket never sets it, `acked` is its
1447
+ * evidence.
1448
+ */
1449
+ valueReceived: boolean;
1450
+ /**
1451
+ * The wire-encoded form of `args`, computed once at `subscribe` time (so an
1452
+ * unsupported value fails loud at the call site, not inside a reconnect's
1453
+ * open handler). Sent on every `subscribe` frame — identical to `args` for
1454
+ * pure JSON, tagged tokens for `bigint`/`Date`/bytes/… (the shard
1455
+ * `decodeWire`s them at its subscribe entry point).
1456
+ *
1457
+ * A SNAPSHOT, not a view: `args` is the caller's own object, retained by
1458
+ * reference and never copied, so a caller that mutates it after subscribing
1459
+ * would otherwise poison every later resubscribe. `encodeWire` rebuilds
1460
+ * every container, so this copy is immune to that.
1461
+ */
1462
+ readonly wireArgs: Record<string, unknown>;
1463
+ }
1464
+ /**
1465
+ * Active subscription registry. The client keys subscriptions by
1466
+ * `(functionPath, stableWireKey(args), shardKey)` so duplicate calls share a
1467
+ * single server-side registration. Args are stably encoded (keys sorted at every
1468
+ * depth) so two structurally-equal arg records constructed with a different key
1469
+ * order (`{ a, b }` vs `{ b, a }`) collapse to the same key instead of leaking a
1470
+ * duplicate subscription. Encoding the args' **wire form** keeps the key
1471
+ * byte-identical for pure-JSON args while giving wire-typed args (`bigint`,
1472
+ * `Date`, bytes, …) distinct stable tokens instead of a throw.
1473
+ */
1474
+ declare class SubscriptionRegistry {
1475
+ static key(functionPath: string, args: Record<string, unknown>, shardKey?: string): string;
1476
+ /**
1477
+ * The registry key of an already-registered state, from its cached
1478
+ * {@link SubscriptionState.argsKey}. Re-deriving it from `state.args` would
1479
+ * re-read the caller's own (mutable) args object, so a caller that mutated
1480
+ * its args after subscribing would compute a DIFFERENT key on unsubscribe
1481
+ * and leak the registration forever.
1482
+ */
1483
+ static keyOf(state: SubscriptionState): string;
1484
+ private readonly byKey;
1485
+ private readonly byId;
1486
+ get(key: string): SubscriptionState | undefined;
1487
+ getById(id: string): SubscriptionState | undefined;
1488
+ add(state: SubscriptionState): void;
1489
+ remove(state: SubscriptionState): void;
1490
+ all(): SubscriptionState[];
1491
+ /**
1492
+ * Drop every registration. Terminal — used by `LunoraClient.close()`, whose
1493
+ * whole point is to release the callback closures each {@link SubscriptionState}
1494
+ * holds (`callbacks`, `errorCallbacks`, `checkpointCallbacks` — React state
1495
+ * setters and `@lunora/db` collection closures), which otherwise outlive the
1496
+ * closed client for as long as the client object is reachable.
1497
+ */
1498
+ clear(): void;
1499
+ }
1500
+ /**
1501
+ * An `Error` carrying the server's machine-readable `code` and (for a
1502
+ * `LunoraError`) structured `data`, plus an optional actionable `hint` (Markdown)
1503
+ * and `docsUrl` resolved from the central error catalog. The client's public
1504
+ * error contract for RPC/batch failures — a UI can render `hint`/`docsUrl` to
1505
+ * tell the user how to fix the error. The `(string & {})` arm keeps
1506
+ * forward-compat/unknown server codes assignable without losing autocomplete on
1507
+ * the known `LunoraErrorCode` union.
1508
+ */
1509
+ type LunoraClientError = Error & {
1510
+ code?: LunoraErrorCode | (string & {});
1511
+ data?: unknown;
1512
+ docsUrl?: string;
1513
+ /**
1514
+ * The headers of the reply this error came from. Set by the RPC, batch and replay paths; absent on
1515
+ * a failure with no reply (a `fetch` that rejected, a timeout) and on the admin and stream paths.
1516
+ */
1517
+ headers?: Readonly<Record<string, string>>;
1518
+ hint?: string | string[];
1519
+ why?: string;
1520
+ };
1521
+ /** One demuxed result slot of a `LunoraClient.batch` call. */
1522
+ type BatchSlot = {
1523
+ error: LunoraClientError | LunoraError;
1524
+ ok: false;
1525
+ } | {
1526
+ ok: true;
1527
+ value: unknown;
1528
+ };
1529
+ /**
1530
+ * Reactive key-value store for local-only client state.
1531
+ *
1532
+ * Unlike a server {@link SubscriptionState} (which tracks a live WS connection,
1533
+ * an `acked` flag, `serverBase`, optimistic layers, and the full subscription
1534
+ * machinery), a `ClientQueryRef` is purely local — no server round-trip, no
1535
+ * WebSocket, no persistence. It exists so framework adapters can offer a
1536
+ * `useClientQuery` hook whose values survive component remounts and are shared
1537
+ * across every consumer of the same ref, with none of the ceremony or coupling
1538
+ * of a dedicated context provider.
1539
+ *
1540
+ * The store lives inside `LunoraClient` (a private field) and is surfaced through
1541
+ * `client.getClientQuery(ref)` / `setClientQuery(ref, value)` /
1542
+ * `subscribeClientQuery(ref, callback)`.
1543
+ */
1544
+ /** Opaque handle for a typed client-local query slot. */
1545
+ interface ClientQueryRef<T = unknown> {
1546
+ /** Default value when no value has been set explicitly. */
1547
+ readonly defaultValue: T;
1548
+ /** Stable identity for the slot. Must be unique within a client instance. */
1549
+ readonly key: string;
1550
+ }
1551
+ /**
1552
+ * Create a typed {@link ClientQueryRef}. Call once per slot at module scope
1553
+ * (or inside a component module) — the ref object is the stable identity.
1554
+ * @example
1555
+ * ```ts
1556
+ * // lunora/client-queries.ts
1557
+ * import { createClientQuery } from "@lunora/client";
1558
+ *
1559
+ * export const sidebarOpen = createClientQuery("sidebarOpen", true);
1560
+ * export const selectedMessageId = createClientQuery("selectedMessageId", undefined as string | undefined);
1561
+ * ```
1562
+ */
1563
+ declare const createClientQuery: <T>(key: string, defaultValue: T) => ClientQueryRef<T>;
1564
+ type WSState = "idle" | "connecting" | "open" | "closed";
1565
+ /**
1566
+ * Aggregate live-socket health across every shard connection, for a UI status
1567
+ * indicator. `idle` = no socket opened yet; `connecting` = at least one socket
1568
+ * is (re)connecting and none is open; `connected` = at least one socket is open;
1569
+ * `polling` = no socket would open, so live queries are being refreshed over HTTP
1570
+ * instead (see `polling-fallback.ts` — live but slower, and shapes
1571
+ * / streams / whispers are dark; mutations go over HTTP as they do while
1572
+ * connected); `offline` = sockets exist but all are down (between reconnect
1573
+ * attempts), and a poll could not reach the origin either.
1574
+ *
1575
+ * `polling` outranks `connecting`: while the fallback is running a reconnect is
1576
+ * still armed in the background, and reporting that attempt would flicker the
1577
+ * indicator between two states while data is in fact arriving on the slow path.
1578
+ */
1579
+ type ConnectionStatus = "connected" | "connecting" | "idle" | "offline" | "polling";
1580
+ /**
1581
+ * Read/write handle over the client's live query cache, handed to a mutation's
1582
+ * `withOptimisticUpdate` callback so a single mutation can optimistically patch
1583
+ * many subscribed queries at once (Convex's `OptimisticLocalStore` model).
1584
+ *
1585
+ * `getQuery` reads the current value (server value or any still-pending
1586
+ * optimistic override) of a subscribed query; `setQuery` registers a constant
1587
+ * optimistic layer on top. The whole batch rebases onto incoming deltas and
1588
+ * settles together — confirmed on the mutation's commit cursor, or rolled back
1589
+ * on failure — the same per-subscription layer machinery the single-query
1590
+ * per-call `optimistic` transform uses, generalized to N queries.
1591
+ */
1592
+ interface OptimisticLocalStore {
1593
+ /**
1594
+ * Every loaded subscription on `function_`, regardless of args, paired with
1595
+ * the args it was subscribed under. Mirrors Convex's `getAllQueries` — handy
1596
+ * when a write must patch every variant of a list query (all channels,
1597
+ * all filters) without enumerating their args up front.
1598
+ */
1599
+ getAllQueries: <F extends FunctionReference>(function_: F) => {
1600
+ args: ArgsOf<F>;
1601
+ value: ReturnOf<F> | undefined;
1602
+ }[];
1603
+ /**
1604
+ * Current cached value for the subscribed `(function_, args)` query, or
1605
+ * `undefined` when nothing is subscribed/loaded for it. Reflects any
1606
+ * optimistic override already written in this batch.
1607
+ */
1608
+ getQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>) => ReturnOf<F> | undefined;
1609
+ /**
1610
+ * Write an optimistic override for the subscribed `(function_, args)`
1611
+ * query. A no-op (returns without effect) when no subscription matches —
1612
+ * mirroring Convex, where you only patch queries the page is watching.
1613
+ */
1614
+ setQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>, value: ReturnOf<F> | undefined) => void;
1615
+ }
1616
+ /** A mutation's multi-query optimistic update: read/write the cache via `localStore`. */
1617
+ type OptimisticUpdate<Args> = (localStore: OptimisticLocalStore, args: Args) => void;
1618
+ /**
1619
+ * Build an {@link OptimisticLocalStore} bound to a subscription registry and the
1620
+ * mutation's shard key. Each `setQuery(value)` registers a constant-value layer
1621
+ * on its target subscription (via `applyOptimisticLayer`): the predicted value
1622
+ * survives incoming server deltas (re-clamped, masking concurrent changes to that
1623
+ * query — not merged) and drops gaplessly on the mutation's commit cursor, like
1624
+ * the single-query per-call `optimistic` path. Returns the store plus the ordered
1625
+ * `confirm` (success) and `rollback` (failure) closures every `setQuery` produced,
1626
+ * so the caller settles the whole batch when the mutation does.
1627
+ */
1628
+ declare const createLocalStore: (subscriptions: SubscriptionRegistry, shardKey: string | undefined) => {
1629
+ confirms: ((commitCursor: number | undefined) => void)[];
1630
+ rollbacks: (() => void)[];
1631
+ store: OptimisticLocalStore;
1632
+ };
1633
+ /** Callback a shape subscription invokes with its materialized rowset on every applied poke. */
1634
+ type ShapeCallback = (rows: Record<string, unknown>[]) => void;
1635
+ declare const DEFAULT_MAX_BUFFER = 1024;
1636
+ interface StreamHandle<T = unknown> {
1637
+ /** Mark the stream complete (no more chunks); resolves any pending consumer to `done:true`. */
1638
+ readonly complete: () => void;
1639
+ /** Surface an error to any pending consumer; subsequent pushes are dropped. */
1640
+ readonly fail: (error: Error) => void;
1641
+ /**
1642
+ * Push one chunk. Silent no-op once the stream is `complete`, `fail`-ed,
1643
+ * or `cancel`-ed. When the buffer is already at `maxBuffer`, the stream
1644
+ * is failed with a `STREAM_BACKPRESSURE` error and the push is dropped —
1645
+ * the producer never sees a thrown exception.
1646
+ */
1647
+ readonly push: (value: T) => void;
1648
+ }
1649
+ interface StreamIterable<T> extends AsyncIterable<T> {
1650
+ /** Cancel the stream from the consumer side: closes the iterator and notifies the registered canceller. */
1651
+ cancel: () => void;
1652
+ }
1653
+ /**
1654
+ * Build a stream handle paired with an async-iterable. The handle is the
1655
+ * server-driven side (the WS dispatcher pushes chunks / completes / errors);
1656
+ * the iterable is what the user awaits. `onCancel` is invoked exactly once
1657
+ * when the consumer calls `.cancel()` (or `.return()`) so the client can
1658
+ * send a `{type:"unsubscribe"}` frame to the server.
1659
+ */
1660
+ declare const createStream: <T>(options: {
1661
+ maxBuffer?: number;
1662
+ onCancel: () => void;
1663
+ /** Invoked once the stream is failed, so a producer can stop feeding it. */
1664
+ onFail?: () => void;
1665
+ }) => {
1666
+ handle: StreamHandle<T>;
1667
+ iterable: StreamIterable<T>;
1668
+ };
1669
+ /** One shard's socket + watermark state in a {@link LunoraClient.debug} snapshot. */
1670
+ interface ClientDebugShard {
1671
+ /**
1672
+ * Highest custom-mutator watermark the server has echoed for this client on this
1673
+ * shard. A write whose `clientSeq` is above this has been sent but not confirmed
1674
+ * — the first thing to check when an optimistic overlay won't clear.
1675
+ */
1676
+ confirmedMutationWatermark: number;
1677
+ /** Whether a `WebSocket` object currently exists (distinct from it being open). */
1678
+ hasSocket: boolean;
1679
+ /** `undefined` for the default (unsharded) connection. */
1680
+ shardKey: string | undefined;
1681
+ /** Whether this shard's socket has ever completed a handshake — gates offline queueing. */
1682
+ wasEverConnected: boolean;
1683
+ wsState: WSState;
1684
+ }
1685
+ /** One live query or shape subscription in a {@link LunoraClient.debug} snapshot. */
1686
+ interface ClientDebugSubscription {
1687
+ /** Whether the server has acknowledged the subscription on the current socket. */
1688
+ acked: boolean;
1689
+ /** `namespace:fn` for a query, `shape:<name>` for a replication shape. */
1690
+ functionPath: string;
1691
+ id: string;
1692
+ kind: "query" | "shape";
1693
+ /** Highest custom-mutator watermark echoed on THIS subscription (absent until a `settled`/poke frame arrives). */
1694
+ lastMutationId?: number;
1695
+ /** Per-call optimistic layers still folded onto this subscription's value — a non-zero count with no pending write is a leak. */
1696
+ pendingOptimisticLayers: number;
1697
+ /** Replicated rowset size (shapes only). */
1698
+ rowCount?: number;
1699
+ /** The `__cdc_log` cursor the current value reflects. */
1700
+ serverCursor?: number;
1701
+ shardKey: string | undefined;
1702
+ /** How many callers share this subscription (subscriptions are deduped by `(fn, args, shard)`). */
1703
+ subscriberCount: number;
1704
+ }
1705
+ /**
1706
+ * Everything the sync engine believes at one instant — see
1707
+ * {@link LunoraClient.debug} for why this exists.
1708
+ */
1709
+ interface ClientDebugSnapshot {
1710
+ /** The watermark key the server's custom-mutator protocol advances per `clientSeq`. */
1711
+ clientId: string;
1712
+ closed: boolean;
1713
+ connectionStatus: ConnectionStatus;
1714
+ /** Writes waiting in the built-in offline queue (not the `@lunora/db` outbox). */
1715
+ pendingWrites: number;
1716
+ shards: ClientDebugShard[];
1717
+ subscriptions: ClientDebugSubscription[];
1718
+ }
1719
+ /**
1720
+ * Whether the client is actually caught up, which `connectionStatus()` alone cannot
1721
+ * say: it reads `"connected"` as soon as any socket is open, though a subscription
1722
+ * on it may not have been acknowledged yet (it has no data) and writes may still be
1723
+ * waiting in the offline queue. See {@link LunoraClient.syncStatus}.
1724
+ */
1725
+ interface SyncStatus {
1726
+ /** The aggregate socket status, as {@link LunoraClient.connectionStatus} reports it. */
1727
+ connection: ConnectionStatus;
1728
+ /** Live queries and shapes the server has not answered yet on the current connection. */
1729
+ pendingSubscriptions: number;
1730
+ /** Writes queued or being replayed from the built-in offline queue (not the `@lunora/db` outbox). */
1731
+ pendingWrites: number;
1732
+ /** `true` only on a live connection with every subscription answered and no write queued. */
1733
+ synced: boolean;
1734
+ }
1735
+ /**
1736
+ * Terminal verdict for a mutation that passed through the offline queue,
1737
+ * delivered to {@link LunoraClient.onMutationSettled}.
1738
+ *
1739
+ * Unlike the Promise returned by {@link LunoraClient.mutation} — which only the
1740
+ * original caller can await, and which no longer exists after a reload — this
1741
+ * fires for *every* queued write the server (or the queue) reaches a verdict on,
1742
+ * including writes restored from durable storage in a later session. It is the
1743
+ * channel a UI uses to tell the user "your queued change couldn't be saved"
1744
+ * instead of silently dropping a rolled-back optimistic row.
1745
+ *
1746
+ * `status: "rejected"` carries the failure `code` (e.g. `CONFLICT`,
1747
+ * `OFFLINE_QUEUE_OVERFLOW`, `OFFLINE_IDENTITY_CHANGED`) and the `error`.
1748
+ * `hadAwaiter` is `false` for a write whose original `mutation()` Promise is
1749
+ * gone (a hydrated/post-reload replay or an eviction), so a listener can tell
1750
+ * "the caller already saw this" apart from "nothing else will report this".
1751
+ */
1752
+ interface MutationSettledEvent {
1753
+ /** The write's args, so a listener can describe or re-offer the change. */
1754
+ readonly args: Record<string, unknown>;
1755
+ /**
1756
+ * Server/queue error code on `rejected` (e.g. `CONFLICT`), when present —
1757
+ * or `WIRE_DECODE_FAILED` on a `committed` write whose result could not be
1758
+ * decoded.
1759
+ */
1760
+ readonly code?: string;
1761
+ /** The rejection error on `status: "rejected"`, or the decode error of a `committed` write whose result could not be read. */
1762
+ readonly error?: unknown;
1763
+ /** The `<file>:<function>` reference of the mutation. */
1764
+ readonly functionPath: string;
1765
+ /** Whether a live caller was still awaiting this write's `mutation()` Promise. */
1766
+ readonly hadAwaiter: boolean;
1767
+ /** The write's stable id (idempotency key / queue id). */
1768
+ readonly id: string;
1769
+ /** Shard the write targeted, if any. */
1770
+ readonly shardKey?: string;
1771
+ /** Terminal outcome. */
1772
+ readonly status: "committed" | "rejected";
1773
+ }
1774
+ /**
1775
+ * Per-call options for {@link LunoraClient.action} — just `shardKey`, since an
1776
+ * action is not a write and carries none of the optimistic machinery. Exported
1777
+ * (at the end of this file) for the same reason {@link MutationCallOptions} is:
1778
+ * so the framework adapters (`@lunora/react`, `/solid`, `/svelte`, `/vue`,
1779
+ * `/angular`) type their `call(args, options?)` against one canonical
1780
+ * definition. Add an option here and every adapter forwards it; re-declare it
1781
+ * per adapter and they silently cannot.
1782
+ */
1783
+ interface ActionCallOptions {
1784
+ /** Route the call to a specific shard. */
1785
+ shardKey?: string;
1786
+ /**
1787
+ * Abort the call. The request is cancelled and the promise rejects with the
1788
+ * signal's reason (an `AbortError` by default). The server may already have
1789
+ * started — or finished — the action, which is not transactional, so an abort
1790
+ * releases the caller; it does not undo the work.
1791
+ */
1792
+ signal?: AbortSignal;
1793
+ }
1794
+ /**
1795
+ * Per-call options for {@link LunoraClient.mutation} — the optimistic-update
1796
+ * machinery plus `shardKey`. Exported (at the end of this file) so the framework
1797
+ * adapters (`@lunora/react`, `/solid`, `/svelte`, `/vue`) can type their
1798
+ * `mutate(args, options?)` against one canonical definition instead of
1799
+ * re-declaring it.
1800
+ */
1801
+ interface MutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unknown> {
1802
+ /**
1803
+ * Override the auto-generated idempotency key (`x-lunora-mutation-id`). Lets a
1804
+ * durable outbox replay a committed-but-unacked write under its *original* key
1805
+ * so the server dedups it instead of applying it twice. Omit for normal calls —
1806
+ * each then gets a fresh key.
1807
+ */
1808
+ mutationId?: string;
1809
+ /**
1810
+ * Never queue, persist or replay this write. When the shard's connection is
1811
+ * down or reconnecting — the states in which a normal write is queued — the
1812
+ * call rejects at once with `OFFLINE_NOT_QUEUED`, and its args never reach the
1813
+ * offline queue, the persistence adapter or the outbox. Use it for a write whose
1814
+ * arguments must not sit on disk: a credential a person typed in, a one-time
1815
+ * token. A function with a `v.sensitive` argument is always online-only, whatever
1816
+ * this option says: the client forces it on, and `false` is refused.
1817
+ *
1818
+ * Ordering: an online-only call neither waits for a queue flush nor queues
1819
+ * behind writes already queued for its shard. When it is sent it can overtake
1820
+ * them, so it may land on the server before an older queued write to the same
1821
+ * document. Optimistic layers are in-memory and are not applied to a refused call.
1822
+ *
1823
+ * Omit for normal calls, which queue as usual.
1824
+ */
1825
+ onlineOnly?: boolean;
1826
+ /**
1827
+ * Single-query shortcut: the transform is layered onto the subscription
1828
+ * registered under **this write's own** `(functionPath, args, shardKey)`, and
1829
+ * nothing else. A client cannot know which queries a write affects, so the
1830
+ * targeting rule is "same reference, same args" — which makes this the
1831
+ * shorthand for a query and a mutation that share a path (a counter, a
1832
+ * document by id), and a silent no-op for anything else.
1833
+ *
1834
+ * **The general case — a `messages:send` mutation patching a `messages:list`
1835
+ * query — is {@link MutationCallOptions.optimisticUpdate}**, whose store names
1836
+ * its targets. Reach for that whenever the mutation and the query are
1837
+ * different functions, which is nearly always.
1838
+ *
1839
+ * The transform must be pure: it re-runs on every server frame while the write
1840
+ * is pending, so derive from `current` rather than closing over a value.
1841
+ */
1842
+ optimistic?: (current: TCurrent | undefined) => TValue;
1843
+ /**
1844
+ * Convex-parity multi-query optimistic update. Receives an
1845
+ * `OptimisticLocalStore` over the live subscription cache plus the
1846
+ * mutation's args, so one mutation can patch many subscribed queries at
1847
+ * once; every write is rolled back atomically if the mutation fails.
1848
+ */
1849
+ optimisticUpdate?: OptimisticUpdate<TArgs>;
1850
+ /**
1851
+ * Sync predicate evaluated just before the offline queue replays this
1852
+ * write on reconnect. When it returns `false` the mutation is dropped
1853
+ * instead of replayed — use it to guard against replaying writes whose
1854
+ * assumptions are no longer valid (e.g. the document it referred to was
1855
+ * deleted by another client while this tab was offline).
1856
+ */
1857
+ precondition?: () => boolean;
1858
+ /**
1859
+ * Pin this call's `.dropStalePatches()` baseline instead of sampling the
1860
+ * client's current view — the durable-replay counterpart to
1861
+ * {@link MutationCallOptions.mutationId}. See
1862
+ * {@link import("./types").OutboxMutation.baselineSeq} for why a replay must
1863
+ * hand back the cursor it was composed at.
1864
+ *
1865
+ * Tri-state, the same shape (and for the same reason) as the `identity` stamp
1866
+ * a queued write carries: `undefined` samples the current cursor, `null` pins
1867
+ * "composed with no baseline", and a number pins that cursor. A plain
1868
+ * `number | undefined` could not express the middle case, so every write
1869
+ * queued without a live subscription would have re-derived.
1870
+ *
1871
+ * Omit for normal calls.
1872
+ */
1873
+ replayBaseline?: null | number;
1874
+ /**
1875
+ * The credential a durable replay was judged under — the one
1876
+ * {@link LunoraClient.replayIdentityVerdict} returns with a `"match"`. The
1877
+ * request is sent with exactly the bearer that verdict was judged against,
1878
+ * never the live one: a `setAuthToken` landing between the verdict and the
1879
+ * send would otherwise put a write judged as one user's on the next user's
1880
+ * bearer, and a bearer request carries no subject for the worker to refuse it
1881
+ * on. Under a cookie session the request also names the user the write was
1882
+ * queued by, and the worker refuses it with `IDENTITY_MISMATCH` when the
1883
+ * cookie now belongs to someone else — the check the client cannot make,
1884
+ * because it cannot see the cookie.
1885
+ *
1886
+ * Single use, and only valid on the client that issued it. A replay refused
1887
+ * for its credential (`UNAUTHENTICATED` / `TOKEN_EXPIRED`) fires {@link LunoraClient.onTokenExpired} once per credential, and only
1888
+ * while that credential is still the current one. Omit for normal calls,
1889
+ * which always send the live token.
1890
+ */
1891
+ replayCredential?: ReplayCredential;
1892
+ shardKey?: string;
1893
+ /**
1894
+ * Stop waiting for the mutation. The promise rejects with the signal's reason
1895
+ * (an `AbortError` by default), and nothing is sent when the signal is already
1896
+ * aborted. A write already on the wire or in the offline queue is NOT
1897
+ * retracted: it still commits or replays on its own, and its optimistic patch
1898
+ * is settled by that outcome — an abort releases the caller, not the write.
1899
+ */
1900
+ signal?: AbortSignal;
1901
+ }
1902
+ declare const replayCredentialBrand: unique symbol;
1903
+ /**
1904
+ * Opaque proof that a durable write was judged replayable, bound to the
1905
+ * credential it was judged under. Issued only by
1906
+ * {@link LunoraClient.replayIdentityVerdict}; pass it to
1907
+ * {@link MutationCallOptions.replayCredential}.
1908
+ */
1909
+ interface ReplayCredential {
1910
+ readonly [replayCredentialBrand]: true;
1911
+ }
1912
+ /** {@link LunoraClient.replayIdentityVerdict}'s answer: a `"match"` carries the credential the replay must be sent with. */
1913
+ type ReplayIdentityVerdict = {
1914
+ credential: ReplayCredential;
1915
+ verdict: "match";
1916
+ } | {
1917
+ verdict: "mismatch";
1918
+ } | {
1919
+ verdict: "unknown";
1920
+ };
1921
+ /**
1922
+ * Lunora browser/edge client. Talks RPC over HTTP and real-time deltas over
1923
+ * a single multiplexed WebSocket.
1924
+ *
1925
+ * Reconnect, offline queueing, and optimistic updates are all handled here;
1926
+ * see the package README for the wire protocol.
1927
+ */
1928
+ declare class LunoraClient {
1929
+ /** Hard cap on concurrently-buffered pokes — a backstop that reclaims buffers abandoned by a mid-poke disconnect (no `pokeEnd`). Far above any real concurrent-in-flight count. */
1930
+ private static readonly MAX_POKE_BUFFERS;
1931
+ /**
1932
+ * Create a typed {@link ClientQueryRef}. Convenience wrapper around
1933
+ * {@link createClientQuery} so you don't need a separate import.
1934
+ * @example
1935
+ * ```ts
1936
+ * const sidebarOpen = LunoraClient.createClientQuery("sidebarOpen", true);
1937
+ * ```
1938
+ */
1939
+ static createClientQuery<T>(key: string, defaultValue: T): ClientQueryRef<T>;
1940
+ readonly url: string;
1941
+ readonly wsUrl: string;
1942
+ /** The admin modules reach the client only through this host. The arrows read `this` when called, so spies and overrides installed after construction still take effect. */
1943
+ protected readonly adminHost: AdminHost;
1944
+ /** Local reactive store for {@link ClientQueryRef} values — no server round-trip. Private; reach it via `getClientQuery` / `setClientQuery` / `subscribeClientQuery`. */
1945
+ private readonly clientQueryStore;
1946
+ /** The session credential, sent in the `connect` frame and never in the URL (protocol §6). */
1947
+ private wsToken;
1948
+ /** The short-lived ticket appended to the upgrade URL as `?token=` (protocol §6). */
1949
+ private wsTicket;
1950
+ /** Bumped on every `setWsToken` / `setWsTicket` change: a provider request started under an older value is superseded. */
1951
+ private wsCredentialGeneration;
1952
+ /** The credential generation the server last refused with 4003, so that refusal notifies once. */
1953
+ private refusedCredentialGeneration;
1954
+ /** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
1955
+ private readonly authBasePath;
1956
+ private readonly fetchImpl;
1957
+ private readonly WebSocketImpl;
1958
+ private readonly bookmark;
1959
+ private readonly reconnectOptions;
1960
+ /** WS connect timeout (ms); `0` disables it. See {@link LunoraClientOptions.connectTimeoutMs}. */
1961
+ private readonly connectTimeoutMs;
1962
+ /** Keepalive cadence (ms); `0` disables the heartbeat. See {@link LunoraClientOptions.heartbeatIntervalMs}. */
1963
+ private readonly heartbeatIntervalMs;
1964
+ /** Deadline (ms) for one HTTP RPC round trip; `0` disables it. See {@link LunoraClientOptions.rpcTimeoutMs}. */
1965
+ private readonly rpcTimeoutMs;
1966
+ /** The socket-lifecycle inputs, built once after the constructor assigns them (none is reassigned later). */
1967
+ private readonly managedSocketOptions;
1968
+ /** Failed-open run that engages the HTTP polling fallback; `0` disables it. */
1969
+ private readonly pollingFallbackAfterFailedAttempts;
1970
+ /** Polling-fallback cadence (ms); `0` disables it. See {@link LunoraClientOptions.pollingFallback}. */
1971
+ private readonly pollingFallbackIntervalMs;
1972
+ /** See {@link LunoraClientOptions.authTokenOnUpgrade}. */
1973
+ private readonly authTokenOnUpgrade;
1974
+ private readonly offlineQueue;
1975
+ /**
1976
+ * Durable outbox seam (the `@lunora/db` `createExecutorOutboxSink`). When
1977
+ * set, offline writes are delegated here and the built-in {@link OfflineQueue}
1978
+ * is bypassed, so a db app has exactly one durable write path.
1979
+ */
1980
+ private readonly outbox;
1981
+ /** Stable per-client id stamped onto every `OutboxMutation` (custom-mutator watermark). */
1982
+ private readonly clientId;
1983
+ /**
1984
+ * Highest CDC cursor this client has seen a write commit at, per shard key
1985
+ * (`""` for the default shard) — the read-your-writes bookmark sent as
1986
+ * `x-lunora-min-seq`.
1987
+ *
1988
+ * In memory only, and deliberately: it exists to keep THIS session's reads
1989
+ * behind THIS session's writes. Persisting it across reloads would pin a
1990
+ * fresh page to a cursor it has no reason to require and force needless
1991
+ * fallbacks to the owner.
1992
+ */
1993
+ private readonly shardCursors;
1994
+ /**
1995
+ * The server's own name for the default shard (`defaultShardKey`), learned
1996
+ * from the first response to a call that named no shard. `undefined` until
1997
+ * then, which is why `cursorKeyFor` falls back to a placeholder entry that
1998
+ * `learnDefaultShardKey` folds in once the name arrives.
1999
+ */
2000
+ private defaultShardKey;
2001
+ /**
2002
+ * `true` when the constructor's hydration microtask has finished loading the
2003
+ * durable read cache (Pillar 2) into `hydratedQueryCache`. Signals that
2004
+ * the cache is ready for synchronous `peekHydratedQuery` reads.
2005
+ */
2006
+ private readyResolved;
2007
+ /** Resolvers for `whenReady()` — called once hydration completes. */
2008
+ private readyResolve;
2009
+ /**
2010
+ * Promise that resolves once the durable read cache has been loaded. When
2011
+ * `hydrateOnStart` is not set or no query cache is configured, resolves
2012
+ * immediately (the constructor creates an already-resolved promise).
2013
+ */
2014
+ private readonly readyPromise;
2015
+ /**
2016
+ * Highest custom-mutator watermark the server has echoed for this client,
2017
+ * nested by identity fingerprint (`identityFingerprint() ?? ""`) then shard
2018
+ * bucket (`shardKey ?? ""`) — the DO tracks one `__client_watermark` per
2019
+ * `(identity, clientId)` pair, not per bucket alone, so a bucket-only key
2020
+ * would let a user switch claim the previous identity's sequence and wedge
2021
+ * every push on `OUT_OF_ORDER` until a reload (plan 316). A nested map
2022
+ * (rather than a single map composite-keyed by a joined string) is what a
2023
+ * previous fix here tried and got wrong: an identity fingerprint or a
2024
+ * `shardKey` is an arbitrary string, so any string delimiter — even one as
2025
+ * exotic as U+FFFD — can appear in one operand and collide with the other
2026
+ * (a fingerprint of `a<SEP>x` + bucket `y` joins to the same string as
2027
+ * a fingerprint of `a` + bucket `x<SEP>y`), mixing two identities' watermarks.
2028
+ * The nested map has no join step, so there is no delimiter to collide.
2029
+ * `callMutator` bumps it from every ack; the `@lunora/db` mutator runtime
2030
+ * seeds its `clientSeq` generator from it so a reload (which resets the
2031
+ * in-memory counter) never reissues a stale sequence the server would
2032
+ * silently swallow as a replay.
2033
+ */
2034
+ private readonly clientWatermarks;
2035
+ /** Monotonic per-client mutation counter backing the server `__client_watermark`. */
2036
+ private outboxMutationCounter;
2037
+ /** Orders offline-queued writes by when they were issued; see {@link QueuedMutation.issueSeq}. */
2038
+ private mutationIssueCounter;
2039
+ private readonly persistence;
2040
+ /** App/schema version stamped on persisted writes + cached reads; mismatches are purged. */
2041
+ private readonly persistenceVersion;
2042
+ /** Removes the page-hide flush listeners on close (see `installPageHideFlush`). */
2043
+ private releasePageHideFlush;
2044
+ /** Releases the multi-tab outbox-leader Web Lock on close (see `hydrateAsOutboxLeader`). */
2045
+ private outboxLeaderRelease;
2046
+ /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
2047
+ private readonly queryCache;
2048
+ /**
2049
+ * Values restored from the `queryCache` at construction, keyed by the
2050
+ * read-cache key, awaiting the `subscribe()` that will consume them. A
2051
+ * key is consumed (deleted) the first time its subscription is created, so
2052
+ * the cache only ever seeds the initial value — live frames take over after.
2053
+ */
2054
+ private readonly hydratedQueryCache;
2055
+ /**
2056
+ * The read-cache entries currently ON DISPLAY in a live subscription, by the
2057
+ * same key — every entry consumed out of `hydratedQueryCache` and not yet
2058
+ * overwritten by a server frame.
2059
+ *
2060
+ * Gating the cache at read time only protects a value not handed over YET.
2061
+ * A credential can change while a cached value is already on screen (the
2062
+ * account-switch shape: an established subject, a token it was never checked
2063
+ * against), and the fingerprint does not move with it — so nothing else
2064
+ * would notice. `revokeCacheSeededValues` takes those values back off
2065
+ * screen and returns the entries to `hydratedQueryCache`, where the ordinary
2066
+ * identity gate decides whether they may ever be shown again.
2067
+ */
2068
+ private readonly cacheSeededQueries;
2069
+ /**
2070
+ * Coalesced read-cache writes: the latest value per key, flushed to
2071
+ * the `queryCache` on a short debounce so a burst of deltas persists once.
2072
+ */
2073
+ private readonly pendingCacheWrites;
2074
+ private cacheFlushTimer;
2075
+ private readonly subscriptions;
2076
+ /**
2077
+ * Cross-tab coordinator; created only when `crossTabSync: true`. When the
2078
+ * client is not the elected leader, all WebSocket operations are skipped.
2079
+ * Not `readonly` — `close()` clears it (mirrors `outboxLeaderRelease`).
2080
+ */
2081
+ private tabCoordinator;
2082
+ /**
2083
+ * The leader's last-broadcast aggregate {@link ConnectionStatus}, mirrored
2084
+ * on a follower tab — which owns no `ShardConnection` of its own to
2085
+ * compute a status from (see `computeStatus`). `undefined` until the
2086
+ * leader's first broadcast (falls back to `"idle"`), and reset back to
2087
+ * `undefined` whenever this tab stops being a follower of the CURRENT
2088
+ * leader (becomes leader itself, or the leader changes), so a stale
2089
+ * mirror from a previous leader never survives a leadership change.
2090
+ */
2091
+ private readonly leader;
2092
+ /** One {@link ShardConnection} per shard key (keyed by `shardKey ?? ""`). */
2093
+ private readonly connections;
2094
+ /**
2095
+ * Shards whose socket was closed for being idle after it had connected (see
2096
+ * {@link LunoraClient.releaseIdleShard}). The connection record is gone, but the write
2097
+ * gate still needs to know the shard was reached — see `connectionGateState`.
2098
+ * Consumed when the shard's connection is recreated.
2099
+ */
2100
+ private readonly idleClosedShards;
2101
+ /** Default `connect`-envelope context applied to a shard with no explicit override. */
2102
+ private readonly defaultConnectionContext;
2103
+ /**
2104
+ * Per-shard `connect`-envelope context registered via `setConnectionContext`
2105
+ * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
2106
+ * on every socket open so it replays across reconnects, and forwarded to the
2107
+ * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
2108
+ * imperative (last-writer-wins) override; refcounted holders registered via
2109
+ * `acquireConnectionContext` live in `connectionContextHolders` and take
2110
+ * precedence — see `effectiveConnectionContext`.
2111
+ */
2112
+ private readonly connectionContexts;
2113
+ /**
2114
+ * Per-shard stack of refcounted connection-context holders (keyed by
2115
+ * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
2116
+ * is an opaque token carrying its `context`; the most-recently acquired
2117
+ * holder wins (last-writer-wins among live holders), and the context is only
2118
+ * cleared for a shard once its last holder releases — so two concurrently
2119
+ * mounted presence hooks on the same shard can't stomp each other's context
2120
+ * on cleanup. A holder is identified by reference identity so a release
2121
+ * removes exactly the right one regardless of stack position.
2122
+ */
2123
+ private readonly connectionContextHolders;
2124
+ private authToken;
2125
+ /** Hash of the current bearer, keyed on the token so a new token misses once. `setAuthToken` drops it on every change, so a replaced or signed-out bearer is not retained. */
2126
+ private tokenFingerprint;
2127
+ /**
2128
+ * Optional STABLE identity subject (a user id), the basis of the offline-queue
2129
+ * identity stamp when supplied. Keeps a same-user token *refresh* from looking
2130
+ * like an identity change (which would discard queued writes). `undefined` =
2131
+ * not supplied, so identity falls back to a hash of the raw token. See
2132
+ * `setAuthToken` / `identityFingerprint`.
2133
+ */
2134
+ private authSubject;
2135
+ /**
2136
+ * The bearer token `authSubject` was last asserted against. A subject
2137
+ * is a claim about WHO a specific credential belongs to; once the token
2138
+ * rotates, the sticky label is carried forward on the assumption it is the
2139
+ * same user — but nothing has confirmed that yet, and the alternative (an
2140
+ * account switch) would replay one user's queued writes as another. While
2141
+ * this is out of step with `authToken` the identity counts as unconfirmed
2142
+ * and every replay verdict is `"unknown"` (hold), until the next session
2143
+ * resolve re-asserts the subject. Only used when a subject is established;
2144
+ * a token-hash identity is self-confirming.
2145
+ */
2146
+ private subjectToken;
2147
+ /**
2148
+ * How many `getCurrentUser()` round trips are in flight.
2149
+ *
2150
+ * The identity gates need to tell two `null` fingerprints apart. For an app
2151
+ * with no auth at all, and for a client the server has answered "no
2152
+ * session" to, `null` is a real and stable identity — nobody else holds it,
2153
+ * so a `null`-stamped queued write or cached read is this client's own and
2154
+ * may be used. While a resolve is IN FLIGHT it is neither: the fingerprint
2155
+ * may be one round trip away from `subj:<id>`, which is the window a cookie
2156
+ * app spends every page load in, and where `null === null` handed one
2157
+ * browser user's durable state to the next. Counted rather than flagged so
2158
+ * two overlapping resolves (a token change during a probe) both have to
2159
+ * finish before the gates reopen.
2160
+ */
2161
+ private sessionProbesInFlight;
2162
+ /**
2163
+ * Monotonic id stamped on each `/get-session` round trip, so only the
2164
+ * NEWEST one may write the shared identity.
2165
+ *
2166
+ * `adoptResolvedSubject`'s token check asks whether the credential the
2167
+ * answer is about is still the one in hand. On a cookie app there is no
2168
+ * credential to ask about: every probe captures `requestToken === null`, so
2169
+ * two overlapping probes both pass it and whichever lands LAST wins —
2170
+ * including an older one, which then replaces the subject a newer answer
2171
+ * already established. Comparing the generation instead asks the question
2172
+ * the token cannot: is this still the current question?
2173
+ */
2174
+ private sessionProbeGeneration;
2175
+ /**
2176
+ * Monotonic id of every question this client asks the server about who it
2177
+ * is: each `/get-session` probe, and each cookie-authenticated socket upgrade
2178
+ * (answered by the `identity` frame the shard sends on `connect`). Probes
2179
+ * take their `sessionProbeGeneration` from it, so both kinds of
2180
+ * answer share one order.
2181
+ */
2182
+ private identityQuestions;
2183
+ /**
2184
+ * The `identityQuestions` id of the newest answer adopted so far. A
2185
+ * cookie-session answer older than it describes an older cookie — a socket
2186
+ * upgraded before a probe that has since answered — and may not move the
2187
+ * identity back. See `adoptCookieSubject`.
2188
+ */
2189
+ private identityAnsweredAt;
2190
+ /** Unregisters this client from the page's session-change signal (`shared/session-change.ts`); set in the constructor. */
2191
+ private releaseSessionChangeListener;
2192
+ /** Whether the one-time `IDENTITY_MISMATCH` configuration warning has been logged (see `noteIdentityMismatch`). */
2193
+ private warnedIdentityDisagreement;
2194
+ /**
2195
+ * Whether anything resolves this client's identity at all.
2196
+ *
2197
+ * The gates need to tell an app with NO AUTH — whose `null` fingerprint is
2198
+ * settled forever and shared with nobody — from a cookie app that simply
2199
+ * has not asked yet. Nothing in the client's own configuration says which
2200
+ * it is (`authBasePath` has a default), so the answer is declared: a
2201
+ * `getCurrentUser()` call, or `@lunora/client/auth`'s identity store
2202
+ * attaching itself, is what makes `null` provisional. An app that does
2203
+ * neither keeps its read cache and its offline queue exactly as before.
2204
+ */
2205
+ private identityResolutionExpected;
2206
+ /**
2207
+ * Whether a `/get-session` round trip has ever produced an ANSWER — a user,
2208
+ * or an explicit "no session". Distinct from `sessionProbesInFlight`, which
2209
+ * only covers the request's own lifetime and so reopened the gates both
2210
+ * before the first probe started and after one failed to answer, leaving a
2211
+ * `null` fingerprint free to match the previous cookie user's cached rows
2212
+ * and queued writes in exactly the window the probe count was added to
2213
+ * close. A transport or parse failure never sets this: it learned nothing.
2214
+ */
2215
+ private identitySettled;
2216
+ /**
2217
+ * Identity stamp recorded against each queued offline mutation, keyed by
2218
+ * the queue-assigned mutation id. Captured at enqueue from the auth token
2219
+ * in effect at the time, and re-checked at flush so a queued write can
2220
+ * never replay under a different identity than the one that issued it.
2221
+ * See `identityFingerprint` for the fingerprint shape.
2222
+ */
2223
+ private readonly queuedIdentities;
2224
+ /**
2225
+ * Distinct shard keys with a mutation currently sitting in `offlineQueue`
2226
+ * — fresh writes queued this session (`enqueueOfflineMutation`) or writes
2227
+ * restored from durable storage (`hydratePersistedQueue`). A follower tab
2228
+ * has no per-shard `ShardConnection` to iterate when its mirrored leader
2229
+ * status turns `"connected"` (see the `onConnectionStatus` coordinator
2230
+ * option), so this is what that flush walks instead. Entries are never
2231
+ * removed — flushing an already-empty shard is a cheap no-op, and the set
2232
+ * is bounded by the app's own distinct shard-key cardinality.
2233
+ */
2234
+ private readonly queuedOfflineShardKeys;
2235
+ private closed;
2236
+ /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
2237
+ private readonly authTokenListeners;
2238
+ /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
2239
+ private readonly statusListeners;
2240
+ /** Room handles' held-send flushers, keyed by the shard connection they send on. */
2241
+ private readonly roomFlushes;
2242
+ /** Room handles' pending-send resets, run when the identity changes so queued sends never cross identities. */
2243
+ private readonly roomIdentityResets;
2244
+ /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
2245
+ private readonly tokenExpiredListeners;
2246
+ /** Subscribers notified when the previous identity's session is retired (see `onIdentityChange`). */
2247
+ private readonly identityChangeListeners;
2248
+ /** How many identities this client has retired (see `identityEpoch`). */
2249
+ private retiredIdentities;
2250
+ /** Token hash the last durable-replay auth refusal fired `onTokenExpired` for — see `noteReplayAuthRefusal`. */
2251
+ private authRefusalNotifiedFor;
2252
+ /** What each outstanding {@link ReplayCredential} was judged against — see `replayIdentityVerdict`. */
2253
+ private readonly replayCredentials;
2254
+ /** Subscribers to offline-queued mutation verdicts (see `onMutationSettled`). */
2255
+ private readonly mutationSettledListeners;
2256
+ /** Subscribers to the offline-queue pending-count (see `onPendingChange`). */
2257
+ private readonly pendingChangeListeners;
2258
+ private readonly syncStatusListeners;
2259
+ /** The last value `syncStatusListeners` was told, to emit only on a real change. */
2260
+ private lastSyncStatus;
2261
+ /**
2262
+ * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
2263
+ * of callbacks. Membership doubles as the resubscribe set replayed on every
2264
+ * (re)connect so a topic survives a socket bounce.
2265
+ */
2266
+ private readonly whisperHandlers;
2267
+ /**
2268
+ * Live-topic grants this client asked for over a WebSocket, keyed `connectionKey(shardKey)` →
2269
+ * subscription id → the stream and topic, and `release`, which leaves the topic's whisper membership once. Replayed on every
2270
+ * `identity` frame: each socket is a new connection id with no grants, so a bounce would otherwise stop delivery silently.
2271
+ */
2272
+ private readonly liveSocketGrants;
2273
+ /** Tail of the live-grant control posts. One chain keeps a subscribe and its unsubscribe in order. */
2274
+ private liveControlChain;
2275
+ /** Join state of each whisper topic, per `connectionKey(shardKey)`, on the current socket. Reset on every open. */
2276
+ private readonly whisperJoins;
2277
+ private nextLiveSocketId;
2278
+ /** Last status broadcast, so we only notify listeners on an actual change. */
2279
+ private lastStatus;
2280
+ private nextSubId;
2281
+ private nextStreamId;
2282
+ /**
2283
+ * In-flight client-side stream readers, keyed by the stream id sent on the
2284
+ * wire. The handle drives the underlying iterator queue and `shardKey`
2285
+ * tells us which socket to push the cancel frame onto when the consumer
2286
+ * calls `.cancel()` or the iterator is garbage-collected.
2287
+ */
2288
+ private readonly streams;
2289
+ /** Live shape subscriptions (partial replication), keyed by their wire id. */
2290
+ /**
2291
+ * Teardown callbacks for the admin sockets {@link LunoraClient.subscribeScheduledJobs}
2292
+ * opens. Those run their own reconnect loop off a closure-local `closed`
2293
+ * flag rather than `this.closed` (they predate `ensureSocket`'s guard), so
2294
+ * without this registry a `close()` left every one of them reconnecting on
2295
+ * its backoff forever — re-minting an ephemeral admin sub-token on each
2296
+ * attempt when a `WsTokenProvider` is wired.
2297
+ */
2298
+ private readonly adminSocketTeardowns;
2299
+ /**
2300
+ * Per-channel hooks that drop a supplementary (route / scheduled) socket so it
2301
+ * reconnects under the current credential. Run when the credential changes.
2302
+ */
2303
+ private readonly supplementaryBounces;
2304
+ /**
2305
+ * The in-flight offline-queue replay per shard (`connectionKey`), while one
2306
+ * is running. Two jobs:
2307
+ *
2308
+ * 1. It serializes overlapping flushes for the same shard — two reconnect
2309
+ * events in quick succession used to drain and replay concurrently.
2310
+ * 2. It is the barrier {@link LunoraClient.mutation} waits on before sending a FRESH
2311
+ * write directly. The socket's `open` handler flips `wsState` to `"open"`
2312
+ * first and calls the flush last, so from that instant `mutation()`'s
2313
+ * offline gate is false and a new write raced straight to `/rpc` against
2314
+ * the replay of the older, queued write for the same document — the newer
2315
+ * one could land first and then be overwritten by the older. Ordering
2316
+ * inside the replay (`replaySequential`) never covered this, because the
2317
+ * racing write was never in the queue.
2318
+ */
2319
+ private readonly offlineFlushes;
2320
+ /**
2321
+ * Subscriptions a socket `open` un-answered that no value-bearing frame has
2322
+ * answered since. What they hold is the previous socket's value, or a blank
2323
+ * after a cold reconnect, and the server acks a `subscribe` before it seeds
2324
+ * it, so neither `lastValue` nor `ack` says the value is current. A queued
2325
+ * write whose snapshot precondition reads one of them is not evaluated yet:
2326
+ * see {@link LunoraClient.snapshotAnswer}. On a follower the open is the
2327
+ * leader's, see {@link LunoraClient.awaitLeaderAnswers}.
2328
+ */
2329
+ private readonly awaitingAnswer;
2330
+ /**
2331
+ * Subscriptions whose wait ended without a value to read: the seed was
2332
+ * refused or undecodable, or the resubscribe was given up on. Still acked and
2333
+ * blank after a cold reconnect, so a snapshot comparison would read the blank
2334
+ * as a change; a guard over one of them is no evidence either way.
2335
+ */
2336
+ private readonly answeredUnreadable;
2337
+ /** Connection keys whose last flush left a write waiting on {@link LunoraClient.awaitingAnswer}; an answer there flushes again. */
2338
+ private readonly answerHeldShards;
2339
+ /** Gives up on the leader relaying an answer, one per subscription, see {@link LunoraClient.awaitLeaderAnswer}. */
2340
+ private readonly leaderAnswerTimers;
2341
+ /**
2342
+ * Per-shard replay backoff, keyed by {@link connectionKey} exactly as the
2343
+ * flushes and their timers are: `delayMs` is the longest hint the CURRENT
2344
+ * flush of that key was given (written by
2345
+ * {@link LunoraClient.noteReplayRetryDelay}, consumed once by
2346
+ * {@link LunoraClient.scheduleRateLimitedRetry} at the end of the drain), and
2347
+ * `attempts` counts its consecutive failed flushes, which is what the
2348
+ * hintless backoff ramps on.
2349
+ *
2350
+ * Keyed, not a single field: flushes are per shard key and run concurrently,
2351
+ * so one field means one limited shard sets the wait for every other shard
2352
+ * and two flushes overwrite — then consume — each other's delay, leaving one
2353
+ * of them with nothing scheduled at all. Evicted by
2354
+ * {@link LunoraClient.scheduleRateLimitedRetry} the moment a key has nothing
2355
+ * left to retry, so an app that shards per document does not accumulate an
2356
+ * entry per document it ever wrote.
2357
+ */
2358
+ private readonly replayRetryState;
2359
+ /** Failed replay attempts collected so far, per ambiguous-send write id (see `spendsLastReplayAttempt`); cleared when the write settles. */
2360
+ private readonly replayAttempts;
2361
+ /** Pending rate-limit retry flushes, keyed by {@link connectionKey}, so `close()` can cancel them. */
2362
+ private readonly replayRetryTimers;
2363
+ private readonly shapeSubscriptions;
2364
+ /** In-flight pokes, keyed by connection and `pokeId`. The key rule is in shape-state.ts. */
2365
+ private readonly pokeAssembler;
2366
+ private nextShapeId;
2367
+ constructor(options: LunoraClientOptions);
2368
+ /**
2369
+ * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
2370
+ * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
2371
+ * sync across all mounted instances.
2372
+ *
2373
+ * Pass a STABLE `subject` (the user id) to key the offline-queue identity on
2374
+ * it instead of the token bytes, so a token *refresh* (same user, new JWT)
2375
+ * doesn't read as an identity change and discard queued writes. The subject is
2376
+ * **sticky**: a later call that omits it (or passes `undefined`) keeps the
2377
+ * established subject — so `setAuthToken(refreshedToken)` after a prior
2378
+ * `setAuthToken(token, user.id)` retains the identity. Clearing the token
2379
+ * clears it too — a credential-less subject would let the NEXT sign-in
2380
+ * inherit the previous user's identity (and their queue and read cache).
2381
+ * Establishing the subject on an UNCHANGED token (e.g. the user id resolves a
2382
+ * tick after the token was set — see {@link getCurrentUser}, which does this
2383
+ * for every adapter) re-stamps any in-flight queued writes rather than
2384
+ * dropping them: same credential, just a more stable label. A real user
2385
+ * switch still drops the previous user's writes.
2386
+ *
2387
+ * A sticky subject carried across a token change is not re-confirmed until
2388
+ * the next session resolve says which user the NEW credential belongs to.
2389
+ * Queued writes are HELD (never sent, never dropped) for that window — see
2390
+ * {@link replayIdentityVerdict} — so a refresh can't replay them and an
2391
+ * account switch can't replay the previous user's writes as the new one.
2392
+ *
2393
+ * Does NOT update the WebSocket auth — a socket keeps the session credential
2394
+ * it connected with for its life. To refresh live WS auth, call
2395
+ * {@link setWsToken} explicitly, which closes existing shard sockets to
2396
+ * force a reconnect with the new credential. With
2397
+ * {@link LunoraClientOptions.authTokenOnUpgrade} (React Native's
2398
+ * `Authorization` header), a sign-in from signed-out (a token where there was
2399
+ * none) reconnects the sockets, cold, so the upgrade presents it.
2400
+ */
2401
+ setAuthToken(token: string | null, subject?: string | null): void;
2402
+ getAuthToken(): string | null;
2403
+ /**
2404
+ * The current identity fingerprint (the same stamp queued offline writes
2405
+ * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
2406
+ * owns its own at-least-once replay outside the built-in `OfflineQueue` —
2407
+ * can drop a persisted write whose captured `identity` no longer matches the
2408
+ * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
2409
+ */
2410
+ currentIdentity(): string | null;
2411
+ /**
2412
+ * Declare that this client's identity is resolved by something — call it
2413
+ * before the first `getCurrentUser()`, not after.
2414
+ *
2415
+ * `@lunora/client/auth`'s identity store calls this when it attaches, which
2416
+ * is the moment an app becomes one that HAS auth. Until something says so,
2417
+ * a `null` fingerprint is taken to be the settled, unshared identity of an
2418
+ * app with no auth at all, because nothing else distinguishes the two: both
2419
+ * hold no token, both have never been answered, and `authBasePath` has a
2420
+ * default. That reading is right for the no-auth app and wrong for a cookie
2421
+ * app whose first `/get-session` has not started — the window where
2422
+ * `null === null` matched the PREVIOUS browser user's cached rows and
2423
+ * queued writes, before any probe was in flight to mark the fingerprint
2424
+ * provisional.
2425
+ *
2426
+ * Idempotent, and one-way: a client that resolves an identity keeps its
2427
+ * gates armed until a probe actually answers.
2428
+ */
2429
+ expectIdentityResolution(): void;
2430
+ /**
2431
+ * This client's current CDC baseline for `shardKey` — the cursor its live
2432
+ * queries have reached, which is what a write composed right now should be
2433
+ * judged against.
2434
+ *
2435
+ * Exposed for the same reason {@link currentIdentity} is: a durable
2436
+ * {@link OutboxSink} owns its own at-least-once replay outside the built-in
2437
+ * `OfflineQueue`, so it has to capture this at COMPOSE time and hand it back
2438
+ * through {@link MutationCallOptions.replayBaseline}. Sampling it inside the
2439
+ * replay instead reads the cursor this client has advanced to in the
2440
+ * meantime, which is the newer state the write must be judged against.
2441
+ *
2442
+ * `undefined` when no subscription on the shard carries a cursor yet.
2443
+ */
2444
+ currentBaseline(shardKey?: string): number | undefined;
2445
+ /**
2446
+ * Verdict on whether a durable write stamped with `stamped` may be replayed
2447
+ * now. The comparison a replay handler must NOT hand-roll.
2448
+ *
2449
+ * `"match"` is the same identity, or the same credential under a token hash
2450
+ * — which a late-resolving subject would otherwise make look different.
2451
+ *
2452
+ * `"unknown"` is nobody signed in *yet*. A durable replay starts when the
2453
+ * executor is constructed, before the app has resolved its session and
2454
+ * called {@link setAuthToken}, so this is the normal state on every reload.
2455
+ * There is no other identity to replay as, so such a write must be HELD,
2456
+ * never dropped — dropping here destroys the queuing user's own offline
2457
+ * writes. It is indistinguishable from an explicit sign-out (the fingerprint
2458
+ * is `null` for both), which is the safe conflation: holding a write for a
2459
+ * signed-out app costs a retry, dropping it costs the write.
2460
+ *
2461
+ * It also covers a `null` stamp against a `null` fingerprint — but only
2462
+ * while {@link identityUnresolved} says a session resolve is in flight.
2463
+ * Two `null`s are the same identity for an app with no auth at all (nobody
2464
+ * else shares that fingerprint, because nobody else exists) and for a
2465
+ * client the server has told there is no session; they are NOT the same
2466
+ * identity in the window where the fingerprint is about to become
2467
+ * `subj:<id>`, which is where one browser user's queued write went out on
2468
+ * the next one's cookie.
2469
+ *
2470
+ * A held write is not stranded: the hold ends when the resolve settles, and
2471
+ * both {@link setAuthToken} and {@link getCurrentUser} re-flush there. If
2472
+ * the identity that arrives is not the one that queued the write, the
2473
+ * verdict is then `"mismatch"` and the write is settled terminally.
2474
+ *
2475
+ * A sticky subject carried across a token change is `"unknown"` for the same
2476
+ * reason: the label says user A, the credential in hand has not been checked
2477
+ * against it, and the two answers (a refresh vs an account switch) call for
2478
+ * opposite verdicts. Hold until the next session resolve settles it.
2479
+ *
2480
+ * `"mismatch"` is a different identity signed in, and is the one that must be
2481
+ * terminal: replaying would attribute one user's write to another and pass
2482
+ * THEIR row-level security.
2483
+ *
2484
+ * A `"match"` carries the {@link ReplayCredential} the replay must be sent
2485
+ * with ({@link MutationCallOptions.replayCredential}): the bearer held right
2486
+ * now, which is the one this verdict judged. The replay goes out with it even
2487
+ * if the token changes before the send, and the outbox's next attempt judges
2488
+ * again against whatever is current then.
2489
+ */
2490
+ replayIdentityVerdict(stamped: null | string | undefined): ReplayIdentityVerdict;
2491
+ /** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
2492
+ clientIdentifier(): string;
2493
+ /**
2494
+ * The highest custom-mutator watermark the server has echoed for this client
2495
+ * on the given shard (0 if none yet). The `@lunora/db` mutator runtime seeds
2496
+ * its `clientSeq` generator from this so a reload never reissues a sequence
2497
+ * the server has already applied (which it would swallow as a replay, silently
2498
+ * dropping the write).
2499
+ */
2500
+ confirmedMutationWatermark(shardKey?: string): number;
2501
+ /**
2502
+ * Push a custom mutator to its authoritative server impl over the watermark
2503
+ * protocol (Phase 4): the request carries `x-lunora-client-id` + a monotonic
2504
+ * `x-lunora-client-seq`, so the DO runs it exactly once and advances this
2505
+ * client's `__client_watermark`.
2506
+ *
2507
+ * Returns the server `result` plus `applied`: `true` when the DO ran this push
2508
+ * as the next-in-order mutation, `false` when it was a replay ack (`clientSeq`
2509
+ * was at or below the stored watermark — e.g. a stale sequence after a reload).
2510
+ * A `false` verdict tells the caller to reissue above the now-known watermark
2511
+ * (echoed into {@link confirmedMutationWatermark}) rather than treat the benign
2512
+ * ack as a confirmed write. Every ack — applied or not — bumps the watermark.
2513
+ *
2514
+ * This is the online transport for `@lunora/db`'s client-mutator runtime; the
2515
+ * optimistic overlay + durable-outbox concerns live in that runtime, not here.
2516
+ */
2517
+ callMutator(functionPath: string, args: Record<string, unknown>, options?: {
2518
+ clientSeq?: number;
2519
+ shardKey?: string;
2520
+ }): Promise<{
2521
+ applied: boolean;
2522
+ result: unknown;
2523
+ }>;
2524
+ /**
2525
+ * Subscribe to auth-token changes. Returns an unsubscribe function. The
2526
+ * listener is NOT invoked on registration — use {@link getAuthToken} for
2527
+ * the current value.
2528
+ */
2529
+ onAuthTokenChange(listener: (token: string | null) => void): Unsubscribe;
2530
+ /**
2531
+ * Subscribe to a user switch or sign-out: fired after {@link setAuthToken}
2532
+ * retires the previous identity's session, i.e. every live subscription has
2533
+ * just been blanked to `undefined` and its socket closed. Not fired when a
2534
+ * bearer identity is first established from signed-out (nothing is
2535
+ * retired), nor when a subject is attached to the same credential, nor on
2536
+ * a cookie session's first answer after page load.
2537
+ *
2538
+ * A cookie session fires it on every change the server reports — sign-out,
2539
+ * a sign-in after a known sign-out, a different user — whether the answer
2540
+ * came from {@link getCurrentUser} or from a socket's `identity` frame. Its
2541
+ * sign-out changes nothing the client can observe on its own; in a browser
2542
+ * the client also re-resolves whenever `@lunora/auth-ui` or the
2543
+ * `lunoraSessionSync()` better-auth plugin reports a session change.
2544
+ *
2545
+ * For caches layered on top of the client. A subscriber only hears the
2546
+ * blank for queries it still subscribes to, so a cache that keeps values for
2547
+ * unmounted queries must drop them here, or the next user can read the
2548
+ * previous user's rows from it.
2549
+ */
2550
+ onIdentityChange(listener: () => void): Unsubscribe;
2551
+ /**
2552
+ * How many identities this client has retired since it was constructed —
2553
+ * the number of times {@link onIdentityChange} has fired. Already moved when
2554
+ * those listeners run.
2555
+ *
2556
+ * A value rendered on the server (a `Preloaded` token) was read for whoever
2557
+ * was signed in when the page loaded, so it is only safe to show while this
2558
+ * is `0`: once a sign-out or user switch has retired that identity, a
2559
+ * component mounting later must not seed the previous user's rows.
2560
+ */
2561
+ identityEpoch(): number;
2562
+ /**
2563
+ * Fetch the currently authenticated user from better-auth's `get-session`
2564
+ * endpoint, returning the `user` record or `null` when signed out. Sends
2565
+ * the stored bearer token (if any) and `credentials: "include"` so a
2566
+ * cookie-session is also honoured.
2567
+ *
2568
+ * `null` means the **server answered** that there is no session — an empty
2569
+ * body, no `user` field, or a non-OK status such as 401. A network or parse
2570
+ * failure **rejects** instead, because "the endpoint was unreachable" is not
2571
+ * the same answer as "you are signed out": collapsing the two made an
2572
+ * offline reload with a valid stored token read as a sign-out in every
2573
+ * adapter's auth gate. Callers that cannot act on the difference can still
2574
+ * `.catch(() => null)`; `@lunora/client/auth`'s identity store maps the
2575
+ * rejection to the `"unreachable"` status instead.
2576
+ *
2577
+ * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
2578
+ * the token changes (that's what `@lunora/react`'s `useAuth` does).
2579
+ *
2580
+ * A resolved user also ESTABLISHES the identity subject for the credential
2581
+ * that resolved it ({@link setAuthToken}'s second argument). This is the one
2582
+ * call every adapter's identity store already makes, and the only place that
2583
+ * knows the answer — leaving it to each adapter is what left the sticky-subject
2584
+ * contract unreached in every shipped one, so a routine JWT refresh read as a
2585
+ * user switch and discarded the user's own queued writes and read cache.
2586
+ *
2587
+ * Under a cookie session (no token held) the answer is adopted whatever it
2588
+ * is, "no session" included, and a change from the identity already known
2589
+ * retires the previous session — see {@link onIdentityChange}.
2590
+ */
2591
+ getCurrentUser(): Promise<User | null>;
2592
+ /**
2593
+ * Replace the session credential sent in the `connect` frame, and close
2594
+ * every open shard socket so the reconnect presents the new value. The
2595
+ * credential never rides the WebSocket URL. Call this when the user's session
2596
+ * changes (sign-in, sign-out, switching workspaces). Accepts a static string
2597
+ * or a {@link WsTokenProvider} resolved fresh at every (re)connect. Bearer
2598
+ * tokens for HTTP RPC are independent — see {@link setAuthToken}.
2599
+ */
2600
+ setWsToken(token: string | undefined | WsTokenProvider): void;
2601
+ /**
2602
+ * Replace the short-lived ticket appended to WS upgrade URLs as `?token=…`,
2603
+ * and close every open shard socket so the reconnect picks up the new value.
2604
+ * Only an ephemeral admin sub-token belongs here (minted by
2605
+ * `POST /_lunora/admin/ws-token`): a URL is logged by every proxy on the way,
2606
+ * so a session credential never goes here — see {@link setWsToken}. Accepts a
2607
+ * static string or a {@link WsTokenProvider} resolved fresh at every (re)connect.
2608
+ */
2609
+ setWsTicket(ticket: string | undefined | WsTokenProvider): void;
2610
+ /**
2611
+ * Register (or clear, with `undefined`) the app context sent in the `connect`
2612
+ * envelope for a shard's socket, overriding the client-wide
2613
+ * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
2614
+ * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
2615
+ * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
2616
+ * presence row is removed the instant the socket drops, with no TTL lag.
2617
+ *
2618
+ * Stored per shard and replayed on every (re)connect. When a socket for the
2619
+ * shard is already open, a fresh `connect` envelope is sent immediately so the
2620
+ * server sees the new context without waiting for a reconnect.
2621
+ *
2622
+ * Not available on a `crossTabSync` FOLLOWER tab — the context rides the
2623
+ * `connect` envelope of a socket a follower does not own, so it would be
2624
+ * stored and never sent. Throws `NOT_IMPLEMENTED` there.
2625
+ */
2626
+ setConnectionContext(context: Record<string, unknown> | undefined, options?: {
2627
+ shardKey?: string;
2628
+ }): void;
2629
+ /**
2630
+ * Refcounted variant of {@link setConnectionContext}: register a connection
2631
+ * `context` for a shard and get back a release function. Unlike the imperative
2632
+ * setter, the context is only cleared once the *last* acquired holder releases
2633
+ * it — so two components (e.g. two mounted `usePresence` hooks) on the same
2634
+ * shard no longer clobber each other's context when one of them unmounts. The
2635
+ * most-recently acquired live holder wins (last-writer-wins), and releasing
2636
+ * the top holder falls back to the previous one rather than clearing.
2637
+ *
2638
+ * With a single holder the behaviour is identical to a
2639
+ * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
2640
+ * Releasing more than once is a no-op (the holder is matched by reference, so
2641
+ * a double release can't drop a different holder).
2642
+ */
2643
+ acquireConnectionContext(context: Record<string, unknown>, options?: {
2644
+ shardKey?: string;
2645
+ }): Unsubscribe;
2646
+ /**
2647
+ * Join a whisper `topic` and receive every ephemeral message other members
2648
+ * broadcast to it on the same shard (typing indicators, live cursors,
2649
+ * presence pings). Whispers never touch the server's durable state — there's
2650
+ * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
2651
+ * is left on the server once its last local handler unsubscribes.
2652
+ *
2653
+ * `handler` receives the raw `data` and the sender's verified `from` user id
2654
+ * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
2655
+ * (the default shard when omitted) — use the same shard you target with the
2656
+ * matching queries/mutations so members land on the same Durable Object.
2657
+ *
2658
+ * Security: a whisper topic is access-controlled only if the app declares an
2659
+ * `onWhisper` authorizer server-side (`@lunora/server`). Without one, the
2660
+ * topic's only boundary is the shard — any client that can open a socket to it
2661
+ * can join, read, and inject on any topic name. `from` is server-stamped and
2662
+ * unforgeable either way, but never trust a whisper's `data` as authorization,
2663
+ * and remember that even an authorized topic is transient awareness with no
2664
+ * durable trace: anything privileged belongs behind a query/mutation with RLS.
2665
+ *
2666
+ * A denied join is silent — whispers are never acked, so nothing distinguishes
2667
+ * "denied" from "nobody is whispering". Gate the UI on a query you can read a
2668
+ * verdict from, not on whether whispers arrive.
2669
+ *
2670
+ * Not available on a `crossTabSync` FOLLOWER tab — whisper frames are not
2671
+ * relayed over the cross-tab channel, so this throws `NOT_IMPLEMENTED`
2672
+ * there rather than registering a handler nothing can ever reach. See
2673
+ * {@link LunoraClientOptions.crossTabSync}.
2674
+ */
2675
+ whisperSubscribe(topic: string, handler: (data: unknown, from?: string) => void, options?: {
2676
+ shardKey?: string;
2677
+ }): Unsubscribe;
2678
+ /**
2679
+ * Follow a live topic of a `defineLiveStream` stream over this client's WebSocket, instead of
2680
+ * an SSE connection (`connectLiveStream`). Joins the bare topic as a whisper member, then asks
2681
+ * the stream's control route (`/live/<stream>/control`) to grant this socket the topic, naming
2682
+ * the socket's connection id. A live publish reaches the socket only with both in place.
2683
+ *
2684
+ * The join needs the app's `onWhisper` approval, the same as any whisper join. The shard runs
2685
+ * the authorizer with `action: "subscribe"` on the bare topic, and a denied join is silent:
2686
+ * the shard acknowledges every join once processed, admitted or not, so the client cannot tell
2687
+ * a denial from a quiet topic. The grant is posted only after that acknowledgement (or after
2688
+ * `LIVE_CONTROL_TIMEOUT_MS` if it never arrives), so a publish cannot outrun the membership it
2689
+ * needs. A grant posted for a denied join still has no membership, so the shard relays no
2690
+ * `live` frame and `onEvent` never fires. An app that streams private data here must declare an
2691
+ * `onWhisper` that allows the topic; without one the join is open to any socket on the shard.
2692
+ *
2693
+ * Grants are re-issued on every reconnect, because each socket gets a new connection id.
2694
+ * A control call that fails is not retried here, so a failed grant delivers nothing. A refusal
2695
+ * (a 4xx other than 404 and 401) is final: the local grant is dropped, so a later subscribe can
2696
+ * be tried again, and `onError` is called with the status. A transient failure keeps the grant.
2697
+ * @returns an unsubscribe function that revokes the grant and leaves the topic
2698
+ */
2699
+ subscribeLiveTopic(options: {
2700
+ onError?: (error: {
2701
+ status: number;
2702
+ topic: string;
2703
+ }) => void;
2704
+ onEvent: (payload: unknown) => void;
2705
+ shardKey?: string;
2706
+ stream: string;
2707
+ topic: string;
2708
+ }): Unsubscribe;
2709
+ /**
2710
+ * Broadcast an ephemeral `data` payload to the other members of a whisper
2711
+ * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
2712
+ * dropped when the shard socket isn't open (whispers are transient, never
2713
+ * queued), and the server silently drops it if the sender exceeds its
2714
+ * whisper rate budget. The sender never receives its own whisper. Omitting
2715
+ * `data` delivers JSON `null` to receivers (not `undefined`).
2716
+ *
2717
+ * Returns `true` when the frame was handed to an open socket, `false` when it
2718
+ * was dropped, so a caller that must not lose a message (one sent right after
2719
+ * connecting, before the socket opens) can detect the drop and retry.
2720
+ *
2721
+ * That best-effort drop is for a socket that is momentarily down. A
2722
+ * `crossTabSync` FOLLOWER tab has no socket and never will (see
2723
+ * {@link LunoraClientOptions.crossTabSync}), so every whisper from it would
2724
+ * be dropped forever — it throws `NOT_IMPLEMENTED` instead.
2725
+ *
2726
+ * A send the app's `onWhisper` authorizer denies is dropped the same silent
2727
+ * way, for the same reason: there is no ack frame to report it on. See
2728
+ * {@link whisperSubscribe} for the security model.
2729
+ */
2730
+ whisper(topic: string, data?: unknown, options?: {
2731
+ shardKey?: string;
2732
+ }): boolean;
2733
+ /**
2734
+ * Join a `defineRoom` room from the client: subscribe to the room's server
2735
+ * dispatches and send typed messages to it. A thin, typed wrapper over
2736
+ * {@link whisperSubscribe} / {@link whisper} on the room's topic
2737
+ * (`room:<name>`, the topic the shard resolves to the room's handler).
2738
+ *
2739
+ * The room is passed as its generated reference, so `onMessage` and `send` are
2740
+ * typed from the room's own message validator:
2741
+ *
2742
+ * ```ts
2743
+ * import { rooms } from "./_generated/api";
2744
+ *
2745
+ * const chat = client.connectRoom(rooms.chat, {
2746
+ * onMessage: (message) => append(message.text),
2747
+ * });
2748
+ * chat.send({ text: "hello" });
2749
+ * chat.close();
2750
+ * ```
2751
+ *
2752
+ * `onMessage` receives what the room's server handler broadcasts (via its
2753
+ * `socket.broadcast`), NOT the sender's own raw send — the handler is
2754
+ * authoritative. Returns a handle with `send` and `close`.
2755
+ */
2756
+ connectRoom<Message>(room: RoomRef<Message>, handlers: {
2757
+ onMessage: (message: Message) => void;
2758
+ }, options?: {
2759
+ shardKey?: string;
2760
+ }): {
2761
+ close: () => void;
2762
+ send: (message: Message) => boolean;
2763
+ };
2764
+ /**
2765
+ * Open a `defineWebSocket` route: a dedicated socket at the route's declared
2766
+ * `path`, typed `send`/`onMessage` like a query's args/result. `path` is the
2767
+ * exact path the server declared (`defineWebSocket({ path: "/chat", … })`).
2768
+ *
2769
+ * `Message` is the route's message type. Codegen does NOT yet infer it from
2770
+ * the route's validator, so pass it explicitly (or rely on a route-typed
2771
+ * wrapper in your app):
2772
+ *
2773
+ * ```ts
2774
+ * const chat = client.connectWebSocket<{ text: string }>("/chat", {
2775
+ * onMessage: (message) => append(message.text),
2776
+ * });
2777
+ * chat.send({ text: "hello" });
2778
+ * chat.close();
2779
+ * ```
2780
+ *
2781
+ * The socket carries the browser's session cookie, or an `Authorization` header
2782
+ * where the client can set one, and either establishes a user. A route declared `auth: true` on
2783
+ * the server refuses a socket with no verified session. The `wsToken` is
2784
+ * sent only on shard sockets, in their first `connect` frame; a route socket
2785
+ * has no `connect` frame, so `wsToken` does not authenticate it. The `wsTicket`
2786
+ * (`?token=`, see {@link setWsTicket}) is an ephemeral admin credential
2787
+ * appended to the URL, and it does not sign a user in to a route, so a
2788
+ * private route needs a verified session from the cookie or an `Authorization`
2789
+ * header. Reconnects with the
2790
+ * client's configured backoff. `onMessage` receives what the route's server
2791
+ * handler sent (via its `socket.send`/`socket.broadcast`), never the sender's
2792
+ * own raw frame — the handler is authoritative. Returns a handle with `send`
2793
+ * and `close`; a `send` while the socket is not open is dropped (the channel
2794
+ * is transient, like a whisper).
2795
+ */
2796
+ connectWebSocket<Message>(path: string, handlers: {
2797
+ onClose?: () => void;
2798
+ onMessage: (message: Message) => void;
2799
+ onOpen?: () => void;
2800
+ }, options?: {
2801
+ shardKey?: string;
2802
+ }): {
2803
+ close: () => void;
2804
+ send: (message: Message) => void;
2805
+ };
2806
+ /**
2807
+ * Subscribe to token-expiry events: invoked whenever the server drops a
2808
+ * shard socket because the connection's credential lapsed (close code
2809
+ * `4001`) or the server refused the session credential (close code `4003`,
2810
+ * notified once per credential). The client already reconnects automatically
2811
+ * (re-resolving identity from the cookie/token in effect); use this to refresh a
2812
+ * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
2813
+ * with a freshly minted one. Returns an unsubscribe function.
2814
+ *
2815
+ * Also fired, once per credential, when a queued write's replay is refused
2816
+ * `TOKEN_EXPIRED` / `UNAUTHENTICATED`. The write is held for the refresh, and
2817
+ * survives it only if the identity is keyed on a `subject`: pass the same user
2818
+ * id with the new token, `setAuthToken(freshToken, user.id)` (or have passed
2819
+ * it before — the subject is sticky). With no subject the identity is the
2820
+ * token hash, so a refresh cannot be told from an account switch and the held
2821
+ * writes are rejected `OFFLINE_IDENTITY_CHANGED`. A cookie session has no
2822
+ * token to replace: renew the cookie, and the held write is re-sent on a
2823
+ * backoff with it.
2824
+ */
2825
+ onTokenExpired(listener: () => void): Unsubscribe;
2826
+ /**
2827
+ * Current aggregate live-socket status across all shard connections. See
2828
+ * {@link ConnectionStatus}.
2829
+ */
2830
+ connectionStatus(): ConnectionStatus;
2831
+ /**
2832
+ * Subscribe to aggregate connection-status changes. Invokes `listener`
2833
+ * immediately with the current status, then on every transition. Returns an
2834
+ * unsubscribe function.
2835
+ */
2836
+ onConnectionStatus(listener: (status: ConnectionStatus) => void): Unsubscribe;
2837
+ /**
2838
+ * Whether the client is caught up: a live connection, every subscription
2839
+ * answered by the server, and no write waiting in the offline queue. Use this
2840
+ * rather than `connectionStatus() === "connected"` for a "synced" indicator —
2841
+ * that reads `"connected"` the moment a socket opens, while subscriptions still
2842
+ * have no data and queued writes are still waiting to go out.
2843
+ *
2844
+ * Over the HTTP polling fallback (judged per shard, so one polling shard does
2845
+ * not wait on an ack while another holds an open socket), and on a cross-tab
2846
+ * follower (neither sees server acknowledgements), a subscription counts as
2847
+ * answered once the current connection has delivered a value for it; a
2848
+ * hydrated cache does not.
2849
+ * A write counts as pending from the moment it is queued until the server
2850
+ * settles it, including while its replay request is on the wire.
2851
+ */
2852
+ syncStatus(): SyncStatus;
2853
+ /**
2854
+ * Subscribe to {@link syncStatus} changes. Invokes `listener` immediately with
2855
+ * the current value, then whenever the connection status, the number of
2856
+ * unanswered subscriptions or the number of unsettled writes (queued, or
2857
+ * being replayed) changes. Returns an unsubscribe function.
2858
+ */
2859
+ onSyncStatus(listener: (status: SyncStatus) => void): Unsubscribe;
2860
+ /**
2861
+ * Number of offline writes waiting in the built-in queue to be sent — the
2862
+ * depth for a "N changes waiting to sync" indicator. Counts writes that are
2863
+ * queued (offline / mid-reconnect), not ones already in flight on the wire.
2864
+ * A `@lunora/db` app whose writes ride the unified outbox should read
2865
+ * `LunoraDb.pendingCount()` instead (this counts only the built-in queue).
2866
+ */
2867
+ pendingCount(): number;
2868
+ /**
2869
+ * A point-in-time snapshot of everything the sync engine believes right now:
2870
+ * per-shard sockets and watermarks, every live query and shape subscription with
2871
+ * its cursor and ack state, and the offline-queue depth.
2872
+ *
2873
+ * This exists because the alternative is `console.log`. When an optimistic
2874
+ * overlay doesn't clear, the questions are always the same — *is the socket open?
2875
+ * what watermark has the server confirmed for this shard? has this shape been
2876
+ * poked since my write? is anything stuck in the queue?* — and none of them were
2877
+ * answerable from outside the client, so every adopter ends up instrumenting the
2878
+ * library by hand or building a bespoke policy layer around a symptom.
2879
+ *
2880
+ * Read it from a devtools console, log it next to a bug report, or render it in a
2881
+ * debug panel. Pull-only and allocation-cheap; nothing here is reactive, so poll
2882
+ * it or read it on demand.
2883
+ *
2884
+ * ```ts
2885
+ * const { shards, subscriptions } = client.debug();
2886
+ * // shards: [{ shardKey: "user-1", wsState: "open", confirmedMutationWatermark: 42, … }]
2887
+ * ```
2888
+ */
2889
+ debug(): ClientDebugSnapshot;
2890
+ /**
2891
+ * Subscribe to changes in {@link pendingCount}. Invokes `listener` immediately
2892
+ * with the current count, then whenever the queue depth changes (a write is
2893
+ * enqueued, flushed, or discarded). Returns an unsubscribe function.
2894
+ */
2895
+ onPendingChange(listener: (pending: number) => void): Unsubscribe;
2896
+ /**
2897
+ * Subscribe to terminal verdicts for offline-queued mutations. The listener
2898
+ * fires once per queued write that commits or is rejected — including a write
2899
+ * restored from durable storage after a reload, whose original `mutation()`
2900
+ * Promise no longer exists (`hadAwaiter: false`), and a write the queue
2901
+ * evicts on overflow or discards on an identity change. This is the durable
2902
+ * channel for surfacing a rolled-back optimistic write to the UI; an online
2903
+ * mutation that never queued still surfaces through the Promise `mutation()`
2904
+ * returns. The listener is NOT invoked on registration. Returns an
2905
+ * unsubscribe function. See {@link MutationSettledEvent}.
2906
+ */
2907
+ onMutationSettled(listener: (event: MutationSettledEvent) => void): Unsubscribe;
2908
+ /**
2909
+ * The `WebSocket` implementation this client was constructed with (an
2910
+ * explicit `options.WebSocket`, or the ambient global on platforms that have
2911
+ * one) — `undefined` if neither is available. This is the seam a feature
2912
+ * that opens its OWN socket outside the client's multiplexed connection
2913
+ * (e.g. a voice-agent hook) should default to, instead of reaching for
2914
+ * `globalThis.WebSocket` directly: on React Native the client wraps this
2915
+ * constructor to inject the auth-headers factory's credential onto the
2916
+ * upgrade request (`createLunoraClient`'s `withAuthWebSocket`), which a raw
2917
+ * `new globalThis.WebSocket(url)` would silently bypass.
2918
+ *
2919
+ * A socket to this client's own WebSocket host over the same transport
2920
+ * security, constructed without its own subprotocols, offers this client's
2921
+ * bearer the way the client's sockets do (see `authTokenOnUpgrade`), read at
2922
+ * construction so it is the token current when the socket opens. Any other
2923
+ * host, or a plaintext `ws:` socket beside a `wss:` endpoint, gets its
2924
+ * arguments untouched: the bearer is a Lunora credential.
2925
+ */
2926
+ getWebSocketImpl(): typeof WebSocket | undefined;
2927
+ /**
2928
+ * `true` while {@link LunoraClientOptions.crossTabSync} is on and this tab
2929
+ * is not the elected leader, including the election window before it knows
2930
+ * whether another tab leads. Such a tab holds no socket: its subscriptions
2931
+ * see only the frames the leader relays for queries the leader holds too,
2932
+ * so a read that must resolve goes over HTTP instead of waiting on a push.
2933
+ */
2934
+ isCrossTabFollower(): boolean;
2935
+ /**
2936
+ * Whether a live query on `shardKey` can expect its value to be pushed: by a
2937
+ * socket that is open or still on its first connect attempt, or by the
2938
+ * polling fallback. `false` once a connect attempt has failed to reach `open`
2939
+ * since the socket last did and polling is not delivering instead, where a
2940
+ * read that must resolve should go over HTTP rather than wait on a push. A
2941
+ * shard with no connection yet expects one: subscribing opens it.
2942
+ */
2943
+ expectsPush(options?: {
2944
+ shardKey?: string;
2945
+ }): boolean;
2946
+ /**
2947
+ * Read the current value for a {@link ClientQueryRef}. Returns
2948
+ * `ref.defaultValue` when no value has been explicitly set.
2949
+ */
2950
+ getClientQuery<T>(ref: ClientQueryRef<T>): T;
2951
+ /**
2952
+ * Set a new value for `ref` and notify every subscriber. Pass `undefined`
2953
+ * to reset the slot to `ref.defaultValue`.
2954
+ */
2955
+ setClientQuery<T>(ref: ClientQueryRef<T>, value: T): void;
2956
+ /**
2957
+ * Subscribe to changes for `ref`. The callback is NOT invoked on
2958
+ * registration — call {@link getClientQuery} for the current value.
2959
+ * Returns an unsubscribe function.
2960
+ */
2961
+ subscribeClientQuery(ref: ClientQueryRef, callback: (value: unknown) => void): Unsubscribe;
2962
+ /**
2963
+ * Reset a {@link ClientQueryRef} to its default value, notifying every
2964
+ * subscriber. Equivalent to `setClientQuery(ref, ref.defaultValue)` but
2965
+ * removes the stored entry so a future {@link getClientQuery} returns
2966
+ * the default rather than an explicitly-set value.
2967
+ */
2968
+ resetClientQuery(ref: ClientQueryRef): void;
2969
+ /**
2970
+ * Capture a snapshot of the current live query value at call time and
2971
+ * produce a `() => boolean` precondition that compares it against the
2972
+ * value at replay time (on queue drain / reconnect).
2973
+ *
2974
+ * Delegates to {@link createSnapshotPrecondition} with this client bound —
2975
+ * no need to pass `client` explicitly. The comparison semantics (including
2976
+ * how an absent subscription is treated) live there, in one place.
2977
+ * @example
2978
+ * ```ts
2979
+ * client.mutation(api.todos.update, { id, text }, {
2980
+ * precondition: client.snapshotPrecondition(api.todos.list, { userId }),
2981
+ * });
2982
+ * ```
2983
+ */
2984
+ snapshotPrecondition(functionRef: FunctionReference, args: Record<string, unknown>, shardKey?: string): () => boolean;
2985
+ /**
2986
+ * Resolves once the durable read cache has been loaded into memory. When
2987
+ * `hydrateOnStart` is not configured or no query cache adapter is active,
2988
+ * returns an already-resolved promise so callers can always await it
2989
+ * unconditionally.
2990
+ *
2991
+ * Framework adapters (React, Vue, etc.) use this to gate the first
2992
+ * (enabled) render of a live query behind hydration, so the user sees
2993
+ * cached data instead of an undefined flash before the socket round-trip.
2994
+ */
2995
+ whenReady(options?: {
2996
+ signal?: AbortSignal;
2997
+ }): Promise<void>;
2998
+ /**
2999
+ * Synchronously reports whether {@link whenReady} has already resolved (the
3000
+ * durable read cache is loaded, or none is configured). Framework adapters
3001
+ * read this to seed the hydration-gate state on the first render without
3002
+ * awaiting, then subscribe via {@link whenReady} for the pending case.
3003
+ */
3004
+ get isReady(): boolean;
3005
+ /**
3006
+ * Synchronously peek at a value the durable read cache loaded for the given
3007
+ * function path + args + shard key. Returns `undefined` when:
3008
+ *
3009
+ * - No query cache adapter is configured.
3010
+ * - Hydration hasn't completed yet (race — await {@link whenReady} first).
3011
+ * - The cached value's identity fingerprint doesn't match the current auth.
3012
+ *
3013
+ * Unlike the internal {@link takeHydratedCache}, this is a READ-ONLY peek:
3014
+ * the cached entry stays in `hydratedQueryCache` so the subscription created
3015
+ * later by {@link subscribe} consumes it normally.
3016
+ */
3017
+ peekHydratedQuery(functionPath: string, args: Record<string, unknown>, shardKey?: string): unknown;
3018
+ /**
3019
+ * Same lookup as {@link peekHydratedQuery} for a caller that already holds the
3020
+ * `stableWireKey`-encoded args string, so the args are not canonicalised again.
3021
+ */
3022
+ peekHydratedQueryByKey(functionPath: string, argsKey: string, shardKey?: string): unknown;
3023
+ /**
3024
+ * Peek at the **current live value** of an active subscription, reporting
3025
+ * whether one exists at all rather than just its value. `present` is `false`
3026
+ * when no subscription is open for the given `(functionPath, args, shardKey)`;
3027
+ * `value` is the subscription's `lastValue`, which includes any optimistic
3028
+ * overlay. `answered` is `false` while an open subscription holds no answer
3029
+ * (never answered, or blanked by a cold reconnect), when `value` is absence
3030
+ * rather than evidence.
3031
+ *
3032
+ * The two are separate because a caller like the snapshot precondition has to
3033
+ * tell "no subscription is active, so this read knows nothing" apart from
3034
+ * "the subscription is active and its value is `undefined`" — collapsing both
3035
+ * into a bare `undefined` return makes an unmounted component look like a
3036
+ * changed value, and drops the queued write.
3037
+ *
3038
+ * Unlike {@link peekHydratedQuery} (which reads from the durable read cache
3039
+ * and is independent of active subscriptions), this reflects the current
3040
+ * in-memory state of an already-opened subscription.
3041
+ */
3042
+ peekActiveQuerySnapshot(functionPath: string, args: Record<string, unknown>, shardKey?: string): {
3043
+ answered: boolean;
3044
+ present: boolean;
3045
+ value: unknown;
3046
+ };
3047
+ query<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
3048
+ shardKey?: string;
3049
+ signal?: AbortSignal;
3050
+ }): Promise<ReturnOf<F>>;
3051
+ /**
3052
+ * Batch several independent calls into ONE round trip (plan 088). Each call is
3053
+ * dispatched server-side exactly as an individual RPC — per-shard
3054
+ * authorization, `(identity, mutationId)` idempotency, and custom-mutator
3055
+ * watermark ordering are all preserved — and the worker splits the batch by
3056
+ * shard so calls to different shards fan out to their own DOs. Results are
3057
+ * demuxed back in input order; a failing call does NOT fail the batch (its
3058
+ * slot carries `{ ok: false, error }`, with `.code`/`.data` reconstructed like
3059
+ * a single call). Args/results ride the value codec (bytes/bigint survive).
3060
+ *
3061
+ * No promise pipelining and no capability passing — a call's args cannot
3062
+ * reference another call's result (see plan 088 §fence; capabilities are
3063
+ * incompatible with DO hibernation).
3064
+ *
3065
+ * The whole exchange, response body included, is bounded by
3066
+ * {@link LunoraClientOptions.rpcTimeoutMs}, rejecting with a retryable
3067
+ * {@link TransportError}. A function's kind is a type-level phantom with no
3068
+ * runtime marker, so unlike {@link action} a batched call cannot be exempted:
3069
+ * call a long-running action through `action()` instead.
3070
+ */
3071
+ batch(calls: ReadonlyArray<{
3072
+ args?: Record<string, unknown>;
3073
+ fn: FunctionReference;
3074
+ shardKey?: string;
3075
+ }>): Promise<BatchSlot[]>;
3076
+ /**
3077
+ * Invoke a mutation. Errors propagate as rejections.
3078
+ *
3079
+ * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
3080
+ * only when the targeted shard's socket was open at least once already
3081
+ * (`wasEverConnected`), so the registry / resubscribe handshake has run.
3082
+ * Mutations issued before the very first WS connect to a shard fail fast.
3083
+ * Opt into queueing-before-first-connect via
3084
+ * `OfflineQueueOptions.queueBeforeFirstConnect`. Pass `onlineOnly: true` to
3085
+ * refuse a write instead of queueing it — see {@link MutationCallOptions.onlineOnly}.
3086
+ *
3087
+ * **Return-value caveat — the queued paths do not carry the server's result.**
3088
+ * The declared `Promise<ReturnOf<F>>` only holds when the write goes straight
3089
+ * to the server. Once a write is queued:
3090
+ *
3091
+ * - with a durable `outbox` configured, this resolves **immediately with
3092
+ * `undefined`** (typed as `ReturnOf<F>`) the moment the write is handed to
3093
+ * the outbox — the replay happens later, out of band, with no awaiter;
3094
+ * - with the built-in offline queue, it stays pending until the replay lands
3095
+ * and then resolves with the replayed call's value.
3096
+ *
3097
+ * So `const id = await client.mutation(api.todos.create, …)` is `undefined`
3098
+ * for every write issued while offline under an outbox. Generate ids
3099
+ * client-side (or read them back from a subscription) rather than depending
3100
+ * on a mutation's return value in an offline-capable app —
3101
+ * {@link LunoraClient.importRows} documents the same caveat for its counts.
3102
+ */
3103
+ mutation<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>> & OnlineOnlyOption<F>): Promise<ReturnOf<F>>;
3104
+ /**
3105
+ * Whether a {@link mutation} on `shardKey` would be queued (offline queue or
3106
+ * durable outbox) rather than fail when the network is down. `false` before
3107
+ * the shard's first connect (unless `queueBeforeFirstConnect` is set) and on
3108
+ * a client with no WebSocket. A caller that wants to hold a write until the
3109
+ * network returns must do so itself when this is `false`.
3110
+ */
3111
+ canQueueOffline(shardKey?: string): boolean;
3112
+ action<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: ActionCallOptions): Promise<ReturnOf<F>>;
3113
+ /**
3114
+ * Bulk-import `rows` through a mutation that accepts a batch, chunked so a large
3115
+ * dataset lands in a bounded number of round-trips.
3116
+ *
3117
+ * **Queued chunks:** `imported` counts only rows the server committed. A chunk a
3118
+ * durable outbox took instead (offline, or behind older queued writes) is counted
3119
+ * in `queued`; the outbox replays it later under the same key. The built-in
3120
+ * offline queue holds the call until each chunk commits, so its rows land in
3121
+ * `imported`. Report "migration complete" only when `queued` is `0`.
3122
+ *
3123
+ * This is the one-shot migration / seed path: "I have 20k rows client-side and a
3124
+ * server mutation that inserts many at once". Doing it by hand goes wrong in two
3125
+ * predictable ways — a serial per-row loop pays one round-trip *and* one watermark
3126
+ * wait per row (a 200-row import becomes 200 sequential hops), while a single
3127
+ * giant call blows the DO's batch limit. So: chunk, send sequentially, and give
3128
+ * each chunk a stable idempotency key derived from `importId` + its index, so a
3129
+ * resumed or retried import doesn't double-insert the chunks that already landed
3130
+ * (for an anonymous caller only while the `clientId` is the same; see `importId`).
3131
+ *
3132
+ * The server mutation is yours (Lunora can't guess the table or the row shape);
3133
+ * back it with `ctx.db.insertMany(...)`, or `insertManyUnsafe(...)` for data you
3134
+ * vouch for. `chunkSize` defaults to 500, matching the DO's default batch cap.
3135
+ *
3136
+ * ```ts
3137
+ * await client.importRows(api.migrate.importNodes, nodes, {
3138
+ * importId: `migrate-${userId}`,
3139
+ * onProgress: ({ done, total }) => setProgress(done / total),
3140
+ * shardKey: userId,
3141
+ * toArgs: (chunk) => ({ nodes: chunk }),
3142
+ * });
3143
+ * ```
3144
+ */
3145
+ importRows(function_: FunctionReference, rows: ReadonlyArray<unknown>, options?: {
3146
+ /** Rows per call. Defaults to 500 — the DO's default batch cap. */
3147
+ chunkSize?: number;
3148
+ /**
3149
+ * Stable id for this import run. Each chunk is sent under
3150
+ * `${importId}:${chunkIndex}` as its mutation id, so re-running an import
3151
+ * that uses the SAME `chunkSize` re-sends each chunk under its prior key
3152
+ * and the server dedupes it instead of inserting twice.
3153
+ *
3154
+ * CAVEAT — the key is POSITIONAL, not content-based: it pins on the chunk
3155
+ * INDEX, not on the rows inside it. Resume or retry with a DIFFERENT
3156
+ * `chunkSize` (or a changed row ordering) and index N now covers different
3157
+ * rows than the first run's index N; the server sees a duplicate key and
3158
+ * SILENTLY DROPS those rows. Keep `chunkSize` (and the row order) identical
3159
+ * across resumes of the same `importId`. Omit `importId` only for a
3160
+ * throwaway import where double-insertion is acceptable.
3161
+ *
3162
+ * CAVEAT — anonymous callers: the server scopes the key to the signed-in
3163
+ * user, or to the client's `clientId` when nobody is signed in. A
3164
+ * `LunoraClient` mints a fresh `clientId` on every construction, so an
3165
+ * anonymous import resumed after a reload is not deduped and inserts the
3166
+ * landed chunks again. Pass a persisted `clientId` to the constructor to
3167
+ * resume anonymously, or run the import signed in.
3168
+ */
3169
+ importId?: string;
3170
+ /**
3171
+ * Called after each chunk is accepted — for a progress bar. `done` counts
3172
+ * committed and queued rows alike; the result separates them.
3173
+ */
3174
+ onProgress?: (progress: {
3175
+ done: number;
3176
+ total: number;
3177
+ }) => void;
3178
+ /** Routes every chunk to one shard's DO. */
3179
+ shardKey?: string;
3180
+ /** Build the mutation args for one chunk. Defaults to `{ rows: chunk }`. */
3181
+ toArgs?: (chunk: ReadonlyArray<unknown>) => Record<string, unknown>;
3182
+ }): Promise<{
3183
+ chunks: number;
3184
+ imported: number;
3185
+ queued: number;
3186
+ }>;
3187
+ /**
3188
+ * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
3189
+ * WebSocket. `onJobs` fires with the full list on connect and on every
3190
+ * change (schedule / cancel / alarm-fire). Reconnects with the client's
3191
+ * configured backoff. Requires `wsTicket` to be set to an admin credential
3192
+ * (the browser can't send an `Authorization` header on a WS) — a
3193
+ * {@link WsTokenProvider} minting the ephemeral sub-token, so the master
3194
+ * credential stays out of the URL. Returns an
3195
+ * unsubscribe function that closes the socket and stops reconnecting.
3196
+ */
3197
+ subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
3198
+ /**
3199
+ * Subscribe to a live query. The callback fires with the current value (from
3200
+ * the durable read cache, when one is hydrated) and again on every server
3201
+ * frame; the returned function unsubscribes.
3202
+ *
3203
+ * Subscriptions are deduped by `(functionPath, args, shardKey)` — a second
3204
+ * `subscribe` for the same triple joins the existing registration and shares
3205
+ * its value, cursor and optimistic layers.
3206
+ *
3207
+ * Available on a `crossTabSync` FOLLOWER tab, unlike the other socket-backed
3208
+ * surfaces: registering here is exactly what lets the cross-tab relay deliver
3209
+ * the leader's broadcasts (see the note in the body). The caveat is that the
3210
+ * channel only carries the LEADER's own subscriptions outward, so a follower
3211
+ * sees this query's frames only while the leader holds it too — see
3212
+ * {@link LunoraClientOptions.crossTabSync}.
3213
+ */
3214
+ subscribe<F extends FunctionReference>(function_: F, args: ArgsOf<F>, callback: (data: ReturnOf<F>) => void, options?: {
3215
+ onCheckpoint?: (watermark: SyncWatermark) => void;
3216
+ onError?: SubscriptionErrorCallback;
3217
+ shardKey?: string;
3218
+ signal?: AbortSignal;
3219
+ }): Unsubscribe;
3220
+ /**
3221
+ * Subscribe to a declarative **shape** — server-side partial replication
3222
+ * scoped by `shardBy` + the shape's predicate + RLS. The parallel to
3223
+ * {@link subscribe} for the poke protocol: the client sends the shape *name* +
3224
+ * validated `args` (never a `where` the client could forge), the server seeds
3225
+ * the current membership as an insert-poke and streams live membership diffs.
3226
+ * Each applied poke materializes the shape's rowset and invokes `callback`.
3227
+ *
3228
+ * Unlike {@link subscribe}, shape subscriptions are NOT deduped by
3229
+ * (name, args): the server resolves them under the socket's verified identity,
3230
+ * so every call gets its own id + view. The returned function unsubscribes.
3231
+ *
3232
+ * Not available on a `crossTabSync` FOLLOWER tab: shape pokes are not part of
3233
+ * the leader→follower broadcast set, so a follower's shape could never
3234
+ * resolve. The returned handle is inert there, and `options.onError` is
3235
+ * invoked with `NOT_IMPLEMENTED` — see
3236
+ * {@link LunoraClientOptions.crossTabSync}. Reporting rather than throwing is
3237
+ * deliberate: `@lunora/db`'s shape-backed `createCollection` calls this from
3238
+ * its sync path, where a throw takes the collection out entirely, while
3239
+ * `onError` is the seam it already routes to `markReady()`.
3240
+ */
3241
+ subscribeShape(shape: {
3242
+ args?: Record<string, unknown>;
3243
+ name: string;
3244
+ }, callback: ShapeCallback, options?: {
3245
+ onCheckpoint?: (watermark: SyncWatermark) => void;
3246
+ onError?: SubscriptionErrorCallback;
3247
+ shardKey?: string;
3248
+ }): Unsubscribe;
3249
+ /**
3250
+ * Open a streaming query. The function reference must be a
3251
+ * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
3252
+ * the type constraint catches accidental use of a query/mutation/action
3253
+ * reference at compile time. The returned iterable yields one element per
3254
+ * chunk frame the server pushes, terminating when the server sends
3255
+ * `complete` or the consumer calls `.cancel()`. Errors arrive as a
3256
+ * rejection on the next `next()`.
3257
+ *
3258
+ * Streams ride the same WS as subscriptions and share the unsubscribe
3259
+ * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id on
3260
+ * the socket the stream runs over. For an ephemeral stream the DO aborts the
3261
+ * in-flight iterator. For a `durable` stream, cancelling detaches this
3262
+ * consumer and the run keeps going: it finishes and stays readable for the
3263
+ * next attach. A cancel made while the socket is down is dropped rather
3264
+ * than queued, because the server already detached every consumer on that
3265
+ * socket when it closed.
3266
+ *
3267
+ * Stream-start frames buffered while the socket is (re)connecting are
3268
+ * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
3269
+ * cap drops the oldest queued frame (and fails its consumer) so a stuck
3270
+ * reconnect can't OOM the page.
3271
+ */
3272
+ stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F>, options?: {
3273
+ durable?: boolean;
3274
+ maxBuffer?: number;
3275
+ shardKey?: string;
3276
+ }): StreamIterable<ReturnOf<F>>;
3277
+ /**
3278
+ * Open a typed **HTTP-SSE route stream** (`httpRoute.<verb>(path).stream()`).
3279
+ * Distinct from {@link LunoraClient.stream}, which consumes the WS procedure
3280
+ * stream (`kind: "stream"`): this one opens the route's own URL with `fetch`
3281
+ * and parses the Server-Sent Events framing the route pump writes (`data:`
3282
+ * chunks, a final `event: complete`, an `event: error` on throw).
3283
+ *
3284
+ * The reference comes from the generated `httpStreams.*` registry, so the
3285
+ * yielded chunk type is the route handler's yielded type. Cancelling the
3286
+ * returned iterable (or aborting `options.signal`) aborts the fetch, which
3287
+ * the server handler observes via its `signal`. The client's bearer token
3288
+ * (when set) rides as an `authorization` header.
3289
+ */
3290
+ httpStream<Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: {
3291
+ headers?: Record<string, string>;
3292
+ maxBuffer?: number;
3293
+ signal?: AbortSignal;
3294
+ }): StreamIterable<HttpStreamChunkOf<Ref>>;
3295
+ close(): void;
3296
+ /**
3297
+ * A genuine credential change: reject the queued writes that can no longer
3298
+ * replay as the incoming identity, and evict the session the previous one
3299
+ * left live. `true` when it evicted, which reconnects every socket cold.
3300
+ */
3301
+ private retirePreviousIdentity;
3302
+ /**
3303
+ * How the open sockets must follow a bearer change when the transport
3304
+ * presents the bearer on the upgrade (React Native's `Authorization`
3305
+ * header). An open upgrade keeps the token it was made with for its whole
3306
+ * life, and a browser socket never carries it, so without
3307
+ * `authTokenOnUpgrade` nothing reconnects.
3308
+ *
3309
+ * A sign-in from signed-out is `"cold"`: the sockets upgraded anonymously,
3310
+ * and no view may resume from an anonymous cursor. A refreshed bearer under
3311
+ * an unchanged identity is `"warm"`: the subscriptions resume from their
3312
+ * cursors.
3313
+ *
3314
+ * A sign-out or an account switch leaves a previous identity behind and is
3315
+ * evicted by `setAuthToken` before this is asked.
3316
+ */
3317
+ private reconcileUpgradeBearer;
3318
+ /**
3319
+ * The subprotocols a socket the worker authenticates offers on its upgrade.
3320
+ * With {@link LunoraClientOptions.authTokenOnUpgrade} and a bearer set, the
3321
+ * bearer rides `Sec-WebSocket-Protocol` (see `shared/ws-bearer-protocol.ts`),
3322
+ * the one handshake header a browser can set, and never the URL.
3323
+ */
3324
+ private upgradeProtocols;
3325
+ private applyUpgradeBearer;
3326
+ /** Guard shared by every public entry point: a closed client accepts no further calls. */
3327
+ private assertOpen;
3328
+ /**
3329
+ * `true` when this tab is a cross-tab FOLLOWER of a live leader — i.e. it
3330
+ * will not open a socket of its own and another tab is known to hold one.
3331
+ *
3332
+ * Deliberately NOT just `!isLeader()`. Every `crossTabSync` client is a
3333
+ * non-leader for the first `leaderTimeout` of its life, while its
3334
+ * claim-leadership probe is outstanding; a lone tab self-promotes at the end
3335
+ * of that window and `onBecomeLeader` opens the sockets and replays every
3336
+ * registered subscription. That window is a legitimate, self-healing defer,
3337
+ * not a failure. A KNOWN leader on another tab is the state that never heals.
3338
+ */
3339
+ private followsAnotherTab;
3340
+ /**
3341
+ * Reject a call that needs a socket this tab will never have.
3342
+ *
3343
+ * The cross-tab protocol is one-directional: a leader broadcasts
3344
+ * `subscription-data` / `-error` / `-settled` / `connection-status` to
3345
+ * followers, and a follower has no frame with which to tell the leader what
3346
+ * it needs (see `cross-tab.ts`'s `WsFollowerMessage`, which is exactly
3347
+ * heartbeat / claim-leadership / yield-leadership). `subscribeShape` /
3348
+ * `whisper*` / `setConnectionContext` / `acquireConnectionContext` — none of
3349
+ * which the leader broadcasts at all — therefore never worked on a follower
3350
+ * under any circumstances: each returned a handle that looked live, fired no
3351
+ * callback, raised no error, and reported `connectionStatus() ===
3352
+ * "connected"` (mirrored from the leader).
3353
+ *
3354
+ * `subscribe` is deliberately NOT in that set. A follower's `subscribe`
3355
+ * registers the key the leader's broadcast is matched against, so it is the
3356
+ * mechanism the relay is built on rather than a surface that silently fails.
3357
+ * A follower sees a query only while the leader holds the same
3358
+ * `(fn, args, shardKey)` — that is the documented shape of the option, not a
3359
+ * defect.
3360
+ *
3361
+ * `subscribeShape` and `stream()` reach the same outcome by a different
3362
+ * route: they fail the handle they return rather than throwing at the call,
3363
+ * because both are driven from a sync/render path where a throw destroys the
3364
+ * caller instead of degrading it. See
3365
+ * {@link LunoraClientOptions.crossTabSync} for what the option does and does
3366
+ * not cover.
3367
+ */
3368
+ private assertLeaderOwnedSurface;
3369
+ /**
3370
+ * Clear every timer a {@link ShardConnection} can have armed.
3371
+ *
3372
+ * One function because both teardown paths must clear all three and a fourth
3373
+ * timer would otherwise have to be remembered in two places — which is how a
3374
+ * leak gets added rather than written.
3375
+ */
3376
+ private clearConnectionTimers;
3377
+ /**
3378
+ * Whether anything still needs `key`'s socket: a live or shape
3379
+ * subscription, a stream, a whisper topic, a connection context (presence
3380
+ * rides its `connect` envelope), or a write queued for or flushing to it.
3381
+ */
3382
+ private shardInUse;
3383
+ /**
3384
+ * Close a non-default shard's socket once nothing uses it, after
3385
+ * {@link IDLE_SHARD_CLOSE_MS} so a quick leave-and-return reuses it. The
3386
+ * connection record is dropped; the shard is remembered in
3387
+ * {@link idleClosedShards}, so writes to it keep the gating a connected shard
3388
+ * gets — sent over HTTP, and queued if the network is down (a queued write
3389
+ * reopens the socket to flush). A later subscription reconnects it.
3390
+ * Every release path calls this; the timer re-checks, so a shard picked up
3391
+ * again in the meantime stays open.
3392
+ */
3393
+ private releaseIdleShard;
3394
+ /** Forget a finished or cancelled stream; it may have been what held its shard open. */
3395
+ private forgetStream;
3396
+ /**
3397
+ * Tear down one {@link ShardConnection}'s live state: clear its reconnect/
3398
+ * connect timers, stop its heartbeat, and close its socket (if any).
3399
+ * Shared by `close()` (terminal) and the cross-tab `onStopBeingLeader`
3400
+ * handler (demoted, but still alive) so a demoted leader can't leak a
3401
+ * pending `reconnectTimer` or an open socket's `heartbeatTimer` the way
3402
+ * an inline `conn.socket?.close()` — which skips both — used to.
3403
+ *
3404
+ * Settles this shard's in-flight streams first. The teardown clears
3405
+ * `conn.socket` BEFORE the real `close` event fires, so that event trips
3406
+ * `openManagedSocket`'s identity guard (`conn.socket !== socket`) and
3407
+ * returns — meaning `handleDisconnect`, the only other place that settles a
3408
+ * shard's streams, never runs for this connection again. `close()` already
3409
+ * failed and cleared `this.streams` before it gets here, so this is a no-op
3410
+ * on that path; the cross-tab demotion path is the one where a consumer's
3411
+ * `for await` used to block forever with no error and no completion.
3412
+ */
3413
+ private teardownConnection;
3414
+ /**
3415
+ * Build (but do not start) this client's `TabCoordinator`. Extracted out of
3416
+ * the constructor so `setAuthToken` can rebuild it on an identity change —
3417
+ * the default channel name embeds the identity fingerprint (see below), so
3418
+ * a new identity needs a new coordinator on a new channel. The callback
3419
+ * bodies are the drift-sensitive region (a hand-merged identity guard on
3420
+ * the shard message listener sits ahead of an extracted `lastFrameAt`
3421
+ * stamp elsewhere in this file) — moved verbatim, not reflowed.
3422
+ */
3423
+ private createTabCoordinator;
3424
+ /** The body of {@link batch}, abortable by the caller's deadline (`batch`'s own, or the polling fallback's timeout). */
3425
+ private sendBatch;
3426
+ /**
3427
+ * The body of {@link mutation}, also saying whether the write committed. `committed` is
3428
+ * `false` only when a durable outbox took the write, which resolves at once
3429
+ * with no server result.
3430
+ */
3431
+ private runMutation;
3432
+ /**
3433
+ * Refuses an `onlineOnly` write whose shard's connection is down or reconnecting,
3434
+ * the states in which a normal write is queued. Reads the gate synchronously, so
3435
+ * the refusal is immediate. Called again after the optimistic updates have been
3436
+ * applied, which is user code and may have dropped the shard: `optimisticRollbacks`
3437
+ * unwinds those layers before the refusal.
3438
+ */
3439
+ private refuseOnlineOnlyWhenDown;
3440
+ /**
3441
+ * Whether this tab's own socket is open for the shard. A follower tab has no socket
3442
+ * of its own: the status it reads is the leader's, which carried no part of the
3443
+ * request that just failed, so it never counts as open.
3444
+ */
3445
+ private ownSocketOpen;
3446
+ /**
3447
+ * Whether a write on `shardKey` would be queued if it failed right now, and
3448
+ * which gate would queue it. A follower tab has no `ShardConnection` of its own —
3449
+ * `connectionGateState` derives the same triple from the mirrored leader status.
3450
+ */
3451
+ private writeQueueGate;
3452
+ /**
3453
+ * Unwind a direct write's optimistic layers after its RPC threw — or keep
3454
+ * them, when it threw only because a COMMITTED result did not decode: the
3455
+ * write happened, so its predicted value stays until the confirming frame
3456
+ * supersedes it.
3457
+ */
3458
+ private settleFailedDirectWrite;
3459
+ /**
3460
+ * Persist a mutation that can't go out on the wire right now (offline, or
3461
+ * mid-reconnect after a prior connect). The optimistic update has already
3462
+ * been applied by `mutation`; this only chooses the durable write path and
3463
+ * rolls the optimistic write back if persistence is rejected.
3464
+ *
3465
+ * Two paths: when an `outbox` sink is wired (the `@lunora/db` executor) it
3466
+ * owns persistence + at-least-once replay, so we delegate and return
3467
+ * optimistically (confirmation rides the synced view). Otherwise the
3468
+ * built-in `OfflineQueue` resolves/rejects the returned promise on replay.
3469
+ */
3470
+ private enqueueOfflineMutation;
3471
+ /**
3472
+ * Is a write for this shard still sitting in the durable path, waiting to
3473
+ * replay? Drives the FIFO gate in {@link mutation}: a live write must never
3474
+ * overtake one that is queued (or held) ahead of it.
3475
+ *
3476
+ * Whichever durable path is wired answers: the built-in {@link OfflineQueue}
3477
+ * knows its entries' shard keys, while an {@link OutboxSink} reports only a
3478
+ * process-wide depth (the executor's pending count is not shard-scoped) —
3479
+ * over-inclusion there costs a write a trip through the outbox it could have
3480
+ * skipped, which is the same trip the writes ahead of it are taking anyway.
3481
+ * A sink that reports nothing keeps the previous behaviour.
3482
+ */
3483
+ private hasPendingWriteAhead;
3484
+ /**
3485
+ * Restore offline mutations persisted in a prior session and open a socket
3486
+ * for each shard they target so they flush once the WS reconnects. Failures
3487
+ * are swallowed — a broken durable store must not stop the client booting.
3488
+ */
3489
+ private hydratePersistedQueue;
3490
+ /**
3491
+ * Re-queue the durable offline writes — but only as the multi-tab LEADER. The
3492
+ * persisted queue is shared across a profile's tabs; without coordination
3493
+ * every tab would re-queue and replay the same writes (correct only because
3494
+ * the server dedups by idempotency key, but wasteful + racy). A Web Lock makes
3495
+ * exactly one tab hydrate; it holds the lock for its lifetime, so when it
3496
+ * closes another tab acquires the lock and takes over. Falls back to
3497
+ * unconditional hydration where Web Locks are unavailable (React Native, older
3498
+ * browsers, SSR) — single-context there, so no coordination is needed.
3499
+ */
3500
+ private hydrateAsOutboxLeader;
3501
+ /**
3502
+ * Load every cached query so a `subscribe()` for the key seeds its initial
3503
+ * value off disk.
3504
+ *
3505
+ * The load is asynchronous but every framework adapter subscribes
3506
+ * SYNCHRONOUSLY at mount, so the subscriptions that most want the cache
3507
+ * already exist by the time it lands. Those are seeded here and their entry
3508
+ * is dropped: an entry that stayed in {@link hydratedQueryCache} behind a
3509
+ * live subscription would be consumed by the NEXT subscribe of the same key
3510
+ * (a remount after navigating away) and replay the previous session's value
3511
+ * over whatever the socket had since delivered. A cache entry therefore
3512
+ * never outlives a live subscription for its key — it is either handed to
3513
+ * that subscription or discarded.
3514
+ *
3515
+ * Only keys with no live subscription are held for a later `subscribe()`;
3516
+ * the identity gate applies to both paths, so a signed-out cache never leaks
3517
+ * into a new session.
3518
+ */
3519
+ private hydrateQueryCache;
3520
+ /**
3521
+ * Hand a loaded read-cache entry to a subscription that was opened before
3522
+ * the load resolved — the same value, cursor and epoch {@link subscribe}
3523
+ * would have taken from {@link takeHydratedCache} had the load finished
3524
+ * first, so the cursor still rides the `subscribe` frame as `sinceSeq` (that
3525
+ * frame only goes out once the socket opens, well after this microtask).
3526
+ *
3527
+ * A no-op once the socket has delivered anything for this key: a live value
3528
+ * always beats the cache. Identity-gated exactly like `takeHydratedCache`.
3529
+ */
3530
+ private seedSubscriptionFromCache;
3531
+ /**
3532
+ * Move the durable read cache in or out of view as the CREDENTIAL changes —
3533
+ * which the identity fingerprint does not track: a sticky subject rides
3534
+ * across a token change (the account-switch shape), leaving the label
3535
+ * unmoved, so `setAuthToken`'s identity-change block never runs for it.
3536
+ * Revoke while that pairing is unchecked, and hand the values back once the
3537
+ * next session resolve confirms the credential really is that subject's.
3538
+ */
3539
+ private syncReadCacheToCredential;
3540
+ /**
3541
+ * A server frame owns this key now, so the read cache may neither take its
3542
+ * seeded value back ({@link revokeCacheSeededValues}) nor hold an entry for
3543
+ * a later `subscribe()` of the same key to replay a stale session over.
3544
+ */
3545
+ private dropCacheSeed;
3546
+ /**
3547
+ * Hand a cache-seeded entry back to {@link hydratedQueryCache} when its last
3548
+ * subscriber detaches, so the NEXT `subscribe()` of the same key can seed
3549
+ * from it again.
3550
+ *
3551
+ * Without this the hydrated cache was one-shot per key: {@link takeHydratedCache}
3552
+ * consumes the entry, the final unsubscribe drops the state that held its
3553
+ * value, and nothing re-seeds. Navigating away from a route and back while
3554
+ * offline therefore rendered `undefined` for the rest of the offline
3555
+ * session even though the durable store still held the rows. React hid it
3556
+ * behind TanStack's `gcTime`; every other adapter showed it immediately.
3557
+ *
3558
+ * Only a seed still listed in {@link cacheSeededQueries} moves — a server
3559
+ * frame calls {@link dropCacheSeed}, which clears both maps, so an entry
3560
+ * that is still here has not been superseded and is the freshest value this
3561
+ * client has for the key. That is the same map-to-map move
3562
+ * {@link revokeCacheSeededValues} makes, and it keeps the two maps disjoint:
3563
+ * an entry is either on display or waiting, never both.
3564
+ */
3565
+ private returnCacheSeed;
3566
+ /**
3567
+ * Take every value the durable read cache is currently displaying back off
3568
+ * screen, and return its entry to {@link hydratedQueryCache} so the identity
3569
+ * gate — not this call — decides whether it is ever shown again. A
3570
+ * same-credential refresh gets its offline-first value back the moment the
3571
+ * next session resolve re-confirms the subject; a genuine account switch
3572
+ * never does, and {@link clearQueryCacheForIdentityChange} wipes it.
3573
+ *
3574
+ * Only cache-seeded values: a server frame has been delivered under a socket
3575
+ * whose own identity is pinned and checked ({@link persistQueryValue}), and
3576
+ * dropping those would blank a live query on every token refresh.
3577
+ */
3578
+ private revokeCacheSeededValues;
3579
+ /**
3580
+ * Consume the hydrated read-cache entry for a key (if any), gated on
3581
+ * identity ({@link cachedQueryMatchesIdentity}). A mismatch yields
3582
+ * `undefined`, so a cache written under a different identity never leaks
3583
+ * into a new session.
3584
+ *
3585
+ * Only a MATCH is removed. The cache seeds a subscription's first value
3586
+ * once, so consuming a match is right — but destroying a mismatch is what
3587
+ * made a late-resolving identity unrecoverable: the subject typically lands
3588
+ * a `/get-session` after the first `subscribe()`, and by then the entry that
3589
+ * would have matched was gone. Left in place, {@link reseedFromHydratedCache}
3590
+ * can still hand it over when the identity settles.
3591
+ */
3592
+ private takeHydratedCache;
3593
+ /**
3594
+ * Hand every still-held read-cache entry to the subscription that is open on
3595
+ * its key, now that the identity has settled onto a resolved subject.
3596
+ *
3597
+ * `subscribe()` runs long before `/get-session` answers, so on a reload the
3598
+ * gate is asked its question with only a raw token in hand. When the token
3599
+ * itself matches, {@link cachedQueryMatchesIdentity} already says yes there
3600
+ * and then; when it has been refreshed since the value was cached, the only
3601
+ * honest answer at that moment is "unknown" — and this is where it becomes
3602
+ * knowable. {@link seedSubscriptionFromCache} is a no-op for any subscription
3603
+ * the socket has already fed, so a live value always wins.
3604
+ */
3605
+ private reseedFromHydratedCache;
3606
+ /**
3607
+ * Queue a coalesced read-cache write for a subscription's current value.
3608
+ * Latest-wins per key; flushed on a short debounce so a delta burst writes
3609
+ * once. No-op when the read cache is disabled or the value is undefined
3610
+ * (nothing to render offline).
3611
+ */
3612
+ private persistQueryValue;
3613
+ /** Drain {@link pendingCacheWrites} to the durable store. */
3614
+ private flushQueryCacheWrites;
3615
+ /**
3616
+ * Flush what is buffered for durable storage when the page is hidden or going
3617
+ * away: writes whose append was rejected get another try, and the debounced
3618
+ * read-cache writes (which would otherwise wait out their timer on a page
3619
+ * that never gets to run it) are written out. Browser lifecycle events only —
3620
+ * a runtime without them (SSR, workers, React Native) installs nothing.
3621
+ */
3622
+ private installPageHideFlush;
3623
+ /** Derive the aggregate status from the per-shard socket states. */
3624
+ private computeStatus;
3625
+ /**
3626
+ * The CDC cursor this client's view of `shardKey` is at — the highest
3627
+ * `serverCursor` any live subscription on that shard has advanced to.
3628
+ *
3629
+ * This is the baseline a `.dropStalePatches()` table judges a write against,
3630
+ * and the "highest" is what makes it sound: a cursor the client has reached on
3631
+ * ANY subscription means the shard's changelog up to that point has been
3632
+ * delivered here, so anything later is by definition something this client had
3633
+ * not seen when it composed the write.
3634
+ *
3635
+ * `undefined` when no subscription on the shard carries a cursor yet — a
3636
+ * client that has only ever issued one-shot RPCs, or a server with CDC off.
3637
+ * That is reported honestly rather than defaulted to `0`: a `0` baseline would
3638
+ * claim the client had seen NOTHING, which makes every field look changed and
3639
+ * would have the shard discard every patch it sends.
3640
+ */
3641
+ private baselineCursorFor;
3642
+ /**
3643
+ * The baseline a mutation is composed against. A replay keeps the one it was
3644
+ * queued with. A fresh write takes the shard's cursor here, before the first
3645
+ * `await` in `runMutation`: frames landing during a queue flush advance
3646
+ * `serverCursor`, so a baseline sampled after the wait would claim the caller
3647
+ * had seen changes that arrived after the write was composed. See
3648
+ * `OutboxMutation.baselineSeq`.
3649
+ */
3650
+ private composedBaselineFor;
3651
+ /**
3652
+ * One polling-fallback pass for a shard: re-run every live query bound to it
3653
+ * over the batch-RPC endpoint and feed each result into the same frame-apply
3654
+ * path a server `data` frame takes.
3655
+ *
3656
+ * Reusing {@link LunoraClient.batch} and {@link LunoraClient.handleDataMessage}
3657
+ * rather than forking either is the whole point. The apply path is where
3658
+ * optimistic layers rebase, the durable read cache is seeded, and subscriber
3659
+ * callbacks fan out; a second implementation of that would drift, and it would
3660
+ * drift into exactly the bugs the live path has already had fixed.
3661
+ *
3662
+ * The result is re-encoded on the way in because `batch` hands back a decoded
3663
+ * value while the frame path expects the wire form. `encodeWire` is identity
3664
+ * for JSON-safe data and lossless for the rest (that is the codec's contract),
3665
+ * so the round trip costs an allocation and changes nothing.
3666
+ *
3667
+ * **No cursor rides this path.** A poll is a full snapshot, so the frames it
3668
+ * synthesizes carry no `cursor`/`epoch` and cannot advance a subscription's
3669
+ * resume watermark — which is correct: the watermark describes what the CDC
3670
+ * log has delivered, and this delivered none of it. When the socket comes
3671
+ * back, the resubscribe resumes from the last cursor the SOCKET saw, and the
3672
+ * server re-snapshots whatever it needs to.
3673
+ *
3674
+ * A slot that failed is fanned to the subscription's error callbacks rather
3675
+ * than being swallowed: the whole point of the fallback is that the app keeps
3676
+ * working, and a query that is now failing (a permission change, a bad arg)
3677
+ * has to be visible.
3678
+ *
3679
+ * Resolves `false` when the request never reached the origin (`fetch` itself
3680
+ * rejected), which is how the fallback tells a device with no network from a
3681
+ * network that only refuses the upgrade. Any answer, an error envelope
3682
+ * included, resolves `true`.
3683
+ *
3684
+ * Optimistic layers need the same care without a cursor. The snapshot is taken
3685
+ * after the request is sent, so every write whose RPC had resolved before that
3686
+ * moment is already in it. Those layers are dropped against the acknowledgement
3687
+ * mark sampled before the send. A write acknowledged after the send may be
3688
+ * missing from the snapshot, so its layer stays.
3689
+ */
3690
+ private pollSubscriptions;
3691
+ /**
3692
+ * Whether a request reaches the origin at all: an empty batch, whose answer
3693
+ * (even a refusal) is the proof. `false` only when `fetch` itself rejects.
3694
+ */
3695
+ private probeOrigin;
3696
+ /** Recompute {@link syncStatus} and notify its listeners if any field changed. */
3697
+ private emitSyncStatus;
3698
+ /** Recompute the aggregate status and notify listeners if it changed. */
3699
+ private emitConnectionStatus;
3700
+ /**
3701
+ * Build a {@link MutationSettledEvent} from a queued entry and emit it on the
3702
+ * {@link onMutationSettled} channel. `item.id` is always assigned by the time
3703
+ * a write settles (`enqueue`/`hydrate` guarantee it), so the `?? ""` fallback
3704
+ * is unreachable — present only to satisfy the optional queue-id type.
3705
+ */
3706
+ private emitItemSettled;
3707
+ /**
3708
+ * Apply an optimistic update to the subscription that matches the mutation's
3709
+ * `(functionRef, args, shardKey)` triple, returning the rollback callbacks to
3710
+ * invoke if the mutation later fails.
3711
+ *
3712
+ * The registry is already indexed by exactly this triple via
3713
+ * `SubscriptionRegistry.key`, so at most one subscription can match. A direct
3714
+ * O(1) keyed lookup replaces the former O(N) linear scan over all subscriptions.
3715
+ *
3716
+ * `shardKey` normalization: both `undefined` and `""` map to the empty string
3717
+ * inside `SubscriptionRegistry.key` (via `?? ""`), so a mutation fired without
3718
+ * a shardKey correctly matches a subscription registered without one regardless
3719
+ * of whether the caller passed `undefined` or omitted the field.
3720
+ */
3721
+ private applyOptimisticUpdates;
3722
+ private applyOptionalOptimisticUpdate;
3723
+ /**
3724
+ * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
3725
+ * to the live subscription registry. Each `setQuery` registers a constant
3726
+ * optimistic LAYER on its target subscription (via the same engine the
3727
+ * per-call `optimistic` path uses), so the multi-query patch rebases onto
3728
+ * incoming deltas and drops gaplessly on its commit cursor — its `confirm` /
3729
+ * `rollback` closures are appended to the mutation's settle lists. A throwing
3730
+ * callback unwinds its own partial writes — LIFO over just the rollbacks it
3731
+ * produced — and is swallowed, so a buggy optimistic update can never fail the
3732
+ * mutation or leave a partial patch live.
3733
+ */
3734
+ private applyOptimisticUpdate;
3735
+ private getConnection;
3736
+ /**
3737
+ * Send an unsubscribe frame (tagged with its wire type) on the shard's
3738
+ * socket, or queue it for the next reconnect when the send can't go out.
3739
+ */
3740
+ private sendOrQueueUnsubscribe;
3741
+ /**
3742
+ * The `(wsState, hasSocket, wasEverConnected, polling)` state `mutation()`'s
3743
+ * offline-queue gate reads. On the leader/single-tab path this is exactly
3744
+ * the real `ShardConnection`'s state (byte-identical to the pre-cross-tab
3745
+ * behavior). A follower has no `ShardConnection` of its own (see
3746
+ * `ensureSocket`), so it derives the same triple from the mirrored
3747
+ * `leader.status`/`leader.wasEverConnected` instead: `"connected"` maps to
3748
+ * `"open"` (queue-eligible once `wasEverConnected`), `"connecting"` stays
3749
+ * `"connecting"` (the mid-reconnect queue branch), anything else is
3750
+ * `"idle"`. `hasSocket` is always `false` for a follower — it never has
3751
+ * one.
3752
+ *
3753
+ * `polling` is `true` while the HTTP polling fallback is reaching the origin
3754
+ * (the leader's mirrored `"polling"` on a follower). Writes then go straight
3755
+ * over HTTP, as they do while connected, instead of queueing for a socket
3756
+ * that may never open.
3757
+ *
3758
+ * `idleClosed` is `true` for a shard whose socket this client closed because
3759
+ * nothing used it (see {@link releaseIdleShard}). It was connected, so it
3760
+ * stays queue-eligible (`wasEverConnected`), but its socket is not "down":
3761
+ * a write is tried over HTTP first, as it went while the socket was open,
3762
+ * and queued only if the network turns out to be unreachable.
3763
+ */
3764
+ private connectionGateState;
3765
+ private getOrCreateConnection;
3766
+ /**
3767
+ * Open a managed WebSocket to a NON-shard endpoint and own its reconnect
3768
+ * loop + teardown. Two callers share it — {@link subscribeScheduledJobs}'s
3769
+ * admin socket and {@link connectWebSocket}'s `defineWebSocket` route — and
3770
+ * they must share it rather than each hand-roll it: the connect-timeout +
3771
+ * heartbeat/watchdog/identity-guard live in `openManagedSocket`, the backoff
3772
+ * policy in `createReconnect`, and reading `wsTicket` at connect time is what
3773
+ * lets a post-connect `setWsTicket()` rotation be picked up on the next
3774
+ * reconnect attempt instead of looping with a stale token. Registered on
3775
+ * {@link adminSocketTeardowns} so `close()` stops it too.
3776
+ *
3777
+ * `base` is the endpoint URL without `shard`/`token` params. `handlers`
3778
+ * parses the frames and observes the lifecycle; `handlers.shardKey` routes
3779
+ * the connection. The returned `resetBackoff` clears the reconnect backoff
3780
+ * once a payload frame proves the socket live, and `socket` is the current
3781
+ * transport (for a send), or `undefined` while it is not open.
3782
+ */
3783
+ private openSupplementarySocket;
3784
+ /**
3785
+ * The URL a supplementary socket — route and scheduled — is reached on: the configured
3786
+ * socket URL with its shard path replaced by `path`. The origin, any path prefix, and
3787
+ * any query the configured URL carries are kept, so a custom `wsUrl` host or proxy
3788
+ * applies to them too and the path never lands inside a query string.
3789
+ */
3790
+ private supplementaryUrl;
3791
+ private wsUrlFor;
3792
+ /**
3793
+ * Build the outbound RPC headers: JSON content type, optional bearer auth,
3794
+ * the optional mutation-replay idempotency key, and the D1 read-your-writes
3795
+ * bookmark when the caller opted into `attachBookmark`. The mutation id
3796
+ * rides both the direct send and any offline-queue replay of the same write,
3797
+ * so a mutation the server already committed returns its cached result
3798
+ * instead of running twice.
3799
+ */
3800
+ private rpcRequestHeaders;
3801
+ private rpc;
3802
+ /**
3803
+ * Authenticated request to a non-RPC admin endpoint (the scheduler list /
3804
+ * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
3805
+ * worker's `{ error: { code, message } }` envelope as a coded `Error` —
3806
+ * mirroring {@link rpc} so callers see the same failure shape.
3807
+ */
3808
+ private adminFetch;
3809
+ /**
3810
+ * Resolve the effective connection context for a shard: the most-recently
3811
+ * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
3812
+ * back to the imperative {@link setConnectionContext} override, then the
3813
+ * client-wide default. Returns `undefined` when none apply.
3814
+ */
3815
+ private effectiveConnectionContext;
3816
+ /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
3817
+ private refreshConnectionContext;
3818
+ /**
3819
+ * Send the one-shot `connect` envelope on an open shard socket. Always sent
3820
+ * once per socket open, so the server's `onConnect` hooks fire symmetrically
3821
+ * with `onDisconnect` (which the DO dispatches unconditionally at close for
3822
+ * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
3823
+ * hooks are registered, and answers with the socket's `identity` frame
3824
+ * (see `handleIdentityFrame`).
3825
+ *
3826
+ * The shard's registered context (or the client-wide default) rides along
3827
+ * when one is set — the DO records it on the attachment for replay to
3828
+ * `onDisconnect`. A socket with no registered context still announces itself;
3829
+ * the envelope simply omits `context`, which is optional on the wire.
3830
+ * Register a context — e.g. `setConnectionContext({})` — to attach app state
3831
+ * to the lifecycle dispatch.
3832
+ */
3833
+ private sendConnectEnvelope;
3834
+ /**
3835
+ * Re-send every shape subscription bound to `shardKey` over its (now open)
3836
+ * socket. Each frame carries the shape's last applied checkpoint, so the
3837
+ * server resumes from it — or re-seeds when the cursor fell below CDC
3838
+ * retention or the epoch forked.
3839
+ */
3840
+ private resendShapeSubscriptions;
3841
+ private ensureSocket;
3842
+ /** Supersede any in-flight credential mint, drop held sends, and bounce the shard sockets onto the new credentials. */
3843
+ private applyWsCredentialChange;
3844
+ /**
3845
+ * Open the shard socket now when both credentials are static, or after
3846
+ * resolving whichever is a {@link WsTokenProvider}. An async function runs
3847
+ * synchronously up to its first `await`, so the static path stays synchronous.
3848
+ */
3849
+ private startShardSocket;
3850
+ /**
3851
+ * Resolve each {@link WsTokenProvider} and open the shard socket with the
3852
+ * minted credentials. The connection is already in the `connecting` state, so the
3853
+ * async gap is race-guarded: a client `close()`, a `setWsToken` / `setWsTicket` bounce, or a
3854
+ * competing connect that landed first all abandon this attempt. A provider
3855
+ * failure fails the attempt through {@link handleDisconnect}, which arms the
3856
+ * normal reconnect backoff — a broken mint endpoint degrades to retries, not
3857
+ * a silent tokenless socket the admin gate would reject.
3858
+ */
3859
+ private openSocketWithProvidedCredentials;
3860
+ /** Construct the shard socket and wire its lifecycle handlers. The connection must already be in the `connecting` state. */
3861
+ private openSocket;
3862
+ /**
3863
+ * Tear down a stream the consumer cancelled, telling the server when its
3864
+ * socket is up.
3865
+ */
3866
+ private cancelStream;
3867
+ private handleDisconnect;
3868
+ /**
3869
+ * Mark every subscription and shape bound to `shardKey` as needing a fresh answer from the server.
3870
+ * `socketOpened` also forgets the values a poll delivered: the socket replaces that connection,
3871
+ * whereas a socket that merely failed to open (or dropped) leaves polling, and its answers, in place.
3872
+ */
3873
+ private markShardPendingAck;
3874
+ /**
3875
+ * Re-send `state`'s `subscribe` frame, but only once fewer than
3876
+ * {@link RESUBSCRIBE_CONCURRENCY} frames on this shard are still awaiting a
3877
+ * reply. Used by every path that resends MANY subscriptions at once — the
3878
+ * socket-open resubscribe and the cross-tab leader handover, which replays
3879
+ * every tab's subscriptions combined. A first subscribe (one frame, caller
3880
+ * paced) still goes straight out through {@link sendSubscribeIfOpen}.
3881
+ */
3882
+ private queueResubscribe;
3883
+ /**
3884
+ * Send queued `subscribe` frames until the in-flight window is full.
3885
+ *
3886
+ * Cannot wedge: a queued subscription whose frame does not actually go out
3887
+ * (socket closed, already acked, unsubscribed while queued) takes no slot,
3888
+ * every sent frame is released by the first server frame carrying its id
3889
+ * (see {@link handleServerMessage}) or by its watchdog, and a disconnect
3890
+ * drops the queue wholesale — the next `open` re-queues every subscription
3891
+ * on the shard, because `markShardPendingAck` un-acked them all.
3892
+ */
3893
+ private drainResubscribeQueue;
3894
+ /**
3895
+ * Stand down `id`'s watchdog on `conn` — its `subscribe` frame was answered or the socket went
3896
+ * away — and, if it held a pacing slot, free it so the next queued subscribe goes out.
3897
+ */
3898
+ private settleSubscribeWatchdog;
3899
+ /**
3900
+ * Abandon this connection's paced resubscribe: clear every watchdog and
3901
+ * forget both the in-flight and the waiting entries. Called wherever the
3902
+ * socket they were sent on goes away — the server drops that socket's
3903
+ * subscriptions anyway, and the next `open` re-queues all of them.
3904
+ */
3905
+ private clearResubscribeQueue;
3906
+ /** Send `state`'s `subscribe` frame when the shard's socket can carry it; `true` when a frame actually went out. */
3907
+ private sendSubscribeIfOpen;
3908
+ /**
3909
+ * Watch `state`'s `subscribe` frame: if no frame bearing its id arrives within
3910
+ * {@link RESUBSCRIBE_ACK_TIMEOUT_MS}, free the pacing slot it holds (if any) and
3911
+ * re-send the frame once. A server that drops the frame without replying (a
3912
+ * shard still waking, a swallowed message) would otherwise leave the
3913
+ * subscription un-acked on a perfectly live socket until the next reconnect.
3914
+ * One retry, not a loop: a query that is merely slow must not be re-run repeatedly.
3915
+ *
3916
+ * The retry gets one ack window of its own (`final`), after which the frame is
3917
+ * stood down so a later `subscribe()` can send again; otherwise a lost retry
3918
+ * refuses every send until the next reconnect. Kept in `unackedWatchdogs`, so
3919
+ * an ack or a teardown cancels either phase.
3920
+ */
3921
+ private armUnackedWatchdog;
3922
+ private sendShapeSubscribeIfOpen;
3923
+ private handleServerMessage;
3924
+ private handleErrorMessage;
3925
+ /** Count a query the server refused as answered, by the evidence {@link syncStatus} asks of it, emitting only on a change. */
3926
+ private markQueryRejected;
3927
+ private handlePokeEnd;
3928
+ /**
3929
+ * Commit one shape's slice of a poke. The decision and the state change live in
3930
+ * `commitPokeSlice`; this method only performs the I/O that follows it.
3931
+ */
3932
+ private applyPokePart;
3933
+ /**
3934
+ * Force the server to re-send a full snapshot for `state`, leaving the
3935
+ * currently displayed value alone until it lands. Used when a delta frame
3936
+ * cannot be applied: dropping the resume cursor is what makes the resubscribe
3937
+ * a snapshot rather than a `resume`, and un-acking is what lets
3938
+ * `sendSubscribeIfOpen` put the frame on the wire at all. Mirrors the shape
3939
+ * path's re-seed on a diverged base.
3940
+ */
3941
+ private resnapshotSubscription;
3942
+ /**
3943
+ * Apply one `data` frame. `snapshotMark` is set only for a frame synthesized
3944
+ * by a poll, which carries no cursor: see {@link pollSubscriptions}.
3945
+ */
3946
+ private handleDataMessage;
3947
+ /**
3948
+ * Handle a `resume` frame (Pillar 1b): the server proved nothing the
3949
+ * subscription reads changed since our `sinceSeq`, so the cached value is
3950
+ * still current. We keep `lastValue` as-is, mark the sub acked, and advance
3951
+ * the cursor (re-persisting so the next reconnect resumes from the newer
3952
+ * watermark). No callback fires — the value didn't change, and `subscribe()`
3953
+ * already replayed the cached value to every consumer synchronously.
3954
+ */
3955
+ private handleResumeMessage;
3956
+ /**
3957
+ * Handle a `settled` frame: a write touched one of this subscription's read
3958
+ * tables but produced a byte-identical result, so the server suppressed the
3959
+ * data frame. Like {@link handleResumeMessage} the value didn't change — we
3960
+ * advance the resume position and re-persist — but we ALSO surface the echoed
3961
+ * custom-mutator watermark via `onCheckpoint` so a `@lunora/db` list
3962
+ * collection drops the optimistic overlay for the confirmed write (otherwise
3963
+ * its checkpoint gate, fed only by data frames, would hang forever). Sent
3964
+ * only to custom-mutator clients; plain `useQuery` subscribers leave
3965
+ * `onCheckpoint` unset and this is a near no-op.
3966
+ */
3967
+ private handleSettledMessage;
3968
+ /**
3969
+ * Mark `state` acked and, when the frame carries a newer cursor/epoch than
3970
+ * the cached position, advance the resume watermark and re-persist. Shared by
3971
+ * the `ack`, `resume` and `settled` frame handlers — each acknowledges the
3972
+ * subscription ("nothing the client must re-render changed, but the resume
3973
+ * position may have moved"; an `ack` carries no position at all). The sync
3974
+ * status is only recomputed when this is the acknowledgement that changes it.
3975
+ */
3976
+ private ackAndAdvanceCursor;
3977
+ /**
3978
+ * Record the socket's connection id from its `identity` frame, then re-issue every live grant
3979
+ * this shard holds: a new socket starts with none.
3980
+ */
3981
+ private adoptSocketConnectionId;
3982
+ /**
3983
+ * Post the live grant `subscriptionId` for the socket `connectionId`, once the socket has
3984
+ * acknowledged the join of the grant's topic. A publish reaches a member only with both in
3985
+ * place, so a grant that landed first would drop a publish made before the join took effect.
3986
+ * The post is skipped if the grant was released or refused meanwhile, or if the socket changed
3987
+ * since `connectionId` was read: the new socket's identity posts its own grants.
3988
+ */
3989
+ private grantWhenJoined;
3990
+ /** Send a `whisper_subscribe` for `topic` on `conn`, and count it as pending until the shard acknowledges it. */
3991
+ private sendWhisperJoin;
3992
+ /** One `whisper_subscribed` frame arrived: the topic is joined once every join sent for it is acknowledged. */
3993
+ private acknowledgeWhisperJoin;
3994
+ /**
3995
+ * Forget a topic's join state once no handler holds the topic and no join is still unacknowledged.
3996
+ * A join still in flight keeps its entry, and {@link acknowledgeWhisperJoin} drops it when the ack
3997
+ * lands: dropping it early would let that stale ack count toward a rejoin of the same topic.
3998
+ */
3999
+ private releaseWhisperJoin;
4000
+ /**
4001
+ * Run `run` once `topic` is joined on the current socket, or after {@link LIVE_CONTROL_TIMEOUT_MS}.
4002
+ * A lost ack must not hold a grant forever, so the timeout runs it anyway: an unacknowledged
4003
+ * join is not necessarily a failed one, and a grant for a join that never landed delivers nothing.
4004
+ */
4005
+ private whenWhisperJoined;
4006
+ /**
4007
+ * Forget the waiters of a socket that is going away, without running them: a grant for the old
4008
+ * socket's connection id is never valid, and the next socket's identity posts its own grants.
4009
+ */
4010
+ private dropWhisperJoinWaiters;
4011
+ private whisperJoinState;
4012
+ /**
4013
+ * Drop a live grant the shard refused for good, and tell its caller. A grant already released
4014
+ * by its unsubscribe handle is gone from the map, so a late refusal reports nothing. A refusal
4015
+ * for a socket that has since been replaced is ignored too: the new socket posts the grant
4016
+ * again and hears its own answer, and releasing now would strip the new socket's membership.
4017
+ */
4018
+ private refuseLiveGrant;
4019
+ /**
4020
+ * POST one live-grant control call, behind every earlier one. The body names the shard when
4021
+ * the socket is not the default one, as the SSE control call does. A refusal (a 4xx other
4022
+ * than 404 and 401) is handed to `onRefused`. Failures are swallowed: a denied grant must
4023
+ * never surface as an unhandled rejection.
4024
+ */
4025
+ private postLiveControl;
4026
+ /**
4027
+ * Route an inbound live publish to the grants on the originating shard whose stream and topic
4028
+ * match. A grant exists only for a subscribed stream and topic, so a frame naming another
4029
+ * stream reaches no handler.
4030
+ */
4031
+ private dispatchLive;
4032
+ /** Route an inbound whisper to the topic's handlers on the originating shard. */
4033
+ private dispatchWhisper;
4034
+ /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
4035
+ private notifyTokenExpired;
4036
+ /**
4037
+ * CLIENT-04: `type: "complete"` today is sent ONLY by `@lunora/do`'s
4038
+ * `handleStream` (see `shard-do.ts`), gated to the `stream` envelope type
4039
+ * and minting only `stream_*` ids — the `subscribe` path never sends it, so
4040
+ * a live SUBSCRIPTION provably never receives `complete` from the current
4041
+ * server. But `ServerCompleteMessage` is a generic `id`-keyed frame and
4042
+ * `ShardDO` is user-subclassable, so this stays defensive rather than
4043
+ * assuming a `sub_*` id can never reach here: unlike the historical
4044
+ * `subscriptions.remove(state)`, which dropped the state out of
4045
+ * `subscriptions.all()` — the set the reconnect resubscribe loop walks
4046
+ * (`ensureSocket`'s `open` handler) — and so froze the query forever across
4047
+ * every future reconnect, this fans a cancellation error to any listener
4048
+ * and marks the registration un-acked instead. Non-destructive: the state
4049
+ * stays in the registry, so the very next reconnect resubscribes it. The
4050
+ * two id-spaces don't overlap (`sub_*` vs `stream_*`), so the stream and
4051
+ * subscription lookups below are mutually exclusive.
4052
+ */
4053
+ private handleCompleteMessage;
4054
+ private unpersist;
4055
+ /**
4056
+ * Stable, non-reversible fingerprint of the current auth identity used to
4057
+ * stamp queued offline writes.
4058
+ *
4059
+ * `null` never matches a bearer-token fingerprint — but it is only an
4060
+ * IDENTITY of its own once this client knows no subject is coming. An app
4061
+ * with no auth at all, and a client the server has answered "no session"
4062
+ * to, both hold a `null` nobody else shares. A client mid-`/get-session`
4063
+ * holds a `null` that may be one round trip from `subj:<id>`, which is
4064
+ * every cookie app's page load: ask {@link identityUnresolved} before
4065
+ * treating it as an identity, or `null === null` matches two different
4066
+ * people. The raw token is never stored;
4067
+ * a length-prefixed FNV-1a hash is enough to detect an identity *change*
4068
+ * without keeping the credential around in the queue map.
4069
+ */
4070
+ private identityFingerprint;
4071
+ /**
4072
+ * Stable token-hash fingerprint of a bearer token (the `<len>:<fnv>:<djb2>`
4073
+ * format a token-stamped queued write carries). Extracted so the replay gate
4074
+ * can recompute the hash of the current credential and recognise a write
4075
+ * stamped under it — even after the fingerprint was relabelled to a subject.
4076
+ *
4077
+ * Two independent 32-bit passes (FNV-1a + djb2) give a ~64-bit digest, so
4078
+ * two distinct equal-length tokens are astronomically unlikely to share a
4079
+ * fingerprint. A single 32-bit hash collides ~1-in-4e9 per equal-length
4080
+ * pair — enough that, on a shared device, user B could hydrate A's cached
4081
+ * reads. Different algorithms (not the same FNV with a different seed, which
4082
+ * would be affine-related) keep the two passes genuinely independent.
4083
+ * Still synchronous (no crypto) and stable across surrogate pairs.
4084
+ */
4085
+ private hashToken;
4086
+ /**
4087
+ * The `credential` field a read-cache write carries: the token hash of the
4088
+ * bearer currently held, or nothing at all when signed out (there is no
4089
+ * credential to match against, and the `null` identity already covers it).
4090
+ */
4091
+ private credentialStamp;
4092
+ /**
4093
+ * Whether a read-cache entry belongs to the identity in effect right now —
4094
+ * the ONE gate the hydrated peek, the subscribe-time take and the late seed
4095
+ * all share.
4096
+ *
4097
+ * Three ways to be the same identity, because the label and the credential
4098
+ * resolve at different times:
4099
+ *
4100
+ * 1. The fingerprints are equal — the plain case.
4101
+ * 2. The entry is stamped under a token hash and the live identity has since
4102
+ * been relabelled to the subject that credential resolved to
4103
+ * ({@link isSameCredentialUnderTokenHash}).
4104
+ * 3. The entry is stamped under a subject and THIS session has only the raw
4105
+ * token so far, but it is byte-for-byte the credential the entry was written
4106
+ * under. This is the direction the strict comparison missed entirely, and it
4107
+ * is the normal shape of every reload: every adapter calls
4108
+ * `setAuthToken(token)` from storage and only learns the subject a
4109
+ * `/get-session` round trip later — which offline never completes at all.
4110
+ * Without it the durable read cache never seeded for a bearer-token app.
4111
+ *
4112
+ * All three want a credential this client actually HOLDS, which is why a
4113
+ * **cookie session seeds nothing on an offline cold start** — a documented
4114
+ * limitation, not a gap. The cookie is `HttpOnly`: the client can neither
4115
+ * read it nor prove it still has it, and offline the `/get-session` that
4116
+ * would resolve the subject never answers, so such entries (stamped
4117
+ * `subj:<id>`, no credential) have nothing to match. Seeding them on the
4118
+ * remembered subject LABEL would hand the rows to whoever opens the browser
4119
+ * profile with nothing evidencing they are that subject, and revoking on a
4120
+ * later mismatch does not repair it: that check can only run once
4121
+ * connectivity returns, which is exactly the state where the offline seed
4122
+ * was not needed. Offline-first reads require a bearer token.
4123
+ *
4124
+ * Case 1 is suspended while the subject awaits re-confirmation
4125
+ * ({@link subjectAwaitingReconfirm}): the fingerprint then labels a
4126
+ * credential nothing has checked it against, which is precisely the
4127
+ * account-switch shape — `setAuthToken(otherAccountsToken)` with no subject,
4128
+ * what every adapter does on a reload, still reading `subj:<previous user>`.
4129
+ * Matching on that label alone hands the new account the previous account's
4130
+ * cached rows. Cases 2 and 3 both PROVE the credential, so the reload this
4131
+ * gate exists for still seeds.
4132
+ */
4133
+ private cachedQueryMatchesIdentity;
4134
+ /**
4135
+ * True when `stamped` is a token-hash of the SAME credential still held now,
4136
+ * even though the live identity has since been relabelled to a subject. Covers
4137
+ * `setAuthToken(token, userId)` where the subject resolved a tick after the
4138
+ * token was set: a write persisted (or requeued) under the token hash must
4139
+ * still replay — the credential never changed, only its label — instead of
4140
+ * being dropped as an identity mismatch. This is the durable counterpart to
4141
+ * {@link restampQueuedIdentity}, which only relabels the in-memory live stamp
4142
+ * (consumed on the first flush) and never touches `item.identity` or the
4143
+ * persisted record, so a reload or a transient-failure requeue would otherwise
4144
+ * fall back to the stale token-hash and wrongly reject the same user's write.
4145
+ */
4146
+ private isSameCredentialUnderTokenHash;
4147
+ /**
4148
+ * Release one {@link sessionProbesInFlight} hold and re-flush the writes
4149
+ * that hold alone was holding.
4150
+ *
4151
+ * A resolve that names a user re-flushes through {@link setAuthToken} (the
4152
+ * identity changed). One that does not — signed out, or unreachable —
4153
+ * changes no identity and so fires no listener, and a write held only
4154
+ * because {@link identityUnresolved} said so would sit queued until the
4155
+ * next reconnect. Same connected-only gate as `setAuthToken`'s, so this
4156
+ * stays a re-flush of a live connection rather than a reason to replay an
4157
+ * offline queue.
4158
+ *
4159
+ * Only for a `null` fingerprint, which is the ONLY hold this probe owns:
4160
+ * {@link replayIdentityVerdict}'s unresolved-identity hold tests
4161
+ * `current === null`, while its other hold — a sticky subject awaiting
4162
+ * re-confirmation — requires an established subject and so a
4163
+ * `subj:<id>` fingerprint. That one is already on the `noteHeldRetryDelay`
4164
+ * backoff and must stay there.
4165
+ *
4166
+ * Re-flushing it from here instead was an unbounded loop, not a slow
4167
+ * backoff: `drainOfflineQueue` answers a subject-awaiting hold by probing
4168
+ * `getCurrentUser()` itself, whose release re-flushed, which drained, which
4169
+ * probed again — hundreds of round trips without a millisecond passing,
4170
+ * until the heap gave out. Narrowing to the `null` fingerprint makes the
4171
+ * cycle unreachable rather than merely rare: the branch that starts a probe
4172
+ * cannot be entered by a flush this guard lets through.
4173
+ */
4174
+ private releaseSessionProbe;
4175
+ /**
4176
+ * Whether this client's `null` identity fingerprint is still provisional —
4177
+ * a {@link getCurrentUser} resolve is in flight and may be about to name a
4178
+ * subject. The one question every identity gate asks before it is willing
4179
+ * to treat `null` as an identity rather than as an absence of one.
4180
+ */
4181
+ private identityUnresolved;
4182
+ /**
4183
+ * Key the offline-queue identity on the resolved user id rather than the
4184
+ * token bytes, so the NEXT token refresh keeps the same identity.
4185
+ *
4186
+ * Under a bearer token only a resolved user labels anything. A 401 or an
4187
+ * empty session resolves `null` for reasons that say nothing about who holds
4188
+ * the token, so the established label is left alone rather than cleared
4189
+ * (which would look like an identity change and drop the queue). A token
4190
+ * that rotated mid-flight belongs to a session this answer predates and is
4191
+ * ignored for the same reason.
4192
+ *
4193
+ * Under a cookie session (no token) the answer is the identity, `null`
4194
+ * included: nothing on the client changes when the user signs out, so "the
4195
+ * server found no session" is the only sign-out this client will ever see.
4196
+ * See {@link adoptCookieSubject}.
4197
+ *
4198
+ * A superseded probe is ignored too, and the token check cannot see it: on a
4199
+ * cookie app both `requestToken`s are `null`, so a slow answer from an OLDER
4200
+ * probe passed that check and overwrote the subject a newer one had already
4201
+ * established. `requestGeneration` is the question's id — it must still be
4202
+ * the current one at the moment of the write.
4203
+ */
4204
+ private adoptResolvedSubject;
4205
+ /**
4206
+ * Adopt the user a cookie session resolved to — `null` for nobody — as this
4207
+ * client's identity, from either source the server answers through: a
4208
+ * `/get-session` probe, or a socket's `identity` frame.
4209
+ *
4210
+ * Three states, told apart by `authSubject`: `undefined` is not known yet
4211
+ * (every page load until the first answer), `null` is known to be nobody,
4212
+ * and a string is that user. {@link setAuthToken} retires the previous
4213
+ * session on every change between two KNOWN states — `A → nobody`,
4214
+ * `nobody → B`, `A → B` — and on none out of `undefined`, so the first
4215
+ * answer after a page load never evicts what the page is already showing
4216
+ * for the session it was loaded under.
4217
+ *
4218
+ * `question` orders the answers: one older than the answer in force
4219
+ * describes an older cookie and is dropped. Returns whether it was adopted.
4220
+ */
4221
+ private adoptCookieSubject;
4222
+ /**
4223
+ * Frame an already-encoded whisper body onto the topic's shard socket. Returns `false`
4224
+ * when the socket is not open, so the caller can hold the body and send it later.
4225
+ */
4226
+ private sendEncodedWhisper;
4227
+ /**
4228
+ * Whether room sends on `shardKey` may go straight to its socket: the socket is open,
4229
+ * the server has confirmed its identity, and its room rejoins are on the wire.
4230
+ */
4231
+ private roomSendsAdmitted;
4232
+ /** Flush the held room sends on `shardKey`, once that socket is admitted. */
4233
+ private releaseRoomSends;
4234
+ /** The server answered this socket's identity: record it, and release the sends that waited on it. */
4235
+ private confirmShardIdentity;
4236
+ /**
4237
+ * A cookie socket's `identity` frame: the user the shard authenticated this
4238
+ * socket as, sent in reply to every `connect`.
4239
+ *
4240
+ * Adopted like a probe's answer when it is the newest one
4241
+ * ({@link adoptCookieSubject}). An OLDER one that disagrees with the
4242
+ * identity in force means this socket was upgraded on a cookie that has
4243
+ * since changed hands, and is still delivering that user's rows: the
4244
+ * session it belongs to is retired, which replaces the socket.
4245
+ *
4246
+ * Ignored for a socket that authenticated with a ticket or an auth token rather
4247
+ * than the cookie (see `ShardConnection.identityQuestion`) — its answer is about
4248
+ * that credential, not about the cookie session this client's identity tracks.
4249
+ */
4250
+ private handleIdentityFrame;
4251
+ /**
4252
+ * The subject half of {@link setAuthToken}.
4253
+ *
4254
+ * Sticky: only an explicit value (incl. `null` = signed out) changes the
4255
+ * subject; omitting it keeps the established one. Two exceptions, both about
4256
+ * a subject that must not outlive the credential it described:
4257
+ *
4258
+ * - Clearing the token clears a user subject — see `setAuthToken`'s
4259
+ * docblock. A `null` one stays: a cookie session known to be nobody's is
4260
+ * still nobody's.
4261
+ * - A token arriving on a session known to be nobody's drops the `null`,
4262
+ * so the identity falls back to the token itself rather than staying
4263
+ * "nobody" while a credential is held.
4264
+ */
4265
+ private applySubject;
4266
+ /**
4267
+ * A cookie session the server has answered "nobody" for — see
4268
+ * {@link adoptCookieSubject}. Distinct from a subject not known YET
4269
+ * (`undefined`).
4270
+ */
4271
+ private isKnownNobody;
4272
+ /**
4273
+ * True while an established subject labels a credential it was never checked
4274
+ * against — see the `subjectToken` field. Every replay verdict is
4275
+ * `"unknown"` (hold) until the next session resolve re-asserts the subject.
4276
+ */
4277
+ private subjectAwaitingReconfirm;
4278
+ /**
4279
+ * The identity a queued write is stamped with. The live `queuedIdentities`
4280
+ * map is the source of truth for this session; a hydrated write whose id
4281
+ * isn't in it falls back to the stamp persisted with the record. `Map.get`
4282
+ * returns `undefined` for unstamped/hydrated ids and `item.identity` is
4283
+ * `undefined` for legacy records (persisted before stamps were durable),
4284
+ * while a persisted `null` (queued while signed out) is a real value that
4285
+ * must not collapse into `undefined` — hence `=== undefined`, not `??`.
4286
+ */
4287
+ private stampOf;
4288
+ /**
4289
+ * Warn when a token refused for a queued write is replaced with no subject
4290
+ * keyed: the likely refresh reads as a user switch, so the writes it was
4291
+ * meant to rescue were just rejected `OFFLINE_IDENTITY_CHANGED`. Dropping is
4292
+ * the safe default — a refresh and an account switch look the same without
4293
+ * a subject — so this only says how to keep them.
4294
+ */
4295
+ private warnRefreshWithoutSubject;
4296
+ /**
4297
+ * Reject the in-memory offline writes that can no longer replay under the
4298
+ * identity now signed in, dropping their durable records so a later
4299
+ * `hydrate` can't resurrect another user's writes.
4300
+ *
4301
+ * Per item, not wholesale: this runs on a plain sign-in too (`null` → a
4302
+ * signed-in identity is a credential change like any other), where the
4303
+ * queue is the *signing-in user's own* restored writes. Every stamp goes
4304
+ * through {@link replayIdentityVerdict}, the one comparison, and only
4305
+ * `"mismatch"` is terminal — `"match"` and `"unknown"` stay queued.
4306
+ *
4307
+ * The durable read cache is cleared only when there WAS a previous identity
4308
+ * to protect. Wiping it on a sign-in from signed-out would destroy the
4309
+ * offline-first cache on every cold boot, and buys nothing: cache entries
4310
+ * are identity-stamped and gated at every read.
4311
+ */
4312
+ private rejectQueuedForIdentityChange;
4313
+ /**
4314
+ * Move the identity stamp of every open shard socket from `from` to `to` —
4315
+ * the sibling of {@link restampQueuedIdentity} for the read cache. A socket
4316
+ * pins the identity it was upgraded under (see `ShardConnection.identity`)
4317
+ * and {@link persistQueryValue} stamps cached reads with it, deliberately,
4318
+ * so a still-open previous-user socket can't file frames under the new
4319
+ * user's stamp. A same-credential relabel is the one case where that pin is
4320
+ * stale rather than protective: without this, every read cached for the rest
4321
+ * of the session is filed under a fingerprint the next session's identity
4322
+ * gate rejects, and the durable read cache silently yields nothing.
4323
+ */
4324
+ private restampConnectionIdentity;
4325
+ /**
4326
+ * Migrate every identity stamp from `from` to `to` — used when the auth
4327
+ * identity label changes but the underlying credential (token) does NOT, e.g.
4328
+ * the user id resolves a tick after the token was set. The in-memory
4329
+ * `queuedIdentities` map is the flush-time source of truth, so re-stamping it
4330
+ * keeps the in-flight writes replayable under the new (more stable) identity
4331
+ * instead of the flush guard discarding them as a mismatch.
4332
+ *
4333
+ * That map alone was not enough: it is consumed and DELETED on the first
4334
+ * flush attempt (`replayIdentityVerdict`), while the queue entry and its
4335
+ * persisted record keep the original stamp. So a reload, or a requeue after a
4336
+ * transient failure, fell back to the old token hash — and once the token had
4337
+ * been refreshed, `isSameCredentialUnderTokenHash` no longer recognised it
4338
+ * and the write was rejected `OFFLINE_IDENTITY_CHANGED` for the very user
4339
+ * `setAuthToken`'s sticky-`subject` contract promises to protect. The queue's
4340
+ * own re-stamp covers both the entry and its durable record.
4341
+ */
4342
+ private restampQueuedIdentity;
4343
+ /**
4344
+ * Migrate the {@link clientWatermarks} bucket map nested under identity
4345
+ * `from` to identity `to` — the sibling of {@link restampQueuedIdentity},
4346
+ * for the same same-credential-subject-resolves case. Without this, a
4347
+ * bucket's watermark cached under the token-hash fingerprint would look
4348
+ * unset once the fingerprint relabels to `subj:…`, so the next push
4349
+ * re-derives `1` against a server watermark the DO already advanced — the
4350
+ * OUT_OF_ORDER wedge this cache-keying scheme exists to fix, reintroduced
4351
+ * by the fix itself. `to` may already hold a bucket map (switching back to
4352
+ * an identity that has its own cached watermarks); merge into it rather
4353
+ * than clobbering it, with `from`'s entries winning on a colliding bucket —
4354
+ * the same overwrite a plain `Map.set` would have done before this was a
4355
+ * nested map.
4356
+ */
4357
+ private restampWatermarks;
4358
+ /**
4359
+ * Drop the durable read cache on an identity change so a cached value stamped
4360
+ * under the previous identity can never hydrate into a new session. Clears
4361
+ * the in-flight write batch and the not-yet-consumed hydrated entries too;
4362
+ * the durable `clear()` is best-effort.
4363
+ */
4364
+ private clearQueryCacheForIdentityChange;
4365
+ /**
4366
+ * Retire everything the PREVIOUS identity left live on a genuine identity
4367
+ * change: the sockets it is authenticated on, and the rows they delivered.
4368
+ *
4369
+ * A WebSocket credential is pinned in its upgrade URL and cannot be rotated
4370
+ * in place, so `setAuthToken` alone left the previous user's socket open and
4371
+ * delivering — the consequence `ShardConnection.identity`'s docblock already
4372
+ * described, with "nothing" as the thing that closes it on a client without
4373
+ * `crossTabSync`. And each `SubscriptionState` keeps the last value that
4374
+ * socket delivered, which `subscribe()` replays synchronously to every new
4375
+ * subscriber, so the incoming user's first render was the outgoing user's
4376
+ * rows even after the socket did go.
4377
+ *
4378
+ * Both halves are needed: closing the socket without clearing the values
4379
+ * leaves them on screen until a frame replaces them (which never comes for a
4380
+ * query the new user cannot read), and clearing the values without closing
4381
+ * the socket lets the next frame put them straight back.
4382
+ */
4383
+ private evictPreviousIdentitySession;
4384
+ /**
4385
+ * Move this tab's cross-tab coordinator onto the channel the new identity
4386
+ * derives, after an identity change.
4387
+ *
4388
+ * The channel name embeds the identity fingerprint (see
4389
+ * {@link createTabCoordinator}), so without this the tab keeps
4390
+ * leading/following the PREVIOUS identity's group. BroadcastChannel names
4391
+ * are immutable, so a stop-old+construct-new is the only way to move
4392
+ * channels — but that means the fresh coordinator would otherwise sit
4393
+ * through the full claim-then-`leaderTimeout` dance (3s default) before any
4394
+ * tab opens a socket again, freezing every live query for that long on
4395
+ * EVERY identity change (including a routine JWT refresh for an app that
4396
+ * doesn't pass a stable `subject` — the documented reason to pass one). If
4397
+ * this tab was already the leader, it's overwhelmingly likely to remain the
4398
+ * sole tab on the new channel too, so promote it immediately instead of
4399
+ * waiting — `promoteImmediately`'s docblock covers the (self-healing) rare
4400
+ * case where another tab does the same at once.
4401
+ */
4402
+ private restartTabCoordinatorForIdentity;
4403
+ /** Drop every room send held before the socket opened: they were made under the identity that is now going away. */
4404
+ private resetRoomSends;
4405
+ /**
4406
+ * Blank every live subscription and shape, forget their resume cursors, and
4407
+ * reconnect every socket, so each resubscribe is a cold one the server
4408
+ * re-seeds for the identity the new socket carries. Used when the socket's
4409
+ * credential changes: resuming from a cursor taken under the previous one
4410
+ * would splice a diff onto rows that identity was never shown.
4411
+ */
4412
+ private reconnectCold;
4413
+ /**
4414
+ * Close every open shard socket so each reconnects carrying the credential
4415
+ * in effect now.
4416
+ *
4417
+ * Non-terminal, unlike {@link close}: the `ShardConnection` records and the
4418
+ * subscriptions riding them survive, and the registered `close` handler
4419
+ * (`handleDisconnect`) schedules the retry and replays the subscribes. This
4420
+ * is the only way to move a WS credential — it lives in the upgrade URL.
4421
+ */
4422
+ private bounceShardSockets;
4423
+ /**
4424
+ * Flush every shard with a mutation currently queued in `offlineQueue`
4425
+ * (see `queuedOfflineShardKeys`). Used on a FOLLOWER tab when the
4426
+ * mirrored leader status transitions to `"connected"` — a follower has no
4427
+ * per-shard `ShardConnection` reconnect event to hang the usual
4428
+ * single-shard `flushOfflineQueue(shardKey)` call off of (see the `onOpen`
4429
+ * callback that calls `flushOfflineQueue(shardKey)`), so this walks every
4430
+ * shard that might have something queued instead. Flushing an already-empty
4431
+ * shard is a cheap no-op (`flushOfflineQueue` returns immediately once
4432
+ * `drain` yields nothing), so over-inclusion here is harmless.
4433
+ */
4434
+ private flushAllOfflineQueues;
4435
+ /**
4436
+ * Replay a shard's queued writes, serialized per shard and published as
4437
+ * {@link offlineFlushes} so a concurrent `mutation()` can wait behind it.
4438
+ * Never rejects: every entry's outcome is settled individually inside
4439
+ * {@link drainOfflineQueue}, and a poisoned chain would strand every later
4440
+ * flush AND every write waiting on the barrier.
4441
+ */
4442
+ private flushOfflineQueue;
4443
+ /**
4444
+ * Where a snapshot precondition's subscription stands on its socket, when
4445
+ * comparing would mislead: `"awaiting"` while a reconnect has un-answered it
4446
+ * and no value has answered since (the comparison would judge the previous
4447
+ * socket's value, or a blank), `"unreadable"` once that wait ended with no
4448
+ * value to read. `undefined` for any other precondition or subscription.
4449
+ */
4450
+ private snapshotAnswer;
4451
+ /**
4452
+ * The precondition a queued write carries. A snapshot precondition reads as
4453
+ * holding while its subscription is awaited, so `drainConflict` keeps the
4454
+ * write rather than drop it on a blank the server acked but has not seeded
4455
+ * yet (the drain then holds it back, {@link drainOfflineQueue}), and once the
4456
+ * wait ended unreadable, which is no evidence the value changed.
4457
+ */
4458
+ private holdWhileUnanswered;
4459
+ /**
4460
+ * A follower's counterpart of a socket open in {@link markShardPendingAck}: every
4461
+ * subscription awaits the leader's next relay. A follower cannot ask the leader for
4462
+ * one, and the leader relays only the queries it holds itself, so the wait is bounded
4463
+ * by the leader's own (an ack window and one retry) and ends unreadable, as the
4464
+ * leader's does when it gives up.
4465
+ */
4466
+ private awaitLeaderAnswers;
4467
+ /**
4468
+ * Holds `state` for the leader's next relay. Its timer is its own, so settling
4469
+ * one subscription early never releases another.
4470
+ */
4471
+ private awaitLeaderAnswer;
4472
+ /**
4473
+ * `state` has been answered on its socket (`readable`), or will not be: release
4474
+ * any write held for it. Not called for an `ack`, which the server sends
4475
+ * before the seed.
4476
+ */
4477
+ private settleAwaitedAnswer;
4478
+ /**
4479
+ * Put back a drained write whose snapshot cannot be compared yet, and every
4480
+ * write behind it (replaying those first would reorder the shard), recording
4481
+ * the hold so the answer flushes again. Returns the writes that may go on.
4482
+ */
4483
+ private holdUndecidedWrites;
4484
+ private drainOfflineQueue;
4485
+ /**
4486
+ * Ask for another flush of this shard after a backoff, because every entry it
4487
+ * drained was HELD for an identity that is not re-confirmed yet.
4488
+ *
4489
+ * Same state and same timer as a rate-limited replay
4490
+ * ({@link LunoraClient.noteReplayRetryDelay}) — one pending flush per shard
4491
+ * key either way — only the reason differs: there is no error to read a
4492
+ * `Retry-After` off, so the hintless {@link defaultReplayRetryDelayMs} ramp
4493
+ * (1s doubling to a 60s ceiling, jittered) is the whole policy. It is a
4494
+ * ceiling on the rate, not a budget of attempts: a durable write is never
4495
+ * dropped for having waited too long, so a subject that never resolves leaves
4496
+ * the queue re-probing at ≤ 60s intervals with the writes intact and
4497
+ * {@link LunoraClient.pendingCount} non-zero for the app to surface. The
4498
+ * retries stop when the hold lifts (the queue drains), when the shard has
4499
+ * nothing queued, or at `close()`.
4500
+ *
4501
+ * Identity is re-read by the flush, never carried across the timer: the
4502
+ * retry re-enters {@link LunoraClient.drainOfflineQueue}, which re-runs
4503
+ * {@link LunoraClient.replayGateVerdict} per entry against the identity in
4504
+ * effect when it runs. A retry therefore cannot replay a write under an
4505
+ * identity that changed while the timer was pending — it re-holds it, or
4506
+ * rejects it as a mismatch, exactly as a reconnect-driven flush would.
4507
+ */
4508
+ private noteHeldRetryDelay;
4509
+ /**
4510
+ * Remember the longest delay this shard's flush was told (or worked out) to
4511
+ * wait, so the drain can honour it before trying again
4512
+ * ({@link LunoraClient.replayRetryState}). Counts the attempt either way:
4513
+ * that is what a hintless refusal backs off on.
4514
+ *
4515
+ * A credential refused under a cookie session (`authToken === null`) backs
4516
+ * off on the hintless ramp too. A bearer refusal waits for `setAuthToken`,
4517
+ * which re-flushes; a cookie is renewed in the browser, invisibly to this
4518
+ * client, so the only way to learn it was is to send again.
4519
+ */
4520
+ private noteReplayRetryDelay;
4521
+ /**
4522
+ * Consume this shard's retry delay and re-flush it once the delay has
4523
+ * elapsed.
4524
+ *
4525
+ * Two things record a delay for it to consume: a transient failure (a server
4526
+ * or edge answer, or a `fetch` that rejected; see {@link replayRetryDelayMs})
4527
+ * and a flush that HELD every entry it drained (see
4528
+ * {@link LunoraClient.noteHeldRetryDelay}). Both happen over a socket that
4529
+ * stays open, so without this the writes sit queued indefinitely. One pending
4530
+ * timer per shard; a second delay replaces it rather than stacking flushes.
4531
+ *
4532
+ * Nothing left to retry on this key (drained, closed, or no delay) drops its
4533
+ * backoff state, which is both the reset after progress and what bounds the
4534
+ * map.
4535
+ */
4536
+ private scheduleRateLimitedRetry;
4537
+ /**
4538
+ * Partition already-gated writes into the encodable ones (returned) and reject
4539
+ * the rest terminally. A write whose args can't be wire-encoded (e.g. a RegExp
4540
+ * or class instance in a `v.any()` field) can NEVER replay — the codec failure
4541
+ * is deterministic, not transient. Rejecting here is essential: otherwise
4542
+ * `encodeWire` throws mid-flush, is classified as transient (a codec error has
4543
+ * no `.code`), and re-queues forever — a silent hang where the caller's Promise
4544
+ * never settles and the optimistic write never rolls back. Encoding is cheap;
4545
+ * the flush is the slow reconnect path.
4546
+ */
4547
+ private encodableOrSettleTerminal;
4548
+ /**
4549
+ * The three-way comparison behind {@link replayIdentityVerdict} (documented
4550
+ * there), without a credential: the built-in queue sends with its own pinned token.
4551
+ */
4552
+ private identityVerdict;
4553
+ /**
4554
+ * Identity gate for one queued write about to replay: a write stamped under
4555
+ * one identity must never replay under another, and must never be DESTROYED
4556
+ * because the identity isn't known yet.
4557
+ *
4558
+ * The three-way verdict is {@link replayIdentityVerdict}'s, not a second
4559
+ * hand-rolled comparison — `@lunora/db`'s durable outbox holds on `"unknown"`
4560
+ * through the same call, and this path (the default for the standalone
4561
+ * client) used to drop there instead, purging the queuing user's own write
4562
+ * on every reload that opened its socket before the session resolved.
4563
+ *
4564
+ * `"send"` replays it and consumes the live stamp. `"hold"` leaves it queued
4565
+ * and persisted, stamp intact, for a later flush once an identity is
4566
+ * established (see `setAuthToken`). `"reject"` means a different identity is
4567
+ * signed in: settle it terminally `OFFLINE_IDENTITY_CHANGED` and purge the
4568
+ * durable record.
4569
+ */
4570
+ private replayGateVerdict;
4571
+ /** Settle a write that replayed successfully: confirm its optimistic layer against the echoed commit cursor BEFORE resolving, so the gapless drop is in place when the awaiter (and any confirming frame) observes the settle. */
4572
+ private settleReplaySuccess;
4573
+ /**
4574
+ * The entry a shard's cursor lives under.
4575
+ *
4576
+ * Only the server knows that an omitted `shardKey` and an explicit one
4577
+ * spelling out its configured default name are the same shard — the default
4578
+ * is server-side configuration the client never sees. Keying on what was
4579
+ * SENT would split one shard's cursor across two entries, so a write under
4580
+ * one spelling would stop constraining a read under the other. Resolving
4581
+ * `undefined` through the learned name is what keeps both spellings on one
4582
+ * entry.
4583
+ */
4584
+ private cursorKeyFor;
4585
+ /**
4586
+ * Learn the server's own name for the default shard from a response to a
4587
+ * call that named no shard.
4588
+ *
4589
+ * Any cursor recorded before the name was known sits under the placeholder
4590
+ * entry, so it is folded in rather than stranded — otherwise the requirement
4591
+ * from a client's first write would be lost exactly once, which is the kind
4592
+ * of gap that only shows up as a stale read under load.
4593
+ */
4594
+ private learnDefaultShardKey;
4595
+ /**
4596
+ * Record the cursor a write committed at as this shard's read-your-writes
4597
+ * requirement.
4598
+ *
4599
+ * Monotonic: responses can land out of order, and moving the requirement
4600
+ * BACKWARDS would let a later read be answered from a replica copy that
4601
+ * predates a write this client already saw.
4602
+ */
4603
+ private recordShardCursor;
4604
+ /**
4605
+ * Whether a replay failure leaves the durable write queued rather than
4606
+ * settling it terminally — the ONE classification the single-call, per-slot
4607
+ * and whole-batch paths share, so a write's fate never depends on how many
4608
+ * siblings rode along.
4609
+ *
4610
+ * {@link isTransientReplayFailure} answers the "no verdict was reached" half.
4611
+ * The other half is a refused CREDENTIAL ({@link isAuthReplayFailure}): the
4612
+ * queue flushes on the shard's `open` handler with whatever bearer survived
4613
+ * the offline window, so an expired token is the expected outcome of a long
4614
+ * disconnect, not a verdict on the write. Notifying {@link onTokenExpired}
4615
+ * here is what closes the loop — the HTTP replay path has no equivalent of
4616
+ * the WS `4001` close frame, so without this nothing tells the app to
4617
+ * refresh, and `setAuthToken` (which re-flushes) is never called.
4618
+ *
4619
+ * Notified once per credential, not once per write: a flush of a hundred
4620
+ * queued writes earns a hundred identical refusals, and firing the hook for
4621
+ * each would put a hundred token refreshes on the app. The stamp re-arms as
4622
+ * soon as the credential moves, which is the only thing that can change the
4623
+ * answer.
4624
+ */
4625
+ private shouldRequeueReplayFailure;
4626
+ /**
4627
+ * Whether `error` refused a replay's CREDENTIAL (`authToken`, the bearer it
4628
+ * was sent with), and if so tell {@link onTokenExpired} — once per
4629
+ * credential, and only while it is still the current one. A refusal of a
4630
+ * token the app has already replaced says nothing about the current one:
4631
+ * the next pass re-sends under it, so asking for another refresh would be
4632
+ * spurious.
4633
+ */
4634
+ private noteReplayAuthRefusal;
4635
+ /**
4636
+ * A request under `authToken` succeeded: if a refusal of that credential was
4637
+ * reported, its next refusal is news again. A bearer re-arms by changing; a
4638
+ * cookie session's `null` never does, so without this the app could be asked
4639
+ * to refresh a cookie only once per page.
4640
+ */
4641
+ private noteCredentialAccepted;
4642
+ /**
4643
+ * Redeem a {@link ReplayCredential} (single use) into the request flags it
4644
+ * pins (the judged bearer, and the subject a cookie replay names) and the
4645
+ * identity stamp it was judged for. Throws for a credential this client did
4646
+ * not issue or already redeemed.
4647
+ */
4648
+ private takeReplayCredential;
4649
+ /**
4650
+ * Whether `failure` is the worker's `IDENTITY_MISMATCH` refusal, and if so,
4651
+ * ask who is signed in now: the answer is what re-runs the replay gate
4652
+ * ({@link setAuthToken}), and nothing else would on a cookie session.
4653
+ */
4654
+ private noteIdentityMismatch;
4655
+ /**
4656
+ * Settle a write the server COMMITTED whose result does not decode. It is
4657
+ * `committed` — its optimistic layer confirms against the echoed cursor like
4658
+ * any success — but there is no value to hand the caller, so the awaiter is
4659
+ * rejected with the decode error and the settled event carries it.
4660
+ */
4661
+ private settleReplayUndecodable;
4662
+ /**
4663
+ * Count a failed replay attempt against `item` and report whether it was the
4664
+ * last attempt the write gets.
4665
+ *
4666
+ * Only a write queued after an ambiguous direct send is capped: its caller is
4667
+ * still waiting, so every transient failure of it except a rate limit or a
4668
+ * refused credential (a transport error, a timeout, `SHARD_UNAVAILABLE`, ...)
4669
+ * counts against {@link MAX_AMBIGUOUS_SEND_ATTEMPTS}. Any other write is never
4670
+ * capped here: a write the shard fails deterministically arrives with a coded
4671
+ * verdict (the handler's own code, `RPC_FAILED`, `BATCH_ENTRY_FAILED`) that
4672
+ * {@link isTransientReplayFailure} settles terminally on the first attempt, and
4673
+ * a transient failure says nothing about the write itself.
4674
+ */
4675
+ private spendsLastReplayAttempt;
4676
+ /** Settle, terminally, the ambiguous-send writes among `items` that `error` was the last attempt for; the rest stay queued. */
4677
+ private keepUnexhaustedAmbiguousWrites;
4678
+ /** Settle a write the server reached a coded verdict on: replaying would re-trigger the same failure (a poison-message loop), so drop it. */
4679
+ private settleReplayTerminal;
4680
+ /**
4681
+ * Replay already-identity-gated writes one at a time on the single-call `/rpc`
4682
+ * path, preserving FIFO order (parallel `.then()` chains would race the
4683
+ * ordering callers depend on). Each replays under its stable `mutationId` so
4684
+ * the server dedups a write it already committed (exactly-once). A server verdict
4685
+ * drops the write; a transient failure ({@link isTransientReplayFailure} — a
4686
+ * transport error, a shard the worker couldn't reach, a rate-limit refusal, or a
4687
+ * non-2xx carrying no `{ error }` envelope) stops the flush and re-queues this
4688
+ * write and every unreplayed one for the next reconnect — their callers stay
4689
+ * pending, and the identity guard re-applies on retry via each record's persisted
4690
+ * stamp. The batch path classifies a slot by the same rule, so a durable write's
4691
+ * fate never depends on how many siblings happened to be queued alongside it.
4692
+ */
4693
+ private replaySequential;
4694
+ /**
4695
+ * Coalesce already-identity-gated writes for a single shard into ONE
4696
+ * `/_lunora/rpc-batch` round trip (plan 088 follow-on). The worker forwards
4697
+ * them to the shard DO, which replays each through its single-call dispatch, so
4698
+ * per-entry `mutationId` idempotency and in-order application are inherited from
4699
+ * the proven path. Per-slot demux mirrors {@link replaySequential}'s
4700
+ * classification: success confirms the optimistic layer against the echoed
4701
+ * `commitCursor`; a coded application verdict is terminal; a failure
4702
+ * {@link shouldRequeueReplayFailure} keeps, a missing slot, or a whole-batch
4703
+ * transport failure re-queues for the next reconnect (never dropping a durable
4704
+ * write). A whole-batch coded rejection (a bad request the server reached a
4705
+ * verdict on) is terminal for every entry.
4706
+ *
4707
+ * The body is also held under {@link MAX_BATCH_BODY_BYTES}: the worker caps a
4708
+ * batch body at 1 MiB and answers `413`, which is ONE refusal covering every
4709
+ * write in the chunk. An over-budget chunk is halved before it is sent, and a
4710
+ * `413` for a chunk of more than one write halves it and retries rather than
4711
+ * settling the whole chunk terminally — so a backlog of large writes still
4712
+ * commits, one bisection deeper.
4713
+ *
4714
+ * Returns the writes that must be re-queued and `stop` — `true` when the whole
4715
+ * chunk failed at the transport level, so the caller leaves later chunks queued
4716
+ * rather than sending on. The caller re-queues once, in order, so requeuing is
4717
+ * NOT done here.
4718
+ */
4719
+ private replayBatched;
4720
+ /**
4721
+ * Classify a `/_lunora/rpc-batch` reply that carried no per-slot results — one
4722
+ * outcome covering every entry in the chunk. A code
4723
+ * {@link shouldRequeueReplayFailure} keeps (an unreachable shard, a
4724
+ * rate-limit refusal, a refused credential) or a {@link TransportError} (an
4725
+ * edge reply with no verdict in it) leaves every write durable for the next
4726
+ * attempt; anything else is a verdict reached on the request itself, and
4727
+ * settles all of them.
4728
+ */
4729
+ private settleWholeBatchError;
4730
+ /**
4731
+ * Split an over-large batch chunk in half and replay each half, preserving
4732
+ * FIFO order. Recurses through {@link replayBatched}, so a chunk keeps halving
4733
+ * until it fits (or reaches one write, which is then the server's verdict to
4734
+ * give). A `stop` on the first half leaves the second unsent and queued.
4735
+ */
4736
+ private replayBatchedHalves;
4737
+ /**
4738
+ * Demux a `/_lunora/rpc-batch` reply back onto the queued writes it replayed,
4739
+ * in input order. Each slot's envelope classifies its write the same way
4740
+ * {@link replaySequential} does: a success confirms the optimistic layer
4741
+ * against the echoed `commitCursor`; a coded application verdict is terminal;
4742
+ * a failure {@link shouldRequeueReplayFailure} keeps, or a slot the server
4743
+ * never returned, is returned for the caller to re-queue.
4744
+ *
4745
+ * A slot whose `error` key holds no readable envelope is in the same position
4746
+ * as one the server never returned — nothing came back about that entry that
4747
+ * can be read as a verdict — so it is kept, not settled.
4748
+ * @returns the writes that must be re-queued (kept slots), in input order
4749
+ */
4750
+ private settleReplayBatchSlots;
4751
+ }
4752
+ export { SchedulerPoolStatus as $, ActionCallOptions as A, BookmarkStorage as B, ConnectionStatus as C, DEFAULT_MAX_BUFFER as D, OptimisticUpdate as E, FunctionArgumentDescriptor as F, GlobalFacetResult as G, HttpStreamRef as H, OutboxMutation as I, OutboxSink as J, PersistedMutation as K, LunoraClient as L, MutationCallOptions as M, ReplayCredential as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReconnectOptions as R, SubscriptionError as S, ReplayIdentityVerdict as T, User as U, RoomRef as V, RowOp as W, RpcEnvelope as X, RpcResponseBody as Y, ScheduleRecord as Z, ScheduleRetryPolicy as _, Unsubscribe as a, SchedulerStatus as a0, ServerMessage as a1, ServerPokeEndMessage as a2, ServerPokePartMessage as a3, ServerPokeStartMessage as a4, ShardTrafficEntry as a5, ShardTrafficResult as a6, StorageListPage as a7, StorageObject as a8, StoredQuery as a9, StreamHandle as aa, SubscriptionCallback as ab, SubscriptionRegistry as ac, SubscriptionState as ad, SyncStatus as ae, SyncWatermark as af, WorkflowInstanceAction as ag, WorkflowInstanceDetail as ah, WorkflowInstancePage as ai, WorkflowInstanceStatus as aj, WorkflowInstanceSummary as ak, WorkflowStepDetail as al, WsTokenProvider as am, createClientQuery as an, createLocalStore as ao, createStream as ap, SubscriptionErrorCallback as b, PersistenceAdapter as c, HttpStreamArgsOf as d, HttpStreamChunkOf as e, StreamIterable as f, BatchSlot as g, CachedQuery as h, ClientDebugShard as i, ClientDebugSnapshot as j, ClientDebugSubscription as k, ClientMessage as l, ClientQueryRef as m, ClientShapeSubscribeMessage as n, ClientShapeUnsubscribeMessage as o, FunctionDescriptor as p, GlobalFacetValue as q, GlobalFilterClause as r, GlobalTableInfo as s, GlobalTablePage as t, HttpStreamCallArgs as u, LunoraClientError as v, LunoraClientOptions as w, MutationSettledEvent as x, OnlineOnlyOption as y, OptimisticLocalStore as z };