@lunora/client 1.0.0-alpha.4 → 1.0.0-alpha.41

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 (85) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +2 -0
  3. package/dist/auth/index.d.mts +11 -10
  4. package/dist/auth/index.d.ts +11 -10
  5. package/dist/auth/index.mjs +1 -60
  6. package/dist/index.d.mts +736 -172
  7. package/dist/index.d.ts +736 -172
  8. package/dist/index.mjs +1 -14
  9. package/dist/packem_shared/CONFLICT_ERROR_CODE-B2SU0CaJ.mjs +1 -0
  10. package/dist/packem_shared/ClientServiceWorker-CRQ5yl7-.mjs +1 -0
  11. package/dist/packem_shared/DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs +1 -0
  12. package/dist/packem_shared/LunoraClient-CB5y0HME.mjs +1 -0
  13. package/dist/packem_shared/OfflineQueue-y4mymc5n.mjs +1 -0
  14. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-D96iRJDY.mjs +1 -0
  15. package/dist/packem_shared/SKIP-CArzT3Vl.mjs +1 -0
  16. package/dist/packem_shared/SubscriptionRegistry-C72rCp44.mjs +1 -0
  17. package/dist/packem_shared/TabCoordinator-CMFYQCL-.mjs +1 -0
  18. package/dist/packem_shared/anyApi-BD4dgvDY.mjs +1 -0
  19. package/dist/packem_shared/applyDelta-DXqQORbM.mjs +1 -0
  20. package/dist/packem_shared/createAsyncStoragePersistence-BRLqeXsC.mjs +1 -0
  21. package/dist/packem_shared/createClientQuery-CrdRoicO.mjs +1 -0
  22. package/dist/packem_shared/createInMemoryBookmarkStorage-DCd5Ej-t.mjs +1 -0
  23. package/dist/packem_shared/createInMemoryPersistence-CQYXy8UP.mjs +1 -0
  24. package/dist/packem_shared/createInMemoryQueryCache-DjCKrLjk.mjs +1 -0
  25. package/dist/packem_shared/createLocalStore-CwuKPK9x.mjs +1 -0
  26. package/dist/packem_shared/createMutationRunner-lQXH8Amk.mjs +1 -0
  27. package/dist/packem_shared/createMutatorRunner-BVzo0FBZ.mjs +1 -0
  28. package/dist/packem_shared/createReconnect-CFT7YRSR.mjs +1 -0
  29. package/dist/packem_shared/createReply-DF0jRsv-.mjs +1 -0
  30. package/dist/packem_shared/createServerClient-C1At_rrh.mjs +1 -0
  31. package/dist/packem_shared/createSnapshotPrecondition-CKvCNKyD.mjs +1 -0
  32. package/dist/packem_shared/deserializePreloaded-CHfOFpka.mjs +1 -0
  33. package/dist/packem_shared/getServerSession-CGjgRBAE.mjs +1 -0
  34. package/dist/packem_shared/httpStream-Cz4_QyjV.mjs +11 -0
  35. package/dist/packem_shared/idb-utility-C-DR8nG1.mjs +1 -0
  36. package/dist/packem_shared/local-store-DFMSEM2j.mjs +1 -0
  37. package/dist/packem_shared/lunora-client.d-D_WLwpn0.d.mts +2175 -0
  38. package/dist/packem_shared/lunora-client.d-cFPjoyDb.d.ts +2175 -0
  39. package/dist/packem_shared/offline-queue-BeWay5u5.mjs +1 -0
  40. package/dist/packem_shared/preload.d-BkbCVtZe.d.ts +21 -0
  41. package/dist/packem_shared/preload.d-DNxm6niZ.d.mts +21 -0
  42. package/dist/packem_shared/preloadQuery-DjwSjFwt.mjs +1 -0
  43. package/dist/packem_shared/types.d-CA7ZeJm9.d.mts +942 -0
  44. package/dist/packem_shared/types.d-CA7ZeJm9.d.ts +942 -0
  45. package/dist/packem_shared/wire-codec-D_fiax9d.mjs +1 -0
  46. package/dist/packem_shared/wire-key-j8BZ65HQ.mjs +1 -0
  47. package/dist/pagination/index.d.mts +42 -42
  48. package/dist/pagination/index.d.ts +42 -42
  49. package/dist/pagination/index.mjs +1 -61
  50. package/dist/query/index.d.mts +43 -42
  51. package/dist/query/index.d.ts +43 -42
  52. package/dist/query/index.mjs +1 -1
  53. package/dist/service.d.mts +49 -0
  54. package/dist/service.d.ts +49 -0
  55. package/dist/service.mjs +1 -0
  56. package/dist/ssr/index.d.mts +80 -79
  57. package/dist/ssr/index.d.ts +80 -79
  58. package/dist/ssr/index.mjs +1 -4
  59. package/dist/upload.d.mts +35 -0
  60. package/dist/upload.d.ts +35 -0
  61. package/dist/upload.mjs +1 -0
  62. package/package.json +13 -1
  63. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +0 -4
  64. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +0 -107
  65. package/dist/packem_shared/LunoraClient-DHMV-94j.mjs +0 -2198
  66. package/dist/packem_shared/OfflineQueue-D5p_QgF_.mjs +0 -127
  67. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  68. package/dist/packem_shared/SubscriptionRegistry-Dn-7k7eo.mjs +0 -1
  69. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +0 -61
  70. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  71. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  72. package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +0 -105
  73. package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +0 -138
  74. package/dist/packem_shared/createLocalStore-DSUfoLqY.mjs +0 -36
  75. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  76. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  77. package/dist/packem_shared/createServerClient-DMh-2UDv.mjs +0 -11
  78. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  79. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  80. package/dist/packem_shared/lunora-client.d-CbnxmuqG.d.mts +0 -1623
  81. package/dist/packem_shared/lunora-client.d-CbnxmuqG.d.ts +0 -1623
  82. package/dist/packem_shared/preload.d-Bhq6DBSe.d.mts +0 -20
  83. package/dist/packem_shared/preload.d-C73DT6bL.d.ts +0 -20
  84. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  85. package/dist/packem_shared/subscription-C1Jy7HiF.mjs +0 -55
@@ -0,0 +1,2175 @@
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-CA7ZeJm9.js";
2
+ import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
3
+ /**
4
+ * Reactive key-value store for local-only client state.
5
+ *
6
+ * Unlike a server {@link SubscriptionState} (which tracks a live WS connection,
7
+ * an `acked` flag, `serverBase`, optimistic layers, and the full subscription
8
+ * machinery), a `ClientQueryRef` is purely local — no server round-trip, no
9
+ * WebSocket, no persistence. It exists so framework adapters can offer a
10
+ * `useClientQuery` hook whose values survive component remounts and are shared
11
+ * across every consumer of the same ref, with none of the ceremony or coupling
12
+ * of a dedicated context provider.
13
+ *
14
+ * The store lives inside `LunoraClient` (a private field) and is surfaced through
15
+ * `client.getClientQuery(ref)` / `setClientQuery(ref, value)` /
16
+ * `subscribeClientQuery(ref, callback)`.
17
+ */
18
+ /** Opaque handle for a typed client-local query slot. */
19
+ interface ClientQueryRef<T = unknown> {
20
+ /** Default value when no value has been set explicitly. */
21
+ readonly defaultValue: T;
22
+ /** Stable identity for the slot. Must be unique within a client instance. */
23
+ readonly key: string;
24
+ }
25
+ /**
26
+ * Create a typed {@link ClientQueryRef}. Call once per slot at module scope
27
+ * (or inside a component module) — the ref object is the stable identity.
28
+ * @example
29
+ * ```ts
30
+ * // lunora/client-queries.ts
31
+ * import { createClientQuery } from "@lunora/client";
32
+ *
33
+ * export const sidebarOpen = createClientQuery("sidebarOpen", true);
34
+ * export const selectedMessageId = createClientQuery("selectedMessageId", undefined as string | undefined);
35
+ * ```
36
+ */
37
+ declare const createClientQuery: <T>(key: string, defaultValue: T) => ClientQueryRef<T>;
38
+ /**
39
+ * The machine-readable error codes a client can observe on a failed
40
+ * RPC/batch/subscription. Mirrors the server's `CODE_STATUS` keys
41
+ * (`@lunora/server`'s `error.ts`) by hand — the client is framework-neutral and
42
+ * must never import the server package (wrong dependency direction / would pull
43
+ * the server into the browser bundle). Keep this list in sync when a server code
44
+ * is added or removed (see the drift-guard note in the plan/maintenance docs).
45
+ */
46
+ declare const LUNORA_ERROR_CODES: readonly ["BAD_REQUEST", "CONFLICT", "COUNT_RLS_UNSUPPORTED", "FORBIDDEN", "INTERNAL_SERVER_ERROR", "MASK_UNSUPPORTED", "NOT_FOUND", "NOT_IMPLEMENTED", "RELATION_PREDICATE_UNSUPPORTED", "TOO_MANY_REQUESTS", "UNAUTHORIZED", "UNPROCESSABLE"];
47
+ /** A machine-readable error `code` the client may observe. Mirror of the server's `LunoraErrorCode`. */
48
+ type LunoraErrorCode = (typeof LUNORA_ERROR_CODES)[number];
49
+ /** Error code the server uses for optimistic-concurrency conflicts (HTTP 409). */
50
+ declare const CONFLICT_ERROR_CODE = "CONFLICT";
51
+ /**
52
+ * Whether an unknown rejection is an optimistic-concurrency conflict — the
53
+ * server lost a write race and the caller should refetch and retry (or surface
54
+ * the conflict). Structural check on the `code` property the client attaches
55
+ * when decoding the worker's `{ error: { code, message } }` envelope.
56
+ */
57
+ declare const isConflictError: (error: unknown) => error is Error & {
58
+ code: "CONFLICT";
59
+ };
60
+ /**
61
+ * Whether a rejection is an RLS/policy denial (`FORBIDDEN`, HTTP 403) — the
62
+ * caller is authenticated but not permitted to read/write the row. The most
63
+ * common per-call error a UI must handle in an RLS-first app.
64
+ */
65
+ declare const isForbiddenError: (error: unknown) => error is Error & {
66
+ code: "FORBIDDEN";
67
+ };
68
+ /** Whether a rejection is an authentication failure (`UNAUTHORIZED`, HTTP 401) — no/invalid identity. */
69
+ declare const isUnauthorizedError: (error: unknown) => error is Error & {
70
+ code: "UNAUTHORIZED";
71
+ };
72
+ /**
73
+ * Whether a rejection is a rate-limit denial (`TOO_MANY_REQUESTS`, HTTP 429).
74
+ * The retry hint (if the server sent one) is read with {@link getRetryAfterMs}.
75
+ */
76
+ declare const isRateLimitedError: (error: unknown) => error is Error & {
77
+ code: "TOO_MANY_REQUESTS";
78
+ };
79
+ /**
80
+ * Read the server's machine-readable `code` off a rejection, narrowed to the
81
+ * known {@link LunoraErrorCode} union. Returns `undefined` for a non-`Error`, a
82
+ * missing code, or an unrecognized code string (forward-compat server codes read
83
+ * as `undefined` here rather than being falsely narrowed).
84
+ */
85
+ declare const getErrorCode: (error: unknown) => LunoraErrorCode | undefined;
86
+ /**
87
+ * Read the rate-limit retry hint (`data.retryAfterMs`) off a
88
+ * `TOO_MANY_REQUESTS` rejection without hand-casting the `unknown` `data`
89
+ * payload. Returns the finite millisecond value the server sent, or `undefined`
90
+ * when absent/non-numeric. Pair with {@link isRateLimitedError}.
91
+ */
92
+ declare const getRetryAfterMs: (error: unknown) => number | undefined;
93
+ type SubscriptionCallback = (data: unknown) => void;
94
+ /** A subscription-scoped error the server pushed for this subscription id. */
95
+ interface SubscriptionError {
96
+ code?: string;
97
+ message: string;
98
+ }
99
+ type SubscriptionErrorCallback = (error: SubscriptionError) => void;
100
+ /**
101
+ * One active per-call optimistic transform layered onto a subscription. The
102
+ * displayed value is the authoritative {@link SubscriptionState.serverBase}
103
+ * folded through every layer's `transform`, in order — so an incoming server
104
+ * frame re-folds the still-pending layers onto the new base (rebasing) instead
105
+ * of clobbering them. A layer is dropped — gaplessly — once a `data`/`delta`
106
+ * frame whose `cursor >= commitCursor` arrives (its write is now reflected in
107
+ * `serverBase`); `commitCursor` is the CDC cursor the server echoed on the
108
+ * mutation's response, and stays `undefined` while the write is still queued/
109
+ * in-flight (so the overlay survives unrelated deltas until confirmed).
110
+ */
111
+ interface OptimisticLayer {
112
+ /** The committed CDC cursor (from the mutation response); `undefined` until confirmed. */
113
+ commitCursor?: number;
114
+ readonly id: symbol;
115
+ readonly transform: (current: unknown) => unknown;
116
+ }
117
+ interface SubscriptionState {
118
+ /** True once the server has acked the subscription on the current socket. */
119
+ acked: boolean;
120
+ readonly args: Record<string, unknown>;
121
+ /**
122
+ * Stable wire-key of `args` (`stableWireKey`), computed once at subscribe
123
+ * time. Cached so the optimistic-update fan-out can compare against a
124
+ * mutation's args key without re-serializing every subscription's args on
125
+ * every mutation.
126
+ */
127
+ readonly argsKey: string;
128
+ readonly callbacks: Set<SubscriptionCallback>;
129
+ /**
130
+ * Notified when a `settled` frame advances this subscription's watermark — a
131
+ * write touched the subscription's tables but the result was byte-identical,
132
+ * so the server suppressed the data frame. A `@lunora/db` list collection
133
+ * uses this to drop the optimistic overlay for the confirmed write.
134
+ *
135
+ * A SET (not a single slot) because `SubscriptionState` is SHARED across
136
+ * every subscriber to the same `(fn, args, shardKey)`: a `@lunora/db`
137
+ * collection may subscribe to a query a plain `useQuery` already opened, so
138
+ * each subscriber registers its own callback (mirroring `callbacks` /
139
+ * `errorCallbacks`) and a `settled` frame fans out to all of them. Plain
140
+ * `useQuery` consumers register nothing, leaving the set empty.
141
+ */
142
+ readonly checkpointCallbacks: Set<(watermark: {
143
+ checkpoint?: number;
144
+ mutationId?: number;
145
+ }) => void>;
146
+ /** Notified when the server rejects this subscription (e.g. admin auth). */
147
+ readonly errorCallbacks: Set<SubscriptionErrorCallback>;
148
+ readonly fn: FunctionReference;
149
+ readonly id: string;
150
+ /**
151
+ * The highest custom-mutator `mutationId` from this client the server has
152
+ * applied, captured from the last `settled` frame (the suppressed-list-frame
153
+ * watermark). Forwarded to {@link SubscriptionState.checkpointCallbacks}.
154
+ * Absent until a `settled` frame arrives.
155
+ */
156
+ lastMutationId?: number;
157
+ /** Last known value, used to short-circuit `useQuery`-style consumers. */
158
+ lastValue: unknown;
159
+ /**
160
+ * Active per-call optimistic layers, in application order (see
161
+ * {@link OptimisticLayer}). Empty for subscriptions with no pending per-call
162
+ * optimistic write — the common case, where `lastValue` tracks `serverBase`
163
+ * exactly and behaviour is identical to a plain server-value assignment.
164
+ */
165
+ optimisticLayers: OptimisticLayer[];
166
+ /**
167
+ * The authoritative server value the optimistic layers fold onto — the value
168
+ * with NO optimistic overlay. Tracks `lastValue` exactly whenever no layers
169
+ * are active; diverges only while a per-call optimistic write is pending. A
170
+ * server frame updates this (and re-folds the layers); the durable read cache
171
+ * persists this, never the optimistic overlay.
172
+ */
173
+ serverBase: unknown;
174
+ /**
175
+ * The `__cdc_log` high-watermark (`cursor`) the `lastValue` reflects,
176
+ * captured from the last `data`/`delta`/`resume` frame. Persisted to the
177
+ * durable read cache and replayed as `sinceSeq` on reconnect so the server
178
+ * can resume instead of re-snapshotting (Pillar 1b/2). Absent until the
179
+ * first cursor-stamped frame arrives.
180
+ */
181
+ serverCursor?: number;
182
+ /**
183
+ * The CDC `epoch` token the `serverCursor` belongs to, captured from the
184
+ * same frame. Replayed as `sinceEpoch` on reconnect so the server resumes
185
+ * only when the client is still on the same changelog timeline — a reset or
186
+ * recycled shard advertises a new epoch, forcing a fresh snapshot. Absent
187
+ * until the first epoch-stamped frame arrives.
188
+ */
189
+ serverEpoch?: string;
190
+ readonly shardKey?: string;
191
+ }
192
+ /**
193
+ * Active subscription registry. The client keys subscriptions by
194
+ * `(functionPath, stableWireKey(args), shardKey)` so duplicate calls share a
195
+ * single server-side registration. Args are stably encoded (keys sorted at every
196
+ * depth) so two structurally-equal arg records constructed with a different key
197
+ * order (`{ a, b }` vs `{ b, a }`) collapse to the same key instead of leaking a
198
+ * duplicate subscription. Encoding the args' **wire form** keeps the key
199
+ * byte-identical for pure-JSON args while giving wire-typed args (`bigint`,
200
+ * `Date`, bytes, …) distinct stable tokens instead of a throw.
201
+ */
202
+ declare class SubscriptionRegistry {
203
+ static key(functionPath: string, args: Record<string, unknown>, shardKey?: string): string;
204
+ private readonly byKey;
205
+ private readonly byId;
206
+ get(key: string): SubscriptionState | undefined;
207
+ getById(id: string): SubscriptionState | undefined;
208
+ add(state: SubscriptionState): void;
209
+ remove(state: SubscriptionState): void;
210
+ all(): SubscriptionState[];
211
+ }
212
+ /**
213
+ * Read/write handle over the client's live query cache, handed to a mutation's
214
+ * `withOptimisticUpdate` callback so a single mutation can optimistically patch
215
+ * many subscribed queries at once (Convex's `OptimisticLocalStore` model).
216
+ *
217
+ * `getQuery` reads the current value (server value or any still-pending
218
+ * optimistic override) of a subscribed query; `setQuery` registers a constant
219
+ * optimistic layer on top. The whole batch rebases onto incoming deltas and
220
+ * settles together — confirmed on the mutation's commit cursor, or rolled back
221
+ * on failure — the same per-subscription layer machinery the single-query
222
+ * per-call `optimistic` transform uses, generalized to N queries.
223
+ */
224
+ interface OptimisticLocalStore {
225
+ /**
226
+ * Every loaded subscription on `function_`, regardless of args, paired with
227
+ * the args it was subscribed under. Mirrors Convex's `getAllQueries` — handy
228
+ * when a write must patch every variant of a list query (all channels,
229
+ * all filters) without enumerating their args up front.
230
+ */
231
+ getAllQueries: <F extends FunctionReference>(function_: F) => {
232
+ args: ArgsOf<F>;
233
+ value: ReturnOf<F> | undefined;
234
+ }[];
235
+ /**
236
+ * Current cached value for the subscribed `(function_, args)` query, or
237
+ * `undefined` when nothing is subscribed/loaded for it. Reflects any
238
+ * optimistic override already written in this batch.
239
+ */
240
+ getQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>) => ReturnOf<F> | undefined;
241
+ /**
242
+ * Write an optimistic override for the subscribed `(function_, args)`
243
+ * query. A no-op (returns without effect) when no subscription matches —
244
+ * mirroring Convex, where you only patch queries the page is watching.
245
+ */
246
+ setQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>, value: ReturnOf<F> | undefined) => void;
247
+ }
248
+ /** A mutation's multi-query optimistic update: read/write the cache via `localStore`. */
249
+ type OptimisticUpdate<Args> = (localStore: OptimisticLocalStore, args: Args) => void;
250
+ /**
251
+ * Build an {@link OptimisticLocalStore} bound to a subscription registry and the
252
+ * mutation's shard key. Each `setQuery(value)` registers a constant-value layer
253
+ * on its target subscription (via `applyOptimisticLayer`): the predicted value
254
+ * survives incoming server deltas (re-clamped, masking concurrent changes to that
255
+ * query — not merged) and drops gaplessly on the mutation's commit cursor, like
256
+ * the single-query per-call `optimistic` path. Returns the store plus the ordered
257
+ * `confirm` (success) and `rollback` (failure) closures every `setQuery` produced,
258
+ * so the caller settles the whole batch when the mutation does.
259
+ */
260
+ declare const createLocalStore: (subscriptions: SubscriptionRegistry, shardKey: string | undefined) => {
261
+ confirms: ((commitCursor: number | undefined) => void)[];
262
+ rollbacks: (() => void)[];
263
+ store: OptimisticLocalStore;
264
+ };
265
+ declare const DEFAULT_MAX_BUFFER = 1024;
266
+ interface StreamHandle<T = unknown> {
267
+ /** Mark the stream complete (no more chunks); resolves any pending consumer to `done:true`. */
268
+ readonly complete: () => void;
269
+ /** Surface an error to any pending consumer; subsequent pushes are dropped. */
270
+ readonly fail: (error: Error) => void;
271
+ /**
272
+ * Push one chunk. Silent no-op once the stream is `complete`, `fail`-ed,
273
+ * or `cancel`-ed. When the buffer is already at `maxBuffer`, the stream
274
+ * is failed with a `STREAM_BACKPRESSURE` error and the push is dropped —
275
+ * the producer never sees a thrown exception.
276
+ */
277
+ readonly push: (value: T) => void;
278
+ }
279
+ interface StreamIterable<T> extends AsyncIterable<T> {
280
+ /** Cancel the stream from the consumer side: closes the iterator and notifies the registered canceller. */
281
+ cancel: () => void;
282
+ }
283
+ /**
284
+ * Build a stream handle paired with an async-iterable. The handle is the
285
+ * server-driven side (the WS dispatcher pushes chunks / completes / errors);
286
+ * the iterable is what the user awaits. `onCancel` is invoked exactly once
287
+ * when the consumer calls `.cancel()` (or `.return()`) so the client can
288
+ * send a `{type:"unsubscribe"}` frame to the server.
289
+ */
290
+ declare const createStream: <T>(options: {
291
+ maxBuffer?: number;
292
+ onCancel: () => void;
293
+ }) => {
294
+ handle: StreamHandle<T>;
295
+ iterable: StreamIterable<T>;
296
+ };
297
+ type WSState = "idle" | "connecting" | "open" | "closed";
298
+ /**
299
+ * Aggregate live-socket health across every shard connection, for a UI status
300
+ * indicator. `idle` = no socket opened yet; `connecting` = at least one socket
301
+ * is (re)connecting and none is open; `connected` = at least one socket is open;
302
+ * `offline` = sockets exist but all are down (between reconnect attempts).
303
+ */
304
+ type ConnectionStatus = "connected" | "connecting" | "idle" | "offline";
305
+ /** One shard's socket + watermark state in a {@link LunoraClient.debug} snapshot. */
306
+ interface ClientDebugShard {
307
+ /**
308
+ * Highest custom-mutator watermark the server has echoed for this client on this
309
+ * shard. A write whose `clientSeq` is above this has been sent but not confirmed
310
+ * — the first thing to check when an optimistic overlay won't clear.
311
+ */
312
+ confirmedMutationWatermark: number;
313
+ /** Whether a `WebSocket` object currently exists (distinct from it being open). */
314
+ hasSocket: boolean;
315
+ /** `undefined` for the default (unsharded) connection. */
316
+ shardKey: string | undefined;
317
+ /** Whether this shard's socket has ever completed a handshake — gates offline queueing. */
318
+ wasEverConnected: boolean;
319
+ wsState: WSState;
320
+ }
321
+ /** One live query or shape subscription in a {@link LunoraClient.debug} snapshot. */
322
+ interface ClientDebugSubscription {
323
+ /** Whether the server has acknowledged the subscription on the current socket. */
324
+ acked: boolean;
325
+ /** `namespace:fn` for a query, `shape:<name>` for a replication shape. */
326
+ functionPath: string;
327
+ id: string;
328
+ kind: "query" | "shape";
329
+ /** Highest custom-mutator watermark echoed on THIS subscription (absent until a `settled`/poke frame arrives). */
330
+ lastMutationId?: number;
331
+ /** Per-call optimistic layers still folded onto this subscription's value — a non-zero count with no pending write is a leak. */
332
+ pendingOptimisticLayers: number;
333
+ /** Replicated rowset size (shapes only). */
334
+ rowCount?: number;
335
+ /** The `__cdc_log` cursor the current value reflects. */
336
+ serverCursor?: number;
337
+ shardKey: string | undefined;
338
+ /** How many callers share this subscription (subscriptions are deduped by `(fn, args, shard)`). */
339
+ subscriberCount: number;
340
+ }
341
+ /**
342
+ * Everything the sync engine believes at one instant — see
343
+ * {@link LunoraClient.debug} for why this exists.
344
+ */
345
+ interface ClientDebugSnapshot {
346
+ /** The watermark key the server's custom-mutator protocol advances per `clientSeq`. */
347
+ clientId: string;
348
+ closed: boolean;
349
+ connectionStatus: ConnectionStatus;
350
+ /** Writes waiting in the built-in offline queue (not the `@lunora/db` outbox). */
351
+ pendingWrites: number;
352
+ shards: ClientDebugShard[];
353
+ subscriptions: ClientDebugSubscription[];
354
+ }
355
+ /**
356
+ * Terminal verdict for a mutation that passed through the offline queue,
357
+ * delivered to {@link LunoraClient.onMutationSettled}.
358
+ *
359
+ * Unlike the Promise returned by {@link LunoraClient.mutation} — which only the
360
+ * original caller can await, and which no longer exists after a reload — this
361
+ * fires for *every* queued write the server (or the queue) reaches a verdict on,
362
+ * including writes restored from durable storage in a later session. It is the
363
+ * channel a UI uses to tell the user "your queued change couldn't be saved"
364
+ * instead of silently dropping a rolled-back optimistic row.
365
+ *
366
+ * `status: "rejected"` carries the failure `code` (e.g. `CONFLICT`,
367
+ * `OFFLINE_QUEUE_OVERFLOW`, `OFFLINE_IDENTITY_CHANGED`) and the `error`.
368
+ * `hadAwaiter` is `false` for a write whose original `mutation()` Promise is
369
+ * gone (a hydrated/post-reload replay or an eviction), so a listener can tell
370
+ * "the caller already saw this" apart from "nothing else will report this".
371
+ */
372
+ interface MutationSettledEvent {
373
+ /** The write's args, so a listener can describe or re-offer the change. */
374
+ readonly args: Record<string, unknown>;
375
+ /** Server/queue error code on `rejected` (e.g. `CONFLICT`), when present. */
376
+ readonly code?: string;
377
+ /** The rejection error on `status: "rejected"`. */
378
+ readonly error?: unknown;
379
+ /** The `<file>:<function>` reference of the mutation. */
380
+ readonly functionPath: string;
381
+ /** Whether a live caller was still awaiting this write's `mutation()` Promise. */
382
+ readonly hadAwaiter: boolean;
383
+ /** The write's stable id (idempotency key / queue id). */
384
+ readonly id: string;
385
+ /** Shard the write targeted, if any. */
386
+ readonly shardKey?: string;
387
+ /** Terminal outcome. */
388
+ readonly status: "committed" | "rejected";
389
+ }
390
+ /**
391
+ * Per-call options for {@link LunoraClient.mutation} — the optimistic-update
392
+ * machinery plus `shardKey`. Exported (at the end of this file) so the framework
393
+ * adapters (`@lunora/react`, `/solid`, `/svelte`, `/vue`) can type their
394
+ * `mutate(args, options?)` against one canonical definition instead of
395
+ * re-declaring it.
396
+ */
397
+ interface MutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unknown> {
398
+ /**
399
+ * Override the auto-generated idempotency key (`x-lunora-mutation-id`). Lets a
400
+ * durable outbox replay a committed-but-unacked write under its *original* key
401
+ * so the server dedups it instead of applying it twice. Omit for normal calls —
402
+ * each then gets a fresh key.
403
+ */
404
+ mutationId?: string;
405
+ optimistic?: (current: TCurrent | undefined) => TValue;
406
+ /**
407
+ * Convex-parity multi-query optimistic update. Receives an
408
+ * `OptimisticLocalStore` over the live subscription cache plus the
409
+ * mutation's args, so one mutation can patch many subscribed queries at
410
+ * once; every write is rolled back atomically if the mutation fails.
411
+ */
412
+ optimisticUpdate?: OptimisticUpdate<TArgs>;
413
+ /**
414
+ * Sync predicate evaluated just before the offline queue replays this
415
+ * write on reconnect. When it returns `false` the mutation is dropped
416
+ * instead of replayed — use it to guard against replaying writes whose
417
+ * assumptions are no longer valid (e.g. the document it referred to was
418
+ * deleted by another client while this tab was offline).
419
+ */
420
+ precondition?: () => boolean;
421
+ shardKey?: string;
422
+ }
423
+ /** Callback a shape subscription invokes with its materialized rowset on every applied poke. */
424
+ type ShapeCallback = (rows: Record<string, unknown>[]) => void;
425
+ /**
426
+ * The high-water marks a shape poke has now synced to the client: `checkpoint`
427
+ * is the op-log cursor and `mutationId` the highest custom-mutator id the server
428
+ * echoed for this client. A `@lunora/db` collection feeds these into its
429
+ * checkpoint registry to drop optimistic overlays once the server's authoritative
430
+ * rows have landed.
431
+ */
432
+ interface SyncWatermark {
433
+ checkpoint?: number;
434
+ mutationId?: number;
435
+ }
436
+ /**
437
+ * An `Error` carrying the server's machine-readable `code` and (for a
438
+ * `LunoraError`) structured `data`, plus an optional actionable `hint` (Markdown)
439
+ * and `docsUrl` resolved from the central error catalog. The client's public
440
+ * error contract for RPC/batch failures — a UI can render `hint`/`docsUrl` to
441
+ * tell the user how to fix the error. The `(string & {})` arm keeps
442
+ * forward-compat/unknown server codes assignable without losing autocomplete on
443
+ * the known {@link LunoraErrorCode} union.
444
+ */
445
+ type LunoraClientError = Error & {
446
+ code?: LunoraErrorCode | (string & {});
447
+ data?: unknown;
448
+ docsUrl?: string;
449
+ hint?: string | string[];
450
+ };
451
+ /** One demuxed result slot of a {@link LunoraClient.batch} call (plan 088). */
452
+ type BatchSlot = {
453
+ error: LunoraClientError;
454
+ ok: false;
455
+ } | {
456
+ ok: true;
457
+ value: unknown;
458
+ };
459
+ /**
460
+ * Lunora browser/edge client. Talks RPC over HTTP and real-time deltas over
461
+ * a single multiplexed WebSocket.
462
+ *
463
+ * Reconnect, offline queueing, and optimistic updates are all handled here;
464
+ * see the package README for the wire protocol.
465
+ */
466
+ declare class LunoraClient {
467
+ /** 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. */
468
+ private static readonly MAX_POKE_BUFFERS;
469
+ /**
470
+ * Create a typed {@link ClientQueryRef}. Convenience wrapper around
471
+ * {@link createClientQuery} so you don't need a separate import.
472
+ * @example
473
+ * ```ts
474
+ * const sidebarOpen = LunoraClient.createClientQuery("sidebarOpen", true);
475
+ * ```
476
+ */
477
+ static createClientQuery<T>(key: string, defaultValue: T): ClientQueryRef<T>;
478
+ readonly url: string;
479
+ readonly wsUrl: string;
480
+ /** Local reactive store for {@link ClientQueryRef} values — no server round-trip. Private; reach it via `getClientQuery` / `setClientQuery` / `subscribeClientQuery`. */
481
+ private readonly clientQueryStore;
482
+ private wsToken;
483
+ /** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
484
+ private readonly authBasePath;
485
+ private readonly fetchImpl;
486
+ private readonly WebSocketImpl;
487
+ private readonly bookmark;
488
+ private readonly reconnectOptions;
489
+ /** WS connect timeout (ms); `0` disables it. See {@link LunoraClientOptions.connectTimeoutMs}. */
490
+ private readonly connectTimeoutMs;
491
+ /** Keepalive cadence (ms); `0` disables the heartbeat. See {@link LunoraClientOptions.heartbeatIntervalMs}. */
492
+ private readonly heartbeatIntervalMs;
493
+ private readonly offlineQueue;
494
+ /**
495
+ * Durable outbox seam (the `@lunora/db` `createExecutorOutboxSink`). When
496
+ * set, offline writes are delegated here and the built-in {@link OfflineQueue}
497
+ * is bypassed, so a db app has exactly one durable write path.
498
+ */
499
+ private readonly outbox;
500
+ /** Stable per-client id stamped onto every `OutboxMutation` (custom-mutator watermark). */
501
+ private readonly clientId;
502
+ /**
503
+ * `true` when the constructor's hydration microtask has finished loading the
504
+ * durable read cache (Pillar 2) into `hydratedQueryCache`. Signals that
505
+ * the cache is ready for synchronous `peekHydratedQuery` reads.
506
+ */
507
+ private readyResolved;
508
+ /** Resolvers for `whenReady()` — called once hydration completes. */
509
+ private readyResolve;
510
+ /**
511
+ * Promise that resolves once the durable read cache has been loaded. When
512
+ * `hydrateOnStart` is not set or no query cache is configured, resolves
513
+ * immediately (the constructor creates an already-resolved promise).
514
+ */
515
+ private readonly readyPromise;
516
+ /**
517
+ * Highest custom-mutator watermark the server has echoed for this client,
518
+ * keyed by shard bucket (`shardKey ?? ""`) since the DO tracks one
519
+ * `__client_watermark` per shard. `callMutator` bumps it from every
520
+ * ack; the `@lunora/db` mutator runtime seeds its `clientSeq` generator from
521
+ * it so a reload (which resets the in-memory counter) never reissues a stale
522
+ * sequence the server would silently swallow as a replay.
523
+ */
524
+ private readonly clientWatermarks;
525
+ /** Monotonic per-client mutation counter backing the server `__client_watermark`. */
526
+ private outboxMutationCounter;
527
+ private readonly onPersistenceError;
528
+ private readonly persistence;
529
+ /** App/schema version stamped on persisted writes + cached reads; mismatches are purged. */
530
+ private readonly persistenceVersion;
531
+ /** Releases the multi-tab outbox-leader Web Lock on close (see `hydrateAsOutboxLeader`). */
532
+ private outboxLeaderRelease;
533
+ /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
534
+ private readonly queryCache;
535
+ /**
536
+ * Values restored from the `queryCache` at construction, keyed by the
537
+ * read-cache key, awaiting the `subscribe()` that will consume them. A
538
+ * key is consumed (deleted) the first time its subscription is created, so
539
+ * the cache only ever seeds the initial value — live frames take over after.
540
+ */
541
+ private readonly hydratedQueryCache;
542
+ /**
543
+ * Coalesced read-cache writes: the latest value per key, flushed to
544
+ * the `queryCache` on a short debounce so a burst of deltas persists once.
545
+ */
546
+ private readonly pendingCacheWrites;
547
+ private cacheFlushTimer;
548
+ private readonly subscriptions;
549
+ /**
550
+ * Cross-tab coordinator; created only when `crossTabSync: true`. When the
551
+ * client is not the elected leader, all WebSocket operations are skipped.
552
+ * Not `readonly` — `close()` clears it (mirrors `outboxLeaderRelease`).
553
+ */
554
+ private tabCoordinator;
555
+ /**
556
+ * The leader's last-broadcast aggregate {@link ConnectionStatus}, mirrored
557
+ * on a follower tab — which owns no `ShardConnection` of its own to
558
+ * compute a status from (see `computeStatus`). `undefined` until the
559
+ * leader's first broadcast (falls back to `"idle"`), and reset back to
560
+ * `undefined` whenever this tab stops being a follower of the CURRENT
561
+ * leader (becomes leader itself, or the leader changes), so a stale
562
+ * mirror from a previous leader never survives a leadership change.
563
+ */
564
+ private leaderStatus;
565
+ /**
566
+ * Sticky "has the mirrored leader status ever reported `connected`" flag —
567
+ * the follower's counterpart to {@link ShardConnection.wasEverConnected},
568
+ * since a follower has no `ShardConnection` of its own. Feeds the
569
+ * offline-queue gate (see `mutation`) exactly like the real per-shard flag
570
+ * does on the leader/single-tab path.
571
+ */
572
+ private leaderWasEverConnected;
573
+ /** One {@link ShardConnection} per shard key (keyed by `shardKey ?? ""`). */
574
+ private readonly connections;
575
+ /** Default `connect`-envelope context applied to a shard with no explicit override. */
576
+ private readonly defaultConnectionContext;
577
+ /**
578
+ * Per-shard `connect`-envelope context registered via `setConnectionContext`
579
+ * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
580
+ * on every socket open so it replays across reconnects, and forwarded to the
581
+ * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
582
+ * imperative (last-writer-wins) override; refcounted holders registered via
583
+ * `acquireConnectionContext` live in `connectionContextHolders` and take
584
+ * precedence — see `effectiveConnectionContext`.
585
+ */
586
+ private readonly connectionContexts;
587
+ /**
588
+ * Per-shard stack of refcounted connection-context holders (keyed by
589
+ * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
590
+ * is an opaque token carrying its `context`; the most-recently acquired
591
+ * holder wins (last-writer-wins among live holders), and the context is only
592
+ * cleared for a shard once its last holder releases — so two concurrently
593
+ * mounted presence hooks on the same shard can't stomp each other's context
594
+ * on cleanup. A holder is identified by reference identity so a release
595
+ * removes exactly the right one regardless of stack position.
596
+ */
597
+ private readonly connectionContextHolders;
598
+ private authToken;
599
+ /**
600
+ * Optional STABLE identity subject (a user id), the basis of the offline-queue
601
+ * identity stamp when supplied. Keeps a same-user token *refresh* from looking
602
+ * like an identity change (which would discard queued writes). `undefined` =
603
+ * not supplied, so identity falls back to a hash of the raw token. See
604
+ * `setAuthToken` / `identityFingerprint`.
605
+ */
606
+ private authSubject;
607
+ /**
608
+ * Identity stamp recorded against each queued offline mutation, keyed by
609
+ * the queue-assigned mutation id. Captured at enqueue from the auth token
610
+ * in effect at the time, and re-checked at flush so a queued write can
611
+ * never replay under a different identity than the one that issued it.
612
+ * See `identityFingerprint` for the fingerprint shape.
613
+ */
614
+ private readonly queuedIdentities;
615
+ /**
616
+ * Distinct shard keys with a mutation currently sitting in `offlineQueue`
617
+ * — fresh writes queued this session (`enqueueOfflineMutation`) or writes
618
+ * restored from durable storage (`hydratePersistedQueue`). A follower tab
619
+ * has no per-shard `ShardConnection` to iterate when its mirrored leader
620
+ * status turns `"connected"` (see the `onConnectionStatus` coordinator
621
+ * option), so this is what that flush walks instead. Entries are never
622
+ * removed — flushing an already-empty shard is a cheap no-op, and the set
623
+ * is bounded by the app's own distinct shard-key cardinality.
624
+ */
625
+ private readonly queuedOfflineShardKeys;
626
+ private closed;
627
+ /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
628
+ private readonly authTokenListeners;
629
+ /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
630
+ private readonly statusListeners;
631
+ /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
632
+ private readonly tokenExpiredListeners;
633
+ /** Subscribers to offline-queued mutation verdicts (see `onMutationSettled`). */
634
+ private readonly mutationSettledListeners;
635
+ /** Subscribers to the offline-queue pending-count (see `onPendingChange`). */
636
+ private readonly pendingChangeListeners;
637
+ /**
638
+ * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
639
+ * of callbacks. Membership doubles as the resubscribe set replayed on every
640
+ * (re)connect so a topic survives a socket bounce.
641
+ */
642
+ private readonly whisperHandlers;
643
+ /** Last status broadcast, so we only notify listeners on an actual change. */
644
+ private lastStatus;
645
+ private nextSubId;
646
+ private nextStreamId;
647
+ /**
648
+ * In-flight client-side stream readers, keyed by the stream id sent on the
649
+ * wire. The handle drives the underlying iterator queue and `shardKey`
650
+ * tells us which socket to push the cancel frame onto when the consumer
651
+ * calls `.cancel()` or the iterator is garbage-collected.
652
+ */
653
+ private readonly streams;
654
+ /** Live shape subscriptions (partial replication), keyed by their wire id. */
655
+ private readonly shapeSubscriptions;
656
+ /** In-flight pokes being assembled between `pokeStart` and `pokeEnd`, keyed by `pokeId`. */
657
+ private readonly pokeBuffers;
658
+ private nextShapeId;
659
+ constructor(options: LunoraClientOptions);
660
+ /**
661
+ * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
662
+ * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
663
+ * sync across all mounted instances.
664
+ *
665
+ * Pass a STABLE `subject` (the user id) to key the offline-queue identity on
666
+ * it instead of the token bytes, so a token *refresh* (same user, new JWT)
667
+ * doesn't read as an identity change and discard queued writes. The subject is
668
+ * **sticky**: a later call that omits it (or passes `undefined`) keeps the
669
+ * established subject — so `setAuthToken(refreshedToken)` after a prior
670
+ * `setAuthToken(token, user.id)` retains the identity. Pass `null` to clear it
671
+ * (an explicit sign-out). Establishing the subject for the first time on an
672
+ * UNCHANGED token (e.g. the user id resolves a tick after the token was set)
673
+ * re-stamps any in-flight queued writes rather than dropping them — same
674
+ * credential, just a more stable label. A real user switch (the token AND
675
+ * subject both change) still drops the previous user's writes.
676
+ *
677
+ * Does NOT update the WebSocket auth — the WS token is fixed at upgrade
678
+ * time and lives in the URL. To refresh live WS auth, call
679
+ * {@link setWsToken} explicitly, which closes existing shard sockets to
680
+ * force a reconnect with the new credential.
681
+ */
682
+ setAuthToken(token: string | null, subject?: string | null): void;
683
+ getAuthToken(): string | null;
684
+ /**
685
+ * The current identity fingerprint (the same stamp queued offline writes
686
+ * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
687
+ * owns its own at-least-once replay outside the built-in `OfflineQueue` —
688
+ * can drop a persisted write whose captured `identity` no longer matches the
689
+ * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
690
+ */
691
+ currentIdentity(): string | null;
692
+ /** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
693
+ clientIdentifier(): string;
694
+ /**
695
+ * The highest custom-mutator watermark the server has echoed for this client
696
+ * on the given shard (0 if none yet). The `@lunora/db` mutator runtime seeds
697
+ * its `clientSeq` generator from this so a reload never reissues a sequence
698
+ * the server has already applied (which it would swallow as a replay, silently
699
+ * dropping the write).
700
+ */
701
+ confirmedMutationWatermark(shardKey?: string): number;
702
+ /**
703
+ * Push a custom mutator to its authoritative server impl over the watermark
704
+ * protocol (Phase 4): the request carries `x-lunora-client-id` + a monotonic
705
+ * `x-lunora-client-seq`, so the DO runs it exactly once and advances this
706
+ * client's `__client_watermark`.
707
+ *
708
+ * Returns the server `result` plus `applied`: `true` when the DO ran this push
709
+ * as the next-in-order mutation, `false` when it was a replay ack (`clientSeq`
710
+ * was at or below the stored watermark — e.g. a stale sequence after a reload).
711
+ * A `false` verdict tells the caller to reissue above the now-known watermark
712
+ * (echoed into {@link confirmedMutationWatermark}) rather than treat the benign
713
+ * ack as a confirmed write. Every ack — applied or not — bumps the watermark.
714
+ *
715
+ * This is the online transport for `@lunora/db`'s client-mutator runtime; the
716
+ * optimistic overlay + durable-outbox concerns live in that runtime, not here.
717
+ */
718
+ callMutator(functionPath: string, args: Record<string, unknown>, options?: {
719
+ clientSeq?: number;
720
+ shardKey?: string;
721
+ }): Promise<{
722
+ applied: boolean;
723
+ result: unknown;
724
+ }>;
725
+ /**
726
+ * Subscribe to auth-token changes. Returns an unsubscribe function. The
727
+ * listener is NOT invoked on registration — use {@link getAuthToken} for
728
+ * the current value.
729
+ */
730
+ onAuthTokenChange(listener: (token: string | null) => void): Unsubscribe;
731
+ /**
732
+ * Fetch the currently authenticated user from better-auth's `get-session`
733
+ * endpoint, returning the `user` record or `null` when signed out. Sends
734
+ * the stored bearer token (if any) and `credentials: "include"` so a
735
+ * cookie-session is also honoured. A network/parse failure or a non-OK
736
+ * response resolves to `null` rather than throwing — callers treat "couldn't
737
+ * resolve identity" as "signed out".
738
+ *
739
+ * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
740
+ * the token changes (that's what `@lunora/react`'s `useAuth` does).
741
+ */
742
+ getCurrentUser(): Promise<User | null>;
743
+ /**
744
+ * Replace the token appended to WS upgrade URLs as `?token=…` and close
745
+ * every open shard socket so the reconnect picks up the new value. Call
746
+ * this whenever the user's WS credential changes (rotating the admin token
747
+ * in the studio, switching workspaces, etc.). Accepts a static string or a
748
+ * {@link WsTokenProvider} resolved fresh at every (re)connect — the channel
749
+ * for short-lived credentials like the minted ephemeral admin sub-token.
750
+ * Bearer tokens for HTTP RPC are independent — see {@link setAuthToken}.
751
+ */
752
+ setWsToken(token: string | undefined | WsTokenProvider): void;
753
+ /**
754
+ * Register (or clear, with `undefined`) the app context sent in the `connect`
755
+ * envelope for a shard's socket, overriding the client-wide
756
+ * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
757
+ * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
758
+ * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
759
+ * presence row is removed the instant the socket drops, with no TTL lag.
760
+ *
761
+ * Stored per shard and replayed on every (re)connect. When a socket for the
762
+ * shard is already open, a fresh `connect` envelope is sent immediately so the
763
+ * server sees the new context without waiting for a reconnect.
764
+ */
765
+ setConnectionContext(context: Record<string, unknown> | undefined, options?: {
766
+ shardKey?: string;
767
+ }): void;
768
+ /**
769
+ * Refcounted variant of {@link setConnectionContext}: register a connection
770
+ * `context` for a shard and get back a release function. Unlike the imperative
771
+ * setter, the context is only cleared once the *last* acquired holder releases
772
+ * it — so two components (e.g. two mounted `usePresence` hooks) on the same
773
+ * shard no longer clobber each other's context when one of them unmounts. The
774
+ * most-recently acquired live holder wins (last-writer-wins), and releasing
775
+ * the top holder falls back to the previous one rather than clearing.
776
+ *
777
+ * With a single holder the behaviour is identical to a
778
+ * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
779
+ * Releasing more than once is a no-op (the holder is matched by reference, so
780
+ * a double release can't drop a different holder).
781
+ */
782
+ acquireConnectionContext(context: Record<string, unknown>, options?: {
783
+ shardKey?: string;
784
+ }): Unsubscribe;
785
+ /**
786
+ * Join a whisper `topic` and receive every ephemeral message other members
787
+ * broadcast to it on the same shard (typing indicators, live cursors,
788
+ * presence pings). Whispers never touch the server's durable state — there's
789
+ * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
790
+ * is left on the server once its last local handler unsubscribes.
791
+ *
792
+ * `handler` receives the raw `data` and the sender's verified `from` user id
793
+ * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
794
+ * (the default shard when omitted) — use the same shard you target with the
795
+ * matching queries/mutations so members land on the same Durable Object.
796
+ *
797
+ * Security: whisper topics are NOT access-controlled beyond the shard
798
+ * boundary — any client that can open a socket to the shard can join, read,
799
+ * and inject on any topic name. `from` is server-stamped and unforgeable, but
800
+ * do not put data on a whisper topic that some shard members shouldn't see,
801
+ * and don't trust a whisper's `data` as authorization. Use a query/mutation
802
+ * (with RLS) for anything privileged; whispers are for transient awareness.
803
+ */
804
+ whisperSubscribe(topic: string, handler: (data: unknown, from?: string) => void, options?: {
805
+ shardKey?: string;
806
+ }): Unsubscribe;
807
+ /**
808
+ * Broadcast an ephemeral `data` payload to the other members of a whisper
809
+ * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
810
+ * dropped when the shard socket isn't open (whispers are transient, never
811
+ * queued), and the server silently drops it if the sender exceeds its
812
+ * whisper rate budget. The sender never receives its own whisper. Omitting
813
+ * `data` delivers JSON `null` to receivers (not `undefined`).
814
+ */
815
+ whisper(topic: string, data?: unknown, options?: {
816
+ shardKey?: string;
817
+ }): void;
818
+ /**
819
+ * Subscribe to token-expiry events: invoked whenever the server drops a
820
+ * shard socket because the connection's credential lapsed (close code
821
+ * `4001`). The client already reconnects automatically (re-resolving
822
+ * identity from the cookie/token in effect); use this to refresh a
823
+ * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
824
+ * with a freshly minted one. Returns an unsubscribe function.
825
+ */
826
+ onTokenExpired(listener: () => void): Unsubscribe;
827
+ /**
828
+ * Current aggregate live-socket status across all shard connections. See
829
+ * {@link ConnectionStatus}.
830
+ */
831
+ connectionStatus(): ConnectionStatus;
832
+ /**
833
+ * Subscribe to aggregate connection-status changes. Invokes `listener`
834
+ * immediately with the current status, then on every transition. Returns an
835
+ * unsubscribe function.
836
+ */
837
+ onConnectionStatus(listener: (status: ConnectionStatus) => void): Unsubscribe;
838
+ /**
839
+ * Number of offline writes waiting in the built-in queue to be sent — the
840
+ * depth for a "N changes waiting to sync" indicator. Counts writes that are
841
+ * queued (offline / mid-reconnect), not ones already in flight on the wire.
842
+ * A `@lunora/db` app whose writes ride the unified outbox should read
843
+ * `LunoraDb.pendingCount()` instead (this counts only the built-in queue).
844
+ */
845
+ pendingCount(): number;
846
+ /**
847
+ * A point-in-time snapshot of everything the sync engine believes right now:
848
+ * per-shard sockets and watermarks, every live query and shape subscription with
849
+ * its cursor and ack state, and the offline-queue depth.
850
+ *
851
+ * This exists because the alternative is `console.log`. When an optimistic
852
+ * overlay doesn't clear, the questions are always the same — *is the socket open?
853
+ * what watermark has the server confirmed for this shard? has this shape been
854
+ * poked since my write? is anything stuck in the queue?* — and none of them were
855
+ * answerable from outside the client, so every adopter ends up instrumenting the
856
+ * library by hand or building a bespoke policy layer around a symptom.
857
+ *
858
+ * Read it from a devtools console, log it next to a bug report, or render it in a
859
+ * debug panel. Pull-only and allocation-cheap; nothing here is reactive, so poll
860
+ * it or read it on demand.
861
+ *
862
+ * ```ts
863
+ * const { shards, subscriptions } = client.debug();
864
+ * // shards: [{ shardKey: "user-1", wsState: "open", confirmedMutationWatermark: 42, … }]
865
+ * ```
866
+ */
867
+ debug(): ClientDebugSnapshot;
868
+ /**
869
+ * Subscribe to changes in {@link pendingCount}. Invokes `listener` immediately
870
+ * with the current count, then whenever the queue depth changes (a write is
871
+ * enqueued, flushed, or discarded). Returns an unsubscribe function.
872
+ */
873
+ onPendingChange(listener: (pending: number) => void): Unsubscribe;
874
+ /**
875
+ * Subscribe to terminal verdicts for offline-queued mutations. The listener
876
+ * fires once per queued write that commits or is rejected — including a write
877
+ * restored from durable storage after a reload, whose original `mutation()`
878
+ * Promise no longer exists (`hadAwaiter: false`), and a write the queue
879
+ * evicts on overflow or discards on an identity change. This is the durable
880
+ * channel for surfacing a rolled-back optimistic write to the UI; an online
881
+ * mutation that never queued still surfaces through the Promise `mutation()`
882
+ * returns. The listener is NOT invoked on registration. Returns an
883
+ * unsubscribe function. See {@link MutationSettledEvent}.
884
+ */
885
+ onMutationSettled(listener: (event: MutationSettledEvent) => void): Unsubscribe;
886
+ /**
887
+ * The `WebSocket` implementation this client was constructed with (an
888
+ * explicit `options.WebSocket`, or the ambient global on platforms that have
889
+ * one) — `undefined` if neither is available. This is the seam a feature
890
+ * that opens its OWN socket outside the client's multiplexed connection
891
+ * (e.g. a voice-agent hook) should default to, instead of reaching for
892
+ * `globalThis.WebSocket` directly: on React Native the client wraps this
893
+ * constructor to inject the auth-headers factory's credential onto the
894
+ * upgrade request (`createLunoraClient`'s `withAuthWebSocket`), which a raw
895
+ * `new globalThis.WebSocket(url)` would silently bypass.
896
+ */
897
+ getWebSocketImpl(): typeof WebSocket | undefined;
898
+ /**
899
+ * Read the current value for a {@link ClientQueryRef}. Returns
900
+ * `ref.defaultValue` when no value has been explicitly set.
901
+ */
902
+ getClientQuery<T>(ref: ClientQueryRef<T>): T;
903
+ /**
904
+ * Set a new value for `ref` and notify every subscriber. Pass `undefined`
905
+ * to reset the slot to `ref.defaultValue`.
906
+ */
907
+ setClientQuery<T>(ref: ClientQueryRef<T>, value: T): void;
908
+ /**
909
+ * Subscribe to changes for `ref`. The callback is NOT invoked on
910
+ * registration — call {@link getClientQuery} for the current value.
911
+ * Returns an unsubscribe function.
912
+ */
913
+ subscribeClientQuery(ref: ClientQueryRef, callback: (value: unknown) => void): Unsubscribe;
914
+ /**
915
+ * Reset a {@link ClientQueryRef} to its default value, notifying every
916
+ * subscriber. Equivalent to `setClientQuery(ref, ref.defaultValue)` but
917
+ * removes the stored entry so a future {@link getClientQuery} returns
918
+ * the default rather than an explicitly-set value.
919
+ */
920
+ resetClientQuery(ref: ClientQueryRef): void;
921
+ /**
922
+ * Capture a snapshot of the current live query value at call time and
923
+ * produce a `() => boolean` precondition that compares it against the
924
+ * value at replay time (on queue drain / reconnect).
925
+ *
926
+ * When the precondition is checked it re-reads the query's current value
927
+ * via `peekActiveQueryValue`. If the value differs from what was
928
+ * captured at call time the precondition returns `false` and the offline
929
+ * mutation is dropped as stale.
930
+ *
931
+ * This is a method wrapper around `createSnapshotPrecondition` that
932
+ * binds the client instance for you — no need to pass `client` explicitly.
933
+ * @example
934
+ * ```ts
935
+ * client.mutation(api.todos.update, { id, text }, {
936
+ * precondition: client.snapshotPrecondition(api.todos.list, { userId }),
937
+ * });
938
+ * ```
939
+ */
940
+ snapshotPrecondition(functionRef: FunctionReference, args: Record<string, unknown>, shardKey?: string): () => boolean;
941
+ /**
942
+ * Resolves once the durable read cache has been loaded into memory. When
943
+ * `hydrateOnStart` is not configured or no query cache adapter is active,
944
+ * returns an already-resolved promise so callers can always await it
945
+ * unconditionally.
946
+ *
947
+ * Framework adapters (React, Vue, etc.) use this to gate the first
948
+ * (enabled) render of a live query behind hydration, so the user sees
949
+ * cached data instead of an undefined flash before the socket round-trip.
950
+ */
951
+ whenReady(): Promise<void>;
952
+ /**
953
+ * Synchronously reports whether {@link whenReady} has already resolved (the
954
+ * durable read cache is loaded, or none is configured). Framework adapters
955
+ * read this to seed the hydration-gate state on the first render without
956
+ * awaiting, then subscribe via {@link whenReady} for the pending case.
957
+ */
958
+ get isReady(): boolean;
959
+ /**
960
+ * Synchronously peek at a value the durable read cache loaded for the given
961
+ * function path + args + shard key. Returns `undefined` when:
962
+ *
963
+ * - No query cache adapter is configured.
964
+ * - Hydration hasn't completed yet (race — await {@link whenReady} first).
965
+ * - The cached value's identity fingerprint doesn't match the current auth.
966
+ *
967
+ * Unlike the internal {@link takeHydratedCache}, this is a READ-ONLY peek:
968
+ * the cached entry stays in `hydratedQueryCache` so the subscription created
969
+ * later by {@link subscribe} consumes it normally.
970
+ */
971
+ peekHydratedQuery(functionPath: string, args: Record<string, unknown>, shardKey?: string): unknown;
972
+ /**
973
+ * Peek at the **current live value** of an active subscription, if one
974
+ * exists. Returns the subscription's `lastValue` (which includes any
975
+ * optimistic overlay) or `undefined` if no subscription is active for the
976
+ * given `(functionPath, args, shardKey)`.
977
+ *
978
+ * Unlike {@link peekHydratedQuery} (which reads from the durable read cache
979
+ * and is independent of active subscriptions), this method reflects the
980
+ * current in-memory state of an already-opened subscription — useful for
981
+ * offline mutation preconditions that need to snapshot the value at call time
982
+ * and compare it at replay time.
983
+ */
984
+ peekActiveQueryValue(functionPath: string, args: Record<string, unknown>, shardKey?: string): unknown;
985
+ query<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
986
+ shardKey?: string;
987
+ }): Promise<ReturnOf<F>>;
988
+ /**
989
+ * Batch several independent calls into ONE round trip (plan 088). Each call is
990
+ * dispatched server-side exactly as an individual RPC — per-shard
991
+ * authorization, `(identity, mutationId)` idempotency, and custom-mutator
992
+ * watermark ordering are all preserved — and the worker splits the batch by
993
+ * shard so calls to different shards fan out to their own DOs. Results are
994
+ * demuxed back in input order; a failing call does NOT fail the batch (its
995
+ * slot carries `{ ok: false, error }`, with `.code`/`.data` reconstructed like
996
+ * a single call). Args/results ride the value codec (bytes/bigint survive).
997
+ *
998
+ * No promise pipelining and no capability passing — a call's args cannot
999
+ * reference another call's result (see plan 088 §fence; capabilities are
1000
+ * incompatible with DO hibernation).
1001
+ */
1002
+ batch(calls: ReadonlyArray<{
1003
+ args?: Record<string, unknown>;
1004
+ fn: FunctionReference;
1005
+ shardKey?: string;
1006
+ }>): Promise<BatchSlot[]>;
1007
+ /**
1008
+ * Invoke a mutation. Errors propagate as rejections.
1009
+ *
1010
+ * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
1011
+ * only when the targeted shard's socket was open at least once already
1012
+ * (`wasEverConnected`), so the registry / resubscribe handshake has run.
1013
+ * Mutations issued before the very first WS connect to a shard fail fast.
1014
+ * Opt into queueing-before-first-connect via
1015
+ * `OfflineQueueOptions.queueBeforeFirstConnect`.
1016
+ */
1017
+ mutation<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>): Promise<ReturnOf<F>>;
1018
+ action<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
1019
+ shardKey?: string;
1020
+ }): Promise<ReturnOf<F>>;
1021
+ /**
1022
+ * Bulk-import `rows` through a mutation that accepts a batch, chunked so a large
1023
+ * dataset lands in a bounded number of round-trips.
1024
+ *
1025
+ * **Offline caveat:** each chunk is sent with {@link LunoraClient.mutation}, which
1026
+ * resolves once the write is durably queued rather than once the server has applied
1027
+ * it. So an import run while offline resolves `{ chunks, imported }` with nothing
1028
+ * committed yet — the counts describe what was *handed over*, and the outbox
1029
+ * replays them on reconnect. Don't report "migration complete" on this alone.
1030
+ *
1031
+ * This is the one-shot migration / seed path: "I have 20k rows client-side and a
1032
+ * server mutation that inserts many at once". Doing it by hand goes wrong in two
1033
+ * predictable ways — a serial per-row loop pays one round-trip *and* one watermark
1034
+ * wait per row (a 200-row import becomes 200 sequential hops), while a single
1035
+ * giant call blows the DO's batch limit. So: chunk, send sequentially, and give
1036
+ * each chunk a stable idempotency key derived from `importId` + its index, so a
1037
+ * resumed or retried import doesn't double-insert the chunks that already landed.
1038
+ *
1039
+ * The server mutation is yours (Lunora can't guess the table or the row shape);
1040
+ * back it with `ctx.db.insertMany(...)`, or `insertManyUnsafe(...)` for data you
1041
+ * vouch for. `chunkSize` defaults to 500, matching the DO's default batch cap.
1042
+ *
1043
+ * ```ts
1044
+ * await client.importRows(api.migrate.importNodes, nodes, {
1045
+ * importId: `migrate-${userId}`,
1046
+ * onProgress: ({ done, total }) => setProgress(done / total),
1047
+ * shardKey: userId,
1048
+ * toArgs: (chunk) => ({ nodes: chunk }),
1049
+ * });
1050
+ * ```
1051
+ */
1052
+ importRows(function_: FunctionReference, rows: ReadonlyArray<unknown>, options?: {
1053
+ /** Rows per call. Defaults to 500 — the DO's default batch cap. */
1054
+ chunkSize?: number;
1055
+ /**
1056
+ * Stable id for this import run. Each chunk is sent under
1057
+ * `${importId}:${chunkIndex}` as its mutation id, so re-running an import
1058
+ * that uses the SAME `chunkSize` re-sends each chunk under its prior key
1059
+ * and the server dedupes it instead of inserting twice.
1060
+ *
1061
+ * CAVEAT — the key is POSITIONAL, not content-based: it pins on the chunk
1062
+ * INDEX, not on the rows inside it. Resume or retry with a DIFFERENT
1063
+ * `chunkSize` (or a changed row ordering) and index N now covers different
1064
+ * rows than the first run's index N; the server sees a duplicate key and
1065
+ * SILENTLY DROPS those rows. Keep `chunkSize` (and the row order) identical
1066
+ * across resumes of the same `importId`. Omit `importId` only for a
1067
+ * throwaway import where double-insertion is acceptable.
1068
+ */
1069
+ importId?: string;
1070
+ /**
1071
+ * Called after each chunk is accepted — for a progress bar.
1072
+ *
1073
+ * "Accepted" is not always "committed": while offline (or mid-reconnect) a
1074
+ * `mutation` resolves as soon as the write is durably **queued**, so a fully
1075
+ * offline import reports completion with nothing yet applied server-side.
1076
+ * Gate a migration's "done" state on connectivity, not just on this.
1077
+ */
1078
+ onProgress?: (progress: {
1079
+ done: number;
1080
+ total: number;
1081
+ }) => void;
1082
+ /** Routes every chunk to one shard's DO. */
1083
+ shardKey?: string;
1084
+ /** Build the mutation args for one chunk. Defaults to `{ rows: chunk }`. */
1085
+ toArgs?: (chunk: ReadonlyArray<unknown>) => Record<string, unknown>;
1086
+ }): Promise<{
1087
+ chunks: number;
1088
+ imported: number;
1089
+ }>;
1090
+ /**
1091
+ * Read the cross-shard request distribution for a `.shardBy(...)` table —
1092
+ * the feed the studio's `hot_shard` advisor lint consumes. Hits the
1093
+ * admin-gated `POST /_lunora/admin/shard-traffic` endpoint, which fans the
1094
+ * cheap per-shard `getMetrics` read out across every live shard and returns
1095
+ * each shard's `{ shardKey, requests }` total (a failed shard surfaces with
1096
+ * `requests: 0`). Requires the worker to be built with a `queryCoordinator`
1097
+ * and `adminToken`, and this client's auth token to match; defaults any
1098
+ * absent field so an older worker yields an empty-but-valid shape.
1099
+ */
1100
+ shardTraffic(table: string): Promise<ShardTrafficResult>;
1101
+ /**
1102
+ * List the functions queued via `runAfter` / `runAt`, soonest-due last
1103
+ * (the worker returns them in storage order). Hits the admin-gated
1104
+ * `/_lunora/admin/scheduled` endpoint, so the worker must be built with a
1105
+ * `schedulerDO` namespace and `adminToken`, and this client's auth token
1106
+ * must match. Powers `@lunora/studio`'s scheduled-jobs panel.
1107
+ */
1108
+ listScheduledJobs(): Promise<ScheduleRecord[]>;
1109
+ /**
1110
+ * Read the app-level workpool backlog that powers `@lunora/studio`'s SLO
1111
+ * view: per-pool `{ name, queued, inFlight, maxConcurrency }` plus the
1112
+ * app-wide `backlog` (total queued) and `inFlight` (total held slots) sums.
1113
+ * Hits the admin-gated `GET /_lunora/admin/scheduled/status` endpoint, so the
1114
+ * same preconditions as {@link listScheduledJobs} apply (a `schedulerDO`
1115
+ * namespace + `adminToken` on the worker and a matching auth token here).
1116
+ * Defaults any absent field so an older worker still yields a valid shape.
1117
+ */
1118
+ schedulerStatus(): Promise<SchedulerStatus>;
1119
+ /** Cancel a pending scheduled job by id. Returns whether a job was removed. */
1120
+ cancelScheduledJob(id: string): Promise<{
1121
+ cancelled: boolean;
1122
+ }>;
1123
+ /**
1124
+ * List the dead-letter jobs: schedules that exhausted their retry budget
1125
+ * and were parked instead of dropped. These never appear in
1126
+ * {@link listScheduledJobs} (their live header is gone), so this is the only
1127
+ * way the studio surfaces a permanently-failed job. Hits the admin-gated
1128
+ * `GET /_lunora/admin/scheduled/dead`; same preconditions as
1129
+ * {@link listScheduledJobs}. Powers `@lunora/studio`'s dead-letter panel.
1130
+ */
1131
+ listDeadJobs(): Promise<ScheduleRecord[]>;
1132
+ /**
1133
+ * Resurrect a dead-letter job by id: it re-enters the schedule with a fresh
1134
+ * retry budget and fires on the next drain. Returns whether a parked record
1135
+ * matched. Hits the admin-gated `POST /_lunora/admin/scheduled/dead/retry`.
1136
+ */
1137
+ retryDeadJob(id: string): Promise<{
1138
+ retried: boolean;
1139
+ }>;
1140
+ /**
1141
+ * Permanently drop a dead-letter job by id (the operator has decided not to
1142
+ * recover it). Returns whether a parked record was removed. Hits the
1143
+ * admin-gated `POST /_lunora/admin/scheduled/dead/cancel`.
1144
+ */
1145
+ removeDeadJob(id: string): Promise<{
1146
+ removed: boolean;
1147
+ }>;
1148
+ /**
1149
+ * List a workflow's instances via the admin Workflows proxy
1150
+ * (`/_lunora/admin/workflows/instances`) — the Cloudflare control-plane data
1151
+ * the `Workflow` binding can't expose. Requires the worker to be built with a
1152
+ * `workflowsClient` (Cloudflare account id + API token). When one isn't
1153
+ * configured this does NOT reject: the proxy returns a `200 { configured:
1154
+ * false }` sentinel, so the result resolves with `configured === false` and an
1155
+ * empty `instances` list — callers should branch on that flag rather than
1156
+ * try/catch. (The instance-detail / status endpoints still reject with 501.)
1157
+ * `name` is the deployed workflow name.
1158
+ */
1159
+ listWorkflowInstances(options: {
1160
+ name: string;
1161
+ page?: number;
1162
+ perPage?: number;
1163
+ status?: WorkflowInstanceStatus;
1164
+ }): Promise<WorkflowInstancePage>;
1165
+ /** Read one workflow instance with its step timeline (`/_lunora/admin/workflows/instance`). */
1166
+ getWorkflowInstance(options: {
1167
+ id: string;
1168
+ name: string;
1169
+ }): Promise<WorkflowInstanceDetail>;
1170
+ /** Pause / resume / terminate a workflow instance (`/_lunora/admin/workflows/status`). Needs an Edit-scoped Cloudflare token. */
1171
+ setWorkflowInstanceStatus(options: {
1172
+ action: WorkflowInstanceAction;
1173
+ id: string;
1174
+ name: string;
1175
+ }): Promise<{
1176
+ status: WorkflowInstanceStatus;
1177
+ }>;
1178
+ /**
1179
+ * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
1180
+ * WebSocket. `onJobs` fires with the full list on connect and on every
1181
+ * change (schedule / cancel / alarm-fire). Reconnects with the client's
1182
+ * configured backoff. Requires `wsToken` to be set to an admin credential
1183
+ * (the browser can't send an `Authorization` header on a WS) — the master
1184
+ * token, or preferably a {@link WsTokenProvider} minting the ephemeral
1185
+ * sub-token so the master credential stays out of the URL. Returns an
1186
+ * unsubscribe function that closes the socket and stops reconnecting.
1187
+ */
1188
+ subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
1189
+ /**
1190
+ * List the registered public functions (queries / mutations / actions) with
1191
+ * their kinds. Hits the admin-gated `GET /_lunora/admin/functions` endpoint —
1192
+ * the worker must be built with a `functions` registry and `adminToken`, and
1193
+ * this client's auth token must match. Powers `@lunora/studio`'s function
1194
+ * runner auto-discovery.
1195
+ */
1196
+ listFunctions(): Promise<FunctionDescriptor[]>;
1197
+ /**
1198
+ * List the code-defined cron triggers (the `cronJobs()` map injected on the
1199
+ * worker), each flattened to its firing `cron` expression. Hits the
1200
+ * admin-gated `GET /_lunora/admin/cron-jobs` endpoint — the worker must be
1201
+ * built with a `cronJobs` map and `adminToken`, and this client's auth token
1202
+ * must match. These are static (Cloudflare exposes no runtime cron
1203
+ * introspection), so the studio renders them read-only alongside the dynamic
1204
+ * scheduler jobs.
1205
+ */
1206
+ getCronJobs(): Promise<CronJobInfo[]>;
1207
+ /**
1208
+ * Manually fire one code-defined cron job by name — the same dispatch the
1209
+ * scheduled trigger runs (dispatch the function, or start the durable
1210
+ * workflow), on demand. Hits the admin-gated `POST /_lunora/admin/cron-jobs/run`
1211
+ * endpoint; the worker must be built with a `cronJobs` map and `adminToken`,
1212
+ * and this client's auth token must match. Resolves when the job has run (a
1213
+ * function job's shard response is 2xx, or the workflow instance was created)
1214
+ * and rejects with the dispatch error otherwise.
1215
+ */
1216
+ runCronJob(name: string): Promise<{
1217
+ name: string;
1218
+ ran: boolean;
1219
+ }>;
1220
+ /**
1221
+ * Fetch the generated OpenAPI 3.1 document. Hits the admin-gated
1222
+ * `GET /_lunora/admin/openapi` endpoint — the worker must be built with an
1223
+ * `openApiSpec` and `adminToken`, and this client's auth token must match.
1224
+ * Powers `@lunora/studio`'s API-reference (Scalar) view. When the worker has
1225
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenAPI
1226
+ * document (no `paths`), so callers can render a "not configured" state.
1227
+ */
1228
+ fetchOpenApi(): Promise<Record<string, unknown>>;
1229
+ /**
1230
+ * Fetch the generated OpenRPC 1.x document. Hits the admin-gated
1231
+ * `GET /_lunora/admin/openrpc` endpoint — the worker must be built with an
1232
+ * `openRpcSpec` and `adminToken`, and this client's auth token must match.
1233
+ * OpenRPC is the RPC-native spec (a `methods` array over the JSON-RPC-shaped
1234
+ * `POST /_lunora/rpc` transport); it documents the RPC functions only.
1235
+ * Powers `@lunora/studio`'s OpenRPC API-reference view. When the worker has
1236
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenRPC
1237
+ * document (no `methods`), so callers can render a "not configured" state.
1238
+ */
1239
+ fetchOpenRpc(): Promise<Record<string, unknown>>;
1240
+ /**
1241
+ * List objects in the storage bucket, optionally under a `prefix` and from a
1242
+ * pagination `cursor`. Hits the admin-gated `GET /_lunora/admin/storage`
1243
+ * endpoint — the worker must be built with a `storageList` function and
1244
+ * `adminToken`, and this client's auth token must match. Powers
1245
+ * `@lunora/studio`'s file browser.
1246
+ */
1247
+ listStorageObjects(options?: {
1248
+ bucket?: string;
1249
+ cursor?: string;
1250
+ limit?: number;
1251
+ prefix?: string;
1252
+ }): Promise<StorageListPage>;
1253
+ /**
1254
+ * Delete one object from the storage bucket by key. Hits the admin-gated
1255
+ * `DELETE /_lunora/admin/storage?key=…` endpoint — the worker must be built
1256
+ * with a `storageDelete` function and `adminToken`. Powers the studio file
1257
+ * browser's per-row delete; resolves `{ deleted, key }`.
1258
+ */
1259
+ deleteStorageObject(key: string, options?: {
1260
+ bucket?: string;
1261
+ }): Promise<{
1262
+ deleted: boolean;
1263
+ key: string;
1264
+ }>;
1265
+ /**
1266
+ * List the storage bucket names the worker exposes, for the studio file
1267
+ * browser's bucket picker. Hits the admin-gated
1268
+ * `GET /_lunora/admin/storage/buckets` endpoint — always resolves (an empty
1269
+ * array when the worker configures no `storageBuckets`, i.e. single-bucket).
1270
+ */
1271
+ listStorageBuckets(): Promise<string[]>;
1272
+ /**
1273
+ * Upload one object to the storage bucket. Hits the admin-gated
1274
+ * `PUT /_lunora/admin/storage?key=…` endpoint with the raw body and an
1275
+ * optional `contentType` header — the worker must be built with a
1276
+ * `storageUpload` function and `adminToken`. Powers the studio file
1277
+ * browser's upload control; resolves `{ etag?, key }`.
1278
+ */
1279
+ uploadStorageObject(options: {
1280
+ body: ArrayBuffer | Blob;
1281
+ bucket?: string;
1282
+ contentType?: string;
1283
+ key: string;
1284
+ }): Promise<{
1285
+ etag?: string;
1286
+ key: string;
1287
+ }>;
1288
+ /**
1289
+ * Build a (signed or public) URL for one object. Hits the admin-gated
1290
+ * `GET /_lunora/admin/storage/url?key=…` endpoint — the worker must be built
1291
+ * with a `storageSignedUrl` function and `adminToken`. Powers the studio
1292
+ * file browser's copy-URL action; resolves the URL string.
1293
+ *
1294
+ * `options.expiresInSeconds` requests a share-link lifetime, which is
1295
+ * validated/clamped server-side. The options object mirrors the worker's
1296
+ * `StorageSignedUrlFunction` options (a `password` / download-limit are noted
1297
+ * as future fields there).
1298
+ */
1299
+ signedStorageUrl(key: string, options?: {
1300
+ bucket?: string;
1301
+ expiresInSeconds?: number;
1302
+ }): Promise<string>;
1303
+ /**
1304
+ * List the `.global()` (D1-backed) tables with their row counts. Hits the
1305
+ * admin-gated `GET /_lunora/admin/global/tables` endpoint — the worker must
1306
+ * be built with a `globalIntrospector` and `adminToken`. Powers the data
1307
+ * browser's global mode.
1308
+ */
1309
+ listGlobalTables(): Promise<GlobalTableInfo[]>;
1310
+ /**
1311
+ * Read a page of rows from one `.global()` table. `filters` AND-narrows the
1312
+ * page to rows matching each `column = value` eq constraint — the drill-down a
1313
+ * facet-value click applies; the array is JSON-encoded into the `filters`
1314
+ * query param and the values are bound server-side.
1315
+ */
1316
+ readGlobalTablePage(options: {
1317
+ filters?: GlobalFilterClause[];
1318
+ limit?: number;
1319
+ offset?: number;
1320
+ table: string;
1321
+ }): Promise<GlobalTablePage>;
1322
+ /**
1323
+ * Summarise the distinct values of one column in a `.global()` table over the
1324
+ * active view (the same eq `filters` the browser is previewing) — the global
1325
+ * twin of the shard browser's facet. Hits the admin-gated
1326
+ * `GET /_lunora/admin/global/facet` endpoint; `column` is validated + bound
1327
+ * server-side. Powers the global data browser's facet sidebar.
1328
+ */
1329
+ facetGlobalColumn(options: {
1330
+ column: string;
1331
+ filters?: GlobalFilterClause[];
1332
+ limit?: number;
1333
+ table: string;
1334
+ }): Promise<GlobalFacetResult>;
1335
+ /**
1336
+ * List the schema's Vectorize indexes with their declared shape (table,
1337
+ * field, dimensions, metric, metadata) and live stats (vector count,
1338
+ * processing watermark) when the binding is reachable. Hits the admin-gated
1339
+ * `GET /_lunora/admin/vector/indexes` endpoint — the worker must be built
1340
+ * with a `vectorIntrospector` and `adminToken`. Powers the studio's vector
1341
+ * browser. Vectorize can't enumerate indexes at runtime, so this list comes
1342
+ * from the generated `LUNORA_VECTOR_INDEXES` registry.
1343
+ */
1344
+ listVectorIndexes(): Promise<VectorIndexSummary[]>;
1345
+ /**
1346
+ * Run a nearest-neighbour similarity query against one vector index: the
1347
+ * worker embeds `text` via the index's embedder and returns the top matches.
1348
+ * Hits the admin-gated `POST /_lunora/admin/vector/query` endpoint. Throws
1349
+ * `VECTOR_QUERY_UNSUPPORTED` when the worker's introspector has no embedder
1350
+ * wired (the index lists read-only).
1351
+ */
1352
+ queryVectorIndex(options: {
1353
+ name: string;
1354
+ text: string;
1355
+ topK?: number;
1356
+ }): Promise<VectorQueryMatch[]>;
1357
+ /**
1358
+ * Read one keyset-paginated page of the durable `ctx.log` archive that
1359
+ * `pipelineLogSink` writes to R2. Server-side only — the worker holds the R2
1360
+ * SQL credentials and runs the reader; the browser only sees the decoded
1361
+ * `{ rows, nextCursor }`. Pass the previous page's `nextCursor` as
1362
+ * `query.cursor` to page. Admin-gated. When the operator hasn't wired the
1363
+ * archive, `adminFetch` throws a `LunoraClientError` with `.code ===
1364
+ * "LOG_ARCHIVE_NOT_CONFIGURED"`, so a caller can render a "not configured"
1365
+ * state rather than an error.
1366
+ */
1367
+ queryLogArchive(query?: PipelineLogQuery): Promise<PipelineLogPage>;
1368
+ /**
1369
+ * List the worker's registered Workers KV namespaces (binding names). Hits
1370
+ * the admin-gated `GET /_lunora/admin/kv/namespaces` endpoint — the worker
1371
+ * must be built with a `kvIntrospector` and `adminToken`. Powers the
1372
+ * studio's KV browser.
1373
+ */
1374
+ listKvNamespaces(): Promise<KvNamespaceSummary[]>;
1375
+ /**
1376
+ * List keys in a KV namespace, optionally filtered by `prefix` and
1377
+ * paginated via `cursor`. Hits the admin-gated
1378
+ * `GET /_lunora/admin/kv/keys` endpoint.
1379
+ */
1380
+ listKvKeys(options: {
1381
+ cursor?: string;
1382
+ limit?: number;
1383
+ namespace: string;
1384
+ prefix?: string;
1385
+ }): Promise<KvKeyListResult>;
1386
+ /**
1387
+ * Read a KV value (as text) and its metadata. Hits the admin-gated
1388
+ * `GET /_lunora/admin/kv/value` endpoint. Returns `{ value: null, metadata: null }`
1389
+ * when the key is absent.
1390
+ */
1391
+ getKvValue(options: {
1392
+ key: string;
1393
+ namespace: string;
1394
+ }): Promise<KvValueResult>;
1395
+ /**
1396
+ * Write a string value to a KV namespace. Accepts an absolute `expiration`
1397
+ * (Unix seconds) or a relative `expirationTtl`, plus optional `metadata` —
1398
+ * re-send the loaded values on edit so a save preserves rather than clears
1399
+ * them. Hits the admin-gated `PUT /_lunora/admin/kv/value` endpoint.
1400
+ */
1401
+ putKvValue(options: {
1402
+ expiration?: number;
1403
+ expirationTtl?: number;
1404
+ key: string;
1405
+ metadata?: unknown;
1406
+ namespace: string;
1407
+ value: string;
1408
+ }): Promise<void>;
1409
+ /**
1410
+ * Delete a key from a KV namespace. No-op when the key is absent. Hits the
1411
+ * admin-gated `DELETE /_lunora/admin/kv/value` endpoint.
1412
+ */
1413
+ deleteKvKey(options: {
1414
+ key: string;
1415
+ namespace: string;
1416
+ }): Promise<void>;
1417
+ /**
1418
+ * List authenticated users, paged and optionally searched / filtered / sorted.
1419
+ * Hits the admin-gated `GET /_lunora/admin/auth/users` endpoint — the worker
1420
+ * must be built with an `authAdmin` and `adminToken`. Powers the studio's
1421
+ * users dashboard.
1422
+ */
1423
+ listAuthUsers(options?: {
1424
+ filterField?: string;
1425
+ filterValue?: string;
1426
+ limit?: number;
1427
+ offset?: number;
1428
+ search?: string;
1429
+ searchField?: string;
1430
+ sortBy?: string;
1431
+ sortDirection?: "asc" | "desc";
1432
+ }): Promise<AuthPage<AuthUser>>;
1433
+ /**
1434
+ * Create a user. Hits the admin-gated `POST /_lunora/admin/auth/users/create`
1435
+ * endpoint (requires the worker's `authAdmin` to implement `createUser`).
1436
+ * `data` carries any app-defined `user.additionalFields`.
1437
+ */
1438
+ createAuthUser(input: {
1439
+ data?: Record<string, unknown>;
1440
+ email: string;
1441
+ name: string;
1442
+ password?: string;
1443
+ role?: string | string[];
1444
+ }): Promise<AuthUser>;
1445
+ /** Set a user's role (string, or array joined comma-wise server-side). */
1446
+ setAuthUserRole(input: {
1447
+ role: string | string[];
1448
+ userId: string;
1449
+ }): Promise<AuthUser>;
1450
+ /** Ban a user. `expiresInSeconds` sets a temporary ban; omit it for a permanent one. Revokes the user's live sessions. */
1451
+ banAuthUser(input: {
1452
+ expiresInSeconds?: number;
1453
+ reason?: string;
1454
+ userId: string;
1455
+ }): Promise<AuthUser>;
1456
+ /** Lift a user's ban. */
1457
+ unbanAuthUser(input: {
1458
+ userId: string;
1459
+ }): Promise<AuthUser>;
1460
+ /** Set a user's password (admin override — no current-password challenge). */
1461
+ setAuthUserPassword(input: {
1462
+ newPassword: string;
1463
+ userId: string;
1464
+ }): Promise<void>;
1465
+ /** Permanently delete a user and revoke their sessions. */
1466
+ removeAuthUser(input: {
1467
+ userId: string;
1468
+ }): Promise<void>;
1469
+ /**
1470
+ * Mint an impersonation session for a user, returning its bearer `token`.
1471
+ * The caller is responsible for using the token (e.g. setting the session
1472
+ * cookie); the server performs no cookie round-trip.
1473
+ */
1474
+ impersonateAuthUser(input: {
1475
+ userId: string;
1476
+ }): Promise<AuthImpersonation>;
1477
+ /** Revoke a single session by its id (force sign-out of one device). */
1478
+ revokeAuthSession(input: {
1479
+ sessionId: string;
1480
+ }): Promise<void>;
1481
+ /** Revoke every session for a user (force sign-out everywhere). */
1482
+ revokeAuthUserSessions(input: {
1483
+ userId: string;
1484
+ }): Promise<void>;
1485
+ /**
1486
+ * Report which auth dashboard surfaces are available — derived server-side
1487
+ * from the enabled better-auth plugins. The studio renders only the panels
1488
+ * whose capability is `true`.
1489
+ */
1490
+ getAuthCapabilities(): Promise<AuthCapabilities>;
1491
+ /** Update a user's fields (name/email/app-defined `additionalFields`). */
1492
+ updateAuthUser(input: {
1493
+ data: Record<string, unknown>;
1494
+ userId: string;
1495
+ }): Promise<AuthUser>;
1496
+ /** List a user's linked accounts (credential / OAuth providers). Token material is stripped server-side. */
1497
+ listAuthAccounts(input: {
1498
+ userId: string;
1499
+ }): Promise<Record<string, unknown>[]>;
1500
+ /** Unlink a linked account from a user. */
1501
+ unlinkAuthAccount(input: {
1502
+ accountId: string;
1503
+ userId: string;
1504
+ }): Promise<void>;
1505
+ /** List a user's registered passkeys (requires the passkey plugin). */
1506
+ listAuthPasskeys(input: {
1507
+ userId: string;
1508
+ }): Promise<Record<string, unknown>[]>;
1509
+ /** Delete a passkey by id (requires the passkey plugin). */
1510
+ deleteAuthPasskey(input: {
1511
+ passkeyId: string;
1512
+ }): Promise<void>;
1513
+ /** Disable two-factor auth for a user (requires the two-factor plugin). */
1514
+ disableAuthTwoFactor(input: {
1515
+ userId: string;
1516
+ }): Promise<void>;
1517
+ /** List organizations, paged (requires the organization plugin). */
1518
+ listAuthOrganizations(options?: {
1519
+ limit?: number;
1520
+ offset?: number;
1521
+ }): Promise<AuthPage<Record<string, unknown>>>;
1522
+ /** List the members of an organization (requires the organization plugin). */
1523
+ listAuthOrgMembers(input: {
1524
+ limit?: number;
1525
+ offset?: number;
1526
+ organizationId: string;
1527
+ }): Promise<AuthPage<Record<string, unknown>>>;
1528
+ /** List an organization's pending invitations (requires the organization plugin). */
1529
+ listAuthOrgInvitations(input: {
1530
+ limit?: number;
1531
+ offset?: number;
1532
+ organizationId: string;
1533
+ }): Promise<AuthPage<Record<string, unknown>>>;
1534
+ /** Remove a member from an organization. */
1535
+ removeAuthOrgMember(input: {
1536
+ memberId: string;
1537
+ }): Promise<void>;
1538
+ /** Cancel a pending organization invitation. */
1539
+ cancelAuthOrgInvitation(input: {
1540
+ invitationId: string;
1541
+ }): Promise<void>;
1542
+ /**
1543
+ * Report the deployment's auth configuration — enabled plugins, sign-in
1544
+ * methods, user-settable create-user fields, organization sub-features
1545
+ * (teams / roles), and session / rate-limit policy. Drives the config panel
1546
+ * and the dynamic create-user form. Never carries a secret.
1547
+ */
1548
+ getAuthConfig(): Promise<AuthConfigInfo>;
1549
+ /** Create an organization; optionally seed an `owner` member for `ownerId`. */
1550
+ createAuthOrganization(input: {
1551
+ logo?: string;
1552
+ metadata?: Record<string, unknown>;
1553
+ name: string;
1554
+ ownerId?: string;
1555
+ slug?: string;
1556
+ }): Promise<Record<string, unknown>>;
1557
+ /** Update an organization's name/slug/logo/metadata. */
1558
+ updateAuthOrganization(input: {
1559
+ logo?: string;
1560
+ metadata?: Record<string, unknown>;
1561
+ name?: string;
1562
+ organizationId: string;
1563
+ slug?: string;
1564
+ }): Promise<Record<string, unknown>>;
1565
+ /** Delete an organization and cascade its members, invitations, teams, and custom roles. */
1566
+ deleteAuthOrganization(input: {
1567
+ organizationId: string;
1568
+ }): Promise<void>;
1569
+ /** Directly add an existing user to an organization (no invitation/acceptance). */
1570
+ addAuthOrgMember(input: {
1571
+ organizationId: string;
1572
+ role?: string;
1573
+ userId: string;
1574
+ }): Promise<Record<string, unknown>>;
1575
+ /** Create a pending email invitation to an organization. */
1576
+ inviteAuthOrgMember(input: {
1577
+ email: string;
1578
+ inviterId?: string;
1579
+ organizationId: string;
1580
+ role?: string;
1581
+ }): Promise<Record<string, unknown>>;
1582
+ /** Change a member's role. */
1583
+ setAuthOrgMemberRole(input: {
1584
+ memberId: string;
1585
+ role: string | string[];
1586
+ }): Promise<Record<string, unknown>>;
1587
+ /** List an organization's teams (requires the organization plugin with teams enabled). */
1588
+ listAuthOrgTeams(input: {
1589
+ limit?: number;
1590
+ offset?: number;
1591
+ organizationId: string;
1592
+ }): Promise<AuthPage<Record<string, unknown>>>;
1593
+ /** Create a team under an organization. */
1594
+ createAuthOrgTeam(input: {
1595
+ name: string;
1596
+ organizationId: string;
1597
+ }): Promise<Record<string, unknown>>;
1598
+ /** Rename a team. */
1599
+ updateAuthOrgTeam(input: {
1600
+ name: string;
1601
+ teamId: string;
1602
+ }): Promise<Record<string, unknown>>;
1603
+ /** Delete a team and its memberships. */
1604
+ removeAuthOrgTeam(input: {
1605
+ teamId: string;
1606
+ }): Promise<void>;
1607
+ /** List a team's members. */
1608
+ listAuthOrgTeamMembers(input: {
1609
+ limit?: number;
1610
+ offset?: number;
1611
+ teamId: string;
1612
+ }): Promise<AuthPage<Record<string, unknown>>>;
1613
+ /** Add a user to a team. */
1614
+ addAuthOrgTeamMember(input: {
1615
+ teamId: string;
1616
+ userId: string;
1617
+ }): Promise<Record<string, unknown>>;
1618
+ /** Remove a member from a team. */
1619
+ removeAuthOrgTeamMember(input: {
1620
+ teamMemberId: string;
1621
+ }): Promise<void>;
1622
+ /** List an organization's custom roles (requires the organization plugin with dynamic access control). */
1623
+ listAuthOrgRoles(input: {
1624
+ limit?: number;
1625
+ offset?: number;
1626
+ organizationId: string;
1627
+ }): Promise<AuthPage<Record<string, unknown>>>;
1628
+ /** Create a custom org role with a permission grant (a `resource -> actions[]` map). */
1629
+ createAuthOrgRole(input: {
1630
+ organizationId: string;
1631
+ permission: Record<string, string[]>;
1632
+ role: string;
1633
+ }): Promise<Record<string, unknown>>;
1634
+ /** Replace a custom org role's permission grant. */
1635
+ updateAuthOrgRole(input: {
1636
+ permission: Record<string, string[]>;
1637
+ roleId: string;
1638
+ }): Promise<Record<string, unknown>>;
1639
+ /** Delete a custom org role. */
1640
+ deleteAuthOrgRole(input: {
1641
+ roleId: string;
1642
+ }): Promise<void>;
1643
+ /** List auth sessions, paged and optionally filtered to one user. */
1644
+ listAuthSessions(options?: {
1645
+ limit?: number;
1646
+ offset?: number;
1647
+ userId?: string;
1648
+ }): Promise<AuthPage<AuthSession>>;
1649
+ subscribe<F extends FunctionReference>(function_: F, args: ArgsOf<F>, callback: (data: ReturnOf<F>) => void, options?: {
1650
+ onCheckpoint?: (watermark: SyncWatermark) => void;
1651
+ onError?: SubscriptionErrorCallback;
1652
+ shardKey?: string;
1653
+ }): Unsubscribe;
1654
+ /**
1655
+ * Subscribe to a declarative **shape** — server-side partial replication
1656
+ * scoped by `shardBy` + the shape's predicate + RLS. The parallel to
1657
+ * {@link subscribe} for the poke protocol: the client sends the shape *name* +
1658
+ * validated `args` (never a `where` the client could forge), the server seeds
1659
+ * the current membership as an insert-poke and streams live membership diffs.
1660
+ * Each applied poke materializes the shape's rowset and invokes `callback`.
1661
+ *
1662
+ * Unlike {@link subscribe}, shape subscriptions are NOT deduped by
1663
+ * (name, args): the server resolves them under the socket's verified identity,
1664
+ * so every call gets its own id + view. The returned function unsubscribes.
1665
+ */
1666
+ subscribeShape(shape: {
1667
+ args?: Record<string, unknown>;
1668
+ name: string;
1669
+ }, callback: ShapeCallback, options?: {
1670
+ onCheckpoint?: (watermark: SyncWatermark) => void;
1671
+ onError?: SubscriptionErrorCallback;
1672
+ shardKey?: string;
1673
+ }): Unsubscribe;
1674
+ /**
1675
+ * Open a streaming query. The function reference must be a
1676
+ * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
1677
+ * the type constraint catches accidental use of a query/mutation/action
1678
+ * reference at compile time. The returned iterable yields one element per
1679
+ * chunk frame the server pushes, terminating when the server sends
1680
+ * `complete` or the consumer calls `.cancel()`. Errors arrive as a
1681
+ * rejection on the next `next()`.
1682
+ *
1683
+ * Streams ride the same WS as subscriptions and share the unsubscribe
1684
+ * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id,
1685
+ * which the DO recognises as an abort signal for the in-flight iterator.
1686
+ *
1687
+ * Stream-start frames buffered while the socket is (re)connecting are
1688
+ * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
1689
+ * cap drops the oldest queued frame (and fails its consumer) so a stuck
1690
+ * reconnect can't OOM the page.
1691
+ */
1692
+ stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F>, options?: {
1693
+ maxBuffer?: number;
1694
+ shardKey?: string;
1695
+ }): StreamIterable<ReturnOf<F>>;
1696
+ /**
1697
+ * Open a typed **HTTP-SSE route stream** (`httpRoute.<verb>(path).stream()`).
1698
+ * Distinct from {@link LunoraClient.stream}, which consumes the WS procedure
1699
+ * stream (`kind: "stream"`): this one opens the route's own URL with `fetch`
1700
+ * and parses the Server-Sent Events framing the route pump writes (`data:`
1701
+ * chunks, a final `event: complete`, an `event: error` on throw).
1702
+ *
1703
+ * The reference comes from the generated `httpStreams.*` registry, so the
1704
+ * yielded chunk type is the route handler's yielded type. Cancelling the
1705
+ * returned iterable (or aborting `options.signal`) aborts the fetch, which
1706
+ * the server handler observes via its `signal`. The client's bearer token
1707
+ * (when set) rides as an `authorization` header.
1708
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
1709
+ */
1710
+ httpStream<Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: {
1711
+ headers?: Record<string, string>;
1712
+ maxBuffer?: number;
1713
+ signal?: AbortSignal;
1714
+ }): StreamIterable<HttpStreamChunkOf<Ref>>;
1715
+ close(): void;
1716
+ /** Guard shared by every public entry point: a closed client accepts no further calls. */
1717
+ private assertOpen;
1718
+ /**
1719
+ * Tear down one {@link ShardConnection}'s live state: clear its reconnect/
1720
+ * connect timers, stop its heartbeat, and close its socket (if any).
1721
+ * Shared by `close()` (terminal) and the cross-tab `onStopBeingLeader`
1722
+ * handler (demoted, but still alive) so a demoted leader can't leak a
1723
+ * pending `reconnectTimer` or an open socket's `heartbeatTimer` the way
1724
+ * an inline `conn.socket?.close()` — which skips both — used to.
1725
+ */
1726
+ private teardownConnection;
1727
+ /**
1728
+ * Build (but do not start) this client's `TabCoordinator`. Extracted out of
1729
+ * the constructor so `setAuthToken` can rebuild it on an identity change —
1730
+ * the default channel name embeds the identity fingerprint (see below), so
1731
+ * a new identity needs a new coordinator on a new channel. The callback
1732
+ * bodies are the drift-sensitive region (a hand-merged identity guard on
1733
+ * the shard message listener sits ahead of an extracted `lastFrameAt`
1734
+ * stamp elsewhere in this file) — moved verbatim, not reflowed.
1735
+ */
1736
+ private createTabCoordinator;
1737
+ /**
1738
+ * Persist a mutation that can't go out on the wire right now (offline, or
1739
+ * mid-reconnect after a prior connect). The optimistic update has already
1740
+ * been applied by `mutation`; this only chooses the durable write path and
1741
+ * rolls the optimistic write back if persistence is rejected.
1742
+ *
1743
+ * Two paths: when an `outbox` sink is wired (the `@lunora/db` executor) it
1744
+ * owns persistence + at-least-once replay, so we delegate and return
1745
+ * optimistically (confirmation rides the synced view). Otherwise the
1746
+ * built-in `OfflineQueue` resolves/rejects the returned promise on replay.
1747
+ */
1748
+ private enqueueOfflineMutation;
1749
+ /**
1750
+ * Restore offline mutations persisted in a prior session and open a socket
1751
+ * for each shard they target so they flush once the WS reconnects. Failures
1752
+ * are swallowed — a broken durable store must not stop the client booting.
1753
+ */
1754
+ private hydratePersistedQueue;
1755
+ /**
1756
+ * Re-queue the durable offline writes — but only as the multi-tab LEADER. The
1757
+ * persisted queue is shared across a profile's tabs; without coordination
1758
+ * every tab would re-queue and replay the same writes (correct only because
1759
+ * the server dedups by idempotency key, but wasteful + racy). A Web Lock makes
1760
+ * exactly one tab hydrate; it holds the lock for its lifetime, so when it
1761
+ * closes another tab acquires the lock and takes over. Falls back to
1762
+ * unconditional hydration where Web Locks are unavailable (React Native, older
1763
+ * browsers, SSR) — single-context there, so no coordination is needed.
1764
+ */
1765
+ private hydrateAsOutboxLeader;
1766
+ /**
1767
+ * Load every cached query into {@link hydratedQueryCache} so the next
1768
+ * `subscribe()` for each key seeds its initial value off disk. A
1769
+ * subscription created before this resolves simply misses the cache (it
1770
+ * gets a live snapshot as before); the gate at seed time also drops any
1771
+ * entry whose stamped identity no longer matches the current one.
1772
+ */
1773
+ private hydrateQueryCache;
1774
+ /**
1775
+ * Consume the hydrated read-cache entry for a key (if any), gated on
1776
+ * identity. The entry is removed whether or not it matches — the cache only
1777
+ * ever seeds a subscription's first value. A mismatch (the cache was written
1778
+ * under a different identity) yields `undefined` so a signed-out cache never
1779
+ * leaks into a new session.
1780
+ */
1781
+ private takeHydratedCache;
1782
+ /**
1783
+ * Queue a coalesced read-cache write for a subscription's current value.
1784
+ * Latest-wins per key; flushed on a short debounce so a delta burst writes
1785
+ * once. No-op when the read cache is disabled or the value is undefined
1786
+ * (nothing to render offline).
1787
+ */
1788
+ private persistQueryValue;
1789
+ /** Drain {@link pendingCacheWrites} to the durable store. */
1790
+ private flushQueryCacheWrites;
1791
+ /** Derive the aggregate status from the per-shard socket states. */
1792
+ private computeStatus;
1793
+ /** Recompute the aggregate status and notify listeners if it changed. */
1794
+ private emitConnectionStatus;
1795
+ /**
1796
+ * Build a {@link MutationSettledEvent} from a queued entry and emit it on the
1797
+ * {@link onMutationSettled} channel. `item.id` is always assigned by the time
1798
+ * a write settles (`enqueue`/`hydrate` guarantee it), so the `?? ""` fallback
1799
+ * is unreachable — present only to satisfy the optional queue-id type.
1800
+ */
1801
+ private emitItemSettled;
1802
+ /**
1803
+ * Apply an optimistic update to the subscription that matches the mutation's
1804
+ * `(functionRef, args, shardKey)` triple, returning the rollback callbacks to
1805
+ * invoke if the mutation later fails.
1806
+ *
1807
+ * The registry is already indexed by exactly this triple via
1808
+ * `SubscriptionRegistry.key`, so at most one subscription can match. A direct
1809
+ * O(1) keyed lookup replaces the former O(N) linear scan over all subscriptions.
1810
+ *
1811
+ * `shardKey` normalization: both `undefined` and `""` map to the empty string
1812
+ * inside `SubscriptionRegistry.key` (via `?? ""`), so a mutation fired without
1813
+ * a shardKey correctly matches a subscription registered without one regardless
1814
+ * of whether the caller passed `undefined` or omitted the field.
1815
+ */
1816
+ private applyOptimisticUpdates;
1817
+ /**
1818
+ * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
1819
+ * to the live subscription registry. Each `setQuery` registers a constant
1820
+ * optimistic LAYER on its target subscription (via the same engine the
1821
+ * per-call `optimistic` path uses), so the multi-query patch rebases onto
1822
+ * incoming deltas and drops gaplessly on its commit cursor — its `confirm` /
1823
+ * `rollback` closures are appended to the mutation's settle lists. A throwing
1824
+ * callback unwinds its own partial writes — LIFO over just the rollbacks it
1825
+ * produced — and is swallowed, so a buggy optimistic update can never fail the
1826
+ * mutation or leave a partial patch live.
1827
+ */
1828
+ private applyOptimisticUpdate;
1829
+ private getConnection;
1830
+ /**
1831
+ * Send an unsubscribe frame (tagged with its wire type) on the shard's
1832
+ * socket, or queue it for the next reconnect when the send can't go out.
1833
+ */
1834
+ private sendOrQueueUnsubscribe;
1835
+ /**
1836
+ * The `(wsState, hasSocket, wasEverConnected)` triple `mutation()`'s
1837
+ * offline-queue gate reads. On the leader/single-tab path this is exactly
1838
+ * the real `ShardConnection`'s state (byte-identical to the pre-cross-tab
1839
+ * behavior). A follower has no `ShardConnection` of its own (see
1840
+ * `ensureSocket`), so it derives the same triple from the mirrored
1841
+ * `leaderStatus`/`leaderWasEverConnected` instead: `"connected"` maps to
1842
+ * `"open"` (queue-eligible once `wasEverConnected`), `"connecting"` stays
1843
+ * `"connecting"` (the mid-reconnect queue branch), anything else is
1844
+ * `"idle"`. `hasSocket` is always `false` for a follower — it never has
1845
+ * one.
1846
+ */
1847
+ private connectionGateState;
1848
+ private getOrCreateConnection;
1849
+ private wsUrlFor;
1850
+ /**
1851
+ * Build the outbound RPC headers: JSON content type, optional bearer auth,
1852
+ * the optional mutation-replay idempotency key, and the D1 read-your-writes
1853
+ * bookmark when the caller opted into `attachBookmark`. The mutation id
1854
+ * rides both the direct send and any offline-queue replay of the same write,
1855
+ * so a mutation the server already committed returns its cached result
1856
+ * instead of running twice.
1857
+ */
1858
+ private rpcRequestHeaders;
1859
+ private rpc;
1860
+ /**
1861
+ * Authenticated request to a non-RPC admin endpoint (the scheduler list /
1862
+ * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
1863
+ * worker's `{ error: { code, message } }` envelope as a coded `Error` —
1864
+ * mirroring {@link rpc} so callers see the same failure shape.
1865
+ */
1866
+ private adminFetch;
1867
+ /**
1868
+ * Resolve the effective connection context for a shard: the most-recently
1869
+ * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
1870
+ * back to the imperative {@link setConnectionContext} override, then the
1871
+ * client-wide default. Returns `undefined` when none apply.
1872
+ */
1873
+ private effectiveConnectionContext;
1874
+ /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
1875
+ private refreshConnectionContext;
1876
+ /**
1877
+ * Send the one-shot `connect` envelope on an open shard socket. Always sent
1878
+ * once per socket open, so the server's `onConnect` hooks fire symmetrically
1879
+ * with `onDisconnect` (which the DO dispatches unconditionally at close for
1880
+ * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
1881
+ * hooks are registered, so the single frame costs nothing in the common case.
1882
+ *
1883
+ * The shard's registered context (or the client-wide default) rides along
1884
+ * when one is set — the DO records it on the attachment for replay to
1885
+ * `onDisconnect`. A socket with no registered context still announces itself;
1886
+ * the envelope simply omits `context`, which is optional on the wire.
1887
+ * Register a context — e.g. `setConnectionContext({})` — to attach app state
1888
+ * to the lifecycle dispatch.
1889
+ */
1890
+ private sendConnectEnvelope;
1891
+ /**
1892
+ * Re-send every shape subscription bound to `shardKey` over its (now open)
1893
+ * socket. Each frame carries the shape's last applied checkpoint, so the
1894
+ * server resumes from it — or re-seeds when the cursor fell below CDC
1895
+ * retention or the epoch forked.
1896
+ */
1897
+ private resendShapeSubscriptions;
1898
+ private ensureSocket;
1899
+ /**
1900
+ * Resolve the {@link WsTokenProvider} and open the shard socket with the
1901
+ * minted token. The connection is already in the `connecting` state, so the
1902
+ * async gap is race-guarded: a client `close()`, a `setWsToken` bounce, or a
1903
+ * competing connect that landed first all abandon this attempt. A provider
1904
+ * failure fails the attempt through {@link handleDisconnect}, which arms the
1905
+ * normal reconnect backoff — a broken mint endpoint degrades to retries, not
1906
+ * a silent tokenless socket the admin gate would reject.
1907
+ */
1908
+ private openSocketWithProvidedToken;
1909
+ /**
1910
+ * Construct one WebSocket connection attempt and wire the shared
1911
+ * lifecycle guarantees around it — the fail-fast connect-timeout, the
1912
+ * identity guard that stops a superseded attempt's late `open`/`message`/
1913
+ * `close`/`error` from touching a connection a newer attempt already
1914
+ * owns, and (once open) the keepalive heartbeat with its half-open
1915
+ * watchdog (plan 217). One call opens ONE attempt; the caller owns
1916
+ * reconnect scheduling from `onClose` — mirrors the shard's existing
1917
+ * `ensureSocket` / `handleDisconnect` split, now shared with
1918
+ * `subscribeScheduledJobs` so it stops re-living the bug that split
1919
+ * already fixed once (CLIENT-05).
1920
+ *
1921
+ * The identity guard is `conn.socket !== socket`, re-checked before every
1922
+ * action below. `conn.socket` is reassigned to a new attempt's socket
1923
+ * synchronously — right here, before `open` ever fires — so an older
1924
+ * attempt's guard trips the instant it's superseded, even if its
1925
+ * underlying socket only fires its real `close`/`error` much later. This
1926
+ * ordering is load-bearing: preserve it exactly.
1927
+ */
1928
+ private openManagedSocket;
1929
+ /** Construct the shard socket and wire its lifecycle handlers. The connection must already be in the `connecting` state. */
1930
+ private openSocket;
1931
+ private handleDisconnect;
1932
+ /**
1933
+ * Begin the keepalive heartbeat on an open connection attempt — the only
1934
+ * caller is {@link openManagedSocket}'s own `open` handler, so both the
1935
+ * shard socket and `subscribeScheduledJobs` share this one implementation
1936
+ * instead of each hand-rolling their own (plan 217, generalized).
1937
+ *
1938
+ * Each tick first checks the half-open watchdog (see
1939
+ * {@link ManagedSocketState.lastFrameAt}): if no frame at all has arrived
1940
+ * within `heartbeatIntervalMs * 2.5`, the far end has gone quiet without
1941
+ * the socket ever firing `close` — force it closed and report it through
1942
+ * `onWatchdogTrip` (the caller's `onClose`) so the normal reconnect/backoff
1943
+ * takes over instead of every live query on it silently staling forever.
1944
+ * Otherwise it sends a {@link WS_KEEPALIVE_PING} text frame the server
1945
+ * answers from its hibernation auto-response without waking the DO. A
1946
+ * no-op when the heartbeat is disabled (an interval of zero or less);
1947
+ * idempotent — any existing timer is cleared first so a reconnect can't
1948
+ * leak intervals.
1949
+ */
1950
+ private startHeartbeat;
1951
+ /** Clear a connection's keepalive timer, if any. Safe to call repeatedly. */
1952
+ private stopHeartbeat;
1953
+ /** Mark every subscription bound to `shardKey` as needing a fresh ack. */
1954
+ private markShardPendingAck;
1955
+ private sendSubscribeIfOpen;
1956
+ private sendShapeSubscribeIfOpen;
1957
+ private handleServerMessage;
1958
+ private handleErrorMessage;
1959
+ private handlePokeStart;
1960
+ private handlePokePart;
1961
+ private handlePokeEnd;
1962
+ /** Materialize a shape's keyed view to an array and invoke its callbacks. */
1963
+ private emitShapeRows;
1964
+ private handleDataMessage;
1965
+ /**
1966
+ * Handle a `resume` frame (Pillar 1b): the server proved nothing the
1967
+ * subscription reads changed since our `sinceSeq`, so the cached value is
1968
+ * still current. We keep `lastValue` as-is, mark the sub acked, and advance
1969
+ * the cursor (re-persisting so the next reconnect resumes from the newer
1970
+ * watermark). No callback fires — the value didn't change, and `subscribe()`
1971
+ * already replayed the cached value to every consumer synchronously.
1972
+ */
1973
+ private handleResumeMessage;
1974
+ /**
1975
+ * Handle a `settled` frame: a write touched one of this subscription's read
1976
+ * tables but produced a byte-identical result, so the server suppressed the
1977
+ * data frame. Like {@link handleResumeMessage} the value didn't change — we
1978
+ * advance the resume position and re-persist — but we ALSO surface the echoed
1979
+ * custom-mutator watermark via `onCheckpoint` so a `@lunora/db` list
1980
+ * collection drops the optimistic overlay for the confirmed write (otherwise
1981
+ * its checkpoint gate, fed only by data frames, would hang forever). Sent
1982
+ * only to custom-mutator clients; plain `useQuery` subscribers leave
1983
+ * `onCheckpoint` unset and this is a near no-op.
1984
+ */
1985
+ private handleSettledMessage;
1986
+ /**
1987
+ * Mark `state` acked and, when the frame carries a newer cursor/epoch than
1988
+ * the cached position, advance the resume watermark and re-persist. Shared by
1989
+ * the `resume` and `settled` frame handlers — both acknowledge "nothing the
1990
+ * client must re-render changed, but the resume position may have moved".
1991
+ */
1992
+ private ackAndAdvanceCursor;
1993
+ /**
1994
+ * Resolve the value to publish for a `data`/`delta` frame.
1995
+ *
1996
+ * A `data` frame is an authoritative snapshot (the server re-execution path)
1997
+ * and always replaces the cached value wholesale. A `delta` frame carrying a
1998
+ * structured `MutationDelta` (the `broadcastDelta` row-change path) is
1999
+ * merged incrementally into the cached list — preserving order, no dup/loss —
2000
+ * so each subscription (including every paginated page) updates by delta
2001
+ * rather than a full re-send. We fall back to full replacement when the
2002
+ * delta isn't a recognisable row change, when there's no cached value yet,
2003
+ * or when it can't be applied cleanly against the current cached shape.
2004
+ */
2005
+ private resolveDataPayload;
2006
+ /** Route an inbound whisper to the topic's handlers on the originating shard. */
2007
+ private dispatchWhisper;
2008
+ /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
2009
+ private notifyTokenExpired;
2010
+ /**
2011
+ * CLIENT-04: `type: "complete"` today is sent ONLY by `@lunora/do`'s
2012
+ * `handleStream` (see `shard-do.ts`), gated to the `stream` envelope type
2013
+ * and minting only `stream_*` ids — the `subscribe` path never sends it, so
2014
+ * a live SUBSCRIPTION provably never receives `complete` from the current
2015
+ * server. But `ServerCompleteMessage` is a generic `id`-keyed frame and
2016
+ * `ShardDO` is user-subclassable, so this stays defensive rather than
2017
+ * assuming a `sub_*` id can never reach here: unlike the historical
2018
+ * `subscriptions.remove(state)`, which dropped the state out of
2019
+ * `subscriptions.all()` — the set the reconnect resubscribe loop walks
2020
+ * (`ensureSocket`'s `open` handler) — and so froze the query forever across
2021
+ * every future reconnect, this fans a cancellation error to any listener
2022
+ * and marks the registration un-acked instead. Non-destructive: the state
2023
+ * stays in the registry, so the very next reconnect resubscribes it. The
2024
+ * two id-spaces don't overlap (`sub_*` vs `stream_*`), so the stream and
2025
+ * subscription lookups below are mutually exclusive.
2026
+ */
2027
+ private handleCompleteMessage;
2028
+ private unpersist;
2029
+ /**
2030
+ * Stable, non-reversible fingerprint of the current auth identity used to
2031
+ * stamp queued offline writes. `null` (signed out) is its own identity and
2032
+ * never matches a bearer-token fingerprint. The raw token is never stored;
2033
+ * a length-prefixed FNV-1a hash is enough to detect an identity *change*
2034
+ * without keeping the credential around in the queue map.
2035
+ */
2036
+ private identityFingerprint;
2037
+ /**
2038
+ * Stable token-hash fingerprint of a bearer token (the `<len>:<fnv>:<djb2>`
2039
+ * format a token-stamped queued write carries). Extracted so the replay gate
2040
+ * can recompute the hash of the current credential and recognise a write
2041
+ * stamped under it — even after the fingerprint was relabelled to a subject.
2042
+ *
2043
+ * Two independent 32-bit passes (FNV-1a + djb2) give a ~64-bit digest, so
2044
+ * two distinct equal-length tokens are astronomically unlikely to share a
2045
+ * fingerprint. A single 32-bit hash collides ~1-in-4e9 per equal-length
2046
+ * pair — enough that, on a shared device, user B could hydrate A's cached
2047
+ * reads. Different algorithms (not the same FNV with a different seed, which
2048
+ * would be affine-related) keep the two passes genuinely independent.
2049
+ * Still synchronous (no crypto) and stable across surrogate pairs.
2050
+ */
2051
+ private hashToken;
2052
+ /**
2053
+ * True when `stamped` is a token-hash of the SAME credential still held now,
2054
+ * even though the live identity has since been relabelled to a subject. Covers
2055
+ * `setAuthToken(token, userId)` where the subject resolved a tick after the
2056
+ * token was set: a write persisted (or requeued) under the token hash must
2057
+ * still replay — the credential never changed, only its label — instead of
2058
+ * being dropped as an identity mismatch. This is the durable counterpart to
2059
+ * {@link restampQueuedIdentity}, which only relabels the in-memory live stamp
2060
+ * (consumed on the first flush) and never touches `item.identity` or the
2061
+ * persisted record, so a reload or a transient-failure requeue would otherwise
2062
+ * fall back to the stale token-hash and wrongly reject the same user's write.
2063
+ */
2064
+ private isSameCredentialUnderTokenHash;
2065
+ /**
2066
+ * Drain every in-memory offline write and reject it because the auth
2067
+ * identity changed. Durable entries are also dropped from persistence so a
2068
+ * later `hydrate` can't resurrect another user's writes. Stamps are cleared
2069
+ * alongside. Persisted entries restored without a live awaiter still get
2070
+ * unpersisted here.
2071
+ */
2072
+ private rejectQueuedForIdentityChange;
2073
+ /**
2074
+ * Migrate every live identity stamp from `from` to `to` — used when the auth
2075
+ * identity label changes but the underlying credential (token) does NOT, e.g.
2076
+ * the user id resolves a tick after the token was set. The in-memory
2077
+ * `queuedIdentities` map is the flush-time source of truth, so re-stamping it
2078
+ * keeps the in-flight writes replayable under the new (more stable) identity
2079
+ * instead of the flush guard discarding them as a mismatch.
2080
+ */
2081
+ private restampQueuedIdentity;
2082
+ /**
2083
+ * Drop the durable read cache on an identity change so a cached value stamped
2084
+ * under the previous identity can never hydrate into a new session. Clears
2085
+ * the in-flight write batch and the not-yet-consumed hydrated entries too;
2086
+ * the durable `clear()` is best-effort.
2087
+ */
2088
+ private clearQueryCacheForIdentityChange;
2089
+ /**
2090
+ * Flush every shard with a mutation currently queued in `offlineQueue`
2091
+ * (see `queuedOfflineShardKeys`). Used on a FOLLOWER tab when the
2092
+ * mirrored leader status transitions to `"connected"` — a follower has no
2093
+ * per-shard `ShardConnection` reconnect event to hang the usual
2094
+ * single-shard `flushOfflineQueue(shardKey)` call off of (see the
2095
+ * `handleConnect` call site), so this walks every shard that might have
2096
+ * something queued instead. Flushing an already-empty shard is a cheap
2097
+ * no-op (`flushOfflineQueue` returns immediately once `drain` yields
2098
+ * nothing), so over-inclusion here is harmless.
2099
+ */
2100
+ private flushAllOfflineQueues;
2101
+ private flushOfflineQueue;
2102
+ /**
2103
+ * Partition already-gated writes into the encodable ones (returned) and reject
2104
+ * the rest terminally. A write whose args can't be wire-encoded (e.g. a RegExp
2105
+ * or class instance in a `v.any()` field) can NEVER replay — the codec failure
2106
+ * is deterministic, not transient. Rejecting here is essential: otherwise
2107
+ * `encodeWire` throws mid-flush, is classified as transient (a codec error has
2108
+ * no `.code`), and re-queues forever — a silent hang where the caller's Promise
2109
+ * never settles and the optimistic write never rolls back. Encoding is cheap;
2110
+ * the flush is the slow reconnect path.
2111
+ */
2112
+ private encodableOrSettleTerminal;
2113
+ /**
2114
+ * Identity guard for one queued write about to replay: a write stamped under
2115
+ * one identity must never replay under another. The live `queuedIdentities`
2116
+ * map is the source of truth for the current session; a hydrated write whose
2117
+ * id isn't in the map falls back to the stamp persisted with the record
2118
+ * (`item.identity`), so a reload can't replay another user's queued writes.
2119
+ * Only legacy records (persisted before stamps were durable —
2120
+ * `item.identity === undefined`) replay under whatever identity is current.
2121
+ *
2122
+ * `Map.get` returns `undefined` for unstamped/hydrated ids and `item.identity`
2123
+ * is `undefined` for legacy records; a persisted `null` (queued while signed
2124
+ * out) is a real value that must not collapse into `undefined` — hence the
2125
+ * explicit `=== undefined` check rather than `??`. Returns `true` when the
2126
+ * write may replay; otherwise settles it `OFFLINE_IDENTITY_CHANGED` and returns
2127
+ * `false`. Either way the live stamp is consumed.
2128
+ */
2129
+ private passesReplayIdentityGate;
2130
+ /** 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. */
2131
+ private settleReplaySuccess;
2132
+ /** Settle a write the server reached a coded verdict on: replaying would re-trigger the same failure (a poison-message loop), so drop it. */
2133
+ private settleReplayTerminal;
2134
+ /**
2135
+ * Replay already-identity-gated writes one at a time on the single-call `/rpc`
2136
+ * path, preserving FIFO order (parallel `.then()` chains would race the
2137
+ * ordering callers depend on). Each replays under its stable `mutationId` so
2138
+ * the server dedups a write it already committed (exactly-once). A coded error
2139
+ * is a server verdict (drop it); a codeless (transport/transient) failure stops
2140
+ * the flush and re-queues this write and every unreplayed one for the next
2141
+ * reconnect — their callers stay pending, and the identity guard re-applies on
2142
+ * retry via each record's persisted stamp.
2143
+ */
2144
+ private replaySequential;
2145
+ /**
2146
+ * Coalesce already-identity-gated writes for a single shard into ONE
2147
+ * `/_lunora/rpc-batch` round trip (plan 088 follow-on). The worker forwards
2148
+ * them to the shard DO, which replays each through its single-call dispatch, so
2149
+ * per-entry `mutationId` idempotency and in-order application are inherited from
2150
+ * the proven path. Per-slot demux mirrors {@link replaySequential}'s
2151
+ * classification: success confirms the optimistic layer against the echoed
2152
+ * `commitCursor`; a coded application verdict is terminal; a transient shard
2153
+ * failure (`SHARD_UNAVAILABLE`/`SHARD_ERROR`), a missing slot, or a whole-batch
2154
+ * transport failure re-queues for the next reconnect (never dropping a durable
2155
+ * write). A whole-batch coded rejection (bad request / authorization denial the
2156
+ * server reached a verdict on) is terminal for every entry.
2157
+ *
2158
+ * Returns the writes that must be re-queued and `stop` — `true` when the whole
2159
+ * chunk failed at the transport level, so the caller leaves later chunks queued
2160
+ * rather than sending on. The caller re-queues once, in order, so requeuing is
2161
+ * NOT done here.
2162
+ */
2163
+ private replayBatched;
2164
+ /**
2165
+ * Demux a `/_lunora/rpc-batch` reply back onto the queued writes it replayed,
2166
+ * in input order. Each slot's envelope classifies its write the same way
2167
+ * {@link replaySequential} does: a success confirms the optimistic layer
2168
+ * against the echoed `commitCursor`; a coded application verdict is terminal;
2169
+ * a transient shard failure ({@link TRANSIENT_BATCH_ERROR_CODES}) or a slot the
2170
+ * server never returned is returned for the caller to re-queue.
2171
+ * @returns the writes that must be re-queued (transient slots), in input order
2172
+ */
2173
+ private settleReplayBatchSlots;
2174
+ }
2175
+ export { BatchSlot as B, ConnectionStatus as C, DEFAULT_MAX_BUFFER as D, LunoraClient as L, MutationCallOptions as M, OptimisticLocalStore as O, SubscriptionError as S, SubscriptionErrorCallback as a, StreamIterable as b, CONFLICT_ERROR_CODE as c, ClientDebugShard as d, ClientDebugSnapshot as e, ClientDebugSubscription as f, ClientQueryRef as g, LunoraClientError as h, LunoraErrorCode as i, MutationSettledEvent as j, OptimisticUpdate as k, StreamHandle as l, SubscriptionCallback as m, SubscriptionRegistry as n, SubscriptionState as o, SyncWatermark as p, createClientQuery as q, createLocalStore as r, createStream as s, getErrorCode as t, getRetryAfterMs as u, isConflictError as v, isForbiddenError as w, isRateLimitedError as x, isUnauthorizedError as y };