@lunora/client 1.0.0-alpha.27 → 1.0.0-alpha.271

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