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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +2 -0
  3. package/dist/auth/index.d.mts +11 -10
  4. package/dist/auth/index.d.ts +11 -10
  5. package/dist/auth/index.mjs +1 -60
  6. package/dist/index.d.mts +736 -172
  7. package/dist/index.d.ts +736 -172
  8. package/dist/index.mjs +1 -14
  9. package/dist/packem_shared/CONFLICT_ERROR_CODE-B2SU0CaJ.mjs +1 -0
  10. package/dist/packem_shared/ClientServiceWorker-CRQ5yl7-.mjs +1 -0
  11. package/dist/packem_shared/DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs +1 -0
  12. package/dist/packem_shared/LunoraClient-CB5y0HME.mjs +1 -0
  13. package/dist/packem_shared/OfflineQueue-y4mymc5n.mjs +1 -0
  14. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-D96iRJDY.mjs +1 -0
  15. package/dist/packem_shared/SKIP-CArzT3Vl.mjs +1 -0
  16. package/dist/packem_shared/SubscriptionRegistry-C72rCp44.mjs +1 -0
  17. package/dist/packem_shared/TabCoordinator-CMFYQCL-.mjs +1 -0
  18. package/dist/packem_shared/anyApi-BD4dgvDY.mjs +1 -0
  19. package/dist/packem_shared/applyDelta-DXqQORbM.mjs +1 -0
  20. package/dist/packem_shared/createAsyncStoragePersistence-BRLqeXsC.mjs +1 -0
  21. package/dist/packem_shared/createClientQuery-CrdRoicO.mjs +1 -0
  22. package/dist/packem_shared/createInMemoryBookmarkStorage-DCd5Ej-t.mjs +1 -0
  23. package/dist/packem_shared/createInMemoryPersistence-CQYXy8UP.mjs +1 -0
  24. package/dist/packem_shared/createInMemoryQueryCache-DjCKrLjk.mjs +1 -0
  25. package/dist/packem_shared/createLocalStore-CwuKPK9x.mjs +1 -0
  26. package/dist/packem_shared/createMutationRunner-lQXH8Amk.mjs +1 -0
  27. package/dist/packem_shared/createMutatorRunner-BVzo0FBZ.mjs +1 -0
  28. package/dist/packem_shared/createReconnect-CFT7YRSR.mjs +1 -0
  29. package/dist/packem_shared/createReply-DF0jRsv-.mjs +1 -0
  30. package/dist/packem_shared/createServerClient-C1At_rrh.mjs +1 -0
  31. package/dist/packem_shared/createSnapshotPrecondition-CKvCNKyD.mjs +1 -0
  32. package/dist/packem_shared/deserializePreloaded-CHfOFpka.mjs +1 -0
  33. package/dist/packem_shared/getServerSession-CGjgRBAE.mjs +1 -0
  34. package/dist/packem_shared/httpStream-Cz4_QyjV.mjs +11 -0
  35. package/dist/packem_shared/idb-utility-C-DR8nG1.mjs +1 -0
  36. package/dist/packem_shared/local-store-DFMSEM2j.mjs +1 -0
  37. package/dist/packem_shared/lunora-client.d-D_WLwpn0.d.mts +2175 -0
  38. package/dist/packem_shared/lunora-client.d-cFPjoyDb.d.ts +2175 -0
  39. package/dist/packem_shared/offline-queue-BeWay5u5.mjs +1 -0
  40. package/dist/packem_shared/preload.d-BkbCVtZe.d.ts +21 -0
  41. package/dist/packem_shared/preload.d-DNxm6niZ.d.mts +21 -0
  42. package/dist/packem_shared/preloadQuery-DjwSjFwt.mjs +1 -0
  43. package/dist/packem_shared/types.d-CA7ZeJm9.d.mts +942 -0
  44. package/dist/packem_shared/types.d-CA7ZeJm9.d.ts +942 -0
  45. package/dist/packem_shared/wire-codec-D_fiax9d.mjs +1 -0
  46. package/dist/packem_shared/wire-key-j8BZ65HQ.mjs +1 -0
  47. package/dist/pagination/index.d.mts +42 -42
  48. package/dist/pagination/index.d.ts +42 -42
  49. package/dist/pagination/index.mjs +1 -61
  50. package/dist/query/index.d.mts +43 -42
  51. package/dist/query/index.d.ts +43 -42
  52. package/dist/query/index.mjs +1 -1
  53. package/dist/service.d.mts +49 -0
  54. package/dist/service.d.ts +49 -0
  55. package/dist/service.mjs +1 -0
  56. package/dist/ssr/index.d.mts +80 -79
  57. package/dist/ssr/index.d.ts +80 -79
  58. package/dist/ssr/index.mjs +1 -4
  59. package/dist/upload.d.mts +35 -0
  60. package/dist/upload.d.ts +35 -0
  61. package/dist/upload.mjs +1 -0
  62. package/package.json +13 -1
  63. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +0 -4
  64. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +0 -107
  65. package/dist/packem_shared/LunoraClient-DHMV-94j.mjs +0 -2198
  66. package/dist/packem_shared/OfflineQueue-D5p_QgF_.mjs +0 -127
  67. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  68. package/dist/packem_shared/SubscriptionRegistry-Dn-7k7eo.mjs +0 -1
  69. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +0 -61
  70. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  71. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  72. package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +0 -105
  73. package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +0 -138
  74. package/dist/packem_shared/createLocalStore-DSUfoLqY.mjs +0 -36
  75. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  76. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  77. package/dist/packem_shared/createServerClient-DMh-2UDv.mjs +0 -11
  78. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  79. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  80. package/dist/packem_shared/lunora-client.d-CbnxmuqG.d.mts +0 -1623
  81. package/dist/packem_shared/lunora-client.d-CbnxmuqG.d.ts +0 -1623
  82. package/dist/packem_shared/preload.d-Bhq6DBSe.d.mts +0 -20
  83. package/dist/packem_shared/preload.d-C73DT6bL.d.ts +0 -20
  84. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  85. package/dist/packem_shared/subscription-C1Jy7HiF.mjs +0 -55
@@ -1,1623 +0,0 @@
1
- import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthSession } from '@lunora/runtime';
2
- /** The registered function kinds a {@link FunctionReference} can describe. `stream` is a query that yields multiple frames over the WS. */
3
- type FunctionKind = "action" | "mutation" | "query" | "stream";
4
- /**
5
- * Opaque reference to a registered function emitted by `@lunora/codegen`.
6
- *
7
- * At runtime it carries the `<file>:<function>` identifier in `__lunoraRef`.
8
- * Generated declarations decorate this with phantom type parameters so the
9
- * client can infer args / return values per call site.
10
- */
11
- interface FunctionReference<Kind extends FunctionKind = FunctionKind, Args = unknown, Return = unknown> {
12
- /**
13
- * Phantom marker carrying the `Kind`/`Args`/`Return` type parameters for
14
- * inference. Never present at runtime; declared as a covariant (output)
15
- * position so a concrete reference stays assignable to a widened one.
16
- */
17
- readonly __lunoraPhantom?: {
18
- args: Args;
19
- kind: Kind;
20
- returns: Return;
21
- };
22
- readonly __lunoraRef: string;
23
- }
24
- /** Extract the args type from a {@link FunctionReference}. */
25
- type ArgsOf<F> = F extends FunctionReference<infer _K, infer A, infer _R> ? A : never;
26
- /** Extract the return type from a {@link FunctionReference}. */
27
- type ReturnOf<F> = F extends FunctionReference<infer _K, infer _A, infer R> ? R : never;
28
- type Unsubscribe = () => void;
29
- /**
30
- * Serializable result of `preloadQuery`. Produced on the server during SSR,
31
- * embedded in the rendered HTML, then handed to `usePreloadedQuery` on the
32
- * client so the first render shows the server value with no loading flash
33
- * before a live subscription attaches. Every field survives `JSON.stringify`.
34
- */
35
- interface Preloaded<T = unknown> {
36
- readonly __lunoraPreloaded: true;
37
- readonly args: Record<string, unknown>;
38
- readonly functionPath: string;
39
- readonly shardKey?: string;
40
- readonly value: T;
41
- }
42
- /**
43
- * Pluggable storage for the `x-d1-bookmark` value used to provide
44
- * read-your-writes between a mutation and subsequent queries.
45
- */
46
- interface BookmarkStorage {
47
- get: () => string | null;
48
- set: (value: string | null) => void;
49
- }
50
- interface ReconnectOptions {
51
- initialDelayMs?: number;
52
- jitter?: boolean;
53
- maxDelayMs?: number;
54
- }
55
- /** Which durable-storage operation failed, passed to {@link OfflineQueueOptions.onPersistenceError}. */
56
- type PersistenceOperation = "append" | "clear" | "load" | "remove";
57
- /** Context handed to a persistence-error handler. */
58
- interface PersistenceErrorContext {
59
- readonly error: unknown;
60
- /** The mutation id involved, when the failing op was scoped to one (`append`/`remove`). */
61
- readonly mutationId?: string;
62
- readonly operation: PersistenceOperation;
63
- }
64
- interface OfflineQueueOptions {
65
- maxItems?: number;
66
- /**
67
- * Invoked when a {@link PersistenceAdapter} call rejects (e.g. IndexedDB quota
68
- * exceeded). Without a handler, failures are logged via `console.warn` so they
69
- * are never fully silent. Note: a failed `append` means the write is queued in
70
- * memory but NOT durable — it will not survive a reload.
71
- */
72
- onPersistenceError?: (context: PersistenceErrorContext) => void;
73
- /**
74
- * Queue mutations issued before a shard's first successful WebSocket
75
- * connect (defaults to `false`). The standard behaviour (`LunoraClient`'s
76
- * `mutation()`) queues only when the targeted shard has been connected at
77
- * least once (`wasEverConnected`), so the registry / resubscribe handshake
78
- * has run. Set this to `true` for offline-first apps that want to enqueue
79
- * writes on the very first session before the WS is up.
80
- */
81
- queueBeforeFirstConnect?: boolean;
82
- }
83
- /**
84
- * Serializable shape of an offline mutation, durably stored by a
85
- * {@link PersistenceAdapter} so queued writes survive a reload/crash. The live
86
- * `resolve`/`reject` callbacks of an in-flight `QueuedMutation` are *not*
87
- * persisted — a restored mutation is replayed with no original awaiter.
88
- */
89
- interface PersistedMutation {
90
- args: Record<string, unknown>;
91
- functionPath: string;
92
- id: string;
93
- /**
94
- * Issuing identity fingerprint, persisted so a hydrated write replays only
95
- * under the identity that queued it (`null` = queued while signed out).
96
- * Absent on records written by older client versions, which replay under
97
- * the ambient identity for back-compat.
98
- */
99
- identity?: string | null;
100
- shardKey?: string;
101
- }
102
- /**
103
- * Durable store for the offline mutation queue. The default client keeps the
104
- * queue in memory; supplying an adapter (e.g. `createIndexedDbPersistence`)
105
- * makes queued writes survive a page reload. Implementations must preserve FIFO
106
- * (enqueue) order in `PersistenceAdapter.load`.
107
- *
108
- * Replay semantics are at-least-once: a mutation is removed only after the
109
- * server confirms (or rejects) it, so a crash between commit and `remove` can
110
- * replay it again on the next load.
111
- */
112
- interface PersistenceAdapter {
113
- /** Append a mutation to durable storage (called on enqueue). */
114
- append: (mutation: PersistedMutation) => Promise<void>;
115
- /** Drop every persisted mutation (e.g. on logout). */
116
- clear: () => Promise<void>;
117
- /** Load all persisted mutations in FIFO order — called once at startup. */
118
- load: () => Promise<PersistedMutation[]>;
119
- /** Remove a mutation by id once it has been replayed (resolved or rejected). */
120
- remove: (id: string) => Promise<void>;
121
- }
122
- /**
123
- * One persisted query result in the durable read cache (Pillar 2). Keyed in the
124
- * store by `shardKey + functionPath + argsKey`; the record carries everything
125
- * needed to render offline on reload and to resume the live subscription.
126
- */
127
- interface CachedQuery {
128
- /**
129
- * Issuing identity fingerprint (same shape the offline queue stamps). A
130
- * cached value only hydrates when it matches the current identity, so a
131
- * signed-out cache never leaks into a new session. `null` = cached while
132
- * signed out.
133
- */
134
- identity: string | null;
135
- /**
136
- * The `cursor` high-watermark this value reflects, replayed as `sinceSeq`
137
- * on reconnect so the server can resume instead of re-snapshotting. Absent
138
- * when the value predates CDC / no cursor was advertised.
139
- */
140
- serverCursor?: number;
141
- /**
142
- * The CDC `epoch` the `serverCursor` belongs to, replayed as `sinceEpoch`
143
- * on reconnect so the server only resumes when the client is still on the
144
- * same changelog timeline. Absent when no epoch was advertised.
145
- */
146
- serverEpoch?: string;
147
- /** Wall-clock millis the value was written — drives LRU eviction. */
148
- ts: number;
149
- /** The full query result last seen from the server. */
150
- value: unknown;
151
- }
152
- /**
153
- * Durable store for the client read cache (Pillar 2): query results survive a
154
- * reload so reads hydrate from disk and render immediately while the socket
155
- * reconnects. Opt-in via {@link LunoraClientOptions.queryCache}; omit to keep
156
- * reads in memory only (today's behaviour). Mirrors {@link PersistenceAdapter}'s
157
- * shape over the same IndexedDB plumbing.
158
- */
159
- interface QueryCacheAdapter {
160
- /** Drop every cached query (e.g. on logout / identity change). */
161
- clear: () => Promise<void>;
162
- /** Load every cached query — called once at startup to hydrate reads. */
163
- load: () => Promise<(CachedQuery & {
164
- key: string;
165
- })[]>;
166
- /** Upsert one cached query by key (called when a subscription value advances). */
167
- put: (key: string, entry: CachedQuery) => Promise<void>;
168
- /** Remove one cached query by key. */
169
- remove: (key: string) => Promise<void>;
170
- }
171
- interface LunoraClientOptions {
172
- /**
173
- * Base path the worker mounts better-auth at, used by the client's
174
- * `getCurrentUser()` to reach the `get-session` route. Defaults to
175
- * `/api/auth` (matching `@lunora/auth`'s `DEFAULT_AUTH_BASE_PATH`).
176
- */
177
- authBasePath?: string;
178
- bookmarkStorage?: BookmarkStorage;
179
- /**
180
- * Default app context sent in the `connect` envelope right after each socket
181
- * opens, forwarded to the server's `onConnect`/`onDisconnect` lifecycle hooks
182
- * as `event.context`. A per-shard context registered via
183
- * `setConnectionContext` overrides this for that shard. Omit when no lifecycle
184
- * hook needs connection context.
185
- */
186
- connectionContext?: Record<string, unknown>;
187
- /**
188
- * Fail-fast timeout (ms) for opening a subscription WebSocket. If the
189
- * handshake doesn't complete within this window — a hung dev proxy or a cold
190
- * worker that never upgrades — the client force-closes the socket and routes
191
- * through its normal reconnect/backoff (surfacing `offline` status) instead
192
- * of leaving the live channel silently stuck on the browser's much longer
193
- * default. Does not affect HTTP queries/mutations (those never ride the WS).
194
- * Defaults to 10000 (10s); set to `0` (or negative) to disable.
195
- */
196
- connectTimeoutMs?: number;
197
- fetch?: typeof fetch;
198
- /**
199
- * Interval (ms) between keepalive pings sent on each open subscription
200
- * socket. The server answers them via the Durable Object's hibernation
201
- * auto-response WITHOUT waking the DO, so an idle socket stays alive across
202
- * hibernation without a billable wakeup. Defaults to 30000 (30s); set to
203
- * `0` (or a negative value) to disable the heartbeat entirely.
204
- */
205
- heartbeatIntervalMs?: number;
206
- offlineQueue?: OfflineQueueOptions;
207
- /** Durable store for the offline mutation queue; omit to keep it in memory. */
208
- persistence?: PersistenceAdapter;
209
- /**
210
- * Durable store for the read cache (Pillar 2). When supplied, query results
211
- * are persisted as their subscriptions advance and hydrated on construction
212
- * so a reload renders cached data before the socket reconnects, then resumes
213
- * the live subscription from the persisted cursor. Omit (or pass `false`) to
214
- * keep reads in memory only — the default, unchanged behaviour.
215
- */
216
- queryCache?: QueryCacheAdapter | false;
217
- reconnect?: ReconnectOptions;
218
- url: string;
219
- WebSocket?: typeof WebSocket;
220
- /**
221
- * Token appended to the WebSocket URL as `?token=…`. The server matches it
222
- * against `LUNORA_WS_BEARER` (to clear the upgrade gate) and/or
223
- * `LUNORA_ADMIN_TOKEN` (to authorize `__lunora_admin__:*` subscriptions —
224
- * what the studio sets it to). Browsers can't set headers on the
225
- * `WebSocket` constructor, so the query parameter is the only channel; it
226
- * ends up in server logs and history, so prefer a short-lived rotating
227
- * token in production.
228
- */
229
- wsToken?: string;
230
- wsUrl?: string;
231
- }
232
- /** Wire envelope sent on `POST /_lunora/rpc`. */
233
- interface RpcEnvelope {
234
- args?: Record<string, unknown>;
235
- functionPath: string;
236
- shardKey?: string;
237
- }
238
- /** Wire response from the shard's `/rpc` endpoint (forwarded by the runtime). */
239
- type RpcResponseBody = {
240
- result: unknown;
241
- } | {
242
- error: {
243
- code: string;
244
- message: string;
245
- };
246
- };
247
- /** Subscription protocol — client → server. */
248
- interface ClientSubscribeMessage {
249
- id: string;
250
- /**
251
- * `sinceSeq` is the persisted `cursor` high-watermark the client last saw
252
- * for this shard (Pillar 1b resume). Present only when a durable
253
- * {@link QueryCacheAdapter} restored a cached value with a cursor; the
254
- * server replies with a lightweight `resume` frame instead of a full
255
- * snapshot when nothing the query reads changed since it. Absent on a
256
- * first-time subscribe.
257
- */
258
- query: {
259
- args?: Record<string, unknown>;
260
- functionPath?: string;
261
- sinceEpoch?: string;
262
- sinceSeq?: number;
263
- table?: string;
264
- };
265
- type: "subscribe";
266
- }
267
- interface ClientUnsubscribeMessage {
268
- id: string;
269
- type: "unsubscribe";
270
- }
271
- /**
272
- * One-shot control frame sent right after the socket opens. Registers the
273
- * connection's app `context` (e.g. `{ roomId, sessionId }`) with the server and
274
- * fires the `onConnect` lifecycle hooks; the same context is replayed to
275
- * `onDisconnect` when the socket drops.
276
- */
277
- interface ClientConnectMessage {
278
- context?: Record<string, unknown>;
279
- id: string;
280
- type: "connect";
281
- }
282
- interface ClientAckMessage {
283
- id: string;
284
- type: "ack";
285
- }
286
- /**
287
- * Start a streaming query. The id namespaces a fresh stream and is echoed on
288
- * every {@link ServerChunkMessage} the server pushes back. Cancel a running
289
- * stream by sending a {@link ClientUnsubscribeMessage} with the same id —
290
- * subscription and stream id-spaces share the cancel channel; the prefix
291
- * (`sub_*` vs `stream_*`) keeps the local registries searchable.
292
- */
293
- interface ClientStreamMessage {
294
- id: string;
295
- query: {
296
- args?: Record<string, unknown>;
297
- functionPath: string;
298
- shardKey?: string;
299
- };
300
- type: "stream";
301
- }
302
- /**
303
- * Join or leave a whisper `topic` — an app-chosen ephemeral channel scoped to a
304
- * shard. While joined, the client receives every {@link ServerWhisperMessage}
305
- * other members broadcast to the topic.
306
- */
307
- interface ClientWhisperSubscribeMessage {
308
- topic: string;
309
- type: "whisper_subscribe" | "whisper_unsubscribe";
310
- }
311
- /**
312
- * Broadcast ephemeral `data` to the topic's other members on the shard. The
313
- * payload is relayed verbatim with no server-side persistence (no SQLite/CDC
314
- * write) — for typing indicators, live cursors, presence pings. The sender does
315
- * not receive its own whisper.
316
- */
317
- interface ClientWhisperMessage {
318
- data?: unknown;
319
- topic: string;
320
- type: "whisper";
321
- }
322
- type ClientMessage = ClientAckMessage | ClientConnectMessage | ClientStreamMessage | ClientSubscribeMessage | ClientUnsubscribeMessage | ClientWhisperMessage | ClientWhisperSubscribeMessage;
323
- /** Subscription protocol — server → client. */
324
- interface ServerDataMessage {
325
- /**
326
- * The `__cdc_log` high-watermark covered by this frame (Pillar 1b). The
327
- * client persists it as the query's `serverCursor` and replays it as
328
- * `sinceSeq` on the next reconnect. Absent on shards that never enabled CDC.
329
- */
330
- cursor?: number;
331
- data?: unknown;
332
- delta?: unknown;
333
- /** The CDC epoch this frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
334
- epoch?: string;
335
- id: string;
336
- type: "data" | "delta";
337
- }
338
- /**
339
- * Lightweight resume acknowledgement (Pillar 1b): the server determined that
340
- * nothing the subscription reads changed since the client's `sinceSeq`, so it
341
- * skips re-sending the snapshot. The client keeps its cached value and only
342
- * advances `serverCursor` to `cursor`.
343
- */
344
- interface ServerResumeMessage {
345
- cursor?: number;
346
- /** The CDC epoch this resume's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
347
- epoch?: string;
348
- id: string;
349
- type: "resume";
350
- }
351
- interface ServerErrorMessage {
352
- error?: unknown;
353
- id?: string;
354
- message?: string;
355
- type: "error";
356
- }
357
- interface ServerAckMessage {
358
- id: string;
359
- type: "ack";
360
- }
361
- interface ServerCompleteMessage {
362
- id: string;
363
- type: "complete";
364
- }
365
- /** One frame of a streaming query — `data` carries the user-yielded chunk. */
366
- interface ServerChunkMessage {
367
- data: unknown;
368
- id: string;
369
- type: "chunk";
370
- }
371
- /**
372
- * An ephemeral whisper relayed from another member of `topic` on the same shard
373
- * (AnyCable-style whispering). `data` is the sender's payload verbatim; `from`
374
- * is the sender's verified user id when known (absent for an anonymous sender).
375
- * Never persisted server-side.
376
- */
377
- interface ServerWhisperMessage {
378
- data: unknown;
379
- from?: string;
380
- topic: string;
381
- type: "whisper";
382
- }
383
- type ServerMessage = ServerAckMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerResumeMessage | ServerWhisperMessage;
384
- /**
385
- * The authenticated user as exposed client-side, mirroring better-auth's
386
- * `user` row (the `user` field of the `get-session` response). Kept minimal
387
- * and structural — only `id` is guaranteed; the rest are the common better-auth
388
- * fields, and the index signature carries any plugin-contributed extras.
389
- */
390
- interface User {
391
- readonly createdAt?: NullableTimestamp;
392
- readonly email?: null | string;
393
- readonly emailVerified?: boolean | null;
394
- readonly id: string;
395
- readonly image?: null | string;
396
- readonly name?: null | string;
397
- readonly [key: string]: unknown;
398
- readonly updatedAt?: NullableTimestamp;
399
- }
400
- /**
401
- * One pending scheduled function, as returned by the worker's
402
- * `GET /_lunora/admin/scheduled` endpoint. Mirrors `@lunora/scheduler`'s
403
- * `ScheduleRecord` structurally so the client carries no dependency on it.
404
- */
405
- interface ScheduleRecord {
406
- args: Record<string, unknown>;
407
- /**
408
- * Dispatch attempts already made. Absent (treated as 0) until the first
409
- * failure; on a dead-letter record it is the exhausted count (> the retry
410
- * budget). Surfaced so the studio can show how hard a job tried before it
411
- * was parked.
412
- */
413
- attempts?: number;
414
- enqueuedAt: number;
415
- functionPath: string;
416
- id: string;
417
- /** Logical workpool the job is routed to (concurrency-gated), when any. */
418
- pool?: string;
419
- scheduledFor: number;
420
- shardKey?: string;
421
- }
422
- /**
423
- * One workpool's live backlog, as returned by the worker's
424
- * `GET /_lunora/admin/scheduled/status` endpoint. Mirrors `@lunora/scheduler`'s
425
- * `SchedulerPoolStatus` structurally so the client carries no dependency on it.
426
- */
427
- interface SchedulerPoolStatus {
428
- /** Jobs currently dispatched-but-not-yet-completed (the held concurrency slots). */
429
- inFlight: number;
430
- /** The pool's concurrency cap. */
431
- maxConcurrency: number;
432
- /** The logical workpool name. */
433
- name: string;
434
- /** Pending jobs routed to this pool but not yet dispatched. */
435
- queued: number;
436
- }
437
- /**
438
- * The app-level scheduler backlog, as returned by the worker's
439
- * `GET /_lunora/admin/scheduled/status` endpoint. `pools` is the per-pool
440
- * breakdown; `backlog` and `inFlight` are the app-wide sums of `queued` and
441
- * `inFlight` across every pool — the headline numbers for the studio SLO
442
- * view. Mirrors `@lunora/scheduler`'s `SchedulerStatus` structurally.
443
- */
444
- interface SchedulerStatus {
445
- /** Sum of every pool's `queued` count — the total pending backlog. */
446
- backlog: number;
447
- /** Sum of every pool's `inFlight` count — the total held concurrency slots. */
448
- inFlight: number;
449
- /** Per-pool backlog breakdown. */
450
- pools: SchedulerPoolStatus[];
451
- }
452
- /**
453
- * One shard's request volume, as returned by the worker's
454
- * `POST /_lunora/admin/shard-traffic` endpoint. The cross-shard traffic feed
455
- * the studio's `hot_shard` advisor lint consumes: `requests` is the shard's
456
- * lifetime dispatch total, `shardKey` the DO id name (`""` for the root shard).
457
- */
458
- interface ShardTrafficEntry {
459
- requests: number;
460
- shardKey: string;
461
- }
462
- /**
463
- * The whole-shard-set traffic distribution returned by the worker's
464
- * `POST /_lunora/admin/shard-traffic` endpoint. `shards` is one entry per live
465
- * shard (a failed shard surfaces with `requests: 0`); `ok`/`failed` count the
466
- * shards that returned vs. errored. Shaped to feed the advisor's `hot_shard`
467
- * lint after the studio tags each entry with its sharded function `group`.
468
- */
469
- interface ShardTrafficResult {
470
- failed: number;
471
- ok: number;
472
- shards: ShardTrafficEntry[];
473
- }
474
- /**
475
- * One object in the storage bucket, as returned by the worker's
476
- * `GET /_lunora/admin/storage` endpoint. Mirrors `@lunora/storage`'s
477
- * `R2ObjectLike` structurally.
478
- */
479
- interface StorageObject {
480
- customMetadata?: Record<string, string>;
481
- etag: string;
482
- httpMetadata?: {
483
- contentType?: string;
484
- };
485
- key: string;
486
- size: number;
487
- /**
488
- * When the object was stored. R2 emits a `Date`, which JSON-serializes to an
489
- * ISO string over the wire; a mock may supply epoch ms — so consumers should
490
- * normalise via `new Date(uploaded)`. Absent if the backend didn't report it.
491
- */
492
- uploaded?: number | string;
493
- }
494
- /** One page of {@link StorageObject}s plus the cursor to fetch the next, if any. */
495
- interface StorageListPage {
496
- cursor?: string;
497
- objects: StorageObject[];
498
- }
499
- /**
500
- * One argument of a registered function, derived from its `v.*` validator by the
501
- * worker. A compact signature shape — enough to render a function's API without
502
- * the build-time codegen types.
503
- */
504
- interface FunctionArgumentDescriptor {
505
- /** Element validator kind for an `array` arg (one level), e.g. `string`. */
506
- element?: string;
507
- /** The (optional-unwrapped) validator kind, e.g. `string`, `id`, `object`. */
508
- kind: string;
509
- /** The argument name. */
510
- name: string;
511
- /** True when the arg is wrapped in `v.optional(...)`. */
512
- optional: boolean;
513
- /** Target table for an `id` arg (`v.id("table")`). */
514
- table?: string;
515
- }
516
- /**
517
- * One registered function, as returned by the worker's
518
- * `GET /_lunora/admin/functions` endpoint: its `&lt;file>:&lt;function>` path, which
519
- * client method (`query` / `mutation` / `action`) invokes it, and its argument
520
- * signature. `args` is absent on responses from an older worker.
521
- */
522
- interface FunctionDescriptor {
523
- args?: FunctionArgumentDescriptor[];
524
- kind: "action" | "mutation" | "query";
525
- path: string;
526
- }
527
- /** A `.global()` (D1-backed) table plus its row count, from `/_lunora/admin/global/tables`. */
528
- interface GlobalTableInfo {
529
- name: string;
530
- rowCount: number;
531
- }
532
- /** A window of rows from one global table, from `/_lunora/admin/global/table`. */
533
- interface GlobalTablePage {
534
- columns: string[];
535
- /** FK columns (local column → referenced table) for external tables with real `REFERENCES` constraints, from `PRAGMA foreign_key_list`. */
536
- refs?: Record<string, string>;
537
- rows: Record<string, unknown>[];
538
- total: number;
539
- }
540
- /**
541
- * One equality constraint a facet-value click adds to the global browser's view
542
- * (`column = value`). `value` is the raw stored scalar the facet returned, sent
543
- * as-is and bound server-side, so it never injects SQL.
544
- */
545
- interface GlobalFilterClause {
546
- column: string;
547
- value: unknown;
548
- }
549
- /** One distinct value of a faceted global column with its row count, from `/_lunora/admin/global/facet`. */
550
- interface GlobalFacetValue {
551
- count: number;
552
- value: unknown;
553
- }
554
- /** Per-column distinct-value summary for the global browser, from `/_lunora/admin/global/facet`. */
555
- interface GlobalFacetResult {
556
- truncated: boolean;
557
- values: GlobalFacetValue[];
558
- }
559
- /** A nullable timestamp field as better-auth serializes it: epoch-ms, ISO string, or null. */
560
- type NullableTimestamp = null | number | string;
561
- /** A workflow instance's lifecycle status. Mirrors Cloudflare's `InstanceStatus`. */
562
- type WorkflowInstanceStatus = "complete" | "errored" | "paused" | "queued" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
563
- /** The lifecycle mutations the status endpoint accepts. */
564
- type WorkflowInstanceAction = "pause" | "resume" | "terminate";
565
- /** One row of the workflow-instances list. */
566
- interface WorkflowInstanceSummary {
567
- createdOn?: string;
568
- endedOn?: string;
569
- id: string;
570
- startedOn?: string;
571
- status: WorkflowInstanceStatus;
572
- }
573
- /** One durable step of an instance's execution timeline. */
574
- interface WorkflowStepDetail {
575
- /** 1-based attempt count (`> 1` means the step retried). */
576
- attempts?: number;
577
- end?: string;
578
- error?: unknown;
579
- name: string;
580
- output?: unknown;
581
- start?: string;
582
- success?: boolean;
583
- /** `step` / `sleep` / `waitForEvent` / … (Cloudflare's step `type`). */
584
- type?: string;
585
- }
586
- /** A workflow instance's full detail: summary plus params/output/error and the step timeline. */
587
- interface WorkflowInstanceDetail extends WorkflowInstanceSummary {
588
- error?: unknown;
589
- output?: unknown;
590
- params?: unknown;
591
- steps: WorkflowStepDetail[];
592
- }
593
- /** A page of workflow instances. */
594
- interface WorkflowInstancePage {
595
- /**
596
- * Whether workflow inspection is configured on the worker (a Cloudflare
597
- * account id + API token). `false` when the admin proxy reports it can't
598
- * inspect instances; omitted (treated as configured) otherwise. Lets a
599
- * caller render a "set credentials" state without a failed request.
600
- */
601
- configured?: boolean;
602
- instances: WorkflowInstanceSummary[];
603
- page: number;
604
- perPage: number;
605
- totalCount?: number;
606
- }
607
- type SubscriptionCallback = (data: unknown) => void;
608
- /** A subscription-scoped error the server pushed for this subscription id. */
609
- interface SubscriptionError {
610
- code?: string;
611
- message: string;
612
- }
613
- type SubscriptionErrorCallback = (error: SubscriptionError) => void;
614
- interface SubscriptionState {
615
- /** True once the server has acked the subscription on the current socket. */
616
- acked: boolean;
617
- readonly args: Record<string, unknown>;
618
- /**
619
- * Stable-stringified `args`, computed once at subscribe time. Cached so the
620
- * optimistic-update fan-out can compare against a mutation's args key without
621
- * re-serializing every subscription's args on every mutation.
622
- */
623
- readonly argsKey: string;
624
- readonly callbacks: Set<SubscriptionCallback>;
625
- /** Notified when the server rejects this subscription (e.g. admin auth). */
626
- readonly errorCallbacks: Set<SubscriptionErrorCallback>;
627
- readonly fn: FunctionReference;
628
- readonly id: string;
629
- /** Last known value, used to short-circuit `useQuery`-style consumers. */
630
- lastValue: unknown;
631
- /**
632
- * The `__cdc_log` high-watermark (`cursor`) the `lastValue` reflects,
633
- * captured from the last `data`/`delta`/`resume` frame. Persisted to the
634
- * durable read cache and replayed as `sinceSeq` on reconnect so the server
635
- * can resume instead of re-snapshotting (Pillar 1b/2). Absent until the
636
- * first cursor-stamped frame arrives.
637
- */
638
- serverCursor?: number;
639
- /**
640
- * The CDC `epoch` token the `serverCursor` belongs to, captured from the
641
- * same frame. Replayed as `sinceEpoch` on reconnect so the server resumes
642
- * only when the client is still on the same changelog timeline — a reset or
643
- * recycled shard advertises a new epoch, forcing a fresh snapshot. Absent
644
- * until the first epoch-stamped frame arrives.
645
- */
646
- serverEpoch?: string;
647
- /**
648
- * Monotonic counter incremented on every server-pushed delta or data.
649
- * Used by optimistic-update rollback to detect whether the server has
650
- * already moved past the value we'd otherwise restore.
651
- */
652
- serverVersion: number;
653
- readonly shardKey?: string;
654
- }
655
- /**
656
- * Active subscription registry. The client keys subscriptions by
657
- * `(functionPath, stableStringify(args), shardKey)` so duplicate calls share a
658
- * single server-side registration. Args are stably encoded (keys sorted at every
659
- * depth) so two structurally-equal arg records constructed with a different key
660
- * order (`{ a, b }` vs `{ b, a }`) collapse to the same key instead of leaking a
661
- * duplicate subscription.
662
- */
663
- declare class SubscriptionRegistry {
664
- static key(functionPath: string, args: Record<string, unknown>, shardKey?: string): string;
665
- private readonly byKey;
666
- private readonly byId;
667
- get(key: string): SubscriptionState | undefined;
668
- getById(id: string): SubscriptionState | undefined;
669
- add(state: SubscriptionState): void;
670
- remove(state: SubscriptionState): void;
671
- all(): SubscriptionState[];
672
- }
673
- /**
674
- * Read/write handle over the client's live query cache, handed to a mutation's
675
- * `withOptimisticUpdate` callback so a single mutation can optimistically patch
676
- * many subscribed queries at once (Convex's `OptimisticLocalStore` model).
677
- *
678
- * `getQuery` reads the current value (server value or any still-pending
679
- * optimistic override) of a subscribed query; `setQuery` writes an optimistic
680
- * override on top. Every write is collected as a rollback closure so the whole
681
- * batch unwinds atomically when the mutation settles or the server advances
682
- * past it — the same per-subscription rollback machinery the legacy
683
- * per-call `optimistic` transform uses, generalized to N queries.
684
- */
685
- interface OptimisticLocalStore {
686
- /**
687
- * Every loaded subscription on `function_`, regardless of args, paired with
688
- * the args it was subscribed under. Mirrors Convex's `getAllQueries` — handy
689
- * when a write must patch every variant of a list query (all channels,
690
- * all filters) without enumerating their args up front.
691
- */
692
- getAllQueries: <F extends FunctionReference>(function_: F) => {
693
- args: ArgsOf<F>;
694
- value: ReturnOf<F> | undefined;
695
- }[];
696
- /**
697
- * Current cached value for the subscribed `(function_, args)` query, or
698
- * `undefined` when nothing is subscribed/loaded for it. Reflects any
699
- * optimistic override already written in this batch.
700
- */
701
- getQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>) => ReturnOf<F> | undefined;
702
- /**
703
- * Write an optimistic override for the subscribed `(function_, args)`
704
- * query. A no-op (returns without effect) when no subscription matches —
705
- * mirroring Convex, where you only patch queries the page is watching.
706
- */
707
- setQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>, value: ReturnOf<F> | undefined) => void;
708
- }
709
- /** A mutation's multi-query optimistic update: read/write the cache via `localStore`. */
710
- type OptimisticUpdate<Args> = (localStore: OptimisticLocalStore, args: Args) => void;
711
- /**
712
- * Build an {@link OptimisticLocalStore} bound to a subscription registry, the
713
- * mutation's shard key, and the `writeOptimisticToState` primitive. Returns the
714
- * store plus the ordered rollback closures every `setQuery` produced, so the
715
- * caller can unwind the whole batch (LIFO) if the mutation later fails — and
716
- * leave them in place to be GC'd alongside the subscription on success.
717
- */
718
- declare const createLocalStore: (subscriptions: SubscriptionRegistry, shardKey: string | undefined, write: (state: SubscriptionState, next: unknown) => () => void, stableStringify: (value: unknown) => string) => {
719
- rollbacks: (() => void)[];
720
- store: OptimisticLocalStore;
721
- };
722
- /**
723
- * Bounded async-iterator queue backing `LunoraClient.stream`.
724
- *
725
- * The server pushes one server `chunk` message per yielded value while the
726
- * client iterates with `for await (const chunk of stream)`. A producer that
727
- * outruns its consumer would otherwise OOM the page, so the buffer is bounded
728
- * — exceeding {@link DEFAULT_MAX_BUFFER} surfaces a `STREAM_BACKPRESSURE`
729
- * error to the iterator (and to the server-side cancel path).
730
- *
731
- * The queue is closed exactly once via {@link StreamHandle.complete} (success)
732
- * or {@link StreamHandle.fail} (transport / server error). Subsequent calls
733
- * are silent no-ops so a duplicate `complete` frame after a cancel doesn't
734
- * crash the page.
735
- */
736
- declare const DEFAULT_MAX_BUFFER = 1024;
737
- interface StreamHandle<T = unknown> {
738
- /** Mark the stream complete (no more chunks); resolves any pending consumer to `done:true`. */
739
- readonly complete: () => void;
740
- /** Surface an error to any pending consumer; subsequent pushes are dropped. */
741
- readonly fail: (error: Error) => void;
742
- /**
743
- * Push one chunk. Silent no-op once the stream is `complete`, `fail`-ed,
744
- * or `cancel`-ed. When the buffer is already at `maxBuffer`, the stream
745
- * is failed with a `STREAM_BACKPRESSURE` error and the push is dropped —
746
- * the producer never sees a thrown exception.
747
- */
748
- readonly push: (value: T) => void;
749
- }
750
- interface StreamIterable<T> extends AsyncIterable<T> {
751
- /** Cancel the stream from the consumer side: closes the iterator and notifies the registered canceller. */
752
- cancel: () => void;
753
- }
754
- /**
755
- * Build a stream handle paired with an async-iterable. The handle is the
756
- * server-driven side (the WS dispatcher pushes chunks / completes / errors);
757
- * the iterable is what the user awaits. `onCancel` is invoked exactly once
758
- * when the consumer calls `.cancel()` (or `.return()`) so the client can
759
- * send a `{type:"unsubscribe"}` frame to the server.
760
- */
761
- declare const createStream: <T>(options: {
762
- maxBuffer?: number;
763
- onCancel: () => void;
764
- }) => {
765
- handle: StreamHandle<T>;
766
- iterable: StreamIterable<T>;
767
- };
768
- /**
769
- * Aggregate live-socket health across every shard connection, for a UI status
770
- * indicator. `idle` = no socket opened yet; `connecting` = at least one socket
771
- * is (re)connecting and none is open; `connected` = at least one socket is open;
772
- * `offline` = sockets exist but all are down (between reconnect attempts).
773
- */
774
- type ConnectionStatus = "connected" | "connecting" | "idle" | "offline";
775
- /**
776
- * Per-call options for {@link LunoraClient.mutation} — the optimistic-update
777
- * machinery plus `shardKey`. Exported (at the end of this file) so the framework
778
- * adapters (`@lunora/react`, `/solid`, `/svelte`, `/vue`) can type their
779
- * `mutate(args, options?)` against one canonical definition instead of
780
- * re-declaring it.
781
- */
782
- interface MutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unknown> {
783
- optimistic?: (current: TCurrent | undefined) => TValue;
784
- /**
785
- * Convex-parity multi-query optimistic update. Receives an
786
- * `OptimisticLocalStore` over the live subscription cache plus the
787
- * mutation's args, so one mutation can patch many subscribed queries at
788
- * once; every write is rolled back atomically if the mutation fails.
789
- */
790
- optimisticUpdate?: OptimisticUpdate<TArgs>;
791
- shardKey?: string;
792
- }
793
- /**
794
- * Lunora browser/edge client. Talks RPC over HTTP and real-time deltas over
795
- * a single multiplexed WebSocket.
796
- *
797
- * Reconnect, offline queueing, and optimistic updates are all handled here;
798
- * see the package README for the wire protocol.
799
- */
800
- declare class LunoraClient {
801
- readonly url: string;
802
- readonly wsUrl: string;
803
- private wsToken;
804
- /** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
805
- private readonly authBasePath;
806
- private readonly fetchImpl;
807
- private readonly WebSocketImpl;
808
- private readonly bookmark;
809
- private readonly reconnectOptions;
810
- /** WS connect timeout (ms); `0` disables it. See {@link LunoraClientOptions.connectTimeoutMs}. */
811
- private readonly connectTimeoutMs;
812
- /** Keepalive cadence (ms); `0` disables the heartbeat. See {@link LunoraClientOptions.heartbeatIntervalMs}. */
813
- private readonly heartbeatIntervalMs;
814
- private readonly offlineQueue;
815
- private readonly onPersistenceError;
816
- private readonly persistence;
817
- /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
818
- private readonly queryCache;
819
- /**
820
- * Values restored from the `queryCache` at construction, keyed by the
821
- * read-cache key, awaiting the `subscribe()` that will consume them. A
822
- * key is consumed (deleted) the first time its subscription is created, so
823
- * the cache only ever seeds the initial value — live frames take over after.
824
- */
825
- private readonly hydratedQueryCache;
826
- /**
827
- * Coalesced read-cache writes: the latest value per key, flushed to
828
- * the `queryCache` on a short debounce so a burst of deltas persists once.
829
- */
830
- private readonly pendingCacheWrites;
831
- private cacheFlushTimer;
832
- private readonly subscriptions;
833
- /** One {@link ShardConnection} per shard key (keyed by `shardKey ?? ""`). */
834
- private readonly connections;
835
- /** Default `connect`-envelope context applied to a shard with no explicit override. */
836
- private readonly defaultConnectionContext;
837
- /**
838
- * Per-shard `connect`-envelope context registered via `setConnectionContext`
839
- * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
840
- * on every socket open so it replays across reconnects, and forwarded to the
841
- * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
842
- * imperative (last-writer-wins) override; refcounted holders registered via
843
- * `acquireConnectionContext` live in `connectionContextHolders` and take
844
- * precedence — see `effectiveConnectionContext`.
845
- */
846
- private readonly connectionContexts;
847
- /**
848
- * Per-shard stack of refcounted connection-context holders (keyed by
849
- * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
850
- * is an opaque token carrying its `context`; the most-recently acquired
851
- * holder wins (last-writer-wins among live holders), and the context is only
852
- * cleared for a shard once its last holder releases — so two concurrently
853
- * mounted presence hooks on the same shard can't stomp each other's context
854
- * on cleanup. A holder is identified by reference identity so a release
855
- * removes exactly the right one regardless of stack position.
856
- */
857
- private readonly connectionContextHolders;
858
- private authToken;
859
- /**
860
- * Identity stamp recorded against each queued offline mutation, keyed by
861
- * the queue-assigned mutation id. Captured at enqueue from the auth token
862
- * in effect at the time, and re-checked at flush so a queued write can
863
- * never replay under a different identity than the one that issued it.
864
- * See `identityFingerprint` for the fingerprint shape.
865
- */
866
- private readonly queuedIdentities;
867
- private closed;
868
- /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
869
- private readonly authTokenListeners;
870
- /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
871
- private readonly statusListeners;
872
- /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
873
- private readonly tokenExpiredListeners;
874
- /**
875
- * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
876
- * of callbacks. Membership doubles as the resubscribe set replayed on every
877
- * (re)connect so a topic survives a socket bounce.
878
- */
879
- private readonly whisperHandlers;
880
- /** Last status broadcast, so we only notify listeners on an actual change. */
881
- private lastStatus;
882
- private nextSubId;
883
- private nextStreamId;
884
- /**
885
- * In-flight client-side stream readers, keyed by the stream id sent on the
886
- * wire. The handle drives the underlying iterator queue and `shardKey`
887
- * tells us which socket to push the cancel frame onto when the consumer
888
- * calls `.cancel()` or the iterator is garbage-collected.
889
- */
890
- private readonly streams;
891
- constructor(options: LunoraClientOptions);
892
- /**
893
- * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
894
- * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
895
- * sync across all mounted instances.
896
- *
897
- * Does NOT update the WebSocket auth — the WS token is fixed at upgrade
898
- * time and lives in the URL. To refresh live WS auth, call
899
- * {@link setWsToken} explicitly, which closes existing shard sockets to
900
- * force a reconnect with the new credential.
901
- */
902
- setAuthToken(token: string | null): void;
903
- getAuthToken(): string | null;
904
- /**
905
- * Subscribe to auth-token changes. Returns an unsubscribe function. The
906
- * listener is NOT invoked on registration — use {@link getAuthToken} for
907
- * the current value.
908
- */
909
- onAuthTokenChange(listener: (token: string | null) => void): Unsubscribe;
910
- /**
911
- * Fetch the currently authenticated user from better-auth's `get-session`
912
- * endpoint, returning the `user` record or `null` when signed out. Sends
913
- * the stored bearer token (if any) and `credentials: "include"` so a
914
- * cookie-session is also honoured. A network/parse failure or a non-OK
915
- * response resolves to `null` rather than throwing — callers treat "couldn't
916
- * resolve identity" as "signed out".
917
- *
918
- * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
919
- * the token changes (that's what `@lunora/react`'s `useAuth` does).
920
- */
921
- getCurrentUser(): Promise<User | null>;
922
- /**
923
- * Replace the token appended to WS upgrade URLs as `?token=…` and close
924
- * every open shard socket so the reconnect picks up the new value. Call
925
- * this whenever the user's WS credential changes (rotating the admin token
926
- * in the studio, switching workspaces, etc.). Bearer tokens for HTTP
927
- * RPC are independent — see {@link setAuthToken}.
928
- */
929
- setWsToken(token: string | undefined): void;
930
- /**
931
- * Register (or clear, with `undefined`) the app context sent in the `connect`
932
- * envelope for a shard's socket, overriding the client-wide
933
- * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
934
- * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
935
- * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
936
- * presence row is removed the instant the socket drops, with no TTL lag.
937
- *
938
- * Stored per shard and replayed on every (re)connect. When a socket for the
939
- * shard is already open, a fresh `connect` envelope is sent immediately so the
940
- * server sees the new context without waiting for a reconnect.
941
- */
942
- setConnectionContext(context: Record<string, unknown> | undefined, options?: {
943
- shardKey?: string;
944
- }): void;
945
- /**
946
- * Refcounted variant of {@link setConnectionContext}: register a connection
947
- * `context` for a shard and get back a release function. Unlike the imperative
948
- * setter, the context is only cleared once the *last* acquired holder releases
949
- * it — so two components (e.g. two mounted `usePresence` hooks) on the same
950
- * shard no longer clobber each other's context when one of them unmounts. The
951
- * most-recently acquired live holder wins (last-writer-wins), and releasing
952
- * the top holder falls back to the previous one rather than clearing.
953
- *
954
- * With a single holder the behaviour is identical to a
955
- * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
956
- * Releasing more than once is a no-op (the holder is matched by reference, so
957
- * a double release can't drop a different holder).
958
- */
959
- acquireConnectionContext(context: Record<string, unknown>, options?: {
960
- shardKey?: string;
961
- }): Unsubscribe;
962
- /**
963
- * Join a whisper `topic` and receive every ephemeral message other members
964
- * broadcast to it on the same shard (typing indicators, live cursors,
965
- * presence pings). Whispers never touch the server's durable state — there's
966
- * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
967
- * is left on the server once its last local handler unsubscribes.
968
- *
969
- * `handler` receives the raw `data` and the sender's verified `from` user id
970
- * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
971
- * (the default shard when omitted) — use the same shard you target with the
972
- * matching queries/mutations so members land on the same Durable Object.
973
- *
974
- * Security: whisper topics are NOT access-controlled beyond the shard
975
- * boundary — any client that can open a socket to the shard can join, read,
976
- * and inject on any topic name. `from` is server-stamped and unforgeable, but
977
- * do not put data on a whisper topic that some shard members shouldn't see,
978
- * and don't trust a whisper's `data` as authorization. Use a query/mutation
979
- * (with RLS) for anything privileged; whispers are for transient awareness.
980
- */
981
- whisperSubscribe(topic: string, handler: (data: unknown, from?: string) => void, options?: {
982
- shardKey?: string;
983
- }): Unsubscribe;
984
- /**
985
- * Broadcast an ephemeral `data` payload to the other members of a whisper
986
- * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
987
- * dropped when the shard socket isn't open (whispers are transient, never
988
- * queued), and the server silently drops it if the sender exceeds its
989
- * whisper rate budget. The sender never receives its own whisper. Omitting
990
- * `data` delivers JSON `null` to receivers (not `undefined`).
991
- */
992
- whisper(topic: string, data?: unknown, options?: {
993
- shardKey?: string;
994
- }): void;
995
- /**
996
- * Subscribe to token-expiry events: invoked whenever the server drops a
997
- * shard socket because the connection's credential lapsed (close code
998
- * `4001`). The client already reconnects automatically (re-resolving
999
- * identity from the cookie/token in effect); use this to refresh a
1000
- * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
1001
- * with a freshly minted one. Returns an unsubscribe function.
1002
- */
1003
- onTokenExpired(listener: () => void): Unsubscribe;
1004
- /**
1005
- * Current aggregate live-socket status across all shard connections. See
1006
- * {@link ConnectionStatus}.
1007
- */
1008
- connectionStatus(): ConnectionStatus;
1009
- /**
1010
- * Subscribe to aggregate connection-status changes. Invokes `listener`
1011
- * immediately with the current status, then on every transition. Returns an
1012
- * unsubscribe function.
1013
- */
1014
- onConnectionStatus(listener: (status: ConnectionStatus) => void): Unsubscribe;
1015
- query<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
1016
- shardKey?: string;
1017
- }): Promise<ReturnOf<F>>;
1018
- /**
1019
- * Invoke a mutation. Errors propagate as rejections.
1020
- *
1021
- * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
1022
- * only when the targeted shard's socket was open at least once already
1023
- * (`wasEverConnected`), so the registry / resubscribe handshake has run.
1024
- * Mutations issued before the very first WS connect to a shard fail fast.
1025
- * Opt into queueing-before-first-connect via
1026
- * `OfflineQueueOptions.queueBeforeFirstConnect`.
1027
- */
1028
- mutation<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>): Promise<ReturnOf<F>>;
1029
- action<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
1030
- shardKey?: string;
1031
- }): Promise<ReturnOf<F>>;
1032
- /**
1033
- * Read the cross-shard request distribution for a `.shardBy(...)` table —
1034
- * the feed the studio's `hot_shard` advisor lint consumes. Hits the
1035
- * admin-gated `POST /_lunora/admin/shard-traffic` endpoint, which fans the
1036
- * cheap per-shard `getMetrics` read out across every live shard and returns
1037
- * each shard's `{ shardKey, requests }` total (a failed shard surfaces with
1038
- * `requests: 0`). Requires the worker to be built with a `queryCoordinator`
1039
- * and `adminToken`, and this client's auth token to match; defaults any
1040
- * absent field so an older worker yields an empty-but-valid shape.
1041
- */
1042
- shardTraffic(table: string): Promise<ShardTrafficResult>;
1043
- /**
1044
- * List the functions queued via `runAfter` / `runAt`, soonest-due last
1045
- * (the worker returns them in storage order). Hits the admin-gated
1046
- * `/_lunora/admin/scheduled` endpoint, so the worker must be built with a
1047
- * `schedulerDO` namespace and `adminToken`, and this client's auth token
1048
- * must match. Powers `@lunora/studio`'s scheduled-jobs panel.
1049
- */
1050
- listScheduledJobs(): Promise<ScheduleRecord[]>;
1051
- /**
1052
- * Read the app-level workpool backlog that powers `@lunora/studio`'s SLO
1053
- * view: per-pool `{ name, queued, inFlight, maxConcurrency }` plus the
1054
- * app-wide `backlog` (total queued) and `inFlight` (total held slots) sums.
1055
- * Hits the admin-gated `GET /_lunora/admin/scheduled/status` endpoint, so the
1056
- * same preconditions as {@link listScheduledJobs} apply (a `schedulerDO`
1057
- * namespace + `adminToken` on the worker and a matching auth token here).
1058
- * Defaults any absent field so an older worker still yields a valid shape.
1059
- */
1060
- schedulerStatus(): Promise<SchedulerStatus>;
1061
- /** Cancel a pending scheduled job by id. Returns whether a job was removed. */
1062
- cancelScheduledJob(id: string): Promise<{
1063
- cancelled: boolean;
1064
- }>;
1065
- /**
1066
- * List the dead-letter jobs: schedules that exhausted their retry budget
1067
- * and were parked instead of dropped. These never appear in
1068
- * {@link listScheduledJobs} (their live header is gone), so this is the only
1069
- * way the studio surfaces a permanently-failed job. Hits the admin-gated
1070
- * `GET /_lunora/admin/scheduled/dead`; same preconditions as
1071
- * {@link listScheduledJobs}. Powers `@lunora/studio`'s dead-letter panel.
1072
- */
1073
- listDeadJobs(): Promise<ScheduleRecord[]>;
1074
- /**
1075
- * Resurrect a dead-letter job by id: it re-enters the schedule with a fresh
1076
- * retry budget and fires on the next drain. Returns whether a parked record
1077
- * matched. Hits the admin-gated `POST /_lunora/admin/scheduled/dead/retry`.
1078
- */
1079
- retryDeadJob(id: string): Promise<{
1080
- retried: boolean;
1081
- }>;
1082
- /**
1083
- * Permanently drop a dead-letter job by id (the operator has decided not to
1084
- * recover it). Returns whether a parked record was removed. Hits the
1085
- * admin-gated `POST /_lunora/admin/scheduled/dead/cancel`.
1086
- */
1087
- removeDeadJob(id: string): Promise<{
1088
- removed: boolean;
1089
- }>;
1090
- /**
1091
- * List a workflow's instances via the admin Workflows proxy
1092
- * (`/_lunora/admin/workflows/instances`) — the Cloudflare control-plane data
1093
- * the `Workflow` binding can't expose. Requires the worker to be built with a
1094
- * `workflowsClient` (Cloudflare account id + API token). When one isn't
1095
- * configured this does NOT reject: the proxy returns a `200 { configured:
1096
- * false }` sentinel, so the result resolves with `configured === false` and an
1097
- * empty `instances` list — callers should branch on that flag rather than
1098
- * try/catch. (The instance-detail / status endpoints still reject with 501.)
1099
- * `name` is the deployed workflow name.
1100
- */
1101
- listWorkflowInstances(options: {
1102
- name: string;
1103
- page?: number;
1104
- perPage?: number;
1105
- status?: WorkflowInstanceStatus;
1106
- }): Promise<WorkflowInstancePage>;
1107
- /** Read one workflow instance with its step timeline (`/_lunora/admin/workflows/instance`). */
1108
- getWorkflowInstance(options: {
1109
- id: string;
1110
- name: string;
1111
- }): Promise<WorkflowInstanceDetail>;
1112
- /** Pause / resume / terminate a workflow instance (`/_lunora/admin/workflows/status`). Needs an Edit-scoped Cloudflare token. */
1113
- setWorkflowInstanceStatus(options: {
1114
- action: WorkflowInstanceAction;
1115
- id: string;
1116
- name: string;
1117
- }): Promise<{
1118
- status: WorkflowInstanceStatus;
1119
- }>;
1120
- /**
1121
- * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
1122
- * WebSocket. `onJobs` fires with the full list on connect and on every
1123
- * change (schedule / cancel / alarm-fire). Reconnects with the client's
1124
- * configured backoff. Requires `wsToken` to be set to the admin token (the
1125
- * browser can't send an `Authorization` header on a WS). Returns an
1126
- * unsubscribe function that closes the socket and stops reconnecting.
1127
- */
1128
- subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
1129
- /**
1130
- * List the registered public functions (queries / mutations / actions) with
1131
- * their kinds. Hits the admin-gated `GET /_lunora/admin/functions` endpoint —
1132
- * the worker must be built with a `functions` registry and `adminToken`, and
1133
- * this client's auth token must match. Powers `@lunora/studio`'s function
1134
- * runner auto-discovery.
1135
- */
1136
- listFunctions(): Promise<FunctionDescriptor[]>;
1137
- /**
1138
- * List the code-defined cron triggers (the `cronJobs()` map injected on the
1139
- * worker), each flattened to its firing `cron` expression. Hits the
1140
- * admin-gated `GET /_lunora/admin/cron-jobs` endpoint — the worker must be
1141
- * built with a `cronJobs` map and `adminToken`, and this client's auth token
1142
- * must match. These are static (Cloudflare exposes no runtime cron
1143
- * introspection), so the studio renders them read-only alongside the dynamic
1144
- * scheduler jobs.
1145
- */
1146
- getCronJobs(): Promise<CronJobInfo[]>;
1147
- /**
1148
- * Manually fire one code-defined cron job by name — the same dispatch the
1149
- * scheduled trigger runs (dispatch the function, or start the durable
1150
- * workflow), on demand. Hits the admin-gated `POST /_lunora/admin/cron-jobs/run`
1151
- * endpoint; the worker must be built with a `cronJobs` map and `adminToken`,
1152
- * and this client's auth token must match. Resolves when the job has run (a
1153
- * function job's shard response is 2xx, or the workflow instance was created)
1154
- * and rejects with the dispatch error otherwise.
1155
- */
1156
- runCronJob(name: string): Promise<{
1157
- name: string;
1158
- ran: boolean;
1159
- }>;
1160
- /**
1161
- * Fetch the generated OpenAPI 3.1 document. Hits the admin-gated
1162
- * `GET /_lunora/admin/openapi` endpoint — the worker must be built with an
1163
- * `openApiSpec` and `adminToken`, and this client's auth token must match.
1164
- * Powers `@lunora/studio`'s API-reference (Scalar) view. When the worker has
1165
- * no spec wired, the endpoint still resolves with an empty-but-valid OpenAPI
1166
- * document (no `paths`), so callers can render a "not configured" state.
1167
- */
1168
- fetchOpenApi(): Promise<Record<string, unknown>>;
1169
- /**
1170
- * Fetch the generated OpenRPC 1.x document. Hits the admin-gated
1171
- * `GET /_lunora/admin/openrpc` endpoint — the worker must be built with an
1172
- * `openRpcSpec` and `adminToken`, and this client's auth token must match.
1173
- * OpenRPC is the RPC-native spec (a `methods` array over the JSON-RPC-shaped
1174
- * `POST /_lunora/rpc` transport); it documents the RPC functions only.
1175
- * Powers `@lunora/studio`'s OpenRPC API-reference view. When the worker has
1176
- * no spec wired, the endpoint still resolves with an empty-but-valid OpenRPC
1177
- * document (no `methods`), so callers can render a "not configured" state.
1178
- */
1179
- fetchOpenRpc(): Promise<Record<string, unknown>>;
1180
- /**
1181
- * List objects in the storage bucket, optionally under a `prefix` and from a
1182
- * pagination `cursor`. Hits the admin-gated `GET /_lunora/admin/storage`
1183
- * endpoint — the worker must be built with a `storageList` function and
1184
- * `adminToken`, and this client's auth token must match. Powers
1185
- * `@lunora/studio`'s file browser.
1186
- */
1187
- listStorageObjects(options?: {
1188
- bucket?: string;
1189
- cursor?: string;
1190
- limit?: number;
1191
- prefix?: string;
1192
- }): Promise<StorageListPage>;
1193
- /**
1194
- * Delete one object from the storage bucket by key. Hits the admin-gated
1195
- * `DELETE /_lunora/admin/storage?key=…` endpoint — the worker must be built
1196
- * with a `storageDelete` function and `adminToken`. Powers the studio file
1197
- * browser's per-row delete; resolves `{ deleted, key }`.
1198
- */
1199
- deleteStorageObject(key: string, options?: {
1200
- bucket?: string;
1201
- }): Promise<{
1202
- deleted: boolean;
1203
- key: string;
1204
- }>;
1205
- /**
1206
- * List the storage bucket names the worker exposes, for the studio file
1207
- * browser's bucket picker. Hits the admin-gated
1208
- * `GET /_lunora/admin/storage/buckets` endpoint — always resolves (an empty
1209
- * array when the worker configures no `storageBuckets`, i.e. single-bucket).
1210
- */
1211
- listStorageBuckets(): Promise<string[]>;
1212
- /**
1213
- * Upload one object to the storage bucket. Hits the admin-gated
1214
- * `PUT /_lunora/admin/storage?key=…` endpoint with the raw body and an
1215
- * optional `contentType` header — the worker must be built with a
1216
- * `storageUpload` function and `adminToken`. Powers the studio file
1217
- * browser's upload control; resolves `{ etag?, key }`.
1218
- */
1219
- uploadStorageObject(options: {
1220
- body: ArrayBuffer | Blob;
1221
- bucket?: string;
1222
- contentType?: string;
1223
- key: string;
1224
- }): Promise<{
1225
- etag?: string;
1226
- key: string;
1227
- }>;
1228
- /**
1229
- * Build a (signed or public) URL for one object. Hits the admin-gated
1230
- * `GET /_lunora/admin/storage/url?key=…` endpoint — the worker must be built
1231
- * with a `storageSignedUrl` function and `adminToken`. Powers the studio
1232
- * file browser's copy-URL action; resolves the URL string.
1233
- *
1234
- * `options.expiresInSeconds` requests a share-link lifetime, which is
1235
- * validated/clamped server-side. The options object mirrors the worker's
1236
- * `StorageSignedUrlFunction` options (a `password` / download-limit are noted
1237
- * as future fields there).
1238
- */
1239
- signedStorageUrl(key: string, options?: {
1240
- bucket?: string;
1241
- expiresInSeconds?: number;
1242
- }): Promise<string>;
1243
- /**
1244
- * List the `.global()` (D1-backed) tables with their row counts. Hits the
1245
- * admin-gated `GET /_lunora/admin/global/tables` endpoint — the worker must
1246
- * be built with a `globalIntrospector` and `adminToken`. Powers the data
1247
- * browser's global mode.
1248
- */
1249
- listGlobalTables(): Promise<GlobalTableInfo[]>;
1250
- /**
1251
- * Read a page of rows from one `.global()` table. `filters` AND-narrows the
1252
- * page to rows matching each `column = value` eq constraint — the drill-down a
1253
- * facet-value click applies; the array is JSON-encoded into the `filters`
1254
- * query param and the values are bound server-side.
1255
- */
1256
- readGlobalTablePage(options: {
1257
- filters?: GlobalFilterClause[];
1258
- limit?: number;
1259
- offset?: number;
1260
- table: string;
1261
- }): Promise<GlobalTablePage>;
1262
- /**
1263
- * Summarise the distinct values of one column in a `.global()` table over the
1264
- * active view (the same eq `filters` the browser is previewing) — the global
1265
- * twin of the shard browser's facet. Hits the admin-gated
1266
- * `GET /_lunora/admin/global/facet` endpoint; `column` is validated + bound
1267
- * server-side. Powers the global data browser's facet sidebar.
1268
- */
1269
- facetGlobalColumn(options: {
1270
- column: string;
1271
- filters?: GlobalFilterClause[];
1272
- limit?: number;
1273
- table: string;
1274
- }): Promise<GlobalFacetResult>;
1275
- /**
1276
- * List the schema's Vectorize indexes with their declared shape (table,
1277
- * field, dimensions, metric, metadata) and live stats (vector count,
1278
- * processing watermark) when the binding is reachable. Hits the admin-gated
1279
- * `GET /_lunora/admin/vector/indexes` endpoint — the worker must be built
1280
- * with a `vectorIntrospector` and `adminToken`. Powers the studio's vector
1281
- * browser. Vectorize can't enumerate indexes at runtime, so this list comes
1282
- * from the generated `LUNORA_VECTOR_INDEXES` registry.
1283
- */
1284
- listVectorIndexes(): Promise<VectorIndexSummary[]>;
1285
- /**
1286
- * Run a nearest-neighbour similarity query against one vector index: the
1287
- * worker embeds `text` via the index's embedder and returns the top matches.
1288
- * Hits the admin-gated `POST /_lunora/admin/vector/query` endpoint. Throws
1289
- * `VECTOR_QUERY_UNSUPPORTED` when the worker's introspector has no embedder
1290
- * wired (the index lists read-only).
1291
- */
1292
- queryVectorIndex(options: {
1293
- name: string;
1294
- text: string;
1295
- topK?: number;
1296
- }): Promise<VectorQueryMatch[]>;
1297
- /**
1298
- * List authenticated users, paged and optionally searched / filtered / sorted.
1299
- * Hits the admin-gated `GET /_lunora/admin/auth/users` endpoint — the worker
1300
- * must be built with an `authAdmin` and `adminToken`. Powers the studio's
1301
- * users dashboard.
1302
- */
1303
- listAuthUsers(options?: {
1304
- filterField?: string;
1305
- filterValue?: string;
1306
- limit?: number;
1307
- offset?: number;
1308
- search?: string;
1309
- searchField?: string;
1310
- sortBy?: string;
1311
- sortDirection?: "asc" | "desc";
1312
- }): Promise<AuthPage<AuthUser>>;
1313
- /**
1314
- * Create a user. Hits the admin-gated `POST /_lunora/admin/auth/users/create`
1315
- * endpoint (requires the worker's `authAdmin` to implement `createUser`).
1316
- * `data` carries any app-defined `user.additionalFields`.
1317
- */
1318
- createAuthUser(input: {
1319
- data?: Record<string, unknown>;
1320
- email: string;
1321
- name: string;
1322
- password?: string;
1323
- role?: string | string[];
1324
- }): Promise<AuthUser>;
1325
- /** Set a user's role (string, or array joined comma-wise server-side). */
1326
- setAuthUserRole(input: {
1327
- role: string | string[];
1328
- userId: string;
1329
- }): Promise<AuthUser>;
1330
- /** Ban a user. `expiresInSeconds` sets a temporary ban; omit it for a permanent one. Revokes the user's live sessions. */
1331
- banAuthUser(input: {
1332
- expiresInSeconds?: number;
1333
- reason?: string;
1334
- userId: string;
1335
- }): Promise<AuthUser>;
1336
- /** Lift a user's ban. */
1337
- unbanAuthUser(input: {
1338
- userId: string;
1339
- }): Promise<AuthUser>;
1340
- /** Set a user's password (admin override — no current-password challenge). */
1341
- setAuthUserPassword(input: {
1342
- newPassword: string;
1343
- userId: string;
1344
- }): Promise<void>;
1345
- /** Permanently delete a user and revoke their sessions. */
1346
- removeAuthUser(input: {
1347
- userId: string;
1348
- }): Promise<void>;
1349
- /**
1350
- * Mint an impersonation session for a user, returning its bearer `token`.
1351
- * The caller is responsible for using the token (e.g. setting the session
1352
- * cookie); the server performs no cookie round-trip.
1353
- */
1354
- impersonateAuthUser(input: {
1355
- userId: string;
1356
- }): Promise<AuthImpersonation>;
1357
- /** Revoke a single session by its id (force sign-out of one device). */
1358
- revokeAuthSession(input: {
1359
- sessionId: string;
1360
- }): Promise<void>;
1361
- /** Revoke every session for a user (force sign-out everywhere). */
1362
- revokeAuthUserSessions(input: {
1363
- userId: string;
1364
- }): Promise<void>;
1365
- /**
1366
- * Report which auth dashboard surfaces are available — derived server-side
1367
- * from the enabled better-auth plugins. The studio renders only the panels
1368
- * whose capability is `true`.
1369
- */
1370
- getAuthCapabilities(): Promise<AuthCapabilities>;
1371
- /** Update a user's fields (name/email/app-defined `additionalFields`). */
1372
- updateAuthUser(input: {
1373
- data: Record<string, unknown>;
1374
- userId: string;
1375
- }): Promise<AuthUser>;
1376
- /** List a user's linked accounts (credential / OAuth providers). Token material is stripped server-side. */
1377
- listAuthAccounts(input: {
1378
- userId: string;
1379
- }): Promise<Record<string, unknown>[]>;
1380
- /** Unlink a linked account from a user. */
1381
- unlinkAuthAccount(input: {
1382
- accountId: string;
1383
- userId: string;
1384
- }): Promise<void>;
1385
- /** List a user's registered passkeys (requires the passkey plugin). */
1386
- listAuthPasskeys(input: {
1387
- userId: string;
1388
- }): Promise<Record<string, unknown>[]>;
1389
- /** Delete a passkey by id (requires the passkey plugin). */
1390
- deleteAuthPasskey(input: {
1391
- passkeyId: string;
1392
- }): Promise<void>;
1393
- /** Disable two-factor auth for a user (requires the two-factor plugin). */
1394
- disableAuthTwoFactor(input: {
1395
- userId: string;
1396
- }): Promise<void>;
1397
- /** List organizations, paged (requires the organization plugin). */
1398
- listAuthOrganizations(options?: {
1399
- limit?: number;
1400
- offset?: number;
1401
- }): Promise<AuthPage<Record<string, unknown>>>;
1402
- /** List the members of an organization (requires the organization plugin). */
1403
- listAuthOrgMembers(input: {
1404
- limit?: number;
1405
- offset?: number;
1406
- organizationId: string;
1407
- }): Promise<AuthPage<Record<string, unknown>>>;
1408
- /** List an organization's pending invitations (requires the organization plugin). */
1409
- listAuthOrgInvitations(input: {
1410
- limit?: number;
1411
- offset?: number;
1412
- organizationId: string;
1413
- }): Promise<AuthPage<Record<string, unknown>>>;
1414
- /** Remove a member from an organization. */
1415
- removeAuthOrgMember(input: {
1416
- memberId: string;
1417
- }): Promise<void>;
1418
- /** Cancel a pending organization invitation. */
1419
- cancelAuthOrgInvitation(input: {
1420
- invitationId: string;
1421
- }): Promise<void>;
1422
- /** List auth sessions, paged and optionally filtered to one user. */
1423
- listAuthSessions(options?: {
1424
- limit?: number;
1425
- offset?: number;
1426
- userId?: string;
1427
- }): Promise<AuthPage<AuthSession>>;
1428
- subscribe<F extends FunctionReference>(function_: F, args: ArgsOf<F>, callback: (data: ReturnOf<F>) => void, options?: {
1429
- onError?: SubscriptionErrorCallback;
1430
- shardKey?: string;
1431
- }): Unsubscribe;
1432
- /**
1433
- * Open a streaming query. The function reference must be a
1434
- * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
1435
- * the type constraint catches accidental use of a query/mutation/action
1436
- * reference at compile time. The returned iterable yields one element per
1437
- * chunk frame the server pushes, terminating when the server sends
1438
- * `complete` or the consumer calls `.cancel()`. Errors arrive as a
1439
- * rejection on the next `next()`.
1440
- *
1441
- * Streams ride the same WS as subscriptions and share the unsubscribe
1442
- * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id,
1443
- * which the DO recognises as an abort signal for the in-flight iterator.
1444
- *
1445
- * Stream-start frames buffered while the socket is (re)connecting are
1446
- * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
1447
- * cap drops the oldest queued frame (and fails its consumer) so a stuck
1448
- * reconnect can't OOM the page.
1449
- */
1450
- stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F>, options?: {
1451
- maxBuffer?: number;
1452
- shardKey?: string;
1453
- }): StreamIterable<ReturnOf<F>>;
1454
- close(): void;
1455
- /**
1456
- * Restore offline mutations persisted in a prior session and open a socket
1457
- * for each shard they target so they flush once the WS reconnects. Failures
1458
- * are swallowed — a broken durable store must not stop the client booting.
1459
- */
1460
- private hydratePersistedQueue;
1461
- /**
1462
- * Load every cached query into {@link hydratedQueryCache} so the next
1463
- * `subscribe()` for each key seeds its initial value off disk. A
1464
- * subscription created before this resolves simply misses the cache (it
1465
- * gets a live snapshot as before); the gate at seed time also drops any
1466
- * entry whose stamped identity no longer matches the current one.
1467
- */
1468
- private hydrateQueryCache;
1469
- /**
1470
- * Consume the hydrated read-cache entry for a key (if any), gated on
1471
- * identity. The entry is removed whether or not it matches — the cache only
1472
- * ever seeds a subscription's first value. A mismatch (the cache was written
1473
- * under a different identity) yields `undefined` so a signed-out cache never
1474
- * leaks into a new session.
1475
- */
1476
- private takeHydratedCache;
1477
- /**
1478
- * Queue a coalesced read-cache write for a subscription's current value.
1479
- * Latest-wins per key; flushed on a short debounce so a delta burst writes
1480
- * once. No-op when the read cache is disabled or the value is undefined
1481
- * (nothing to render offline).
1482
- */
1483
- private persistQueryValue;
1484
- /** Drain {@link pendingCacheWrites} to the durable store. */
1485
- private flushQueryCacheWrites;
1486
- /** Derive the aggregate status from the per-shard socket states. */
1487
- private computeStatus;
1488
- /** Recompute the aggregate status and notify listeners if it changed. */
1489
- private emitConnectionStatus;
1490
- /**
1491
- * Apply an optimistic update to every subscription that matches the
1492
- * mutation's function ref, shard key, and args, returning the rollback
1493
- * callbacks to invoke if the mutation later fails. Scoping to the same
1494
- * (fn, shardKey, args) keeps one user's mutation from clobbering another
1495
- * subscriber's value on the same function (e.g. two users on different rooms).
1496
- */
1497
- private applyOptimisticUpdates;
1498
- /**
1499
- * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
1500
- * to the live subscription registry, appending each `setQuery` write's
1501
- * rollback to `optimisticRollbacks` (the same LIFO list the legacy path uses,
1502
- * unwound on settle/error). A throwing callback unwinds its own partial
1503
- * writes — LIFO over just the rollbacks it produced — and is swallowed, so a
1504
- * buggy optimistic update can never fail the mutation or leave a partial
1505
- * patch live, mirroring the legacy transform's throw handling.
1506
- */
1507
- private applyOptimisticUpdate;
1508
- private getConnection;
1509
- private getOrCreateConnection;
1510
- private wsUrlFor;
1511
- /**
1512
- * Build the outbound RPC headers: JSON content type, optional bearer auth,
1513
- * the optional mutation-replay idempotency key, and the D1 read-your-writes
1514
- * bookmark when the caller opted into `attachBookmark`. The mutation id
1515
- * rides both the direct send and any offline-queue replay of the same write,
1516
- * so a mutation the server already committed returns its cached result
1517
- * instead of running twice.
1518
- */
1519
- private rpcRequestHeaders;
1520
- private rpc;
1521
- /**
1522
- * Authenticated request to a non-RPC admin endpoint (the scheduler list /
1523
- * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
1524
- * worker's `{ error: { code, message } }` envelope as a coded `Error` —
1525
- * mirroring {@link rpc} so callers see the same failure shape.
1526
- */
1527
- private adminFetch;
1528
- /**
1529
- * Resolve the effective connection context for a shard: the most-recently
1530
- * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
1531
- * back to the imperative {@link setConnectionContext} override, then the
1532
- * client-wide default. Returns `undefined` when none apply.
1533
- */
1534
- private effectiveConnectionContext;
1535
- /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
1536
- private refreshConnectionContext;
1537
- /**
1538
- * Send the one-shot `connect` envelope on an open shard socket. Always sent
1539
- * once per socket open, so the server's `onConnect` hooks fire symmetrically
1540
- * with `onDisconnect` (which the DO dispatches unconditionally at close for
1541
- * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
1542
- * hooks are registered, so the single frame costs nothing in the common case.
1543
- *
1544
- * The shard's registered context (or the client-wide default) rides along
1545
- * when one is set — the DO records it on the attachment for replay to
1546
- * `onDisconnect`. A socket with no registered context still announces itself;
1547
- * the envelope simply omits `context`, which is optional on the wire.
1548
- * Register a context — e.g. `setConnectionContext({})` — to attach app state
1549
- * to the lifecycle dispatch.
1550
- */
1551
- private sendConnectEnvelope;
1552
- private ensureSocket;
1553
- private handleDisconnect;
1554
- /**
1555
- * Begin the keepalive heartbeat on an open connection. Each tick sends a
1556
- * {@link WS_KEEPALIVE_PING} text frame the server answers from its
1557
- * hibernation auto-response without waking the DO. A no-op when the
1558
- * heartbeat is disabled (an interval of zero or less); idempotent — any
1559
- * existing timer is cleared first so a reconnect can't leak intervals.
1560
- */
1561
- private startHeartbeat;
1562
- /** Clear a connection's keepalive timer, if any. Safe to call repeatedly. */
1563
- private stopHeartbeat;
1564
- /** Mark every subscription bound to `shardKey` as needing a fresh ack. */
1565
- private markShardPendingAck;
1566
- private sendSubscribeIfOpen;
1567
- private handleServerMessage;
1568
- private handleErrorMessage;
1569
- private handleDataMessage;
1570
- /**
1571
- * Handle a `resume` frame (Pillar 1b): the server proved nothing the
1572
- * subscription reads changed since our `sinceSeq`, so the cached value is
1573
- * still current. We keep `lastValue` as-is, mark the sub acked, and advance
1574
- * the cursor (re-persisting so the next reconnect resumes from the newer
1575
- * watermark). No callback fires — the value didn't change, and `subscribe()`
1576
- * already replayed the cached value to every consumer synchronously.
1577
- */
1578
- private handleResumeMessage;
1579
- /**
1580
- * Resolve the value to publish for a `data`/`delta` frame.
1581
- *
1582
- * A `data` frame is an authoritative snapshot (the server re-execution path)
1583
- * and always replaces the cached value wholesale. A `delta` frame carrying a
1584
- * structured `MutationDelta` (the `broadcastDelta` row-change path) is
1585
- * merged incrementally into the cached list — preserving order, no dup/loss —
1586
- * so each subscription (including every paginated page) updates by delta
1587
- * rather than a full re-send. We fall back to full replacement when the
1588
- * delta isn't a recognisable row change, when there's no cached value yet,
1589
- * or when it can't be applied cleanly against the current cached shape.
1590
- */
1591
- private resolveDataPayload;
1592
- /** Route an inbound whisper to the topic's handlers on the originating shard. */
1593
- private dispatchWhisper;
1594
- /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
1595
- private notifyTokenExpired;
1596
- private handleCompleteMessage;
1597
- private unpersist;
1598
- /**
1599
- * Stable, non-reversible fingerprint of the current auth identity used to
1600
- * stamp queued offline writes. `null` (signed out) is its own identity and
1601
- * never matches a bearer-token fingerprint. The raw token is never stored;
1602
- * a length-prefixed FNV-1a hash is enough to detect an identity *change*
1603
- * without keeping the credential around in the queue map.
1604
- */
1605
- private identityFingerprint;
1606
- /**
1607
- * Drain every in-memory offline write and reject it because the auth
1608
- * identity changed. Durable entries are also dropped from persistence so a
1609
- * later `hydrate` can't resurrect another user's writes. Stamps are cleared
1610
- * alongside. Persisted entries restored without a live awaiter still get
1611
- * unpersisted here.
1612
- */
1613
- private rejectQueuedForIdentityChange;
1614
- /**
1615
- * Drop the durable read cache on an identity change so a cached value stamped
1616
- * under the previous identity can never hydrate into a new session. Clears
1617
- * the in-flight write batch and the not-yet-consumed hydrated entries too;
1618
- * the durable `clear()` is best-effort.
1619
- */
1620
- private clearQueryCacheForIdentityChange;
1621
- private flushOfflineQueue;
1622
- }
1623
- export { ArgsOf as A, BookmarkStorage as B, CachedQuery as C, DEFAULT_MAX_BUFFER as D, StreamHandle as E, FunctionReference as F, GlobalFacetResult as G, StreamIterable as H, SubscriptionCallback as I, SubscriptionRegistry as J, SubscriptionState as K, LunoraClient as L, MutationCallOptions as M, WorkflowInstanceDetail as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReturnOf as R, SubscriptionError as S, WorkflowInstancePage as T, User as U, WorkflowInstanceStatus as V, WorkflowInstanceAction as W, WorkflowInstanceSummary as X, WorkflowStepDetail as Y, createLocalStore as Z, createStream as _, Unsubscribe as a, SubscriptionErrorCallback as b, PersistenceAdapter as c, ReconnectOptions as d, ClientMessage as e, ConnectionStatus as f, FunctionArgumentDescriptor as g, FunctionDescriptor as h, GlobalFacetValue as i, GlobalFilterClause as j, GlobalTableInfo as k, GlobalTablePage as l, LunoraClientOptions as m, OptimisticLocalStore as n, OptimisticUpdate as o, PersistedMutation as p, RpcEnvelope as q, RpcResponseBody as r, ScheduleRecord as s, SchedulerPoolStatus as t, SchedulerStatus as u, ServerMessage as v, ShardTrafficEntry as w, ShardTrafficResult as x, StorageListPage as y, StorageObject as z };