@lunora/client 0.0.0 → 1.0.0-alpha.10

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 (45) hide show
  1. package/LICENSE.md +105 -0
  2. package/README.md +113 -9
  3. package/__assets__/package-og.svg +14 -0
  4. package/dist/auth/index.d.mts +20 -0
  5. package/dist/auth/index.d.ts +20 -0
  6. package/dist/auth/index.mjs +60 -0
  7. package/dist/index.d.mts +385 -0
  8. package/dist/index.d.ts +385 -0
  9. package/dist/index.mjs +15 -0
  10. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +4 -0
  11. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +107 -0
  12. package/dist/packem_shared/LunoraClient-CgZ6FhKP.mjs +2721 -0
  13. package/dist/packem_shared/OfflineQueue-BI0FNNvc.mjs +1 -0
  14. package/dist/packem_shared/SKIP-vItZChkw.mjs +50 -0
  15. package/dist/packem_shared/SubscriptionRegistry-Dn-7k7eo.mjs +1 -0
  16. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +61 -0
  17. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +45 -0
  18. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +11 -0
  19. package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +105 -0
  20. package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +138 -0
  21. package/dist/packem_shared/createLocalStore-IOur0jHF.mjs +1 -0
  22. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +21 -0
  23. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +31 -0
  24. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +22 -0
  25. package/dist/packem_shared/createServerClient-BxkNcRlR.mjs +11 -0
  26. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +4 -0
  27. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +13 -0
  28. package/dist/packem_shared/local-store-BNgN3Dw3.mjs +111 -0
  29. package/dist/packem_shared/lunora-client.d-B5vWSgvD.d.mts +2196 -0
  30. package/dist/packem_shared/lunora-client.d-B5vWSgvD.d.ts +2196 -0
  31. package/dist/packem_shared/offline-queue-7Wc4onA0.mjs +164 -0
  32. package/dist/packem_shared/preload.d-3XJD-2hM.d.mts +20 -0
  33. package/dist/packem_shared/preload.d-CKZR675M.d.ts +20 -0
  34. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +13 -0
  35. package/dist/packem_shared/subscription-C1Jy7HiF.mjs +55 -0
  36. package/dist/pagination/index.d.mts +82 -0
  37. package/dist/pagination/index.d.ts +82 -0
  38. package/dist/pagination/index.mjs +61 -0
  39. package/dist/query/index.d.mts +62 -0
  40. package/dist/query/index.d.ts +62 -0
  41. package/dist/query/index.mjs +1 -0
  42. package/dist/ssr/index.d.mts +115 -0
  43. package/dist/ssr/index.d.ts +115 -0
  44. package/dist/ssr/index.mjs +4 -0
  45. package/package.json +53 -17
@@ -0,0 +1,2196 @@
1
+ import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthSession } from '@lunora/runtime';
2
+ /** The registered function kinds a {@link FunctionReference} can describe. `stream` is a query that yields multiple frames over the WS. */
3
+ type FunctionKind = "action" | "mutation" | "query" | "stream";
4
+ /**
5
+ * Opaque reference to a registered function emitted by `@lunora/codegen`.
6
+ *
7
+ * At runtime it carries the `<file>:<function>` identifier in `__lunoraRef`.
8
+ * Generated declarations decorate this with phantom type parameters so the
9
+ * client can infer args / return values per call site.
10
+ */
11
+ interface FunctionReference<Kind extends FunctionKind = FunctionKind, Args = unknown, Return = unknown> {
12
+ /**
13
+ * Phantom marker carrying the `Kind`/`Args`/`Return` type parameters for
14
+ * inference. Never present at runtime; declared as a covariant (output)
15
+ * position so a concrete reference stays assignable to a widened one.
16
+ */
17
+ readonly __lunoraPhantom?: {
18
+ args: Args;
19
+ kind: Kind;
20
+ returns: Return;
21
+ };
22
+ readonly __lunoraRef: string;
23
+ }
24
+ /** Extract the args type from a {@link FunctionReference}. */
25
+ type ArgsOf<F> = F extends FunctionReference<infer _K, infer A, infer _R> ? A : never;
26
+ /** Extract the return type from a {@link FunctionReference}. */
27
+ type ReturnOf<F> = F extends FunctionReference<infer _K, infer _A, infer R> ? R : never;
28
+ type Unsubscribe = () => void;
29
+ /**
30
+ * Serializable result of `preloadQuery`. Produced on the server during SSR,
31
+ * embedded in the rendered HTML, then handed to `usePreloadedQuery` on the
32
+ * client so the first render shows the server value with no loading flash
33
+ * before a live subscription attaches. Every field survives `JSON.stringify`.
34
+ */
35
+ interface Preloaded<T = unknown> {
36
+ readonly __lunoraPreloaded: true;
37
+ readonly args: Record<string, unknown>;
38
+ readonly functionPath: string;
39
+ readonly shardKey?: string;
40
+ readonly value: T;
41
+ }
42
+ /**
43
+ * Pluggable storage for the `x-d1-bookmark` value used to provide
44
+ * read-your-writes between a mutation and subsequent queries.
45
+ */
46
+ interface BookmarkStorage {
47
+ get: () => string | null;
48
+ set: (value: string | null) => void;
49
+ }
50
+ interface ReconnectOptions {
51
+ initialDelayMs?: number;
52
+ jitter?: boolean;
53
+ maxDelayMs?: number;
54
+ }
55
+ /** Which durable-storage operation failed, passed to {@link OfflineQueueOptions.onPersistenceError}. */
56
+ type PersistenceOperation = "append" | "clear" | "load" | "remove";
57
+ /** Context handed to a persistence-error handler. */
58
+ interface PersistenceErrorContext {
59
+ readonly error: unknown;
60
+ /** The mutation id involved, when the failing op was scoped to one (`append`/`remove`). */
61
+ readonly mutationId?: string;
62
+ readonly operation: PersistenceOperation;
63
+ }
64
+ interface OfflineQueueOptions {
65
+ maxItems?: number;
66
+ /**
67
+ * Invoked when a {@link PersistenceAdapter} call rejects (e.g. IndexedDB quota
68
+ * exceeded). Without a handler, failures are logged via `console.warn` so they
69
+ * are never fully silent. Note: a failed `append` means the write is queued in
70
+ * memory but NOT durable — it will not survive a reload.
71
+ */
72
+ onPersistenceError?: (context: PersistenceErrorContext) => void;
73
+ /**
74
+ * Queue mutations issued before a shard's first successful WebSocket
75
+ * connect (defaults to `false`). The standard behaviour (`LunoraClient`'s
76
+ * `mutation()`) queues only when the targeted shard has been connected at
77
+ * least once (`wasEverConnected`), so the registry / resubscribe handshake
78
+ * has run. Set this to `true` for offline-first apps that want to enqueue
79
+ * writes on the very first session before the WS is up.
80
+ */
81
+ queueBeforeFirstConnect?: boolean;
82
+ }
83
+ /**
84
+ * Serializable shape of an offline mutation, durably stored by a
85
+ * {@link PersistenceAdapter} so queued writes survive a reload/crash. The live
86
+ * `resolve`/`reject` callbacks of an in-flight `QueuedMutation` are *not*
87
+ * persisted — a restored mutation is replayed with no original awaiter.
88
+ */
89
+ interface PersistedMutation {
90
+ args: Record<string, unknown>;
91
+ functionPath: string;
92
+ id: string;
93
+ /**
94
+ * Issuing identity fingerprint, persisted so a hydrated write replays only
95
+ * under the identity that queued it (`null` = queued while signed out).
96
+ * Absent on records written by older client versions, which replay under
97
+ * the ambient identity for back-compat.
98
+ */
99
+ identity?: string | null;
100
+ shardKey?: string;
101
+ /**
102
+ * App/schema version stamped at enqueue (from `LunoraClientOptions.persistenceVersion`).
103
+ * On hydrate, a record whose `version` doesn't match the current one is dropped
104
+ * and purged rather than replayed — so a write persisted by an older deploy
105
+ * (with a now-changed function signature) can't replay against the new schema.
106
+ * Absent when no `persistenceVersion` is configured (no version gating).
107
+ */
108
+ version?: string;
109
+ }
110
+ /**
111
+ * Durable store for the offline mutation queue. The default client keeps the
112
+ * queue in memory; supplying an adapter (e.g. `createIndexedDbPersistence`)
113
+ * makes queued writes survive a page reload. Implementations must preserve FIFO
114
+ * (enqueue) order in `PersistenceAdapter.load`.
115
+ *
116
+ * Replay semantics are at-least-once: a mutation is removed only after the
117
+ * server confirms (or rejects) it, so a crash between commit and `remove` can
118
+ * replay it again on the next load.
119
+ */
120
+ interface PersistenceAdapter {
121
+ /** Append a mutation to durable storage (called on enqueue). */
122
+ append: (mutation: PersistedMutation) => Promise<void>;
123
+ /** Drop every persisted mutation (e.g. on logout). */
124
+ clear: () => Promise<void>;
125
+ /** Load all persisted mutations in FIFO order — called once at startup. */
126
+ load: () => Promise<PersistedMutation[]>;
127
+ /** Remove a mutation by id once it has been replayed (resolved or rejected). */
128
+ remove: (id: string) => Promise<void>;
129
+ }
130
+ /**
131
+ * One write handed to an {@link OutboxSink}. Mirrors {@link PersistedMutation}
132
+ * plus the custom-mutator identity (`clientId`/`mutationId`/`idempotencyKey`)
133
+ * the durable outbox needs to dedupe and watermark replays.
134
+ */
135
+ interface OutboxMutation {
136
+ args: Record<string, unknown>;
137
+ /** Stable per-client id; pairs with {@link OutboxMutation.mutationId} as `idempotencyKey`. */
138
+ clientId: string;
139
+ functionPath: string;
140
+ /** `${clientId}:${mutationId}` — sent as `x-lunora-mutation-id` so a replay is server-idempotent. */
141
+ idempotencyKey: string;
142
+ /** Issuing identity fingerprint (`null` = signed out); drives the sink's identity guard. */
143
+ identity: string | null;
144
+ /** Monotonic per-client mutation id, backing the server `__client_watermark`. */
145
+ mutationId: number;
146
+ shardKey?: string;
147
+ }
148
+ /**
149
+ * Pluggable durable outbox seam. When set on {@link LunoraClientOptions.outbox},
150
+ * the client delegates offline write durability + at-least-once replay to this
151
+ * sink instead of its built-in {@link PersistenceAdapter}-backed `OfflineQueue`.
152
+ * `@lunora/db` supplies the blessed implementation (`createExecutorOutboxSink`,
153
+ * backed by the TanStack `OfflineExecutor`); the interface itself is
154
+ * dependency-free so `@lunora/client` stays TanStack-free.
155
+ */
156
+ interface OutboxSink {
157
+ /**
158
+ * Persist and schedule a write for replay. Rejects with an
159
+ * `OFFLINE_QUEUE_OVERFLOW`-coded error when the sink's cap is exceeded, so
160
+ * the caller can surface back-pressure to the issuing mutation.
161
+ */
162
+ enqueue: (mutation: OutboxMutation) => Promise<void>;
163
+ }
164
+ /**
165
+ * One persisted query result in the durable read cache (Pillar 2). Keyed in the
166
+ * store by `shardKey + functionPath + argsKey`; the record carries everything
167
+ * needed to render offline on reload and to resume the live subscription.
168
+ */
169
+ interface CachedQuery {
170
+ /**
171
+ * Issuing identity fingerprint (same shape the offline queue stamps). A
172
+ * cached value only hydrates when it matches the current identity, so a
173
+ * signed-out cache never leaks into a new session. `null` = cached while
174
+ * signed out.
175
+ */
176
+ identity: string | null;
177
+ /**
178
+ * The `cursor` high-watermark this value reflects, replayed as `sinceSeq`
179
+ * on reconnect so the server can resume instead of re-snapshotting. Absent
180
+ * when the value predates CDC / no cursor was advertised.
181
+ */
182
+ serverCursor?: number;
183
+ /**
184
+ * The CDC `epoch` the `serverCursor` belongs to, replayed as `sinceEpoch`
185
+ * on reconnect so the server only resumes when the client is still on the
186
+ * same changelog timeline. Absent when no epoch was advertised.
187
+ */
188
+ serverEpoch?: string;
189
+ /** Wall-clock millis the value was written — drives LRU eviction. */
190
+ ts: number;
191
+ /** The full query result last seen from the server. */
192
+ value: unknown;
193
+ /**
194
+ * App/schema version stamped when persisted (from `LunoraClientOptions.persistenceVersion`).
195
+ * A cached value whose `version` doesn't match the current one is not hydrated —
196
+ * so a result of a now-changed shape from an older deploy can't render. Absent
197
+ * when no `persistenceVersion` is configured (no version gating).
198
+ */
199
+ version?: string;
200
+ }
201
+ /**
202
+ * Durable store for the client read cache (Pillar 2): query results survive a
203
+ * reload so reads hydrate from disk and render immediately while the socket
204
+ * reconnects. Opt-in via {@link LunoraClientOptions.queryCache}; omit to keep
205
+ * reads in memory only (today's behaviour). Mirrors {@link PersistenceAdapter}'s
206
+ * shape over the same IndexedDB plumbing.
207
+ */
208
+ interface QueryCacheAdapter {
209
+ /** Drop every cached query (e.g. on logout / identity change). */
210
+ clear: () => Promise<void>;
211
+ /** Load every cached query — called once at startup to hydrate reads. */
212
+ load: () => Promise<(CachedQuery & {
213
+ key: string;
214
+ })[]>;
215
+ /** Upsert one cached query by key (called when a subscription value advances). */
216
+ put: (key: string, entry: CachedQuery) => Promise<void>;
217
+ /** Remove one cached query by key. */
218
+ remove: (key: string) => Promise<void>;
219
+ }
220
+ interface LunoraClientOptions {
221
+ /**
222
+ * Base path the worker mounts better-auth at, used by the client's
223
+ * `getCurrentUser()` to reach the `get-session` route. Defaults to
224
+ * `/api/auth` (matching `@lunora/auth`'s `DEFAULT_AUTH_BASE_PATH`).
225
+ */
226
+ authBasePath?: string;
227
+ bookmarkStorage?: BookmarkStorage;
228
+ /**
229
+ * Stable per-client id backing the custom-mutator watermark. Sent on the
230
+ * `connect` envelope (so the server can scope this client's
231
+ * `__client_watermark`) and stamped onto every {@link OutboxMutation} the
232
+ * {@link LunoraClientOptions.outbox} sink persists, where it pairs with the
233
+ * monotonic mutation id to form the idempotency key. The `@lunora/db` path
234
+ * persists a stable id alongside the outbox and passes it here; omit for the
235
+ * standalone client, which generates an ephemeral per-session id.
236
+ */
237
+ clientId?: string;
238
+ /**
239
+ * Default app context sent in the `connect` envelope right after each socket
240
+ * opens, forwarded to the server's `onConnect`/`onDisconnect` lifecycle hooks
241
+ * as `event.context`. A per-shard context registered via
242
+ * `setConnectionContext` overrides this for that shard. Omit when no lifecycle
243
+ * hook needs connection context.
244
+ */
245
+ connectionContext?: Record<string, unknown>;
246
+ /**
247
+ * Fail-fast timeout (ms) for opening a subscription WebSocket. If the
248
+ * handshake doesn't complete within this window — a hung dev proxy or a cold
249
+ * worker that never upgrades — the client force-closes the socket and routes
250
+ * through its normal reconnect/backoff (surfacing `offline` status) instead
251
+ * of leaving the live channel silently stuck on the browser's much longer
252
+ * default. Does not affect HTTP queries/mutations (those never ride the WS).
253
+ * Defaults to 10000 (10s); set to `0` (or negative) to disable.
254
+ */
255
+ connectTimeoutMs?: number;
256
+ fetch?: typeof fetch;
257
+ /**
258
+ * Interval (ms) between keepalive pings sent on each open subscription
259
+ * socket. The server answers them via the Durable Object's hibernation
260
+ * auto-response WITHOUT waking the DO, so an idle socket stays alive across
261
+ * hibernation without a billable wakeup. Defaults to 30000 (30s); set to
262
+ * `0` (or a negative value) to disable the heartbeat entirely.
263
+ */
264
+ heartbeatIntervalMs?: number;
265
+ offlineQueue?: OfflineQueueOptions;
266
+ /**
267
+ * Durable outbox seam for offline writes. When supplied (the `@lunora/db`
268
+ * path wires `createExecutorOutboxSink`), offline mutations are delegated to
269
+ * the sink and the built-in {@link PersistenceAdapter}-backed `OfflineQueue`
270
+ * is bypassed, so a db app has exactly one durable write path. Omit for the
271
+ * standalone client, which keeps using {@link LunoraClientOptions.persistence}.
272
+ */
273
+ outbox?: OutboxSink;
274
+ /** Durable store for the offline mutation queue; omit to keep it in memory. */
275
+ persistence?: PersistenceAdapter;
276
+ /**
277
+ * App/schema version stamped onto every persisted queued write and cached
278
+ * read. Bump it on a breaking change to a function signature or query shape:
279
+ * on the next boot, persisted writes / cached reads stamped with a different
280
+ * version are dropped (and purged) rather than replayed / hydrated against the
281
+ * new schema. Omit to disable version gating (records are never invalidated by
282
+ * version).
283
+ *
284
+ * **Adoption is itself an invalidation event:** records written before you set
285
+ * `persistenceVersion` carry no version, so the first boot after enabling it
286
+ * purges all currently-queued offline writes (and cached reads) as stale. Adopt
287
+ * it on a build where that clean slate is acceptable — typically the same
288
+ * breaking deploy you're protecting against — not purely speculatively.
289
+ */
290
+ persistenceVersion?: string;
291
+ /**
292
+ * Durable store for the read cache (Pillar 2). When supplied, query results
293
+ * are persisted as their subscriptions advance and hydrated on construction
294
+ * so a reload renders cached data before the socket reconnects, then resumes
295
+ * the live subscription from the persisted cursor. Omit (or pass `false`) to
296
+ * keep reads in memory only — the default, unchanged behaviour.
297
+ */
298
+ queryCache?: QueryCacheAdapter | false;
299
+ reconnect?: ReconnectOptions;
300
+ url: string;
301
+ WebSocket?: typeof WebSocket;
302
+ /**
303
+ * Token appended to the WebSocket URL as `?token=…`. The server matches it
304
+ * against `LUNORA_WS_BEARER` (to clear the upgrade gate) and/or
305
+ * `LUNORA_ADMIN_TOKEN` (to authorize `__lunora_admin__:*` subscriptions —
306
+ * what the studio sets it to). Browsers can't set headers on the
307
+ * `WebSocket` constructor, so the query parameter is the only channel; it
308
+ * ends up in server logs and history, so prefer a short-lived rotating
309
+ * token in production.
310
+ */
311
+ wsToken?: string;
312
+ wsUrl?: string;
313
+ }
314
+ /** Wire envelope sent on `POST /_lunora/rpc`. */
315
+ interface RpcEnvelope {
316
+ args?: Record<string, unknown>;
317
+ /**
318
+ * Stable per-client identifier (custom-mutator push path). Pairs with
319
+ * {@link RpcEnvelope.mutationId} to form `idempotencyKey` and scope the
320
+ * server `__client_watermark`. Absent on plain `client.mutation` calls.
321
+ */
322
+ clientId?: string;
323
+ functionPath: string;
324
+ /**
325
+ * Idempotency key (`${clientId}:${mutationId}`) for the custom-mutator push
326
+ * path, mirrored into the `x-lunora-mutation-id` header. Absent on plain
327
+ * `client.mutation` calls.
328
+ */
329
+ idempotencyKey?: string;
330
+ /**
331
+ * Monotonic per-client mutation id (custom-mutator push path), backing the
332
+ * server-side per-client watermark: `id &lt;= watermark` is a replay (skipped),
333
+ * `id == watermark + 1` runs authoritatively, `id > watermark + 1` halts the
334
+ * batch so the client resends from `watermark + 1`. Absent on plain
335
+ * `client.mutation` calls.
336
+ */
337
+ mutationId?: number;
338
+ shardKey?: string;
339
+ }
340
+ /**
341
+ * Wire response from the shard's `/rpc` endpoint (forwarded by the runtime). A
342
+ * watermarked custom-mutator push additionally carries `lastMutationId` — the
343
+ * highest per-client sequence the DO has applied — which the client uses to keep
344
+ * its `clientSeq` generator monotonic across reloads (see `LunoraClient.callMutator`).
345
+ * A plain mutation on a CDC shard carries `commitCursor` — the cursor the write
346
+ * committed at — which gates the drop of a per-call optimistic layer.
347
+ */
348
+ type RpcResponseBody = {
349
+ error: {
350
+ code: string;
351
+ message: string;
352
+ };
353
+ } | {
354
+ commitCursor?: number;
355
+ lastMutationId?: number;
356
+ result: unknown;
357
+ };
358
+ /** Subscription protocol — client → server. */
359
+ interface ClientSubscribeMessage {
360
+ id: string;
361
+ /**
362
+ * `sinceSeq` is the persisted `cursor` high-watermark the client last saw
363
+ * for this shard (Pillar 1b resume). Present only when a durable
364
+ * {@link QueryCacheAdapter} restored a cached value with a cursor; the
365
+ * server replies with a lightweight `resume` frame instead of a full
366
+ * snapshot when nothing the query reads changed since it. Absent on a
367
+ * first-time subscribe.
368
+ */
369
+ query: {
370
+ args?: Record<string, unknown>;
371
+ functionPath?: string;
372
+ sinceEpoch?: string;
373
+ sinceSeq?: number;
374
+ table?: string;
375
+ };
376
+ type: "subscribe";
377
+ }
378
+ interface ClientUnsubscribeMessage {
379
+ id: string;
380
+ type: "unsubscribe";
381
+ }
382
+ /**
383
+ * One-shot control frame sent right after the socket opens. Registers the
384
+ * connection's app `context` (e.g. `{ roomId, sessionId }`) with the server and
385
+ * fires the `onConnect` lifecycle hooks; the same context is replayed to
386
+ * `onDisconnect` when the socket drops.
387
+ */
388
+ interface ClientConnectMessage {
389
+ /**
390
+ * Stable per-client id (persisted alongside the outbox). Lets the server
391
+ * scope this connection's `__client_watermark` so custom-mutator pokes can
392
+ * echo the right per-client `lastMutationId`. Omitted by clients that don't
393
+ * use custom mutators.
394
+ */
395
+ clientId?: string;
396
+ context?: Record<string, unknown>;
397
+ id: string;
398
+ type: "connect";
399
+ }
400
+ /**
401
+ * Subscribe to a declarative **shape** — server-side partial replication scoped
402
+ * by `shardBy` + the shape's predicate + RLS. The client sends the shape *name*
403
+ * + validated `args`; the server resolves the trusted `where` (identity/RLS
404
+ * `baseWhere` the client can't forge) and streams the matching rowset, then live
405
+ * {@link ServerPokePartMessage} diffs. `id` namespaces the subscription and is
406
+ * echoed as `shapeId` on every poke part.
407
+ */
408
+ interface ClientShapeSubscribeMessage {
409
+ id: string;
410
+ shape: {
411
+ args?: Record<string, unknown>;
412
+ name: string;
413
+ };
414
+ /**
415
+ * Resume from this checkpoint (the `__cdc_log` cursor the client last
416
+ * applied for this shape). When absent or below the server's retained floor
417
+ * (`minCdcSeq`), the server re-seeds with a full insert-poke instead of a
418
+ * delta.
419
+ */
420
+ sinceCheckpoint?: number;
421
+ /**
422
+ * The CDC epoch {@link ClientShapeSubscribeMessage.sinceCheckpoint} belongs
423
+ * to. A mismatch (forked changelog timeline) forces a full re-seed even when
424
+ * the cursor is numerically in range.
425
+ */
426
+ sinceEpoch?: string;
427
+ type: "shape_subscribe";
428
+ }
429
+ /** Cancel a shape subscription started with the same `id`. */
430
+ interface ClientShapeUnsubscribeMessage {
431
+ id: string;
432
+ type: "shape_unsubscribe";
433
+ }
434
+ interface ClientAckMessage {
435
+ id: string;
436
+ type: "ack";
437
+ }
438
+ /**
439
+ * Start a streaming query. The id namespaces a fresh stream and is echoed on
440
+ * every {@link ServerChunkMessage} the server pushes back. Cancel a running
441
+ * stream by sending a {@link ClientUnsubscribeMessage} with the same id —
442
+ * subscription and stream id-spaces share the cancel channel; the prefix
443
+ * (`sub_*` vs `stream_*`) keeps the local registries searchable.
444
+ */
445
+ interface ClientStreamMessage {
446
+ id: string;
447
+ query: {
448
+ args?: Record<string, unknown>;
449
+ functionPath: string;
450
+ shardKey?: string;
451
+ };
452
+ type: "stream";
453
+ }
454
+ /**
455
+ * Join or leave a whisper `topic` — an app-chosen ephemeral channel scoped to a
456
+ * shard. While joined, the client receives every {@link ServerWhisperMessage}
457
+ * other members broadcast to the topic.
458
+ */
459
+ interface ClientWhisperSubscribeMessage {
460
+ topic: string;
461
+ type: "whisper_subscribe" | "whisper_unsubscribe";
462
+ }
463
+ /**
464
+ * Broadcast ephemeral `data` to the topic's other members on the shard. The
465
+ * payload is relayed verbatim with no server-side persistence (no SQLite/CDC
466
+ * write) — for typing indicators, live cursors, presence pings. The sender does
467
+ * not receive its own whisper.
468
+ */
469
+ interface ClientWhisperMessage {
470
+ data?: unknown;
471
+ topic: string;
472
+ type: "whisper";
473
+ }
474
+ type ClientMessage = ClientAckMessage | ClientConnectMessage | ClientShapeSubscribeMessage | ClientShapeUnsubscribeMessage | ClientStreamMessage | ClientSubscribeMessage | ClientUnsubscribeMessage | ClientWhisperMessage | ClientWhisperSubscribeMessage;
475
+ /** Subscription protocol — server → client. */
476
+ interface ServerDataMessage {
477
+ /**
478
+ * The `__cdc_log` high-watermark covered by this frame (Pillar 1b). The
479
+ * client persists it as the query's `serverCursor` and replays it as
480
+ * `sinceSeq` on the next reconnect. Absent on shards that never enabled CDC.
481
+ */
482
+ cursor?: number;
483
+ data?: unknown;
484
+ delta?: unknown;
485
+ /** The CDC epoch this frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
486
+ epoch?: string;
487
+ id: string;
488
+ /**
489
+ * The highest custom-mutator `mutationId` from this client the server has
490
+ * now applied (the per-client `__client_watermark`). Echoed so the client's
491
+ * outbox can drop confirmed pending mutations and let TanStack DB collapse
492
+ * the matching optimistic overlay. Absent on shards without custom mutators.
493
+ */
494
+ lastMutationId?: number;
495
+ type: "data" | "delta";
496
+ }
497
+ /**
498
+ * Lightweight resume acknowledgement (Pillar 1b): the server determined that
499
+ * nothing the subscription reads changed since the client's `sinceSeq`, so it
500
+ * skips re-sending the snapshot. The client keeps its cached value and only
501
+ * advances `serverCursor` to `cursor`.
502
+ */
503
+ interface ServerResumeMessage {
504
+ cursor?: number;
505
+ /** The CDC epoch this resume's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
506
+ epoch?: string;
507
+ id: string;
508
+ /** Per-client custom-mutator watermark (see {@link ServerDataMessage.lastMutationId}). */
509
+ lastMutationId?: number;
510
+ type: "resume";
511
+ }
512
+ /**
513
+ * Settled acknowledgement for a **list** subscription: a write touched one of
514
+ * the subscription's read tables but produced a byte-identical result, so the
515
+ * server suppressed the data frame. Sent ONLY to a `@lunora/db` custom-mutator
516
+ * client (one that announced a `clientId`, hence has a server-side
517
+ * `__client_watermark`) so its optimistic list overlay drops even when no data
518
+ * frame arrives. Plain `useQuery` subscribers never receive it, and an older
519
+ * client safely ignores the unknown frame.
520
+ */
521
+ interface ServerSettledMessage {
522
+ cursor?: number;
523
+ /** The CDC epoch this settled frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
524
+ epoch?: string;
525
+ id: string;
526
+ /**
527
+ * The highest custom-mutator `mutationId` from this client the server has
528
+ * now applied (the per-client `__client_watermark`). Forwarded to a
529
+ * collection's `onCheckpoint` so it can drop the overlay for the confirmed
530
+ * write whose result didn't change this list.
531
+ */
532
+ lastMutationId?: number;
533
+ type: "settled";
534
+ }
535
+ interface ServerErrorMessage {
536
+ error?: unknown;
537
+ id?: string;
538
+ message?: string;
539
+ type: "error";
540
+ }
541
+ interface ServerAckMessage {
542
+ id: string;
543
+ type: "ack";
544
+ }
545
+ interface ServerCompleteMessage {
546
+ id: string;
547
+ type: "complete";
548
+ }
549
+ /** One frame of a streaming query — `data` carries the user-yielded chunk. */
550
+ interface ServerChunkMessage {
551
+ data: unknown;
552
+ id: string;
553
+ type: "chunk";
554
+ }
555
+ /**
556
+ * An ephemeral whisper relayed from another member of `topic` on the same shard
557
+ * (AnyCable-style whispering). `data` is the sender's payload verbatim; `from`
558
+ * is the sender's verified user id when known (absent for an anonymous sender).
559
+ * Never persisted server-side.
560
+ */
561
+ interface ServerWhisperMessage {
562
+ data: unknown;
563
+ from?: string;
564
+ topic: string;
565
+ type: "whisper";
566
+ }
567
+ /**
568
+ * One row-level change in a shape's replication stream — the wire form of the
569
+ * DO's `__cdc_log` `CdcChange`. `insert`/`update` carry the post-image in
570
+ * `value` (projected to the shape's `columns`); `delete` omits it, identifying
571
+ * the removed row by `key` alone. The client applies these to its local
572
+ * collection; an unknown `key` on a `delete` is a safe no-op (a row the client
573
+ * never had in this shape).
574
+ */
575
+ interface RowOp {
576
+ /** Row primary key (`_id`). */
577
+ key: string;
578
+ op: "delete" | "insert" | "update";
579
+ /** Logical table the row belongs to. */
580
+ table: string;
581
+ /** Post-image document for insert/update; absent on delete. */
582
+ value?: Record<string, unknown>;
583
+ }
584
+ /**
585
+ * Opens a **poke** — an atomically-applied batch of shape diffs (Zero's poke
586
+ * protocol). A `pokeStart` is followed by zero or more {@link ServerPokePartMessage}
587
+ * frames and closed by exactly one {@link ServerPokeEndMessage}; the client
588
+ * buffers every part and applies them in a single transaction at `pokeEnd`, so a
589
+ * socket that drops mid-poke simply re-seeds on reconnect (no torn view).
590
+ */
591
+ interface ServerPokeStartMessage {
592
+ /** The checkpoint the client's view is expected to be at before this poke applies (for ordering/gap detection). */
593
+ baseCheckpoint?: number;
594
+ /** CDC epoch this poke belongs to; a mismatch forces the client to re-seed rather than apply. */
595
+ epoch?: string;
596
+ /** Correlates this poke's `pokeStart`/`pokePart`/`pokeEnd` frames. */
597
+ pokeId: string;
598
+ type: "pokeStart";
599
+ }
600
+ /** One shape's slice of an in-flight poke: the row-ops to apply for `shapeId`. */
601
+ interface ServerPokePartMessage {
602
+ /** Per-client custom-mutator watermark carried with this slice (see {@link ServerSettledMessage.lastMutationId}). */
603
+ lastMutationId?: number;
604
+ pokeId: string;
605
+ /** Ordered row-level changes for this shape, applied in sequence at `pokeEnd`. */
606
+ rowsPatch: RowOp[];
607
+ /** The {@link ClientShapeSubscribeMessage.id} these row-ops belong to. */
608
+ shapeId: string;
609
+ type: "pokePart";
610
+ }
611
+ /**
612
+ * Closes a poke: the client commits the buffered parts atomically and advances
613
+ * its checkpoint to {@link ServerPokeEndMessage.checkpoint} (the `__cdc_log`
614
+ * cursor high-watermark the view now reflects), replayed as `sinceCheckpoint` on
615
+ * the next reconnect.
616
+ */
617
+ interface ServerPokeEndMessage {
618
+ /** The `__cdc_log` cursor the view is at after applying this poke. */
619
+ checkpoint?: number;
620
+ /** CDC epoch the {@link ServerPokeEndMessage.checkpoint} belongs to. */
621
+ epoch?: string;
622
+ pokeId: string;
623
+ type: "pokeEnd";
624
+ }
625
+ type ServerMessage = ServerAckMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerPokeEndMessage | ServerPokePartMessage | ServerPokeStartMessage | ServerResumeMessage | ServerSettledMessage | ServerWhisperMessage;
626
+ /**
627
+ * The authenticated user as exposed client-side, mirroring better-auth's
628
+ * `user` row (the `user` field of the `get-session` response). Kept minimal
629
+ * and structural — only `id` is guaranteed; the rest are the common better-auth
630
+ * fields, and the index signature carries any plugin-contributed extras.
631
+ */
632
+ interface User {
633
+ readonly createdAt?: NullableTimestamp;
634
+ readonly email?: null | string;
635
+ readonly emailVerified?: boolean | null;
636
+ readonly id: string;
637
+ readonly image?: null | string;
638
+ readonly name?: null | string;
639
+ readonly [key: string]: unknown;
640
+ readonly updatedAt?: NullableTimestamp;
641
+ }
642
+ /**
643
+ * One pending scheduled function, as returned by the worker's
644
+ * `GET /_lunora/admin/scheduled` endpoint. Mirrors `@lunora/scheduler`'s
645
+ * `ScheduleRecord` structurally so the client carries no dependency on it.
646
+ */
647
+ interface ScheduleRecord {
648
+ args: Record<string, unknown>;
649
+ /**
650
+ * Dispatch attempts already made. Absent (treated as 0) until the first
651
+ * failure; on a dead-letter record it is the exhausted count (> the retry
652
+ * budget). Surfaced so the studio can show how hard a job tried before it
653
+ * was parked.
654
+ */
655
+ attempts?: number;
656
+ enqueuedAt: number;
657
+ functionPath: string;
658
+ id: string;
659
+ /** Logical workpool the job is routed to (concurrency-gated), when any. */
660
+ pool?: string;
661
+ scheduledFor: number;
662
+ shardKey?: string;
663
+ }
664
+ /**
665
+ * One workpool's live backlog, as returned by the worker's
666
+ * `GET /_lunora/admin/scheduled/status` endpoint. Mirrors `@lunora/scheduler`'s
667
+ * `SchedulerPoolStatus` structurally so the client carries no dependency on it.
668
+ */
669
+ interface SchedulerPoolStatus {
670
+ /** Jobs currently dispatched-but-not-yet-completed (the held concurrency slots). */
671
+ inFlight: number;
672
+ /** The pool's concurrency cap. */
673
+ maxConcurrency: number;
674
+ /** The logical workpool name. */
675
+ name: string;
676
+ /** Pending jobs routed to this pool but not yet dispatched. */
677
+ queued: number;
678
+ }
679
+ /**
680
+ * The app-level scheduler backlog, as returned by the worker's
681
+ * `GET /_lunora/admin/scheduled/status` endpoint. `pools` is the per-pool
682
+ * breakdown; `backlog` and `inFlight` are the app-wide sums of `queued` and
683
+ * `inFlight` across every pool — the headline numbers for the studio SLO
684
+ * view. Mirrors `@lunora/scheduler`'s `SchedulerStatus` structurally.
685
+ */
686
+ interface SchedulerStatus {
687
+ /** Sum of every pool's `queued` count — the total pending backlog. */
688
+ backlog: number;
689
+ /** Sum of every pool's `inFlight` count — the total held concurrency slots. */
690
+ inFlight: number;
691
+ /** Per-pool backlog breakdown. */
692
+ pools: SchedulerPoolStatus[];
693
+ }
694
+ /**
695
+ * One shard's request volume, as returned by the worker's
696
+ * `POST /_lunora/admin/shard-traffic` endpoint. The cross-shard traffic feed
697
+ * the studio's `hot_shard` advisor lint consumes: `requests` is the shard's
698
+ * lifetime dispatch total, `shardKey` the DO id name (`""` for the root shard).
699
+ */
700
+ interface ShardTrafficEntry {
701
+ requests: number;
702
+ shardKey: string;
703
+ }
704
+ /**
705
+ * The whole-shard-set traffic distribution returned by the worker's
706
+ * `POST /_lunora/admin/shard-traffic` endpoint. `shards` is one entry per live
707
+ * shard (a failed shard surfaces with `requests: 0`); `ok`/`failed` count the
708
+ * shards that returned vs. errored. Shaped to feed the advisor's `hot_shard`
709
+ * lint after the studio tags each entry with its sharded function `group`.
710
+ */
711
+ interface ShardTrafficResult {
712
+ failed: number;
713
+ ok: number;
714
+ shards: ShardTrafficEntry[];
715
+ }
716
+ /**
717
+ * One object in the storage bucket, as returned by the worker's
718
+ * `GET /_lunora/admin/storage` endpoint. Mirrors `@lunora/storage`'s
719
+ * `R2ObjectLike` structurally.
720
+ */
721
+ interface StorageObject {
722
+ customMetadata?: Record<string, string>;
723
+ etag: string;
724
+ httpMetadata?: {
725
+ contentType?: string;
726
+ };
727
+ key: string;
728
+ size: number;
729
+ /**
730
+ * When the object was stored. R2 emits a `Date`, which JSON-serializes to an
731
+ * ISO string over the wire; a mock may supply epoch ms — so consumers should
732
+ * normalise via `new Date(uploaded)`. Absent if the backend didn't report it.
733
+ */
734
+ uploaded?: number | string;
735
+ }
736
+ /** One page of {@link StorageObject}s plus the cursor to fetch the next, if any. */
737
+ interface StorageListPage {
738
+ cursor?: string;
739
+ objects: StorageObject[];
740
+ }
741
+ /**
742
+ * One argument of a registered function, derived from its `v.*` validator by the
743
+ * worker. A compact signature shape — enough to render a function's API without
744
+ * the build-time codegen types.
745
+ */
746
+ interface FunctionArgumentDescriptor {
747
+ /** Element validator kind for an `array` arg (one level), e.g. `string`. */
748
+ element?: string;
749
+ /** The (optional-unwrapped) validator kind, e.g. `string`, `id`, `object`. */
750
+ kind: string;
751
+ /** The argument name. */
752
+ name: string;
753
+ /** True when the arg is wrapped in `v.optional(...)`. */
754
+ optional: boolean;
755
+ /** Target table for an `id` arg (`v.id("table")`). */
756
+ table?: string;
757
+ }
758
+ /**
759
+ * One registered function, as returned by the worker's
760
+ * `GET /_lunora/admin/functions` endpoint: its `&lt;file>:&lt;function>` path, which
761
+ * client method (`query` / `mutation` / `action`) invokes it, and its argument
762
+ * signature. `args` is absent on responses from an older worker.
763
+ */
764
+ interface FunctionDescriptor {
765
+ args?: FunctionArgumentDescriptor[];
766
+ kind: "action" | "mutation" | "query";
767
+ path: string;
768
+ }
769
+ /** A `.global()` (D1-backed) table plus its row count, from `/_lunora/admin/global/tables`. */
770
+ interface GlobalTableInfo {
771
+ name: string;
772
+ rowCount: number;
773
+ }
774
+ /** A window of rows from one global table, from `/_lunora/admin/global/table`. */
775
+ interface GlobalTablePage {
776
+ columns: string[];
777
+ /** FK columns (local column → referenced table) for external tables with real `REFERENCES` constraints, from `PRAGMA foreign_key_list`. */
778
+ refs?: Record<string, string>;
779
+ rows: Record<string, unknown>[];
780
+ total: number;
781
+ }
782
+ /**
783
+ * One equality constraint a facet-value click adds to the global browser's view
784
+ * (`column = value`). `value` is the raw stored scalar the facet returned, sent
785
+ * as-is and bound server-side, so it never injects SQL.
786
+ */
787
+ interface GlobalFilterClause {
788
+ column: string;
789
+ value: unknown;
790
+ }
791
+ /** One distinct value of a faceted global column with its row count, from `/_lunora/admin/global/facet`. */
792
+ interface GlobalFacetValue {
793
+ count: number;
794
+ value: unknown;
795
+ }
796
+ /** Per-column distinct-value summary for the global browser, from `/_lunora/admin/global/facet`. */
797
+ interface GlobalFacetResult {
798
+ truncated: boolean;
799
+ values: GlobalFacetValue[];
800
+ }
801
+ /** A nullable timestamp field as better-auth serializes it: epoch-ms, ISO string, or null. */
802
+ type NullableTimestamp = null | number | string;
803
+ /** A workflow instance's lifecycle status. Mirrors Cloudflare's `InstanceStatus`. */
804
+ type WorkflowInstanceStatus = "complete" | "errored" | "paused" | "queued" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
805
+ /** The lifecycle mutations the status endpoint accepts. */
806
+ type WorkflowInstanceAction = "pause" | "resume" | "terminate";
807
+ /** One row of the workflow-instances list. */
808
+ interface WorkflowInstanceSummary {
809
+ createdOn?: string;
810
+ endedOn?: string;
811
+ id: string;
812
+ startedOn?: string;
813
+ status: WorkflowInstanceStatus;
814
+ }
815
+ /** One durable step of an instance's execution timeline. */
816
+ interface WorkflowStepDetail {
817
+ /** 1-based attempt count (`> 1` means the step retried). */
818
+ attempts?: number;
819
+ end?: string;
820
+ error?: unknown;
821
+ name: string;
822
+ output?: unknown;
823
+ start?: string;
824
+ success?: boolean;
825
+ /** `step` / `sleep` / `waitForEvent` / … (Cloudflare's step `type`). */
826
+ type?: string;
827
+ }
828
+ /** A workflow instance's full detail: summary plus params/output/error and the step timeline. */
829
+ interface WorkflowInstanceDetail extends WorkflowInstanceSummary {
830
+ error?: unknown;
831
+ output?: unknown;
832
+ params?: unknown;
833
+ steps: WorkflowStepDetail[];
834
+ }
835
+ /** A page of workflow instances. */
836
+ interface WorkflowInstancePage {
837
+ /**
838
+ * Whether workflow inspection is configured on the worker (a Cloudflare
839
+ * account id + API token). `false` when the admin proxy reports it can't
840
+ * inspect instances; omitted (treated as configured) otherwise. Lets a
841
+ * caller render a "set credentials" state without a failed request.
842
+ */
843
+ configured?: boolean;
844
+ instances: WorkflowInstanceSummary[];
845
+ page: number;
846
+ perPage: number;
847
+ totalCount?: number;
848
+ }
849
+ type SubscriptionCallback = (data: unknown) => void;
850
+ /** A subscription-scoped error the server pushed for this subscription id. */
851
+ interface SubscriptionError {
852
+ code?: string;
853
+ message: string;
854
+ }
855
+ type SubscriptionErrorCallback = (error: SubscriptionError) => void;
856
+ /**
857
+ * One active per-call optimistic transform layered onto a subscription. The
858
+ * displayed value is the authoritative {@link SubscriptionState.serverBase}
859
+ * folded through every layer's `transform`, in order — so an incoming server
860
+ * frame re-folds the still-pending layers onto the new base (rebasing) instead
861
+ * of clobbering them. A layer is dropped — gaplessly — once a `data`/`delta`
862
+ * frame whose `cursor >= commitCursor` arrives (its write is now reflected in
863
+ * `serverBase`); `commitCursor` is the CDC cursor the server echoed on the
864
+ * mutation's response, and stays `undefined` while the write is still queued/
865
+ * in-flight (so the overlay survives unrelated deltas until confirmed).
866
+ */
867
+ interface OptimisticLayer {
868
+ /** The committed CDC cursor (from the mutation response); `undefined` until confirmed. */
869
+ commitCursor?: number;
870
+ readonly id: symbol;
871
+ readonly transform: (current: unknown) => unknown;
872
+ }
873
+ interface SubscriptionState {
874
+ /** True once the server has acked the subscription on the current socket. */
875
+ acked: boolean;
876
+ readonly args: Record<string, unknown>;
877
+ /**
878
+ * Stable-stringified `args`, computed once at subscribe time. Cached so the
879
+ * optimistic-update fan-out can compare against a mutation's args key without
880
+ * re-serializing every subscription's args on every mutation.
881
+ */
882
+ readonly argsKey: string;
883
+ readonly callbacks: Set<SubscriptionCallback>;
884
+ /**
885
+ * Notified when a `settled` frame advances this subscription's watermark — a
886
+ * write touched the subscription's tables but the result was byte-identical,
887
+ * so the server suppressed the data frame. A `@lunora/db` list collection
888
+ * uses this to drop the optimistic overlay for the confirmed write.
889
+ *
890
+ * A SET (not a single slot) because `SubscriptionState` is SHARED across
891
+ * every subscriber to the same `(fn, args, shardKey)`: a `@lunora/db`
892
+ * collection may subscribe to a query a plain `useQuery` already opened, so
893
+ * each subscriber registers its own callback (mirroring `callbacks` /
894
+ * `errorCallbacks`) and a `settled` frame fans out to all of them. Plain
895
+ * `useQuery` consumers register nothing, leaving the set empty.
896
+ */
897
+ readonly checkpointCallbacks: Set<(watermark: {
898
+ checkpoint?: number;
899
+ mutationId?: number;
900
+ }) => void>;
901
+ /** Notified when the server rejects this subscription (e.g. admin auth). */
902
+ readonly errorCallbacks: Set<SubscriptionErrorCallback>;
903
+ readonly fn: FunctionReference;
904
+ readonly id: string;
905
+ /**
906
+ * The highest custom-mutator `mutationId` from this client the server has
907
+ * applied, captured from the last `settled` frame (the suppressed-list-frame
908
+ * watermark). Forwarded to {@link SubscriptionState.checkpointCallbacks}.
909
+ * Absent until a `settled` frame arrives.
910
+ */
911
+ lastMutationId?: number;
912
+ /** Last known value, used to short-circuit `useQuery`-style consumers. */
913
+ lastValue: unknown;
914
+ /**
915
+ * Active per-call optimistic layers, in application order (see
916
+ * {@link OptimisticLayer}). Empty for subscriptions with no pending per-call
917
+ * optimistic write — the common case, where `lastValue` tracks `serverBase`
918
+ * exactly and behaviour is identical to a plain server-value assignment.
919
+ */
920
+ optimisticLayers: OptimisticLayer[];
921
+ /**
922
+ * The authoritative server value the optimistic layers fold onto — the value
923
+ * with NO optimistic overlay. Tracks `lastValue` exactly whenever no layers
924
+ * are active; diverges only while a per-call optimistic write is pending. A
925
+ * server frame updates this (and re-folds the layers); the durable read cache
926
+ * persists this, never the optimistic overlay.
927
+ */
928
+ serverBase: unknown;
929
+ /**
930
+ * The `__cdc_log` high-watermark (`cursor`) the `lastValue` reflects,
931
+ * captured from the last `data`/`delta`/`resume` frame. Persisted to the
932
+ * durable read cache and replayed as `sinceSeq` on reconnect so the server
933
+ * can resume instead of re-snapshotting (Pillar 1b/2). Absent until the
934
+ * first cursor-stamped frame arrives.
935
+ */
936
+ serverCursor?: number;
937
+ /**
938
+ * The CDC `epoch` token the `serverCursor` belongs to, captured from the
939
+ * same frame. Replayed as `sinceEpoch` on reconnect so the server resumes
940
+ * only when the client is still on the same changelog timeline — a reset or
941
+ * recycled shard advertises a new epoch, forcing a fresh snapshot. Absent
942
+ * until the first epoch-stamped frame arrives.
943
+ */
944
+ serverEpoch?: string;
945
+ readonly shardKey?: string;
946
+ }
947
+ /**
948
+ * Active subscription registry. The client keys subscriptions by
949
+ * `(functionPath, stableStringify(args), shardKey)` so duplicate calls share a
950
+ * single server-side registration. Args are stably encoded (keys sorted at every
951
+ * depth) so two structurally-equal arg records constructed with a different key
952
+ * order (`{ a, b }` vs `{ b, a }`) collapse to the same key instead of leaking a
953
+ * duplicate subscription.
954
+ */
955
+ declare class SubscriptionRegistry {
956
+ static key(functionPath: string, args: Record<string, unknown>, shardKey?: string): string;
957
+ private readonly byKey;
958
+ private readonly byId;
959
+ get(key: string): SubscriptionState | undefined;
960
+ getById(id: string): SubscriptionState | undefined;
961
+ add(state: SubscriptionState): void;
962
+ remove(state: SubscriptionState): void;
963
+ all(): SubscriptionState[];
964
+ }
965
+ /**
966
+ * Read/write handle over the client's live query cache, handed to a mutation's
967
+ * `withOptimisticUpdate` callback so a single mutation can optimistically patch
968
+ * many subscribed queries at once (Convex's `OptimisticLocalStore` model).
969
+ *
970
+ * `getQuery` reads the current value (server value or any still-pending
971
+ * optimistic override) of a subscribed query; `setQuery` registers a constant
972
+ * optimistic layer on top. The whole batch rebases onto incoming deltas and
973
+ * settles together — confirmed on the mutation's commit cursor, or rolled back
974
+ * on failure — the same per-subscription layer machinery the single-query
975
+ * per-call `optimistic` transform uses, generalized to N queries.
976
+ */
977
+ interface OptimisticLocalStore {
978
+ /**
979
+ * Every loaded subscription on `function_`, regardless of args, paired with
980
+ * the args it was subscribed under. Mirrors Convex's `getAllQueries` — handy
981
+ * when a write must patch every variant of a list query (all channels,
982
+ * all filters) without enumerating their args up front.
983
+ */
984
+ getAllQueries: <F extends FunctionReference>(function_: F) => {
985
+ args: ArgsOf<F>;
986
+ value: ReturnOf<F> | undefined;
987
+ }[];
988
+ /**
989
+ * Current cached value for the subscribed `(function_, args)` query, or
990
+ * `undefined` when nothing is subscribed/loaded for it. Reflects any
991
+ * optimistic override already written in this batch.
992
+ */
993
+ getQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>) => ReturnOf<F> | undefined;
994
+ /**
995
+ * Write an optimistic override for the subscribed `(function_, args)`
996
+ * query. A no-op (returns without effect) when no subscription matches —
997
+ * mirroring Convex, where you only patch queries the page is watching.
998
+ */
999
+ setQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>, value: ReturnOf<F> | undefined) => void;
1000
+ }
1001
+ /** A mutation's multi-query optimistic update: read/write the cache via `localStore`. */
1002
+ type OptimisticUpdate<Args> = (localStore: OptimisticLocalStore, args: Args) => void;
1003
+ /**
1004
+ * Build an {@link OptimisticLocalStore} bound to a subscription registry and the
1005
+ * mutation's shard key. Each `setQuery(value)` registers a constant-value layer
1006
+ * on its target subscription (via `applyOptimisticLayer`): the predicted value
1007
+ * survives incoming server deltas (re-clamped, masking concurrent changes to that
1008
+ * query — not merged) and drops gaplessly on the mutation's commit cursor, like
1009
+ * the single-query per-call `optimistic` path. Returns the store plus the ordered
1010
+ * `confirm` (success) and `rollback` (failure) closures every `setQuery` produced,
1011
+ * so the caller settles the whole batch when the mutation does.
1012
+ */
1013
+ declare const createLocalStore: (subscriptions: SubscriptionRegistry, shardKey: string | undefined, stableStringify: (value: unknown) => string) => {
1014
+ confirms: ((commitCursor: number | undefined) => void)[];
1015
+ rollbacks: (() => void)[];
1016
+ store: OptimisticLocalStore;
1017
+ };
1018
+ /**
1019
+ * Bounded async-iterator queue backing `LunoraClient.stream`.
1020
+ *
1021
+ * The server pushes one server `chunk` message per yielded value while the
1022
+ * client iterates with `for await (const chunk of stream)`. A producer that
1023
+ * outruns its consumer would otherwise OOM the page, so the buffer is bounded
1024
+ * — exceeding {@link DEFAULT_MAX_BUFFER} surfaces a `STREAM_BACKPRESSURE`
1025
+ * error to the iterator (and to the server-side cancel path).
1026
+ *
1027
+ * The queue is closed exactly once via {@link StreamHandle.complete} (success)
1028
+ * or {@link StreamHandle.fail} (transport / server error). Subsequent calls
1029
+ * are silent no-ops so a duplicate `complete` frame after a cancel doesn't
1030
+ * crash the page.
1031
+ */
1032
+ declare const DEFAULT_MAX_BUFFER = 1024;
1033
+ interface StreamHandle<T = unknown> {
1034
+ /** Mark the stream complete (no more chunks); resolves any pending consumer to `done:true`. */
1035
+ readonly complete: () => void;
1036
+ /** Surface an error to any pending consumer; subsequent pushes are dropped. */
1037
+ readonly fail: (error: Error) => void;
1038
+ /**
1039
+ * Push one chunk. Silent no-op once the stream is `complete`, `fail`-ed,
1040
+ * or `cancel`-ed. When the buffer is already at `maxBuffer`, the stream
1041
+ * is failed with a `STREAM_BACKPRESSURE` error and the push is dropped —
1042
+ * the producer never sees a thrown exception.
1043
+ */
1044
+ readonly push: (value: T) => void;
1045
+ }
1046
+ interface StreamIterable<T> extends AsyncIterable<T> {
1047
+ /** Cancel the stream from the consumer side: closes the iterator and notifies the registered canceller. */
1048
+ cancel: () => void;
1049
+ }
1050
+ /**
1051
+ * Build a stream handle paired with an async-iterable. The handle is the
1052
+ * server-driven side (the WS dispatcher pushes chunks / completes / errors);
1053
+ * the iterable is what the user awaits. `onCancel` is invoked exactly once
1054
+ * when the consumer calls `.cancel()` (or `.return()`) so the client can
1055
+ * send a `{type:"unsubscribe"}` frame to the server.
1056
+ */
1057
+ declare const createStream: <T>(options: {
1058
+ maxBuffer?: number;
1059
+ onCancel: () => void;
1060
+ }) => {
1061
+ handle: StreamHandle<T>;
1062
+ iterable: StreamIterable<T>;
1063
+ };
1064
+ /**
1065
+ * Aggregate live-socket health across every shard connection, for a UI status
1066
+ * indicator. `idle` = no socket opened yet; `connecting` = at least one socket
1067
+ * is (re)connecting and none is open; `connected` = at least one socket is open;
1068
+ * `offline` = sockets exist but all are down (between reconnect attempts).
1069
+ */
1070
+ type ConnectionStatus = "connected" | "connecting" | "idle" | "offline";
1071
+ /**
1072
+ * Terminal verdict for a mutation that passed through the offline queue,
1073
+ * delivered to {@link LunoraClient.onMutationSettled}.
1074
+ *
1075
+ * Unlike the Promise returned by {@link LunoraClient.mutation} — which only the
1076
+ * original caller can await, and which no longer exists after a reload — this
1077
+ * fires for *every* queued write the server (or the queue) reaches a verdict on,
1078
+ * including writes restored from durable storage in a later session. It is the
1079
+ * channel a UI uses to tell the user "your queued change couldn't be saved"
1080
+ * instead of silently dropping a rolled-back optimistic row.
1081
+ *
1082
+ * `status: "rejected"` carries the failure `code` (e.g. `CONFLICT`,
1083
+ * `OFFLINE_QUEUE_OVERFLOW`, `OFFLINE_IDENTITY_CHANGED`) and the `error`.
1084
+ * `hadAwaiter` is `false` for a write whose original `mutation()` Promise is
1085
+ * gone (a hydrated/post-reload replay or an eviction), so a listener can tell
1086
+ * "the caller already saw this" apart from "nothing else will report this".
1087
+ */
1088
+ interface MutationSettledEvent {
1089
+ /** The write's args, so a listener can describe or re-offer the change. */
1090
+ readonly args: Record<string, unknown>;
1091
+ /** Server/queue error code on `rejected` (e.g. `CONFLICT`), when present. */
1092
+ readonly code?: string;
1093
+ /** The rejection error on `status: "rejected"`. */
1094
+ readonly error?: unknown;
1095
+ /** The `&lt;file>:&lt;function>` reference of the mutation. */
1096
+ readonly functionPath: string;
1097
+ /** Whether a live caller was still awaiting this write's `mutation()` Promise. */
1098
+ readonly hadAwaiter: boolean;
1099
+ /** The write's stable id (idempotency key / queue id). */
1100
+ readonly id: string;
1101
+ /** Shard the write targeted, if any. */
1102
+ readonly shardKey?: string;
1103
+ /** Terminal outcome. */
1104
+ readonly status: "committed" | "rejected";
1105
+ }
1106
+ /**
1107
+ * Per-call options for {@link LunoraClient.mutation} — the optimistic-update
1108
+ * machinery plus `shardKey`. Exported (at the end of this file) so the framework
1109
+ * adapters (`@lunora/react`, `/solid`, `/svelte`, `/vue`) can type their
1110
+ * `mutate(args, options?)` against one canonical definition instead of
1111
+ * re-declaring it.
1112
+ */
1113
+ interface MutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unknown> {
1114
+ /**
1115
+ * Override the auto-generated idempotency key (`x-lunora-mutation-id`). Lets a
1116
+ * durable outbox replay a committed-but-unacked write under its *original* key
1117
+ * so the server dedups it instead of applying it twice. Omit for normal calls —
1118
+ * each then gets a fresh key.
1119
+ */
1120
+ mutationId?: string;
1121
+ optimistic?: (current: TCurrent | undefined) => TValue;
1122
+ /**
1123
+ * Convex-parity multi-query optimistic update. Receives an
1124
+ * `OptimisticLocalStore` over the live subscription cache plus the
1125
+ * mutation's args, so one mutation can patch many subscribed queries at
1126
+ * once; every write is rolled back atomically if the mutation fails.
1127
+ */
1128
+ optimisticUpdate?: OptimisticUpdate<TArgs>;
1129
+ shardKey?: string;
1130
+ }
1131
+ /** Callback a shape subscription invokes with its materialized rowset on every applied poke. */
1132
+ type ShapeCallback = (rows: Record<string, unknown>[]) => void;
1133
+ /**
1134
+ * The high-water marks a shape poke has now synced to the client: `checkpoint`
1135
+ * is the op-log cursor and `mutationId` the highest custom-mutator id the server
1136
+ * echoed for this client. A `@lunora/db` collection feeds these into its
1137
+ * checkpoint registry to drop optimistic overlays once the server's authoritative
1138
+ * rows have landed.
1139
+ */
1140
+ interface SyncWatermark {
1141
+ checkpoint?: number;
1142
+ mutationId?: number;
1143
+ }
1144
+ /**
1145
+ * Lunora browser/edge client. Talks RPC over HTTP and real-time deltas over
1146
+ * a single multiplexed WebSocket.
1147
+ *
1148
+ * Reconnect, offline queueing, and optimistic updates are all handled here;
1149
+ * see the package README for the wire protocol.
1150
+ */
1151
+ declare class LunoraClient {
1152
+ /** 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. */
1153
+ private static readonly MAX_POKE_BUFFERS;
1154
+ readonly url: string;
1155
+ readonly wsUrl: string;
1156
+ private wsToken;
1157
+ /** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
1158
+ private readonly authBasePath;
1159
+ private readonly fetchImpl;
1160
+ private readonly WebSocketImpl;
1161
+ private readonly bookmark;
1162
+ private readonly reconnectOptions;
1163
+ /** WS connect timeout (ms); `0` disables it. See {@link LunoraClientOptions.connectTimeoutMs}. */
1164
+ private readonly connectTimeoutMs;
1165
+ /** Keepalive cadence (ms); `0` disables the heartbeat. See {@link LunoraClientOptions.heartbeatIntervalMs}. */
1166
+ private readonly heartbeatIntervalMs;
1167
+ private readonly offlineQueue;
1168
+ /**
1169
+ * Durable outbox seam (the `@lunora/db` `createExecutorOutboxSink`). When
1170
+ * set, offline writes are delegated here and the built-in {@link OfflineQueue}
1171
+ * is bypassed, so a db app has exactly one durable write path.
1172
+ */
1173
+ private readonly outbox;
1174
+ /** Stable per-client id stamped onto every `OutboxMutation` (custom-mutator watermark). */
1175
+ private readonly clientId;
1176
+ /**
1177
+ * Highest custom-mutator watermark the server has echoed for this client,
1178
+ * keyed by shard bucket (`shardKey ?? ""`) since the DO tracks one
1179
+ * `__client_watermark` per shard. `callMutator` bumps it from every
1180
+ * ack; the `@lunora/db` mutator runtime seeds its `clientSeq` generator from
1181
+ * it so a reload (which resets the in-memory counter) never reissues a stale
1182
+ * sequence the server would silently swallow as a replay.
1183
+ */
1184
+ private readonly clientWatermarks;
1185
+ /** Monotonic per-client mutation counter backing the server `__client_watermark`. */
1186
+ private outboxMutationCounter;
1187
+ private readonly onPersistenceError;
1188
+ private readonly persistence;
1189
+ /** App/schema version stamped on persisted writes + cached reads; mismatches are purged. */
1190
+ private readonly persistenceVersion;
1191
+ /** Releases the multi-tab outbox-leader Web Lock on close (see `hydrateAsOutboxLeader`). */
1192
+ private outboxLeaderRelease;
1193
+ /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
1194
+ private readonly queryCache;
1195
+ /**
1196
+ * Values restored from the `queryCache` at construction, keyed by the
1197
+ * read-cache key, awaiting the `subscribe()` that will consume them. A
1198
+ * key is consumed (deleted) the first time its subscription is created, so
1199
+ * the cache only ever seeds the initial value — live frames take over after.
1200
+ */
1201
+ private readonly hydratedQueryCache;
1202
+ /**
1203
+ * Coalesced read-cache writes: the latest value per key, flushed to
1204
+ * the `queryCache` on a short debounce so a burst of deltas persists once.
1205
+ */
1206
+ private readonly pendingCacheWrites;
1207
+ private cacheFlushTimer;
1208
+ private readonly subscriptions;
1209
+ /** One {@link ShardConnection} per shard key (keyed by `shardKey ?? ""`). */
1210
+ private readonly connections;
1211
+ /** Default `connect`-envelope context applied to a shard with no explicit override. */
1212
+ private readonly defaultConnectionContext;
1213
+ /**
1214
+ * Per-shard `connect`-envelope context registered via `setConnectionContext`
1215
+ * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
1216
+ * on every socket open so it replays across reconnects, and forwarded to the
1217
+ * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
1218
+ * imperative (last-writer-wins) override; refcounted holders registered via
1219
+ * `acquireConnectionContext` live in `connectionContextHolders` and take
1220
+ * precedence — see `effectiveConnectionContext`.
1221
+ */
1222
+ private readonly connectionContexts;
1223
+ /**
1224
+ * Per-shard stack of refcounted connection-context holders (keyed by
1225
+ * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
1226
+ * is an opaque token carrying its `context`; the most-recently acquired
1227
+ * holder wins (last-writer-wins among live holders), and the context is only
1228
+ * cleared for a shard once its last holder releases — so two concurrently
1229
+ * mounted presence hooks on the same shard can't stomp each other's context
1230
+ * on cleanup. A holder is identified by reference identity so a release
1231
+ * removes exactly the right one regardless of stack position.
1232
+ */
1233
+ private readonly connectionContextHolders;
1234
+ private authToken;
1235
+ /**
1236
+ * Optional STABLE identity subject (a user id), the basis of the offline-queue
1237
+ * identity stamp when supplied. Keeps a same-user token *refresh* from looking
1238
+ * like an identity change (which would discard queued writes). `undefined` =
1239
+ * not supplied, so identity falls back to a hash of the raw token. See
1240
+ * `setAuthToken` / `identityFingerprint`.
1241
+ */
1242
+ private authSubject;
1243
+ /**
1244
+ * Identity stamp recorded against each queued offline mutation, keyed by
1245
+ * the queue-assigned mutation id. Captured at enqueue from the auth token
1246
+ * in effect at the time, and re-checked at flush so a queued write can
1247
+ * never replay under a different identity than the one that issued it.
1248
+ * See `identityFingerprint` for the fingerprint shape.
1249
+ */
1250
+ private readonly queuedIdentities;
1251
+ private closed;
1252
+ /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
1253
+ private readonly authTokenListeners;
1254
+ /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
1255
+ private readonly statusListeners;
1256
+ /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
1257
+ private readonly tokenExpiredListeners;
1258
+ /** Subscribers to offline-queued mutation verdicts (see `onMutationSettled`). */
1259
+ private readonly mutationSettledListeners;
1260
+ /** Subscribers to the offline-queue pending-count (see `onPendingChange`). */
1261
+ private readonly pendingChangeListeners;
1262
+ /**
1263
+ * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
1264
+ * of callbacks. Membership doubles as the resubscribe set replayed on every
1265
+ * (re)connect so a topic survives a socket bounce.
1266
+ */
1267
+ private readonly whisperHandlers;
1268
+ /** Last status broadcast, so we only notify listeners on an actual change. */
1269
+ private lastStatus;
1270
+ private nextSubId;
1271
+ private nextStreamId;
1272
+ /**
1273
+ * In-flight client-side stream readers, keyed by the stream id sent on the
1274
+ * wire. The handle drives the underlying iterator queue and `shardKey`
1275
+ * tells us which socket to push the cancel frame onto when the consumer
1276
+ * calls `.cancel()` or the iterator is garbage-collected.
1277
+ */
1278
+ private readonly streams;
1279
+ /** Live shape subscriptions (partial replication), keyed by their wire id. */
1280
+ private readonly shapeSubscriptions;
1281
+ /** In-flight pokes being assembled between `pokeStart` and `pokeEnd`, keyed by `pokeId`. */
1282
+ private readonly pokeBuffers;
1283
+ private nextShapeId;
1284
+ constructor(options: LunoraClientOptions);
1285
+ /**
1286
+ * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
1287
+ * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
1288
+ * sync across all mounted instances.
1289
+ *
1290
+ * Pass a STABLE `subject` (the user id) to key the offline-queue identity on
1291
+ * it instead of the token bytes, so a token *refresh* (same user, new JWT)
1292
+ * doesn't read as an identity change and discard queued writes. The subject is
1293
+ * **sticky**: a later call that omits it (or passes `undefined`) keeps the
1294
+ * established subject — so `setAuthToken(refreshedToken)` after a prior
1295
+ * `setAuthToken(token, user.id)` retains the identity. Pass `null` to clear it
1296
+ * (an explicit sign-out). Establishing the subject for the first time on an
1297
+ * UNCHANGED token (e.g. the user id resolves a tick after the token was set)
1298
+ * re-stamps any in-flight queued writes rather than dropping them — same
1299
+ * credential, just a more stable label. A real user switch (the token AND
1300
+ * subject both change) still drops the previous user's writes.
1301
+ *
1302
+ * Does NOT update the WebSocket auth — the WS token is fixed at upgrade
1303
+ * time and lives in the URL. To refresh live WS auth, call
1304
+ * {@link setWsToken} explicitly, which closes existing shard sockets to
1305
+ * force a reconnect with the new credential.
1306
+ */
1307
+ setAuthToken(token: string | null, subject?: string | null): void;
1308
+ getAuthToken(): string | null;
1309
+ /**
1310
+ * The current identity fingerprint (the same stamp queued offline writes
1311
+ * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
1312
+ * owns its own at-least-once replay outside the built-in `OfflineQueue` —
1313
+ * can drop a persisted write whose captured `identity` no longer matches the
1314
+ * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
1315
+ */
1316
+ currentIdentity(): string | null;
1317
+ /** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
1318
+ clientIdentifier(): string;
1319
+ /**
1320
+ * The highest custom-mutator watermark the server has echoed for this client
1321
+ * on the given shard (0 if none yet). The `@lunora/db` mutator runtime seeds
1322
+ * its `clientSeq` generator from this so a reload never reissues a sequence
1323
+ * the server has already applied (which it would swallow as a replay, silently
1324
+ * dropping the write).
1325
+ */
1326
+ confirmedMutationWatermark(shardKey?: string): number;
1327
+ /**
1328
+ * Push a custom mutator to its authoritative server impl over the watermark
1329
+ * protocol (Phase 4): the request carries `x-lunora-client-id` + a monotonic
1330
+ * `x-lunora-client-seq`, so the DO runs it exactly once and advances this
1331
+ * client's `__client_watermark`.
1332
+ *
1333
+ * Returns the server `result` plus `applied`: `true` when the DO ran this push
1334
+ * as the next-in-order mutation, `false` when it was a replay ack (`clientSeq`
1335
+ * was at or below the stored watermark — e.g. a stale sequence after a reload).
1336
+ * A `false` verdict tells the caller to reissue above the now-known watermark
1337
+ * (echoed into {@link confirmedMutationWatermark}) rather than treat the benign
1338
+ * ack as a confirmed write. Every ack — applied or not — bumps the watermark.
1339
+ *
1340
+ * This is the online transport for `@lunora/db`'s client-mutator runtime; the
1341
+ * optimistic overlay + durable-outbox concerns live in that runtime, not here.
1342
+ */
1343
+ callMutator(functionPath: string, args: Record<string, unknown>, options?: {
1344
+ clientSeq?: number;
1345
+ shardKey?: string;
1346
+ }): Promise<{
1347
+ applied: boolean;
1348
+ result: unknown;
1349
+ }>;
1350
+ /**
1351
+ * Subscribe to auth-token changes. Returns an unsubscribe function. The
1352
+ * listener is NOT invoked on registration — use {@link getAuthToken} for
1353
+ * the current value.
1354
+ */
1355
+ onAuthTokenChange(listener: (token: string | null) => void): Unsubscribe;
1356
+ /**
1357
+ * Fetch the currently authenticated user from better-auth's `get-session`
1358
+ * endpoint, returning the `user` record or `null` when signed out. Sends
1359
+ * the stored bearer token (if any) and `credentials: "include"` so a
1360
+ * cookie-session is also honoured. A network/parse failure or a non-OK
1361
+ * response resolves to `null` rather than throwing — callers treat "couldn't
1362
+ * resolve identity" as "signed out".
1363
+ *
1364
+ * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
1365
+ * the token changes (that's what `@lunora/react`'s `useAuth` does).
1366
+ */
1367
+ getCurrentUser(): Promise<User | null>;
1368
+ /**
1369
+ * Replace the token appended to WS upgrade URLs as `?token=…` and close
1370
+ * every open shard socket so the reconnect picks up the new value. Call
1371
+ * this whenever the user's WS credential changes (rotating the admin token
1372
+ * in the studio, switching workspaces, etc.). Bearer tokens for HTTP
1373
+ * RPC are independent — see {@link setAuthToken}.
1374
+ */
1375
+ setWsToken(token: string | undefined): void;
1376
+ /**
1377
+ * Register (or clear, with `undefined`) the app context sent in the `connect`
1378
+ * envelope for a shard's socket, overriding the client-wide
1379
+ * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
1380
+ * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
1381
+ * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
1382
+ * presence row is removed the instant the socket drops, with no TTL lag.
1383
+ *
1384
+ * Stored per shard and replayed on every (re)connect. When a socket for the
1385
+ * shard is already open, a fresh `connect` envelope is sent immediately so the
1386
+ * server sees the new context without waiting for a reconnect.
1387
+ */
1388
+ setConnectionContext(context: Record<string, unknown> | undefined, options?: {
1389
+ shardKey?: string;
1390
+ }): void;
1391
+ /**
1392
+ * Refcounted variant of {@link setConnectionContext}: register a connection
1393
+ * `context` for a shard and get back a release function. Unlike the imperative
1394
+ * setter, the context is only cleared once the *last* acquired holder releases
1395
+ * it — so two components (e.g. two mounted `usePresence` hooks) on the same
1396
+ * shard no longer clobber each other's context when one of them unmounts. The
1397
+ * most-recently acquired live holder wins (last-writer-wins), and releasing
1398
+ * the top holder falls back to the previous one rather than clearing.
1399
+ *
1400
+ * With a single holder the behaviour is identical to a
1401
+ * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
1402
+ * Releasing more than once is a no-op (the holder is matched by reference, so
1403
+ * a double release can't drop a different holder).
1404
+ */
1405
+ acquireConnectionContext(context: Record<string, unknown>, options?: {
1406
+ shardKey?: string;
1407
+ }): Unsubscribe;
1408
+ /**
1409
+ * Join a whisper `topic` and receive every ephemeral message other members
1410
+ * broadcast to it on the same shard (typing indicators, live cursors,
1411
+ * presence pings). Whispers never touch the server's durable state — there's
1412
+ * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
1413
+ * is left on the server once its last local handler unsubscribes.
1414
+ *
1415
+ * `handler` receives the raw `data` and the sender's verified `from` user id
1416
+ * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
1417
+ * (the default shard when omitted) — use the same shard you target with the
1418
+ * matching queries/mutations so members land on the same Durable Object.
1419
+ *
1420
+ * Security: whisper topics are NOT access-controlled beyond the shard
1421
+ * boundary — any client that can open a socket to the shard can join, read,
1422
+ * and inject on any topic name. `from` is server-stamped and unforgeable, but
1423
+ * do not put data on a whisper topic that some shard members shouldn't see,
1424
+ * and don't trust a whisper's `data` as authorization. Use a query/mutation
1425
+ * (with RLS) for anything privileged; whispers are for transient awareness.
1426
+ */
1427
+ whisperSubscribe(topic: string, handler: (data: unknown, from?: string) => void, options?: {
1428
+ shardKey?: string;
1429
+ }): Unsubscribe;
1430
+ /**
1431
+ * Broadcast an ephemeral `data` payload to the other members of a whisper
1432
+ * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
1433
+ * dropped when the shard socket isn't open (whispers are transient, never
1434
+ * queued), and the server silently drops it if the sender exceeds its
1435
+ * whisper rate budget. The sender never receives its own whisper. Omitting
1436
+ * `data` delivers JSON `null` to receivers (not `undefined`).
1437
+ */
1438
+ whisper(topic: string, data?: unknown, options?: {
1439
+ shardKey?: string;
1440
+ }): void;
1441
+ /**
1442
+ * Subscribe to token-expiry events: invoked whenever the server drops a
1443
+ * shard socket because the connection's credential lapsed (close code
1444
+ * `4001`). The client already reconnects automatically (re-resolving
1445
+ * identity from the cookie/token in effect); use this to refresh a
1446
+ * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
1447
+ * with a freshly minted one. Returns an unsubscribe function.
1448
+ */
1449
+ onTokenExpired(listener: () => void): Unsubscribe;
1450
+ /**
1451
+ * Current aggregate live-socket status across all shard connections. See
1452
+ * {@link ConnectionStatus}.
1453
+ */
1454
+ connectionStatus(): ConnectionStatus;
1455
+ /**
1456
+ * Subscribe to aggregate connection-status changes. Invokes `listener`
1457
+ * immediately with the current status, then on every transition. Returns an
1458
+ * unsubscribe function.
1459
+ */
1460
+ onConnectionStatus(listener: (status: ConnectionStatus) => void): Unsubscribe;
1461
+ /**
1462
+ * Number of offline writes waiting in the built-in queue to be sent — the
1463
+ * depth for a "N changes waiting to sync" indicator. Counts writes that are
1464
+ * queued (offline / mid-reconnect), not ones already in flight on the wire.
1465
+ * A `@lunora/db` app whose writes ride the unified outbox should read
1466
+ * `LunoraDb.pendingCount()` instead (this counts only the built-in queue).
1467
+ */
1468
+ pendingCount(): number;
1469
+ /**
1470
+ * Subscribe to changes in {@link pendingCount}. Invokes `listener` immediately
1471
+ * with the current count, then whenever the queue depth changes (a write is
1472
+ * enqueued, flushed, or discarded). Returns an unsubscribe function.
1473
+ */
1474
+ onPendingChange(listener: (pending: number) => void): Unsubscribe;
1475
+ /**
1476
+ * Subscribe to terminal verdicts for offline-queued mutations. The listener
1477
+ * fires once per queued write that commits or is rejected — including a write
1478
+ * restored from durable storage after a reload, whose original `mutation()`
1479
+ * Promise no longer exists (`hadAwaiter: false`), and a write the queue
1480
+ * evicts on overflow or discards on an identity change. This is the durable
1481
+ * channel for surfacing a rolled-back optimistic write to the UI; an online
1482
+ * mutation that never queued still surfaces through the Promise `mutation()`
1483
+ * returns. The listener is NOT invoked on registration. Returns an
1484
+ * unsubscribe function. See {@link MutationSettledEvent}.
1485
+ */
1486
+ onMutationSettled(listener: (event: MutationSettledEvent) => void): Unsubscribe;
1487
+ query<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
1488
+ shardKey?: string;
1489
+ }): Promise<ReturnOf<F>>;
1490
+ /**
1491
+ * Invoke a mutation. Errors propagate as rejections.
1492
+ *
1493
+ * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
1494
+ * only when the targeted shard's socket was open at least once already
1495
+ * (`wasEverConnected`), so the registry / resubscribe handshake has run.
1496
+ * Mutations issued before the very first WS connect to a shard fail fast.
1497
+ * Opt into queueing-before-first-connect via
1498
+ * `OfflineQueueOptions.queueBeforeFirstConnect`.
1499
+ */
1500
+ mutation<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>): Promise<ReturnOf<F>>;
1501
+ action<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
1502
+ shardKey?: string;
1503
+ }): Promise<ReturnOf<F>>;
1504
+ /**
1505
+ * Read the cross-shard request distribution for a `.shardBy(...)` table —
1506
+ * the feed the studio's `hot_shard` advisor lint consumes. Hits the
1507
+ * admin-gated `POST /_lunora/admin/shard-traffic` endpoint, which fans the
1508
+ * cheap per-shard `getMetrics` read out across every live shard and returns
1509
+ * each shard's `{ shardKey, requests }` total (a failed shard surfaces with
1510
+ * `requests: 0`). Requires the worker to be built with a `queryCoordinator`
1511
+ * and `adminToken`, and this client's auth token to match; defaults any
1512
+ * absent field so an older worker yields an empty-but-valid shape.
1513
+ */
1514
+ shardTraffic(table: string): Promise<ShardTrafficResult>;
1515
+ /**
1516
+ * List the functions queued via `runAfter` / `runAt`, soonest-due last
1517
+ * (the worker returns them in storage order). Hits the admin-gated
1518
+ * `/_lunora/admin/scheduled` endpoint, so the worker must be built with a
1519
+ * `schedulerDO` namespace and `adminToken`, and this client's auth token
1520
+ * must match. Powers `@lunora/studio`'s scheduled-jobs panel.
1521
+ */
1522
+ listScheduledJobs(): Promise<ScheduleRecord[]>;
1523
+ /**
1524
+ * Read the app-level workpool backlog that powers `@lunora/studio`'s SLO
1525
+ * view: per-pool `{ name, queued, inFlight, maxConcurrency }` plus the
1526
+ * app-wide `backlog` (total queued) and `inFlight` (total held slots) sums.
1527
+ * Hits the admin-gated `GET /_lunora/admin/scheduled/status` endpoint, so the
1528
+ * same preconditions as {@link listScheduledJobs} apply (a `schedulerDO`
1529
+ * namespace + `adminToken` on the worker and a matching auth token here).
1530
+ * Defaults any absent field so an older worker still yields a valid shape.
1531
+ */
1532
+ schedulerStatus(): Promise<SchedulerStatus>;
1533
+ /** Cancel a pending scheduled job by id. Returns whether a job was removed. */
1534
+ cancelScheduledJob(id: string): Promise<{
1535
+ cancelled: boolean;
1536
+ }>;
1537
+ /**
1538
+ * List the dead-letter jobs: schedules that exhausted their retry budget
1539
+ * and were parked instead of dropped. These never appear in
1540
+ * {@link listScheduledJobs} (their live header is gone), so this is the only
1541
+ * way the studio surfaces a permanently-failed job. Hits the admin-gated
1542
+ * `GET /_lunora/admin/scheduled/dead`; same preconditions as
1543
+ * {@link listScheduledJobs}. Powers `@lunora/studio`'s dead-letter panel.
1544
+ */
1545
+ listDeadJobs(): Promise<ScheduleRecord[]>;
1546
+ /**
1547
+ * Resurrect a dead-letter job by id: it re-enters the schedule with a fresh
1548
+ * retry budget and fires on the next drain. Returns whether a parked record
1549
+ * matched. Hits the admin-gated `POST /_lunora/admin/scheduled/dead/retry`.
1550
+ */
1551
+ retryDeadJob(id: string): Promise<{
1552
+ retried: boolean;
1553
+ }>;
1554
+ /**
1555
+ * Permanently drop a dead-letter job by id (the operator has decided not to
1556
+ * recover it). Returns whether a parked record was removed. Hits the
1557
+ * admin-gated `POST /_lunora/admin/scheduled/dead/cancel`.
1558
+ */
1559
+ removeDeadJob(id: string): Promise<{
1560
+ removed: boolean;
1561
+ }>;
1562
+ /**
1563
+ * List a workflow's instances via the admin Workflows proxy
1564
+ * (`/_lunora/admin/workflows/instances`) — the Cloudflare control-plane data
1565
+ * the `Workflow` binding can't expose. Requires the worker to be built with a
1566
+ * `workflowsClient` (Cloudflare account id + API token). When one isn't
1567
+ * configured this does NOT reject: the proxy returns a `200 { configured:
1568
+ * false }` sentinel, so the result resolves with `configured === false` and an
1569
+ * empty `instances` list — callers should branch on that flag rather than
1570
+ * try/catch. (The instance-detail / status endpoints still reject with 501.)
1571
+ * `name` is the deployed workflow name.
1572
+ */
1573
+ listWorkflowInstances(options: {
1574
+ name: string;
1575
+ page?: number;
1576
+ perPage?: number;
1577
+ status?: WorkflowInstanceStatus;
1578
+ }): Promise<WorkflowInstancePage>;
1579
+ /** Read one workflow instance with its step timeline (`/_lunora/admin/workflows/instance`). */
1580
+ getWorkflowInstance(options: {
1581
+ id: string;
1582
+ name: string;
1583
+ }): Promise<WorkflowInstanceDetail>;
1584
+ /** Pause / resume / terminate a workflow instance (`/_lunora/admin/workflows/status`). Needs an Edit-scoped Cloudflare token. */
1585
+ setWorkflowInstanceStatus(options: {
1586
+ action: WorkflowInstanceAction;
1587
+ id: string;
1588
+ name: string;
1589
+ }): Promise<{
1590
+ status: WorkflowInstanceStatus;
1591
+ }>;
1592
+ /**
1593
+ * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
1594
+ * WebSocket. `onJobs` fires with the full list on connect and on every
1595
+ * change (schedule / cancel / alarm-fire). Reconnects with the client's
1596
+ * configured backoff. Requires `wsToken` to be set to the admin token (the
1597
+ * browser can't send an `Authorization` header on a WS). Returns an
1598
+ * unsubscribe function that closes the socket and stops reconnecting.
1599
+ */
1600
+ subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
1601
+ /**
1602
+ * List the registered public functions (queries / mutations / actions) with
1603
+ * their kinds. Hits the admin-gated `GET /_lunora/admin/functions` endpoint —
1604
+ * the worker must be built with a `functions` registry and `adminToken`, and
1605
+ * this client's auth token must match. Powers `@lunora/studio`'s function
1606
+ * runner auto-discovery.
1607
+ */
1608
+ listFunctions(): Promise<FunctionDescriptor[]>;
1609
+ /**
1610
+ * List the code-defined cron triggers (the `cronJobs()` map injected on the
1611
+ * worker), each flattened to its firing `cron` expression. Hits the
1612
+ * admin-gated `GET /_lunora/admin/cron-jobs` endpoint — the worker must be
1613
+ * built with a `cronJobs` map and `adminToken`, and this client's auth token
1614
+ * must match. These are static (Cloudflare exposes no runtime cron
1615
+ * introspection), so the studio renders them read-only alongside the dynamic
1616
+ * scheduler jobs.
1617
+ */
1618
+ getCronJobs(): Promise<CronJobInfo[]>;
1619
+ /**
1620
+ * Manually fire one code-defined cron job by name — the same dispatch the
1621
+ * scheduled trigger runs (dispatch the function, or start the durable
1622
+ * workflow), on demand. Hits the admin-gated `POST /_lunora/admin/cron-jobs/run`
1623
+ * endpoint; the worker must be built with a `cronJobs` map and `adminToken`,
1624
+ * and this client's auth token must match. Resolves when the job has run (a
1625
+ * function job's shard response is 2xx, or the workflow instance was created)
1626
+ * and rejects with the dispatch error otherwise.
1627
+ */
1628
+ runCronJob(name: string): Promise<{
1629
+ name: string;
1630
+ ran: boolean;
1631
+ }>;
1632
+ /**
1633
+ * Fetch the generated OpenAPI 3.1 document. Hits the admin-gated
1634
+ * `GET /_lunora/admin/openapi` endpoint — the worker must be built with an
1635
+ * `openApiSpec` and `adminToken`, and this client's auth token must match.
1636
+ * Powers `@lunora/studio`'s API-reference (Scalar) view. When the worker has
1637
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenAPI
1638
+ * document (no `paths`), so callers can render a "not configured" state.
1639
+ */
1640
+ fetchOpenApi(): Promise<Record<string, unknown>>;
1641
+ /**
1642
+ * Fetch the generated OpenRPC 1.x document. Hits the admin-gated
1643
+ * `GET /_lunora/admin/openrpc` endpoint — the worker must be built with an
1644
+ * `openRpcSpec` and `adminToken`, and this client's auth token must match.
1645
+ * OpenRPC is the RPC-native spec (a `methods` array over the JSON-RPC-shaped
1646
+ * `POST /_lunora/rpc` transport); it documents the RPC functions only.
1647
+ * Powers `@lunora/studio`'s OpenRPC API-reference view. When the worker has
1648
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenRPC
1649
+ * document (no `methods`), so callers can render a "not configured" state.
1650
+ */
1651
+ fetchOpenRpc(): Promise<Record<string, unknown>>;
1652
+ /**
1653
+ * List objects in the storage bucket, optionally under a `prefix` and from a
1654
+ * pagination `cursor`. Hits the admin-gated `GET /_lunora/admin/storage`
1655
+ * endpoint — the worker must be built with a `storageList` function and
1656
+ * `adminToken`, and this client's auth token must match. Powers
1657
+ * `@lunora/studio`'s file browser.
1658
+ */
1659
+ listStorageObjects(options?: {
1660
+ bucket?: string;
1661
+ cursor?: string;
1662
+ limit?: number;
1663
+ prefix?: string;
1664
+ }): Promise<StorageListPage>;
1665
+ /**
1666
+ * Delete one object from the storage bucket by key. Hits the admin-gated
1667
+ * `DELETE /_lunora/admin/storage?key=…` endpoint — the worker must be built
1668
+ * with a `storageDelete` function and `adminToken`. Powers the studio file
1669
+ * browser's per-row delete; resolves `{ deleted, key }`.
1670
+ */
1671
+ deleteStorageObject(key: string, options?: {
1672
+ bucket?: string;
1673
+ }): Promise<{
1674
+ deleted: boolean;
1675
+ key: string;
1676
+ }>;
1677
+ /**
1678
+ * List the storage bucket names the worker exposes, for the studio file
1679
+ * browser's bucket picker. Hits the admin-gated
1680
+ * `GET /_lunora/admin/storage/buckets` endpoint — always resolves (an empty
1681
+ * array when the worker configures no `storageBuckets`, i.e. single-bucket).
1682
+ */
1683
+ listStorageBuckets(): Promise<string[]>;
1684
+ /**
1685
+ * Upload one object to the storage bucket. Hits the admin-gated
1686
+ * `PUT /_lunora/admin/storage?key=…` endpoint with the raw body and an
1687
+ * optional `contentType` header — the worker must be built with a
1688
+ * `storageUpload` function and `adminToken`. Powers the studio file
1689
+ * browser's upload control; resolves `{ etag?, key }`.
1690
+ */
1691
+ uploadStorageObject(options: {
1692
+ body: ArrayBuffer | Blob;
1693
+ bucket?: string;
1694
+ contentType?: string;
1695
+ key: string;
1696
+ }): Promise<{
1697
+ etag?: string;
1698
+ key: string;
1699
+ }>;
1700
+ /**
1701
+ * Build a (signed or public) URL for one object. Hits the admin-gated
1702
+ * `GET /_lunora/admin/storage/url?key=…` endpoint — the worker must be built
1703
+ * with a `storageSignedUrl` function and `adminToken`. Powers the studio
1704
+ * file browser's copy-URL action; resolves the URL string.
1705
+ *
1706
+ * `options.expiresInSeconds` requests a share-link lifetime, which is
1707
+ * validated/clamped server-side. The options object mirrors the worker's
1708
+ * `StorageSignedUrlFunction` options (a `password` / download-limit are noted
1709
+ * as future fields there).
1710
+ */
1711
+ signedStorageUrl(key: string, options?: {
1712
+ bucket?: string;
1713
+ expiresInSeconds?: number;
1714
+ }): Promise<string>;
1715
+ /**
1716
+ * List the `.global()` (D1-backed) tables with their row counts. Hits the
1717
+ * admin-gated `GET /_lunora/admin/global/tables` endpoint — the worker must
1718
+ * be built with a `globalIntrospector` and `adminToken`. Powers the data
1719
+ * browser's global mode.
1720
+ */
1721
+ listGlobalTables(): Promise<GlobalTableInfo[]>;
1722
+ /**
1723
+ * Read a page of rows from one `.global()` table. `filters` AND-narrows the
1724
+ * page to rows matching each `column = value` eq constraint — the drill-down a
1725
+ * facet-value click applies; the array is JSON-encoded into the `filters`
1726
+ * query param and the values are bound server-side.
1727
+ */
1728
+ readGlobalTablePage(options: {
1729
+ filters?: GlobalFilterClause[];
1730
+ limit?: number;
1731
+ offset?: number;
1732
+ table: string;
1733
+ }): Promise<GlobalTablePage>;
1734
+ /**
1735
+ * Summarise the distinct values of one column in a `.global()` table over the
1736
+ * active view (the same eq `filters` the browser is previewing) — the global
1737
+ * twin of the shard browser's facet. Hits the admin-gated
1738
+ * `GET /_lunora/admin/global/facet` endpoint; `column` is validated + bound
1739
+ * server-side. Powers the global data browser's facet sidebar.
1740
+ */
1741
+ facetGlobalColumn(options: {
1742
+ column: string;
1743
+ filters?: GlobalFilterClause[];
1744
+ limit?: number;
1745
+ table: string;
1746
+ }): Promise<GlobalFacetResult>;
1747
+ /**
1748
+ * List the schema's Vectorize indexes with their declared shape (table,
1749
+ * field, dimensions, metric, metadata) and live stats (vector count,
1750
+ * processing watermark) when the binding is reachable. Hits the admin-gated
1751
+ * `GET /_lunora/admin/vector/indexes` endpoint — the worker must be built
1752
+ * with a `vectorIntrospector` and `adminToken`. Powers the studio's vector
1753
+ * browser. Vectorize can't enumerate indexes at runtime, so this list comes
1754
+ * from the generated `LUNORA_VECTOR_INDEXES` registry.
1755
+ */
1756
+ listVectorIndexes(): Promise<VectorIndexSummary[]>;
1757
+ /**
1758
+ * Run a nearest-neighbour similarity query against one vector index: the
1759
+ * worker embeds `text` via the index's embedder and returns the top matches.
1760
+ * Hits the admin-gated `POST /_lunora/admin/vector/query` endpoint. Throws
1761
+ * `VECTOR_QUERY_UNSUPPORTED` when the worker's introspector has no embedder
1762
+ * wired (the index lists read-only).
1763
+ */
1764
+ queryVectorIndex(options: {
1765
+ name: string;
1766
+ text: string;
1767
+ topK?: number;
1768
+ }): Promise<VectorQueryMatch[]>;
1769
+ /**
1770
+ * List authenticated users, paged and optionally searched / filtered / sorted.
1771
+ * Hits the admin-gated `GET /_lunora/admin/auth/users` endpoint — the worker
1772
+ * must be built with an `authAdmin` and `adminToken`. Powers the studio's
1773
+ * users dashboard.
1774
+ */
1775
+ listAuthUsers(options?: {
1776
+ filterField?: string;
1777
+ filterValue?: string;
1778
+ limit?: number;
1779
+ offset?: number;
1780
+ search?: string;
1781
+ searchField?: string;
1782
+ sortBy?: string;
1783
+ sortDirection?: "asc" | "desc";
1784
+ }): Promise<AuthPage<AuthUser>>;
1785
+ /**
1786
+ * Create a user. Hits the admin-gated `POST /_lunora/admin/auth/users/create`
1787
+ * endpoint (requires the worker's `authAdmin` to implement `createUser`).
1788
+ * `data` carries any app-defined `user.additionalFields`.
1789
+ */
1790
+ createAuthUser(input: {
1791
+ data?: Record<string, unknown>;
1792
+ email: string;
1793
+ name: string;
1794
+ password?: string;
1795
+ role?: string | string[];
1796
+ }): Promise<AuthUser>;
1797
+ /** Set a user's role (string, or array joined comma-wise server-side). */
1798
+ setAuthUserRole(input: {
1799
+ role: string | string[];
1800
+ userId: string;
1801
+ }): Promise<AuthUser>;
1802
+ /** Ban a user. `expiresInSeconds` sets a temporary ban; omit it for a permanent one. Revokes the user's live sessions. */
1803
+ banAuthUser(input: {
1804
+ expiresInSeconds?: number;
1805
+ reason?: string;
1806
+ userId: string;
1807
+ }): Promise<AuthUser>;
1808
+ /** Lift a user's ban. */
1809
+ unbanAuthUser(input: {
1810
+ userId: string;
1811
+ }): Promise<AuthUser>;
1812
+ /** Set a user's password (admin override — no current-password challenge). */
1813
+ setAuthUserPassword(input: {
1814
+ newPassword: string;
1815
+ userId: string;
1816
+ }): Promise<void>;
1817
+ /** Permanently delete a user and revoke their sessions. */
1818
+ removeAuthUser(input: {
1819
+ userId: string;
1820
+ }): Promise<void>;
1821
+ /**
1822
+ * Mint an impersonation session for a user, returning its bearer `token`.
1823
+ * The caller is responsible for using the token (e.g. setting the session
1824
+ * cookie); the server performs no cookie round-trip.
1825
+ */
1826
+ impersonateAuthUser(input: {
1827
+ userId: string;
1828
+ }): Promise<AuthImpersonation>;
1829
+ /** Revoke a single session by its id (force sign-out of one device). */
1830
+ revokeAuthSession(input: {
1831
+ sessionId: string;
1832
+ }): Promise<void>;
1833
+ /** Revoke every session for a user (force sign-out everywhere). */
1834
+ revokeAuthUserSessions(input: {
1835
+ userId: string;
1836
+ }): Promise<void>;
1837
+ /**
1838
+ * Report which auth dashboard surfaces are available — derived server-side
1839
+ * from the enabled better-auth plugins. The studio renders only the panels
1840
+ * whose capability is `true`.
1841
+ */
1842
+ getAuthCapabilities(): Promise<AuthCapabilities>;
1843
+ /** Update a user's fields (name/email/app-defined `additionalFields`). */
1844
+ updateAuthUser(input: {
1845
+ data: Record<string, unknown>;
1846
+ userId: string;
1847
+ }): Promise<AuthUser>;
1848
+ /** List a user's linked accounts (credential / OAuth providers). Token material is stripped server-side. */
1849
+ listAuthAccounts(input: {
1850
+ userId: string;
1851
+ }): Promise<Record<string, unknown>[]>;
1852
+ /** Unlink a linked account from a user. */
1853
+ unlinkAuthAccount(input: {
1854
+ accountId: string;
1855
+ userId: string;
1856
+ }): Promise<void>;
1857
+ /** List a user's registered passkeys (requires the passkey plugin). */
1858
+ listAuthPasskeys(input: {
1859
+ userId: string;
1860
+ }): Promise<Record<string, unknown>[]>;
1861
+ /** Delete a passkey by id (requires the passkey plugin). */
1862
+ deleteAuthPasskey(input: {
1863
+ passkeyId: string;
1864
+ }): Promise<void>;
1865
+ /** Disable two-factor auth for a user (requires the two-factor plugin). */
1866
+ disableAuthTwoFactor(input: {
1867
+ userId: string;
1868
+ }): Promise<void>;
1869
+ /** List organizations, paged (requires the organization plugin). */
1870
+ listAuthOrganizations(options?: {
1871
+ limit?: number;
1872
+ offset?: number;
1873
+ }): Promise<AuthPage<Record<string, unknown>>>;
1874
+ /** List the members of an organization (requires the organization plugin). */
1875
+ listAuthOrgMembers(input: {
1876
+ limit?: number;
1877
+ offset?: number;
1878
+ organizationId: string;
1879
+ }): Promise<AuthPage<Record<string, unknown>>>;
1880
+ /** List an organization's pending invitations (requires the organization plugin). */
1881
+ listAuthOrgInvitations(input: {
1882
+ limit?: number;
1883
+ offset?: number;
1884
+ organizationId: string;
1885
+ }): Promise<AuthPage<Record<string, unknown>>>;
1886
+ /** Remove a member from an organization. */
1887
+ removeAuthOrgMember(input: {
1888
+ memberId: string;
1889
+ }): Promise<void>;
1890
+ /** Cancel a pending organization invitation. */
1891
+ cancelAuthOrgInvitation(input: {
1892
+ invitationId: string;
1893
+ }): Promise<void>;
1894
+ /** List auth sessions, paged and optionally filtered to one user. */
1895
+ listAuthSessions(options?: {
1896
+ limit?: number;
1897
+ offset?: number;
1898
+ userId?: string;
1899
+ }): Promise<AuthPage<AuthSession>>;
1900
+ subscribe<F extends FunctionReference>(function_: F, args: ArgsOf<F>, callback: (data: ReturnOf<F>) => void, options?: {
1901
+ onCheckpoint?: (watermark: SyncWatermark) => void;
1902
+ onError?: SubscriptionErrorCallback;
1903
+ shardKey?: string;
1904
+ }): Unsubscribe;
1905
+ /**
1906
+ * Subscribe to a declarative **shape** — server-side partial replication
1907
+ * scoped by `shardBy` + the shape's predicate + RLS. The parallel to
1908
+ * {@link subscribe} for the poke protocol: the client sends the shape *name* +
1909
+ * validated `args` (never a `where` the client could forge), the server seeds
1910
+ * the current membership as an insert-poke and streams live membership diffs.
1911
+ * Each applied poke materializes the shape's rowset and invokes `callback`.
1912
+ *
1913
+ * Unlike {@link subscribe}, shape subscriptions are NOT deduped by
1914
+ * (name, args): the server resolves them under the socket's verified identity,
1915
+ * so every call gets its own id + view. The returned function unsubscribes.
1916
+ */
1917
+ subscribeShape(shape: {
1918
+ args?: Record<string, unknown>;
1919
+ name: string;
1920
+ }, callback: ShapeCallback, options?: {
1921
+ onCheckpoint?: (watermark: SyncWatermark) => void;
1922
+ onError?: SubscriptionErrorCallback;
1923
+ shardKey?: string;
1924
+ }): Unsubscribe;
1925
+ /**
1926
+ * Open a streaming query. The function reference must be a
1927
+ * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
1928
+ * the type constraint catches accidental use of a query/mutation/action
1929
+ * reference at compile time. The returned iterable yields one element per
1930
+ * chunk frame the server pushes, terminating when the server sends
1931
+ * `complete` or the consumer calls `.cancel()`. Errors arrive as a
1932
+ * rejection on the next `next()`.
1933
+ *
1934
+ * Streams ride the same WS as subscriptions and share the unsubscribe
1935
+ * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id,
1936
+ * which the DO recognises as an abort signal for the in-flight iterator.
1937
+ *
1938
+ * Stream-start frames buffered while the socket is (re)connecting are
1939
+ * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
1940
+ * cap drops the oldest queued frame (and fails its consumer) so a stuck
1941
+ * reconnect can't OOM the page.
1942
+ */
1943
+ stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F>, options?: {
1944
+ maxBuffer?: number;
1945
+ shardKey?: string;
1946
+ }): StreamIterable<ReturnOf<F>>;
1947
+ close(): void;
1948
+ /**
1949
+ * Persist a mutation that can't go out on the wire right now (offline, or
1950
+ * mid-reconnect after a prior connect). The optimistic update has already
1951
+ * been applied by `mutation`; this only chooses the durable write path and
1952
+ * rolls the optimistic write back if persistence is rejected.
1953
+ *
1954
+ * Two paths: when an `outbox` sink is wired (the `@lunora/db` executor) it
1955
+ * owns persistence + at-least-once replay, so we delegate and return
1956
+ * optimistically (confirmation rides the synced view). Otherwise the
1957
+ * built-in `OfflineQueue` resolves/rejects the returned promise on replay.
1958
+ */
1959
+ private enqueueOfflineMutation;
1960
+ /**
1961
+ * Restore offline mutations persisted in a prior session and open a socket
1962
+ * for each shard they target so they flush once the WS reconnects. Failures
1963
+ * are swallowed — a broken durable store must not stop the client booting.
1964
+ */
1965
+ private hydratePersistedQueue;
1966
+ /**
1967
+ * Re-queue the durable offline writes — but only as the multi-tab LEADER. The
1968
+ * persisted queue is shared across a profile's tabs; without coordination
1969
+ * every tab would re-queue and replay the same writes (correct only because
1970
+ * the server dedups by idempotency key, but wasteful + racy). A Web Lock makes
1971
+ * exactly one tab hydrate; it holds the lock for its lifetime, so when it
1972
+ * closes another tab acquires the lock and takes over. Falls back to
1973
+ * unconditional hydration where Web Locks are unavailable (React Native, older
1974
+ * browsers, SSR) — single-context there, so no coordination is needed.
1975
+ */
1976
+ private hydrateAsOutboxLeader;
1977
+ /**
1978
+ * Load every cached query into {@link hydratedQueryCache} so the next
1979
+ * `subscribe()` for each key seeds its initial value off disk. A
1980
+ * subscription created before this resolves simply misses the cache (it
1981
+ * gets a live snapshot as before); the gate at seed time also drops any
1982
+ * entry whose stamped identity no longer matches the current one.
1983
+ */
1984
+ private hydrateQueryCache;
1985
+ /**
1986
+ * Consume the hydrated read-cache entry for a key (if any), gated on
1987
+ * identity. The entry is removed whether or not it matches — the cache only
1988
+ * ever seeds a subscription's first value. A mismatch (the cache was written
1989
+ * under a different identity) yields `undefined` so a signed-out cache never
1990
+ * leaks into a new session.
1991
+ */
1992
+ private takeHydratedCache;
1993
+ /**
1994
+ * Queue a coalesced read-cache write for a subscription's current value.
1995
+ * Latest-wins per key; flushed on a short debounce so a delta burst writes
1996
+ * once. No-op when the read cache is disabled or the value is undefined
1997
+ * (nothing to render offline).
1998
+ */
1999
+ private persistQueryValue;
2000
+ /** Drain {@link pendingCacheWrites} to the durable store. */
2001
+ private flushQueryCacheWrites;
2002
+ /** Derive the aggregate status from the per-shard socket states. */
2003
+ private computeStatus;
2004
+ /** Recompute the aggregate status and notify listeners if it changed. */
2005
+ private emitConnectionStatus;
2006
+ /**
2007
+ * Build a {@link MutationSettledEvent} from a queued entry and emit it on the
2008
+ * {@link onMutationSettled} channel. `item.id` is always assigned by the time
2009
+ * a write settles (`enqueue`/`hydrate` guarantee it), so the `?? ""` fallback
2010
+ * is unreachable — present only to satisfy the optional queue-id type.
2011
+ */
2012
+ private emitItemSettled;
2013
+ /**
2014
+ * Apply an optimistic update to the subscription that matches the mutation's
2015
+ * `(functionRef, args, shardKey)` triple, returning the rollback callbacks to
2016
+ * invoke if the mutation later fails.
2017
+ *
2018
+ * The registry is already indexed by exactly this triple via
2019
+ * `SubscriptionRegistry.key`, so at most one subscription can match. A direct
2020
+ * O(1) keyed lookup replaces the former O(N) linear scan over all subscriptions.
2021
+ *
2022
+ * `shardKey` normalization: both `undefined` and `""` map to the empty string
2023
+ * inside `SubscriptionRegistry.key` (via `?? ""`), so a mutation fired without
2024
+ * a shardKey correctly matches a subscription registered without one regardless
2025
+ * of whether the caller passed `undefined` or omitted the field.
2026
+ */
2027
+ private applyOptimisticUpdates;
2028
+ /**
2029
+ * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
2030
+ * to the live subscription registry. Each `setQuery` registers a constant
2031
+ * optimistic LAYER on its target subscription (via the same engine the
2032
+ * per-call `optimistic` path uses), so the multi-query patch rebases onto
2033
+ * incoming deltas and drops gaplessly on its commit cursor — its `confirm` /
2034
+ * `rollback` closures are appended to the mutation's settle lists. A throwing
2035
+ * callback unwinds its own partial writes — LIFO over just the rollbacks it
2036
+ * produced — and is swallowed, so a buggy optimistic update can never fail the
2037
+ * mutation or leave a partial patch live.
2038
+ */
2039
+ private applyOptimisticUpdate;
2040
+ private getConnection;
2041
+ private getOrCreateConnection;
2042
+ private wsUrlFor;
2043
+ /**
2044
+ * Build the outbound RPC headers: JSON content type, optional bearer auth,
2045
+ * the optional mutation-replay idempotency key, and the D1 read-your-writes
2046
+ * bookmark when the caller opted into `attachBookmark`. The mutation id
2047
+ * rides both the direct send and any offline-queue replay of the same write,
2048
+ * so a mutation the server already committed returns its cached result
2049
+ * instead of running twice.
2050
+ */
2051
+ private rpcRequestHeaders;
2052
+ private rpc;
2053
+ /**
2054
+ * Authenticated request to a non-RPC admin endpoint (the scheduler list /
2055
+ * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
2056
+ * worker's `{ error: { code, message } }` envelope as a coded `Error` —
2057
+ * mirroring {@link rpc} so callers see the same failure shape.
2058
+ */
2059
+ private adminFetch;
2060
+ /**
2061
+ * Resolve the effective connection context for a shard: the most-recently
2062
+ * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
2063
+ * back to the imperative {@link setConnectionContext} override, then the
2064
+ * client-wide default. Returns `undefined` when none apply.
2065
+ */
2066
+ private effectiveConnectionContext;
2067
+ /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
2068
+ private refreshConnectionContext;
2069
+ /**
2070
+ * Send the one-shot `connect` envelope on an open shard socket. Always sent
2071
+ * once per socket open, so the server's `onConnect` hooks fire symmetrically
2072
+ * with `onDisconnect` (which the DO dispatches unconditionally at close for
2073
+ * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
2074
+ * hooks are registered, so the single frame costs nothing in the common case.
2075
+ *
2076
+ * The shard's registered context (or the client-wide default) rides along
2077
+ * when one is set — the DO records it on the attachment for replay to
2078
+ * `onDisconnect`. A socket with no registered context still announces itself;
2079
+ * the envelope simply omits `context`, which is optional on the wire.
2080
+ * Register a context — e.g. `setConnectionContext({})` — to attach app state
2081
+ * to the lifecycle dispatch.
2082
+ */
2083
+ private sendConnectEnvelope;
2084
+ /**
2085
+ * Re-send every shape subscription bound to `shardKey` over its (now open)
2086
+ * socket. Each frame carries the shape's last applied checkpoint, so the
2087
+ * server resumes from it — or re-seeds when the cursor fell below CDC
2088
+ * retention or the epoch forked.
2089
+ */
2090
+ private resendShapeSubscriptions;
2091
+ private ensureSocket;
2092
+ private handleDisconnect;
2093
+ /**
2094
+ * Begin the keepalive heartbeat on an open connection. Each tick sends a
2095
+ * {@link WS_KEEPALIVE_PING} text frame the server answers from its
2096
+ * hibernation auto-response without waking the DO. A no-op when the
2097
+ * heartbeat is disabled (an interval of zero or less); idempotent — any
2098
+ * existing timer is cleared first so a reconnect can't leak intervals.
2099
+ */
2100
+ private startHeartbeat;
2101
+ /** Clear a connection's keepalive timer, if any. Safe to call repeatedly. */
2102
+ private stopHeartbeat;
2103
+ /** Mark every subscription bound to `shardKey` as needing a fresh ack. */
2104
+ private markShardPendingAck;
2105
+ private sendSubscribeIfOpen;
2106
+ private sendShapeSubscribeIfOpen;
2107
+ private handleServerMessage;
2108
+ private handleErrorMessage;
2109
+ private handlePokeStart;
2110
+ private handlePokePart;
2111
+ private handlePokeEnd;
2112
+ /** Materialize a shape's keyed view to an array and invoke its callbacks. */
2113
+ private emitShapeRows;
2114
+ private handleDataMessage;
2115
+ /**
2116
+ * Handle a `resume` frame (Pillar 1b): the server proved nothing the
2117
+ * subscription reads changed since our `sinceSeq`, so the cached value is
2118
+ * still current. We keep `lastValue` as-is, mark the sub acked, and advance
2119
+ * the cursor (re-persisting so the next reconnect resumes from the newer
2120
+ * watermark). No callback fires — the value didn't change, and `subscribe()`
2121
+ * already replayed the cached value to every consumer synchronously.
2122
+ */
2123
+ private handleResumeMessage;
2124
+ /**
2125
+ * Handle a `settled` frame: a write touched one of this subscription's read
2126
+ * tables but produced a byte-identical result, so the server suppressed the
2127
+ * data frame. Like {@link handleResumeMessage} the value didn't change — we
2128
+ * advance the resume position and re-persist — but we ALSO surface the echoed
2129
+ * custom-mutator watermark via `onCheckpoint` so a `@lunora/db` list
2130
+ * collection drops the optimistic overlay for the confirmed write (otherwise
2131
+ * its checkpoint gate, fed only by data frames, would hang forever). Sent
2132
+ * only to custom-mutator clients; plain `useQuery` subscribers leave
2133
+ * `onCheckpoint` unset and this is a near no-op.
2134
+ */
2135
+ private handleSettledMessage;
2136
+ /**
2137
+ * Mark `state` acked and, when the frame carries a newer cursor/epoch than
2138
+ * the cached position, advance the resume watermark and re-persist. Shared by
2139
+ * the `resume` and `settled` frame handlers — both acknowledge "nothing the
2140
+ * client must re-render changed, but the resume position may have moved".
2141
+ */
2142
+ private ackAndAdvanceCursor;
2143
+ /**
2144
+ * Resolve the value to publish for a `data`/`delta` frame.
2145
+ *
2146
+ * A `data` frame is an authoritative snapshot (the server re-execution path)
2147
+ * and always replaces the cached value wholesale. A `delta` frame carrying a
2148
+ * structured `MutationDelta` (the `broadcastDelta` row-change path) is
2149
+ * merged incrementally into the cached list — preserving order, no dup/loss —
2150
+ * so each subscription (including every paginated page) updates by delta
2151
+ * rather than a full re-send. We fall back to full replacement when the
2152
+ * delta isn't a recognisable row change, when there's no cached value yet,
2153
+ * or when it can't be applied cleanly against the current cached shape.
2154
+ */
2155
+ private resolveDataPayload;
2156
+ /** Route an inbound whisper to the topic's handlers on the originating shard. */
2157
+ private dispatchWhisper;
2158
+ /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
2159
+ private notifyTokenExpired;
2160
+ private handleCompleteMessage;
2161
+ private unpersist;
2162
+ /**
2163
+ * Stable, non-reversible fingerprint of the current auth identity used to
2164
+ * stamp queued offline writes. `null` (signed out) is its own identity and
2165
+ * never matches a bearer-token fingerprint. The raw token is never stored;
2166
+ * a length-prefixed FNV-1a hash is enough to detect an identity *change*
2167
+ * without keeping the credential around in the queue map.
2168
+ */
2169
+ private identityFingerprint;
2170
+ /**
2171
+ * Drain every in-memory offline write and reject it because the auth
2172
+ * identity changed. Durable entries are also dropped from persistence so a
2173
+ * later `hydrate` can't resurrect another user's writes. Stamps are cleared
2174
+ * alongside. Persisted entries restored without a live awaiter still get
2175
+ * unpersisted here.
2176
+ */
2177
+ private rejectQueuedForIdentityChange;
2178
+ /**
2179
+ * Migrate every live identity stamp from `from` to `to` — used when the auth
2180
+ * identity label changes but the underlying credential (token) does NOT, e.g.
2181
+ * the user id resolves a tick after the token was set. The in-memory
2182
+ * `queuedIdentities` map is the flush-time source of truth, so re-stamping it
2183
+ * keeps the in-flight writes replayable under the new (more stable) identity
2184
+ * instead of the flush guard discarding them as a mismatch.
2185
+ */
2186
+ private restampQueuedIdentity;
2187
+ /**
2188
+ * Drop the durable read cache on an identity change so a cached value stamped
2189
+ * under the previous identity can never hydrate into a new session. Clears
2190
+ * the in-flight write batch and the not-yet-consumed hydrated entries too;
2191
+ * the durable `clear()` is best-effort.
2192
+ */
2193
+ private clearQueryCacheForIdentityChange;
2194
+ private flushOfflineQueue;
2195
+ }
2196
+ export { SubscriptionState as $, ArgsOf as A, BookmarkStorage as B, CachedQuery as C, DEFAULT_MAX_BUFFER as D, SchedulerStatus as E, FunctionReference as F, GlobalFacetResult as G, ServerMessage as H, ServerPokeEndMessage as I, ServerPokePartMessage as J, ServerPokeStartMessage as K, LunoraClient as L, MutationCallOptions as M, ShardTrafficEntry as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReturnOf as R, SubscriptionError as S, ShardTrafficResult as T, User as U, StorageListPage as V, StorageObject as W, StreamHandle as X, StreamIterable as Y, SubscriptionCallback as Z, SubscriptionRegistry as _, Unsubscribe as a, SyncWatermark as a0, WorkflowInstanceAction as a1, WorkflowInstanceDetail as a2, WorkflowInstancePage as a3, WorkflowInstanceStatus as a4, WorkflowInstanceSummary as a5, WorkflowStepDetail as a6, createLocalStore as a7, createStream as a8, SubscriptionErrorCallback as b, PersistenceAdapter as c, ReconnectOptions as d, ClientMessage as e, ClientShapeSubscribeMessage as f, ClientShapeUnsubscribeMessage as g, ConnectionStatus as h, FunctionArgumentDescriptor as i, FunctionDescriptor as j, GlobalFacetValue as k, GlobalFilterClause as l, GlobalTableInfo as m, GlobalTablePage as n, LunoraClientOptions as o, MutationSettledEvent as p, OptimisticLocalStore as q, OptimisticUpdate as r, OutboxMutation as s, OutboxSink as t, PersistedMutation as u, RowOp as v, RpcEnvelope as w, RpcResponseBody as x, ScheduleRecord as y, SchedulerPoolStatus as z };