@lunora/client 1.0.0-alpha.17 → 1.0.0-alpha.171

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