@lunora/client 1.0.0-alpha.10 → 1.0.0-alpha.101

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 (91) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +16 -3
  3. package/dist/auth/index.d.mts +12 -10
  4. package/dist/auth/index.d.ts +12 -10
  5. package/dist/auth/index.mjs +1 -60
  6. package/dist/index.d.mts +876 -246
  7. package/dist/index.d.ts +876 -246
  8. package/dist/index.mjs +1 -15
  9. package/dist/packem_shared/CONFLICT_ERROR_CODE-BOeeP_Wl.mjs +1 -0
  10. package/dist/packem_shared/ClientServiceWorker-DXnBXeWK.mjs +1 -0
  11. package/dist/packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs +1 -0
  12. package/dist/packem_shared/LunoraClient-DLD6tKKQ.mjs +1 -0
  13. package/dist/packem_shared/OfflineQueue-ZapYrAVi.mjs +1 -0
  14. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
  15. package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
  16. package/dist/packem_shared/SubscriptionRegistry-CS-AFUI9.mjs +1 -0
  17. package/dist/packem_shared/TabCoordinator-CXD7vulJ.mjs +1 -0
  18. package/dist/packem_shared/anyApi-CBOws2ZA.mjs +1 -0
  19. package/dist/packem_shared/applyDelta-DwcQmRsV.mjs +1 -0
  20. package/dist/packem_shared/createAsyncStoragePersistence-CeUW9NTj.mjs +1 -0
  21. package/dist/packem_shared/createAsyncStorageQueryCache-BfZkthAE.mjs +1 -0
  22. package/dist/packem_shared/createCallRunner-Bwcrfh76.mjs +1 -0
  23. package/dist/packem_shared/createClientQuery-B8Nfj-7o.mjs +1 -0
  24. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  25. package/dist/packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs +1 -0
  26. package/dist/packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs +1 -0
  27. package/dist/packem_shared/createLocalStore-BFdXRTFz.mjs +1 -0
  28. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  29. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  30. package/dist/packem_shared/createReply-CwFABEJs.mjs +1 -0
  31. package/dist/packem_shared/createServerClient-DOixEaPw.mjs +1 -0
  32. package/dist/packem_shared/createSnapshotPrecondition-GRVKxPsh.mjs +1 -0
  33. package/dist/packem_shared/delta-merge-vxvH3PvF.mjs +1 -0
  34. package/dist/packem_shared/deserializePreloaded-C6NTQdFa.mjs +1 -0
  35. package/dist/packem_shared/function-reference.d-Br_hsKje.d.mts +45 -0
  36. package/dist/packem_shared/function-reference.d-Br_hsKje.d.ts +45 -0
  37. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  38. package/dist/packem_shared/httpStream-CPdblK2G.mjs +11 -0
  39. package/dist/packem_shared/idb-utility-C8WS390w.mjs +1 -0
  40. package/dist/packem_shared/local-store-BjenEm3t.mjs +1 -0
  41. package/dist/packem_shared/lunora-client.d-CB9PYBUV.d.mts +3951 -0
  42. package/dist/packem_shared/lunora-client.d-DYAbI4hF.d.ts +3951 -0
  43. package/dist/packem_shared/offline-queue-xntsWiKt.mjs +1 -0
  44. package/dist/packem_shared/preload.d-6fhT68fk.d.mts +21 -0
  45. package/dist/packem_shared/preload.d-CrbYQ-02.d.ts +21 -0
  46. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  47. package/dist/packem_shared/single-blob-store-DrhzObic.mjs +1 -0
  48. package/dist/packem_shared/wire-codec-Sw1rAu-Z.mjs +1 -0
  49. package/dist/packem_shared/wire-key-HsUDTlQ7.mjs +1 -0
  50. package/dist/pagination/index.d.mts +42 -42
  51. package/dist/pagination/index.d.ts +42 -42
  52. package/dist/pagination/index.mjs +1 -61
  53. package/dist/query/index.d.mts +111 -43
  54. package/dist/query/index.d.ts +111 -43
  55. package/dist/query/index.mjs +1 -1
  56. package/dist/service.d.mts +49 -0
  57. package/dist/service.d.ts +49 -0
  58. package/dist/service.mjs +1 -0
  59. package/dist/ssr/index.d.mts +109 -79
  60. package/dist/ssr/index.d.ts +109 -79
  61. package/dist/ssr/index.mjs +1 -4
  62. package/dist/upload.d.mts +35 -0
  63. package/dist/upload.d.ts +35 -0
  64. package/dist/upload.mjs +1 -0
  65. package/package.json +16 -1
  66. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +0 -4
  67. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +0 -107
  68. package/dist/packem_shared/LunoraClient-CgZ6FhKP.mjs +0 -2721
  69. package/dist/packem_shared/OfflineQueue-BI0FNNvc.mjs +0 -1
  70. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  71. package/dist/packem_shared/SubscriptionRegistry-Dn-7k7eo.mjs +0 -1
  72. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +0 -61
  73. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  74. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  75. package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +0 -105
  76. package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +0 -138
  77. package/dist/packem_shared/createLocalStore-IOur0jHF.mjs +0 -1
  78. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  79. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  80. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  81. package/dist/packem_shared/createServerClient-BxkNcRlR.mjs +0 -11
  82. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  83. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  84. package/dist/packem_shared/local-store-BNgN3Dw3.mjs +0 -111
  85. package/dist/packem_shared/lunora-client.d-B5vWSgvD.d.mts +0 -2196
  86. package/dist/packem_shared/lunora-client.d-B5vWSgvD.d.ts +0 -2196
  87. package/dist/packem_shared/offline-queue-7Wc4onA0.mjs +0 -164
  88. package/dist/packem_shared/preload.d-3XJD-2hM.d.mts +0 -20
  89. package/dist/packem_shared/preload.d-CKZR675M.d.ts +0 -20
  90. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  91. package/dist/packem_shared/subscription-C1Jy7HiF.mjs +0 -55
@@ -0,0 +1,3951 @@
1
+ import { LunoraErrorCodeInput, LunoraErrorCode } from '@lunora/errors';
2
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./function-reference.d-Br_hsKje.mjs";
3
+ import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
4
+ /**
5
+ * Reactive key-value store for local-only client state.
6
+ *
7
+ * Unlike a server {@link SubscriptionState} (which tracks a live WS connection,
8
+ * an `acked` flag, `serverBase`, optimistic layers, and the full subscription
9
+ * machinery), a `ClientQueryRef` is purely local — no server round-trip, no
10
+ * WebSocket, no persistence. It exists so framework adapters can offer a
11
+ * `useClientQuery` hook whose values survive component remounts and are shared
12
+ * across every consumer of the same ref, with none of the ceremony or coupling
13
+ * of a dedicated context provider.
14
+ *
15
+ * The store lives inside `LunoraClient` (a private field) and is surfaced through
16
+ * `client.getClientQuery(ref)` / `setClientQuery(ref, value)` /
17
+ * `subscribeClientQuery(ref, callback)`.
18
+ */
19
+ /** Opaque handle for a typed client-local query slot. */
20
+ interface ClientQueryRef<T = unknown> {
21
+ /** Default value when no value has been set explicitly. */
22
+ readonly defaultValue: T;
23
+ /** Stable identity for the slot. Must be unique within a client instance. */
24
+ readonly key: string;
25
+ }
26
+ /**
27
+ * Create a typed {@link ClientQueryRef}. Call once per slot at module scope
28
+ * (or inside a component module) — the ref object is the stable identity.
29
+ * @example
30
+ * ```ts
31
+ * // lunora/client-queries.ts
32
+ * import { createClientQuery } from "@lunora/client";
33
+ *
34
+ * export const sidebarOpen = createClientQuery("sidebarOpen", true);
35
+ * export const selectedMessageId = createClientQuery("selectedMessageId", undefined as string | undefined);
36
+ * ```
37
+ */
38
+ declare const createClientQuery: <T>(key: string, defaultValue: T) => ClientQueryRef<T>;
39
+ /**
40
+ * Typed reference to an HTTP-SSE stream route (`httpRoute.<verb>(path).stream()`)
41
+ * emitted by `@lunora/codegen` as `httpStreams.<namespace>.<name>`.
42
+ *
43
+ * Distinct from {@link FunctionReference}: this is the **HTTP-SSE route stream**
44
+ * (opened with `fetch` + `ReadableStream` against the route's own URL), not the
45
+ * WS procedure stream (`kind: "stream"`). At runtime it carries the HTTP verb
46
+ * and the route path; the phantom marker carries the chunk / searchParams /
47
+ * params types so `httpStream` (and the framework hooks over it) infer the
48
+ * chunk type end-to-end.
49
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
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
+ * @experimental Part of the HTTP-SSE stream surface.
71
+ */
72
+ interface HttpStreamCallArgs<SearchParams = unknown, Params = unknown> {
73
+ /** Values for the route path's `:name` segments. */
74
+ params?: Params;
75
+ /** URL query params, appended to the request URL (undefined entries are skipped). */
76
+ searchParams?: SearchParams;
77
+ }
78
+ /**
79
+ * Extract the chunk type from a {@link HttpStreamRef}.
80
+ * @experimental Part of the HTTP-SSE stream surface.
81
+ */
82
+ type HttpStreamChunkOf<R> = R extends HttpStreamRef<infer Chunk, infer _S, infer _P> ? Chunk : never;
83
+ /**
84
+ * Extract the call-side args type from a {@link HttpStreamRef}.
85
+ * @experimental Part of the HTTP-SSE stream surface.
86
+ */
87
+ type HttpStreamArgsOf<R> = R extends HttpStreamRef<infer _C, infer S, infer P> ? HttpStreamCallArgs<S, P> : never;
88
+ type Unsubscribe = () => void;
89
+ /**
90
+ * Serializable result of `preloadQuery`. Produced on the server during SSR,
91
+ * embedded in the rendered HTML, then handed to `usePreloadedQuery` on the
92
+ * client so the first render shows the server value with no loading flash
93
+ * before a live subscription attaches. Every field survives `JSON.stringify`.
94
+ */
95
+ interface Preloaded<T = unknown> {
96
+ readonly __lunoraPreloaded: true;
97
+ readonly args: Record<string, unknown>;
98
+ readonly functionPath: string;
99
+ readonly shardKey?: string;
100
+ readonly value: T;
101
+ }
102
+ /**
103
+ * Pluggable storage for the `x-d1-bookmark` value used to provide
104
+ * read-your-writes between a mutation and subsequent queries.
105
+ */
106
+ interface BookmarkStorage {
107
+ get: () => string | null;
108
+ set: (value: string | null) => void;
109
+ }
110
+ interface ReconnectOptions {
111
+ initialDelayMs?: number;
112
+ jitter?: boolean;
113
+ maxDelayMs?: number;
114
+ }
115
+ /** Which durable-storage operation failed, passed to {@link OfflineQueueOptions.onPersistenceError}. */
116
+ type PersistenceOperation = "append" | "clear" | "load" | "remove" | "replace";
117
+ /** Context handed to a persistence-error handler. */
118
+ interface PersistenceErrorContext {
119
+ readonly error: unknown;
120
+ /** The mutation id involved, when the failing op was scoped to one (`append`/`remove`). */
121
+ readonly mutationId?: string;
122
+ readonly operation: PersistenceOperation;
123
+ }
124
+ interface OfflineQueueOptions {
125
+ maxItems?: number;
126
+ /**
127
+ * Invoked when a {@link PersistenceAdapter} call rejects (e.g. IndexedDB quota
128
+ * exceeded). Without a handler, failures are logged via `console.warn` so they
129
+ * are never fully silent. Note: a failed `append` means the write is queued in
130
+ * memory but NOT durable — it will not survive a reload.
131
+ */
132
+ onPersistenceError?: (context: PersistenceErrorContext) => void;
133
+ /**
134
+ * Queue mutations issued before a shard's first successful WebSocket
135
+ * connect (defaults to `false`). The standard behaviour (`LunoraClient`'s
136
+ * `mutation()`) queues only when the targeted shard has been connected at
137
+ * least once (`wasEverConnected`), so the registry / resubscribe handshake
138
+ * has run. Set this to `true` for offline-first apps that want to enqueue
139
+ * writes on the very first session before the WS is up.
140
+ */
141
+ queueBeforeFirstConnect?: boolean;
142
+ }
143
+ /**
144
+ * Serializable shape of an offline mutation, durably stored by a
145
+ * {@link PersistenceAdapter} so queued writes survive a reload/crash. The live
146
+ * `resolve`/`reject` callbacks of an in-flight `QueuedMutation` are *not*
147
+ * persisted — a restored mutation is replayed with no original awaiter.
148
+ */
149
+ interface PersistedMutation {
150
+ args: Record<string, unknown>;
151
+ /**
152
+ * The client id that queued this write, persisted so a replay after a reload
153
+ * lands in the SAME server-side dedup namespace it was issued under. The
154
+ * standalone client's own `clientId` is minted per session, so replaying under
155
+ * the live one would miss the `__idempotency` row for an anonymous caller and
156
+ * re-run a write the server already committed. Absent on records written by
157
+ * older client versions, which replay under the live id.
158
+ */
159
+ clientId?: string;
160
+ functionPath: string;
161
+ id: string;
162
+ /**
163
+ * Issuing identity fingerprint, persisted so a hydrated write replays only
164
+ * under the identity that queued it (`null` = queued while signed out).
165
+ * Absent on records written by older client versions, which replay under
166
+ * the ambient identity for back-compat.
167
+ */
168
+ identity?: string | null;
169
+ shardKey?: string;
170
+ /**
171
+ * App/schema version stamped at enqueue (from `LunoraClientOptions.persistenceVersion`).
172
+ * On hydrate, a record whose `version` doesn't match the current one is dropped
173
+ * and purged rather than replayed — so a write persisted by an older deploy
174
+ * (with a now-changed function signature) can't replay against the new schema.
175
+ * Absent when no `persistenceVersion` is configured (no version gating).
176
+ */
177
+ version?: string;
178
+ }
179
+ /**
180
+ * Durable store for the offline mutation queue. The default client keeps the
181
+ * queue in memory; supplying an adapter (e.g. `createIndexedDbPersistence`)
182
+ * makes queued writes survive a page reload. Implementations must preserve FIFO
183
+ * (enqueue) order in `PersistenceAdapter.load`.
184
+ *
185
+ * Replay semantics are at-least-once: a mutation is removed only after the
186
+ * server confirms (or rejects) it, so a crash between commit and `remove` can
187
+ * replay it again on the next load.
188
+ */
189
+ interface PersistenceAdapter {
190
+ /** Append a mutation to durable storage (called on enqueue). */
191
+ append: (mutation: PersistedMutation) => Promise<void>;
192
+ /** Drop every persisted mutation (e.g. on logout). */
193
+ clear: () => Promise<void>;
194
+ /** Load all persisted mutations in FIFO order — called once at startup. */
195
+ load: () => Promise<PersistedMutation[]>;
196
+ /** Remove a mutation by id once it has been replayed (resolved or rejected). */
197
+ remove: (id: string) => Promise<void>;
198
+ /**
199
+ * Overwrite an already-persisted mutation IN PLACE, keeping its position in
200
+ * FIFO order. Used when a queued write's identity stamp is rewritten after a
201
+ * sign-in / sign-out.
202
+ *
203
+ * Must be atomic: a `remove` + `append` pair has a window where a process
204
+ * stop leaves the mutation in no durable store at all, and the in-memory
205
+ * entry has already advanced, so a reload loses the write outright. It also
206
+ * moved the record to the BACK of the queue, replaying it out of the order
207
+ * it was issued in. Implementations do the whole swap under one transaction
208
+ * (or one serialized blob write).
209
+ *
210
+ * A mutation whose id is not present is left alone — the record was drained
211
+ * concurrently and re-inserting it would replay a settled write.
212
+ */
213
+ replace: (mutation: PersistedMutation) => Promise<void>;
214
+ }
215
+ /**
216
+ * One write handed to an {@link OutboxSink}. Mirrors {@link PersistedMutation}
217
+ * plus the custom-mutator identity (`clientId`/`mutationId`/`idempotencyKey`)
218
+ * the durable outbox needs to dedupe and watermark replays.
219
+ */
220
+ interface OutboxMutation {
221
+ args: Record<string, unknown>;
222
+ /** Stable per-client id; pairs with {@link OutboxMutation.mutationId} as `idempotencyKey`. */
223
+ clientId: string;
224
+ functionPath: string;
225
+ /** `${clientId}:${mutationId}` — sent as `x-lunora-mutation-id` so a replay is server-idempotent. */
226
+ idempotencyKey: string;
227
+ /** Issuing identity fingerprint (`null` = signed out); drives the sink's identity guard. */
228
+ identity: string | null;
229
+ /** Monotonic per-client mutation id, backing the server `__client_watermark`. */
230
+ mutationId: number;
231
+ /**
232
+ * Roll this write's optimistic patch back. The sink's owner invokes it when
233
+ * the replay reaches a PERMANENT verdict (a coded rejection, an identity
234
+ * drop) — never on a transient failure it will retry, and never on success.
235
+ *
236
+ * Without it a rejected replay leaves its predicted value on screen until an
237
+ * unrelated frame or a reload: the client drops the layer when it hands the
238
+ * write over (it cannot cursor-confirm through this path) and has no other
239
+ * signal that the write died. Absent when the write carried no optimistic
240
+ * update, and safe to ignore — a sink that never calls it behaves as before.
241
+ */
242
+ onRejected?: () => void;
243
+ shardKey?: string;
244
+ }
245
+ /**
246
+ * Pluggable durable outbox seam. When set on {@link LunoraClientOptions.outbox},
247
+ * the client delegates offline write durability + at-least-once replay to this
248
+ * sink instead of its built-in {@link PersistenceAdapter}-backed `OfflineQueue`.
249
+ * `@lunora/db` supplies the blessed implementation (`createExecutorOutboxSink`,
250
+ * backed by the TanStack `OfflineExecutor`); the interface itself is
251
+ * dependency-free so `@lunora/client` stays TanStack-free.
252
+ */
253
+ interface OutboxSink {
254
+ /**
255
+ * Persist and schedule a write for replay. Rejects with an
256
+ * `OFFLINE_QUEUE_OVERFLOW`-coded error when the sink's cap is exceeded, so
257
+ * the caller can surface back-pressure to the issuing mutation.
258
+ */
259
+ enqueue: (mutation: OutboxMutation) => Promise<void>;
260
+ }
261
+ /**
262
+ * One persisted query result in the durable read cache (Pillar 2). Keyed in the
263
+ * store by `shardKey + functionPath + argsKey`; the record carries everything
264
+ * needed to render offline on reload and to resume the live subscription.
265
+ */
266
+ interface CachedQuery {
267
+ /**
268
+ * Token-hash fingerprint of the bearer the value was cached under, when the
269
+ * entry was written by the identity the client currently advertises.
270
+ *
271
+ * The second half of the identity gate, and the half that makes the cache
272
+ * usable at all for a bearer-token app. `identity` settles on the resolved
273
+ * subject (`subj:<id>`) once the session resolves, but on the NEXT reload
274
+ * every adapter can only offer the stored token first — the subject arrives
275
+ * a round trip later, and offline it never arrives at all. Matching the
276
+ * credential the entry was written under is what lets the seed happen before
277
+ * (or without) that round trip. Absent when signed out, or when the value
278
+ * arrived over a socket authenticated as someone else.
279
+ */
280
+ credential?: string;
281
+ /**
282
+ * Issuing identity fingerprint (same shape the offline queue stamps). A
283
+ * cached value only hydrates when it matches the current identity, so a
284
+ * signed-out cache never leaks into a new session. `null` = cached while
285
+ * signed out.
286
+ */
287
+ identity: string | null;
288
+ /**
289
+ * The `cursor` high-watermark this value reflects, replayed as `sinceSeq`
290
+ * on reconnect so the server can resume instead of re-snapshotting. Absent
291
+ * when the value predates CDC / no cursor was advertised.
292
+ */
293
+ serverCursor?: number;
294
+ /**
295
+ * The CDC `epoch` the `serverCursor` belongs to, replayed as `sinceEpoch`
296
+ * on reconnect so the server only resumes when the client is still on the
297
+ * same changelog timeline. Absent when no epoch was advertised.
298
+ */
299
+ serverEpoch?: string;
300
+ /** Wall-clock millis the value was written — drives LRU eviction. */
301
+ ts: number;
302
+ /** The full query result last seen from the server. */
303
+ value: unknown;
304
+ /**
305
+ * App/schema version stamped when persisted (from `LunoraClientOptions.persistenceVersion`).
306
+ * A cached value whose `version` doesn't match the current one is not hydrated —
307
+ * so a result of a now-changed shape from an older deploy can't render. Absent
308
+ * when no `persistenceVersion` is configured (no version gating).
309
+ */
310
+ version?: string;
311
+ }
312
+ /** A stored read-cache row: the {@link CachedQuery} plus the key it is stored under. */
313
+ interface StoredQuery extends CachedQuery {
314
+ key: string;
315
+ }
316
+ /**
317
+ * Durable store for the client read cache (Pillar 2): query results survive a
318
+ * reload so reads hydrate from disk and render immediately while the socket
319
+ * reconnects. Opt-in via {@link LunoraClientOptions.queryCache}; omit to keep
320
+ * reads in memory only (today's behaviour). Mirrors {@link PersistenceAdapter}'s
321
+ * shape over the same IndexedDB plumbing.
322
+ */
323
+ interface QueryCacheAdapter {
324
+ /** Drop every cached query (e.g. on logout / identity change). */
325
+ clear: () => Promise<void>;
326
+ /** Load every cached query — called once at startup to hydrate reads. */
327
+ load: () => Promise<StoredQuery[]>;
328
+ /** Upsert one cached query by key (called when a subscription value advances). */
329
+ put: (key: string, entry: CachedQuery) => Promise<void>;
330
+ /** Remove one cached query by key. */
331
+ remove: (key: string) => Promise<void>;
332
+ }
333
+ /**
334
+ * Resolves the WS `?token=` credential fresh at every (re)connect — the channel
335
+ * for short-lived tokens (e.g. the ephemeral admin sub-token the worker mints
336
+ * at `POST /_lunora/admin/ws-token`) instead of a static secret in the URL.
337
+ * May return the token synchronously or as a Promise; returning `undefined`
338
+ * connects without a token. A thrown error / rejected Promise fails that
339
+ * connect attempt, and the client retries with its normal reconnect backoff.
340
+ */
341
+ type WsTokenProvider = () => Promise<string | undefined> | string | undefined;
342
+ interface LunoraClientOptions {
343
+ /**
344
+ * Base path the worker mounts better-auth at, used by the client's
345
+ * `getCurrentUser()` to reach the `get-session` route. Defaults to
346
+ * `/api/auth` (matching `@lunora/auth`'s `DEFAULT_AUTH_BASE_PATH`).
347
+ */
348
+ authBasePath?: string;
349
+ bookmarkStorage?: BookmarkStorage;
350
+ /**
351
+ * Stable per-client id backing the custom-mutator watermark. Sent on the
352
+ * `connect` envelope (so the server can scope this client's
353
+ * `__client_watermark`) and stamped onto every {@link OutboxMutation} the
354
+ * {@link LunoraClientOptions.outbox} sink persists, where it pairs with the
355
+ * monotonic mutation id to form the idempotency key. The `@lunora/db` path
356
+ * persists a stable id alongside the outbox and passes it here; omit for the
357
+ * standalone client, which generates an ephemeral per-session id.
358
+ */
359
+ clientId?: string;
360
+ /**
361
+ * Default app context sent in the `connect` envelope right after each socket
362
+ * opens, forwarded to the server's `onConnect`/`onDisconnect` lifecycle hooks
363
+ * as `event.context`. A per-shard context registered via
364
+ * `setConnectionContext` overrides this for that shard. Omit when no lifecycle
365
+ * hook needs connection context.
366
+ */
367
+ connectionContext?: Record<string, unknown>;
368
+ /**
369
+ * Fail-fast timeout (ms) for opening a subscription WebSocket. If the
370
+ * handshake doesn't complete within this window — a hung dev proxy or a cold
371
+ * worker that never upgrades — the client force-closes the socket and routes
372
+ * through its normal reconnect/backoff (surfacing `offline` status) instead
373
+ * of leaving the live channel silently stuck on the browser's much longer
374
+ * default. Does not affect HTTP queries/mutations (those never ride the WS).
375
+ * Defaults to 10000 (10s); set to `0` (or negative) to disable.
376
+ */
377
+ connectTimeoutMs?: number;
378
+ /**
379
+ * When `true`, tabs sharing the same origin (and the same signed-in identity)
380
+ * coordinate via BroadcastChannel so only one tab — the "leader" — opens
381
+ * WebSocket connections to the server. Reduces simultaneous WS connections,
382
+ * bandwidth, and cross-tab state drift. Requires `BroadcastChannel`
383
+ * (browser-only); silently ignored otherwise. Defaults to `false`.
384
+ *
385
+ * **The channel is one-directional: leader → follower.** The leader
386
+ * broadcasts the values, errors, checkpoints and connection status of the
387
+ * subscriptions *it* holds; there is no frame with which a follower can ask
388
+ * the leader for anything.
389
+ *
390
+ * `subscribe` works on a follower and is how the relay delivers: the
391
+ * registration is what the leader's broadcast key is matched against, so a
392
+ * follower sees a value while the leader independently holds the same
393
+ * `(fn, args, shardKey)`.
394
+ *
395
+ * Nothing else is served, because the leader broadcasts nothing for it and a
396
+ * follower cannot ask. `subscribeShape` and `acquireConnectionContext` are
397
+ * inert on a follower — framework code (`@lunora/db`'s shape sync, every
398
+ * `usePresence` adapter) calls them from an effect the app cannot opt out
399
+ * of, so throwing would unwind the tab rather than degrade one feature.
400
+ * `whisper`, `whisperSubscribe`, `setConnectionContext` and `stream` are
401
+ * only ever called by app code, which can handle a failure, so those throw
402
+ * `NOT_IMPLEMENTED` rather than returning a handle that never fires. (The
403
+ * brief window every tab spends claiming leadership at startup is not a
404
+ * follower state: a lone tab self-promotes and its registered subscriptions
405
+ * are sent then.) HTTP surfaces — `query`, `mutation`, `action`, the offline
406
+ * queue's replay — are unaffected on every tab.
407
+ *
408
+ * So: enable this when your tabs run the SAME app views over plain
409
+ * `subscribe`, and leave it off if tabs can sit on different routes or you
410
+ * use shapes, whispers, streams, or connection context.
411
+ */
412
+ crossTabSync?: boolean;
413
+ fetch?: typeof fetch;
414
+ /**
415
+ * Interval (ms) between keepalive pings sent on each open subscription
416
+ * socket. The server answers them via the Durable Object's hibernation
417
+ * auto-response WITHOUT waking the DO, so an idle socket stays alive across
418
+ * hibernation without a billable wakeup. Defaults to 30000 (30s); set to
419
+ * `0` (or a negative value) to disable the heartbeat entirely.
420
+ */
421
+ heartbeatIntervalMs?: number;
422
+ /**
423
+ * When `true` and a `queryCache` is active, React's `useQuery` holds its
424
+ * TanStack query disabled until the durable cache has finished loading
425
+ * (`whenReady()`), so its first enabled render can seed the cached value
426
+ * instead of issuing an HTTP read that the cache would immediately
427
+ * overwrite. Defaults to `false`.
428
+ *
429
+ * It is ONLY React's `useQuery` that defers — the Vue, Svelte, Solid and
430
+ * Angular hooks subscribe at mount regardless of this flag, and so does
431
+ * React's own subscription registry. They do not need the gate: a
432
+ * subscription opened before the load completes is seeded by the load
433
+ * itself, so a cached value reaches the first subscriber either way.
434
+ *
435
+ * Requires `queryCache` to be set (not `false`); silently ignored otherwise.
436
+ */
437
+ hydrateOnStart?: boolean;
438
+ offlineQueue?: OfflineQueueOptions;
439
+ /**
440
+ * Durable outbox seam for offline writes. When supplied (the `@lunora/db`
441
+ * path wires `createExecutorOutboxSink`), offline mutations are delegated to
442
+ * the sink and the built-in {@link PersistenceAdapter}-backed `OfflineQueue`
443
+ * is bypassed, so a db app has exactly one durable write path. Omit for the
444
+ * standalone client, which keeps using {@link LunoraClientOptions.persistence}.
445
+ */
446
+ outbox?: OutboxSink;
447
+ /**
448
+ * Durable store for the offline mutation queue. Tri-state — an explicit
449
+ * {@link PersistenceAdapter} is used as-is; `false` opts out (the queue stays
450
+ * in memory, lost on reload); omitted (the default) auto-probes a durable
451
+ * IndexedDB store when the `indexedDB` global is present (browsers), otherwise
452
+ * in-memory, so SSR/Node/React-Native keep the in-memory behaviour and only
453
+ * environments that can persist do. Pass `createAsyncStoragePersistence()` on
454
+ * React Native.
455
+ */
456
+ persistence?: false | PersistenceAdapter;
457
+ /**
458
+ * App/schema version stamped onto every persisted queued write and cached
459
+ * read. Bump it on a breaking change to a function signature or query shape:
460
+ * on the next boot, persisted writes / cached reads stamped with a different
461
+ * version are dropped (and purged) rather than replayed / hydrated against the
462
+ * new schema. Omit to disable version gating (records are never invalidated by
463
+ * version).
464
+ *
465
+ * **Adoption is itself an invalidation event:** records written before you set
466
+ * `persistenceVersion` carry no version, so the first boot after enabling it
467
+ * purges all currently-queued offline writes (and cached reads) as stale. Adopt
468
+ * it on a build where that clean slate is acceptable — typically the same
469
+ * breaking deploy you're protecting against — not purely speculatively.
470
+ */
471
+ persistenceVersion?: string;
472
+ /**
473
+ * Durable store for the read cache (Pillar 2). When active, query results
474
+ * are persisted as their subscriptions advance and hydrated on construction
475
+ * so a reload renders cached data before the socket reconnects, then resumes
476
+ * the live subscription from the persisted cursor. Tri-state — an explicit
477
+ * {@link QueryCacheAdapter} is used as-is; `false` opts out (reads stay in
478
+ * memory only); omitted (the default) auto-probes IndexedDB exactly like
479
+ * {@link LunoraClientOptions.persistence}.
480
+ */
481
+ queryCache?: QueryCacheAdapter | false;
482
+ reconnect?: ReconnectOptions;
483
+ url: string;
484
+ WebSocket?: typeof WebSocket;
485
+ /**
486
+ * Credential appended to the WebSocket URL as `?token=…`. The server matches
487
+ * it against `LUNORA_WS_BEARER` (to clear the upgrade gate) and/or
488
+ * `LUNORA_ADMIN_TOKEN` (to authorize `__lunora_admin__:*` subscriptions —
489
+ * what the studio supplies). Browsers can't set headers on the `WebSocket`
490
+ * constructor, so the query parameter is the only channel; it ends up in
491
+ * server logs and history, so prefer a short-lived rotating token in
492
+ * production over a static secret.
493
+ *
494
+ * Pass a {@link WsTokenProvider} function to resolve the token fresh at
495
+ * every (re)connect — the channel for short-lived credentials such as the
496
+ * ephemeral admin sub-token minted by `POST /_lunora/admin/ws-token`: the
497
+ * provider re-mints on each reconnect, including the one following a `4001`
498
+ * token-expired drop, so a static master token never has to ride the URL.
499
+ */
500
+ wsToken?: string | WsTokenProvider;
501
+ wsUrl?: string;
502
+ }
503
+ /** Wire envelope sent on `POST /_lunora/rpc`. */
504
+ interface RpcEnvelope {
505
+ args?: Record<string, unknown>;
506
+ /**
507
+ * Stable per-client identifier (custom-mutator push path). Pairs with
508
+ * {@link RpcEnvelope.mutationId} to form `idempotencyKey` and scope the
509
+ * server `__client_watermark`. Absent on plain `client.mutation` calls.
510
+ */
511
+ clientId?: string;
512
+ functionPath: string;
513
+ /**
514
+ * Idempotency key (`${clientId}:${mutationId}`) for the custom-mutator push
515
+ * path, mirrored into the `x-lunora-mutation-id` header. Absent on plain
516
+ * `client.mutation` calls.
517
+ */
518
+ idempotencyKey?: string;
519
+ /**
520
+ * Monotonic per-client mutation id (custom-mutator push path), backing the
521
+ * server-side per-client watermark: `id <= watermark` is a replay (skipped),
522
+ * `id == watermark + 1` runs authoritatively, `id > watermark + 1` halts the
523
+ * batch so the client resends from `watermark + 1`. Absent on plain
524
+ * `client.mutation` calls.
525
+ */
526
+ mutationId?: number;
527
+ shardKey?: string;
528
+ }
529
+ /**
530
+ * Wire response from the shard's `/rpc` endpoint (forwarded by the runtime). A
531
+ * watermarked custom-mutator push additionally carries `lastMutationId` — the
532
+ * highest per-client sequence the DO has applied — which the client uses to keep
533
+ * its `clientSeq` generator monotonic across reloads (see `LunoraClient.callMutator`).
534
+ * A plain mutation on a CDC shard carries `commitCursor` — the cursor the write
535
+ * committed at — which gates the drop of a per-call optimistic layer.
536
+ */
537
+ type RpcResponseBody = {
538
+ error: {
539
+ code: string;
540
+ data?: unknown;
541
+ message: string;
542
+ };
543
+ } | {
544
+ commitCursor?: number;
545
+ lastMutationId?: number;
546
+ result: unknown;
547
+ };
548
+ /** Subscription protocol — client → server. */
549
+ interface ClientSubscribeMessage {
550
+ id: string;
551
+ /**
552
+ * `sinceSeq` is the persisted `cursor` high-watermark the client last saw
553
+ * for this shard (Pillar 1b resume). Present only when a durable
554
+ * {@link QueryCacheAdapter} restored a cached value with a cursor; the
555
+ * server replies with a lightweight `resume` frame instead of a full
556
+ * snapshot when nothing the query reads changed since it. Absent on a
557
+ * first-time subscribe.
558
+ */
559
+ query: {
560
+ args?: Record<string, unknown>;
561
+ functionPath?: string;
562
+ sinceEpoch?: string;
563
+ sinceSeq?: number;
564
+ table?: string;
565
+ };
566
+ type: "subscribe";
567
+ }
568
+ interface ClientUnsubscribeMessage {
569
+ id: string;
570
+ type: "unsubscribe";
571
+ }
572
+ /**
573
+ * One-shot control frame sent right after the socket opens. Registers the
574
+ * connection's app `context` (e.g. `{ roomId, sessionId }`) with the server and
575
+ * fires the `onConnect` lifecycle hooks; the same context is replayed to
576
+ * `onDisconnect` when the socket drops.
577
+ */
578
+ interface ClientConnectMessage {
579
+ /**
580
+ * Wire behaviours this client can handle that an older one cannot, so the
581
+ * server can use them without breaking clients that can't. Currently just
582
+ * `"pageDelta"`; see `shared/page-result.ts` for what it promises and why it
583
+ * must be announced rather than assumed. Omitting it is always safe.
584
+ */
585
+ caps?: ReadonlyArray<string>;
586
+ /**
587
+ * Stable per-client id (persisted alongside the outbox). Lets the server
588
+ * scope this connection's `__client_watermark` so custom-mutator pokes can
589
+ * echo the right per-client `lastMutationId`. Omitted by clients that don't
590
+ * use custom mutators.
591
+ */
592
+ clientId?: string;
593
+ context?: Record<string, unknown>;
594
+ id: string;
595
+ type: "connect";
596
+ }
597
+ /**
598
+ * Subscribe to a declarative **shape** — server-side partial replication scoped
599
+ * by `shardBy` + the shape's predicate + RLS. The client sends the shape *name*
600
+ * + validated `args`; the server resolves the trusted `where` (identity/RLS
601
+ * `baseWhere` the client can't forge) and streams the matching rowset, then live
602
+ * {@link ServerPokePartMessage} diffs. `id` namespaces the subscription and is
603
+ * echoed as `shapeId` on every poke part.
604
+ */
605
+ interface ClientShapeSubscribeMessage {
606
+ id: string;
607
+ shape: {
608
+ args?: Record<string, unknown>;
609
+ name: string;
610
+ };
611
+ /**
612
+ * Resume from this checkpoint (the `__cdc_log` cursor the client last
613
+ * applied for this shape). When absent or below the server's retained floor
614
+ * (`minCdcSeq`), the server re-seeds with a full insert-poke instead of a
615
+ * delta.
616
+ */
617
+ sinceCheckpoint?: number;
618
+ /**
619
+ * The CDC epoch {@link ClientShapeSubscribeMessage.sinceCheckpoint} belongs
620
+ * to. A mismatch (forked changelog timeline) forces a full re-seed even when
621
+ * the cursor is numerically in range.
622
+ */
623
+ sinceEpoch?: string;
624
+ type: "shape_subscribe";
625
+ }
626
+ /** Cancel a shape subscription started with the same `id`. */
627
+ interface ClientShapeUnsubscribeMessage {
628
+ id: string;
629
+ type: "shape_unsubscribe";
630
+ }
631
+ interface ClientAckMessage {
632
+ id: string;
633
+ type: "ack";
634
+ }
635
+ /**
636
+ * Start a streaming query. The id namespaces a fresh stream and is echoed on
637
+ * every {@link ServerChunkMessage} the server pushes back. Cancel a running
638
+ * stream by sending a {@link ClientUnsubscribeMessage} with the same id —
639
+ * subscription and stream id-spaces share the cancel channel; the prefix
640
+ * (`sub_*` vs `stream_*`) keeps the local registries searchable.
641
+ */
642
+ interface ClientStreamMessage {
643
+ /**
644
+ * Run generation the {@link ClientStreamMessage.sinceChunk} watermark
645
+ * belongs to: the `generation` stamp carried by the chunk frames this
646
+ * client already received, echoed back on a resume. The server refuses to
647
+ * splice a different run's tail onto the held prefix — a mismatch fails
648
+ * with `STREAM_INTERRUPTED` instead. Omitted on a first attach.
649
+ */
650
+ generation?: number;
651
+ id: string;
652
+ query: {
653
+ args?: Record<string, unknown>;
654
+ functionPath: string;
655
+ shardKey?: string;
656
+ };
657
+ /**
658
+ * Resume watermark: the highest chunk `seq` this client already received.
659
+ * Only meaningful for a stream the server declared `durable` — the run
660
+ * replays everything after it and then continues live, which is what turns
661
+ * a reconnect into a resume instead of a lost generation. Omitted on a
662
+ * first attach.
663
+ *
664
+ * Named `sinceChunk`, not `sinceSeq`, because a subscribe envelope already
665
+ * carries a `query.sinceSeq` meaning the CDC cursor.
666
+ */
667
+ sinceChunk?: number;
668
+ type: "stream";
669
+ }
670
+ /**
671
+ * Join or leave a whisper `topic` — an app-chosen ephemeral channel scoped to a
672
+ * shard. While joined, the client receives every {@link ServerWhisperMessage}
673
+ * other members broadcast to the topic.
674
+ */
675
+ interface ClientWhisperSubscribeMessage {
676
+ topic: string;
677
+ type: "whisper_subscribe" | "whisper_unsubscribe";
678
+ }
679
+ /**
680
+ * Broadcast ephemeral `data` to the topic's other members on the shard. The
681
+ * payload is relayed verbatim with no server-side persistence (no SQLite/CDC
682
+ * write) — for typing indicators, live cursors, presence pings. The sender does
683
+ * not receive its own whisper.
684
+ */
685
+ interface ClientWhisperMessage {
686
+ data?: unknown;
687
+ topic: string;
688
+ type: "whisper";
689
+ }
690
+ type ClientMessage = ClientAckMessage | ClientConnectMessage | ClientShapeSubscribeMessage | ClientShapeUnsubscribeMessage | ClientStreamMessage | ClientSubscribeMessage | ClientUnsubscribeMessage | ClientWhisperMessage | ClientWhisperSubscribeMessage;
691
+ /** Subscription protocol — server → client. */
692
+ interface ServerDataMessage {
693
+ /**
694
+ * The `__cdc_log` high-watermark covered by this frame (Pillar 1b). The
695
+ * client persists it as the query's `serverCursor` and replays it as
696
+ * `sinceSeq` on the next reconnect. Absent on shards that never enabled CDC.
697
+ */
698
+ cursor?: number;
699
+ data?: unknown;
700
+ delta?: unknown;
701
+ /** The CDC epoch this frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
702
+ epoch?: string;
703
+ id: string;
704
+ /**
705
+ * The highest custom-mutator `mutationId` from this client the server has
706
+ * now applied (the per-client `__client_watermark`). Echoed so the client's
707
+ * outbox can drop confirmed pending mutations and let TanStack DB collapse
708
+ * the matching optimistic overlay. Absent on shards without custom mutators.
709
+ */
710
+ lastMutationId?: number;
711
+ type: "data" | "delta";
712
+ }
713
+ /**
714
+ * Lightweight resume acknowledgement (Pillar 1b): the server determined that
715
+ * nothing the subscription reads changed since the client's `sinceSeq`, so it
716
+ * skips re-sending the snapshot. The client keeps its cached value and only
717
+ * advances `serverCursor` to `cursor`.
718
+ */
719
+ interface ServerResumeMessage {
720
+ cursor?: number;
721
+ /** The CDC epoch this resume's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
722
+ epoch?: string;
723
+ id: string;
724
+ /** Per-client custom-mutator watermark (see {@link ServerDataMessage.lastMutationId}). */
725
+ lastMutationId?: number;
726
+ type: "resume";
727
+ }
728
+ /**
729
+ * Settled acknowledgement for a **list** subscription: a write touched one of
730
+ * the subscription's read tables but produced a byte-identical result, so the
731
+ * server suppressed the data frame. Sent ONLY to a `@lunora/db` custom-mutator
732
+ * client (one that announced a `clientId`, hence has a server-side
733
+ * `__client_watermark`) so its optimistic list overlay drops even when no data
734
+ * frame arrives. Plain `useQuery` subscribers never receive it, and an older
735
+ * client safely ignores the unknown frame.
736
+ */
737
+ interface ServerSettledMessage {
738
+ cursor?: number;
739
+ /** The CDC epoch this settled frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
740
+ epoch?: string;
741
+ id: string;
742
+ /**
743
+ * The highest custom-mutator `mutationId` from this client the server has
744
+ * now applied (the per-client `__client_watermark`). Forwarded to a
745
+ * collection's `onCheckpoint` so it can drop the overlay for the confirmed
746
+ * write whose result didn't change this list.
747
+ */
748
+ lastMutationId?: number;
749
+ type: "settled";
750
+ }
751
+ interface ServerErrorMessage {
752
+ error?: unknown;
753
+ id?: string;
754
+ message?: string;
755
+ type: "error";
756
+ }
757
+ interface ServerAckMessage {
758
+ id: string;
759
+ type: "ack";
760
+ }
761
+ interface ServerCompleteMessage {
762
+ id: string;
763
+ type: "complete";
764
+ }
765
+ /** One frame of a streaming query — `data` carries the user-yielded chunk. */
766
+ interface ServerChunkMessage {
767
+ data: unknown;
768
+ /**
769
+ * Generation stamp of the **durable** run this chunk belongs to. The client
770
+ * stores it beside {@link ServerChunkMessage.seq} and echoes it as
771
+ * {@link ClientStreamMessage.generation} on a resume, so the server can
772
+ * tell a genuine resume from an attempt to splice onto a different run
773
+ * under the same key. Absent on an ephemeral stream.
774
+ */
775
+ generation?: number;
776
+ id: string;
777
+ /**
778
+ * Monotonic position of this chunk within a **durable** run, starting at 1.
779
+ * The client stores the last one it saw and replays it as
780
+ * {@link ClientStreamMessage.sinceChunk} when the socket comes back. Absent
781
+ * on an ephemeral stream, which has nothing to resume from.
782
+ */
783
+ seq?: number;
784
+ type: "chunk";
785
+ }
786
+ /**
787
+ * An ephemeral whisper relayed from another member of `topic` on the same shard
788
+ * (AnyCable-style whispering). `data` is the sender's payload verbatim; `from`
789
+ * is the sender's verified user id when known (absent for an anonymous sender).
790
+ * Never persisted server-side.
791
+ */
792
+ interface ServerWhisperMessage {
793
+ data: unknown;
794
+ from?: string;
795
+ topic: string;
796
+ type: "whisper";
797
+ }
798
+ /**
799
+ * One row-level change in a shape's replication stream — the wire form of the
800
+ * DO's `__cdc_log` `CdcChange`. `insert`/`update` carry the post-image in
801
+ * `value` (projected to the shape's `columns`); `delete` omits it, identifying
802
+ * the removed row by `key` alone. The client applies these to its local
803
+ * collection; an unknown `key` on a `delete` is a safe no-op (a row the client
804
+ * never had in this shape).
805
+ */
806
+ interface RowOp {
807
+ /** Row primary key (`_id`). */
808
+ key: string;
809
+ op: "delete" | "insert" | "update";
810
+ /** Logical table the row belongs to. */
811
+ table: string;
812
+ /** Post-image document for insert/update; absent on delete. */
813
+ value?: Record<string, unknown>;
814
+ }
815
+ /**
816
+ * Opens a **poke** — an atomically-applied batch of shape diffs (Zero's poke
817
+ * protocol). A `pokeStart` is followed by zero or more {@link ServerPokePartMessage}
818
+ * frames and closed by exactly one {@link ServerPokeEndMessage}; the client
819
+ * buffers every part and applies them in a single transaction at `pokeEnd`, so a
820
+ * socket that drops mid-poke simply re-seeds on reconnect (no torn view).
821
+ */
822
+ interface ServerPokeStartMessage {
823
+ /**
824
+ * Poke-level fallback base, stamped by single-part senders. Per-shape
825
+ * {@link ServerPokePartMessage.baseCheckpoint} takes precedence; this is what
826
+ * a part without its own base falls back to.
827
+ */
828
+ baseCheckpoint?: number;
829
+ /** CDC epoch this poke belongs to; a mismatch forces the client to re-seed rather than apply. */
830
+ epoch?: string;
831
+ /** Correlates this poke's `pokeStart`/`pokePart`/`pokeEnd` frames. */
832
+ pokeId: string;
833
+ type: "pokeStart";
834
+ }
835
+ /** One shape's slice of an in-flight poke: the row-ops to apply for `shapeId`. */
836
+ interface ServerPokePartMessage {
837
+ /**
838
+ * The checkpoint this shape's view must be at for `rowsPatch` to splice on
839
+ * cleanly. Per shape, because every shape on a socket has its own
840
+ * delivered-through cursor. Absent when the server cannot name a base — the
841
+ * gap check is then disarmed for this part, never guessed at.
842
+ */
843
+ baseCheckpoint?: number;
844
+ /** Per-client custom-mutator watermark carried with this slice (see {@link ServerSettledMessage.lastMutationId}). */
845
+ lastMutationId?: number;
846
+ pokeId: string;
847
+ /**
848
+ * `true` when `rowsPatch` is the shape's COMPLETE membership, not a diff (a
849
+ * full seed or re-seed). The client MUST drop its current view for this shape
850
+ * before applying: a seed is inserts-only, so merging it leaves any row that
851
+ * left the shape while the client was disconnected on screen forever.
852
+ *
853
+ * Never inferred from an absent {@link ServerPokePartMessage.baseCheckpoint} —
854
+ * most live poke paths legitimately carry no base.
855
+ */
856
+ reset?: boolean;
857
+ /** Ordered row-level changes for this shape, applied in sequence at `pokeEnd`. */
858
+ rowsPatch: RowOp[];
859
+ /** The {@link ClientShapeSubscribeMessage.id} these row-ops belong to. */
860
+ shapeId: string;
861
+ type: "pokePart";
862
+ }
863
+ /**
864
+ * Closes a poke: the client commits the buffered parts atomically and advances
865
+ * its checkpoint to {@link ServerPokeEndMessage.checkpoint} (the `__cdc_log`
866
+ * cursor high-watermark the view now reflects), replayed as `sinceCheckpoint` on
867
+ * the next reconnect.
868
+ */
869
+ interface ServerPokeEndMessage {
870
+ /** The `__cdc_log` cursor the view is at after applying this poke. */
871
+ checkpoint?: number;
872
+ /** CDC epoch the {@link ServerPokeEndMessage.checkpoint} belongs to. */
873
+ epoch?: string;
874
+ pokeId: string;
875
+ type: "pokeEnd";
876
+ }
877
+ type ServerMessage = ServerAckMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerPokeEndMessage | ServerPokePartMessage | ServerPokeStartMessage | ServerResumeMessage | ServerSettledMessage | ServerWhisperMessage;
878
+ /**
879
+ * The authenticated user as exposed client-side, mirroring better-auth's
880
+ * `user` row (the `user` field of the `get-session` response). Kept minimal
881
+ * and structural — only `id` is guaranteed; the rest are the common better-auth
882
+ * fields, and the index signature carries any plugin-contributed extras.
883
+ */
884
+ interface User {
885
+ readonly createdAt?: NullableTimestamp;
886
+ readonly email?: null | string;
887
+ readonly emailVerified?: boolean | null;
888
+ readonly id: string;
889
+ readonly image?: null | string;
890
+ readonly name?: null | string;
891
+ readonly [key: string]: unknown;
892
+ readonly updatedAt?: NullableTimestamp;
893
+ }
894
+ /**
895
+ * Per-job retry policy carried on a {@link ScheduleRecord}. Mirrors
896
+ * `@lunora/scheduler`'s `RetryPolicy`; absent means the scheduler's defaults.
897
+ */
898
+ interface ScheduleRetryPolicy {
899
+ /** Backoff growth across attempts. Default `"exponential"`. */
900
+ backoff?: "exponential" | "linear";
901
+ /** Base delay in milliseconds for the first retry. Default `30_000`. */
902
+ baseMs?: number;
903
+ /** Maximum number of dispatch attempts before dead-lettering. Default `5`. */
904
+ maxAttempts?: number;
905
+ /** Optional ceiling clamping the computed backoff delay. */
906
+ maxMs?: number;
907
+ }
908
+ /**
909
+ * One pending scheduled function, as returned by the worker's
910
+ * `GET /_lunora/admin/scheduled` endpoint. The route is a byte-for-byte proxy of
911
+ * the SchedulerDO's own `/list`, so this mirrors `@lunora/scheduler`'s
912
+ * `ScheduleRecord` field-for-field — structurally, so the client carries no
913
+ * dependency on it. `packages/client/__tests__/structural-mirrors.test.ts` fails
914
+ * when the two drift.
915
+ */
916
+ interface ScheduleRecord {
917
+ args: Record<string, unknown>;
918
+ /**
919
+ * Dispatch attempts already made. Absent (treated as 0) until the first
920
+ * failure; on a dead-letter record it is the exhausted count (> the retry
921
+ * budget). Surfaced so the studio can show how hard a job tried before it
922
+ * was parked.
923
+ */
924
+ attempts?: number;
925
+ enqueuedAt: number;
926
+ /**
927
+ * The `ns:fn` path dispatched on fire. Absent when the job targets a durable
928
+ * workflow/agent instead — exactly one of `functionPath` /
929
+ * {@link ScheduleRecord.workflow} is set, so a view rendering a job's target
930
+ * must fall back to `workflow` rather than assuming a path.
931
+ */
932
+ functionPath?: string;
933
+ id: string;
934
+ /** Scheduler/workpool instance the job was enqueued through. Absent for the default instance. */
935
+ instanceName?: string;
936
+ /** Logical workpool the job is routed to (concurrency-gated), when any. */
937
+ pool?: string;
938
+ /** Per-job retry policy; absent means the scheduler's built-in defaults. */
939
+ retry?: ScheduleRetryPolicy;
940
+ scheduledFor: number;
941
+ shardKey?: string;
942
+ /**
943
+ * The `WORKFLOW_*`/`AGENT_*` binding a fresh durable instance is started from
944
+ * on fire (the {@link ScheduleRecord.args} become its `params`). Set instead
945
+ * of {@link ScheduleRecord.functionPath}.
946
+ */
947
+ workflow?: string;
948
+ }
949
+ /**
950
+ * One workpool's live backlog, as returned by the worker's
951
+ * `GET /_lunora/admin/scheduled/status` endpoint. Mirrors `@lunora/scheduler`'s
952
+ * `SchedulerPoolStatus` structurally so the client carries no dependency on it.
953
+ */
954
+ interface SchedulerPoolStatus {
955
+ /** Jobs currently dispatched-but-not-yet-completed (the held concurrency slots). */
956
+ inFlight: number;
957
+ /** The pool's concurrency cap. */
958
+ maxConcurrency: number;
959
+ /** The logical workpool name. */
960
+ name: string;
961
+ /** Pending jobs routed to this pool but not yet dispatched. */
962
+ queued: number;
963
+ }
964
+ /**
965
+ * The app-level scheduler backlog, as returned by the worker's
966
+ * `GET /_lunora/admin/scheduled/status` endpoint. `pools` is the per-pool
967
+ * breakdown; `backlog` and `inFlight` are the app-wide sums of `queued` and
968
+ * `inFlight` across every pool — the headline numbers for the studio SLO
969
+ * view. Mirrors `@lunora/scheduler`'s `SchedulerStatus` structurally.
970
+ */
971
+ interface SchedulerStatus {
972
+ /** Sum of every pool's `queued` count — the total pending backlog. */
973
+ backlog: number;
974
+ /** Sum of every pool's `inFlight` count — the total held concurrency slots. */
975
+ inFlight: number;
976
+ /** Per-pool backlog breakdown. */
977
+ pools: SchedulerPoolStatus[];
978
+ }
979
+ /**
980
+ * One shard's request volume, as returned by the worker's
981
+ * `POST /_lunora/admin/shard-traffic` endpoint. The cross-shard traffic feed
982
+ * the studio's `hot_shard` advisor lint consumes: `requests` is the shard's
983
+ * lifetime dispatch total, `shardKey` the DO id name (`""` for the root shard).
984
+ */
985
+ interface ShardTrafficEntry {
986
+ requests: number;
987
+ shardKey: string;
988
+ }
989
+ /**
990
+ * The whole-shard-set traffic distribution returned by the worker's
991
+ * `POST /_lunora/admin/shard-traffic` endpoint. `shards` is one entry per live
992
+ * shard (a failed shard surfaces with `requests: 0`); `ok`/`failed` count the
993
+ * shards that returned vs. errored. Shaped to feed the advisor's `hot_shard`
994
+ * lint after the studio tags each entry with its sharded function `group`.
995
+ */
996
+ interface ShardTrafficResult {
997
+ failed: number;
998
+ ok: number;
999
+ shards: ShardTrafficEntry[];
1000
+ }
1001
+ /**
1002
+ * One object in the storage bucket, as returned by the worker's
1003
+ * `GET /_lunora/admin/storage` endpoint. Mirrors `@lunora/storage`'s
1004
+ * `R2ObjectLike` structurally.
1005
+ */
1006
+ interface StorageObject {
1007
+ customMetadata?: Record<string, string>;
1008
+ etag: string;
1009
+ httpMetadata?: {
1010
+ contentType?: string;
1011
+ };
1012
+ key: string;
1013
+ size: number;
1014
+ /**
1015
+ * When the object was stored. R2 emits a `Date`, which JSON-serializes to an
1016
+ * ISO string over the wire; a mock may supply epoch ms — so consumers should
1017
+ * normalise via `new Date(uploaded)`. Absent if the backend didn't report it.
1018
+ */
1019
+ uploaded?: number | string;
1020
+ }
1021
+ /** One page of {@link StorageObject}s plus the cursor to fetch the next, if any. */
1022
+ interface StorageListPage {
1023
+ cursor?: string;
1024
+ objects: StorageObject[];
1025
+ }
1026
+ /**
1027
+ * One argument of a registered function, derived from its `v.*` validator by the
1028
+ * worker. A compact signature shape — enough to render a function's API without
1029
+ * the build-time codegen types.
1030
+ */
1031
+ interface FunctionArgumentDescriptor {
1032
+ /** Element validator kind for an `array` arg (one level), e.g. `string`. */
1033
+ element?: string;
1034
+ /** The (optional-unwrapped) validator kind, e.g. `string`, `id`, `object`. */
1035
+ kind: string;
1036
+ /** The argument name. */
1037
+ name: string;
1038
+ /** True when the arg is wrapped in `v.optional(...)`. */
1039
+ optional: boolean;
1040
+ /** Target table for an `id` arg (`v.id("table")`). */
1041
+ table?: string;
1042
+ }
1043
+ /**
1044
+ * One registered function, as returned by the worker's
1045
+ * `GET /_lunora/admin/functions` endpoint: its `<file>:<function>` path, which
1046
+ * client method (`query` / `mutation` / `action`) invokes it, and its argument
1047
+ * signature. `args` is absent on responses from an older worker.
1048
+ */
1049
+ interface FunctionDescriptor {
1050
+ args?: FunctionArgumentDescriptor[];
1051
+ kind: "action" | "mutation" | "query";
1052
+ path: string;
1053
+ }
1054
+ /** A `.global()` (D1-backed) table plus its row count, from `/_lunora/admin/global/tables`. */
1055
+ interface GlobalTableInfo {
1056
+ name: string;
1057
+ rowCount: number;
1058
+ }
1059
+ /** A window of rows from one global table, from `/_lunora/admin/global/table`. */
1060
+ interface GlobalTablePage {
1061
+ columns: string[];
1062
+ /** FK columns (local column → referenced table) for external tables with real `REFERENCES` constraints, from `PRAGMA foreign_key_list`. */
1063
+ refs?: Record<string, string>;
1064
+ rows: Record<string, unknown>[];
1065
+ total: number;
1066
+ }
1067
+ /**
1068
+ * One equality constraint a facet-value click adds to the global browser's view
1069
+ * (`column = value`). `value` is the raw stored scalar the facet returned, sent
1070
+ * as-is and bound server-side, so it never injects SQL.
1071
+ */
1072
+ interface GlobalFilterClause {
1073
+ column: string;
1074
+ value: unknown;
1075
+ }
1076
+ /** One distinct value of a faceted global column with its row count, from `/_lunora/admin/global/facet`. */
1077
+ interface GlobalFacetValue {
1078
+ count: number;
1079
+ value: unknown;
1080
+ }
1081
+ /** Per-column distinct-value summary for the global browser, from `/_lunora/admin/global/facet`. */
1082
+ interface GlobalFacetResult {
1083
+ truncated: boolean;
1084
+ values: GlobalFacetValue[];
1085
+ }
1086
+ /** A nullable timestamp field as better-auth serializes it: epoch-ms, ISO string, or null. */
1087
+ type NullableTimestamp = null | number | string;
1088
+ /** A workflow instance's lifecycle status. Mirrors Cloudflare's `InstanceStatus`. */
1089
+ type WorkflowInstanceStatus = "complete" | "errored" | "paused" | "queued" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
1090
+ /** The lifecycle mutations the status endpoint accepts. */
1091
+ type WorkflowInstanceAction = "pause" | "resume" | "terminate";
1092
+ /** One row of the workflow-instances list. */
1093
+ interface WorkflowInstanceSummary {
1094
+ createdOn?: string;
1095
+ endedOn?: string;
1096
+ id: string;
1097
+ startedOn?: string;
1098
+ status: WorkflowInstanceStatus;
1099
+ }
1100
+ /** One durable step of an instance's execution timeline. */
1101
+ interface WorkflowStepDetail {
1102
+ /** 1-based attempt count (`> 1` means the step retried). */
1103
+ attempts?: number;
1104
+ end?: string;
1105
+ error?: unknown;
1106
+ name: string;
1107
+ output?: unknown;
1108
+ start?: string;
1109
+ success?: boolean;
1110
+ /** `step` / `sleep` / `waitForEvent` / … (Cloudflare's step `type`). */
1111
+ type?: string;
1112
+ }
1113
+ /** A workflow instance's full detail: summary plus params/output/error and the step timeline. */
1114
+ interface WorkflowInstanceDetail extends WorkflowInstanceSummary {
1115
+ error?: unknown;
1116
+ output?: unknown;
1117
+ params?: unknown;
1118
+ steps: WorkflowStepDetail[];
1119
+ }
1120
+ /** A page of workflow instances. */
1121
+ interface WorkflowInstancePage {
1122
+ /**
1123
+ * Whether workflow inspection is configured on the worker (a Cloudflare
1124
+ * account id + API token). `false` when the admin proxy reports it can't
1125
+ * inspect instances; omitted (treated as configured) otherwise. Lets a
1126
+ * caller render a "set credentials" state without a failed request.
1127
+ */
1128
+ configured?: boolean;
1129
+ instances: WorkflowInstanceSummary[];
1130
+ page: number;
1131
+ perPage: number;
1132
+ totalCount?: number;
1133
+ }
1134
+ type SubscriptionCallback = (data: unknown) => void;
1135
+ /**
1136
+ * The high-water marks a shape poke has now synced to the client: `checkpoint`
1137
+ * is the op-log cursor and `mutationId` the highest custom-mutator id the server
1138
+ * echoed for this client. A `@lunora/db` collection feeds these into its
1139
+ * checkpoint registry to drop optimistic overlays once the server's authoritative
1140
+ * rows have landed.
1141
+ */
1142
+ interface SyncWatermark {
1143
+ checkpoint?: number;
1144
+ mutationId?: number;
1145
+ /**
1146
+ * `true` only on the checkpoint a `data`/`delta` frame fires immediately
1147
+ * before that same frame's rowset callback — i.e. the one checkpoint whose
1148
+ * `mutationId` describes rows that are about to arrive.
1149
+ *
1150
+ * A `settled` frame (and a cross-tab `subscription-settled` relay) fires a
1151
+ * checkpoint with NO matching rowset, because the server suppressed a data
1152
+ * frame whose value didn't change. A consumer that stashes `mutationId` for
1153
+ * the next rowset to consume — `@lunora/db`'s `pendingFrameWatermark` — must
1154
+ * not stash those, or the value sits until some later unstamped frame eats
1155
+ * it and the checkpoint gate resolves at a stale watermark instead of
1156
+ * falling back to the RPC-ack compensator.
1157
+ */
1158
+ rowsFollow?: boolean;
1159
+ }
1160
+ /** A subscription-scoped error the server pushed for this subscription id. */
1161
+ interface SubscriptionError {
1162
+ /**
1163
+ * The coded reason, when the frame carried one. `LunoraErrorCodeInput`, not
1164
+ * `LunoraErrorCode`: the catalog codes autocomplete for a consumer branching
1165
+ * on this (the shard sends `BAD_SUBSCRIPTION_ARGS`, `TOO_MANY_SUBSCRIPTIONS`,
1166
+ * `SUBSCRIPTION_PERSIST_FAILED`, …; the client itself adds
1167
+ * `WIRE_DECODE_FAILED` for a frame `decodeWire` refuses), but this value is
1168
+ * read verbatim off the wire and nothing validates it against the catalog,
1169
+ * so narrowing it to `LunoraErrorCode` would be a lie a newer server tells.
1170
+ */
1171
+ code?: LunoraErrorCodeInput;
1172
+ message: string;
1173
+ }
1174
+ type SubscriptionErrorCallback = (error: SubscriptionError) => void;
1175
+ /**
1176
+ * One active per-call optimistic transform layered onto a subscription. The
1177
+ * displayed value is the authoritative {@link SubscriptionState.serverBase}
1178
+ * folded through every layer's `transform`, in order — so an incoming server
1179
+ * frame re-folds the still-pending layers onto the new base (rebasing) instead
1180
+ * of clobbering them. A layer is dropped — gaplessly — once a `data`/`delta`
1181
+ * frame whose `cursor >= commitCursor` arrives (its write is now reflected in
1182
+ * `serverBase`); `commitCursor` is the CDC cursor the server echoed on the
1183
+ * mutation's response, and stays `undefined` while the write is still queued/
1184
+ * in-flight (so the overlay survives unrelated deltas until confirmed).
1185
+ */
1186
+ interface OptimisticLayer {
1187
+ /** The committed CDC cursor (from the mutation response); `undefined` until confirmed. */
1188
+ commitCursor?: number;
1189
+ readonly id: symbol;
1190
+ readonly transform: (current: unknown) => unknown;
1191
+ }
1192
+ interface SubscriptionState {
1193
+ /** True once the server has acked the subscription on the current socket. */
1194
+ acked: boolean;
1195
+ readonly args: Record<string, unknown>;
1196
+ /**
1197
+ * Stable wire-key of `args` (`stableWireKey`), computed once at subscribe
1198
+ * time. Cached so the optimistic-update fan-out can compare against a
1199
+ * mutation's args key without re-serializing every subscription's args on
1200
+ * every mutation.
1201
+ */
1202
+ readonly argsKey: string;
1203
+ readonly callbacks: Set<SubscriptionCallback>;
1204
+ /**
1205
+ * Notified when a `settled` frame advances this subscription's watermark — a
1206
+ * write touched the subscription's tables but the result was byte-identical,
1207
+ * so the server suppressed the data frame. A `@lunora/db` list collection
1208
+ * uses this to drop the optimistic overlay for the confirmed write.
1209
+ *
1210
+ * A SET (not a single slot) because `SubscriptionState` is SHARED across
1211
+ * every subscriber to the same `(fn, args, shardKey)`: a `@lunora/db`
1212
+ * collection may subscribe to a query a plain `useQuery` already opened, so
1213
+ * each subscriber registers its own callback (mirroring `callbacks` /
1214
+ * `errorCallbacks`) and a `settled` frame fans out to all of them. Plain
1215
+ * `useQuery` consumers register nothing, leaving the set empty.
1216
+ */
1217
+ readonly checkpointCallbacks: Set<(watermark: SyncWatermark) => void>;
1218
+ /** Notified when the server rejects this subscription (e.g. admin auth). */
1219
+ readonly errorCallbacks: Set<SubscriptionErrorCallback>;
1220
+ readonly fn: FunctionReference;
1221
+ readonly id: string;
1222
+ /**
1223
+ * The highest custom-mutator `mutationId` from this client the server has
1224
+ * applied, captured from the last `settled` frame (the suppressed-list-frame
1225
+ * watermark). Forwarded to {@link SubscriptionState.checkpointCallbacks}.
1226
+ * Absent until a `settled` frame arrives.
1227
+ */
1228
+ lastMutationId?: number;
1229
+ /** Last known value, used to short-circuit `useQuery`-style consumers. */
1230
+ lastValue: unknown;
1231
+ /**
1232
+ * Active per-call optimistic layers, in application order (see
1233
+ * {@link OptimisticLayer}). Empty for subscriptions with no pending per-call
1234
+ * optimistic write — the common case, where `lastValue` tracks `serverBase`
1235
+ * exactly and behaviour is identical to a plain server-value assignment.
1236
+ */
1237
+ optimisticLayers: OptimisticLayer[];
1238
+ /**
1239
+ * The authoritative server value the optimistic layers fold onto — the value
1240
+ * with NO optimistic overlay. Tracks `lastValue` exactly whenever no layers
1241
+ * are active; diverges only while a per-call optimistic write is pending. A
1242
+ * server frame updates this (and re-folds the layers); the durable read cache
1243
+ * persists this, never the optimistic overlay.
1244
+ */
1245
+ serverBase: unknown;
1246
+ /**
1247
+ * The `__cdc_log` high-watermark (`cursor`) the `lastValue` reflects,
1248
+ * captured from the last `data`/`delta`/`resume` frame. Persisted to the
1249
+ * durable read cache and replayed as `sinceSeq` on reconnect so the server
1250
+ * can resume instead of re-snapshotting (Pillar 1b/2). Absent until the
1251
+ * first cursor-stamped frame arrives.
1252
+ */
1253
+ serverCursor?: number;
1254
+ /**
1255
+ * The CDC `epoch` token the `serverCursor` belongs to, captured from the
1256
+ * same frame. Replayed as `sinceEpoch` on reconnect so the server resumes
1257
+ * only when the client is still on the same changelog timeline — a reset or
1258
+ * recycled shard advertises a new epoch, forcing a fresh snapshot. Absent
1259
+ * until the first epoch-stamped frame arrives.
1260
+ */
1261
+ serverEpoch?: string;
1262
+ readonly shardKey?: string;
1263
+ /**
1264
+ * The wire-encoded form of `args`, computed once at `subscribe` time (so an
1265
+ * unsupported value fails loud at the call site, not inside a reconnect's
1266
+ * open handler). Sent on every `subscribe` frame — identical to `args` for
1267
+ * pure JSON, tagged tokens for `bigint`/`Date`/bytes/… (the shard
1268
+ * `decodeWire`s them at its subscribe entry point).
1269
+ *
1270
+ * A SNAPSHOT, not a view: `args` is the caller's own object, retained by
1271
+ * reference and never copied, so a caller that mutates it after subscribing
1272
+ * would otherwise poison every later resubscribe. `encodeWire` rebuilds
1273
+ * every container, so this copy is immune to that.
1274
+ */
1275
+ readonly wireArgs: Record<string, unknown>;
1276
+ }
1277
+ /**
1278
+ * Active subscription registry. The client keys subscriptions by
1279
+ * `(functionPath, stableWireKey(args), shardKey)` so duplicate calls share a
1280
+ * single server-side registration. Args are stably encoded (keys sorted at every
1281
+ * depth) so two structurally-equal arg records constructed with a different key
1282
+ * order (`{ a, b }` vs `{ b, a }`) collapse to the same key instead of leaking a
1283
+ * duplicate subscription. Encoding the args' **wire form** keeps the key
1284
+ * byte-identical for pure-JSON args while giving wire-typed args (`bigint`,
1285
+ * `Date`, bytes, …) distinct stable tokens instead of a throw.
1286
+ */
1287
+ declare class SubscriptionRegistry {
1288
+ static key(functionPath: string, args: Record<string, unknown>, shardKey?: string): string;
1289
+ /**
1290
+ * The registry key of an already-registered state, from its cached
1291
+ * {@link SubscriptionState.argsKey}. Re-deriving it from `state.args` would
1292
+ * re-read the caller's own (mutable) args object, so a caller that mutated
1293
+ * its args after subscribing would compute a DIFFERENT key on unsubscribe
1294
+ * and leak the registration forever.
1295
+ */
1296
+ static keyOf(state: SubscriptionState): string;
1297
+ private readonly byKey;
1298
+ private readonly byId;
1299
+ get(key: string): SubscriptionState | undefined;
1300
+ getById(id: string): SubscriptionState | undefined;
1301
+ add(state: SubscriptionState): void;
1302
+ remove(state: SubscriptionState): void;
1303
+ all(): SubscriptionState[];
1304
+ /**
1305
+ * Drop every registration. Terminal — used by `LunoraClient.close()`, whose
1306
+ * whole point is to release the callback closures each {@link SubscriptionState}
1307
+ * holds (`callbacks`, `errorCallbacks`, `checkpointCallbacks` — React state
1308
+ * setters and `@lunora/db` collection closures), which otherwise outlive the
1309
+ * closed client for as long as the client object is reachable.
1310
+ */
1311
+ clear(): void;
1312
+ }
1313
+ /**
1314
+ * Read/write handle over the client's live query cache, handed to a mutation's
1315
+ * `withOptimisticUpdate` callback so a single mutation can optimistically patch
1316
+ * many subscribed queries at once (Convex's `OptimisticLocalStore` model).
1317
+ *
1318
+ * `getQuery` reads the current value (server value or any still-pending
1319
+ * optimistic override) of a subscribed query; `setQuery` registers a constant
1320
+ * optimistic layer on top. The whole batch rebases onto incoming deltas and
1321
+ * settles together — confirmed on the mutation's commit cursor, or rolled back
1322
+ * on failure — the same per-subscription layer machinery the single-query
1323
+ * per-call `optimistic` transform uses, generalized to N queries.
1324
+ */
1325
+ interface OptimisticLocalStore {
1326
+ /**
1327
+ * Every loaded subscription on `function_`, regardless of args, paired with
1328
+ * the args it was subscribed under. Mirrors Convex's `getAllQueries` — handy
1329
+ * when a write must patch every variant of a list query (all channels,
1330
+ * all filters) without enumerating their args up front.
1331
+ */
1332
+ getAllQueries: <F extends FunctionReference>(function_: F) => {
1333
+ args: ArgsOf<F>;
1334
+ value: ReturnOf<F> | undefined;
1335
+ }[];
1336
+ /**
1337
+ * Current cached value for the subscribed `(function_, args)` query, or
1338
+ * `undefined` when nothing is subscribed/loaded for it. Reflects any
1339
+ * optimistic override already written in this batch.
1340
+ */
1341
+ getQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>) => ReturnOf<F> | undefined;
1342
+ /**
1343
+ * Write an optimistic override for the subscribed `(function_, args)`
1344
+ * query. A no-op (returns without effect) when no subscription matches —
1345
+ * mirroring Convex, where you only patch queries the page is watching.
1346
+ */
1347
+ setQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>, value: ReturnOf<F> | undefined) => void;
1348
+ }
1349
+ /** A mutation's multi-query optimistic update: read/write the cache via `localStore`. */
1350
+ type OptimisticUpdate<Args> = (localStore: OptimisticLocalStore, args: Args) => void;
1351
+ /**
1352
+ * Build an {@link OptimisticLocalStore} bound to a subscription registry and the
1353
+ * mutation's shard key. Each `setQuery(value)` registers a constant-value layer
1354
+ * on its target subscription (via `applyOptimisticLayer`): the predicted value
1355
+ * survives incoming server deltas (re-clamped, masking concurrent changes to that
1356
+ * query — not merged) and drops gaplessly on the mutation's commit cursor, like
1357
+ * the single-query per-call `optimistic` path. Returns the store plus the ordered
1358
+ * `confirm` (success) and `rollback` (failure) closures every `setQuery` produced,
1359
+ * so the caller settles the whole batch when the mutation does.
1360
+ */
1361
+ declare const createLocalStore: (subscriptions: SubscriptionRegistry, shardKey: string | undefined) => {
1362
+ confirms: ((commitCursor: number | undefined) => void)[];
1363
+ rollbacks: (() => void)[];
1364
+ store: OptimisticLocalStore;
1365
+ };
1366
+ declare const DEFAULT_MAX_BUFFER = 1024;
1367
+ interface StreamHandle<T = unknown> {
1368
+ /** Mark the stream complete (no more chunks); resolves any pending consumer to `done:true`. */
1369
+ readonly complete: () => void;
1370
+ /** Surface an error to any pending consumer; subsequent pushes are dropped. */
1371
+ readonly fail: (error: Error) => void;
1372
+ /**
1373
+ * Push one chunk. Silent no-op once the stream is `complete`, `fail`-ed,
1374
+ * or `cancel`-ed. When the buffer is already at `maxBuffer`, the stream
1375
+ * is failed with a `STREAM_BACKPRESSURE` error and the push is dropped —
1376
+ * the producer never sees a thrown exception.
1377
+ */
1378
+ readonly push: (value: T) => void;
1379
+ }
1380
+ interface StreamIterable<T> extends AsyncIterable<T> {
1381
+ /** Cancel the stream from the consumer side: closes the iterator and notifies the registered canceller. */
1382
+ cancel: () => void;
1383
+ }
1384
+ /**
1385
+ * Build a stream handle paired with an async-iterable. The handle is the
1386
+ * server-driven side (the WS dispatcher pushes chunks / completes / errors);
1387
+ * the iterable is what the user awaits. `onCancel` is invoked exactly once
1388
+ * when the consumer calls `.cancel()` (or `.return()`) so the client can
1389
+ * send a `{type:"unsubscribe"}` frame to the server.
1390
+ */
1391
+ declare const createStream: <T>(options: {
1392
+ maxBuffer?: number;
1393
+ onCancel: () => void;
1394
+ }) => {
1395
+ handle: StreamHandle<T>;
1396
+ iterable: StreamIterable<T>;
1397
+ };
1398
+ type WSState = "idle" | "connecting" | "open" | "closed";
1399
+ /**
1400
+ * Aggregate live-socket health across every shard connection, for a UI status
1401
+ * indicator. `idle` = no socket opened yet; `connecting` = at least one socket
1402
+ * is (re)connecting and none is open; `connected` = at least one socket is open;
1403
+ * `offline` = sockets exist but all are down (between reconnect attempts).
1404
+ */
1405
+ type ConnectionStatus = "connected" | "connecting" | "idle" | "offline";
1406
+ /** One shard's socket + watermark state in a {@link LunoraClient.debug} snapshot. */
1407
+ interface ClientDebugShard {
1408
+ /**
1409
+ * Highest custom-mutator watermark the server has echoed for this client on this
1410
+ * shard. A write whose `clientSeq` is above this has been sent but not confirmed
1411
+ * — the first thing to check when an optimistic overlay won't clear.
1412
+ */
1413
+ confirmedMutationWatermark: number;
1414
+ /** Whether a `WebSocket` object currently exists (distinct from it being open). */
1415
+ hasSocket: boolean;
1416
+ /** `undefined` for the default (unsharded) connection. */
1417
+ shardKey: string | undefined;
1418
+ /** Whether this shard's socket has ever completed a handshake — gates offline queueing. */
1419
+ wasEverConnected: boolean;
1420
+ wsState: WSState;
1421
+ }
1422
+ /** One live query or shape subscription in a {@link LunoraClient.debug} snapshot. */
1423
+ interface ClientDebugSubscription {
1424
+ /** Whether the server has acknowledged the subscription on the current socket. */
1425
+ acked: boolean;
1426
+ /** `namespace:fn` for a query, `shape:<name>` for a replication shape. */
1427
+ functionPath: string;
1428
+ id: string;
1429
+ kind: "query" | "shape";
1430
+ /** Highest custom-mutator watermark echoed on THIS subscription (absent until a `settled`/poke frame arrives). */
1431
+ lastMutationId?: number;
1432
+ /** Per-call optimistic layers still folded onto this subscription's value — a non-zero count with no pending write is a leak. */
1433
+ pendingOptimisticLayers: number;
1434
+ /** Replicated rowset size (shapes only). */
1435
+ rowCount?: number;
1436
+ /** The `__cdc_log` cursor the current value reflects. */
1437
+ serverCursor?: number;
1438
+ shardKey: string | undefined;
1439
+ /** How many callers share this subscription (subscriptions are deduped by `(fn, args, shard)`). */
1440
+ subscriberCount: number;
1441
+ }
1442
+ /**
1443
+ * Everything the sync engine believes at one instant — see
1444
+ * {@link LunoraClient.debug} for why this exists.
1445
+ */
1446
+ interface ClientDebugSnapshot {
1447
+ /** The watermark key the server's custom-mutator protocol advances per `clientSeq`. */
1448
+ clientId: string;
1449
+ closed: boolean;
1450
+ connectionStatus: ConnectionStatus;
1451
+ /** Writes waiting in the built-in offline queue (not the `@lunora/db` outbox). */
1452
+ pendingWrites: number;
1453
+ shards: ClientDebugShard[];
1454
+ subscriptions: ClientDebugSubscription[];
1455
+ }
1456
+ /**
1457
+ * Terminal verdict for a mutation that passed through the offline queue,
1458
+ * delivered to {@link LunoraClient.onMutationSettled}.
1459
+ *
1460
+ * Unlike the Promise returned by {@link LunoraClient.mutation} — which only the
1461
+ * original caller can await, and which no longer exists after a reload — this
1462
+ * fires for *every* queued write the server (or the queue) reaches a verdict on,
1463
+ * including writes restored from durable storage in a later session. It is the
1464
+ * channel a UI uses to tell the user "your queued change couldn't be saved"
1465
+ * instead of silently dropping a rolled-back optimistic row.
1466
+ *
1467
+ * `status: "rejected"` carries the failure `code` (e.g. `CONFLICT`,
1468
+ * `OFFLINE_QUEUE_OVERFLOW`, `OFFLINE_IDENTITY_CHANGED`) and the `error`.
1469
+ * `hadAwaiter` is `false` for a write whose original `mutation()` Promise is
1470
+ * gone (a hydrated/post-reload replay or an eviction), so a listener can tell
1471
+ * "the caller already saw this" apart from "nothing else will report this".
1472
+ */
1473
+ interface MutationSettledEvent {
1474
+ /** The write's args, so a listener can describe or re-offer the change. */
1475
+ readonly args: Record<string, unknown>;
1476
+ /** Server/queue error code on `rejected` (e.g. `CONFLICT`), when present. */
1477
+ readonly code?: string;
1478
+ /** The rejection error on `status: "rejected"`. */
1479
+ readonly error?: unknown;
1480
+ /** The `<file>:<function>` reference of the mutation. */
1481
+ readonly functionPath: string;
1482
+ /** Whether a live caller was still awaiting this write's `mutation()` Promise. */
1483
+ readonly hadAwaiter: boolean;
1484
+ /** The write's stable id (idempotency key / queue id). */
1485
+ readonly id: string;
1486
+ /** Shard the write targeted, if any. */
1487
+ readonly shardKey?: string;
1488
+ /** Terminal outcome. */
1489
+ readonly status: "committed" | "rejected";
1490
+ }
1491
+ /**
1492
+ * Per-call options for {@link LunoraClient.action} — just `shardKey`, since an
1493
+ * action is not a write and carries none of the optimistic machinery. Exported
1494
+ * (at the end of this file) for the same reason {@link MutationCallOptions} is:
1495
+ * so the framework adapters (`@lunora/react`, `/solid`, `/svelte`, `/vue`,
1496
+ * `/angular`) type their `call(args, options?)` against one canonical
1497
+ * definition. Add an option here and every adapter forwards it; re-declare it
1498
+ * per adapter and they silently cannot.
1499
+ */
1500
+ interface ActionCallOptions {
1501
+ /** Route the call to a specific shard. */
1502
+ shardKey?: string;
1503
+ }
1504
+ /**
1505
+ * Per-call options for {@link LunoraClient.mutation} — the optimistic-update
1506
+ * machinery plus `shardKey`. Exported (at the end of this file) so the framework
1507
+ * adapters (`@lunora/react`, `/solid`, `/svelte`, `/vue`) can type their
1508
+ * `mutate(args, options?)` against one canonical definition instead of
1509
+ * re-declaring it.
1510
+ */
1511
+ interface MutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unknown> {
1512
+ /**
1513
+ * Override the auto-generated idempotency key (`x-lunora-mutation-id`). Lets a
1514
+ * durable outbox replay a committed-but-unacked write under its *original* key
1515
+ * so the server dedups it instead of applying it twice. Omit for normal calls —
1516
+ * each then gets a fresh key.
1517
+ */
1518
+ mutationId?: string;
1519
+ /**
1520
+ * Single-query shortcut: the transform is layered onto the subscription
1521
+ * registered under **this write's own** `(functionPath, args, shardKey)`, and
1522
+ * nothing else. A client cannot know which queries a write affects, so the
1523
+ * targeting rule is "same reference, same args" — which makes this the
1524
+ * shorthand for a query and a mutation that share a path (a counter, a
1525
+ * document by id), and a silent no-op for anything else.
1526
+ *
1527
+ * **The general case — a `messages:send` mutation patching a `messages:list`
1528
+ * query — is {@link MutationCallOptions.optimisticUpdate}**, whose store names
1529
+ * its targets. Reach for that whenever the mutation and the query are
1530
+ * different functions, which is nearly always.
1531
+ *
1532
+ * The transform must be pure: it re-runs on every server frame while the write
1533
+ * is pending, so derive from `current` rather than closing over a value.
1534
+ */
1535
+ optimistic?: (current: TCurrent | undefined) => TValue;
1536
+ /**
1537
+ * Convex-parity multi-query optimistic update. Receives an
1538
+ * `OptimisticLocalStore` over the live subscription cache plus the
1539
+ * mutation's args, so one mutation can patch many subscribed queries at
1540
+ * once; every write is rolled back atomically if the mutation fails.
1541
+ */
1542
+ optimisticUpdate?: OptimisticUpdate<TArgs>;
1543
+ /**
1544
+ * Sync predicate evaluated just before the offline queue replays this
1545
+ * write on reconnect. When it returns `false` the mutation is dropped
1546
+ * instead of replayed — use it to guard against replaying writes whose
1547
+ * assumptions are no longer valid (e.g. the document it referred to was
1548
+ * deleted by another client while this tab was offline).
1549
+ */
1550
+ precondition?: () => boolean;
1551
+ shardKey?: string;
1552
+ }
1553
+ /** Callback a shape subscription invokes with its materialized rowset on every applied poke. */
1554
+ type ShapeCallback = (rows: Record<string, unknown>[]) => void;
1555
+ /**
1556
+ * An `Error` carrying the server's machine-readable `code` and (for a
1557
+ * `LunoraError`) structured `data`, plus an optional actionable `hint` (Markdown)
1558
+ * and `docsUrl` resolved from the central error catalog. The client's public
1559
+ * error contract for RPC/batch failures — a UI can render `hint`/`docsUrl` to
1560
+ * tell the user how to fix the error. The `(string & {})` arm keeps
1561
+ * forward-compat/unknown server codes assignable without losing autocomplete on
1562
+ * the known {@link LunoraErrorCode} union.
1563
+ */
1564
+ type LunoraClientError = Error & {
1565
+ code?: LunoraErrorCode | (string & {});
1566
+ data?: unknown;
1567
+ docsUrl?: string;
1568
+ hint?: string | string[];
1569
+ };
1570
+ /** One demuxed result slot of a {@link LunoraClient.batch} call (plan 088). */
1571
+ type BatchSlot = {
1572
+ error: LunoraClientError;
1573
+ ok: false;
1574
+ } | {
1575
+ ok: true;
1576
+ value: unknown;
1577
+ };
1578
+ /**
1579
+ * Lunora browser/edge client. Talks RPC over HTTP and real-time deltas over
1580
+ * a single multiplexed WebSocket.
1581
+ *
1582
+ * Reconnect, offline queueing, and optimistic updates are all handled here;
1583
+ * see the package README for the wire protocol.
1584
+ */
1585
+ declare class LunoraClient {
1586
+ /** 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. */
1587
+ private static readonly MAX_POKE_BUFFERS;
1588
+ /**
1589
+ * Create a typed {@link ClientQueryRef}. Convenience wrapper around
1590
+ * {@link createClientQuery} so you don't need a separate import.
1591
+ * @example
1592
+ * ```ts
1593
+ * const sidebarOpen = LunoraClient.createClientQuery("sidebarOpen", true);
1594
+ * ```
1595
+ */
1596
+ static createClientQuery<T>(key: string, defaultValue: T): ClientQueryRef<T>;
1597
+ readonly url: string;
1598
+ readonly wsUrl: string;
1599
+ /** Local reactive store for {@link ClientQueryRef} values — no server round-trip. Private; reach it via `getClientQuery` / `setClientQuery` / `subscribeClientQuery`. */
1600
+ private readonly clientQueryStore;
1601
+ private wsToken;
1602
+ /** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
1603
+ private readonly authBasePath;
1604
+ private readonly fetchImpl;
1605
+ private readonly WebSocketImpl;
1606
+ private readonly bookmark;
1607
+ private readonly reconnectOptions;
1608
+ /** WS connect timeout (ms); `0` disables it. See {@link LunoraClientOptions.connectTimeoutMs}. */
1609
+ private readonly connectTimeoutMs;
1610
+ /** Keepalive cadence (ms); `0` disables the heartbeat. See {@link LunoraClientOptions.heartbeatIntervalMs}. */
1611
+ private readonly heartbeatIntervalMs;
1612
+ private readonly offlineQueue;
1613
+ /**
1614
+ * Durable outbox seam (the `@lunora/db` `createExecutorOutboxSink`). When
1615
+ * set, offline writes are delegated here and the built-in {@link OfflineQueue}
1616
+ * is bypassed, so a db app has exactly one durable write path.
1617
+ */
1618
+ private readonly outbox;
1619
+ /** Stable per-client id stamped onto every `OutboxMutation` (custom-mutator watermark). */
1620
+ private readonly clientId;
1621
+ /**
1622
+ * Highest CDC cursor this client has seen a write commit at, per shard key
1623
+ * (`""` for the default shard) — the read-your-writes bookmark sent as
1624
+ * `x-lunora-min-seq`.
1625
+ *
1626
+ * In memory only, and deliberately: it exists to keep THIS session's reads
1627
+ * behind THIS session's writes. Persisting it across reloads would pin a
1628
+ * fresh page to a cursor it has no reason to require and force needless
1629
+ * fallbacks to the owner.
1630
+ */
1631
+ private readonly shardCursors;
1632
+ /**
1633
+ * The server's own name for the default shard (`defaultShardKey`), learned
1634
+ * from the first response to a call that named no shard. `undefined` until
1635
+ * then, which is why `cursorKeyFor` falls back to a placeholder entry that
1636
+ * `learnDefaultShardKey` folds in once the name arrives.
1637
+ */
1638
+ private defaultShardKey;
1639
+ /**
1640
+ * `true` when the constructor's hydration microtask has finished loading the
1641
+ * durable read cache (Pillar 2) into `hydratedQueryCache`. Signals that
1642
+ * the cache is ready for synchronous `peekHydratedQuery` reads.
1643
+ */
1644
+ private readyResolved;
1645
+ /** Resolvers for `whenReady()` — called once hydration completes. */
1646
+ private readyResolve;
1647
+ /**
1648
+ * Promise that resolves once the durable read cache has been loaded. When
1649
+ * `hydrateOnStart` is not set or no query cache is configured, resolves
1650
+ * immediately (the constructor creates an already-resolved promise).
1651
+ */
1652
+ private readonly readyPromise;
1653
+ /**
1654
+ * Highest custom-mutator watermark the server has echoed for this client,
1655
+ * nested by identity fingerprint (`identityFingerprint() ?? ""`) then shard
1656
+ * bucket (`shardKey ?? ""`) — the DO tracks one `__client_watermark` per
1657
+ * `(identity, clientId)` pair, not per bucket alone, so a bucket-only key
1658
+ * would let a user switch claim the previous identity's sequence and wedge
1659
+ * every push on `OUT_OF_ORDER` until a reload (plan 316). A nested map
1660
+ * (rather than a single map composite-keyed by a joined string) is what a
1661
+ * previous fix here tried and got wrong: an identity fingerprint or a
1662
+ * `shardKey` is an arbitrary string, so any string delimiter — even one as
1663
+ * exotic as U+FFFD — can appear in one operand and collide with the other
1664
+ * (a fingerprint of `a<SEP>x` + bucket `y` joins to the same string as
1665
+ * a fingerprint of `a` + bucket `x<SEP>y`), mixing two identities' watermarks.
1666
+ * The nested map has no join step, so there is no delimiter to collide.
1667
+ * `callMutator` bumps it from every ack; the `@lunora/db` mutator runtime
1668
+ * seeds its `clientSeq` generator from it so a reload (which resets the
1669
+ * in-memory counter) never reissues a stale sequence the server would
1670
+ * silently swallow as a replay.
1671
+ */
1672
+ private readonly clientWatermarks;
1673
+ /** Monotonic per-client mutation counter backing the server `__client_watermark`. */
1674
+ private outboxMutationCounter;
1675
+ private readonly onPersistenceError;
1676
+ private readonly persistence;
1677
+ /** App/schema version stamped on persisted writes + cached reads; mismatches are purged. */
1678
+ private readonly persistenceVersion;
1679
+ /** Releases the multi-tab outbox-leader Web Lock on close (see `hydrateAsOutboxLeader`). */
1680
+ private outboxLeaderRelease;
1681
+ /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
1682
+ private readonly queryCache;
1683
+ /**
1684
+ * Values restored from the `queryCache` at construction, keyed by the
1685
+ * read-cache key, awaiting the `subscribe()` that will consume them. A
1686
+ * key is consumed (deleted) the first time its subscription is created, so
1687
+ * the cache only ever seeds the initial value — live frames take over after.
1688
+ */
1689
+ private readonly hydratedQueryCache;
1690
+ /**
1691
+ * The read-cache entries currently ON DISPLAY in a live subscription, by the
1692
+ * same key — every entry consumed out of `hydratedQueryCache` and not yet
1693
+ * overwritten by a server frame.
1694
+ *
1695
+ * Gating the cache at read time only protects a value not handed over YET.
1696
+ * A credential can change while a cached value is already on screen (the
1697
+ * account-switch shape: an established subject, a token it was never checked
1698
+ * against), and the fingerprint does not move with it — so nothing else
1699
+ * would notice. `revokeCacheSeededValues` takes those values back off
1700
+ * screen and returns the entries to `hydratedQueryCache`, where the ordinary
1701
+ * identity gate decides whether they may ever be shown again.
1702
+ */
1703
+ private readonly cacheSeededQueries;
1704
+ /**
1705
+ * Coalesced read-cache writes: the latest value per key, flushed to
1706
+ * the `queryCache` on a short debounce so a burst of deltas persists once.
1707
+ */
1708
+ private readonly pendingCacheWrites;
1709
+ private cacheFlushTimer;
1710
+ private readonly subscriptions;
1711
+ /**
1712
+ * Cross-tab coordinator; created only when `crossTabSync: true`. When the
1713
+ * client is not the elected leader, all WebSocket operations are skipped.
1714
+ * Not `readonly` — `close()` clears it (mirrors `outboxLeaderRelease`).
1715
+ */
1716
+ private tabCoordinator;
1717
+ /**
1718
+ * The leader's last-broadcast aggregate {@link ConnectionStatus}, mirrored
1719
+ * on a follower tab — which owns no `ShardConnection` of its own to
1720
+ * compute a status from (see `computeStatus`). `undefined` until the
1721
+ * leader's first broadcast (falls back to `"idle"`), and reset back to
1722
+ * `undefined` whenever this tab stops being a follower of the CURRENT
1723
+ * leader (becomes leader itself, or the leader changes), so a stale
1724
+ * mirror from a previous leader never survives a leadership change.
1725
+ */
1726
+ private leaderStatus;
1727
+ /**
1728
+ * Sticky "has the mirrored leader status ever reported `connected`" flag —
1729
+ * the follower's counterpart to {@link ShardConnection.wasEverConnected},
1730
+ * since a follower has no `ShardConnection` of its own. Feeds the
1731
+ * offline-queue gate (see `mutation`) exactly like the real per-shard flag
1732
+ * does on the leader/single-tab path.
1733
+ */
1734
+ private leaderWasEverConnected;
1735
+ /** One {@link ShardConnection} per shard key (keyed by `shardKey ?? ""`). */
1736
+ private readonly connections;
1737
+ /** Default `connect`-envelope context applied to a shard with no explicit override. */
1738
+ private readonly defaultConnectionContext;
1739
+ /**
1740
+ * Per-shard `connect`-envelope context registered via `setConnectionContext`
1741
+ * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
1742
+ * on every socket open so it replays across reconnects, and forwarded to the
1743
+ * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
1744
+ * imperative (last-writer-wins) override; refcounted holders registered via
1745
+ * `acquireConnectionContext` live in `connectionContextHolders` and take
1746
+ * precedence — see `effectiveConnectionContext`.
1747
+ */
1748
+ private readonly connectionContexts;
1749
+ /**
1750
+ * Per-shard stack of refcounted connection-context holders (keyed by
1751
+ * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
1752
+ * is an opaque token carrying its `context`; the most-recently acquired
1753
+ * holder wins (last-writer-wins among live holders), and the context is only
1754
+ * cleared for a shard once its last holder releases — so two concurrently
1755
+ * mounted presence hooks on the same shard can't stomp each other's context
1756
+ * on cleanup. A holder is identified by reference identity so a release
1757
+ * removes exactly the right one regardless of stack position.
1758
+ */
1759
+ private readonly connectionContextHolders;
1760
+ private authToken;
1761
+ /**
1762
+ * Optional STABLE identity subject (a user id), the basis of the offline-queue
1763
+ * identity stamp when supplied. Keeps a same-user token *refresh* from looking
1764
+ * like an identity change (which would discard queued writes). `undefined` =
1765
+ * not supplied, so identity falls back to a hash of the raw token. See
1766
+ * `setAuthToken` / `identityFingerprint`.
1767
+ */
1768
+ private authSubject;
1769
+ /**
1770
+ * The bearer token `authSubject` was last asserted against. A subject
1771
+ * is a claim about WHO a specific credential belongs to; once the token
1772
+ * rotates, the sticky label is carried forward on the assumption it is the
1773
+ * same user — but nothing has confirmed that yet, and the alternative (an
1774
+ * account switch) would replay one user's queued writes as another. While
1775
+ * this is out of step with `authToken` the identity counts as unconfirmed
1776
+ * and every replay verdict is `"unknown"` (hold), until the next session
1777
+ * resolve re-asserts the subject. Only used when a subject is established;
1778
+ * a token-hash identity is self-confirming.
1779
+ */
1780
+ private subjectToken;
1781
+ /**
1782
+ * Identity stamp recorded against each queued offline mutation, keyed by
1783
+ * the queue-assigned mutation id. Captured at enqueue from the auth token
1784
+ * in effect at the time, and re-checked at flush so a queued write can
1785
+ * never replay under a different identity than the one that issued it.
1786
+ * See `identityFingerprint` for the fingerprint shape.
1787
+ */
1788
+ private readonly queuedIdentities;
1789
+ /**
1790
+ * Distinct shard keys with a mutation currently sitting in `offlineQueue`
1791
+ * — fresh writes queued this session (`enqueueOfflineMutation`) or writes
1792
+ * restored from durable storage (`hydratePersistedQueue`). A follower tab
1793
+ * has no per-shard `ShardConnection` to iterate when its mirrored leader
1794
+ * status turns `"connected"` (see the `onConnectionStatus` coordinator
1795
+ * option), so this is what that flush walks instead. Entries are never
1796
+ * removed — flushing an already-empty shard is a cheap no-op, and the set
1797
+ * is bounded by the app's own distinct shard-key cardinality.
1798
+ */
1799
+ private readonly queuedOfflineShardKeys;
1800
+ private closed;
1801
+ /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
1802
+ private readonly authTokenListeners;
1803
+ /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
1804
+ private readonly statusListeners;
1805
+ /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
1806
+ private readonly tokenExpiredListeners;
1807
+ /** Token hash the last durable-replay auth refusal fired `onTokenExpired` for — see `shouldRequeueReplayFailure`. */
1808
+ private authRefusalNotifiedFor;
1809
+ /** Subscribers to offline-queued mutation verdicts (see `onMutationSettled`). */
1810
+ private readonly mutationSettledListeners;
1811
+ /** Subscribers to the offline-queue pending-count (see `onPendingChange`). */
1812
+ private readonly pendingChangeListeners;
1813
+ /**
1814
+ * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
1815
+ * of callbacks. Membership doubles as the resubscribe set replayed on every
1816
+ * (re)connect so a topic survives a socket bounce.
1817
+ */
1818
+ private readonly whisperHandlers;
1819
+ /** Last status broadcast, so we only notify listeners on an actual change. */
1820
+ private lastStatus;
1821
+ private nextSubId;
1822
+ private nextStreamId;
1823
+ /**
1824
+ * In-flight client-side stream readers, keyed by the stream id sent on the
1825
+ * wire. The handle drives the underlying iterator queue and `shardKey`
1826
+ * tells us which socket to push the cancel frame onto when the consumer
1827
+ * calls `.cancel()` or the iterator is garbage-collected.
1828
+ */
1829
+ private readonly streams;
1830
+ /** Live shape subscriptions (partial replication), keyed by their wire id. */
1831
+ /**
1832
+ * Teardown callbacks for the admin sockets {@link LunoraClient.subscribeScheduledJobs}
1833
+ * opens. Those run their own reconnect loop off a closure-local `closed`
1834
+ * flag rather than `this.closed` (they predate `ensureSocket`'s guard), so
1835
+ * without this registry a `close()` left every one of them reconnecting on
1836
+ * its backoff forever — re-minting an ephemeral admin sub-token on each
1837
+ * attempt when a `WsTokenProvider` is wired.
1838
+ */
1839
+ private readonly adminSocketTeardowns;
1840
+ /**
1841
+ * The in-flight offline-queue replay per shard (`connectionKey`), while one
1842
+ * is running. Two jobs:
1843
+ *
1844
+ * 1. It serializes overlapping flushes for the same shard — two reconnect
1845
+ * events in quick succession used to drain and replay concurrently.
1846
+ * 2. It is the barrier {@link LunoraClient.mutation} waits on before sending a FRESH
1847
+ * write directly. The socket's `open` handler flips `wsState` to `"open"`
1848
+ * first and calls the flush last, so from that instant `mutation()`'s
1849
+ * offline gate is false and a new write raced straight to `/rpc` against
1850
+ * the replay of the older, queued write for the same document — the newer
1851
+ * one could land first and then be overwritten by the older. Ordering
1852
+ * inside the replay (`replaySequential`) never covered this, because the
1853
+ * racing write was never in the queue.
1854
+ */
1855
+ private readonly offlineFlushes;
1856
+ /**
1857
+ * Per-shard replay backoff, keyed by {@link connectionKey} exactly as the
1858
+ * flushes and their timers are: `delayMs` is the longest hint the CURRENT
1859
+ * flush of that key was given (written by
1860
+ * {@link LunoraClient.noteReplayRetryDelay}, consumed once by
1861
+ * {@link LunoraClient.scheduleRateLimitedRetry} at the end of the drain), and
1862
+ * `attempts` counts its consecutive failed flushes, which is what the
1863
+ * hintless backoff ramps on.
1864
+ *
1865
+ * Keyed, not a single field: flushes are per shard key and run concurrently,
1866
+ * so one field means one limited shard sets the wait for every other shard
1867
+ * and two flushes overwrite — then consume — each other's delay, leaving one
1868
+ * of them with nothing scheduled at all. Evicted by
1869
+ * {@link LunoraClient.scheduleRateLimitedRetry} the moment a key has nothing
1870
+ * left to retry, so an app that shards per document does not accumulate an
1871
+ * entry per document it ever wrote.
1872
+ */
1873
+ private readonly replayRetryState;
1874
+ /** Pending rate-limit retry flushes, keyed by {@link connectionKey}, so `close()` can cancel them. */
1875
+ private readonly replayRetryTimers;
1876
+ private readonly shapeSubscriptions;
1877
+ /**
1878
+ * In-flight pokes being assembled between `pokeStart` and `pokeEnd`, keyed by
1879
+ * `<connectionKey>\u0000<pokeId>`.
1880
+ *
1881
+ * The connection has to be in the key: `pokeId` is a per-DO counter that also
1882
+ * resets on eviction, so a multi-shard client — one socket per shard, one map
1883
+ * here — sees two shards mint `poke-1` concurrently. Keyed by `pokeId` alone
1884
+ * their frames interleave into a single buffer: one shard applies the other's
1885
+ * epoch (spurious fork → view wiped) and the other finds no buffer for its
1886
+ * parts at all, silently dropping rows while the server's memo advances.
1887
+ */
1888
+ private readonly pokeBuffers;
1889
+ private nextShapeId;
1890
+ constructor(options: LunoraClientOptions);
1891
+ /**
1892
+ * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
1893
+ * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
1894
+ * sync across all mounted instances.
1895
+ *
1896
+ * Pass a STABLE `subject` (the user id) to key the offline-queue identity on
1897
+ * it instead of the token bytes, so a token *refresh* (same user, new JWT)
1898
+ * doesn't read as an identity change and discard queued writes. The subject is
1899
+ * **sticky**: a later call that omits it (or passes `undefined`) keeps the
1900
+ * established subject — so `setAuthToken(refreshedToken)` after a prior
1901
+ * `setAuthToken(token, user.id)` retains the identity. Clearing the token
1902
+ * clears it too — a credential-less subject would let the NEXT sign-in
1903
+ * inherit the previous user's identity (and their queue and read cache).
1904
+ * Establishing the subject on an UNCHANGED token (e.g. the user id resolves a
1905
+ * tick after the token was set — see {@link getCurrentUser}, which does this
1906
+ * for every adapter) re-stamps any in-flight queued writes rather than
1907
+ * dropping them: same credential, just a more stable label. A real user
1908
+ * switch still drops the previous user's writes.
1909
+ *
1910
+ * A sticky subject carried across a token change is not re-confirmed until
1911
+ * the next session resolve says which user the NEW credential belongs to.
1912
+ * Queued writes are HELD (never sent, never dropped) for that window — see
1913
+ * {@link replayIdentityVerdict} — so a refresh can't replay them and an
1914
+ * account switch can't replay the previous user's writes as the new one.
1915
+ *
1916
+ * Does NOT update the WebSocket auth — the WS token is fixed at upgrade
1917
+ * time and lives in the URL. To refresh live WS auth, call
1918
+ * {@link setWsToken} explicitly, which closes existing shard sockets to
1919
+ * force a reconnect with the new credential.
1920
+ */
1921
+ setAuthToken(token: string | null, subject?: string | null): void;
1922
+ getAuthToken(): string | null;
1923
+ /**
1924
+ * The current identity fingerprint (the same stamp queued offline writes
1925
+ * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
1926
+ * owns its own at-least-once replay outside the built-in `OfflineQueue` —
1927
+ * can drop a persisted write whose captured `identity` no longer matches the
1928
+ * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
1929
+ */
1930
+ currentIdentity(): string | null;
1931
+ /**
1932
+ * Verdict on whether a durable write stamped with `stamped` may be replayed
1933
+ * now. The comparison a replay handler must NOT hand-roll.
1934
+ *
1935
+ * `"match"` is the same identity, or the same credential under a token hash
1936
+ * — which a late-resolving subject would otherwise make look different.
1937
+ *
1938
+ * `"unknown"` is nobody signed in *yet*. A durable replay starts when the
1939
+ * executor is constructed, before the app has resolved its session and
1940
+ * called {@link setAuthToken}, so this is the normal state on every reload.
1941
+ * There is no other identity to replay as, so such a write must be HELD,
1942
+ * never dropped — dropping here destroys the queuing user's own offline
1943
+ * writes. It is indistinguishable from an explicit sign-out (the fingerprint
1944
+ * is `null` for both), which is the safe conflation: holding a write for a
1945
+ * signed-out app costs a retry, dropping it costs the write.
1946
+ *
1947
+ * A sticky subject carried across a token change is `"unknown"` for the same
1948
+ * reason: the label says user A, the credential in hand has not been checked
1949
+ * against it, and the two answers (a refresh vs an account switch) call for
1950
+ * opposite verdicts. Hold until the next session resolve settles it.
1951
+ *
1952
+ * `"mismatch"` is a different identity signed in, and is the one that must be
1953
+ * terminal: replaying would attribute one user's write to another and pass
1954
+ * THEIR row-level security.
1955
+ */
1956
+ replayIdentityVerdict(stamped: null | string | undefined): "match" | "mismatch" | "unknown";
1957
+ /** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
1958
+ clientIdentifier(): string;
1959
+ /**
1960
+ * The highest custom-mutator watermark the server has echoed for this client
1961
+ * on the given shard (0 if none yet). The `@lunora/db` mutator runtime seeds
1962
+ * its `clientSeq` generator from this so a reload never reissues a sequence
1963
+ * the server has already applied (which it would swallow as a replay, silently
1964
+ * dropping the write).
1965
+ */
1966
+ confirmedMutationWatermark(shardKey?: string): number;
1967
+ /**
1968
+ * Push a custom mutator to its authoritative server impl over the watermark
1969
+ * protocol (Phase 4): the request carries `x-lunora-client-id` + a monotonic
1970
+ * `x-lunora-client-seq`, so the DO runs it exactly once and advances this
1971
+ * client's `__client_watermark`.
1972
+ *
1973
+ * Returns the server `result` plus `applied`: `true` when the DO ran this push
1974
+ * as the next-in-order mutation, `false` when it was a replay ack (`clientSeq`
1975
+ * was at or below the stored watermark — e.g. a stale sequence after a reload).
1976
+ * A `false` verdict tells the caller to reissue above the now-known watermark
1977
+ * (echoed into {@link confirmedMutationWatermark}) rather than treat the benign
1978
+ * ack as a confirmed write. Every ack — applied or not — bumps the watermark.
1979
+ *
1980
+ * This is the online transport for `@lunora/db`'s client-mutator runtime; the
1981
+ * optimistic overlay + durable-outbox concerns live in that runtime, not here.
1982
+ */
1983
+ callMutator(functionPath: string, args: Record<string, unknown>, options?: {
1984
+ clientSeq?: number;
1985
+ shardKey?: string;
1986
+ }): Promise<{
1987
+ applied: boolean;
1988
+ result: unknown;
1989
+ }>;
1990
+ /**
1991
+ * Subscribe to auth-token changes. Returns an unsubscribe function. The
1992
+ * listener is NOT invoked on registration — use {@link getAuthToken} for
1993
+ * the current value.
1994
+ */
1995
+ onAuthTokenChange(listener: (token: string | null) => void): Unsubscribe;
1996
+ /**
1997
+ * Fetch the currently authenticated user from better-auth's `get-session`
1998
+ * endpoint, returning the `user` record or `null` when signed out. Sends
1999
+ * the stored bearer token (if any) and `credentials: "include"` so a
2000
+ * cookie-session is also honoured. A network/parse failure or a non-OK
2001
+ * response resolves to `null` rather than throwing — callers treat "couldn't
2002
+ * resolve identity" as "signed out".
2003
+ *
2004
+ * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
2005
+ * the token changes (that's what `@lunora/react`'s `useAuth` does).
2006
+ *
2007
+ * A resolved user also ESTABLISHES the identity subject for the credential
2008
+ * that resolved it ({@link setAuthToken}'s second argument). This is the one
2009
+ * call every adapter's identity store already makes, and the only place that
2010
+ * knows the answer — leaving it to each adapter is what left the sticky-subject
2011
+ * contract unreached in every shipped one, so a routine JWT refresh read as a
2012
+ * user switch and discarded the user's own queued writes and read cache.
2013
+ */
2014
+ getCurrentUser(): Promise<User | null>;
2015
+ /**
2016
+ * Replace the token appended to WS upgrade URLs as `?token=…` and close
2017
+ * every open shard socket so the reconnect picks up the new value. Call
2018
+ * this whenever the user's WS credential changes (rotating the admin token
2019
+ * in the studio, switching workspaces, etc.). Accepts a static string or a
2020
+ * {@link WsTokenProvider} resolved fresh at every (re)connect — the channel
2021
+ * for short-lived credentials like the minted ephemeral admin sub-token.
2022
+ * Bearer tokens for HTTP RPC are independent — see {@link setAuthToken}.
2023
+ */
2024
+ setWsToken(token: string | undefined | WsTokenProvider): void;
2025
+ /**
2026
+ * Register (or clear, with `undefined`) the app context sent in the `connect`
2027
+ * envelope for a shard's socket, overriding the client-wide
2028
+ * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
2029
+ * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
2030
+ * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
2031
+ * presence row is removed the instant the socket drops, with no TTL lag.
2032
+ *
2033
+ * Stored per shard and replayed on every (re)connect. When a socket for the
2034
+ * shard is already open, a fresh `connect` envelope is sent immediately so the
2035
+ * server sees the new context without waiting for a reconnect.
2036
+ *
2037
+ * Not available on a `crossTabSync` FOLLOWER tab — the context rides the
2038
+ * `connect` envelope of a socket a follower does not own, so it would be
2039
+ * stored and never sent. Throws `NOT_IMPLEMENTED` there.
2040
+ */
2041
+ setConnectionContext(context: Record<string, unknown> | undefined, options?: {
2042
+ shardKey?: string;
2043
+ }): void;
2044
+ /**
2045
+ * Refcounted variant of {@link setConnectionContext}: register a connection
2046
+ * `context` for a shard and get back a release function. Unlike the imperative
2047
+ * setter, the context is only cleared once the *last* acquired holder releases
2048
+ * it — so two components (e.g. two mounted `usePresence` hooks) on the same
2049
+ * shard no longer clobber each other's context when one of them unmounts. The
2050
+ * most-recently acquired live holder wins (last-writer-wins), and releasing
2051
+ * the top holder falls back to the previous one rather than clearing.
2052
+ *
2053
+ * With a single holder the behaviour is identical to a
2054
+ * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
2055
+ * Releasing more than once is a no-op (the holder is matched by reference, so
2056
+ * a double release can't drop a different holder).
2057
+ */
2058
+ acquireConnectionContext(context: Record<string, unknown>, options?: {
2059
+ shardKey?: string;
2060
+ }): Unsubscribe;
2061
+ /**
2062
+ * Join a whisper `topic` and receive every ephemeral message other members
2063
+ * broadcast to it on the same shard (typing indicators, live cursors,
2064
+ * presence pings). Whispers never touch the server's durable state — there's
2065
+ * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
2066
+ * is left on the server once its last local handler unsubscribes.
2067
+ *
2068
+ * `handler` receives the raw `data` and the sender's verified `from` user id
2069
+ * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
2070
+ * (the default shard when omitted) — use the same shard you target with the
2071
+ * matching queries/mutations so members land on the same Durable Object.
2072
+ *
2073
+ * Security: whisper topics are NOT access-controlled beyond the shard
2074
+ * boundary — any client that can open a socket to the shard can join, read,
2075
+ * and inject on any topic name. `from` is server-stamped and unforgeable, but
2076
+ * do not put data on a whisper topic that some shard members shouldn't see,
2077
+ * and don't trust a whisper's `data` as authorization. Use a query/mutation
2078
+ * (with RLS) for anything privileged; whispers are for transient awareness.
2079
+ *
2080
+ * Not available on a `crossTabSync` FOLLOWER tab — whisper frames are not
2081
+ * relayed over the cross-tab channel, so this throws `NOT_IMPLEMENTED`
2082
+ * there rather than registering a handler nothing can ever reach. See
2083
+ * {@link LunoraClientOptions.crossTabSync}.
2084
+ */
2085
+ whisperSubscribe(topic: string, handler: (data: unknown, from?: string) => void, options?: {
2086
+ shardKey?: string;
2087
+ }): Unsubscribe;
2088
+ /**
2089
+ * Broadcast an ephemeral `data` payload to the other members of a whisper
2090
+ * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
2091
+ * dropped when the shard socket isn't open (whispers are transient, never
2092
+ * queued), and the server silently drops it if the sender exceeds its
2093
+ * whisper rate budget. The sender never receives its own whisper. Omitting
2094
+ * `data` delivers JSON `null` to receivers (not `undefined`).
2095
+ *
2096
+ * That best-effort drop is for a socket that is momentarily down. A
2097
+ * `crossTabSync` FOLLOWER tab has no socket and never will (see
2098
+ * {@link LunoraClientOptions.crossTabSync}), so every whisper from it would
2099
+ * be dropped forever — it throws `NOT_IMPLEMENTED` instead.
2100
+ */
2101
+ whisper(topic: string, data?: unknown, options?: {
2102
+ shardKey?: string;
2103
+ }): void;
2104
+ /**
2105
+ * Subscribe to token-expiry events: invoked whenever the server drops a
2106
+ * shard socket because the connection's credential lapsed (close code
2107
+ * `4001`). The client already reconnects automatically (re-resolving
2108
+ * identity from the cookie/token in effect); use this to refresh a
2109
+ * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
2110
+ * with a freshly minted one. Returns an unsubscribe function.
2111
+ */
2112
+ onTokenExpired(listener: () => void): Unsubscribe;
2113
+ /**
2114
+ * Current aggregate live-socket status across all shard connections. See
2115
+ * {@link ConnectionStatus}.
2116
+ */
2117
+ connectionStatus(): ConnectionStatus;
2118
+ /**
2119
+ * Subscribe to aggregate connection-status changes. Invokes `listener`
2120
+ * immediately with the current status, then on every transition. Returns an
2121
+ * unsubscribe function.
2122
+ */
2123
+ onConnectionStatus(listener: (status: ConnectionStatus) => void): Unsubscribe;
2124
+ /**
2125
+ * Number of offline writes waiting in the built-in queue to be sent — the
2126
+ * depth for a "N changes waiting to sync" indicator. Counts writes that are
2127
+ * queued (offline / mid-reconnect), not ones already in flight on the wire.
2128
+ * A `@lunora/db` app whose writes ride the unified outbox should read
2129
+ * `LunoraDb.pendingCount()` instead (this counts only the built-in queue).
2130
+ */
2131
+ pendingCount(): number;
2132
+ /**
2133
+ * A point-in-time snapshot of everything the sync engine believes right now:
2134
+ * per-shard sockets and watermarks, every live query and shape subscription with
2135
+ * its cursor and ack state, and the offline-queue depth.
2136
+ *
2137
+ * This exists because the alternative is `console.log`. When an optimistic
2138
+ * overlay doesn't clear, the questions are always the same — *is the socket open?
2139
+ * what watermark has the server confirmed for this shard? has this shape been
2140
+ * poked since my write? is anything stuck in the queue?* — and none of them were
2141
+ * answerable from outside the client, so every adopter ends up instrumenting the
2142
+ * library by hand or building a bespoke policy layer around a symptom.
2143
+ *
2144
+ * Read it from a devtools console, log it next to a bug report, or render it in a
2145
+ * debug panel. Pull-only and allocation-cheap; nothing here is reactive, so poll
2146
+ * it or read it on demand.
2147
+ *
2148
+ * ```ts
2149
+ * const { shards, subscriptions } = client.debug();
2150
+ * // shards: [{ shardKey: "user-1", wsState: "open", confirmedMutationWatermark: 42, … }]
2151
+ * ```
2152
+ */
2153
+ debug(): ClientDebugSnapshot;
2154
+ /**
2155
+ * Subscribe to changes in {@link pendingCount}. Invokes `listener` immediately
2156
+ * with the current count, then whenever the queue depth changes (a write is
2157
+ * enqueued, flushed, or discarded). Returns an unsubscribe function.
2158
+ */
2159
+ onPendingChange(listener: (pending: number) => void): Unsubscribe;
2160
+ /**
2161
+ * Subscribe to terminal verdicts for offline-queued mutations. The listener
2162
+ * fires once per queued write that commits or is rejected — including a write
2163
+ * restored from durable storage after a reload, whose original `mutation()`
2164
+ * Promise no longer exists (`hadAwaiter: false`), and a write the queue
2165
+ * evicts on overflow or discards on an identity change. This is the durable
2166
+ * channel for surfacing a rolled-back optimistic write to the UI; an online
2167
+ * mutation that never queued still surfaces through the Promise `mutation()`
2168
+ * returns. The listener is NOT invoked on registration. Returns an
2169
+ * unsubscribe function. See {@link MutationSettledEvent}.
2170
+ */
2171
+ onMutationSettled(listener: (event: MutationSettledEvent) => void): Unsubscribe;
2172
+ /**
2173
+ * The `WebSocket` implementation this client was constructed with (an
2174
+ * explicit `options.WebSocket`, or the ambient global on platforms that have
2175
+ * one) — `undefined` if neither is available. This is the seam a feature
2176
+ * that opens its OWN socket outside the client's multiplexed connection
2177
+ * (e.g. a voice-agent hook) should default to, instead of reaching for
2178
+ * `globalThis.WebSocket` directly: on React Native the client wraps this
2179
+ * constructor to inject the auth-headers factory's credential onto the
2180
+ * upgrade request (`createLunoraClient`'s `withAuthWebSocket`), which a raw
2181
+ * `new globalThis.WebSocket(url)` would silently bypass.
2182
+ */
2183
+ getWebSocketImpl(): typeof WebSocket | undefined;
2184
+ /**
2185
+ * Read the current value for a {@link ClientQueryRef}. Returns
2186
+ * `ref.defaultValue` when no value has been explicitly set.
2187
+ */
2188
+ getClientQuery<T>(ref: ClientQueryRef<T>): T;
2189
+ /**
2190
+ * Set a new value for `ref` and notify every subscriber. Pass `undefined`
2191
+ * to reset the slot to `ref.defaultValue`.
2192
+ */
2193
+ setClientQuery<T>(ref: ClientQueryRef<T>, value: T): void;
2194
+ /**
2195
+ * Subscribe to changes for `ref`. The callback is NOT invoked on
2196
+ * registration — call {@link getClientQuery} for the current value.
2197
+ * Returns an unsubscribe function.
2198
+ */
2199
+ subscribeClientQuery(ref: ClientQueryRef, callback: (value: unknown) => void): Unsubscribe;
2200
+ /**
2201
+ * Reset a {@link ClientQueryRef} to its default value, notifying every
2202
+ * subscriber. Equivalent to `setClientQuery(ref, ref.defaultValue)` but
2203
+ * removes the stored entry so a future {@link getClientQuery} returns
2204
+ * the default rather than an explicitly-set value.
2205
+ */
2206
+ resetClientQuery(ref: ClientQueryRef): void;
2207
+ /**
2208
+ * Capture a snapshot of the current live query value at call time and
2209
+ * produce a `() => boolean` precondition that compares it against the
2210
+ * value at replay time (on queue drain / reconnect).
2211
+ *
2212
+ * Delegates to {@link createSnapshotPrecondition} with this client bound —
2213
+ * no need to pass `client` explicitly. The comparison semantics (including
2214
+ * how an absent subscription is treated) live there, in one place.
2215
+ * @example
2216
+ * ```ts
2217
+ * client.mutation(api.todos.update, { id, text }, {
2218
+ * precondition: client.snapshotPrecondition(api.todos.list, { userId }),
2219
+ * });
2220
+ * ```
2221
+ */
2222
+ snapshotPrecondition(functionRef: FunctionReference, args: Record<string, unknown>, shardKey?: string): () => boolean;
2223
+ /**
2224
+ * Resolves once the durable read cache has been loaded into memory. When
2225
+ * `hydrateOnStart` is not configured or no query cache adapter is active,
2226
+ * returns an already-resolved promise so callers can always await it
2227
+ * unconditionally.
2228
+ *
2229
+ * Framework adapters (React, Vue, etc.) use this to gate the first
2230
+ * (enabled) render of a live query behind hydration, so the user sees
2231
+ * cached data instead of an undefined flash before the socket round-trip.
2232
+ */
2233
+ whenReady(): Promise<void>;
2234
+ /**
2235
+ * Synchronously reports whether {@link whenReady} has already resolved (the
2236
+ * durable read cache is loaded, or none is configured). Framework adapters
2237
+ * read this to seed the hydration-gate state on the first render without
2238
+ * awaiting, then subscribe via {@link whenReady} for the pending case.
2239
+ */
2240
+ get isReady(): boolean;
2241
+ /**
2242
+ * Synchronously peek at a value the durable read cache loaded for the given
2243
+ * function path + args + shard key. Returns `undefined` when:
2244
+ *
2245
+ * - No query cache adapter is configured.
2246
+ * - Hydration hasn't completed yet (race — await {@link whenReady} first).
2247
+ * - The cached value's identity fingerprint doesn't match the current auth.
2248
+ *
2249
+ * Unlike the internal {@link takeHydratedCache}, this is a READ-ONLY peek:
2250
+ * the cached entry stays in `hydratedQueryCache` so the subscription created
2251
+ * later by {@link subscribe} consumes it normally.
2252
+ */
2253
+ peekHydratedQuery(functionPath: string, args: Record<string, unknown>, shardKey?: string): unknown;
2254
+ /**
2255
+ * Peek at the **current live value** of an active subscription, reporting
2256
+ * whether one exists at all rather than just its value. `present` is `false`
2257
+ * when no subscription is open for the given `(functionPath, args, shardKey)`;
2258
+ * `value` is the subscription's `lastValue`, which includes any optimistic
2259
+ * overlay.
2260
+ *
2261
+ * The two are separate because a caller like the snapshot precondition has to
2262
+ * tell "no subscription is active, so this read knows nothing" apart from
2263
+ * "the subscription is active and its value is `undefined`" — collapsing both
2264
+ * into a bare `undefined` return makes an unmounted component look like a
2265
+ * changed value, and drops the queued write.
2266
+ *
2267
+ * Unlike {@link peekHydratedQuery} (which reads from the durable read cache
2268
+ * and is independent of active subscriptions), this reflects the current
2269
+ * in-memory state of an already-opened subscription.
2270
+ */
2271
+ peekActiveQuerySnapshot(functionPath: string, args: Record<string, unknown>, shardKey?: string): {
2272
+ present: boolean;
2273
+ value: unknown;
2274
+ };
2275
+ query<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
2276
+ shardKey?: string;
2277
+ }): Promise<ReturnOf<F>>;
2278
+ /**
2279
+ * Batch several independent calls into ONE round trip (plan 088). Each call is
2280
+ * dispatched server-side exactly as an individual RPC — per-shard
2281
+ * authorization, `(identity, mutationId)` idempotency, and custom-mutator
2282
+ * watermark ordering are all preserved — and the worker splits the batch by
2283
+ * shard so calls to different shards fan out to their own DOs. Results are
2284
+ * demuxed back in input order; a failing call does NOT fail the batch (its
2285
+ * slot carries `{ ok: false, error }`, with `.code`/`.data` reconstructed like
2286
+ * a single call). Args/results ride the value codec (bytes/bigint survive).
2287
+ *
2288
+ * No promise pipelining and no capability passing — a call's args cannot
2289
+ * reference another call's result (see plan 088 §fence; capabilities are
2290
+ * incompatible with DO hibernation).
2291
+ */
2292
+ batch(calls: ReadonlyArray<{
2293
+ args?: Record<string, unknown>;
2294
+ fn: FunctionReference;
2295
+ shardKey?: string;
2296
+ }>): Promise<BatchSlot[]>;
2297
+ /**
2298
+ * Invoke a mutation. Errors propagate as rejections.
2299
+ *
2300
+ * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
2301
+ * only when the targeted shard's socket was open at least once already
2302
+ * (`wasEverConnected`), so the registry / resubscribe handshake has run.
2303
+ * Mutations issued before the very first WS connect to a shard fail fast.
2304
+ * Opt into queueing-before-first-connect via
2305
+ * `OfflineQueueOptions.queueBeforeFirstConnect`.
2306
+ *
2307
+ * **Return-value caveat — the queued paths do not carry the server's result.**
2308
+ * The declared `Promise<ReturnOf<F>>` only holds when the write goes straight
2309
+ * to the server. Once a write is queued:
2310
+ *
2311
+ * - with a durable `outbox` configured, this resolves **immediately with
2312
+ * `undefined`** (typed as `ReturnOf<F>`) the moment the write is handed to
2313
+ * the outbox — the replay happens later, out of band, with no awaiter;
2314
+ * - with the built-in offline queue, it stays pending until the replay lands
2315
+ * and then resolves with the replayed call's value.
2316
+ *
2317
+ * So `const id = await client.mutation(api.todos.create, …)` is `undefined`
2318
+ * for every write issued while offline under an outbox. Generate ids
2319
+ * client-side (or read them back from a subscription) rather than depending
2320
+ * on a mutation's return value in an offline-capable app —
2321
+ * {@link LunoraClient.importRows} documents the same caveat for its counts.
2322
+ */
2323
+ mutation<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>): Promise<ReturnOf<F>>;
2324
+ action<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: ActionCallOptions): Promise<ReturnOf<F>>;
2325
+ /**
2326
+ * Bulk-import `rows` through a mutation that accepts a batch, chunked so a large
2327
+ * dataset lands in a bounded number of round-trips.
2328
+ *
2329
+ * **Offline caveat:** each chunk is sent with {@link LunoraClient.mutation}, which
2330
+ * resolves once the write is durably queued rather than once the server has applied
2331
+ * it. So an import run while offline resolves `{ chunks, imported }` with nothing
2332
+ * committed yet — the counts describe what was *handed over*, and the outbox
2333
+ * replays them on reconnect. Don't report "migration complete" on this alone.
2334
+ *
2335
+ * This is the one-shot migration / seed path: "I have 20k rows client-side and a
2336
+ * server mutation that inserts many at once". Doing it by hand goes wrong in two
2337
+ * predictable ways — a serial per-row loop pays one round-trip *and* one watermark
2338
+ * wait per row (a 200-row import becomes 200 sequential hops), while a single
2339
+ * giant call blows the DO's batch limit. So: chunk, send sequentially, and give
2340
+ * each chunk a stable idempotency key derived from `importId` + its index, so a
2341
+ * resumed or retried import doesn't double-insert the chunks that already landed.
2342
+ *
2343
+ * The server mutation is yours (Lunora can't guess the table or the row shape);
2344
+ * back it with `ctx.db.insertMany(...)`, or `insertManyUnsafe(...)` for data you
2345
+ * vouch for. `chunkSize` defaults to 500, matching the DO's default batch cap.
2346
+ *
2347
+ * ```ts
2348
+ * await client.importRows(api.migrate.importNodes, nodes, {
2349
+ * importId: `migrate-${userId}`,
2350
+ * onProgress: ({ done, total }) => setProgress(done / total),
2351
+ * shardKey: userId,
2352
+ * toArgs: (chunk) => ({ nodes: chunk }),
2353
+ * });
2354
+ * ```
2355
+ */
2356
+ importRows(function_: FunctionReference, rows: ReadonlyArray<unknown>, options?: {
2357
+ /** Rows per call. Defaults to 500 — the DO's default batch cap. */
2358
+ chunkSize?: number;
2359
+ /**
2360
+ * Stable id for this import run. Each chunk is sent under
2361
+ * `${importId}:${chunkIndex}` as its mutation id, so re-running an import
2362
+ * that uses the SAME `chunkSize` re-sends each chunk under its prior key
2363
+ * and the server dedupes it instead of inserting twice.
2364
+ *
2365
+ * CAVEAT — the key is POSITIONAL, not content-based: it pins on the chunk
2366
+ * INDEX, not on the rows inside it. Resume or retry with a DIFFERENT
2367
+ * `chunkSize` (or a changed row ordering) and index N now covers different
2368
+ * rows than the first run's index N; the server sees a duplicate key and
2369
+ * SILENTLY DROPS those rows. Keep `chunkSize` (and the row order) identical
2370
+ * across resumes of the same `importId`. Omit `importId` only for a
2371
+ * throwaway import where double-insertion is acceptable.
2372
+ */
2373
+ importId?: string;
2374
+ /**
2375
+ * Called after each chunk is accepted — for a progress bar.
2376
+ *
2377
+ * "Accepted" is not always "committed": while offline (or mid-reconnect) a
2378
+ * `mutation` resolves as soon as the write is durably **queued**, so a fully
2379
+ * offline import reports completion with nothing yet applied server-side.
2380
+ * Gate a migration's "done" state on connectivity, not just on this.
2381
+ */
2382
+ onProgress?: (progress: {
2383
+ done: number;
2384
+ total: number;
2385
+ }) => void;
2386
+ /** Routes every chunk to one shard's DO. */
2387
+ shardKey?: string;
2388
+ /** Build the mutation args for one chunk. Defaults to `{ rows: chunk }`. */
2389
+ toArgs?: (chunk: ReadonlyArray<unknown>) => Record<string, unknown>;
2390
+ }): Promise<{
2391
+ chunks: number;
2392
+ imported: number;
2393
+ }>;
2394
+ /**
2395
+ * Read the cross-shard request distribution for a `.shardBy(...)` table —
2396
+ * the feed the studio's `hot_shard` advisor lint consumes. Hits the
2397
+ * admin-gated `POST /_lunora/admin/shard-traffic` endpoint, which fans the
2398
+ * cheap per-shard `getMetrics` read out across every live shard and returns
2399
+ * each shard's `{ shardKey, requests }` total (a failed shard surfaces with
2400
+ * `requests: 0`). Requires the worker to be built with a `queryCoordinator`
2401
+ * and `adminToken`, and this client's auth token to match; defaults any
2402
+ * absent field so an older worker yields an empty-but-valid shape.
2403
+ */
2404
+ shardTraffic(table: string): Promise<ShardTrafficResult>;
2405
+ /**
2406
+ * List the functions queued via `runAfter` / `runAt`, soonest-due last
2407
+ * (the worker returns them in storage order). Hits the admin-gated
2408
+ * `/_lunora/admin/scheduled` endpoint, so the worker must be built with a
2409
+ * `schedulerDO` namespace and `adminToken`, and this client's auth token
2410
+ * must match. Powers `@lunora/studio`'s scheduled-jobs panel.
2411
+ */
2412
+ listScheduledJobs(): Promise<ScheduleRecord[]>;
2413
+ /**
2414
+ * Read the app-level workpool backlog that powers `@lunora/studio`'s SLO
2415
+ * view: per-pool `{ name, queued, inFlight, maxConcurrency }` plus the
2416
+ * app-wide `backlog` (total queued) and `inFlight` (total held slots) sums.
2417
+ * Hits the admin-gated `GET /_lunora/admin/scheduled/status` endpoint, so the
2418
+ * same preconditions as {@link listScheduledJobs} apply (a `schedulerDO`
2419
+ * namespace + `adminToken` on the worker and a matching auth token here).
2420
+ * Defaults any absent field so an older worker still yields a valid shape.
2421
+ */
2422
+ schedulerStatus(): Promise<SchedulerStatus>;
2423
+ /** Cancel a pending scheduled job by id. Returns whether a job was removed. */
2424
+ cancelScheduledJob(id: string): Promise<{
2425
+ cancelled: boolean;
2426
+ }>;
2427
+ /**
2428
+ * List the dead-letter jobs: schedules that exhausted their retry budget
2429
+ * and were parked instead of dropped. These never appear in
2430
+ * {@link listScheduledJobs} (their live header is gone), so this is the only
2431
+ * way the studio surfaces a permanently-failed job. Hits the admin-gated
2432
+ * `GET /_lunora/admin/scheduled/dead`; same preconditions as
2433
+ * {@link listScheduledJobs}. Powers `@lunora/studio`'s dead-letter panel.
2434
+ */
2435
+ listDeadJobs(): Promise<ScheduleRecord[]>;
2436
+ /**
2437
+ * Resurrect a dead-letter job by id: it re-enters the schedule with a fresh
2438
+ * retry budget and fires on the next drain. Returns whether a parked record
2439
+ * matched. Hits the admin-gated `POST /_lunora/admin/scheduled/dead/retry`.
2440
+ */
2441
+ retryDeadJob(id: string): Promise<{
2442
+ retried: boolean;
2443
+ }>;
2444
+ /**
2445
+ * Permanently drop a dead-letter job by id (the operator has decided not to
2446
+ * recover it). Returns whether a parked record was removed. Hits the
2447
+ * admin-gated `POST /_lunora/admin/scheduled/dead/cancel`.
2448
+ */
2449
+ removeDeadJob(id: string): Promise<{
2450
+ removed: boolean;
2451
+ }>;
2452
+ /**
2453
+ * List a workflow's instances via the admin Workflows proxy
2454
+ * (`/_lunora/admin/workflows/instances`) — the Cloudflare control-plane data
2455
+ * the `Workflow` binding can't expose. Requires the worker to be built with a
2456
+ * `workflowsClient` (Cloudflare account id + API token). When one isn't
2457
+ * configured this does NOT reject: the proxy returns a `200 { configured:
2458
+ * false }` sentinel, so the result resolves with `configured === false` and an
2459
+ * empty `instances` list — callers should branch on that flag rather than
2460
+ * try/catch. (The instance-detail / status endpoints still reject with 501.)
2461
+ * `name` is the deployed workflow name.
2462
+ */
2463
+ listWorkflowInstances(options: {
2464
+ name: string;
2465
+ page?: number;
2466
+ perPage?: number;
2467
+ status?: WorkflowInstanceStatus;
2468
+ }): Promise<WorkflowInstancePage>;
2469
+ /** Read one workflow instance with its step timeline (`/_lunora/admin/workflows/instance`). */
2470
+ getWorkflowInstance(options: {
2471
+ id: string;
2472
+ name: string;
2473
+ }): Promise<WorkflowInstanceDetail>;
2474
+ /** Pause / resume / terminate a workflow instance (`/_lunora/admin/workflows/status`). Needs an Edit-scoped Cloudflare token. */
2475
+ setWorkflowInstanceStatus(options: {
2476
+ action: WorkflowInstanceAction;
2477
+ id: string;
2478
+ name: string;
2479
+ }): Promise<{
2480
+ status: WorkflowInstanceStatus;
2481
+ }>;
2482
+ /**
2483
+ * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
2484
+ * WebSocket. `onJobs` fires with the full list on connect and on every
2485
+ * change (schedule / cancel / alarm-fire). Reconnects with the client's
2486
+ * configured backoff. Requires `wsToken` to be set to an admin credential
2487
+ * (the browser can't send an `Authorization` header on a WS) — the master
2488
+ * token, or preferably a {@link WsTokenProvider} minting the ephemeral
2489
+ * sub-token so the master credential stays out of the URL. Returns an
2490
+ * unsubscribe function that closes the socket and stops reconnecting.
2491
+ */
2492
+ subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
2493
+ /**
2494
+ * List the registered public functions (queries / mutations / actions) with
2495
+ * their kinds. Hits the admin-gated `GET /_lunora/admin/functions` endpoint —
2496
+ * the worker must be built with a `functions` registry and `adminToken`, and
2497
+ * this client's auth token must match. Powers `@lunora/studio`'s function
2498
+ * runner auto-discovery.
2499
+ */
2500
+ listFunctions(): Promise<FunctionDescriptor[]>;
2501
+ /**
2502
+ * List the code-defined cron triggers (the `cronJobs()` map injected on the
2503
+ * worker), each flattened to its firing `cron` expression. Hits the
2504
+ * admin-gated `GET /_lunora/admin/cron-jobs` endpoint — the worker must be
2505
+ * built with a `cronJobs` map and `adminToken`, and this client's auth token
2506
+ * must match. These are static (Cloudflare exposes no runtime cron
2507
+ * introspection), so the studio renders them read-only alongside the dynamic
2508
+ * scheduler jobs.
2509
+ */
2510
+ getCronJobs(): Promise<CronJobInfo[]>;
2511
+ /**
2512
+ * Manually fire one code-defined cron job by name — the same dispatch the
2513
+ * scheduled trigger runs (dispatch the function, or start the durable
2514
+ * workflow), on demand. Hits the admin-gated `POST /_lunora/admin/cron-jobs/run`
2515
+ * endpoint; the worker must be built with a `cronJobs` map and `adminToken`,
2516
+ * and this client's auth token must match. Resolves when the job has run (a
2517
+ * function job's shard response is 2xx, or the workflow instance was created)
2518
+ * and rejects with the dispatch error otherwise.
2519
+ */
2520
+ runCronJob(name: string): Promise<{
2521
+ name: string;
2522
+ ran: boolean;
2523
+ }>;
2524
+ /**
2525
+ * Fetch the generated OpenAPI 3.1 document. Hits the admin-gated
2526
+ * `GET /_lunora/admin/openapi` endpoint — the worker must be built with an
2527
+ * `openApiSpec` and `adminToken`, and this client's auth token must match.
2528
+ * Powers `@lunora/studio`'s API-reference (Scalar) view. When the worker has
2529
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenAPI
2530
+ * document (no `paths`), so callers can render a "not configured" state.
2531
+ */
2532
+ fetchOpenApi(): Promise<Record<string, unknown>>;
2533
+ /**
2534
+ * Fetch the generated OpenRPC 1.x document. Hits the admin-gated
2535
+ * `GET /_lunora/admin/openrpc` endpoint — the worker must be built with an
2536
+ * `openRpcSpec` and `adminToken`, and this client's auth token must match.
2537
+ * OpenRPC is the RPC-native spec (a `methods` array over the JSON-RPC-shaped
2538
+ * `POST /_lunora/rpc` transport); it documents the RPC functions only.
2539
+ * Powers `@lunora/studio`'s OpenRPC API-reference view. When the worker has
2540
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenRPC
2541
+ * document (no `methods`), so callers can render a "not configured" state.
2542
+ */
2543
+ fetchOpenRpc(): Promise<Record<string, unknown>>;
2544
+ /**
2545
+ * List objects in the storage bucket, optionally under a `prefix` and from a
2546
+ * pagination `cursor`. Hits the admin-gated `GET /_lunora/admin/storage`
2547
+ * endpoint — the worker must be built with a `storageList` function and
2548
+ * `adminToken`, and this client's auth token must match. Powers
2549
+ * `@lunora/studio`'s file browser.
2550
+ */
2551
+ listStorageObjects(options?: {
2552
+ bucket?: string;
2553
+ cursor?: string;
2554
+ limit?: number;
2555
+ prefix?: string;
2556
+ }): Promise<StorageListPage>;
2557
+ /**
2558
+ * Delete one object from the storage bucket by key. Hits the admin-gated
2559
+ * `DELETE /_lunora/admin/storage?key=…` endpoint — the worker must be built
2560
+ * with a `storageDelete` function and `adminToken`. Powers the studio file
2561
+ * browser's per-row delete; resolves `{ deleted, key }`.
2562
+ *
2563
+ * An absent `deleted` field reads as `false`, matching every sibling admin
2564
+ * verb (`runCronJob`'s `ran`, …): the studio renders this value as the row's
2565
+ * outcome, so defaulting a missing field to success would report a delete
2566
+ * that a mismatched/older worker never performed.
2567
+ */
2568
+ deleteStorageObject(key: string, options?: {
2569
+ bucket?: string;
2570
+ }): Promise<{
2571
+ deleted: boolean;
2572
+ key: string;
2573
+ }>;
2574
+ /**
2575
+ * List the storage bucket names the worker exposes, for the studio file
2576
+ * browser's bucket picker. Hits the admin-gated
2577
+ * `GET /_lunora/admin/storage/buckets` endpoint — always resolves (an empty
2578
+ * array when the worker configures no `storageBuckets`, i.e. single-bucket).
2579
+ */
2580
+ listStorageBuckets(): Promise<string[]>;
2581
+ /**
2582
+ * Upload one object to the storage bucket. Hits the admin-gated
2583
+ * `PUT /_lunora/admin/storage?key=…` endpoint with the raw body and an
2584
+ * optional `contentType` header — the worker must be built with a
2585
+ * `storageUpload` function and `adminToken`. Powers the studio file
2586
+ * browser's upload control; resolves `{ etag?, key }`.
2587
+ */
2588
+ uploadStorageObject(options: {
2589
+ body: ArrayBuffer | Blob;
2590
+ bucket?: string;
2591
+ contentType?: string;
2592
+ key: string;
2593
+ }): Promise<{
2594
+ etag?: string;
2595
+ key: string;
2596
+ }>;
2597
+ /**
2598
+ * Build a (signed or public) URL for one object. Hits the admin-gated
2599
+ * `GET /_lunora/admin/storage/url?key=…` endpoint — the worker must be built
2600
+ * with a `storageSignedUrl` function and `adminToken`. Powers the studio
2601
+ * file browser's copy-URL action; resolves the URL string.
2602
+ *
2603
+ * `options.expiresInSeconds` requests a share-link lifetime, which is
2604
+ * validated/clamped server-side. The options object mirrors the worker's
2605
+ * `StorageSignedUrlFunction` options (a `password` / download-limit are noted
2606
+ * as future fields there).
2607
+ */
2608
+ signedStorageUrl(key: string, options?: {
2609
+ bucket?: string;
2610
+ expiresInSeconds?: number;
2611
+ }): Promise<string>;
2612
+ /**
2613
+ * List the `.global()` (D1-backed) tables with their row counts. Hits the
2614
+ * admin-gated `GET /_lunora/admin/global/tables` endpoint — the worker must
2615
+ * be built with a `globalIntrospector` and `adminToken`. Powers the data
2616
+ * browser's global mode.
2617
+ */
2618
+ listGlobalTables(): Promise<GlobalTableInfo[]>;
2619
+ /**
2620
+ * Read a page of rows from one `.global()` table. `filters` AND-narrows the
2621
+ * page to rows matching each `column = value` eq constraint — the drill-down a
2622
+ * facet-value click applies; the array is wire-encoded, JSON-encoded into the
2623
+ * `filters` query param, and the values are bound server-side.
2624
+ *
2625
+ * The response is `decodeWire`d. The worker encodes it (`readGlobalTablePage`
2626
+ * in `@lunora/d1`) because JSON cannot carry a `v.bigint()` column at all and
2627
+ * silently flattens a `v.bytes()` one to `{}` — so without the decode here the
2628
+ * grid renders the raw 3-element tagged array instead of the value. The shard
2629
+ * browser's twin already pairs the same way through `rpc`; this is the global
2630
+ * half of that symmetry.
2631
+ */
2632
+ readGlobalTablePage(options: {
2633
+ filters?: GlobalFilterClause[];
2634
+ limit?: number;
2635
+ offset?: number;
2636
+ table: string;
2637
+ }): Promise<GlobalTablePage>;
2638
+ /**
2639
+ * Summarise the distinct values of one column in a `.global()` table over the
2640
+ * active view (the same eq `filters` the browser is previewing) — the global
2641
+ * twin of the shard browser's facet. Hits the admin-gated
2642
+ * `GET /_lunora/admin/global/facet` endpoint; `column` is validated + bound
2643
+ * server-side. Powers the global data browser's facet sidebar.
2644
+ *
2645
+ * Wire-encoded/decoded on both legs for the same reason
2646
+ * {@link LunoraClient.readGlobalTablePage} is: a facet over a BLOB column
2647
+ * returns bytes, which `Response.json` flattens to `{}` — and since a facet
2648
+ * value is exactly what a click sends back as a `filters` clause, that is a
2649
+ * broken drill-down rather than a display glitch.
2650
+ */
2651
+ facetGlobalColumn(options: {
2652
+ column: string;
2653
+ filters?: GlobalFilterClause[];
2654
+ limit?: number;
2655
+ table: string;
2656
+ }): Promise<GlobalFacetResult>;
2657
+ /**
2658
+ * List the schema's Vectorize indexes with their declared shape (table,
2659
+ * field, dimensions, metric, metadata) and live stats (vector count,
2660
+ * processing watermark) when the binding is reachable. Hits the admin-gated
2661
+ * `GET /_lunora/admin/vector/indexes` endpoint — the worker must be built
2662
+ * with a `vectorIntrospector` and `adminToken`. Powers the studio's vector
2663
+ * browser. Vectorize can't enumerate indexes at runtime, so this list comes
2664
+ * from the generated `LUNORA_VECTOR_INDEXES` registry.
2665
+ */
2666
+ listVectorIndexes(): Promise<VectorIndexSummary[]>;
2667
+ /**
2668
+ * Run a nearest-neighbour similarity query against one vector index: the
2669
+ * worker embeds `text` via the index's embedder and returns the top matches.
2670
+ * Hits the admin-gated `POST /_lunora/admin/vector/query` endpoint. Throws
2671
+ * `VECTOR_QUERY_UNSUPPORTED` when the worker's introspector has no embedder
2672
+ * wired (the index lists read-only).
2673
+ */
2674
+ queryVectorIndex(options: {
2675
+ name: string;
2676
+ text: string;
2677
+ topK?: number;
2678
+ }): Promise<VectorQueryMatch[]>;
2679
+ /**
2680
+ * Read one keyset-paginated page of the durable `ctx.log` archive that
2681
+ * `pipelineLogSink` writes to R2. Server-side only — the worker holds the R2
2682
+ * SQL credentials and runs the reader; the browser only sees the decoded
2683
+ * `{ rows, nextCursor }`. Pass the previous page's `nextCursor` as
2684
+ * `query.cursor` to page. Admin-gated. When the operator hasn't wired the
2685
+ * archive, `adminFetch` throws a `LunoraClientError` with `.code ===
2686
+ * "LOG_ARCHIVE_NOT_CONFIGURED"`, so a caller can render a "not configured"
2687
+ * state rather than an error.
2688
+ */
2689
+ queryLogArchive(query?: PipelineLogQuery): Promise<PipelineLogPage>;
2690
+ /**
2691
+ * List the worker's registered Workers KV namespaces (binding names). Hits
2692
+ * the admin-gated `GET /_lunora/admin/kv/namespaces` endpoint — the worker
2693
+ * must be built with a `kvIntrospector` and `adminToken`. Powers the
2694
+ * studio's KV browser.
2695
+ */
2696
+ listKvNamespaces(): Promise<KvNamespaceSummary[]>;
2697
+ /**
2698
+ * List keys in a KV namespace, optionally filtered by `prefix` and
2699
+ * paginated via `cursor`. Hits the admin-gated
2700
+ * `GET /_lunora/admin/kv/keys` endpoint.
2701
+ */
2702
+ listKvKeys(options: {
2703
+ cursor?: string;
2704
+ limit?: number;
2705
+ namespace: string;
2706
+ prefix?: string;
2707
+ }): Promise<KvKeyListResult>;
2708
+ /**
2709
+ * Read a KV value (as text) and its metadata. Hits the admin-gated
2710
+ * `GET /_lunora/admin/kv/value` endpoint. Returns `{ value: null, metadata: null }`
2711
+ * when the key is absent.
2712
+ */
2713
+ getKvValue(options: {
2714
+ key: string;
2715
+ namespace: string;
2716
+ }): Promise<KvValueResult>;
2717
+ /**
2718
+ * Write a string value to a KV namespace. Accepts an absolute `expiration`
2719
+ * (Unix seconds) or a relative `expirationTtl`, plus optional `metadata` —
2720
+ * re-send the loaded values on edit so a save preserves rather than clears
2721
+ * them. Hits the admin-gated `PUT /_lunora/admin/kv/value` endpoint.
2722
+ */
2723
+ putKvValue(options: {
2724
+ expiration?: number;
2725
+ expirationTtl?: number;
2726
+ key: string;
2727
+ metadata?: unknown;
2728
+ namespace: string;
2729
+ value: string;
2730
+ }): Promise<void>;
2731
+ /**
2732
+ * Delete a key from a KV namespace. No-op when the key is absent. Hits the
2733
+ * admin-gated `DELETE /_lunora/admin/kv/value` endpoint.
2734
+ */
2735
+ deleteKvKey(options: {
2736
+ key: string;
2737
+ namespace: string;
2738
+ }): Promise<void>;
2739
+ /**
2740
+ * List authenticated users, paged and optionally searched / filtered / sorted.
2741
+ * Hits the admin-gated `GET /_lunora/admin/auth/users` endpoint — the worker
2742
+ * must be built with an `authAdmin` and `adminToken`. Powers the studio's
2743
+ * users dashboard.
2744
+ */
2745
+ listAuthUsers(options?: {
2746
+ filterField?: string;
2747
+ filterValue?: string;
2748
+ limit?: number;
2749
+ offset?: number;
2750
+ search?: string;
2751
+ searchField?: string;
2752
+ sortBy?: string;
2753
+ sortDirection?: "asc" | "desc";
2754
+ }): Promise<AuthPage<AuthUser>>;
2755
+ /**
2756
+ * Create a user. Hits the admin-gated `POST /_lunora/admin/auth/users/create`
2757
+ * endpoint (requires the worker's `authAdmin` to implement `createUser`).
2758
+ * `data` carries any app-defined `user.additionalFields`.
2759
+ */
2760
+ createAuthUser(input: {
2761
+ data?: Record<string, unknown>;
2762
+ email: string;
2763
+ name: string;
2764
+ password?: string;
2765
+ role?: string | string[];
2766
+ }): Promise<AuthUser>;
2767
+ /** Set a user's role (string, or array joined comma-wise server-side). */
2768
+ setAuthUserRole(input: {
2769
+ role: string | string[];
2770
+ userId: string;
2771
+ }): Promise<AuthUser>;
2772
+ /** Ban a user. `expiresInSeconds` sets a temporary ban; omit it for a permanent one. Revokes the user's live sessions. */
2773
+ banAuthUser(input: {
2774
+ expiresInSeconds?: number;
2775
+ reason?: string;
2776
+ userId: string;
2777
+ }): Promise<AuthUser>;
2778
+ /** Lift a user's ban. */
2779
+ unbanAuthUser(input: {
2780
+ userId: string;
2781
+ }): Promise<AuthUser>;
2782
+ /** Set a user's password (admin override — no current-password challenge). */
2783
+ setAuthUserPassword(input: {
2784
+ newPassword: string;
2785
+ userId: string;
2786
+ }): Promise<void>;
2787
+ /** Permanently delete a user and revoke their sessions. */
2788
+ removeAuthUser(input: {
2789
+ userId: string;
2790
+ }): Promise<void>;
2791
+ /**
2792
+ * Mint an impersonation session for a user, returning its bearer `token`.
2793
+ * The caller is responsible for using the token (e.g. setting the session
2794
+ * cookie); the server performs no cookie round-trip.
2795
+ */
2796
+ impersonateAuthUser(input: {
2797
+ userId: string;
2798
+ }): Promise<AuthImpersonation>;
2799
+ /** Revoke a single session by its id (force sign-out of one device). */
2800
+ revokeAuthSession(input: {
2801
+ sessionId: string;
2802
+ }): Promise<void>;
2803
+ /** Revoke every session for a user (force sign-out everywhere). */
2804
+ revokeAuthUserSessions(input: {
2805
+ userId: string;
2806
+ }): Promise<void>;
2807
+ /**
2808
+ * Report which auth dashboard surfaces are available — derived server-side
2809
+ * from the enabled better-auth plugins. The studio renders only the panels
2810
+ * whose capability is `true`.
2811
+ */
2812
+ getAuthCapabilities(): Promise<AuthCapabilities>;
2813
+ /** Update a user's fields (name/email/app-defined `additionalFields`). */
2814
+ updateAuthUser(input: {
2815
+ data: Record<string, unknown>;
2816
+ userId: string;
2817
+ }): Promise<AuthUser>;
2818
+ /** List a user's linked accounts (credential / OAuth providers). Token material is stripped server-side. */
2819
+ listAuthAccounts(input: {
2820
+ userId: string;
2821
+ }): Promise<Record<string, unknown>[]>;
2822
+ /** Unlink a linked account from a user. */
2823
+ unlinkAuthAccount(input: {
2824
+ accountId: string;
2825
+ userId: string;
2826
+ }): Promise<void>;
2827
+ /** List a user's registered passkeys (requires the passkey plugin). */
2828
+ listAuthPasskeys(input: {
2829
+ userId: string;
2830
+ }): Promise<Record<string, unknown>[]>;
2831
+ /** Delete a passkey by id (requires the passkey plugin). */
2832
+ deleteAuthPasskey(input: {
2833
+ passkeyId: string;
2834
+ }): Promise<void>;
2835
+ /** Disable two-factor auth for a user (requires the two-factor plugin). */
2836
+ disableAuthTwoFactor(input: {
2837
+ userId: string;
2838
+ }): Promise<void>;
2839
+ /** List organizations, paged (requires the organization plugin). */
2840
+ listAuthOrganizations(options?: {
2841
+ limit?: number;
2842
+ offset?: number;
2843
+ }): Promise<AuthPage<Record<string, unknown>>>;
2844
+ /** List the members of an organization (requires the organization plugin). */
2845
+ listAuthOrgMembers(input: {
2846
+ limit?: number;
2847
+ offset?: number;
2848
+ organizationId: string;
2849
+ }): Promise<AuthPage<Record<string, unknown>>>;
2850
+ /** List an organization's pending invitations (requires the organization plugin). */
2851
+ listAuthOrgInvitations(input: {
2852
+ limit?: number;
2853
+ offset?: number;
2854
+ organizationId: string;
2855
+ }): Promise<AuthPage<Record<string, unknown>>>;
2856
+ /**
2857
+ * List sign-up invitations, newest first (requires the `inviteOnly` plugin).
2858
+ * Unfiltered: a row is pending when `acceptedAt` is null and `expiresAt` is in
2859
+ * the future, and the caller labels it — filtering server-side after the page
2860
+ * would let page 1 come back empty while pending rows sat on page 2.
2861
+ */
2862
+ listAuthSignUpInvitations(options?: {
2863
+ limit?: number;
2864
+ offset?: number;
2865
+ }): Promise<AuthPage<Record<string, unknown>>>;
2866
+ /** Invite an address to sign up, or refresh an existing invitation for it. */
2867
+ createAuthSignUpInvitation(input: {
2868
+ email: string;
2869
+ expiresInSeconds?: number;
2870
+ invitedBy?: string;
2871
+ }): Promise<Record<string, unknown>>;
2872
+ /** Withdraw a sign-up invitation. Not retroactive — an account already created keeps existing. */
2873
+ revokeAuthSignUpInvitation(input: {
2874
+ email: string;
2875
+ }): Promise<void>;
2876
+ /** Remove a member from an organization. */
2877
+ removeAuthOrgMember(input: {
2878
+ memberId: string;
2879
+ }): Promise<void>;
2880
+ /** Cancel a pending organization invitation. */
2881
+ cancelAuthOrgInvitation(input: {
2882
+ invitationId: string;
2883
+ }): Promise<void>;
2884
+ /**
2885
+ * Report the deployment's auth configuration — enabled plugins, sign-in
2886
+ * methods, user-settable create-user fields, organization sub-features
2887
+ * (teams / roles), and session / rate-limit policy. Drives the config panel
2888
+ * and the dynamic create-user form. Never carries a secret.
2889
+ */
2890
+ getAuthConfig(): Promise<AuthConfigInfo>;
2891
+ /** Create an organization; optionally seed an `owner` member for `ownerId`. */
2892
+ createAuthOrganization(input: {
2893
+ logo?: string;
2894
+ metadata?: Record<string, unknown>;
2895
+ name: string;
2896
+ ownerId?: string;
2897
+ slug?: string;
2898
+ }): Promise<Record<string, unknown>>;
2899
+ /** Update an organization's name/slug/logo/metadata. */
2900
+ updateAuthOrganization(input: {
2901
+ logo?: string;
2902
+ metadata?: Record<string, unknown>;
2903
+ name?: string;
2904
+ organizationId: string;
2905
+ slug?: string;
2906
+ }): Promise<Record<string, unknown>>;
2907
+ /** Delete an organization and cascade its members, invitations, teams, and custom roles. */
2908
+ deleteAuthOrganization(input: {
2909
+ organizationId: string;
2910
+ }): Promise<void>;
2911
+ /** Directly add an existing user to an organization (no invitation/acceptance). */
2912
+ addAuthOrgMember(input: {
2913
+ organizationId: string;
2914
+ role?: string;
2915
+ userId: string;
2916
+ }): Promise<Record<string, unknown>>;
2917
+ /** Create a pending email invitation to an organization. */
2918
+ inviteAuthOrgMember(input: {
2919
+ email: string;
2920
+ inviterId?: string;
2921
+ organizationId: string;
2922
+ role?: string;
2923
+ }): Promise<Record<string, unknown>>;
2924
+ /** Change a member's role. */
2925
+ setAuthOrgMemberRole(input: {
2926
+ memberId: string;
2927
+ role: string | string[];
2928
+ }): Promise<Record<string, unknown>>;
2929
+ /** List an organization's teams (requires the organization plugin with teams enabled). */
2930
+ listAuthOrgTeams(input: {
2931
+ limit?: number;
2932
+ offset?: number;
2933
+ organizationId: string;
2934
+ }): Promise<AuthPage<Record<string, unknown>>>;
2935
+ /** Create a team under an organization. */
2936
+ createAuthOrgTeam(input: {
2937
+ name: string;
2938
+ organizationId: string;
2939
+ }): Promise<Record<string, unknown>>;
2940
+ /** Rename a team. */
2941
+ updateAuthOrgTeam(input: {
2942
+ name: string;
2943
+ teamId: string;
2944
+ }): Promise<Record<string, unknown>>;
2945
+ /** Delete a team and its memberships. */
2946
+ removeAuthOrgTeam(input: {
2947
+ teamId: string;
2948
+ }): Promise<void>;
2949
+ /** List a team's members. */
2950
+ listAuthOrgTeamMembers(input: {
2951
+ limit?: number;
2952
+ offset?: number;
2953
+ teamId: string;
2954
+ }): Promise<AuthPage<Record<string, unknown>>>;
2955
+ /** Add a user to a team. */
2956
+ addAuthOrgTeamMember(input: {
2957
+ teamId: string;
2958
+ userId: string;
2959
+ }): Promise<Record<string, unknown>>;
2960
+ /** Remove a member from a team. */
2961
+ removeAuthOrgTeamMember(input: {
2962
+ teamMemberId: string;
2963
+ }): Promise<void>;
2964
+ /** List an organization's custom roles (requires the organization plugin with dynamic access control). */
2965
+ listAuthOrgRoles(input: {
2966
+ limit?: number;
2967
+ offset?: number;
2968
+ organizationId: string;
2969
+ }): Promise<AuthPage<Record<string, unknown>>>;
2970
+ /** Create a custom org role with a permission grant (a `resource -> actions[]` map). */
2971
+ createAuthOrgRole(input: {
2972
+ organizationId: string;
2973
+ permission: Record<string, string[]>;
2974
+ role: string;
2975
+ }): Promise<Record<string, unknown>>;
2976
+ /** Replace a custom org role's permission grant. */
2977
+ updateAuthOrgRole(input: {
2978
+ permission: Record<string, string[]>;
2979
+ roleId: string;
2980
+ }): Promise<Record<string, unknown>>;
2981
+ /** Delete a custom org role. */
2982
+ deleteAuthOrgRole(input: {
2983
+ roleId: string;
2984
+ }): Promise<void>;
2985
+ /** List auth sessions, paged and optionally filtered to one user. */
2986
+ listAuthSessions(options?: {
2987
+ limit?: number;
2988
+ offset?: number;
2989
+ userId?: string;
2990
+ }): Promise<AuthPage<AuthSession>>;
2991
+ /**
2992
+ * Subscribe to a live query. The callback fires with the current value (from
2993
+ * the durable read cache, when one is hydrated) and again on every server
2994
+ * frame; the returned function unsubscribes.
2995
+ *
2996
+ * Subscriptions are deduped by `(functionPath, args, shardKey)` — a second
2997
+ * `subscribe` for the same triple joins the existing registration and shares
2998
+ * its value, cursor and optimistic layers.
2999
+ *
3000
+ * Available on a `crossTabSync` FOLLOWER tab, unlike the other socket-backed
3001
+ * surfaces: registering here is exactly what lets the cross-tab relay deliver
3002
+ * the leader's broadcasts (see the note in the body). The caveat is that the
3003
+ * channel only carries the LEADER's own subscriptions outward, so a follower
3004
+ * sees this query's frames only while the leader holds it too — see
3005
+ * {@link LunoraClientOptions.crossTabSync}.
3006
+ */
3007
+ subscribe<F extends FunctionReference>(function_: F, args: ArgsOf<F>, callback: (data: ReturnOf<F>) => void, options?: {
3008
+ onCheckpoint?: (watermark: SyncWatermark) => void;
3009
+ onError?: SubscriptionErrorCallback;
3010
+ shardKey?: string;
3011
+ }): Unsubscribe;
3012
+ /**
3013
+ * Subscribe to a declarative **shape** — server-side partial replication
3014
+ * scoped by `shardBy` + the shape's predicate + RLS. The parallel to
3015
+ * {@link subscribe} for the poke protocol: the client sends the shape *name* +
3016
+ * validated `args` (never a `where` the client could forge), the server seeds
3017
+ * the current membership as an insert-poke and streams live membership diffs.
3018
+ * Each applied poke materializes the shape's rowset and invokes `callback`.
3019
+ *
3020
+ * Unlike {@link subscribe}, shape subscriptions are NOT deduped by
3021
+ * (name, args): the server resolves them under the socket's verified identity,
3022
+ * so every call gets its own id + view. The returned function unsubscribes.
3023
+ *
3024
+ * Not available on a `crossTabSync` FOLLOWER tab: shape pokes are not part of
3025
+ * the leader→follower broadcast set, so a follower's shape could never
3026
+ * resolve. The returned handle is inert there, and `options.onError` is
3027
+ * invoked with `NOT_IMPLEMENTED` — see
3028
+ * {@link LunoraClientOptions.crossTabSync}. Reporting rather than throwing is
3029
+ * deliberate: `@lunora/db`'s shape-backed `createCollection` calls this from
3030
+ * its sync path, where a throw takes the collection out entirely, while
3031
+ * `onError` is the seam it already routes to `markReady()`.
3032
+ */
3033
+ subscribeShape(shape: {
3034
+ args?: Record<string, unknown>;
3035
+ name: string;
3036
+ }, callback: ShapeCallback, options?: {
3037
+ onCheckpoint?: (watermark: SyncWatermark) => void;
3038
+ onError?: SubscriptionErrorCallback;
3039
+ shardKey?: string;
3040
+ }): Unsubscribe;
3041
+ /**
3042
+ * Open a streaming query. The function reference must be a
3043
+ * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
3044
+ * the type constraint catches accidental use of a query/mutation/action
3045
+ * reference at compile time. The returned iterable yields one element per
3046
+ * chunk frame the server pushes, terminating when the server sends
3047
+ * `complete` or the consumer calls `.cancel()`. Errors arrive as a
3048
+ * rejection on the next `next()`.
3049
+ *
3050
+ * Streams ride the same WS as subscriptions and share the unsubscribe
3051
+ * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id,
3052
+ * which the DO recognises as an abort signal for the in-flight iterator.
3053
+ *
3054
+ * Stream-start frames buffered while the socket is (re)connecting are
3055
+ * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
3056
+ * cap drops the oldest queued frame (and fails its consumer) so a stuck
3057
+ * reconnect can't OOM the page.
3058
+ */
3059
+ stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F>, options?: {
3060
+ durable?: boolean;
3061
+ maxBuffer?: number;
3062
+ shardKey?: string;
3063
+ }): StreamIterable<ReturnOf<F>>;
3064
+ /**
3065
+ * Open a typed **HTTP-SSE route stream** (`httpRoute.<verb>(path).stream()`).
3066
+ * Distinct from {@link LunoraClient.stream}, which consumes the WS procedure
3067
+ * stream (`kind: "stream"`): this one opens the route's own URL with `fetch`
3068
+ * and parses the Server-Sent Events framing the route pump writes (`data:`
3069
+ * chunks, a final `event: complete`, an `event: error` on throw).
3070
+ *
3071
+ * The reference comes from the generated `httpStreams.*` registry, so the
3072
+ * yielded chunk type is the route handler's yielded type. Cancelling the
3073
+ * returned iterable (or aborting `options.signal`) aborts the fetch, which
3074
+ * the server handler observes via its `signal`. The client's bearer token
3075
+ * (when set) rides as an `authorization` header.
3076
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
3077
+ */
3078
+ httpStream<Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: {
3079
+ headers?: Record<string, string>;
3080
+ maxBuffer?: number;
3081
+ signal?: AbortSignal;
3082
+ }): StreamIterable<HttpStreamChunkOf<Ref>>;
3083
+ close(): void;
3084
+ /** Guard shared by every public entry point: a closed client accepts no further calls. */
3085
+ private assertOpen;
3086
+ /**
3087
+ * `true` when this tab is a cross-tab FOLLOWER of a live leader — i.e. it
3088
+ * will not open a socket of its own and another tab is known to hold one.
3089
+ *
3090
+ * Deliberately NOT just `!isLeader()`. Every `crossTabSync` client is a
3091
+ * non-leader for the first `leaderTimeout` of its life, while its
3092
+ * claim-leadership probe is outstanding; a lone tab self-promotes at the end
3093
+ * of that window and `onBecomeLeader` opens the sockets and replays every
3094
+ * registered subscription. That window is a legitimate, self-healing defer,
3095
+ * not a failure. A KNOWN leader on another tab is the state that never heals.
3096
+ */
3097
+ private followsAnotherTab;
3098
+ /**
3099
+ * Reject a call that needs a socket this tab will never have.
3100
+ *
3101
+ * The cross-tab protocol is one-directional: a leader broadcasts
3102
+ * `subscription-data` / `-error` / `-settled` / `connection-status` to
3103
+ * followers, and a follower has no frame with which to tell the leader what
3104
+ * it needs (see `cross-tab.ts`'s `WsFollowerMessage`, which is exactly
3105
+ * heartbeat / claim-leadership / yield-leadership). `subscribeShape` /
3106
+ * `whisper*` / `setConnectionContext` / `acquireConnectionContext` — none of
3107
+ * which the leader broadcasts at all — therefore never worked on a follower
3108
+ * under any circumstances: each returned a handle that looked live, fired no
3109
+ * callback, raised no error, and reported `connectionStatus() ===
3110
+ * "connected"` (mirrored from the leader).
3111
+ *
3112
+ * `subscribe` is deliberately NOT in that set. A follower's `subscribe`
3113
+ * registers the key the leader's broadcast is matched against, so it is the
3114
+ * mechanism the relay is built on rather than a surface that silently fails.
3115
+ * A follower sees a query only while the leader holds the same
3116
+ * `(fn, args, shardKey)` — that is the documented shape of the option, not a
3117
+ * defect.
3118
+ *
3119
+ * `subscribeShape` and `stream()` reach the same outcome by a different
3120
+ * route: they fail the handle they return rather than throwing at the call,
3121
+ * because both are driven from a sync/render path where a throw destroys the
3122
+ * caller instead of degrading it. See
3123
+ * {@link LunoraClientOptions.crossTabSync} for what the option does and does
3124
+ * not cover.
3125
+ */
3126
+ private assertLeaderOwnedSurface;
3127
+ /**
3128
+ * Clear every timer a {@link ShardConnection} can have armed.
3129
+ *
3130
+ * One function because both teardown paths must clear all three and a fourth
3131
+ * timer would otherwise have to be remembered in two places — which is how a
3132
+ * leak gets added rather than written.
3133
+ */
3134
+ private clearConnectionTimers;
3135
+ /**
3136
+ * Tear down one {@link ShardConnection}'s live state: clear its reconnect/
3137
+ * connect timers, stop its heartbeat, and close its socket (if any).
3138
+ * Shared by `close()` (terminal) and the cross-tab `onStopBeingLeader`
3139
+ * handler (demoted, but still alive) so a demoted leader can't leak a
3140
+ * pending `reconnectTimer` or an open socket's `heartbeatTimer` the way
3141
+ * an inline `conn.socket?.close()` — which skips both — used to.
3142
+ *
3143
+ * Settles this shard's in-flight streams first. The teardown clears
3144
+ * `conn.socket` BEFORE the real `close` event fires, so that event trips
3145
+ * `openManagedSocket`'s identity guard (`conn.socket !== socket`) and
3146
+ * returns — meaning `handleDisconnect`, the only other place that settles a
3147
+ * shard's streams, never runs for this connection again. `close()` already
3148
+ * failed and cleared `this.streams` before it gets here, so this is a no-op
3149
+ * on that path; the cross-tab demotion path is the one where a consumer's
3150
+ * `for await` used to block forever with no error and no completion.
3151
+ */
3152
+ private teardownConnection;
3153
+ /**
3154
+ * Build (but do not start) this client's `TabCoordinator`. Extracted out of
3155
+ * the constructor so `setAuthToken` can rebuild it on an identity change —
3156
+ * the default channel name embeds the identity fingerprint (see below), so
3157
+ * a new identity needs a new coordinator on a new channel. The callback
3158
+ * bodies are the drift-sensitive region (a hand-merged identity guard on
3159
+ * the shard message listener sits ahead of an extracted `lastFrameAt`
3160
+ * stamp elsewhere in this file) — moved verbatim, not reflowed.
3161
+ */
3162
+ private createTabCoordinator;
3163
+ /**
3164
+ * Persist a mutation that can't go out on the wire right now (offline, or
3165
+ * mid-reconnect after a prior connect). The optimistic update has already
3166
+ * been applied by `mutation`; this only chooses the durable write path and
3167
+ * rolls the optimistic write back if persistence is rejected.
3168
+ *
3169
+ * Two paths: when an `outbox` sink is wired (the `@lunora/db` executor) it
3170
+ * owns persistence + at-least-once replay, so we delegate and return
3171
+ * optimistically (confirmation rides the synced view). Otherwise the
3172
+ * built-in `OfflineQueue` resolves/rejects the returned promise on replay.
3173
+ */
3174
+ private enqueueOfflineMutation;
3175
+ /**
3176
+ * Restore offline mutations persisted in a prior session and open a socket
3177
+ * for each shard they target so they flush once the WS reconnects. Failures
3178
+ * are swallowed — a broken durable store must not stop the client booting.
3179
+ */
3180
+ private hydratePersistedQueue;
3181
+ /**
3182
+ * Re-queue the durable offline writes — but only as the multi-tab LEADER. The
3183
+ * persisted queue is shared across a profile's tabs; without coordination
3184
+ * every tab would re-queue and replay the same writes (correct only because
3185
+ * the server dedups by idempotency key, but wasteful + racy). A Web Lock makes
3186
+ * exactly one tab hydrate; it holds the lock for its lifetime, so when it
3187
+ * closes another tab acquires the lock and takes over. Falls back to
3188
+ * unconditional hydration where Web Locks are unavailable (React Native, older
3189
+ * browsers, SSR) — single-context there, so no coordination is needed.
3190
+ */
3191
+ private hydrateAsOutboxLeader;
3192
+ /**
3193
+ * Load every cached query so a `subscribe()` for the key seeds its initial
3194
+ * value off disk.
3195
+ *
3196
+ * The load is asynchronous but every framework adapter subscribes
3197
+ * SYNCHRONOUSLY at mount, so the subscriptions that most want the cache
3198
+ * already exist by the time it lands. Those are seeded here and their entry
3199
+ * is dropped: an entry that stayed in {@link hydratedQueryCache} behind a
3200
+ * live subscription would be consumed by the NEXT subscribe of the same key
3201
+ * (a remount after navigating away) and replay the previous session's value
3202
+ * over whatever the socket had since delivered. A cache entry therefore
3203
+ * never outlives a live subscription for its key — it is either handed to
3204
+ * that subscription or discarded.
3205
+ *
3206
+ * Only keys with no live subscription are held for a later `subscribe()`;
3207
+ * the identity gate applies to both paths, so a signed-out cache never leaks
3208
+ * into a new session.
3209
+ */
3210
+ private hydrateQueryCache;
3211
+ /**
3212
+ * Hand a loaded read-cache entry to a subscription that was opened before
3213
+ * the load resolved — the same value, cursor and epoch {@link subscribe}
3214
+ * would have taken from {@link takeHydratedCache} had the load finished
3215
+ * first, so the cursor still rides the `subscribe` frame as `sinceSeq` (that
3216
+ * frame only goes out once the socket opens, well after this microtask).
3217
+ *
3218
+ * A no-op once the socket has delivered anything for this key: a live value
3219
+ * always beats the cache. Identity-gated exactly like `takeHydratedCache`.
3220
+ */
3221
+ private seedSubscriptionFromCache;
3222
+ /**
3223
+ * Move the durable read cache in or out of view as the CREDENTIAL changes —
3224
+ * which the identity fingerprint does not track: a sticky subject rides
3225
+ * across a token change (the account-switch shape), leaving the label
3226
+ * unmoved, so `setAuthToken`'s identity-change block never runs for it.
3227
+ * Revoke while that pairing is unchecked, and hand the values back once the
3228
+ * next session resolve confirms the credential really is that subject's.
3229
+ */
3230
+ private syncReadCacheToCredential;
3231
+ /**
3232
+ * A server frame owns this key now, so the read cache may neither take its
3233
+ * seeded value back ({@link revokeCacheSeededValues}) nor hold an entry for
3234
+ * a later `subscribe()` of the same key to replay a stale session over.
3235
+ */
3236
+ private dropCacheSeed;
3237
+ /**
3238
+ * Hand a cache-seeded entry back to {@link hydratedQueryCache} when its last
3239
+ * subscriber detaches, so the NEXT `subscribe()` of the same key can seed
3240
+ * from it again.
3241
+ *
3242
+ * Without this the hydrated cache was one-shot per key: {@link takeHydratedCache}
3243
+ * consumes the entry, the final unsubscribe drops the state that held its
3244
+ * value, and nothing re-seeds. Navigating away from a route and back while
3245
+ * offline therefore rendered `undefined` for the rest of the offline
3246
+ * session even though the durable store still held the rows. React hid it
3247
+ * behind TanStack's `gcTime`; every other adapter showed it immediately.
3248
+ *
3249
+ * Only a seed still listed in {@link cacheSeededQueries} moves — a server
3250
+ * frame calls {@link dropCacheSeed}, which clears both maps, so an entry
3251
+ * that is still here has not been superseded and is the freshest value this
3252
+ * client has for the key. That is the same map-to-map move
3253
+ * {@link revokeCacheSeededValues} makes, and it keeps the two maps disjoint:
3254
+ * an entry is either on display or waiting, never both.
3255
+ */
3256
+ private returnCacheSeed;
3257
+ /**
3258
+ * Take every value the durable read cache is currently displaying back off
3259
+ * screen, and return its entry to {@link hydratedQueryCache} so the identity
3260
+ * gate — not this call — decides whether it is ever shown again. A
3261
+ * same-credential refresh gets its offline-first value back the moment the
3262
+ * next session resolve re-confirms the subject; a genuine account switch
3263
+ * never does, and {@link clearQueryCacheForIdentityChange} wipes it.
3264
+ *
3265
+ * Only cache-seeded values: a server frame has been delivered under a socket
3266
+ * whose own identity is pinned and checked ({@link persistQueryValue}), and
3267
+ * dropping those would blank a live query on every token refresh.
3268
+ */
3269
+ private revokeCacheSeededValues;
3270
+ /**
3271
+ * Consume the hydrated read-cache entry for a key (if any), gated on
3272
+ * identity ({@link cachedQueryMatchesIdentity}). A mismatch yields
3273
+ * `undefined`, so a cache written under a different identity never leaks
3274
+ * into a new session.
3275
+ *
3276
+ * Only a MATCH is removed. The cache seeds a subscription's first value
3277
+ * once, so consuming a match is right — but destroying a mismatch is what
3278
+ * made a late-resolving identity unrecoverable: the subject typically lands
3279
+ * a `/get-session` after the first `subscribe()`, and by then the entry that
3280
+ * would have matched was gone. Left in place, {@link reseedFromHydratedCache}
3281
+ * can still hand it over when the identity settles.
3282
+ */
3283
+ private takeHydratedCache;
3284
+ /**
3285
+ * Hand every still-held read-cache entry to the subscription that is open on
3286
+ * its key, now that the identity has settled onto a resolved subject.
3287
+ *
3288
+ * `subscribe()` runs long before `/get-session` answers, so on a reload the
3289
+ * gate is asked its question with only a raw token in hand. When the token
3290
+ * itself matches, {@link cachedQueryMatchesIdentity} already says yes there
3291
+ * and then; when it has been refreshed since the value was cached, the only
3292
+ * honest answer at that moment is "unknown" — and this is where it becomes
3293
+ * knowable. {@link seedSubscriptionFromCache} is a no-op for any subscription
3294
+ * the socket has already fed, so a live value always wins.
3295
+ */
3296
+ private reseedFromHydratedCache;
3297
+ /**
3298
+ * Queue a coalesced read-cache write for a subscription's current value.
3299
+ * Latest-wins per key; flushed on a short debounce so a delta burst writes
3300
+ * once. No-op when the read cache is disabled or the value is undefined
3301
+ * (nothing to render offline).
3302
+ */
3303
+ private persistQueryValue;
3304
+ /** Drain {@link pendingCacheWrites} to the durable store. */
3305
+ private flushQueryCacheWrites;
3306
+ /** Derive the aggregate status from the per-shard socket states. */
3307
+ private computeStatus;
3308
+ /** Recompute the aggregate status and notify listeners if it changed. */
3309
+ private emitConnectionStatus;
3310
+ /**
3311
+ * Build a {@link MutationSettledEvent} from a queued entry and emit it on the
3312
+ * {@link onMutationSettled} channel. `item.id` is always assigned by the time
3313
+ * a write settles (`enqueue`/`hydrate` guarantee it), so the `?? ""` fallback
3314
+ * is unreachable — present only to satisfy the optional queue-id type.
3315
+ */
3316
+ private emitItemSettled;
3317
+ /**
3318
+ * Apply an optimistic update to the subscription that matches the mutation's
3319
+ * `(functionRef, args, shardKey)` triple, returning the rollback callbacks to
3320
+ * invoke if the mutation later fails.
3321
+ *
3322
+ * The registry is already indexed by exactly this triple via
3323
+ * `SubscriptionRegistry.key`, so at most one subscription can match. A direct
3324
+ * O(1) keyed lookup replaces the former O(N) linear scan over all subscriptions.
3325
+ *
3326
+ * `shardKey` normalization: both `undefined` and `""` map to the empty string
3327
+ * inside `SubscriptionRegistry.key` (via `?? ""`), so a mutation fired without
3328
+ * a shardKey correctly matches a subscription registered without one regardless
3329
+ * of whether the caller passed `undefined` or omitted the field.
3330
+ */
3331
+ private applyOptimisticUpdates;
3332
+ /**
3333
+ * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
3334
+ * to the live subscription registry. Each `setQuery` registers a constant
3335
+ * optimistic LAYER on its target subscription (via the same engine the
3336
+ * per-call `optimistic` path uses), so the multi-query patch rebases onto
3337
+ * incoming deltas and drops gaplessly on its commit cursor — its `confirm` /
3338
+ * `rollback` closures are appended to the mutation's settle lists. A throwing
3339
+ * callback unwinds its own partial writes — LIFO over just the rollbacks it
3340
+ * produced — and is swallowed, so a buggy optimistic update can never fail the
3341
+ * mutation or leave a partial patch live.
3342
+ */
3343
+ private applyOptimisticUpdate;
3344
+ private getConnection;
3345
+ /**
3346
+ * Send an unsubscribe frame (tagged with its wire type) on the shard's
3347
+ * socket, or queue it for the next reconnect when the send can't go out.
3348
+ */
3349
+ private sendOrQueueUnsubscribe;
3350
+ /**
3351
+ * The `(wsState, hasSocket, wasEverConnected)` triple `mutation()`'s
3352
+ * offline-queue gate reads. On the leader/single-tab path this is exactly
3353
+ * the real `ShardConnection`'s state (byte-identical to the pre-cross-tab
3354
+ * behavior). A follower has no `ShardConnection` of its own (see
3355
+ * `ensureSocket`), so it derives the same triple from the mirrored
3356
+ * `leaderStatus`/`leaderWasEverConnected` instead: `"connected"` maps to
3357
+ * `"open"` (queue-eligible once `wasEverConnected`), `"connecting"` stays
3358
+ * `"connecting"` (the mid-reconnect queue branch), anything else is
3359
+ * `"idle"`. `hasSocket` is always `false` for a follower — it never has
3360
+ * one.
3361
+ */
3362
+ private connectionGateState;
3363
+ private getOrCreateConnection;
3364
+ private wsUrlFor;
3365
+ /**
3366
+ * Build the outbound RPC headers: JSON content type, optional bearer auth,
3367
+ * the optional mutation-replay idempotency key, and the D1 read-your-writes
3368
+ * bookmark when the caller opted into `attachBookmark`. The mutation id
3369
+ * rides both the direct send and any offline-queue replay of the same write,
3370
+ * so a mutation the server already committed returns its cached result
3371
+ * instead of running twice.
3372
+ */
3373
+ private rpcRequestHeaders;
3374
+ private rpc;
3375
+ /**
3376
+ * Authenticated request to a non-RPC admin endpoint (the scheduler list /
3377
+ * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
3378
+ * worker's `{ error: { code, message } }` envelope as a coded `Error` —
3379
+ * mirroring {@link rpc} so callers see the same failure shape.
3380
+ */
3381
+ private adminFetch;
3382
+ /**
3383
+ * Resolve the effective connection context for a shard: the most-recently
3384
+ * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
3385
+ * back to the imperative {@link setConnectionContext} override, then the
3386
+ * client-wide default. Returns `undefined` when none apply.
3387
+ */
3388
+ private effectiveConnectionContext;
3389
+ /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
3390
+ private refreshConnectionContext;
3391
+ /**
3392
+ * Send the one-shot `connect` envelope on an open shard socket. Always sent
3393
+ * once per socket open, so the server's `onConnect` hooks fire symmetrically
3394
+ * with `onDisconnect` (which the DO dispatches unconditionally at close for
3395
+ * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
3396
+ * hooks are registered, so the single frame costs nothing in the common case.
3397
+ *
3398
+ * The shard's registered context (or the client-wide default) rides along
3399
+ * when one is set — the DO records it on the attachment for replay to
3400
+ * `onDisconnect`. A socket with no registered context still announces itself;
3401
+ * the envelope simply omits `context`, which is optional on the wire.
3402
+ * Register a context — e.g. `setConnectionContext({})` — to attach app state
3403
+ * to the lifecycle dispatch.
3404
+ */
3405
+ private sendConnectEnvelope;
3406
+ /**
3407
+ * Re-send every shape subscription bound to `shardKey` over its (now open)
3408
+ * socket. Each frame carries the shape's last applied checkpoint, so the
3409
+ * server resumes from it — or re-seeds when the cursor fell below CDC
3410
+ * retention or the epoch forked.
3411
+ */
3412
+ private resendShapeSubscriptions;
3413
+ private ensureSocket;
3414
+ /**
3415
+ * Resolve the {@link WsTokenProvider} and open the shard socket with the
3416
+ * minted token. The connection is already in the `connecting` state, so the
3417
+ * async gap is race-guarded: a client `close()`, a `setWsToken` bounce, or a
3418
+ * competing connect that landed first all abandon this attempt. A provider
3419
+ * failure fails the attempt through {@link handleDisconnect}, which arms the
3420
+ * normal reconnect backoff — a broken mint endpoint degrades to retries, not
3421
+ * a silent tokenless socket the admin gate would reject.
3422
+ */
3423
+ private openSocketWithProvidedToken;
3424
+ /**
3425
+ * Construct one WebSocket connection attempt and wire the shared
3426
+ * lifecycle guarantees around it — the fail-fast connect-timeout, the
3427
+ * identity guard that stops a superseded attempt's late `open`/`message`/
3428
+ * `close`/`error` from touching a connection a newer attempt already
3429
+ * owns, and (once open) the keepalive heartbeat with its half-open
3430
+ * watchdog (plan 217). One call opens ONE attempt; the caller owns
3431
+ * reconnect scheduling from `onClose` — mirrors the shard's existing
3432
+ * `ensureSocket` / `handleDisconnect` split, now shared with
3433
+ * `subscribeScheduledJobs` so it stops re-living the bug that split
3434
+ * already fixed once (CLIENT-05).
3435
+ *
3436
+ * The identity guard is `conn.socket !== socket`, re-checked before every
3437
+ * action below. `conn.socket` is reassigned to a new attempt's socket
3438
+ * synchronously — right here, before `open` ever fires — so an older
3439
+ * attempt's guard trips the instant it's superseded, even if its
3440
+ * underlying socket only fires its real `close`/`error` much later. This
3441
+ * ordering is load-bearing: preserve it exactly.
3442
+ */
3443
+ private openManagedSocket;
3444
+ /** Construct the shard socket and wire its lifecycle handlers. The connection must already be in the `connecting` state. */
3445
+ private openSocket;
3446
+ /**
3447
+ * Send the stream-start frames queued while the socket was (re)connecting,
3448
+ * marking each one that lands as started on the server.
3449
+ */
3450
+ private flushPendingStreams;
3451
+ /**
3452
+ * Tear down a stream the consumer cancelled, telling the server when the
3453
+ * server is the one still holding it.
3454
+ */
3455
+ private cancelStream;
3456
+ private handleDisconnect;
3457
+ /**
3458
+ * Begin the keepalive heartbeat on an open connection attempt — the only
3459
+ * caller is {@link openManagedSocket}'s own `open` handler, so both the
3460
+ * shard socket and `subscribeScheduledJobs` share this one implementation
3461
+ * instead of each hand-rolling their own (plan 217, generalized).
3462
+ *
3463
+ * Each tick first checks the half-open watchdog (see
3464
+ * {@link ManagedSocketState.lastFrameAt}): if no frame at all has arrived
3465
+ * within `heartbeatIntervalMs * 2.5`, the far end has gone quiet without
3466
+ * the socket ever firing `close` — force it closed and report it through
3467
+ * `onWatchdogTrip` (the caller's `onClose`) so the normal reconnect/backoff
3468
+ * takes over instead of every live query on it silently staling forever.
3469
+ * Otherwise it sends a {@link WS_KEEPALIVE_PING} text frame the server
3470
+ * answers from its hibernation auto-response without waking the DO. A
3471
+ * no-op when the heartbeat is disabled (an interval of zero or less);
3472
+ * idempotent — any existing timer is cleared first so a reconnect can't
3473
+ * leak intervals.
3474
+ */
3475
+ private startHeartbeat;
3476
+ /** Clear a connection's keepalive timer, if any. Safe to call repeatedly. */
3477
+ private stopHeartbeat;
3478
+ /** Mark every subscription bound to `shardKey` as needing a fresh ack. */
3479
+ private markShardPendingAck;
3480
+ private sendSubscribeIfOpen;
3481
+ private sendShapeSubscribeIfOpen;
3482
+ private handleServerMessage;
3483
+ private handleErrorMessage;
3484
+ /** Buffer key for an in-flight poke: `pokeId` is only unique per shard socket, so it is scoped by connection. */
3485
+ private pokeBufferKey;
3486
+ private handlePokeStart;
3487
+ private handlePokePart;
3488
+ private handlePokeEnd;
3489
+ /**
3490
+ * Commit one shape's slice of a poke, or refuse it and re-seed.
3491
+ *
3492
+ * Split out of {@link handlePokeEnd} because every decision here is PER SHAPE
3493
+ * — the reset flag, the base checkpoint, the watermark — while the poke
3494
+ * envelope around it is not.
3495
+ */
3496
+ private applyPokePart;
3497
+ /**
3498
+ * Force the server to re-send a full snapshot for `state`, leaving the
3499
+ * currently displayed value alone until it lands. Used when a delta frame
3500
+ * cannot be applied: dropping the resume cursor is what makes the resubscribe
3501
+ * a snapshot rather than a `resume`, and un-acking is what lets
3502
+ * `sendSubscribeIfOpen` put the frame on the wire at all. Mirrors the shape
3503
+ * path's re-seed on a diverged base.
3504
+ */
3505
+ private resnapshotSubscription;
3506
+ /** Materialize a shape's keyed view to an array and invoke its callbacks. */
3507
+ private emitShapeRows;
3508
+ private handleDataMessage;
3509
+ /**
3510
+ * Handle a `resume` frame (Pillar 1b): the server proved nothing the
3511
+ * subscription reads changed since our `sinceSeq`, so the cached value is
3512
+ * still current. We keep `lastValue` as-is, mark the sub acked, and advance
3513
+ * the cursor (re-persisting so the next reconnect resumes from the newer
3514
+ * watermark). No callback fires — the value didn't change, and `subscribe()`
3515
+ * already replayed the cached value to every consumer synchronously.
3516
+ */
3517
+ private handleResumeMessage;
3518
+ /**
3519
+ * Handle a `settled` frame: a write touched one of this subscription's read
3520
+ * tables but produced a byte-identical result, so the server suppressed the
3521
+ * data frame. Like {@link handleResumeMessage} the value didn't change — we
3522
+ * advance the resume position and re-persist — but we ALSO surface the echoed
3523
+ * custom-mutator watermark via `onCheckpoint` so a `@lunora/db` list
3524
+ * collection drops the optimistic overlay for the confirmed write (otherwise
3525
+ * its checkpoint gate, fed only by data frames, would hang forever). Sent
3526
+ * only to custom-mutator clients; plain `useQuery` subscribers leave
3527
+ * `onCheckpoint` unset and this is a near no-op.
3528
+ */
3529
+ private handleSettledMessage;
3530
+ /**
3531
+ * Mark `state` acked and, when the frame carries a newer cursor/epoch than
3532
+ * the cached position, advance the resume watermark and re-persist. Shared by
3533
+ * the `resume` and `settled` frame handlers — both acknowledge "nothing the
3534
+ * client must re-render changed, but the resume position may have moved".
3535
+ */
3536
+ private ackAndAdvanceCursor;
3537
+ /**
3538
+ * Resolve the value to publish for a `data`/`delta` frame.
3539
+ *
3540
+ * A `data` frame is an authoritative snapshot (the server re-execution path)
3541
+ * and always replaces the cached value wholesale. A `delta` frame carrying a
3542
+ * structured `MutationDelta` (the `broadcastDelta` row-change path) is
3543
+ * merged incrementally into the cached list — preserving order, no dup/loss —
3544
+ * so each subscription (including every paginated page) updates by delta
3545
+ * rather than a full re-send. We fall back to full replacement when the
3546
+ * delta isn't a recognisable row change, when there's no cached value yet,
3547
+ * or when it can't be applied cleanly against the current cached shape.
3548
+ */
3549
+ private resolveDataPayload;
3550
+ /** Route an inbound whisper to the topic's handlers on the originating shard. */
3551
+ private dispatchWhisper;
3552
+ /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
3553
+ private notifyTokenExpired;
3554
+ /**
3555
+ * CLIENT-04: `type: "complete"` today is sent ONLY by `@lunora/do`'s
3556
+ * `handleStream` (see `shard-do.ts`), gated to the `stream` envelope type
3557
+ * and minting only `stream_*` ids — the `subscribe` path never sends it, so
3558
+ * a live SUBSCRIPTION provably never receives `complete` from the current
3559
+ * server. But `ServerCompleteMessage` is a generic `id`-keyed frame and
3560
+ * `ShardDO` is user-subclassable, so this stays defensive rather than
3561
+ * assuming a `sub_*` id can never reach here: unlike the historical
3562
+ * `subscriptions.remove(state)`, which dropped the state out of
3563
+ * `subscriptions.all()` — the set the reconnect resubscribe loop walks
3564
+ * (`ensureSocket`'s `open` handler) — and so froze the query forever across
3565
+ * every future reconnect, this fans a cancellation error to any listener
3566
+ * and marks the registration un-acked instead. Non-destructive: the state
3567
+ * stays in the registry, so the very next reconnect resubscribes it. The
3568
+ * two id-spaces don't overlap (`sub_*` vs `stream_*`), so the stream and
3569
+ * subscription lookups below are mutually exclusive.
3570
+ */
3571
+ private handleCompleteMessage;
3572
+ private unpersist;
3573
+ /**
3574
+ * Stable, non-reversible fingerprint of the current auth identity used to
3575
+ * stamp queued offline writes. `null` (signed out) is its own identity and
3576
+ * never matches a bearer-token fingerprint. The raw token is never stored;
3577
+ * a length-prefixed FNV-1a hash is enough to detect an identity *change*
3578
+ * without keeping the credential around in the queue map.
3579
+ */
3580
+ private identityFingerprint;
3581
+ /**
3582
+ * Stable token-hash fingerprint of a bearer token (the `<len>:<fnv>:<djb2>`
3583
+ * format a token-stamped queued write carries). Extracted so the replay gate
3584
+ * can recompute the hash of the current credential and recognise a write
3585
+ * stamped under it — even after the fingerprint was relabelled to a subject.
3586
+ *
3587
+ * Two independent 32-bit passes (FNV-1a + djb2) give a ~64-bit digest, so
3588
+ * two distinct equal-length tokens are astronomically unlikely to share a
3589
+ * fingerprint. A single 32-bit hash collides ~1-in-4e9 per equal-length
3590
+ * pair — enough that, on a shared device, user B could hydrate A's cached
3591
+ * reads. Different algorithms (not the same FNV with a different seed, which
3592
+ * would be affine-related) keep the two passes genuinely independent.
3593
+ * Still synchronous (no crypto) and stable across surrogate pairs.
3594
+ */
3595
+ private hashToken;
3596
+ /**
3597
+ * The `credential` field a read-cache write carries: the token hash of the
3598
+ * bearer currently held, or nothing at all when signed out (there is no
3599
+ * credential to match against, and the `null` identity already covers it).
3600
+ */
3601
+ private credentialStamp;
3602
+ /**
3603
+ * Whether a read-cache entry belongs to the identity in effect right now —
3604
+ * the ONE gate the hydrated peek, the subscribe-time take and the late seed
3605
+ * all share.
3606
+ *
3607
+ * Three ways to be the same identity, because the label and the credential
3608
+ * resolve at different times:
3609
+ *
3610
+ * 1. The fingerprints are equal — the plain case.
3611
+ * 2. The entry is stamped under a token hash and the live identity has since
3612
+ * been relabelled to the subject that credential resolved to
3613
+ * ({@link isSameCredentialUnderTokenHash}).
3614
+ * 3. The entry is stamped under a subject and THIS session has only the raw
3615
+ * token so far, but it is byte-for-byte the credential the entry was written
3616
+ * under. This is the direction the strict comparison missed entirely, and it
3617
+ * is the normal shape of every reload: every adapter calls
3618
+ * `setAuthToken(token)` from storage and only learns the subject a
3619
+ * `/get-session` round trip later — which offline never completes at all.
3620
+ * Without it the durable read cache never seeded for a bearer-token app.
3621
+ *
3622
+ * All three want a credential this client actually HOLDS, which is why a
3623
+ * **cookie session seeds nothing on an offline cold start** — a documented
3624
+ * limitation, not a gap. The cookie is `HttpOnly`: the client can neither
3625
+ * read it nor prove it still has it, and offline the `/get-session` that
3626
+ * would resolve the subject never answers, so such entries (stamped
3627
+ * `subj:<id>`, no credential) have nothing to match. Seeding them on the
3628
+ * remembered subject LABEL would hand the rows to whoever opens the browser
3629
+ * profile with nothing evidencing they are that subject, and revoking on a
3630
+ * later mismatch does not repair it: that check can only run once
3631
+ * connectivity returns, which is exactly the state where the offline seed
3632
+ * was not needed. Offline-first reads require a bearer token.
3633
+ *
3634
+ * Case 1 is suspended while the subject awaits re-confirmation
3635
+ * ({@link subjectAwaitingReconfirm}): the fingerprint then labels a
3636
+ * credential nothing has checked it against, which is precisely the
3637
+ * account-switch shape — `setAuthToken(otherAccountsToken)` with no subject,
3638
+ * what every adapter does on a reload, still reading `subj:<previous user>`.
3639
+ * Matching on that label alone hands the new account the previous account's
3640
+ * cached rows. Cases 2 and 3 both PROVE the credential, so the reload this
3641
+ * gate exists for still seeds.
3642
+ */
3643
+ private cachedQueryMatchesIdentity;
3644
+ /**
3645
+ * True when `stamped` is a token-hash of the SAME credential still held now,
3646
+ * even though the live identity has since been relabelled to a subject. Covers
3647
+ * `setAuthToken(token, userId)` where the subject resolved a tick after the
3648
+ * token was set: a write persisted (or requeued) under the token hash must
3649
+ * still replay — the credential never changed, only its label — instead of
3650
+ * being dropped as an identity mismatch. This is the durable counterpart to
3651
+ * {@link restampQueuedIdentity}, which only relabels the in-memory live stamp
3652
+ * (consumed on the first flush) and never touches `item.identity` or the
3653
+ * persisted record, so a reload or a transient-failure requeue would otherwise
3654
+ * fall back to the stale token-hash and wrongly reject the same user's write.
3655
+ */
3656
+ private isSameCredentialUnderTokenHash;
3657
+ /**
3658
+ * Key the offline-queue identity on the resolved user id rather than the
3659
+ * token bytes, so the NEXT token refresh keeps the same identity.
3660
+ *
3661
+ * Only a resolved user labels anything. A 401, a network failure or an
3662
+ * empty session resolves `null` for reasons that say nothing about who is
3663
+ * signed in, and a token that rotated mid-flight belongs to a session this
3664
+ * answer predates — both leave the established label alone rather than
3665
+ * clearing it (which would look like an identity change and drop the queue).
3666
+ */
3667
+ private adoptResolvedSubject;
3668
+ /**
3669
+ * True while an established subject labels a credential it was never checked
3670
+ * against — see the `subjectToken` field. Every replay verdict is
3671
+ * `"unknown"` (hold) until the next session resolve re-asserts the subject.
3672
+ */
3673
+ private subjectAwaitingReconfirm;
3674
+ /**
3675
+ * The identity a queued write is stamped with. The live `queuedIdentities`
3676
+ * map is the source of truth for this session; a hydrated write whose id
3677
+ * isn't in it falls back to the stamp persisted with the record. `Map.get`
3678
+ * returns `undefined` for unstamped/hydrated ids and `item.identity` is
3679
+ * `undefined` for legacy records (persisted before stamps were durable),
3680
+ * while a persisted `null` (queued while signed out) is a real value that
3681
+ * must not collapse into `undefined` — hence `=== undefined`, not `??`.
3682
+ */
3683
+ private stampOf;
3684
+ /**
3685
+ * Reject the in-memory offline writes that can no longer replay under the
3686
+ * identity now signed in, dropping their durable records so a later
3687
+ * `hydrate` can't resurrect another user's writes.
3688
+ *
3689
+ * Per item, not wholesale: this runs on a plain sign-in too (`null` → a
3690
+ * signed-in identity is a credential change like any other), where the
3691
+ * queue is the *signing-in user's own* restored writes. Every stamp goes
3692
+ * through {@link replayIdentityVerdict}, the one comparison, and only
3693
+ * `"mismatch"` is terminal — `"match"` and `"unknown"` stay queued.
3694
+ *
3695
+ * The durable read cache is cleared only when there WAS a previous identity
3696
+ * to protect. Wiping it on a sign-in from signed-out would destroy the
3697
+ * offline-first cache on every cold boot, and buys nothing: cache entries
3698
+ * are identity-stamped and gated at every read.
3699
+ */
3700
+ private rejectQueuedForIdentityChange;
3701
+ /**
3702
+ * Move the identity stamp of every open shard socket from `from` to `to` —
3703
+ * the sibling of {@link restampQueuedIdentity} for the read cache. A socket
3704
+ * pins the identity it was upgraded under (see `ShardConnection.identity`)
3705
+ * and {@link persistQueryValue} stamps cached reads with it, deliberately,
3706
+ * so a still-open previous-user socket can't file frames under the new
3707
+ * user's stamp. A same-credential relabel is the one case where that pin is
3708
+ * stale rather than protective: without this, every read cached for the rest
3709
+ * of the session is filed under a fingerprint the next session's identity
3710
+ * gate rejects, and the durable read cache silently yields nothing.
3711
+ */
3712
+ private restampConnectionIdentity;
3713
+ /**
3714
+ * Migrate every identity stamp from `from` to `to` — used when the auth
3715
+ * identity label changes but the underlying credential (token) does NOT, e.g.
3716
+ * the user id resolves a tick after the token was set. The in-memory
3717
+ * `queuedIdentities` map is the flush-time source of truth, so re-stamping it
3718
+ * keeps the in-flight writes replayable under the new (more stable) identity
3719
+ * instead of the flush guard discarding them as a mismatch.
3720
+ *
3721
+ * That map alone was not enough: it is consumed and DELETED on the first
3722
+ * flush attempt (`passesReplayIdentityGate`), while the queue entry and its
3723
+ * persisted record keep the original stamp. So a reload, or a requeue after a
3724
+ * transient failure, fell back to the old token hash — and once the token had
3725
+ * been refreshed, `isSameCredentialUnderTokenHash` no longer recognised it
3726
+ * and the write was rejected `OFFLINE_IDENTITY_CHANGED` for the very user
3727
+ * `setAuthToken`'s sticky-`subject` contract promises to protect. The queue's
3728
+ * own re-stamp covers both the entry and its durable record.
3729
+ */
3730
+ private restampQueuedIdentity;
3731
+ /**
3732
+ * Migrate the {@link clientWatermarks} bucket map nested under identity
3733
+ * `from` to identity `to` — the sibling of {@link restampQueuedIdentity},
3734
+ * for the same same-credential-subject-resolves case. Without this, a
3735
+ * bucket's watermark cached under the token-hash fingerprint would look
3736
+ * unset once the fingerprint relabels to `subj:…`, so the next push
3737
+ * re-derives `1` against a server watermark the DO already advanced — the
3738
+ * OUT_OF_ORDER wedge this cache-keying scheme exists to fix, reintroduced
3739
+ * by the fix itself. `to` may already hold a bucket map (switching back to
3740
+ * an identity that has its own cached watermarks); merge into it rather
3741
+ * than clobbering it, with `from`'s entries winning on a colliding bucket —
3742
+ * the same overwrite a plain `Map.set` would have done before this was a
3743
+ * nested map.
3744
+ */
3745
+ private restampWatermarks;
3746
+ /**
3747
+ * Drop the durable read cache on an identity change so a cached value stamped
3748
+ * under the previous identity can never hydrate into a new session. Clears
3749
+ * the in-flight write batch and the not-yet-consumed hydrated entries too;
3750
+ * the durable `clear()` is best-effort.
3751
+ */
3752
+ private clearQueryCacheForIdentityChange;
3753
+ /**
3754
+ * Flush every shard with a mutation currently queued in `offlineQueue`
3755
+ * (see `queuedOfflineShardKeys`). Used on a FOLLOWER tab when the
3756
+ * mirrored leader status transitions to `"connected"` — a follower has no
3757
+ * per-shard `ShardConnection` reconnect event to hang the usual
3758
+ * single-shard `flushOfflineQueue(shardKey)` call off of (see the
3759
+ * `handleConnect` call site), so this walks every shard that might have
3760
+ * something queued instead. Flushing an already-empty shard is a cheap
3761
+ * no-op (`flushOfflineQueue` returns immediately once `drain` yields
3762
+ * nothing), so over-inclusion here is harmless.
3763
+ */
3764
+ private flushAllOfflineQueues;
3765
+ /**
3766
+ * Replay a shard's queued writes, serialized per shard and published as
3767
+ * {@link offlineFlushes} so a concurrent `mutation()` can wait behind it.
3768
+ * Never rejects: every entry's outcome is settled individually inside
3769
+ * {@link drainOfflineQueue}, and a poisoned chain would strand every later
3770
+ * flush AND every write waiting on the barrier.
3771
+ */
3772
+ private flushOfflineQueue;
3773
+ private drainOfflineQueue;
3774
+ /**
3775
+ * Remember the longest delay this shard's flush was told (or worked out) to
3776
+ * wait, so the drain can honour it before trying again
3777
+ * ({@link LunoraClient.replayRetryState}). Counts the attempt either way:
3778
+ * that is what a hintless refusal backs off on.
3779
+ */
3780
+ private noteReplayRetryDelay;
3781
+ /**
3782
+ * Consume this shard's retry delay and re-flush it once the delay has
3783
+ * elapsed.
3784
+ *
3785
+ * Only a failure the server or an edge ANSWERED schedules anything (see
3786
+ * {@link replayRetryDelayMs}): a `fetch` that never landed is already covered
3787
+ * by the reconnect that will flush the queue, whereas a refused flush happens
3788
+ * over a socket that stays open — so without this the writes sit queued
3789
+ * indefinitely. One pending timer per shard; a second delay replaces it
3790
+ * rather than stacking flushes.
3791
+ *
3792
+ * Nothing left to retry on this key (drained, closed, or no delay) drops its
3793
+ * backoff state, which is both the reset after progress and what bounds the
3794
+ * map.
3795
+ */
3796
+ private scheduleRateLimitedRetry;
3797
+ /**
3798
+ * Partition already-gated writes into the encodable ones (returned) and reject
3799
+ * the rest terminally. A write whose args can't be wire-encoded (e.g. a RegExp
3800
+ * or class instance in a `v.any()` field) can NEVER replay — the codec failure
3801
+ * is deterministic, not transient. Rejecting here is essential: otherwise
3802
+ * `encodeWire` throws mid-flush, is classified as transient (a codec error has
3803
+ * no `.code`), and re-queues forever — a silent hang where the caller's Promise
3804
+ * never settles and the optimistic write never rolls back. Encoding is cheap;
3805
+ * the flush is the slow reconnect path.
3806
+ */
3807
+ private encodableOrSettleTerminal;
3808
+ /**
3809
+ * Identity gate for one queued write about to replay: a write stamped under
3810
+ * one identity must never replay under another, and must never be DESTROYED
3811
+ * because the identity isn't known yet.
3812
+ *
3813
+ * The three-way verdict is {@link replayIdentityVerdict}'s, not a second
3814
+ * hand-rolled comparison — `@lunora/db`'s durable outbox holds on `"unknown"`
3815
+ * through the same call, and this path (the default for the standalone
3816
+ * client) used to drop there instead, purging the queuing user's own write
3817
+ * on every reload that opened its socket before the session resolved.
3818
+ *
3819
+ * `"send"` replays it and consumes the live stamp. `"hold"` leaves it queued
3820
+ * and persisted, stamp intact, for a later flush once an identity is
3821
+ * established (see `setAuthToken`). `"reject"` means a different identity is
3822
+ * signed in: settle it terminally `OFFLINE_IDENTITY_CHANGED` and purge the
3823
+ * durable record.
3824
+ */
3825
+ private replayGateVerdict;
3826
+ /** 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. */
3827
+ private settleReplaySuccess;
3828
+ /**
3829
+ * The entry a shard's cursor lives under.
3830
+ *
3831
+ * Only the server knows that an omitted `shardKey` and an explicit one
3832
+ * spelling out its configured default name are the same shard — the default
3833
+ * is server-side configuration the client never sees. Keying on what was
3834
+ * SENT would split one shard's cursor across two entries, so a write under
3835
+ * one spelling would stop constraining a read under the other. Resolving
3836
+ * `undefined` through the learned name is what keeps both spellings on one
3837
+ * entry.
3838
+ */
3839
+ private cursorKeyFor;
3840
+ /**
3841
+ * Learn the server's own name for the default shard from a response to a
3842
+ * call that named no shard.
3843
+ *
3844
+ * Any cursor recorded before the name was known sits under the placeholder
3845
+ * entry, so it is folded in rather than stranded — otherwise the requirement
3846
+ * from a client's first write would be lost exactly once, which is the kind
3847
+ * of gap that only shows up as a stale read under load.
3848
+ */
3849
+ private learnDefaultShardKey;
3850
+ /**
3851
+ * Record the cursor a write committed at as this shard's read-your-writes
3852
+ * requirement.
3853
+ *
3854
+ * Monotonic: responses can land out of order, and moving the requirement
3855
+ * BACKWARDS would let a later read be answered from a replica copy that
3856
+ * predates a write this client already saw.
3857
+ */
3858
+ private recordShardCursor;
3859
+ /**
3860
+ * Whether a replay failure leaves the durable write queued rather than
3861
+ * settling it terminally — the ONE classification the single-call, per-slot
3862
+ * and whole-batch paths share, so a write's fate never depends on how many
3863
+ * siblings rode along.
3864
+ *
3865
+ * {@link isTransientReplayFailure} answers the "no verdict was reached" half.
3866
+ * The other half is a refused CREDENTIAL ({@link isAuthReplayFailure}): the
3867
+ * queue flushes on the shard's `open` handler with whatever bearer survived
3868
+ * the offline window, so an expired token is the expected outcome of a long
3869
+ * disconnect, not a verdict on the write. Notifying {@link onTokenExpired}
3870
+ * here is what closes the loop — the HTTP replay path has no equivalent of
3871
+ * the WS `4001` close frame, so without this nothing tells the app to
3872
+ * refresh, and `setAuthToken` (which re-flushes) is never called.
3873
+ *
3874
+ * Notified once per credential, not once per write: a flush of a hundred
3875
+ * queued writes earns a hundred identical refusals, and firing the hook for
3876
+ * each would put a hundred token refreshes on the app. The stamp re-arms as
3877
+ * soon as the credential moves, which is the only thing that can change the
3878
+ * answer.
3879
+ */
3880
+ private shouldRequeueReplayFailure;
3881
+ /** Settle a write the server reached a coded verdict on: replaying would re-trigger the same failure (a poison-message loop), so drop it. */
3882
+ private settleReplayTerminal;
3883
+ /**
3884
+ * Replay already-identity-gated writes one at a time on the single-call `/rpc`
3885
+ * path, preserving FIFO order (parallel `.then()` chains would race the
3886
+ * ordering callers depend on). Each replays under its stable `mutationId` so
3887
+ * the server dedups a write it already committed (exactly-once). A server verdict
3888
+ * drops the write; a transient failure ({@link isTransientReplayFailure} — a
3889
+ * transport error, a shard the worker couldn't reach, a rate-limit refusal, or a
3890
+ * non-2xx carrying no `{ error }` envelope) stops the flush and re-queues this
3891
+ * write and every unreplayed one for the next reconnect — their callers stay
3892
+ * pending, and the identity guard re-applies on retry via each record's persisted
3893
+ * stamp. The batch path classifies a slot by the same rule, so a durable write's
3894
+ * fate never depends on how many siblings happened to be queued alongside it.
3895
+ */
3896
+ private replaySequential;
3897
+ /**
3898
+ * Coalesce already-identity-gated writes for a single shard into ONE
3899
+ * `/_lunora/rpc-batch` round trip (plan 088 follow-on). The worker forwards
3900
+ * them to the shard DO, which replays each through its single-call dispatch, so
3901
+ * per-entry `mutationId` idempotency and in-order application are inherited from
3902
+ * the proven path. Per-slot demux mirrors {@link replaySequential}'s
3903
+ * classification: success confirms the optimistic layer against the echoed
3904
+ * `commitCursor`; a coded application verdict is terminal; a failure
3905
+ * {@link shouldRequeueReplayFailure} keeps, a missing slot, or a whole-batch
3906
+ * transport failure re-queues for the next reconnect (never dropping a durable
3907
+ * write). A whole-batch coded rejection (a bad request the server reached a
3908
+ * verdict on) is terminal for every entry.
3909
+ *
3910
+ * The body is also held under {@link MAX_BATCH_BODY_BYTES}: the worker caps a
3911
+ * batch body at 1 MiB and answers `413`, which is ONE refusal covering every
3912
+ * write in the chunk. An over-budget chunk is halved before it is sent, and a
3913
+ * `413` for a chunk of more than one write halves it and retries rather than
3914
+ * settling the whole chunk terminally — so a backlog of large writes still
3915
+ * commits, one bisection deeper.
3916
+ *
3917
+ * Returns the writes that must be re-queued and `stop` — `true` when the whole
3918
+ * chunk failed at the transport level, so the caller leaves later chunks queued
3919
+ * rather than sending on. The caller re-queues once, in order, so requeuing is
3920
+ * NOT done here.
3921
+ */
3922
+ private replayBatched;
3923
+ /**
3924
+ * Classify a `/_lunora/rpc-batch` reply that carried no per-slot results — one
3925
+ * outcome covering every entry in the chunk. A code
3926
+ * {@link shouldRequeueReplayFailure} keeps (an unreachable shard, a
3927
+ * rate-limit refusal, a refused credential) or a {@link TransportError} (an
3928
+ * edge reply with no verdict in it) leaves every write durable for the next
3929
+ * attempt; anything else is a verdict reached on the request itself, and
3930
+ * settles all of them.
3931
+ */
3932
+ private settleWholeBatchError;
3933
+ /**
3934
+ * Split an over-large batch chunk in half and replay each half, preserving
3935
+ * FIFO order. Recurses through {@link replayBatched}, so a chunk keeps halving
3936
+ * until it fits (or reaches one write, which is then the server's verdict to
3937
+ * give). A `stop` on the first half leaves the second unsent and queued.
3938
+ */
3939
+ private replayBatchedHalves;
3940
+ /**
3941
+ * Demux a `/_lunora/rpc-batch` reply back onto the queued writes it replayed,
3942
+ * in input order. Each slot's envelope classifies its write the same way
3943
+ * {@link replaySequential} does: a success confirms the optimistic layer
3944
+ * against the echoed `commitCursor`; a coded application verdict is terminal;
3945
+ * a failure {@link shouldRequeueReplayFailure} keeps, or a slot the server
3946
+ * never returned, is returned for the caller to re-queue.
3947
+ * @returns the writes that must be re-queued (kept slots), in input order
3948
+ */
3949
+ private settleReplayBatchSlots;
3950
+ }
3951
+ export { ServerPokePartMessage as $, ActionCallOptions as A, BookmarkStorage as B, ConnectionStatus as C, DEFAULT_MAX_BUFFER as D, OutboxMutation as E, FunctionArgumentDescriptor as F, GlobalFacetResult as G, HttpStreamRef as H, OutboxSink as I, PersistedMutation as J, RowOp as K, LunoraClient as L, MutationCallOptions as M, RpcEnvelope as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReconnectOptions as R, SubscriptionError as S, RpcResponseBody as T, User as U, ScheduleRecord as V, ScheduleRetryPolicy as W, SchedulerPoolStatus as X, SchedulerStatus as Y, ServerMessage as Z, ServerPokeEndMessage as _, Unsubscribe as a, ServerPokeStartMessage as a0, ShardTrafficEntry as a1, ShardTrafficResult as a2, StorageListPage as a3, StorageObject as a4, StoredQuery as a5, StreamHandle as a6, SubscriptionCallback as a7, SubscriptionRegistry as a8, SubscriptionState as a9, SyncWatermark as aa, WorkflowInstanceAction as ab, WorkflowInstanceDetail as ac, WorkflowInstancePage as ad, WorkflowInstanceStatus as ae, WorkflowInstanceSummary as af, WorkflowStepDetail as ag, WsTokenProvider as ah, createClientQuery as ai, createLocalStore as aj, createStream as ak, 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, OptimisticLocalStore as y, OptimisticUpdate as z };